@openchamber/web 1.5.6 → 1.5.7

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,236 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CaD8MAGl.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-C4dfK_Ah.js","assets/index-Do__y_zo.js","assets/index-DRQKzuPI.css"])))=>i.map(i=>d[i]);
2
- import{t as Hp,c as Wp,F as Up,j as e,R as Vp,T as Gp,P as qp,C as Kp,A as Qp,a as Yp,b as os,d as us,p as Vs,e as Gs,f as Xp,_ as Ss,g as i,r as nm,i as es,I as Jp,k as Zp,l as eh,m as th,n as sh,L as rh,o as nh,q as oh,s as ah,u as Qt,S as ih,v as lh,w as om,x as ch,y as dh,z as uh,B as mh,D as fh,E as ph,G as Re,H as jc,J as hh,K as gh,M as gr,N as Ji,O as Sc,Q as Ha,U as Ht,V as zs,W as Ft,X as Al,Y as am,Z as im,$ as xh,a0 as Gr,a1 as yh,a2 as Ys,a3 as nr,a4 as Qr,a5 as Kt,a6 as El,a7 as bh,a8 as pn,a9 as Il,aa as vn,ab as hn,ac as Zi,ad as Ts,ae as lm,af as wh,ag as vh,ah as jh,ai as Sh,aj as Nh,ak as kh,al as Ch,am as na,an as Mh,ao as cm,ap as dr,aq as qr,ar as xs,as as jn,at as Ws,au as Do,av as cs,aw as jr,ax as Dh,ay as Ah,az as dm,aA as Pl,aB as gn,aC as Tl,aD as Sr,aE as um,aF as zn,aG as Eh,aH as Wa,aI as ur,aJ as mm,aK as xn,aL as yn,aM as Fl,aN as ui,aO as Ih,aP as Yr,aQ as Dr,aR as Js,aS as Ph,aT as qs,aU as Th,aV as Nc,aW as el,aX as Fh,aY as Rh,aZ as Lh,a_ as Oh,a$ as _h,b0 as $h,b1 as Bh,b2 as zh,b3 as Hh,b4 as fm,b5 as mi,b6 as Wh,b7 as Uh,b8 as Vh,b9 as Gh,ba as qh,bb as Kh,bc as Qh,bd as Yh,be as Xh,bf as Jh,bg as Zh,bh as eg,bi as tg,bj as sg,bk as rg,bl as ng,bm as og,bn as Ar,bo as va,bp as Nr,bq as yr,br as ag,bs as ig,bt as Ua,bu as lg,bv as Rl,bw as cg,bx as dg,by as ug,bz as Hn,bA as mg,bB as fg,bC as pg,bD as hg,bE as gg,bF as wo,bG as oa,bH as Va,bI as xg,bJ as yg,bK as On,bL as In,bM as pm,bN as bg,bO as wg,bP as Xs,bQ as vg,bR as jg,bS as hm,bT as Sg,bU as Ng,bV as tl,bW as gm,bX as xm,bY as kg,bZ as Ir,b_ as Wn,b$ as Cg,c0 as kc,c1 as Mg,c2 as sl,c3 as Xn,c4 as Jn,c5 as Dg,c6 as ym,c7 as Ll,c8 as Ol,c9 as _l,ca as Ag,cb as Eg,cc as Ig,cd as Pg,ce as Cc,cf as bm,cg as Tg,ch as Fg,ci as Rg,cj as Ga,ck as Lg,cl as Og,cm as _g,cn as Pn,co as Mc,cp as $g,cq as Bg,cr as zg,cs as Hg,ct as Wg,cu as Ug,cv as Zn,cw as Vg,cx as Gg,cy as qg,cz as Kg,cA as Qg,cB as Yg,cC as wm,cD as vm,cE as jm,cF as Sm,cG as Nm,cH as Xg,cI as km,cJ as Cm,cK as Mm,cL as Tn,cM as Jg,cN as Zg,cO as ex,cP as Ze,cQ as tx,cR as sx,cS as rx,cT as nx,cU as Dc,cV as ox,cW as ax,cX as vo,cY as Dm,cZ as Am,c_ as fi,c$ as qa,d0 as Em,d1 as ix,d2 as lx,d3 as ja,d4 as Im,d5 as rl,d6 as cx,d7 as dx,d8 as ux,d9 as mx,da as fx,db as px}from"./vendor-.bun-CaD8MAGl.js";import{c as hx,l as gx,g as xx,r as yx,d as bx,a as wx,b as vx,e as jx,u as Sx,f as Nx,h as kx,i as Cx,j as Mx,k as Dx,m as Ax,n as Ex,o as Ix}from"./index-Do__y_zo.js";const ds=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Vt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,br=()=>typeof window>"u"?!1:!ds()&&!Vt(),Xr=()=>ds()?window.opencodeDesktop??null:null,Pm=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const t=window.opencodeDesktop;return t?.getSettings&&t?.updateSettings?{getSettings:t.getSettings.bind(t),updateSettings:t.updateSettings.bind(t)}:null},Tm=async()=>{const t=Xr();if(typeof window<"u"){const r=window.__OPENCHAMBER_HOME__;if(r&&r.length>0)return r}if(!t)return null;if(typeof t.homeDirectory=="string"&&t.homeDirectory.length>0)return t.homeDirectory;try{if(!t.getHomeDirectory)return null;const r=await t.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},Px=async()=>{const t=Xr();if(!t)return null;try{return await t.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Tx=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Lr=async()=>{const t=Pm();if(!t)return null;try{return await t.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Fx=async t=>{const r=Pm();if(!r)return null;try{return await r.updateSettings(t)}catch(s){return console.warn("[desktop] Failed to update desktop settings",s),null}},Rx=async t=>{const r=Xr();if(!r||!r.requestDirectoryAccess)return{success:!0,path:t};try{return await r.requestDirectoryAccess(t)}catch(s){return console.warn("Failed to request directory access",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},Lx=async t=>{const r=Xr();if(!r||!r.startAccessingDirectory)return{success:!0};try{return await r.startAccessingDirectory(t)}catch(s){return console.warn("Failed to start accessing directory",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},Ox=async t=>{const r=Xr();if(!r||!r.stopAccessingDirectory)return{success:!0};try{return await r.stopAccessingDirectory(t)}catch(s){return console.warn("Failed to stop accessing directory",s),{success:!1,error:s instanceof Error?s.message:String(s)}}},_x=async()=>{const t=Xr();if(!t||!t.checkForUpdates)return null;try{return await t.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},$x=async t=>{const r=Xr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(t),!0}catch(s){return console.warn("Failed to download update",s),!1}},Bx=async()=>{const t=Xr();if(!t||!t.restartToUpdate)return!1;try{return await t.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function F(...t){return Hp(Wp(t))}const Fm=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Ls=t=>Fm()&&ds()?t.metaKey:t.ctrlKey,Zt=()=>Fm()&&ds()?"⌘":"Ctrl",Rm=(t,r)=>{const s=t??"",n=Math.max(16,r?.maxLength??45);if(s.length<=n)return s;const o=s.split("/");if(o.length<=1)return s;const a=o.pop()??"";if(!a)return s;const l=Math.max(0,n-(a.length+2));if(l<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>l)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,l):""}return c?`${c}…/${a}`:`…/${a}`},Sa=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function cn(t,r){if(!t)return"";const s=Sa(t);if(s==="/")return"/";const n=r?Sa(r):void 0;if(n&&n!=="/"){if(s===n)return"~";if(s.startsWith(`${n}/`)){const o=s.slice(n.length+1);return o?`~/${o}`:"~"}}return s}function Ac(t,r){if(!t)return"/";const s=Sa(t);if(!s||s==="/")return"/";const n=r?Sa(r):void 0;return n&&n!=="/"&&s===n?"~":s.split("/").pop()||s||"/"}function Ks(t,r){return r?t?t.toLowerCase().includes(r.toLowerCase())?!0:new Up([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function zx({delayDuration:t=0,...r}){return e.jsx(Yp,{"data-slot":"tooltip-provider",delayDuration:t,...r})}function lt({delayDuration:t=0,...r}){return e.jsx(zx,{delayDuration:t,children:e.jsx(Vp,{"data-slot":"tooltip",...r})})}function ct({...t}){return e.jsx(Gp,{"data-slot":"tooltip-trigger",...t})}function it({className:t,sideOffset:r=0,children:s,...n}){return e.jsx(qp,{children:e.jsxs(Kp,{"data-slot":"tooltip-content",sideOffset:r,className:F("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",t),...n,children:[s,e.jsx(Qp,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let pi=null;const Ec=()=>{const t=new Map;return{getItem:r=>t.get(r)??null,setItem:(r,s)=>{t.set(r,s)},removeItem:r=>{t.delete(r)},clear:()=>{t.clear()},key:r=>Array.from(t.keys())[r]??null,get length(){return t.size}}},Hx=()=>{if(typeof window>"u"||!window.localStorage)return Ec();const t=window.localStorage,r=Ec();let s=!0;const n=()=>{s=!1};return{getItem:u=>{if(s)try{const m=t.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(s)try{t.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(s)try{t.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(s)try{t.clear()}catch{n()}r.clear()},key:u=>{if(s)try{return t.key(u)}catch{n()}return r.key(u)},get length(){if(s)try{return t.length+r.length}catch{n()}return r.length}}},ws=()=>(pi||(pi=Hx()),pi),$l={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Wx={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Ic(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Er={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)"}}},aa={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Er.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:aa.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Er.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:aa.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Er.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:aa.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Er.tool.inline})},ke=os()(us(Vs((t,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",mainTabGuard:null,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,memoryLimitHistorical:90,memoryLimitViewport:120,memoryLimitActiveSession:180,toolCallExpansion:"collapsed",fontSize:100,padding:100,cornerRadius:12,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"single",isTimelineDialogOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",setTheme:s=>{t({theme:s}),r().applyTheme()},toggleSidebar:()=>{t(s=>{const n=!s.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:s=>{t(()=>{if(s&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:s,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:s}})},setSidebarWidth:s=>{t({sidebarWidth:s,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:s=>{t({isSessionSwitcherOpen:s})},setMainTabGuard:s=>{t({mainTabGuard:s})},setActiveMainTab:s=>{const n=r().mainTabGuard;n&&!n(s)||t({activeMainTab:s})},setPendingDiffFile:s=>{t({pendingDiffFile:s})},navigateToDiff:s=>{const n=r().mainTabGuard;n&&!n("diff")||t({pendingDiffFile:s,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:s}=r();return s&&t({pendingDiffFile:null}),s},setIsMobile:s=>{t({isMobile:s})},toggleCommandPalette:()=>{t(s=>({isCommandPaletteOpen:!s.isCommandPaletteOpen}))},setCommandPaletteOpen:s=>{t({isCommandPaletteOpen:s})},toggleHelpDialog:()=>{t(s=>({isHelpDialogOpen:!s.isHelpDialogOpen}))},setHelpDialogOpen:s=>{t({isHelpDialogOpen:s})},setAboutDialogOpen:s=>{t({isAboutDialogOpen:s})},setSessionCreateDialogOpen:s=>{t({isSessionCreateDialogOpen:s})},setSettingsDialogOpen:s=>{t({isSettingsDialogOpen:s})},setModelSelectorOpen:s=>{t({isModelSelectorOpen:s})},setSidebarSection:s=>{t({sidebarSection:s})},setEventStreamStatus:(s,n)=>{t({eventStreamStatus:s,eventStreamHint:n??null})},setShowReasoningTraces:s=>{t({showReasoningTraces:s})},setAutoDeleteEnabled:s=>{t({autoDeleteEnabled:s})},setAutoDeleteAfterDays:s=>{const n=Math.max(1,Math.min(365,s));t({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:s=>{t({autoDeleteLastRunAt:s})},setMemoryLimitHistorical:s=>{const n=Math.max(10,Math.min(500,Math.round(s)));t({memoryLimitHistorical:n})},setMemoryLimitViewport:s=>{const n=Math.max(20,Math.min(500,Math.round(s)));t({memoryLimitViewport:n})},setMemoryLimitActiveSession:s=>{const n=Math.max(30,Math.min(1e3,Math.round(s)));t({memoryLimitActiveSession:n})},setToolCallExpansion:s=>{t({toolCallExpansion:s})},setFontSize:s=>{const n=Math.max(50,Math.min(200,s));t({fontSize:n}),r().applyTypography()},setPadding:s=>{const n=Math.max(50,Math.min(200,s));t({padding:n}),r().applyPadding()},setCornerRadius:s=>{t({cornerRadius:s})},applyTypography:()=>{const{fontSize:s}=r(),n=document.documentElement,o=s/100,a=Object.entries($l);if(o===1){for(const[l]of a)n.style.removeProperty(Ic(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Ic(l),`${d*o}rem`)}},applyPadding:()=>{const{padding:s}=r(),n=document.documentElement,o=s/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const l=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*l).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*l).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*l).toFixed(3)),n.style.setProperty("--line-height-loose",(2*l).toFixed(3))},setDiffLayoutPreference:s=>{t({diffLayoutPreference:s})},setDiffFileLayout:(s,n)=>{t(o=>({diffFileLayout:{...o.diffFileLayout,[s]:n}}))},setDiffWrapLines:s=>{t({diffWrapLines:s})},setDiffViewMode:s=>{t({diffViewMode:s})},setInputBarOffset:s=>{t({inputBarOffset:s})},setKeyboardOpen:s=>{t({isKeyboardOpen:s})},toggleFavoriteModel:(s,n)=>{t(o=>o.favoriteModels.some(l=>l.providerID===s&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===s&&l.modelID===n))}:{favoriteModels:[{providerID:s,modelID:n},...o.favoriteModels]})},isFavoriteModel:(s,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===s&&a.modelID===n)},addRecentModel:(s,n)=>{t(o=>{const a=o.recentModels.filter(l=>!(l.providerID===s&&l.modelID===n));return{recentModels:[{providerID:s,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||t(s=>{const n={};return s.isSidebarOpen&&!s.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:s}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),s==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(s)},setMultiRunLauncherOpen:s=>{t(n=>({isMultiRunLauncherOpen:s,multiRunLauncherPrefillPrompt:s?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:s=>{t({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:s,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:s=>{t({isTimelineDialogOpen:s})},setNativeNotificationsEnabled:s=>{t({nativeNotificationsEnabled:s})},setNotificationMode:s=>{t({notificationMode:s})}}),{name:"ui-store",storage:Gs(()=>ws()),partialize:t=>({theme:t.theme,isSidebarOpen:t.isSidebarOpen,sidebarWidth:t.sidebarWidth,isSessionSwitcherOpen:t.isSessionSwitcherOpen,activeMainTab:t.activeMainTab,sidebarSection:t.sidebarSection,isSessionCreateDialogOpen:t.isSessionCreateDialogOpen,isSettingsDialogOpen:t.isSettingsDialogOpen,showReasoningTraces:t.showReasoningTraces,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,autoDeleteLastRunAt:t.autoDeleteLastRunAt,memoryLimitHistorical:t.memoryLimitHistorical,memoryLimitViewport:t.memoryLimitViewport,memoryLimitActiveSession:t.memoryLimitActiveSession,toolCallExpansion:t.toolCallExpansion,fontSize:t.fontSize,padding:t.padding,cornerRadius:t.cornerRadius,favoriteModels:t.favoriteModels,recentModels:t.recentModels,diffLayoutPreference:t.diffLayoutPreference,diffWrapLines:t.diffWrapLines,diffViewMode:t.diffViewMode,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode})}),{name:"ui-store"}));async function Ux(){try{const t=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Server responded with ${t.status}`);const r=await t.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(t){return console.warn("Failed to check for web updates:",t),null}}function Vx(){return ds()?"desktop":br()?"web":null}const Pc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Ka=os()((t,r)=>({...Pc,checkForUpdates:async()=>{const s=Vx();if(s){t({checking:!0,error:null,runtimeType:s});try{let n=null;s==="desktop"?n=await _x():s==="web"&&(n=await Ux()),t({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){t({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:s,runtimeType:n}=r();if(!(n!=="desktop"||!s)){t({downloading:!0,error:null,progress:null});try{await $x(o=>{t({progress:o})}),t({downloading:!1,downloaded:!0})}catch(o){t({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:s,runtimeType:n}=r();if(!(n!=="desktop"||!s))try{await Bx()}catch(o){t({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(Pc)}})),Gx="/api",qx=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Kx=t=>{const r=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(qx.test(r)||typeof window>"u")return r;const s=window.location?.href||window.location?.origin;if(!s)return r;try{return new URL(r,s).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},Qx=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!t||!r)return null;const s=typeof t.origin=="string"&&t.origin.length>0?t.origin:null;return s?`${s}/api`:null},Fo=t=>t.replace(/\\/g,"/"),hi=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Yx{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=Gx){const n=Qx()||r;this.baseUrl=Kx(n),this.client=Xp({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const n=s.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const s=r.match(/^([A-Za-z]:)(?:\/|$)/);if(s){const a=s[1],c=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,s){if(r==null)return s();const n=this.currentDirectory;this.currentDirectory=r;try{return await s()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,s=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&&(s(a.directory),s(a.worktree),s(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);s(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>s(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(s(this.currentDirectory),typeof window<"u")try{s(window.localStorage.getItem("lastDirectory")),s(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&s(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 s=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!s.data)throw new Error("Failed to create session");return s.data}async getSession(r){const s=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!s.data)throw new Error("Session not found");return s.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,s){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:s});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r,s){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof s=="number"?{limit:s}:{}})).data||[]}async getSessionTodos(r){try{const s=this.baseUrl.replace(/\/$/,""),n=new URL(`${s}/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 s=r.toLowerCase();return s.startsWith("text/")&&s!=="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(s)}isHeicMime(r){if(!r)return!1;const s=r.toLowerCase();return s==="image/heic"||s==="image/heif"}async compressImage(r,s,n=.8,o=2048){return typeof document>"u"?r:new Promise(a=>{const l=new Image;l.onload=()=>{let c=l.width,d=l.height;(c>o||d>o)&&(c>d?(d=Math.round(d*(o/c)),c=o):(c=Math.round(c*(o/d)),d=o));const u=document.createElement("canvas");u.width=c,u.height=d;const m=u.getContext("2d");if(!m){a(r);return}m.drawImage(l,0,0,c,d);let f=s;s==="image/png"&&r.length>2.5*1024*1024&&(f="image/jpeg");try{a(u.toDataURL(f,n))}catch{a(r)}},l.onerror=()=>a(r),l.src=r})}async convertHeicToJpeg(r){try{const s=(await Ss(async()=>{const{default:f}=await import("./vendor-.bun-CaD8MAGl.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),l=new Uint8Array(a.length);for(let f=0;f<a.length;f++)l[f]=a.charCodeAt(f);const c=new Blob([l],{type:r.mime}),d=await s({blob:c,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const h=new FileReader;h.onload=()=>f(h.result),h.onerror=p,h.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(s){return console.warn("Failed to convert HEIC to JPEG:",s),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(r.mime.startsWith("image/")&&(r.mime==="image/jpeg"||r.mime==="image/png"||r.mime==="image/webp")&&r.url.length>1.33*1024*1024){const n=await this.compressImage(r.url,r.mime),o=n.startsWith("data:image/jpeg")?"image/jpeg":r.mime;return{...r,mime:o,url:n}}if(!this.shouldNormalizeToTextPlain(r.mime))return r;let s=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);s=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:s}}async sendMessage(r){const s=Date.now(),n=r.messageId??`temp_${s}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText,synthetic:r.prefaceTextSynthetic!==!1}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const l=await this.normalizeFilePart(a),c={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(c)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text,...a.synthetic?{synthetic:!0}:{}}),a.files&&a.files.length>0)for(const l of a.files){const c=await this.normalizeFilePart(l),d={type:"file",mime:c.mime,filename:c.filename,url:c.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,s,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:s,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const s=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!s.data)throw new Error("Failed to unrevert session");return s.data}async forkSession(r,s){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:s});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 s=this.baseUrl.replace(/\/$/,""),n=new URL(`${s}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const l=await a.json().catch(()=>null);return!l||typeof l!="object"?{}:l}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async listToolIds(r){try{const s=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(s?{directory:s}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,s,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:s,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(r,s){const n=!Array.isArray(s)||s.length===0?[]:Array.isArray(s[0])?s:[s];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 s=[],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[]}};s.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)s.push(n(d));const a=await Promise.all(s),l=[],c=new Set;for(const d of a)for(const u of d){if(!u||typeof u!="object")continue;const m=u.id;typeof m!="string"||m.length===0||c.has(m)||(c.add(m),l.push(u))}return l}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const s=`${this.baseUrl}/config`,n=await fetch(s,{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 s=await this.getConfig(),n=r(s);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 s=r.split(`
3
- `),n=[];let o;for(const l of s)if(l.startsWith("data:"))n.push(l.slice(5).replace(/^\s/,""));else if(l.startsWith("id:")){const c=l.slice(3).trim();c&&(o=c)}if(n.length===0)return null;const a=n.join(`
4
- `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const s=r,n=typeof s.directory=="string"?s.directory:typeof s.properties=="object"&&s.properties!==null?s.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof s.type=="string")return{directory:o&&o.length>0?o:"global",payload:s};const a=s.payload;if(a&&typeof a=="object"){const l=a;if(typeof l.type=="string")return{directory:o&&o.length>0?o:"global",payload:l}}return null}emitGlobalSseEvent(r){for(const s of this.globalSseListeners)try{s(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(s){console.warn("[OpencodeClient] Global SSE open handler error:",s)}}notifyGlobalSseError(r){for(const s of this.globalSseErrorListeners)try{s(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(s=>{s?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",s)}).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 s=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!r.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const l=await fetch(s,{method:"GET",headers:a,signal:r.signal});if(!l.ok||!l.body)throw new Error(`Global SSE connect failed with status ${l.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const c=l.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await c.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
5
- `);const h=u.split(`
6
-
7
- `);u=h.pop()??"";for(const x of h){const g=this.parseSseBlock(x);if(!g)continue;g.id&&(this.globalSseLastEventId=g.id);const w=this.normalizeRoutedSsePayload(g.data);w&&this.emitGlobalSseEvent(w)}}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,s,n,o){const a=this.normalizeCandidatePath(o?.directory??null),l=c=>{a&&c.directory!==a||r(c)};return this.globalSseListeners.add(l),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(c){console.warn("[OpencodeClient] Global SSE open handler error:",c)}},0)),s&&this.globalSseErrorListeners.add(s),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(l),n&&this.globalSseOpenListeners.delete(n),s&&this.globalSseErrorListeners.delete(s),this.maybeStopGlobalSse()}}subscribeToEvents(r,s,n,o,a){const l=a?.key??"default",c=a?.scope??"directory",d=this.sseAbortControllers.get(l);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(l,u);let m;if(c==="global"){let p=null;const h=g=>{if(g.directory==="global")return g.payload;const w=g.payload,y=typeof w.properties=="object"&&w.properties!==null?w.properties:{};return y.directory===g.directory?g.payload:{...w,properties:{...y,directory:g.directory}}},x=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)};return u.signal.addEventListener("abort",x,{once:!0}),p=this.subscribeToGlobalEvents(g=>{u.signal.aborted||r(h(g))},s?g=>{u.signal.aborted||s(g)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{x(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const h=p;if(typeof h.type=="string")return h;const x=h.payload;if(x&&typeof x=="object"){const g=x;if(typeof g.type=="string"){if(typeof h.directory=="string"&&h.directory.length>0){const y={...(typeof g.properties=="object"&&g.properties!==null?g.properties:null)??{},directory:h.directory};return{...g,properties:y}}return g}}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 h=async x=>{try{const g=p?{directory:p}:void 0,w={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),s&&!u.signal.aborted&&s(v))},onSseEvent:v=>{if(u.signal.aborted)return;v.id&&typeof v.id=="string"&&(m=v.id);const S=v.data,k=f(S);k&&r(k)}};m&&(w.headers={...w.headers||{},"Last-Event-ID":m});const y=await this.client.event.subscribe(g,w);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const v of y.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(g){if(g?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",g),s&&s(g);const w=Math.min(3e3*Math.pow(2,x),3e4);await new Promise(y=>setTimeout(y,w)),u.signal.aborted||await h(x+1);return}if(!u.signal.aborted){const g=Math.min(3e3*Math.pow(2,x),3e4);await new Promise(w=>setTimeout(w,g)),await h(x+1)}};try{await h(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)}})(),()=>{this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l),u.abort()}}async readFile(r){try{const s=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!s.ok)throw new Error(`Failed to read file: ${s.statusText}`);return await s.text()}catch{return`// Content of ${r}
8
- // This would be loaded from the server`}}async listFiles(r){try{const s=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:s})});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(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(s=>({name:s.name,description:s.description,agent:s.agent,model:s.model,template:s.template,subtask:s.subtask}))}catch{return[]}}async getCommandDetails(r){try{const s=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(s.data){const n=s.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 s=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;s==="/api"?r="/health":s.endsWith("/api")?r=`${s.slice(0,-4)}/health`:r=`${s}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const s=hi();if(s?.createDirectory)try{return await s.createDirectory(r)}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(l||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r,s){const n=hi();if(n)try{const o=await n.listDirectory(r||"",s);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:Fo(a.path),isDirectory:!!a.isDirectory,isFile:!a.isDirectory,isSymbolicLink:!1}))}catch(o){throw console.error("Failed to list directory contents:",o),o}try{const o=new URLSearchParams;r&&r.trim().length>0&&o.set("path",r),s?.respectGitignore&&o.set("respectGitignore","true");const a=o.toString(),l=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!l.ok){const d=await l.json().catch(()=>({})),u=typeof d.error=="string"?d.error:"Failed to list directory";throw new Error(u)}const c=await l.json();return!c||!Array.isArray(c.entries)?[]:c.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(r,s){const n=hi(),o=typeof s?.directory=="string"&&s.directory.trim().length>0?s.directory.trim():this.currentDirectory,a=o?Fo(o):null;if(n)try{const m=await n.search({directory:o||"",query:r,maxResults:s?.limit,includeHidden:s?.includeHidden,respectGitignore:s?.respectGitignore});return Array.isArray(m)?m.map(f=>{const p=Fo(f.path),h=p.split("/").filter(Boolean).pop()||p,x=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Fo(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:x,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const l=new URLSearchParams;o&&o.length>0&&l.set("directory",o),typeof r=="string"&&l.set("q",r),typeof s?.limit=="number"&&Number.isFinite(s.limit)&&l.set("limit",String(s.limit)),s?.includeHidden&&l.set("includeHidden","true"),s?.respectGitignore===!1&&l.set("respectGitignore","false");const c=`${this.baseUrl}/fs/search${l.toString()?`?${l.toString()}`:""}`,d=await fetch(c,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await Tm();if(r)return r;try{const s=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!s.ok){const o=await s.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 s.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(s){return console.warn("Failed to resolve filesystem home directory:",s),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const s=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",s,"with path:",r);try{const n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},l=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(l)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const Fe=new Yx,Xx=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Fe},Symbol.toStringTag,{value:"Module"})),nl=new Set;function Qa(t){return nl.add(t),()=>{nl.delete(t)}}function wr(t,r){const s=Array.isArray(t)?t:[t],n=Array.from(new Set(s));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 nl)try{const l=a(o);l instanceof Promise&&l.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(l){console.error("[ConfigSync] Listener threw:",l)}}function jo(t,r){return t.scopes.includes("all")||t.scopes.includes(r)}const Bl="Updating OpenCode configuration...";let vr=0,Kr=Bl;const ol=new Set;function Na(){const t={isUpdating:vr>0,message:Kr};ol.forEach(r=>r(t))}function Hs(t){vr+=1,vr===1?(Kr=t||Bl,Na()):t&&(Kr=t,Na())}function Fs(){vr!==0&&(vr-=1,vr===0&&(Kr=Bl,Na()))}function Pr(t){Kr===t&&vr>0||(Kr=t,vr>0&&Na())}function Jx(t){return ol.add(t),t({isUpdating:vr>0,message:Kr}),()=>{ol.delete(t)}}function Zx(){return{isUpdating:vr>0,message:Kr}}const xr=os()(us(Vs((t,r)=>({queuedMessages:{},queueModeEnabled:!1,addToQueue:(s,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};t(l=>{const c=l.queuedMessages[s]??[];return{queuedMessages:{...l.queuedMessages,[s]:[...c,a]}}})},removeFromQueue:(s,n)=>{t(o=>{const l=(o.queuedMessages[s]??[]).filter(c=>c.id!==n);if(l.length===0){const{[s]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[s]:l}}})},popToInput:(s,n)=>{const l=(r().queuedMessages[s]??[]).find(c=>c.id===n);return l?(t(c=>{const u=(c.queuedMessages[s]??[]).filter(m=>m.id!==n);if(u.length===0){const{[s]:m,...f}=c.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...c.queuedMessages,[s]:u}}}),l):null},clearQueue:s=>{t(n=>{const{[s]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:s=>{t({queueModeEnabled:s}),fs({queueModeEnabled:s})},getQueueForSession:s=>r().queuedMessages[s]??[]}),{name:"message-queue-store",storage:Gs(()=>ws()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),Tc=t=>{if(!t||typeof t!="object")return null;const r={};return typeof t.showReasoningTraces=="boolean"&&(r.showReasoningTraces=t.showReasoningTraces),Object.keys(r).length>0?r:null},ey=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},ty=t=>{const r=ke.getState();typeof t.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(t.showReasoningTraces)},sy=async()=>{if(typeof window>"u")return null;if(ds()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const s=await r.load();return Tc(typeof s=="object"&&s!==null?s:null)}catch(s){return console.warn("Failed to load appearance preferences from desktop storage:",s),null}}const t=localStorage.getItem("appearance-preferences");if(!t)return null;try{const r=JSON.parse(t),s=ey(r);return Tc(s)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Lm=null;const Fc=t=>{Lm=t},Ms=()=>Lm,ia=t=>{typeof window>"u"||(t.themeId&&localStorage.setItem("selectedThemeId",t.themeId),t.themeVariant&&localStorage.setItem("selectedThemeVariant",t.themeVariant),t.lightThemeId&&localStorage.setItem("lightThemeId",t.lightThemeId),t.darkThemeId&&localStorage.setItem("darkThemeId",t.darkThemeId),typeof t.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(t.useSystemTheme)),t.lastDirectory&&localStorage.setItem("lastDirectory",t.lastDirectory),t.homeDirectory&&(localStorage.setItem("homeDirectory",t.homeDirectory),window.__OPENCHAMBER_HOME__=t.homeDirectory),Array.isArray(t.projects)&&t.projects.length>0?localStorage.setItem("projects",JSON.stringify(t.projects)):localStorage.removeItem("projects"),t.activeProjectId?localStorage.setItem("activeProjectId",t.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(t.pinnedDirectories)&&t.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(t.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),typeof t.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(t.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"))},ry=t=>{if(!Array.isArray(t))return;const r=[],s=new Set;for(const n of t){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",l=typeof o.label=="string"?o.label.trim():"",c=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!l||!c||s.has(a)||(s.add(a),r.push({id:a,label:l,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},ny=t=>{if(!Array.isArray(t))return;const r=[],s=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=c==="/"?c:c.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||s.has(l)||n.has(d))continue;s.add(l),n.add(d);const u={id:l,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&m.branchPrefix.trim()&&(f.branchPrefix=m.branchPrefix.trim()),typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},Om=()=>{const t=ke.persist;if(t&&typeof t=="object")return t},_m=()=>Ms()?.settings??null,la=t=>{const r=ke.getState(),s=xr.getState();if(typeof t.showReasoningTraces=="boolean"&&t.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(t.showReasoningTraces),typeof t.autoDeleteEnabled=="boolean"&&t.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(t.autoDeleteEnabled),typeof t.autoDeleteAfterDays=="number"&&Number.isFinite(t.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,t.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof t.memoryLimitHistorical=="number"&&Number.isFinite(t.memoryLimitHistorical)&&r.setMemoryLimitHistorical(t.memoryLimitHistorical),typeof t.memoryLimitViewport=="number"&&Number.isFinite(t.memoryLimitViewport)&&r.setMemoryLimitViewport(t.memoryLimitViewport),typeof t.memoryLimitActiveSession=="number"&&Number.isFinite(t.memoryLimitActiveSession)&&r.setMemoryLimitActiveSession(t.memoryLimitActiveSession),typeof t.queueModeEnabled=="boolean"&&t.queueModeEnabled!==s.queueModeEnabled&&s.setQueueMode(t.queueModeEnabled)},Rc=t=>{if(!t||typeof t!="object")return null;const r=t,s={};typeof r.themeId=="string"&&r.themeId.length>0&&(s.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(s.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(s.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(s.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(s.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(s.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(s.homeDirectory=r.homeDirectory);const n=ny(r.projects);n&&(s.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(s.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(s.approvedDirectories=r.approvedDirectories.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.securityScopedBookmarks)&&(s.securityScopedBookmarks=r.securityScopedBookmarks.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.pinnedDirectories)&&(s.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(a=>typeof a=="string"&&a.length>0)))),typeof r.showReasoningTraces=="boolean"&&(s.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(s.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(s.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(s.defaultModel=r.defaultModel),typeof r.defaultVariant=="string"&&r.defaultVariant.length>0&&(s.defaultVariant=r.defaultVariant),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(s.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(s.autoCreateWorktree=r.autoCreateWorktree),typeof r.gitmojiEnabled=="boolean"&&(s.gitmojiEnabled=r.gitmojiEnabled),typeof r.queueModeEnabled=="boolean"&&(s.queueModeEnabled=r.queueModeEnabled),typeof r.memoryLimitHistorical=="number"&&Number.isFinite(r.memoryLimitHistorical)&&(s.memoryLimitHistorical=r.memoryLimitHistorical),typeof r.memoryLimitViewport=="number"&&Number.isFinite(r.memoryLimitViewport)&&(s.memoryLimitViewport=r.memoryLimitViewport),typeof r.memoryLimitActiveSession=="number"&&Number.isFinite(r.memoryLimitActiveSession)&&(s.memoryLimitActiveSession=r.memoryLimitActiveSession);const o=ry(r.skillCatalogs);return o&&(s.skillCatalogs=o),s},oy=async()=>{const t=_m();if(t)try{const r=await t.load();return Rc(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 s=await r.json().catch(()=>null);return Rc(s)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},$m=async()=>{if(typeof window>"u")return;const t=Om(),r=s=>{ia(s);const n=()=>la(s);if(t?.hasHydrated?.())n();else if(n(),t?.onFinishHydration){const o=t.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:s}))};try{const s=ds()?await Lr():await oy();s&&r(s)}catch(s){console.warn("Failed to synchronise settings:",s)}},fs=async t=>{if(typeof window>"u")return;if(ds()){try{const s=await Fx(t);s&&(ia(s),la(s))}catch(s){console.warn("Failed to update desktop settings:",s)}return}const r=_m();if(r)try{const s=await r.save(t);s&&(ia(s),la(s));return}catch(s){console.warn("Failed to update settings via runtime settings API:",s)}try{const s=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)});if(!s.ok){console.warn("Failed to update shared settings via API:",s.status,s.statusText);return}const n=await s.json().catch(()=>null);n&&(ia(n),la(n))}catch(s){console.warn("Failed to update shared settings via API:",s)}},Bm=async()=>{if(typeof window>"u")return;const t=Om();try{const r=await sy();if(!r)return;const s=()=>ty(r);if(t?.hasHydrated?.()){s();return}if(s(),t?.onFinishHydration){const n=t.onFinishHydration(()=>{n?.(),s()})}}catch(r){console.warn("Failed to load appearance preferences:",r)}},ay=3e4,iy=40,ly=60,cy=(t,r,s,n,o)=>{const a=t.trim(),l=r.trim().toLowerCase();return`${a}::${l}::${s}::${n?"1":"0"}::${o?"1":"0"}`},Ya=os()(us((t,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=ly,a){if(!s||s.trim().length===0)return[];const l=s.trim(),c=typeof n=="string"?n.trim():"",d=!!a?.includeHidden,u=a?.respectGitignore??!0,m=cy(l,c,o,d,u),f=Date.now(),p=r().cache[m];if(p&&f-p.timestamp<ay)return p.files;const h=r().inFlight[m];if(h)return h;const x=Fe.searchFiles(c,{directory:l,limit:o,includeHidden:d,respectGitignore:u}).then(g=>(t(w=>{const y={...w.cache,[m]:{files:g,timestamp:Date.now()}},v=w.cacheKeys.filter(S=>S!==m);for(v.push(m);v.length>iy;){const S=v.shift();S&&delete y[S]}return{cache:y,cacheKeys:v}}),g)).finally(()=>{t(g=>{const w={...g.inFlight};return delete w[m],{inFlight:w}})});return t(g=>({inFlight:{...g.inFlight,[m]:x}})),x},invalidateDirectory(s){if(!s||s.trim().length===0){t({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${s.trim()}::`;t(a=>{const l={...a.cache},c=a.cacheKeys.filter(m=>m.startsWith(o)?(delete l[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:l,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"})),ms=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var dy={};let ar=null;const or=ws(),Lc=or.getItem("lastDirectory"),uy=typeof Lc=="string"&&Lc.length>0,Ro=t=>{try{Ya.getState().invalidateDirectory(t)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},zm=t=>{const r=t.trim();if(!r)return r;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},my=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},ca=(t,r)=>{const s=my(t,r);return zm(s)},ka=()=>{if(typeof window<"u"){const r=or.getItem("homeDirectory")||ar||null,s=or.getItem("lastDirectory");if(s&&!Vt())return ca(s,r);if(ar)return ar;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 ar=n,or.setItem("homeDirectory",n),n;if(r&&!Vt())return ar=r,r}const t=typeof process<"u"&&dy?.HOME;return t||process?.cwd?.()||"/"},fy=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");if(s.length>1){const n=s.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return s==="/"||s.length===0?null:s},py=t=>(ar=t,typeof window<"u"&&or.setItem("homeDirectory",t),fs({homeDirectory:t}),t),Hm=async()=>{const t=n=>{const o=fy(n);return o?py(o):null};try{const n=await Fe.getFilesystemHome(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Fe.getSystemInfo(),o=t(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await Tm(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=ka(),s=t(r);return s||r},hy=()=>{if(!Vt())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const r=zm(t);return r.length>0?r:null},dn=hy()||ka();dn&&Fe.setDirectory(dn);const gy=!!(dn&&dn!=="/"),gt=os()(us((t,r)=>({currentDirectory:dn,directoryHistory:[dn],historyIndex:0,homeDirectory:dn,hasPersistedDirectory:uy,isHomeReady:gy,isSwitchingDirectory:!1,setDirectory:(s,n)=>{const o=ar||r().homeDirectory||or.getItem("homeDirectory"),a=ca(s,o);ms()&&console.log("[DirectoryStore] setDirectory called with path:",a),Fe.setDirectory(a),Ro(),t(l=>{const c=[...l.directoryHistory.slice(0,l.historyIndex+1),a];return or.setItem("lastDirectory",a),fs({lastDirectory:a}),{currentDirectory:a,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const s=r();if(s.historyIndex>0){const n=s.historyIndex-1,o=s.directoryHistory[n];Fe.setDirectory(o),Ro(),or.setItem("lastDirectory",o),fs({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const s=r();if(s.historyIndex<s.directoryHistory.length-1){const n=s.historyIndex+1,o=s.directoryHistory[n];Fe.setDirectory(o),Ro(),or.setItem("lastDirectory",o),fs({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=r(),o=ar||r().homeDirectory||ka();if(s===o||s==="/")return;const a=s.endsWith("/")?s.slice(0,-1):s,l=a.lastIndexOf("/");if(l===-1){const c=ar||ka();n(c)}else n(l===0?"/":a.substring(0,l))},goHome:async()=>{const s=ar||r().homeDirectory||await Hm();r().setDirectory(s)},synchronizeHomeDirectory:s=>{const n=r(),o=s;ar=o;const a=n.homeDirectory!==o,l=or.getItem("lastDirectory"),c=typeof l=="string"&&l.length>0,d=!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||t({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?ca(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>ca(g,o)),p=f.some((g,w)=>g!==n.directoryHistory[w]),h=!!(m&&m!==n.currentDirectory),x={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d?(x.currentDirectory=o,x.directoryHistory=[o],x.historyIndex=0,x.isSwitchingDirectory=!1):(h||p)&&(x.currentDirectory=m,x.directoryHistory=f,x.historyIndex=Math.min(n.historyIndex,f.length-1),x.isSwitchingDirectory=!1),t(()=>x),(d||h)&&u){const g=d?o:m;Fe.setDirectory(g),Ro(),or.setItem("lastDirectory",g),fs({lastDirectory:g})}fs({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Hm().then(t=>{gt.getState().synchronizeHomeDirectory(t)});const _n=ws(),Wm="projects",al="activeProjectId",xy=(t,r)=>{const s=t.trim();return!s.startsWith("~")||!r?s:s==="~"?r:s.startsWith("~/")||s.startsWith("~\\")?`${r}${s.slice(1)}`:s},Xa=t=>{const r=t.trim();if(!r)return"";const s=_n.getItem("homeDirectory")||gt.getState().homeDirectory||"",o=xy(r,s).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Um=t=>{const r=Xa(t);if(!r||r==="/")return"Root";const s=r.split("/").filter(Boolean);return s[s.length-1]||r},yy=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Vm=t=>{if(!Array.isArray(t))return[];const r=[],s=new Set,n=new Set;for(const o of t){if(!o||typeof o!="object")continue;const a=o,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=Xa(c);if(!d||s.has(l)||n.has(d))continue;s.add(l),n.add(d);const u={id:l,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&(f.branchPrefix=m.branchPrefix),typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},by=()=>{try{const t=_n.getItem(Wm);return t?Vm(JSON.parse(t)):[]}catch{return[]}},wy=()=>{try{const t=_n.getItem(al);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},zl=(t,r)=>{try{_n.setItem(Wm,JSON.stringify(t))}catch{}try{r?_n.setItem(al,r):_n.removeItem(al)}catch{}},kn=(t,r)=>{zl(t,r),fs({projects:t,activeProjectId:r??void 0})},vy=by(),jy=()=>{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 s=Xa(r);if(!s)return null;const n=`vscode:${s}`,o={id:n,path:s,label:Um(s),addedAt:Date.now(),lastOpenedAt:Date.now()};return ms()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},rr=jy(),Hl=rr?.projects??vy,Gm=rr?.activeProjectId??wy()??Hl[0]?.id??null;rr&&zl(Hl,Gm);const zt=os()(us((t,r)=>({projects:Hl,activeProjectId:Gm,validateProjectPath:s=>{if(typeof s!="string"||s.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=Xa(s);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(s,n)=>{if(rr)return null;const{validateProjectPath:o}=r(),a=o(s);if(!a.ok||!a.normalizedPath)return null;const l=a.normalizedPath,c=r().projects.find(x=>x.path===l);if(c)return r().setActiveProject(c.id),c;const d=Date.now(),u=n?.label?.trim()||Um(l),m=n?.id?.trim(),p={id:m&&!r().projects.some(x=>x.id===m)?m:yy(),path:l,label:u,addedAt:d,lastOpenedAt:d},h=[...r().projects,p];return t({projects:h}),ms()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:s=>{if(rr)return;const n=r(),o=n.projects.filter(l=>l.id!==s);let a=n.activeProjectId;if(n.activeProjectId===s&&(a=o[0]?.id??null),t({projects:o,activeProjectId:a}),kn(o,a),a){const l=o.find(c=>c.id===a);l&&(Fe.setDirectory(l.path),gt.getState().setDirectory(l.path,{showOverlay:!1}))}else gt.getState().goHome()},setActiveProject:s=>{if(rr)return;const{projects:n,activeProjectId:o}=r();if(o===s)return;const a=n.find(d=>d.id===s);if(!a)return;const l=Date.now(),c=n.map(d=>d.id===s?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:s}),kn(c,s),Fe.setDirectory(a.path),gt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:s=>{if(rr)return;const{projects:n,activeProjectId:o}=r();if(o===s||!n.find(d=>d.id===s))return;const l=Date.now(),c=n.map(d=>d.id===s?{...d,lastOpenedAt:l}:d);t({projects:c,activeProjectId:s}),kn(c,s)},renameProject:(s,n)=>{if(rr)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:l}=r(),c=a.map(d=>d.id===s?{...d,label:o}:d);t({projects:c}),kn(c,l)},reorderProjects:(s,n)=>{if(rr)return;const{projects:o,activeProjectId:a}=r();if(s<0||s>=o.length||n<0||n>=o.length||s===n)return;const l=[...o],[c]=l.splice(s,1);l.splice(n,0,c),t({projects:l}),kn(l,a)},synchronizeFromSettings:s=>{if(rr)return;const n=Vm(s.projects??[]),o=typeof s.activeProjectId=="string"&&s.activeProjectId.trim()?s.activeProjectId.trim():null,a=r(),l=JSON.stringify(a.projects)!==JSON.stringify(n),c=a.activeProjectId!==o;if(!(!l&&!c)&&(t({projects:n,activeProjectId:o}),zl(n,o),o)){const d=n.find(u=>u.id===o);d&&(Fe.setDirectory(d.path),gt.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:s,activeProjectId:n}=r();return n?s.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(s,n)=>{if(rr)return;const{projects:o,activeProjectId:a}=r(),l=o.find(u=>u.id===s);if(!l)return;const c={...l.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?c.branchPrefix=n.branchPrefix.trim():delete c.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?c.baseBranch=n.baseBranch.trim():delete c.baseBranch),n.autoCreateWorktree!==void 0&&(c.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===s?{...u,worktreeDefaults:Object.keys(c).length>0?c:void 0}:u);t({projects:d}),kn(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const r=t.detail;r&&typeof r=="object"&&zt.getState().synchronizeFromSettings(r)});const Sy=new Set(["init","review"]),Fn=t=>Sy.has(t.name),mo="useCommandsStore",il=t=>new Promise(r=>setTimeout(r,t)),Lo=()=>{try{const r=zt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Fe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},Ny=2e4,Oc=300,_c=4,ky=800,Cy=200,My=2e3,Jr=os()(us(Vs((t,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:s=>{t({selectedCommandName:s})},setCommandDraft:s=>{t({commandDraft:s})},loadCommands:async()=>{t({isLoading:!0});const s=r().commands;let n=null;for(let o=0;o<3;o++)try{const a=Lo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await Fe.withDirectory(a,()=>Fe.listCommandsWithDetails()),d=await Promise.all(c.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${l}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const h=f.sources;p=(h.md?.exists?h.md.scope:void 0)??(h.json?.exists?h.json.scope:void 0)??h.md?.scope??h.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(s)!==JSON.stringify(d)?t({commands:d,isLoading:!1}):t({isLoading:!1}),!0}catch(a){n=a;const l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load commands:",n),t({commands:s,isLoading:!1}),!1},createCommand:async s=>{Hs("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",s.name);const o={template:s.template||""};s.description&&(o.description=s.description),s.agent&&(o.agent=s.agent),s.model&&(o.model=s.model),s.subtask!==void 0&&(o.subtask=s.subtask),s.scope&&(o.scope=s.scope),console.log("[CommandsStore] Command config to save:",o);const a=Lo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(s.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await gi({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&wr("commands",{source:mo}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Fs()}},updateCommand:async(s,n)=>{Hs("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",s),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const l=Lo(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await gi({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&wr("commands",{source:mo}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Fs()}},deleteCommand:async s=>{Hs("Deleting command configuration…");let n=!1;try{const o=Lo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),c?.requiresReload??!0)return n=!0,await gi({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&wr("commands",{source:mo}),r().selectedCommandName===s&&t({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Fs()}},getCommandByName:s=>{const{commands:n}=r();return n.find(o=>o.name===s)}}),{name:"commands-store",storage:Gs(()=>ws()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Jr);async function Dy(t){const r=typeof t=="number"&&t>0?Math.min(t,Oc):0;r>0&&await il(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<Ny;){n+=1,Pr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Fe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=_c&&a<1200?Oc:Math.min(ky+Math.max(0,n-_c)*Cy,My);await il(l)}throw o||new Error("OpenCode did not become ready in time")}async function gi(t={}){const{message:r,delayMs:s}=t;try{Pr(r||"Refreshing commands…")}catch{}try{await Dy(s),Pr("Refreshing commands…"),await Jr.getState().loadCommands(),wr("commands",{source:mo})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Pr("OpenCode refresh failed. Please retry refreshing configuration manually."),await il(1500)}finally{Fs()}}let $c=null;$c||($c=Qa(t=>{if(t.source!==mo&&jo(t,"commands")){const{loadCommands:r}=Jr.getState();r()}}));const $r=()=>{const t=Fe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},da="useSkillsStore",ir=os()(us(Vs((t,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:s=>{t({selectedSkillName:s})},setSkillDraft:s=>{t({skillDraft:s})},loadSkills:async()=>{t({isLoading:!0});const s=r().skills;let n=null;for(let o=0;o<3;o++)try{const a=$r(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills${l}`);if(!c.ok)throw new Error(`Failed to list skills: ${c.status}`);const m=((await c.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return t({skills:m,isLoading:!1}),!0}catch(a){n=a;const l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load skills:",n),t({skills:s,isLoading:!1}),!1},getSkillDetail:async s=>{try{const n=$r(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async s=>{Hs("Creating skill...");try{const n={name:s.name,description:s.description};s.instructions&&(n.instructions=s.instructions),s.scope&&(n.scope=s.scope),s.supportingFiles&&(n.supportingFiles=s.supportingFiles);const o=$r(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),c=await l.json().catch(()=>null);if(!l.ok){const u=c?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&wr("skills",{source:da}),d}catch{return!1}finally{Fs()}},updateSkill:async(s,n)=>{Hs("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=$r(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(s)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&wr("skills",{source:da}),u}catch{return!1}finally{Fs()}},deleteSkill:async s=>{Hs("Deleting skill...");try{const n=$r(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`,{method:"DELETE"}),l=await a.json().catch(()=>null);if(!a.ok){const d=l?.error||"Failed to delete skill";throw new Error(d)}const c=await r().loadSkills();return c&&wr("skills",{source:da}),r().selectedSkillName===s&&t({selectedSkillName:null}),c}catch{return!1}finally{Fs()}},getSkillByName:s=>{const{skills:n}=r();return n.find(o=>o.name===s)},readSupportingFile:async(s,n)=>{try{const o=$r(),a=o?`&directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return l.ok?(await l.json()).content??null:null}catch{return null}},writeSupportingFile:async(s,n,o)=>{try{const a=$r(),l=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${l}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(s,n)=>{try{const o=$r(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Gs(()=>ws()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=ir);let Bc=null;Bc||(Bc=Qa(t=>{if(t.source!==da&&jo(t,"skills")){const{loadSkills:r}=ir.getState();r()}}));const xi=()=>{const t=Fe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Ao=os()(us((t,r)=>({sources:[],itemsBySource:{},selectedSourceId:null,isLoadingCatalog:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:s=>t({selectedSourceId:s}),loadCatalog:async s=>{t({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource};let o=null;try{for(let a=0;a<3;a++)try{const l=xi(),c=s?.refresh?"&refresh=true":"",d=l?`?directory=${encodeURIComponent(l)}${c}`:c?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const g=200*(a+1);await new Promise(w=>setTimeout(w,g));continue}const f=m.sources||[],p=m.itemsBySource||{},h=r().selectedSourceId,x=h&&f.some(g=>g.id===h)?h:f[0]?.id??null;return t({sources:f,itemsBySource:p,selectedSourceId:x}),!0}catch(l){o={kind:"unknown",message:l instanceof Error?l.message:String(l)};const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}return t({sources:n.sources,itemsBySource:n.itemsBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{t({isLoadingCatalog:!1})}},scanRepo:async s=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const n=xi(),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(s)}),l=await a.json().catch(()=>null);if(!a.ok||!l){const c=l?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:c}),{ok:!1,error:c}}return l.ok?(t({scanResults:l.items||[]}),l):(t({lastScanError:l.error||{kind:"unknown",message:"Failed to scan repository"}}),l)}finally{t({isScanning:!1})}},installSkills:async s=>{t({isInstalling:!0,lastInstallError:null});try{const n=xi(),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(s)}),l=await a.json().catch(()=>null);if(!l){const c={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:c}),{ok:!1,error:c}}if(!a.ok||!l.ok){const c=l.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:c}),{ok:!1,error:c}}return ir.getState().loadSkills(),l}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return t({lastInstallError:o}),{ok:!1,error:o}}finally{t({isInstalling:!1})}}}),{name:"skills-catalog-store"})),Ay=()=>{const t=Fe.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Oo=()=>{try{const r=zt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const s=Fe.getDirectory();if(s?.trim())return s.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null},on=t=>{const r=t;return r.native===!0||r.builtIn===!0},qm=t=>{const r=t;return r.hidden===!0||r.options?.hidden===!0},Km=t=>t.filter(r=>!qm(r)),ua="useAgentsStore",Ca=t=>new Promise(r=>setTimeout(r,t)),Ey=2e4,zc=300,Hc=4,Iy=800,Py=200,Ty=2e3,Zr=os()(us(Vs((t,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:s=>{t({selectedAgentName:s})},setAgentDraft:s=>{t({agentDraft:s})},loadAgents:async()=>{t({isLoading:!0});const s=r().agents;for(let n=0;n<3;n++)try{const o=Oo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await Fe.withDirectory(o,()=>Fe.listAgents()),c=await Promise.all(l.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(s)!==JSON.stringify(c)?t({agents:c,isLoading:!1}):t({isLoading:!1}),!0}catch{}return t({isLoading:!1}),!1},createAgent:async s=>{Hs("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",s.name);const o={mode:s.mode||"subagent"};s.description&&(o.description=s.description),s.model&&(o.model=s.model),s.temperature!==void 0&&(o.temperature=s.temperature),s.top_p!==void 0&&(o.top_p=s.top_p),s.prompt&&(o.prompt=s.prompt),s.permission&&(o.permission=s.permission),s.disable!==void 0&&(o.disable=s.disable),s.scope&&(o.scope=s.scope),console.log("[AgentsStore] Agent config to save:",o);const a=Oo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(s.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await fo({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&wr("agents",{source:ua}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Fs()}},updateAgent:async(s,n)=>{Hs("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const l=Oo(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await fo({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&wr("agents",{source:ua}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Fs()}},deleteAgent:async s=>{Hs("Deleting agent configuration…");let n=!1;try{const o=Oo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete agent";throw new Error(m)}if(c?.requiresReload??!0)return n=!0,await fo({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&wr("agents",{source:ua}),r().selectedAgentName===s&&t({selectedAgentName:null}),u}catch{return!1}finally{n||Fs()}},getAgentByName:s=>{const{agents:n}=r();return n.find(o=>o.name===s)},getVisibleAgents:()=>{const{agents:s}=r();return Km(s)}}),{name:"agents-store",storage:Gs(()=>ws()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Zr);async function Fy(t){const r=typeof t=="number"&&t>0?Math.min(t,zc):0;r>0&&await Ca(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<Ey;){n+=1,Pr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Fe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-s,l=n<=Hc&&a<1200?zc:Math.min(Iy+Math.max(0,n-Hc)*Py,Ty);await Ca(l)}throw o||new Error("OpenCode did not become ready in time")}const Ry=t=>{if(!t||t.length===0)return["all"];const r=Array.from(new Set(t));return r.includes("all")?["all"]:r};async function Ly(t={}){const{message:r,delayMs:s}=t,n=Ry(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{Pr(r||"Refreshing configuration…")}catch{}try{await Fy(s);const a=et.getState(),l=Zr.getState(),c=Jr.getState(),d=ir.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"),h=n.includes("all")||n.includes("commands"),x=n.includes("all")||n.includes("skills"),g=Ay(),w=o==="projects"?zt.getState().projects:[],y=Array.from(new Set([...g?[g]:[],...w.map(k=>k.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&et.setState({directoryScoped:{}});const v=[];for(const k of y)m&&v.push(a.loadProviders({directory:k}).then(()=>{})),f&&v.push(a.loadAgents({directory:k}).then(()=>{}));const S=[];p&&S.push(l.loadAgents().then(()=>{})),h&&S.push(c.loadCommands().then(()=>{})),x&&(S.push(d.loadSkills().then(()=>{})),S.push(u.loadCatalog().then(()=>{}))),Pr("Refreshing configuration…"),await Promise.all([...v,...S])}catch{Pr("OpenCode refresh failed. Please retry."),await Ca(1500)}finally{Fs()}}async function fo(t){await Ly(t)}async function po(t){Hs(t?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),s=await r.json().catch(()=>null);if(!r.ok){const o=s?.error||"Failed to reload configuration";throw new Error(o)}const n={...t,scopes:t?.scopes??["all"],mode:t?.mode??"projects"};s?.requiresReload?await fo({...n,message:s.message,delayMs:s.reloadDelayMs}):await fo(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),Pr("Failed to reload configuration. Please try again."),await Ca(2e3),Fs(),r}}let Wc=null;Wc||(Wc=Qa(t=>{if(t.source!==ua&&jo(t,"agents")){const{loadAgents:r}=Zr.getState();r()}}));const Oy="https://models.dev/api.json",_y="/api/openchamber/models-metadata",Uc="opencode",Vc="big-pickle",$y=async()=>{try{if(ds()){const c=await Lr();return{defaultModel:c?.defaultModel,defaultVariant:c?.defaultVariant,defaultAgent:c?.defaultAgent,autoCreateWorktree:c?.autoCreateWorktree,gitmojiEnabled:c?.gitmojiEnabled}}const t=Ms()?.settings;if(t)try{const d=(await t.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?.gitmojiEnabled=="boolean"?d.gitmojiEnabled:void 0;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,gitmojiEnabled:p}}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const s=await r.json(),n=typeof s?.defaultModel=="string"?s.defaultModel.trim():"",o=typeof s?.defaultVariant=="string"?s.defaultVariant.trim():"",a=typeof s?.defaultAgent=="string"?s.defaultAgent.trim():"",l=typeof s?.gitmojiEnabled=="boolean"?s.gitmojiEnabled:void 0;return{defaultModel:n.length>0?n:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:a.length>0?a:void 0,autoCreateWorktree:typeof s?.autoCreateWorktree=="boolean"?s.autoCreateWorktree:void 0,gitmojiEnabled:l}}catch{return{}}},_o=t=>{if(!t||typeof t!="string")return null;const r=t.split("/");return r.length!==2||!r[0]||!r[1]?null:{providerId:r[0],modelId:r[1]}},By=t=>t?.toLowerCase?.()??"",zy=t=>t==="primary"||t==="all"||t===void 0||t===null,So=t=>typeof t=="object"&&t!==null,Ma=t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),Hy=t=>{if(!So(t))return!1;const r=t;if(r.modalities){const{input:s,output:n}=r.modalities;if(s&&!Ma(s)||n&&!Ma(n))return!1}return!0},Wy=t=>{if(!So(t))return!1;const r=t;return r.models===void 0||So(r.models)},Qm=(t,r)=>{const s=By(t);return!s||!r?"":`${s}/${r}`},Uy=t=>{const r=new Map;if(!So(t))return r;for(const[s,n]of Object.entries(t)){if(!Wy(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:s,a=n.models;if(!(!a||!So(a)))for(const[l,c]of Object.entries(a)){if(!Hy(c))continue;const d=typeof l=="string"&&l.length>0?l:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:Ma(c.modalities.input)?c.modalities.input:void 0,output:Ma(c.modalities.output)?c.modalities.output:void 0}:void 0,cost:c.cost,limit:c.limit,knowledge:typeof c.knowledge=="string"?c.knowledge:void 0,release_date:typeof c.release_date=="string"?c.release_date:void 0,last_updated:typeof c.last_updated=="string"?c.last_updated:void 0},m=Qm(o,d);m&&r.set(m,u)}}return r},Vy=async()=>{if(typeof fetch!="function")return new Map;const t=[_y,Oy];for(const r of t){const s=typeof AbortController<"u"?new AbortController:void 0,n=s?setTimeout(()=>s.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:s?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const l=await fetch(r,a);if(!l.ok)throw new Error(`Metadata request to ${r} returned status ${l.status}`);const c=await l.json();return Uy(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let yi=null;const Gy=(t,r)=>{t().size>0||yi||(yi=Vy().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{yi=null}))},qy=t=>new Promise(r=>setTimeout(r,t)),Wl="__global__",$n=t=>{const r=typeof t=="string"?t.trim():"";return r.length>0?r:Wl},Cn=t=>t===Wl?null:t,Ky=()=>{if(typeof window>"u")return Wl;const t=Fe.getDirectory()??gt.getState().currentDirectory;return $n(t)},et=os()(us(Vs((t,r)=>({activeDirectoryKey:Ky(),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,settingsGitmojiEnabled:!1,activateDirectory:async s=>{const n=$n(s);t(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 s=>{const n=$n(s?.directory??Cn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),l=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let c=null;for(let d=0;d<3;d++)try{Gy(()=>r().modelsMetadata,h=>t({modelsMetadata:h}));const u=await Fe.withDirectory(Cn(n),()=>Fe.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(h=>{const x=h.models??{},g=Object.keys(x).map(w=>x[w]);return{...h,models:g}});t(h=>{const g={...h.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},w={directoryScoped:{...h.directoryScoped,[n]:g}};if(h.activeDirectoryKey===n&&(w.providers=p,w.defaultProviders=f,!h.currentProviderId&&!h.currentModelId&&h.settingsDefaultModel)){const y=_o(h.settingsDefaultModel);if(y){const v=p.find(S=>S.id===y.providerId);if(v?.models.some(S=>S.id===y.modelId)){const S=v.models.find(b=>b.id===y.modelId),k=h.settingsDefaultVariant&&S?.variants?.[h.settingsDefaultVariant]?h.settingsDefaultVariant:void 0;w.currentProviderId=y.providerId,w.currentModelId=y.modelId,w.currentVariant=k,w.selectedProviderId=y.providerId,g.currentProviderId=y.providerId,g.currentModelId=y.modelId,g.currentVariant=k,g.selectedProviderId=y.providerId}}}return w});return}catch(u){c=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",c),t(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:l},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=l,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=_o(d.settingsDefaultModel);if(p){const h=a.find(x=>x.id===p.providerId);if(h?.models.some(x=>x.id===p.modelId)){const x=h.models.find(w=>w.id===p.modelId),g=d.settingsDefaultVariant&&x?.variants?.[d.settingsDefaultVariant]?d.settingsDefaultVariant:void 0;f.currentProviderId=p.providerId,f.currentModelId=p.modelId,f.currentVariant=g,f.selectedProviderId=p.providerId,m.currentProviderId=p.providerId,m.currentModelId=p.modelId,m.currentVariant=g,m.selectedProviderId=p.providerId}}}return f})},setProvider:s=>{const{providers:n}=r(),o=n.find(c=>c.id===s);if(!o)return;const l=o.models[0]?.id||"";t(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentVariant:c.currentVariant,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentProviderId:s,currentModelId:l,selectedProviderId:s};return{currentProviderId:s,currentModelId:l,selectedProviderId:s,directoryScoped:{...c.directoryScoped,[d]:m}}})},setModel:s=>{t(n=>{const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:s};return{currentModelId:s,directoryScoped:{...n.directoryScoped,[o]:l}}})},setCurrentVariant:s=>{t(n=>{if(n.currentVariant===s)return n;const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:s};return{currentVariant:s,directoryScoped:{...n.directoryScoped,[o]:l}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const s=r().getCurrentModelVariants();if(s.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(s[0]);return}const o=s.indexOf(n);if(o===-1||o===s.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(s[o+1])},setSelectedProvider:s=>{t(n=>{const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:s};return{selectedProviderId:s,directoryScoped:{...n.directoryScoped,[o]:l}}})},saveAgentModelSelection:(s,n,o)=>{t(a=>{const l=a.activeDirectoryKey,c={...a.agentModelSelections,[s]:{providerId:n,modelId:o}},u={...a.directoryScoped[l]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:c};return{agentModelSelections:c,directoryScoped:{...a.directoryScoped,[l]:u}}})},getAgentModelSelection:s=>{const{agentModelSelections:n}=r();return n[s]||null},loadAgents:async s=>{const n=$n(s?.directory??Cn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let l=null;for(let c=0;c<3;c++)try{const[d,u]=await Promise.all([Fe.withDirectory(Cn(n),()=>Fe.listAgents()),$y()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(t(b=>{const D={...b.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},j={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsGitmojiEnabled:u.gitmojiEnabled??!1,directoryScoped:{...b.directoryScoped,[n]:D}};return b.activeDirectoryKey===n&&(j.agents=m),j}),m.length===0)return t(b=>{const D={...b.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},j={directoryScoped:{...b.directoryScoped,[n]:D}};return b.activeDirectoryKey===n&&(j.currentAgentName=void 0),j}),!0;const p=(b,N)=>{const D=f.find(j=>j.id===b);return D?D.models.some(j=>j.id===N):!1},h=m.filter(b=>zy(b.mode));let w=h.find(b=>b.name==="build")||h[0]||m[0];const y={};if(u.defaultAgent){const b=m.find(N=>N.name===u.defaultAgent);b?w=b:y.defaultAgent=""}let v,S,k;if(u.defaultModel){const b=_o(u.defaultModel);if(b&&p(b.providerId,b.modelId)){if(v=b.providerId,S=b.modelId,u.defaultVariant){const j=f.find(M=>M.id===b.providerId)?.models.find(M=>M.id===b.modelId)?.variants;j&&Object.prototype.hasOwnProperty.call(j,u.defaultVariant)?k=u.defaultVariant:y.defaultVariant=""}}else y.defaultModel=""}if(!v&&w?.model?.providerID&&w?.model?.modelID){const{providerID:b,modelID:N}=w.model;p(b,N)&&(v=b,S=N)}if(!v)if(p(Uc,Vc))v=Uc,S=Vc;else{const b=f[0],N=b?.models[0];b&&N&&(v=b.id,S=N.id)}return t(b=>{const N=b.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},D={...N,providers:f,agents:m,currentAgentName:w.name,currentProviderId:v??N.currentProviderId,currentModelId:S??N.currentModelId,currentVariant:k},j={directoryScoped:{...b.directoryScoped,[n]:D}};return b.activeDirectoryKey===n&&(j.currentAgentName=w.name,v&&S&&(j.currentProviderId=v,j.currentModelId=S,j.currentVariant=k)),j}),Object.keys(y).length>0&&(t({settingsDefaultModel:y.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:y.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:y.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),fs(y).catch(()=>{})),!0}catch(d){l=d;const u=200*(c+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",l),t(c=>{const d=c.activeDirectoryKey===n?c.providers:c.directoryScoped[n]?.providers??[],m={...c.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...c.directoryScoped,[n]:m}};return c.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:s=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:l}=r();if(t(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentAgentName:s};return{currentAgentName:s,directoryScoped:{...c.directoryScoped,[d]:m}}}),s&&typeof window<"u"){const c=window.__zustand_session_store__;if(c){const d=c.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&c.setState(h=>{const x=new Map(h.currentAgentContext);return x.set(u,s),{currentAgentContext:x}}),u&&m(u)&&(p(u,s)||f(u,n))}}if(s&&typeof window<"u"){const c=window.__zustand_session_store__;if(c?.getState){const{currentSessionId:m,getAgentModelForSession:f}=c.getState();if(m&&f(m,s))return}if(a){const m=_o(a);if(m&&o.find(p=>p.id===m.providerId)?.models.some(p=>p.id===m.modelId)){t(p=>{const h=p.activeDirectoryKey,x=p.directoryScoped[h]??{providers:p.providers,agents:p.agents,currentProviderId:p.currentProviderId,currentModelId:p.currentModelId,currentVariant:p.currentVariant,currentAgentName:p.currentAgentName,selectedProviderId:p.selectedProviderId,agentModelSelections:p.agentModelSelections,defaultProviders:p.defaultProviders};let g;if(l){const S=o.find(k=>k.id===m.providerId)?.models.find(k=>k.id===m.modelId)?.variants;S&&Object.prototype.hasOwnProperty.call(S,l)&&(g=l)}const w={...x,currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:g};return{currentProviderId:m.providerId,currentModelId:m.modelId,currentVariant:g,directoryScoped:{...p.directoryScoped,[h]:w}}});return}}const u=n.find(m=>m.name===s)?.model;if(u?.providerID&&u?.modelID){const{providerID:m,modelID:f}=u;o.find(x=>x.id===m)?.models.find(x=>x.id===f)&&t(x=>{const g=x.activeDirectoryKey,y={...x.directoryScoped[g]??{providers:x.providers,agents:x.agents,currentProviderId:x.currentProviderId,currentModelId:x.currentModelId,currentAgentName:x.currentAgentName,selectedProviderId:x.selectedProviderId,agentModelSelections:x.agentModelSelections,defaultProviders:x.defaultProviders},currentProviderId:m,currentModelId:f,selectedProviderId:m};return{currentProviderId:m,currentModelId:f,selectedProviderId:m,directoryScoped:{...x.directoryScoped,[g]:y}}})}}},setSettingsDefaultModel:s=>{t({settingsDefaultModel:s})},setSettingsDefaultVariant:s=>{t({settingsDefaultVariant:s})},setSettingsDefaultAgent:s=>{t({settingsDefaultAgent:s})},setSettingsAutoCreateWorktree:s=>{t({settingsAutoCreateWorktree:s})},setSettingsGitmojiEnabled:s=>{t({settingsGitmojiEnabled:s})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Fe.checkHealth();return t({isConnected:a}),a}catch(a){o=a,n+=1;const l=400*n;await qy(l)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const s=ms();s&&console.log("Starting app initialization...");const n=await r().checkConnection();if(s&&console.log("Connection check result:",n),!n){s&&console.log("Server not connected"),t({isConnected:!1});return}s&&console.log("Initializing app..."),await Fe.initApp(),s&&console.log("Loading providers..."),await r().loadProviders(),s&&console.log("Loading agents..."),await r().loadAgents(),t({isInitialized:!0,isConnected:!0}),s&&console.log("App initialized successfully")}catch(s){console.error("Failed to initialize app:",s),t({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:s,currentProviderId:n}=r();return s.find(o=>o.id===n)},getCurrentModel:()=>{const s=r().getCurrentProvider(),{currentModelId:n}=r();if(s)return s.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:s,currentAgentName:n}=r();if(n)return s.find(o=>o.name===n)},getModelMetadata:(s,n)=>{const o=Qm(s,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:s}=r();return Km(s)}}),{name:"config-store",storage:Gs(()=>ws()),partialize:t=>({activeDirectoryKey:t.activeDirectoryKey,directoryScoped:t.directoryScoped,currentProviderId:t.currentProviderId,currentModelId:t.currentModelId,currentVariant:t.currentVariant,currentAgentName:t.currentAgentName,selectedProviderId:t.selectedProviderId,agentModelSelections:t.agentModelSelections,defaultProviders:t.defaultProviders,settingsDefaultModel:t.settingsDefaultModel,settingsDefaultVariant:t.settingsDefaultVariant,settingsDefaultAgent:t.settingsDefaultAgent,settingsAutoCreateWorktree:t.settingsAutoCreateWorktree,settingsGitmojiEnabled:t.settingsGitmojiEnabled})})));typeof window<"u"&&(window.__zustand_config_store__=et);let Gc=null;Gc||(Gc=Qa(async t=>{const r=[];if(jo(t,"agents")){const{loadAgents:s}=et.getState();r.push(s().then(()=>{}))}if(jo(t,"providers")){const{loadProviders:s}=et.getState();r.push(s())}r.length>0&&await Promise.all(r)}));let qc=null;typeof window<"u"&&!qc&&(qc=gt.subscribe((t,r)=>{const s=$n(t.currentDirectory),n=$n(r.currentDirectory);s!==n&&et.getState().activateDirectory(t.currentDirectory)}));const an={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,HISTORICAL_MESSAGES:90,FETCH_BUFFER:20,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},ll=180,Da=()=>{const t=ke.getState?.();return t?{...an,HISTORICAL_MESSAGES:t.memoryLimitHistorical??an.HISTORICAL_MESSAGES,VIEWPORT_MESSAGES:t.memoryLimitViewport??an.VIEWPORT_MESSAGES}:an},cl=()=>{const t=ke.getState?.();return t?t.memoryLimitActiveSession??ll:ll},Mr=an,Ds=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Or(t){const r=Ds();return r?r.checkIsGitRepository(t):hx(t)}async function Qy(t){const r=Ds();return r?r.getGitStatus(t):xx(t)}async function Ja(t){const r=Ds();return r?r.getGitBranches(t):Ax(t)}async function Yy(t,r){const s=Ds();return s?s.deleteGitBranch(t,r):bx(t,r)}async function Xy(t,r){const s=Ds();return s?s.deleteRemoteBranch(t,r):wx(t,r)}async function Jy(t,r){const s=Ds();return s?.generatePullRequestDescription?s.generatePullRequestDescription(t,r):Ix(t,r)}async function Ym(t){const r=Ds();return r?r.listGitWorktrees(t):gx(t)}async function Zy(t,r){const s=Ds();return s?s.addGitWorktree(t,r):vx(t,r)}async function Xm(t,r){const s=Ds();return s?s.removeGitWorktree(t,r):yx(t,r)}async function eb(t){const r=Ds();return r?r.ensureOpenChamberIgnored(t):Dx(t)}async function tb(t,r={}){const s=Ds();return s?s.gitFetch(t,r):Ex(t,r)}async function sb(){const t=Ds();return t?t.getGitIdentities():Mx()}async function rb(t){const r=Ds();return r?r.createGitIdentity(t):Nx(t)}async function nb(t,r){const s=Ds();return s?s.updateGitIdentity(t,r):Sx(t,r)}async function ob(t){const r=Ds();return r?r.deleteGitIdentity(t):jx(t)}async function ab(){const t=Ds();return t?.discoverGitCredentials?t.discoverGitCredentials():kx()}async function ib(){const t=Ds();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():Cx()}const lb="openchamber.json",Jm=".openchamber";function Zm(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const cb=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},dl=(t,r)=>{const s=cb(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},ef=t=>dl(dl(t,Jm),lb);async function tf(t){const r=ef(t);try{const s=Zm();if(s?.readFile)try{const l=await s.readFile(r);if(!l.content.trim())return null;const c=JSON.parse(l.content);return!c||typeof c!="object"?null:c}catch{return null}const n=await fetch(`${rf()}/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 db(t,r){const s=ef(t),n=dl(t,Jm);try{await Fe.createDirectory(n);const o=Zm();if(o?.writeFile)try{return(await o.writeFile(s,JSON.stringify(r,null,2))).success}catch(l){return console.error("Failed to write openchamber config via runtime API:",l),!1}return(await fetch(`${rf()}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s,content:JSON.stringify(r,null,2)})})).ok}catch(o){return console.error("Failed to write openchamber config:",o),!1}}async function ub(t,r){const n={...await tf(t)||{},...r};return db(t,n)}async function Sn(t){return(await tf(t))?.["setup-worktree"]??[]}async function sf(t,r){const s=r.filter(n=>n.trim().length>0);return ub(t,{"setup-worktree":s})}function mb(t,r){return t.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function rf(){const t="/api";return t.startsWith("/"),t}const fb=".openchamber",Kc="/api";function pb(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Rr=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Qc=(t,r)=>{const s=Rr(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},nf=t=>t?t.startsWith("refs/heads/")?t.substring(11):t.startsWith("heads/")?t.substring(6):t.startsWith("refs/")?t.substring(5):t:"",hb=async t=>{try{await Fe.createDirectory(t)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function gb(t,r){const s=Rr(t),n=Qc(s,fb);return await hb(n),Qc(n,r)}async function Za(t){const{projectDirectory:r,worktreeSlug:s,branch:n,createBranch:o,startPoint:a}=t,l=Rr(r),c=await gb(l,s),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await Zy(l,d),{path:c,branch:n,label:nf(n),projectDirectory:l,relativePath:c.startsWith(`${l}/`)?c.slice(l.length+1):c}}async function Ul(t){const{projectDirectory:r,path:s,force:n}=t,o=Rr(r);await Xm(o,{path:s,force:n})}async function of(t){const{projectDirectory:r,path:s,branch:n,force:o,deleteRemote:a,remote:l}=t,c=Rr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Xm(c,{path:s,force:o}),d&&(await Yy(c,{branch:d,force:!0}),a))try{await Xy(c,{branch:d,remote:l})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Un(t){const r=Rr(t);return Ym(r)}async function Eo(t){const r=Rr(t),s=await Qy(r);return{isDirty:!s.isClean,ahead:s.ahead,behind:s.behind,upstream:s.tracking}}function Vn(t,r){const s=Rr(t),n=Rr(r.worktree);return{path:n,branch:r.branch??"",label:nf(r.branch??""),projectDirectory:s,relativePath:n.startsWith(`${s}/`)?n.slice(s.length+1):n}}async function ei(t,r,s){const n=s??await Sn(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>mb(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:t,projectDirectory:r,commands:o});try{const a=pb();if(a?.execCommands){console.log("[worktreeService] Using runtime API for exec");try{const d=await a.execCommands(o,t);return console.log("[worktreeService] Runtime exec result:",d),d}catch(d){return console.error("[worktreeService] Runtime exec error:",d),{success:!1,results:o.map(u=>({command:u,success:!1,error:d instanceof Error?d.message:"Unknown error"}))}}}console.log("[worktreeService] Using web API for exec");const l=await fetch(`${Kc}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:t,background:!0})}),c=await l.json().catch(()=>null);if(l.status===202&&c&&typeof c.jobId=="string"){const d=c.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(g=>setTimeout(g,u));const p=await fetch(`${Kc}/fs/exec/${d}`,{method:"GET"}),h=await p.json().catch(()=>null);if(!p.ok)return{success:!1,results:o.map(g=>({command:g,success:!1,error:h&&h.error||"Failed to poll exec job"}))};if(h?.status==="done"){const g=Array.isArray(h?.results)?h.results:[];return{success:h?.success===!0,results:g}}}return{success:!1,results:o.map(p=>({command:p,success:!1,error:"Setup commands timed out"}))}}if(!l.ok){const d=c&&c.error||"Request failed";return console.error("[worktreeService] Web exec failed:",c),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",c),c}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(l=>({command:l,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const af=ws(),lf="oc.sessionSelectionByDirectory",bi=".openchamber",xb=()=>{try{const t=af.getItem(lf);if(!t)return{};const r=JSON.parse(t);return!r||typeof r!="object"?{}:Object.entries(r).reduce((s,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(s[n]=o),s),{})}catch{return{}}};let ma=null;const Vl=()=>(ma||(ma=xb()),ma),cf=t=>{ma=t;try{af.setItem(lf,JSON.stringify(t))}catch{}},df=t=>{if(!t)return null;const s=Vl()[t];return typeof s=="string"?s:null},kr=(t,r)=>{if(!t)return;const s={...Vl()};r?s[t]=r:delete s[t],cf(s)},yb=(t,r)=>{if(!t)return;const s=df(t);if(!s)return;if(!new Set(r).has(s)){const o={...Vl()};delete o[t],cf(o)}},Yc=async(t,r)=>{const s=t.status??await Eo(t.path).catch(()=>{});await of({projectDirectory:t.projectDirectory,path:t.path,branch:t.branch,force:!!s?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},It=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},Xc=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,r=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return It(r)},bb=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,$o=(...t)=>{ms()&&bb()&&console.log("[OpenChamber][VSCode][sessions]",...t)},Br=t=>{const r=new Map;return t.forEach(s=>{if(!s||typeof s.id!="string"||s.id.length===0)return;const n=r.get(s.id);if(!n){r.set(s.id,s);return}const o=n.time?.updated??0;(s.time?.updated??0)>o&&r.set(s.id,s)}),Array.from(r.values())},er=t=>{const r=new Map;t.forEach(s=>{const n=It(s.directory??null);if(!n)return;const o=r.get(n);o?o.push(s):r.set(n,[s])});for(const[s,n]of r.entries())r.set(s,Br(n));return r},Mn=(t,r)=>{const s=t.find(n=>n.id===r);return s?It(s.directory??null):null},wb=async(t,r,s)=>{const n=It(r);if(!n||t.length===0)return null;const o=t.map(u=>({id:u.id,directory:It(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Un(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(s);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const l=new Map;a.forEach(u=>{const m=Vn(n,u),f=It(m.path)??m.path;f!==n&&l.set(f,m)});let c=!1;const d=new Map(s);return o.forEach(({id:u,directory:m})=>{const f=l.get(m);if(!f){d.delete(u)&&(c=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),c=!0)}),c?d:null},pt=os()(us(Vs((t,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()=>{t({isLoading:!0,error:null});try{const s=gt.getState(),n=zt.getState(),o=Fe.getApiClient(),a=Xc(),l=!!a;$o("loadSessions:start",{workspace:a,currentDirectory:s.currentDirectory,clientDirectory:Fe.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const c=new Map,d=async R=>{const K=It(R)??R,Y=K,_=c.get(Y);if(_)return _;try{const J=await o.path.get({directory:R}),Q=It(J.data?.directory??null)??K;return c.set(Y,Q),Q}catch{return c.set(Y,K),K}},u=(R,K,Y)=>{const _=It(K);if(!_)return R;const q=Y?.includeDescendants===!0?`${_}/`:null,Q=Y?.includeMissingDirectory===!0;return R.filter(z=>{const H=It(z.directory??null);return H?!!(H===_||q&&H.startsWith(q)):Q})},m=(R,K,Y)=>{const _=It(K);if(!_)return R;const J=It(Y??null);if(!J||J===_)return R.map(z=>It(z.directory??null)?z:{...z,directory:_});const q=J==="/"?"/":`${J}/`,Q=_==="/"?"/":`${_}/`;return R.map(z=>{const H=It(z.directory??null);if(!H)return{...z,directory:_};if(H===J)return{...z,directory:_};if(q!=="/"&&H.startsWith(q)){const W=H.slice(q.length);return{...z,directory:`${Q}${W}`}}return z})},f=async R=>{const K=It(R);if(!K)try{const H=await o.session.list(void 0);return Array.isArray(H.data)?H.data:[]}catch(H){throw console.debug("Failed to list sessions (global):",H),H}const Y=await d(K),_=async()=>{const H=await o.session.list({directory:K});return Array.isArray(H.data)?H.data:[]};let J=[],q=null,Q=!1;try{J=await _()}catch(H){console.debug("Failed to list sessions for directory:",K,H),q=H,J=[]}if(J.length===0){Q=!0;try{const H=await o.session.list(void 0),W=Array.isArray(H.data)?H.data:[];J=u(W,Y,{includeDescendants:l,includeMissingDirectory:!1})}catch(H){throw console.debug("Failed to list sessions (global fallback):",H),q||H}}const z=u(J,Y,{includeDescendants:l,includeMissingDirectory:!Q});return $o("fetchSessionsForDirectory",{requestedDirectory:K,canonicalDirectory:Y,fetched:J.length,filtered:z.length}),m(z,K,Y)},p=It(s.currentDirectory??Fe.getDirectory()??null),h=n.projects.find(R=>R.id===n.activeProjectId)??null,x=It(h?.path??null),g=x??p??null,w=n.projects.length>0?n.projects:g?[{id:"legacy",path:g}]:[];if(w.length===0){t({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const y=await Promise.all(w.map(async R=>{const K=It(R.path);if(!K)return{projectId:R.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const Y=await Or(K).catch(()=>!1),_=await f(K||null);$o("projectSessions",{projectId:R.id,projectPath:K,isGitRepo:Y,parentSessions:_.length});const J=[];let q=[];const Q=new Set;if(Q.add(K),Y){const H=`${K}/${bi}`;try{const W=new Set;(await Fe.listLocalDirectory(K)).some(ae=>ae.isDirectory&&ae.name===bi)&&(await Fe.listLocalDirectory(H)).filter(O=>O.isDirectory).forEach(O=>{const X=/^([A-Za-z]:)?\//.test(O.path)?O.path:`${H}/${O.name}`,re=It(X)??X;W.add(re)});const L=await Un(K);Array.isArray(L)&&(q=L.map(ae=>Vn(K,ae)).filter(ae=>ae.path.includes(`/${bi}/`)),q.forEach(ae=>W.add(ae.path))),W.forEach(ae=>{const O=It(ae)??ae;Q.add(O)}),W.size>0&&(await Promise.allSettled(Array.from(W).map(O=>f(O)))).forEach(O=>{O.status==="fulfilled"&&Array.isArray(O.value)&&J.push(...O.value)})}catch{q=[]}}const z=Br([..._,...J]);return{projectId:R.id,projectPath:K,sessions:z,discoveredWorktrees:q,validPaths:Q}})),v=new Map;y.forEach(R=>{R.projectPath&&R.validPaths.forEach(K=>{const Y=It(K)??K,_=R.sessions.filter(J=>(It(J.directory??null)??Y)===Y);v.set(Y,Br(_))})});const S=Br(Array.from(v.values()).flat()),k=r();let b=k.worktreeMetadata;for(const R of y)if(R.projectPath)try{const K=await wb(R.sessions,R.projectPath,b);K&&(b=K)}catch(K){console.debug("Failed to refresh worktree metadata during session load:",K)}const N=new Map;y.forEach(R=>{R.projectPath&&N.set(R.projectPath,R.discoveredWorktrees)});const D=new Set;y.forEach(R=>{R.validPaths.forEach(K=>{const Y=It(K)??K;Y&&D.add(Y)})});const j=p??x??null,M=j&&D.has(j)?j:x??j,C=M?v.get(M)??[]:S,P=new Set(S.map(R=>R.id));for(const[R,K]of v.entries())yb(R,K.map(Y=>Y.id));const E=(M??null)!==(k.lastLoadedDirectory??null);let I=k.currentSessionId;if((!I||!P.has(I)||E)&&(I=C[0]?.id??S[0]?.id??null),M){const R=df(M);R&&P.has(R)&&(I=R)}const A=(()=>{if(!I)return M??null;const R=b.get(I)?.path;if(R)return It(R)??R;const K=Mn(S,I);return K||(M??null)})();try{Fe.setDirectory(A??void 0)}catch(R){console.warn("Failed to sync OpenCode directory after session load:",R)}const T=x?y.find(R=>R.projectPath===x)?.discoveredWorktrees??[]:[];t({sessions:S,sessionsByDirectory:v,currentSessionId:I,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:b,availableWorktrees:T,availableWorktreesByProject:N}),M&&kr(M,I),A&&A!==M&&kr(A,I)}catch(s){t({error:s instanceof Error?s.message:"Failed to load sessions",isLoading:!1})}},createSession:async(s,n,o)=>{t({error:null});const a=gt.getState(),l=It(a.currentDirectory),c=Xc(),d=c??It(n??Fe.getDirectory()??l);$o("createSession:start",{title:s,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:c});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(g=>g.id)),p={id:u,title:s||"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(t(g=>{const w=[p,...g.sessions],y=new Map(g.sessionsByDirectory);if(d){const v=y.get(d)??[];y.set(d,Br([p,...v]))}return{sessions:w,sessionsByDirectory:y,currentSessionId:u,webUICreatedSessions:new Set([...g.webUICreatedSessions,u]),isLoading:!1}}),d)try{Fe.setDirectory(d)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const h=g=>{const w=d??null,y=w?{...g,directory:w}:g;t(v=>{const S=v.sessions.map(b=>b.id===u?y:b),k=new Map(v.sessionsByDirectory);if(d){const N=(k.get(d)??[]).map(D=>D.id===u?y:D);k.set(d,Br(N))}return{sessions:S,sessionsByDirectory:er(S),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(b=>b!==u),y.id])}}),kr(d??null,y.id)},x=async()=>{const g=Fe.getApiClient(),w=20;for(let y=0;y<w;y+=1){try{const v=await g.session.list(d?{directory:d}:void 0),k=(Array.isArray(v.data)?v.data:[]).find(b=>!(f.has(b.id)||s&&b.title&&b.title!==s));if(k)return k}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,2e3))}return null};try{const g=()=>Fe.createSession({title:s,parentID:o??void 0});let w=null;try{w=d?await Fe.withDirectory(d,g):await g()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return w||(w=await x()),w?(h(w),w):(t(y=>({sessions:y.sessions.filter(v=>v.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(v=>v!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return t(w=>({sessions:w.sessions.filter(y=>y.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(w.webUICreatedSessions).filter(y=>y!==u)),isLoading:!1,error:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(s,n)=>{t({isLoading:!0,error:null});const o=r().worktreeMetadata.get(s),a=Mn(r().sessions,s),l=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await Yc(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Fe.deleteSession(s);if(!(l?await Fe.withDirectory(l,d):await d()))return t(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const x=new Map(p.worktreeMetadata);x.delete(s),h.worktreeMetadata=x}return h}),!1;let m=null;t(p=>{const h=p.sessions.filter(y=>y.id!==s);m=p.currentSessionId===s?null:p.currentSessionId;const x=new Map(p.worktreeMetadata);x.delete(s);const g=n?.archiveWorktree&&o?p.availableWorktrees.filter(y=>It(y.path)!==It(o.path)):p.availableWorktrees,w=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const y=It(o.projectDirectory)??o.projectDirectory,v=w.get(y)??[];w.set(y,v.filter(S=>It(S.path)!==It(o.path)))}return{sessions:h,sessionsByDirectory:er(h),currentSessionId:m,isLoading:!1,worktreeMetadata:x,availableWorktrees:g,availableWorktreesByProject:w}});const f=l??Fe.getDirectory()??null;return kr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return t(c?m=>{const f=new Map(m.worktreeMetadata);return f.delete(s),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(s,n)=>{const o=Array.from(new Set(s.filter(w=>typeof w=="string"&&w.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||t({isLoading:!0,error:null});const l=[],c=[],d=new Set,u=[],m=new Set;for(const w of o)try{const y=r().worktreeMetadata.get(w),v=Mn(r().sessions,w),S=y?.path??v;y&&n?.archiveWorktree&&!m.has(y.path)&&(await Yc(y,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(w),u.push({path:y.path,projectDirectory:y.projectDirectory}),m.add(y.path));const k=()=>Fe.deleteSession(w);(S?await Fe.withDirectory(S,k):await k())?(l.push(w),y?.path&&!u.some(N=>N.path===y.path)&&u.push({path:y.path,projectDirectory:y.projectDirectory})):c.push(w)}catch{c.push(w)}const f=gt.getState();u.forEach(({path:w,projectDirectory:y})=>{f.currentDirectory===w&&f.setDirectory(y,{showOverlay:!1})});const p=new Set(l),h=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let x=null;t(w=>{const y=w.sessions.filter(N=>!p.has(N.id));w.currentSessionId&&p.has(w.currentSessionId)?x=null:x=w.currentSessionId;const v=new Map(w.worktreeMetadata);for(const N of p)v.delete(N);for(const N of d)v.delete(N);const S=new Set(u.map(N=>It(N.path)).filter(N=>!!N)),k=S.size>0?w.availableWorktrees.filter(N=>!S.has(It(N.path)??N.path)):w.availableWorktrees,b=new Map(w.availableWorktreesByProject);return u.length>0&&u.reduce((D,j)=>{const M=It(j.projectDirectory)??j.projectDirectory,C=It(j.path)??j.path;return D.has(M)||D.set(M,new Set),D.get(M)?.add(C),D},new Map).forEach((D,j)=>{const C=(b.get(j)??[]).filter(P=>!D.has(It(P.path)??P.path));b.set(j,C)}),{sessions:y,sessionsByDirectory:er(y),currentSessionId:x,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:k,availableWorktreesByProject:b}});const g=Fe.getDirectory()??null;return kr(g,x),{deletedIds:l,failedIds:c}},updateSessionTitle:async(s,n)=>{try{const o=Mn(r().sessions,s),a=r().worktreeMetadata.get(s),l=()=>Fe.updateSession(s,n),c=a?.path??o,d=c?await Fe.withDirectory(c,l):await l();t(u=>{const m=u.sessions.map(f=>f.id===s?d:f);return{sessions:m,sessionsByDirectory:er(m)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async s=>{try{const n=Mn(r().sessions,s),o=Fe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Fe.getDirectory();return o.session.share({sessionID:s,...u?{directory:u}:{}})},d=l?await Fe.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:er(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async s=>{try{const n=Mn(r().sessions,s),o=Fe.getApiClient(),l=r().worktreeMetadata.get(s)?.path??n,c=async()=>{const u=n??Fe.getDirectory();return o.session.unshare({sessionID:s,...u?{directory:u}:{}})},d=l?await Fe.withDirectory(l,c):await c();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:er(m)}}),d.data):null}catch(n){return t({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:s=>{t({currentSessionId:s,error:null});const n=Fe.getDirectory()??null;kr(n,s)},clearError:()=>{t({error:null})},getSessionsByDirectory:s=>{const n=It(s)??s,{sessionsByDirectory:o,sessions:a}=r(),l=o.get(n);return l||a.filter(c=>(It(c.directory??null)??n)===n)},getDirectoryForSession:s=>{if(!s)return null;const n=r().worktreeMetadata.get(s);if(n?.path)return It(n.path)??n.path;const o=r().sessions.find(l=>l.id===s);return It(o?.directory??null)},applySessionMetadata:(s,n)=>{!s||!n||t(o=>{const a=o.sessions.findIndex(h=>h.id===s);if(a===-1)return o;const l=o.sessions[a],c=n.time?{...l.time,...n.time}:l.time,d=n.summary===void 0?l.summary:n.summary||void 0,u=n.share===void 0?l.share:n.share||void 0,m={...l,...n,time:c,summary:d,share:u},f=m.title!==l.title||m.parentID!==l.parentID||m.directory!==l.directory||m.version!==l.version||m.projectID!==l.projectID||JSON.stringify(m.time)!==JSON.stringify(l.time)||JSON.stringify(m.summary??null)!==JSON.stringify(l.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(l.share??null),p=[...o.sessions];return p[a]=f?m:l,{sessions:p,sessionsByDirectory:er(p)}})},isOpenChamberCreatedSession:s=>{const{webUICreatedSessions:n}=r();return n.has(s)},markSessionAsOpenChamberCreated:s=>{t(n=>{const o=new Set(n.webUICreatedSessions);return o.add(s),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:s=>{const{markSessionAsOpenChamberCreated:n}=r();n(s)},setWorktreeMetadata:(s,n)=>{s&&t(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(s,n):a.delete(s),{worktreeMetadata:a}})},getWorktreeMetadata:s=>{if(s)return r().worktreeMetadata.get(s)},setSessionDirectory:(s,n)=>{if(!s)return;const o=r().sessions,a=o.findIndex(u=>u.id===s);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(t(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:er(m)}}),c&&kr(c,null),n&&kr(n,s))},updateSession:s=>{t(n=>{const a=n.sessions.findIndex(c=>c.id===s.id)===-1?[s,...n.sessions]:n.sessions.map(c=>c.id===s.id?s:c),l=Br(a);return{sessions:l,sessionsByDirectory:er(l)}})},removeSessionFromStore:s=>{s&&t(n=>{const o=n.sessions.find(u=>u.id===s),a=It(o?.directory??null),l=n.sessions.filter(u=>u.id!==s);if(l.length===n.sessions.length)return n;const c=new Map(n.worktreeMetadata);c.delete(s);const d=n.currentSessionId===s?null:n.currentSessionId;return a&&kr(a,null),{sessions:l,sessionsByDirectory:er(l),currentSessionId:d,worktreeMetadata:c}})}}),{name:"session-store",storage:Gs(()=>ws()),partialize:t=>({currentSessionId:t.currentSessionId,sessions:t.sessions,lastLoadedDirectory:t.lastLoadedDirectory,webUICreatedSessions:Array.from(t.webUICreatedSessions),worktreeMetadata:Array.from(t.worktreeMetadata.entries()),availableWorktrees:t.availableWorktrees,availableWorktreesByProject:Array.from(t.availableWorktreesByProject.entries())}),merge:(t,r)=>{if(!(p=>typeof p=="object"&&p!==null)(t))return r;const n=Array.isArray(t.sessions)?t.sessions:r.sessions,o=typeof t.currentSessionId=="string"||t.currentSessionId===null?t.currentSessionId:r.currentSessionId,a=Array.isArray(t.webUICreatedSessions)?t.webUICreatedSessions:[],l=Array.isArray(t.worktreeMetadata)?t.worktreeMetadata:[],c=Array.isArray(t.availableWorktrees)?t.availableWorktrees:r.availableWorktrees,d=Array.isArray(t.availableWorktreesByProject)?t.availableWorktreesByProject:[],u=new Map(d),m=typeof t.lastLoadedDirectory=="string"?t.lastLoadedDirectory:r.lastLoadedDirectory??null,f=Br(n);return{...r,...t,sessions:f,sessionsByDirectory:er(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(l),availableWorktrees:c,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),uf="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.",vb="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: ",wi=t=>typeof t=="string"&&t.trim()===uf.trim(),vi=(t,r)=>{const s=Date.now(),n=t.get(r),o=new Map(t);return o.set(r,{phase:"streaming",startedAt:n?.startedAt??s,lastUpdateAt:s}),o},so=(t,r)=>{const s=Array.from(r);if(!s.some(a=>t.has(a)))return t;const o=new Map(t);return s.forEach(a=>{o.delete(a)}),o},Jc=new Map,mf=t=>{const r=Jc.get(t);r&&(clearTimeout(r),Jc.delete(t))},tn=t=>{for(const r of t)mf(r)},No=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>No(r)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(r=>No(r)).join("")}return""},ho=t=>{if(!t)return"";const r=t;if(typeof r.text=="string")return r.text;if(Array.isArray(r.text))return r.text.map(n=>typeof n=="string"?n:ho(n)).join("");const s=No(r.delta);return s||(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||No(o.delta)||""}return""}).join(""):"")},ro=(t,r)=>{const s={...t};if(s.type=s.type||"text",s.type==="text"){const n=r&&typeof r.text=="string"?r.text:"",o=typeof s.text=="string"?s.text:"",a=No(t.delta);o?s.text=o:a?s.text=n?`${n}${a}`:a:n?s.text=n:s.text="",delete s.delta}return s},Zc=50*1024*1024,jb=t=>{const r=(t||"").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"}},Sb=t=>{if(t.type&&t.type.trim().length>0)return t.type;const r=(t.name||"").toLowerCase(),s=r.includes(".")&&r.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(r))return"text/plain";switch(s){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"}},Nb=t=>{const r=t.replace(/\s+/g,"");if(!r)return 0;const s=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(r.length*3/4)-s},kb=t=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let s="";for(let n=0;n<t.length;n+=3){const o=t[n]??0,a=t[n+1],l=t[n+2],c=o<<16|(a??0)<<8|(l??0);s+=r[c>>18&63],s+=r[c>>12&63],s+=typeof a=="number"?r[c>>6&63]:"=",s+=typeof l=="number"?r[c&63]:"="}return s},lr=os()(us(Vs((t,r)=>({attachedFiles:[],addAttachedFile:async s=>{const{attachedFiles:n}=r();if(n.some(x=>x.filename===s.name&&x.size===s.size)){console.log(`File "${s.name}" is already attached`);return}const a=Zc;if(s.size>a)throw new Error(`File "${s.name}" is too large. Maximum size is 50MB.`);const l=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],c=Sb(s);!l.some(x=>c.startsWith(x)||c===x||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,m=await new Promise((x,g)=>{u.onload=()=>x(u.result),u.onerror=g,u.readAsDataURL(s)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${c}`):m,p=x=>{const g=x.replace(/\\/g,"/").split("/");return g[g.length-1]||x},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:s,dataUrl:f,mimeType:c,filename:p(s.name),size:s.size,source:"local"};t(x=>({attachedFiles:[...x.attachedFiles,h]}))},addServerFile:async(s,n,o)=>{const{attachedFiles:a}=r();if(a.some(y=>y.serverPath===s&&y.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,u;if(!c)try{const y=Fe.getApiClient(),v=s.lastIndexOf("/"),S=v>0?s.substring(0,v):"/",k=v>0?s.substring(v+1):s,b=await y.file.read({path:k,directory:S});b.data&&"content"in b.data?(c=b.data.content,d=b.data.encoding??void 0,u=b.data.mimeType??void 0):c=""}catch(y){console.error("Failed to read server file:",y),c=`[File: ${n}]`}const m=u||jb(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return kb(v)})(),h=d==="base64"?Nb(p):new TextEncoder().encode(c||"").length;if(h>Zc)throw new Error(`File "${n}" is too large. Maximum size is 50MB.`);const x=new File([],n,{type:f}),g=`data:${f};base64,${p}`,w={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:x,dataUrl:g,mimeType:f,filename:n,size:h,source:"server",serverPath:s};t(y=>({attachedFiles:[...y.attachedFiles,w]}))},removeAttachedFile:s=>{t(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==s)}))},clearAttachedFiles:()=>{t({attachedFiles:[]})}}),{name:"file-store",storage:Gs(()=>ws()),partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),Cb=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Mb=t=>t?Cb.has(t.toLowerCase()):!1,Db=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Ab=t=>{if(t)try{const r=Db();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===t)}catch{}},Eb=(t,r)=>{if(!t||t.length===0)return"ask";for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.permission===r&&n.pattern==="*")return n.action}for(let s=t.length-1;s>=0;s-=1){const n=t[s];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},fa=t=>{const r=Ab(t);return r?Eb(r.permission,"edit"):"ask"},ed=t=>{if(!t||typeof t!="object")return 0;const r=t.input??0,s=t.output??0,n=t.reasoning??0,o=t.cache&&typeof t.cache=="object"?t.cache.read??0:0,a=t.cache&&typeof t.cache=="object"?t.cache.write??0:0;return r+s+n+o+a},ji=t=>{const r=t.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return ed(r);const s=t.parts.find(n=>typeof n.tokens<"u");return!s||typeof s.tokens>"u"?0:typeof s.tokens=="number"?s.tokens:ed(s.tokens)},Si=(t,r,s)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(s)&&s>0,a=o?Math.max(s,0):0,l=Math.min(o?a:32e3,32e3),c=Math.min(l,n),d=n>0?Math.max(n-c,1):0,u=d>0?t/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},no=["ask","allow","full"],at=os()(us(Vs((t,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:(s,n,o)=>{t(a=>{const l=new Map(a.sessionModelSelections);return l.set(s,{providerId:n,modelId:o}),{sessionModelSelections:l}})},getSessionModelSelection:s=>{const{sessionModelSelections:n}=r();return n.get(s)||null},saveSessionAgentSelection:(s,n)=>{t(o=>{const a=new Map(o.sessionAgentSelections);return a.set(s,n),{sessionAgentSelections:a}})},getSessionAgentSelection:s=>{const{sessionAgentSelections:n}=r();return n.get(s)||null},saveAgentModelForSession:(s,n,o,a)=>{t(l=>{const c=new Map(l.sessionAgentModelSelections);let d=c.get(s);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(s,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(s,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(s);return a&&a.get(n)||null},saveAgentModelVariantForSession:(s,n,o,a,l)=>{t(c=>{const d=new Map(c.sessionAgentModelVariantSelections);let u=d.get(s);u?u=new Map(u):u=new Map;let m=u.get(n);m?m=new Map(m):m=new Map;const f=`${o}/${a}`;return l===void 0?(m.delete(f),m.size===0?(u.delete(n),u.size===0?d.delete(s):d.set(s,u)):(u.set(n,m),d.set(s,u))):(m.set(f,l),u.set(n,m),d.set(s,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(s,n,o,a)=>{const{sessionAgentModelVariantSelections:l}=r(),c=l.get(s);if(!c)return;const d=c.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(s,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:l}=r(),c=new Map,d=(x,g)=>{if("mode"in x&&x.mode&&typeof x.mode=="string"&&n.find(S=>S.name===x.mode))return x.mode;if(x.providerID&&x.modelID){const v=n.find(S=>S.model?.providerID===x.providerID&&S.model?.modelID===x.modelID);if(v)return v.name}const{currentAgentContext:w}=r(),y=w.get(s);if(y&&n.find(v=>v.name===y))return y;if(g>0&&x.providerID&&x.modelID){const S=(o.get(s)||[]).filter(k=>k.info.role==="assistant").sort((k,b)=>k.info.time.created-b.info.time.created);for(let k=g-1;k>=0;k--){const N=S[k].info;if(N.providerID===x.providerID&&N.modelID===x.modelID){if(N.mode&&typeof N.mode=="string"&&n.find(M=>M.name===N.mode))return N.mode;const D=n.find(j=>j.model?.providerID===N.providerID&&j.model?.modelID===N.modelID);if(D)return D.name}}}return x.providerID&&x.modelID&&n.find(S=>S.name==="build")?"build":null},u=o.get(s)||[],m=u.filter(x=>x.info.role==="assistant"||x.info.role==="user").sort((x,g)=>x.info.time.created-g.info.time.created),f=u.filter(x=>x.info.role==="assistant").sort((x,g)=>x.info.time.created-g.info.time.created);let p,h;for(let x=0;x<m.length;x++){const g=m[x],{info:w}=g,y=w;if(y.role==="user"){p=typeof y.variant=="string"&&y.variant.trim().length>0?y.variant:void 0,h=y.model?.providerID&&y.model?.modelID?{providerID:y.model.providerID,modelID:y.model.modelID}:void 0;continue}if(y.providerID&&y.modelID){const v=d(y,f.indexOf(g));if(v&&n.find(S=>S.name===v)){p&&h&&h.providerID===y.providerID&&h.modelID===y.modelID&&l(s,v,y.providerID,y.modelID,p);const S={providerId:y.providerID,modelId:y.modelID,timestamp:w.time.created},k=c.get(v);(!k||S.timestamp>k.timestamp)&&c.set(v,S)}}p=void 0,h=void 0}for(const[x,g]of c)a(s,x,g.providerId,g.modelId);return c},getContextUsage:(s,n,o,a)=>{if(!s)return null;const l=Si(0,n,o),c=l.contextLimit,d=l.normalizedOutput??0,u=l.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(s)||[]).filter(S=>S.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,x=S=>{const k=()=>{t(b=>{const N=b.sessionContextUsage.get(s);if(N&&N.totalTokens===S.totalTokens&&N.percentage===S.percentage&&N.contextLimit===S.contextLimit&&(N.outputLimit??0)===(S.outputLimit??0)&&(N.normalizedOutput??0)===(S.normalizedOutput??0)&&N.thresholdLimit===S.thresholdLimit&&N.lastMessageId===S.lastMessageId)return b;const D=new Map(b.sessionContextUsage);return D.set(s,S),{sessionContextUsage:D}})};typeof queueMicrotask=="function"?queueMicrotask(k):typeof window<"u"?window.setTimeout(k,0):setTimeout(k,0)},g=r().sessionContextUsage.get(s);if(g&&g.lastMessageId===h){const S=g.normalizedOutput??g.outputLimit??0,k=g.contextLimit!==c||S!==d||g.thresholdLimit!==u;if(k&&g.totalTokens>0){const b=g.totalTokens/u*100,N={totalTokens:g.totalTokens,percentage:Math.min(b,100),contextLimit:c,outputLimit:l.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return x(N),N}if(!k&&g.totalTokens>0)return g}const w=ji(p);if(w===0)return g||null;const y=Si(w,n,o),v={totalTokens:w,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit,normalizedOutput:y.normalizedOutput,thresholdLimit:y.thresholdLimit,lastMessageId:h};return x(v),v},updateSessionContextUsage:(s,n,o,a)=>{const c=(a.get(s)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=ji(d);if(u===0)return;const m=Si(u,n,o);t(f=>{const p=new Map(f.sessionContextUsage);return p.set(s,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(s,n,o,a)=>{const c=r().sessionContextUsage.get(s);(!c||c.totalTokens===0)&&r().updateSessionContextUsage(s,n,o,a)},pollForTokenUpdates:(s,n,o,a=10)=>{let l=0;const c=()=>{l++;const u=(o.get(s)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&ji(u)>0){r().updateSessionContextUsage(s,0,0,o);return}l<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:s=>{const{currentAgentContext:n}=r();return n.get(s)},getSessionAgentEditMode:(s,n,o=fa(n))=>!s||!n?o:r().sessionAgentEditModes.get(s)?.get(n)??o,setSessionAgentEditMode:(s,n,o,a=fa(n))=>{if(!s||!n)return;const l=a??"ask";l==="deny"||o==="deny"||no.includes(o)&&t(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(s)??new Map);return o===l?(u.delete(n),u.size===0?d.delete(s):d.set(s,u)):(u.set(n,o),d.set(s,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(s,n,o=fa(n))=>{if(!s||!n)return;const a=o??"ask";if(a==="deny")return;const l=r().getSessionAgentEditMode(s,n,a),c=no.indexOf(l),d=no.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%no.length,f=no[m];r().setSessionAgentEditMode(s,n,f,a)}}),{name:"context-store",storage:Gs(()=>ws()),partialize:t=>({sessionModelSelections:Array.from(t.sessionModelSelections.entries()),sessionAgentSelections:Array.from(t.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(t.sessionAgentModelSelections.entries()).map(([r,s])=>[r,Array.from(s.entries())]),sessionAgentModelVariantSelections:Array.from(t.sessionAgentModelVariantSelections.entries()).map(([r,s])=>[r,Array.from(s.entries()).map(([n,o])=>[n,Array.from(o.entries())])]),currentAgentContext:Array.from(t.currentAgentContext.entries()),sessionContextUsage:Array.from(t.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(t.sessionAgentEditModes.entries()).map(([r,s])=>[r,Array.from(s.entries())])}),merge:(t,r)=>{const s=new Map;t?.sessionAgentModelSelections&&t.sessionAgentModelSelections.forEach(([a,l])=>{s.set(a,new Map(l))});const n=new Map;t?.sessionAgentModelVariantSelections&&t.sessionAgentModelVariantSelections.forEach(([a,l])=>{const c=new Map;l.forEach(([d,u])=>{c.set(d,new Map(u))}),n.set(a,c)});const o=new Map;return t?.sessionAgentEditModes&&t.sessionAgentEditModes.forEach(([a,l])=>{o.set(a,new Map(l))}),{...r,...t,sessionModelSelections:new Map(t?.sessionModelSelections||[]),sessionAgentSelections:new Map(t?.sessionAgentSelections||[]),sessionAgentModelSelections:s,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(t?.currentAgentContext||[]),sessionContextUsage:new Map(t?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),td=(t,r)=>{const s=new Map(t);return s.delete(r),s};let Ni=[],ki=null;const Ib=50,Pb=3e4,sn=new Map,Bo=new Map,Dn=new Map,Tb=10,Aa=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.indexOf("_"),n=s>=0?r.slice(s+1):r;return!n||n.length<Tb?null:n},zo=(t,r)=>{const s=Aa(t),n=Aa(r);return!s||!n||s.length!==n.length?!0:s>n},Fb=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Rn=t=>!Array.isArray(t)||t.length===0?0:t.reduce((r,s)=>{if(!s||s.type!=="text")return r;const n=s.text??s.content;return typeof n=="string"?r+n.length:r},0),Ea=t=>t?.finish==="stop",sd=t=>{if(t){if(typeof t.id=="string"&&t.id.length>0)return t.id;if(t.type){const r=t.reason,s=t.callID;return`${t.type}-${r??""}-${s??""}`}}},rd=new Set,Ia=(t=[],r=[])=>{if(!r.length)return[...t];const s=[...t],n=new Set(t.map(sd).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=sd(o);a&&n.has(a)||(s.push(o),a&&n.add(a))}),s},Rb=(t,r)=>{const s=Array.isArray(t.parts)?t.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=Rn(s),a=Rn(n),l=Ea(t.info),c=Ea(r.info);let d=n;return l&&o>=a?d=Ia(s,n):c&&a>=o?d=Ia(n,s):o>=a&&(d=s),{...r,info:{...t.info,...r.info},parts:d}},Ho=t=>{const r=[],s=new Map;for(const n of t){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){r.push(n);continue}const a=s.get(o);if(a===void 0){s.set(o,r.length),r.push(n);continue}r[a]=Rb(r[a],n)}return r},Lb=(t,r)=>{let s=r,n=r?Aa(r):null;for(const o of t){const a=o?.info?.id,l=Aa(a);!a||!l||(!n||l>n)&&(n=l,s=a)}return s},mr=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return s?o.set(r,s):o.delete(r),o},An=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return o.set(r,s),o},Wo=(t,r)=>{const s=new Map(t);let n=!1;for(const o of r)s.delete(o)&&(n=!0);return n?s:t},Ob=(t,r)=>{const s=new Set,n=t.streamingMessageIds.get(r);return n&&s.add(n),t.messageStreamStates.forEach((o,a)=>{t.messageSessionIndex.get(a)===r&&s.add(a)}),s},nd=(t,r,s)=>t.streamingMessageIds.get(r)===s?!0:t.messageSessionIndex.get(s)===r&&t.messageStreamStates.has(s),_b=async t=>{if(t)try{return pt.getState().getDirectoryForSession(t)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},od=t=>{if(!t)return null;try{return pt.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},ad=(t,r)=>{if(!r)return t;const s=t.findIndex(n=>n.info.id===r);return s===-1?t:t.slice(0,s)},Ci=async(t,r)=>{const s=await _b(t);return s?Fe.withDirectory(s,r):r()},kt=os()(us(Vs((t,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(s,n)=>{const o=Da(),a=n===1/0,l=a?1/0:n??o.HISTORICAL_MESSAGES,c=r().sessionMemoryState.get(s)?.isStreaming,d=c?o.VIEWPORT_MESSAGES:l,u=c||a?void 0:d+o.FETCH_BUFFER,m=await Ci(s,()=>Fe.getSessionMessages(s,u)),f=od(s),p=ad(m,f),h=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,g=(h?p.filter(w=>{const y=w?.info?.id;return y?zo(y,h):!0}):p).slice(-d);t(w=>{const y=new Map(w.messages),v=w.messages.get(s)||[],S=new Map(v.filter(T=>typeof T.info?.id=="string").map(T=>[T.info.id,T])),k=g.map(T=>{const R={...T.info,clientRole:T.info?.clientRole??T.info.role,userMessageMarker:T.info.role==="user"?!0:T.info?.userMessageMarker},K=(Array.isArray(T.parts)?T.parts:[]).map(_=>{if(_?.type==="text"){const J=_.text??_.content??"";if(wi(J))return{..._,synthetic:!0}}return _}),Y=R?.id?S.get(R.id):void 0;if(Y&&Y.info.role==="assistant"){const _=Array.isArray(Y.parts)?Y.parts:[],J=Rn(_),q=Rn(K);if(Ea(Y.info)&&J>q){const z=Ia(_,K);return{...T,info:R,parts:z}}}return{...T,info:R,parts:K}}),b=Ho(k),N=new Set(v.map(T=>T.info.id)),D=new Set(b.map(T=>T.info.id)),j=[];N.forEach(T=>{D.has(T)||j.push(T)}),y.set(s,b);const M=new Map(w.sessionMemoryState),C=w.sessionMemoryState.get(s);M.set(s,{...C,viewportAnchor:b.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:m.length,hasMoreAbove:m.length>g.length,trimmedHeadMaxId:C?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const P={messages:y,sessionMemoryState:M};tn(j);const E=so(w.messageStreamStates,j);if(E!==w.messageStreamStates&&(P.messageStreamStates=E),j.length>0){const T=w.streamingMessageIds.get(s);T&&j.includes(T)&&(P.streamingMessageIds=mr(P.streamingMessageIds??w.streamingMessageIds,s,null))}if(j.length>0){const T=Wo(P.messageSessionIndex??w.messageSessionIndex,j);T!==(P.messageSessionIndex??w.messageSessionIndex)&&(P.messageSessionIndex=T)}if(j.length>0){const T=new Map(w.pendingAssistantParts);let R=!1;j.forEach(K=>{T.delete(K)&&(R=!0)}),R&&(P.pendingAssistantParts=T)}const I=P.messageSessionIndex??w.messageSessionIndex;let A=I;return b.forEach(T=>{const R=T?.info?.id;typeof R=="string"&&R.length>0&&(A=An(A,R,s))}),A!==I&&(P.messageSessionIndex=A),P})},sendMessage:async(s,n,o,a,l,c,d,u,m)=>{if(!l)throw new Error("No session selected");const f=l;r().sessionAbortFlags.has(f)&&t(p=>{const h=new Map(p.sessionAbortFlags);return h.delete(f),{sessionAbortFlags:h}}),await Ci(f,async()=>{try{let p=s;if(s.startsWith("/")){const x=s.indexOf(" "),g=x===-1?s.substring(1):s.substring(1,x),w=x===-1?"":s.substring(x+1).trim(),y=Fe.getApiClient(),v=Fe.getDirectory();if(g==="init"){const S=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:f,...v?{directory:v}:{},messageID:S,providerID:n,modelID:o});return}if(g==="summarize"){await y.session.summarize({sessionID:f,...v?{directory:v}:{},providerID:n,modelID:o});return}try{const S=await Fe.getCommandDetails(g);S?.template?p=S.template.replace(/\$ARGUMENTS/g,w):p=s}catch(S){console.error("Command template resolution failed:",S),p=s}}t({lastUsedProvider:{providerID:n,modelID:o}}),t(x=>{const g=x.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},w=Dn.get(f);w&&(clearTimeout(w),Dn.delete(f));const y=new Map(x.sessionMemoryState);return y.set(f,{...g,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:y}});try{const x=new AbortController;t(y=>{const v=new Map(y.abortControllers);return v.set(f,x),{abortControllers:v}});const g=(c??[]).map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}));t(y=>{const v=new Set(y.pendingAssistantHeaderSessions);v.add(f);const S=new Map(y.pendingUserMessageMetaBySession);return S.set(f,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o,variant:typeof m=="string"&&m.trim().length>0?m:void 0}),{pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:S}});const w=u?.map(y=>({text:y.text,files:y.attachments?.map(v=>({type:"file",mime:v.mimeType,filename:v.filename,url:v.dataUrl}))}));if(await Fe.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:g.length>0?g:void 0,additionalParts:w,agentMentions:d?[{name:d}]:void 0}),g.length>0)try{lr.getState().clearAttachedFiles()}catch(y){console.error("Failed to clear attached files after send",y)}t(y=>{const v=new Map(y.abortControllers);return v.delete(f),{abortControllers:v}})}catch(x){let g="Network error while sending message. The message may still be processing.";if(x.name==="AbortError")g="Request timed out. The message may still be processing.";else if(x.message?.includes("504")||x.message?.includes("Gateway")){g="Gateway timeout - your message is being processed. Please wait for response.",t(w=>{const y=new Map(w.abortControllers);return y.delete(f),{abortControllers:y}});return}else x.message&&(g=x.message);throw t(w=>{const y=new Map(w.abortControllers);y.delete(f);const v=new Set(w.pendingAssistantHeaderSessions);v.delete(f);const S=new Map(w.pendingUserMessageMetaBySession);return S.delete(f),{abortControllers:y,pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:S}}),new Error(g)}}catch(p){let h="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?h="Request timed out. The message may still be processing.":p.response?.status===401?h="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?h="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?h="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(h=p.message),t(x=>{const g=new Map(x.abortControllers);g.delete(f);const w=new Set(x.pendingAssistantHeaderSessions);w.delete(f);const y=new Map(x.pendingUserMessageMetaBySession);return y.delete(f),{abortControllers:g,pendingAssistantHeaderSessions:w,pendingUserMessageMetaBySession:y}}),new Error(h)}})},abortCurrentOperation:async s=>{if(!s)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(s)?.abort();const c=Ob(n,s);if(c.size===0){const u=s?a.get(s)??[]:[];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(x=>x.type==="reasoning"||x.type==="tool"||x.type==="step-start")){c.add(p.info.id);break}}c.size===0&&m&&c.add(m)}for(const u of c){const m=sn.get(u);m&&(clearTimeout(m),sn.delete(u),Bo.delete(u))}c.size>0&&tn(c);const d=Date.now();t(u=>{const m=so(u.messageStreamStates,c),f=u.messages.get(s)??[];let p=!1,h=u.messages;if(f.length>0&&c.size>0){const y=f.map(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const S=(v.parts??[]).map(k=>{if(k.type==="reasoning"){const b=k,N={...b.time??{}};return typeof N.end!="number"&&(N.end=d),{...b,time:N}}if(k.type==="tool"){const b=k,N={...b.state??{}};return(N.status==="running"||N.status==="pending")&&(N.status="aborted"),{...b,state:N}}return k.type==="step-start"?{...k,type:"step-finish",aborted:!0}:k});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(s,y))}const x=u.sessionMemoryState.get(s);let g=u.sessionMemoryState;if(x){const y=new Map(u.sessionMemoryState);y.set(s,{...x,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),g=y}const w=new Map(u.sessionAbortFlags);return w.set(s,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:g,sessionAbortFlags:w,abortControllers:(()=>{const y=new Map(u.abortControllers);return y.delete(s),y})(),streamingMessageIds:mr(u.streamingMessageIds,s,null),...p?{messages:h}:{}}}),Fe.abortSession(s).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(s,n,o,a,l)=>{const c=r();if(rd.has(n))return;const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!zo(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.messages.get(s)||[],m=u.find(h=>h.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=r().sessionMemoryState.get(s);if(p?.streamStartTime&&Date.now()-p.streamStartTime>Mr.ZOMBIE_TIMEOUT){p.isZombie||t(x=>{const g=new Map(x.sessionMemoryState);return g.set(s,{...p,isZombie:!0}),{sessionMemoryState:g}}),setTimeout(()=>{r().completeStreamingMessage(s,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}t(h=>{const g=[...h.messages.get(s)||[]],w={},y=An(h.messageSessionIndex,n,s);y!==h.messageSessionIndex&&(w.messageSessionIndex=y);const v=M=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(s)))return M;const P=new Map(h.sessionAbortFlags);return P.delete(s),{...M,sessionAbortFlags:P}},S=M=>{const C=M||"",P=Bo.get(n);if(C&&P===C){const A=r();if(nd(A,s,n)){const T=sn.get(n);T&&(clearTimeout(T),sn.delete(n)),setTimeout(()=>{const R=r();typeof R.forceCompleteMessage=="function"&&R.forceCompleteMessage(s,n,"timeout"),R.completeStreamingMessage(s,n)},100)}}Bo.set(n,C);const E=sn.get(n);E&&clearTimeout(E);const I=setTimeout(()=>{const A=r();typeof A.forceCompleteMessage=="function"&&A.forceCompleteMessage(s,n,"timeout"),nd(A,s,n)&&A.completeStreamingMessage(s,n),sn.delete(n),Bo.delete(n)},8e3);sn.set(n,I)},k=s!==l,b=h.sessionMemoryState.get(s);if(k&&b?.isStreaming){g.length>=Mr.BACKGROUND_STREAMING_BUFFER&&g.shift();const M=new Map(h.sessionMemoryState);M.set(s,{...b,backgroundMessageCount:(b.backgroundMessageCount||0)+1}),h.sessionMemoryState=M}if(f==="assistant"){const M=h.sessionMemoryState.get(s);if(M){const C=Date.now(),P=new Map(h.sessionMemoryState);P.set(s,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??C,lastAccessedAt:C,isZombie:!1}),h.sessionMemoryState=P}}const N=ho(o);if(wi(N)&&(o.synthetic=!0),Fb()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:N.length,snapshotParts:u.length})}catch{}const D=w.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=mr(D,s,n);M!==D&&(w.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const j=g.findIndex(M=>M.info.id===n);if(j!==-1&&f==="user"){const M=g[j],C=M.parts.findIndex(T=>T.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const P=ro(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`user_part_type:${P.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((T,R)=>R===C?P:T):E.parts=[...E.parts,P];const I=[...g];I[j]=E;const A=new Map(h.messages);return A.set(s,I),v({messages:A})}if(f==="assistant"&&j!==-1){const M=g[j],C=M.parts.findIndex(R=>R.id===o.id),P=ro(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${P.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((R,K)=>K===C?P:R):E.parts=[...E.parts,P];const I=[...g];I[j]=E;const A=new Map(h.messages);A.set(s,I),w.messageStreamStates=vi(h.messageStreamStates,n);const T=mr(w.streamingMessageIds??h.streamingMessageIds,s,n);return T!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set")),P.type==="text"?S(P.text||""):S(""),v({messages:A,...w})}if(j===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const B=ro(o);window.__messageTracker?.(n,`new_user_part_type:${B.type||"unknown"}`);const se=h.pendingUserMessageMetaBySession.get(s),L=at.getState(),ae=se?.mode??L.getSessionAgentSelection(s)??L.getCurrentAgent(s),O=typeof ae=="string"&&ae.trim().length>0?ae.trim():void 0,V=se?.providerID??(h.lastUsedProvider?.providerID||void 0),X=se?.modelID??(h.lastUsedProvider?.modelID||void 0);se&&(w.pendingUserMessageMetaBySession=td(h.pendingUserMessageMetaBySession,s));const re={info:{id:n,sessionID:s,role:"user",clientRole:"user",userMessageMarker:!0,...O?{mode:O}:{},...V?{providerID:V}:{},...X?{modelID:X}:{},time:{created:Date.now()}},parts:[B]},me=[...g,re];me.sort((he,ye)=>{const ge=he.info?.time?.created||0,$e=ye.info?.time?.created||0;return ge-$e});const G=new Map(h.messages);return G.set(s,me),v({messages:G})}if(o?.type==="text"){const B=ho(o).trim();if(B.length>0){const se=[...g].reverse().find(L=>L.info.role==="user");if(se){const L=se.parts.map(ae=>ho(ae)).join("").trim();if(L.length>0&&L===B)return rd.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=ro(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?S(M.text||""):S("");const C=h.pendingAssistantParts.get(n),P=C?[...C.parts]:[],E=P.findIndex(B=>B.id===M.id);E!==-1?P[E]=M:P.push(M);const I=new Map(h.pendingAssistantParts);I.set(n,{sessionId:s,parts:P});const A=h.lastUsedProvider?.providerID||"",T=h.lastUsedProvider?.modelID||"",R=Date.now(),K=Fe.getDirectory()??"/",Y=at.getState(),_=Y.getSessionAgentSelection(s)??Y.getCurrentAgent(s),J=typeof _=="string"&&_.trim().length>0?_.trim():void 0,q=h.pendingAssistantHeaderSessions.has(s);if(q){const B=new Set(h.pendingAssistantHeaderSessions);B.delete(s),w.pendingAssistantHeaderSessions=B}const z={info:f==="user"?{id:n,sessionID:s,role:"user",time:{created:R},agent:J||"default",model:{providerID:A,modelID:T},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:s,role:"assistant",time:{created:R},parentID:n,modelID:T,providerID:A,mode:J||"default",...q?{openchamberHeaderAnchor:!0}:{},path:{cwd:K,root:K},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:P},H=[...g,z],W=new Map(h.messages);if(W.set(s,H),f==="assistant"){w.messageStreamStates=vi(h.messageStreamStates,n);const B=mr(w.streamingMessageIds??h.streamingMessageIds,s,n);B!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=B,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:W,pendingAssistantParts:I,...w})}else{const M=g[j],C=M.parts.findIndex(T=>T.id===o.id),P=ro(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${P.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((T,R)=>R===C?P:T):E.parts=[...E.parts,P];const I=[...g];I[j]=E;const A=new Map(h.messages);if(A.set(s,I),E.info.role==="assistant"){w.messageStreamStates=vi(h.messageStreamStates,n);const T=mr(w.streamingMessageIds??h.streamingMessageIds,s,n);T!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set"))}return P.type==="text"?S(P.text||""):S(""),v({messages:A,...w})}})},addStreamingPart:(s,n,o,a,l)=>{if(a!=="user"){r()._addStreamingPartImmediate(s,n,o,a,l);return}Ni.push({sessionId:s,messageId:n,part:o,role:a,currentSessionId:l}),ki||(ki=setTimeout(()=>{const c=[...Ni];Ni=[],ki=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Ib))},forceCompleteMessage:(s,n,o="timeout")=>{const a=l=>{if(s)return s;for(const[c,d]of l.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};t(l=>{const c=a(l);if(!c)return l;const d=l.messages.get(c)??[],u=d.findIndex(b=>b.info.id===n);if(u===-1)return l;const m=d[u];if(!m)return l;const f=Date.now(),p=m.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let x=!1;const g={...p};h||(g.time={...p.time??{},completed:f},x=!0),g.status!=="completed"&&(g.status="completed",x=!0),g.streaming&&(g.streaming=!1,x=!0);let w=!1;const y=m.parts.map(b=>{if(!b)return b;if(b.type==="tool"){const N=b.state;if(!N)return b;const D=N.status,j=D==="running"||D==="pending"||D==="started",M=!N.time||typeof N.time?.end!="number";if(j||M){const C={...N};return j&&(C.status="completed"),M&&(C.time={...N.time??{},end:f}),w=!0,{...b,state:C}}return b}if(b.type==="reasoning"){const N=b.time;return!N||typeof N.end!="number"?(w=!0,{...b,time:{...N??{},end:f}}):b}if(b.type==="text"){const N=b.time;return N&&typeof N.end!="number"?(w=!0,{...b,time:{...N,end:f}}):b}return b});if(!x&&!w)return l;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:g,parts:w?y:m.parts},S=[...d];S[u]=v;const k=new Map(l.messages);return k.set(c,S),{messages:k}})},markMessageStreamSettled:s=>{t(n=>{mf(s);const o=new Map(n.messageStreamStates);o.delete(s);let a=n.messages,l=!1;return n.messages.forEach((d,u)=>{if(l)return;const m=d.findIndex(g=>g.info.id===s);if(m===-1)return;const f=d[m];if(f.info?.animationSettled)return;const p={...f,info:{...f.info,animationSettled:!0}},h=[...d];h[m]=p;const x=new Map(n.messages);x.set(u,h),a=x,l=!0}),{messageStreamStates:o,...l?{messages:a}:{}}}),tn([s])},updateMessageInfo:(s,n,o)=>{t(c=>{const d=c.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!zo(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(s)??[]],f=m.findIndex(j=>j.info.id===n),p=c.pendingAssistantParts.get(n),h=(j=[],M=[])=>{if(!M.length)return j;const C=[...j];return M.forEach(P=>{const E=C.findIndex(I=>I.id===P.id);E===-1?C.push(P):C[E]=P}),C},x=j=>{if(!j)return j;const M=j.clientRole??j.role,C=M==="user"?!0:j.userMessageMarker;return{...j,clientRole:M,...C?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:s,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const K=m[0]?.info,Y=typeof K?.time?.created=="number"?K.time.created:null,_=typeof K?.id=="string"?K.id:null,J=o,q=typeof J?.time?.created=="number"?J.time.created:null,Q=typeof J?.id=="string"?J.id:n;let z=!1;if(q!==null&&Y!==null&&(z=q<Y),!z&&Q&&_&&(z=Q.localeCompare(_)<0),z)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const j=x(o);if(j&&j.role==="user"){const R=p?.parts??[],K=c.pendingUserMessageMetaBySession.get(s),Y={info:{...j,userMessageMarker:!0,clientRole:"user",...K?.mode?{mode:K.mode}:{},...K?.providerID?{providerID:K.providerID}:{},...K?.modelID?{modelID:K.modelID}:{}},parts:R.length>0?[...R]:[]},_=new Map(c.messages),J=[...m,Y];J.sort((z,H)=>{const W=z.info?.time?.created||0,B=H.info?.time?.created||0;return W-B}),_.set(s,J);const q={messages:_,...K?{pendingUserMessageMetaBySession:td(c.pendingUserMessageMetaBySession,s)}:{}},Q=An(q.messageSessionIndex??c.messageSessionIndex,n,s);if(Q!==(q.messageSessionIndex??c.messageSessionIndex)&&(q.messageSessionIndex=Q),p){const z=new Map(c.pendingAssistantParts);z.delete(n),q.pendingAssistantParts=z}return q}if(!j||j.role!=="assistant")return c;const M=p?.parts??[],C=c.pendingAssistantHeaderSessions.has(s),P={info:{...j,animationSettled:j?.animationSettled??!1,...C?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},E=new Map(c.messages),I=[...m,P];E.set(s,I);const A={messages:E,...C?{pendingAssistantHeaderSessions:(()=>{const R=new Set(c.pendingAssistantHeaderSessions);return R.delete(s),R})()}:{}},T=An(A.messageSessionIndex??c.messageSessionIndex,n,s);if(T!==(A.messageSessionIndex??c.messageSessionIndex)&&(A.messageSessionIndex=T),p){const R=new Map(c.pendingAssistantParts);R.delete(n),A.pendingAssistantParts=R}return A}const g=m[f],w=g.info;if(w.userMessageMarker===!0||w.clientRole==="user"||w.role==="user"){const j={...g.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:w.providerID||void 0,modelID:w.modelID||void 0},M=c.pendingUserMessageMetaBySession.get(s);M&&!j.mode&&M.mode&&(j.mode=M.mode);const C={...g,info:j},P=new Map(c.messages),E=[...m];if(E[f]=C,P.set(s,E),M){const I=new Map(c.pendingUserMessageMetaBySession);return I.delete(s),{messages:P,pendingUserMessageMetaBySession:I}}return{messages:P}}const v={...g.info,...o};o.role&&o.role!==g.info.role&&(v.role=g.info.role),v.clientRole=v.clientRole??g.info.clientRole??g.info.role,v.clientRole==="user"&&(v.userMessageMarker=!0);const S=p?.parts?h(g.parts,p.parts):g.parts,k={...g,info:v,parts:S},b=new Map(c.messages),N=[...m];N[f]=k,b.set(s,N);const D={messages:b};if(p){const j=new Map(c.pendingAssistantParts);j.delete(n),D.pendingAssistantParts=j}return D});const a=o?.finish,l=o?.role;typeof a=="string"&&l!=="user"&&setTimeout(()=>{r().completeStreamingMessage(s,n)},0)},completeStreamingMessage:(s,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(s)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(s,n,"cooldown");const a=o.streamingMessageIds.get(s)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const l={};if(a&&(l.streamingMessageIds=mr(o.streamingMessageIds,s,null),l.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(s),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),l.messageStreamStates=d}Object.keys(l).length>0&&t(l),o.pendingAssistantParts.has(n)&&t(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),tn([n]);let c=!1;if(t(d=>{const u=d.sessionMemoryState.get(s);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(s,p),c=!0,{sessionMemoryState:m}}),c){const d=Dn.get(s);d&&(clearTimeout(d),Dn.delete(s));const u=setTimeout(()=>{t(m=>{const f=m.sessionMemoryState.get(s);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:h,...x}=f;return p.set(s,x),{sessionMemoryState:p}}),Dn.delete(s)},2e3);Dn.set(s,u)}},syncMessages:(s,n)=>{const o=od(s),a=ad(n,o),l=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,c=l?a.filter(d=>{const u=d?.info?.id;return u?zo(u,l):!0}):a;t(d=>{const u=new Map(d.messages),m=d.messages.get(s)||[],f=new Map(m.filter(b=>typeof b.info?.id=="string").map(b=>[b.info.id,b])),p=c.map(b=>{const N={...b.info,clientRole:b.info?.clientRole??b.info.role,userMessageMarker:b.info.role==="user"?!0:b.info?.userMessageMarker,animationSettled:b.info.role==="assistant"?b.info?.animationSettled??!0:b.info?.animationSettled},D=(Array.isArray(b.parts)?b.parts:[]).map(C=>{if(C?.type==="text"){const P=C.text??C.content??"";if(wi(P))return{...C,synthetic:!0}}return C}),j=typeof N?.id=="string"?N.id:void 0,M=j?f.get(j):void 0;if(M&&M.info.role==="assistant"){const C=Array.isArray(M.parts)?M.parts:[],P=Rn(C),E=Rn(D);if(Ea(M.info)&&P>E){const A=Ia(C,D);return{...b,info:N,parts:A}}}return{...b,info:N,parts:D}}),h=Ho(p),x=new Set(m.map(b=>b.info.id)),g=new Set(h.map(b=>b.info.id)),w=[];x.forEach(b=>{g.has(b)||w.push(b)}),u.set(s,h);const y={messages:u,isSyncing:!0};tn(w);const v=so(d.messageStreamStates,w);if(v!==d.messageStreamStates&&(y.messageStreamStates=v),w.length>0){const b=d.streamingMessageIds.get(s);b&&w.includes(b)&&(y.streamingMessageIds=mr(y.streamingMessageIds??d.streamingMessageIds,s,null))}if(w.length>0){const b=Wo(y.messageSessionIndex??d.messageSessionIndex,w);b!==(y.messageSessionIndex??d.messageSessionIndex)&&(y.messageSessionIndex=b)}if(w.length>0){const b=new Map(d.pendingAssistantParts);let N=!1;w.forEach(D=>{b.delete(D)&&(N=!0)}),N&&(y.pendingAssistantParts=b)}const S=y.messageSessionIndex??d.messageSessionIndex;let k=S;return h.forEach(b=>{const N=b?.info?.id;typeof N=="string"&&N.length>0&&(k=An(k,N,s))}),k!==S&&(y.messageSessionIndex=k),y}),setTimeout(()=>{t({isSyncing:!1})},100)},updateSessionCompaction:(s,n)=>{t(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(s)?(a.delete(s),{sessionCompactionUntil:a}):o;const l=n+Pb;return a.get(s)===l?o:(a.set(s,l),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:s=>{s&&t(n=>{const o=n.sessionAbortFlags.get(s);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(s,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(s,n)=>{t(o=>{const a=o.sessionMemoryState.get(s)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(o.sessionMemoryState);return l.set(s,{...a,viewportAnchor:n}),{sessionMemoryState:l}})},trimToViewportWindow:(s,n,o)=>{const a=n??Da().VIEWPORT_MESSAGES,l=r(),c=l.messages.get(s);if(!c||c.length<=a)return;const d=l.sessionMemoryState.get(s)||{viewportAnchor:c.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(d.isStreaming&&s===o)return;const u=d.viewportAnchor||c.length-1;let m=Math.max(0,u-Math.floor(a/2));const f=Math.min(c.length,m+a);f===c.length&&f-m<a&&(m=Math.max(0,f-a));const p=c.slice(m,f),h=c.slice(0,m),x=new Set(p.map(w=>w.info.id)),g=c.filter(w=>!x.has(w.info.id)).map(w=>w.info.id);t(w=>{const y=new Map(w.messages);y.set(s,p);const v=new Map(w.sessionMemoryState),S={...d,viewportAnchor:u-m,trimmedHeadMaxId:Lb(h,d.trimmedHeadMaxId)};v.set(s,S);const k={messages:y,sessionMemoryState:v};tn(g);const b=so(w.messageStreamStates,g);if(b!==w.messageStreamStates&&(k.messageStreamStates=b),g.length>0){const j=w.streamingMessageIds.get(s);j&&g.includes(j)&&(k.streamingMessageIds=mr(k.streamingMessageIds??w.streamingMessageIds,s,null))}if(g.length>0){const j=Wo(k.messageSessionIndex??w.messageSessionIndex,g);j!==(k.messageSessionIndex??w.messageSessionIndex)&&(k.messageSessionIndex=j)}const N=k.messageSessionIndex??w.messageSessionIndex;let D=N;return p.forEach(j=>{const M=j?.info?.id;typeof M=="string"&&M.length>0&&(D=An(D,M,s))}),D!==N&&(k.messageSessionIndex=D),k})},evictLeastRecentlyUsed:s=>{const n=r();if(n.messages.size<=Mr.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const l=a.filter(([d,u])=>d!==s&&!u.isStreaming);if(l.length===0)return;l.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=l[0][0];t(d=>{const m=(d.messages.get(c)||[]).map(k=>k.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c);const h={messages:f,sessionMemoryState:p},x=new Map(d.pendingAssistantParts);let g=!1;x.forEach((k,b)=>{k.sessionId===c&&(x.delete(b),g=!0)}),g&&(h.pendingAssistantParts=x);const w=new Map(d.sessionCompactionUntil);w.delete(c)&&(h.sessionCompactionUntil=w),tn(m);const y=so(d.messageStreamStates,m);y!==d.messageStreamStates&&(h.messageStreamStates=y);const v=Wo(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const S=mr(d.streamingMessageIds,c,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(c)){const k=new Map(d.abortControllers);k.delete(c),h.abortControllers=k}return h})},loadMoreMessages:async(s,n="up")=>{const o=r(),a=o.messages.get(s),l=o.sessionMemoryState.get(s);if(!a||!l||l.totalAvailableMessages&&a.length>=l.totalAvailableMessages)return;const c=await Ci(s,()=>Fe.getSessionMessages(s));if(n==="up"&&a.length>0){const d=Ho(c),u=a[0],m=d.findIndex(f=>f.info.id===u.info.id);if(m>0){const f=Math.min(Mr.VIEWPORT_MESSAGES,m),p=d.slice(m-f,m);t(h=>{const x=[...p,...a],g=Ho(x),w=Math.max(0,g.length-a.length),y=new Map(h.messages);y.set(s,g);const v=new Map(h.sessionMemoryState);return v.set(s,{...l,viewportAnchor:l.viewportAnchor+w,hasMoreAbove:m-f>0,totalAvailableMessages:d.length}),{messages:y,sessionMemoryState:v}})}else m===0&&t(f=>{const p=new Map(f.sessionMemoryState);return p.set(s,{...l,hasMoreAbove:!1,totalAvailableMessages:d.length}),{sessionMemoryState:p}})}},getLastMessageModel:s=>{const{messages:n}=r(),o=n.get(s);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const l=o[a];if(l.info.role==="assistant"&&"providerID"in l.info&&"modelID"in l.info)return{providerID:l.info.providerID,modelID:l.info.modelID}}return null}}),{name:"message-store",storage:Gs(()=>ws()),partialize:t=>({lastUsedProvider:t.lastUsedProvider,sessionMemoryState:Array.from(t.sessionMemoryState.entries()).map(([r,s])=>[r,{viewportAnchor:s.viewportAnchor,isStreaming:s.isStreaming,lastAccessedAt:s.lastAccessedAt,backgroundMessageCount:s.backgroundMessageCount,totalAvailableMessages:s.totalAvailableMessages,hasMoreAbove:s.hasMoreAbove,trimmedHeadMaxId:s.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(t.sessionAbortFlags.entries()).map(([r,s])=>[r,{timestamp:s.timestamp,acknowledged:s.acknowledged}])}),merge:(t,r)=>{if(!t)return r;let s=r.sessionMemoryState;Array.isArray(t.sessionMemoryState)&&(s=new Map(t.sessionMemoryState.map(o=>o)));let n=r.sessionAbortFlags;return Array.isArray(t.sessionAbortFlags)&&(n=new Map(t.sessionAbortFlags)),{...r,lastUsedProvider:t.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:s,sessionAbortFlags:n}}}),{name:"message-store"})),$b=t=>typeof t=="object"&&t!==null,Bb=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(s=>{if(!Array.isArray(s)||s.length!==2)return;const[n,o]=s;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},zb=async(t,r)=>{try{const n=pt.getState().getDirectoryForSession(t);if(n)return Fe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for permission handling:",s)}return r()},ko=os()(us(Vs((t,r)=>({permissions:new Map,addPermission:(s,n)=>{const o=s.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===s.id))return;const l=s.permission?.toLowerCase?.()??null;let c=n?.currentAgentContext?.get(o);if(c||(c=n?.sessionAgentSelections?.get(o)??void 0),!c&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(c=f.getState().currentAgentName??void 0)}const d=fa(c),u=n?.getSessionAgentEditMode?.(o,c)??d;if(u==="full"||u==="allow"&&Mb(l)){r().respondToPermission(o,s.id,"once").catch(()=>{});return}t(f=>{const p=f.permissions.get(o)||[],h=new Map(f.permissions);return h.set(o,[...p,s]),{permissions:h}})},respondToPermission:async(s,n,o)=>{await zb(s,()=>Fe.replyToPermission(n,o)),o==="reject"&&await kt.getState().abortCurrentOperation(s),t(a=>{const c=(a.permissions.get(s)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(s,c),{permissions:d}})}}),{name:"permission-store",storage:Gs(()=>ws()),partialize:t=>({permissions:Array.from(t.permissions.entries())}),merge:(t,r)=>{if(!$b(t))return r;const s=Bb(t.permissions);return{...r,permissions:new Map(s)}}}),{name:"permission-store"})),Hb=t=>typeof t=="object"&&t!==null,Wb=t=>{if(!Array.isArray(t))return[];const r=[];return t.forEach(s=>{if(!Array.isArray(s)||s.length!==2)return;const[n,o]=s;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},id=async(t,r)=>{try{const n=pt.getState().getDirectoryForSession(t);if(n)return Fe.withDirectory(n,r)}catch(s){console.warn("Failed to resolve session directory for question handling:",s)}return r()},Ln=os()(us(Vs((t,r)=>({questions:new Map,addQuestion:s=>{const n=s.sessionID;!n||r().questions.get(n)?.some(a=>a.id===s.id)||t(a=>{const l=a.questions.get(n)||[],c=new Map(a.questions);return c.set(n,[...l,s]),{questions:c}})},dismissQuestion:(s,n)=>{!s||!n||t(o=>{const l=(o.questions.get(s)||[]).filter(d=>d.id!==n),c=new Map(o.questions);return c.set(s,l),{questions:c}})},respondToQuestion:async(s,n,o)=>{await id(s,()=>Fe.replyToQuestion(n,o)),r().dismissQuestion(s,n)},rejectQuestion:async(s,n)=>{await id(s,()=>Fe.rejectQuestion(n)),r().dismissQuestion(s,n)}}),{name:"question-store",storage:Gs(()=>ws()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,r)=>{if(!Hb(t))return r;const s=Wb(t.questions);return{...r,questions:new Map(s)}}}),{name:"question-store"})),Gl=t=>t.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
- `),go=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s},ld=(t,r,s)=>{if(!r)return null;const n=s(r)?.path;if(typeof n=="string"&&n.trim().length>0)return go(n);const o=t.find(a=>a.id===r);return o?go(o.directory??null):null},fe=os()(us((t,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:(s,n,o)=>at.getState().getSessionAgentEditMode(s,n,o),toggleSessionAgentEditMode:(s,n,o)=>at.getState().toggleSessionAgentEditMode(s,n,o),setSessionAgentEditMode:(s,n,o,a)=>at.getState().setSessionAgentEditMode(s,n,o,a),loadSessions:()=>pt.getState().loadSessions(),openNewSessionDraft:s=>{let n=null;s?.directoryOverride!==void 0?n=s.directoryOverride:n=zt.getState().getActiveProject()?.path??null,t({newSessionDraft:{open:!0,directoryOverride:n,parentID:s?.parentID??null,title:s?.title},currentSessionId:null,error:null});try{const o=et.getState(),a=o.getVisibleAgents();let l;if(o.settingsDefaultAgent){const c=a.find(d=>d.name===o.settingsDefaultAgent);c&&(l=c.name)}l||(l=a.find(c=>c.name==="build")?.name||a[0]?.name),l&&o.setAgent(l)}catch{}},closeNewSessionDraft:()=>{const s=pt.getState().currentSessionId;t({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:s})},createSession:async(s,n,o)=>{r().closeNewSessionDraft();const a=await pt.getState().createSession(s,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async s=>{if(!s)return;const n=kt.getState(),{messages:o,lastUsedProvider:a}=n;let l,c;if(o.forEach((y,v)=>{const S=y.find(k=>k.info?.id===s);S&&!l&&(l=S,c=v)}),!l||l.info.role!=="assistant")return;const d=Gl(l.parts);if(!d.trim())return;const u=pt.getState(),m=ld(u.sessions,c??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:x}=et.getState(),g=p||a?.providerID,w=h||a?.modelID;!g||!w||await Fe.sendMessage({id:f.id,providerID:g,modelID:w,text:d,prefaceText:uf,agent:x??void 0})},deleteSession:(s,n)=>pt.getState().deleteSession(s,n),deleteSessions:(s,n)=>pt.getState().deleteSessions(s,n),updateSessionTitle:(s,n)=>pt.getState().updateSessionTitle(s,n),shareSession:s=>pt.getState().shareSession(s),unshareSession:s=>pt.getState().unshareSession(s),setCurrentSession:async s=>{s&&r().closeNewSessionDraft();const n=pt.getState().currentSessionId,o=ld(pt.getState().sessions,s,pt.getState().getWorktreeMetadata),a=Fe.getDirectory()??gt.getState().currentDirectory??null,l=o??a;try{Fe.setDirectory(l??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}if(n&&n!==s&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,Da().VIEWPORT_MESSAGES)}if(pt.getState().setCurrentSession(s),s){r().messages.get(s)||await r().loadMessages(s),r().trimToViewportWindow(s,cl());const d=r().messages.get(s);if(d&&d.length>0){const u=et.getState().agents;if(u.length>0)try{await at.getState().analyzeAndSaveExternalSessionChoices(s,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:(s,n)=>kt.getState().loadMessages(s,n),sendMessage:async(s,n,o,a,l,c,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=v=>{t(S=>{const k=new Map(S.sessionActivityPhase??new Map);return k.set(v,"busy"),{sessionActivityPhase:k}})},h=v=>{t(S=>{const k=new Map(S.sessionActivityPhase??new Map);return k.set(v,"idle"),{sessionActivityPhase:k}})};if(m?.open){const v=await pt.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!v?.id)throw new Error("Failed to create session");const S=et.getState(),k=S.currentAgentName,b=f??k,N=S.currentProviderId,D=S.currentModelId;if(N&&D)try{at.getState().saveSessionModelSelection(v.id,N,D)}catch{}if(b){try{at.getState().saveSessionAgentSelection(v.id,b)}catch{}if(N&&D){try{at.getState().saveAgentModelForSession(v.id,b,N,D)}catch{}if(u!==void 0)try{at.getState().saveAgentModelVariantForSession(v.id,b,N,D,u)}catch{}}}try{pt.getState().initializeNewOpenChamberSession(v.id,S.agents)}catch{}r().closeNewSessionDraft(),p(v.id);try{return await kt.getState().sendMessage(s,n,o,b,v.id,l,c,d,u)}catch(j){throw h(v.id),j}}const x=pt.getState().currentSessionId,g=x?at.getState().getSessionAgentSelection(x):null,w=et.getState().currentAgentName,y=f||g||w||void 0;if(x&&y){try{at.getState().saveSessionAgentSelection(x,y)}catch{}if(u!==void 0)try{at.getState().saveAgentModelVariantForSession(x,y,n,o,u)}catch{}}x&&p(x);try{return await kt.getState().sendMessage(s,n,o,y,x||void 0,l,c,d,u)}catch(v){throw x&&h(x),v}},abortCurrentOperation:()=>{const s=pt.getState().currentSessionId;return kt.getState().abortCurrentOperation(s||void 0)},armAbortPrompt:(s=3e3)=>{const n=pt.getState().currentSessionId;if(!n)return null;const o=Date.now()+s;return t({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{t({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:s=>{s&&kt.getState().acknowledgeSessionAbort(s)},addStreamingPart:(s,n,o,a)=>{const c=pt.getState().currentSessionId||s;return kt.getState().addStreamingPart(s,n,o,a,c)},completeStreamingMessage:(s,n)=>kt.getState().completeStreamingMessage(s,n),markMessageStreamSettled:s=>kt.getState().markMessageStreamSettled(s),updateMessageInfo:(s,n,o)=>kt.getState().updateMessageInfo(s,n,o),updateSessionCompaction:(s,n)=>kt.getState().updateSessionCompaction(s,n??null),addPermission:s=>{const n={currentAgentContext:at.getState().currentAgentContext,sessionAgentSelections:at.getState().sessionAgentSelections,getSessionAgentEditMode:at.getState().getSessionAgentEditMode};return ko.getState().addPermission(s,n)},respondToPermission:(s,n,o)=>ko.getState().respondToPermission(s,n,o),addQuestion:s=>Ln.getState().addQuestion(s),dismissQuestion:(s,n)=>Ln.getState().dismissQuestion(s,n),respondToQuestion:(s,n,o)=>Ln.getState().respondToQuestion(s,n,o),rejectQuestion:(s,n)=>Ln.getState().rejectQuestion(s,n),clearError:()=>pt.getState().clearError(),getSessionsByDirectory:s=>pt.getState().getSessionsByDirectory(s),getDirectoryForSession:s=>pt.getState().getDirectoryForSession(s),getLastMessageModel:s=>kt.getState().getLastMessageModel(s),getCurrentAgent:s=>at.getState().getCurrentAgent(s),syncMessages:(s,n)=>kt.getState().syncMessages(s,n),applySessionMetadata:(s,n)=>pt.getState().applySessionMetadata(s,n),addAttachedFile:s=>lr.getState().addAttachedFile(s),addServerFile:(s,n,o)=>lr.getState().addServerFile(s,n,o),removeAttachedFile:s=>lr.getState().removeAttachedFile(s),clearAttachedFiles:()=>lr.getState().clearAttachedFiles(),updateViewportAnchor:(s,n)=>kt.getState().updateViewportAnchor(s,n),trimToViewportWindow:(s,n)=>{const o=pt.getState().currentSessionId,a=r().sessionActivityPhase?.get(s);if(!(a==="busy"||a==="cooldown"))return kt.getState().trimToViewportWindow(s,n,o||void 0)},evictLeastRecentlyUsed:()=>{const s=pt.getState().currentSessionId;return kt.getState().evictLeastRecentlyUsed(s||void 0)},loadMoreMessages:(s,n)=>kt.getState().loadMoreMessages(s,n),saveSessionModelSelection:(s,n,o)=>at.getState().saveSessionModelSelection(s,n,o),getSessionModelSelection:s=>at.getState().getSessionModelSelection(s),saveSessionAgentSelection:(s,n)=>at.getState().saveSessionAgentSelection(s,n),getSessionAgentSelection:s=>at.getState().getSessionAgentSelection(s),saveAgentModelForSession:(s,n,o,a)=>at.getState().saveAgentModelForSession(s,n,o,a),getAgentModelForSession:(s,n)=>at.getState().getAgentModelForSession(s,n),saveAgentModelVariantForSession:(s,n,o,a,l)=>at.getState().saveAgentModelVariantForSession(s,n,o,a,l),getAgentModelVariantForSession:(s,n,o,a)=>at.getState().getAgentModelVariantForSession(s,n,o,a),analyzeAndSaveExternalSessionChoices:(s,n)=>{const o=kt.getState().messages;return at.getState().analyzeAndSaveExternalSessionChoices(s,n,o)},isOpenChamberCreatedSession:s=>pt.getState().isOpenChamberCreatedSession(s),markSessionAsOpenChamberCreated:s=>pt.getState().markSessionAsOpenChamberCreated(s),initializeNewOpenChamberSession:(s,n)=>pt.getState().initializeNewOpenChamberSession(s,n),setWorktreeMetadata:(s,n)=>pt.getState().setWorktreeMetadata(s,n),setSessionDirectory:(s,n)=>pt.getState().setSessionDirectory(s,n),getWorktreeMetadata:s=>pt.getState().getWorktreeMetadata(s),getContextUsage:(s,n)=>{if(r().newSessionDraft?.open)return null;const o=pt.getState().currentSessionId;if(!o)return null;const a=kt.getState().messages;return at.getState().getContextUsage(o,s,n,a)},updateSessionContextUsage:(s,n,o)=>{const a=kt.getState().messages;return at.getState().updateSessionContextUsage(s,n,o,a)},initializeSessionContextUsage:(s,n,o)=>{const a=kt.getState().messages;return at.getState().initializeSessionContextUsage(s,n,o,a)},debugSessionMessages:async s=>{const n=kt.getState().messages.get(s)||[],o=pt.getState().sessions.find(a=>a.id===s);console.log(`Debug session ${s}:`,{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:(s,n,o)=>{const a=kt.getState().messages;return at.getState().pollForTokenUpdates(s,n,a,o)},updateSession:s=>pt.getState().updateSession(s),removeSessionFromStore:s=>pt.getState().removeSessionFromStore(s),revertToMessage:async(s,n)=>{const a=(kt.getState().messages.get(s)||[]).find(m=>m.info.id===n);let l="";a&&a.info.role==="user"&&(l=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
- `).trim());const c=await Fe.revertSession(s,n);pt.getState().updateSession(c);const d=kt.getState().messages.get(s)||[],u=c.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);kt.getState().syncMessages(s,f)}}l&&t({pendingInputText:l})},handleSlashUndo:async s=>{const o=(r().messages.get(s)||[]).filter(p=>p.info.role==="user"),l=r().sessions.find(p=>p.id===s);if(o.length===0)return;const c=l?.revert?.messageID;let d;if(c){const p=o.findIndex(h=>h.info.id===c);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(s,d.info.id);const{toast:f}=await Ss(async()=>{const{toast:p}=await import("./vendor-.bun-CaD8MAGl.js").then(h=>h.dd);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async s=>{const a=r().sessions.find(m=>m.id===s)?.revert?.messageID;if(!a)return;const c=(r().messages.get(s)||[]).filter(m=>m.info.role==="user"),d=c.findIndex(m=>m.info.id===a),u=c[d-1];if(u){const m=u.parts.find(h=>h.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(s,u.info.id);const{toast:p}=await Ss(async()=>{const{toast:h}=await import("./vendor-.bun-CaD8MAGl.js").then(x=>x.dd);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Fe.unrevertSession(s);await pt.getState().updateSession(m),await r().loadMessages(s);const{toast:f}=await Ss(async()=>{const{toast:p}=await import("./vendor-.bun-CaD8MAGl.js").then(h=>h.dd);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(s,n)=>{const a=r().sessions.find(l=>l.id===s);if(a)try{const l=await Fe.forkSession(s,n);if(!l||!l.id){const{toast:f}=await Ss(async()=>{const{toast:p}=await import("./vendor-.bun-CaD8MAGl.js").then(h=>h.dd);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(r().messages.get(s)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await Ss(async()=>{const{toast:p}=await import("./vendor-.bun-CaD8MAGl.js").then(h=>h.dd);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(l.id),u&&t({pendingInputText:u}),await r().loadMessages(l.id);const{toast:m}=await Ss(async()=>{const{toast:f}=await import("./vendor-.bun-CaD8MAGl.js").then(p=>p.dd);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(l){console.error("Failed to fork session:",l);const{toast:c}=await Ss(async()=>{const{toast:d}=await import("./vendor-.bun-CaD8MAGl.js").then(u=>u.dd);return{toast:d}},__vite__mapDeps([0,1]));c.error("Failed to fork session")}},setPendingInputText:s=>{t({pendingInputText:s})},consumePendingInputText:()=>{const s=r().pendingInputText;return s!==null&&t({pendingInputText:null}),s}}),{name:"composed-session-store"}));pt.subscribe((t,r)=>{if(t.sessions===r.sessions&&t.sessionsByDirectory===r.sessionsByDirectory&&t.currentSessionId===r.currentSessionId&&t.lastLoadedDirectory===r.lastLoadedDirectory&&t.isLoading===r.isLoading&&t.error===r.error&&t.webUICreatedSessions===r.webUICreatedSessions&&t.worktreeMetadata===r.worktreeMetadata&&t.availableWorktrees===r.availableWorktrees&&t.availableWorktreesByProject===r.availableWorktreesByProject)return;const s=fe.getState().newSessionDraft?.open;fe.setState({sessions:t.sessions,sessionsByDirectory:t.sessionsByDirectory,currentSessionId:s?null:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,isLoading:t.isLoading,error:t.error,webUICreatedSessions:t.webUICreatedSessions,worktreeMetadata:t.worktreeMetadata,availableWorktrees:t.availableWorktrees,availableWorktreesByProject:t.availableWorktreesByProject})});kt.subscribe((t,r)=>{if(t.messages===r.messages&&t.sessionMemoryState===r.sessionMemoryState&&t.messageStreamStates===r.messageStreamStates&&t.sessionCompactionUntil===r.sessionCompactionUntil&&t.sessionAbortFlags===r.sessionAbortFlags&&t.streamingMessageIds===r.streamingMessageIds&&t.abortControllers===r.abortControllers&&t.lastUsedProvider===r.lastUsedProvider&&t.isSyncing===r.isSyncing)return;const s=new Map;t.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const l=n[a];if(!l||!l.info)continue;const c=l.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=c.time&&typeof c.time.created=="number"?c.time.created:null;s.set(o,{title:u,createdAt:m});break}}}}}),fe.setState({messages:t.messages,sessionMemoryState:t.sessionMemoryState,messageStreamStates:t.messageStreamStates,sessionCompactionUntil:t.sessionCompactionUntil,sessionAbortFlags:t.sessionAbortFlags,streamingMessageIds:t.streamingMessageIds,abortControllers:t.abortControllers,lastUsedProvider:t.lastUsedProvider,isSyncing:t.isSyncing,userSummaryTitles:s})});lr.subscribe((t,r)=>{t.attachedFiles!==r.attachedFiles&&fe.setState({attachedFiles:t.attachedFiles})});at.subscribe((t,r)=>{t.sessionModelSelections===r.sessionModelSelections&&t.sessionAgentSelections===r.sessionAgentSelections&&t.sessionAgentModelSelections===r.sessionAgentModelSelections&&t.currentAgentContext===r.currentAgentContext&&t.sessionContextUsage===r.sessionContextUsage&&t.sessionAgentEditModes===r.sessionAgentEditModes||fe.setState({sessionModelSelections:t.sessionModelSelections,sessionAgentSelections:t.sessionAgentSelections,sessionAgentModelSelections:t.sessionAgentModelSelections,currentAgentContext:t.currentAgentContext,sessionContextUsage:t.sessionContextUsage,sessionAgentEditModes:t.sessionAgentEditModes})});ko.subscribe((t,r)=>{t.permissions!==r.permissions&&fe.setState({permissions:t.permissions})});Ln.subscribe((t,r)=>{t.questions!==r.questions&&fe.setState({questions:t.questions})});gt.subscribe((t,r)=>{const s=go(t.currentDirectory??null),n=go(r.currentDirectory??null);if(s===n)return;const o=fe.getState().newSessionDraft;if(!o?.open)return;const a=go(o.directoryOverride);a&&a!==n||fe.setState(l=>({newSessionDraft:{...l.newSessionDraft,directoryOverride:s,parentID:null}}))});const Ub=fe.getState().newSessionDraft?.open;fe.setState({sessions:pt.getState().sessions,currentSessionId:Ub?null:pt.getState().currentSessionId,lastLoadedDirectory:pt.getState().lastLoadedDirectory,isLoading:pt.getState().isLoading,error:pt.getState().error,webUICreatedSessions:pt.getState().webUICreatedSessions,worktreeMetadata:pt.getState().worktreeMetadata,availableWorktrees:pt.getState().availableWorktrees,availableWorktreesByProject:pt.getState().availableWorktreesByProject,messages:kt.getState().messages,sessionMemoryState:kt.getState().sessionMemoryState,messageStreamStates:kt.getState().messageStreamStates,sessionCompactionUntil:kt.getState().sessionCompactionUntil,sessionAbortFlags:kt.getState().sessionAbortFlags,streamingMessageIds:kt.getState().streamingMessageIds,abortControllers:kt.getState().abortControllers,lastUsedProvider:kt.getState().lastUsedProvider,isSyncing:kt.getState().isSyncing,permissions:ko.getState().permissions,questions:Ln.getState().questions,attachedFiles:lr.getState().attachedFiles,sessionModelSelections:at.getState().sessionModelSelections,sessionAgentSelections:at.getState().sessionAgentSelections,sessionAgentModelSelections:at.getState().sessionAgentModelSelections,currentAgentContext:at.getState().currentAgentContext,sessionContextUsage:at.getState().sessionContextUsage,sessionAgentEditModes:at.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=fe);const ql=({containerRef:t,minThumbSize:r=32,hideDelayMs:s=1e3,className:n,disableHorizontal:o=!1})=>{const[a,l]=i.useState(!1),[c,d]=i.useState({length:0,offset:0}),[u,m]=i.useState({length:0,offset:0}),f=i.useRef(null),p=i.useRef(null),h=i.useRef(!1),x=i.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),g=i.useRef(null),w=i.useCallback(()=>{const M=t.current;if(!M)return;const{scrollHeight:C,clientHeight:P,scrollTop:E,scrollWidth:I,clientWidth:A,scrollLeft:T}=M,R=8;if(C>P){const K=Math.max(P-R*2,0),Y=P/C*K,_=Math.max(r,Math.min(K,Y)),J=Math.max(K-_,0),q=Math.max(C-P,1),Q=E/q*J;d({length:_,offset:Q})}else d({length:0,offset:0});if(!o&&I>A){const K=Math.max(A-R*2,0),Y=A/I*K,_=Math.max(r,Math.min(K,Y)),J=Math.max(K-_,0),q=Math.max(I-A,1),Q=T/q*J;m({length:_,offset:Q})}else m({length:0,offset:0})},[t,r,o]),y=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),s)},[s]),v=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{w(),l(!0),y()})},[y,w]);i.useEffect(()=>{const M=t.current;if(!M)return;w(),l(!0),y(),M.addEventListener("scroll",v,{passive:!0});const C=typeof ResizeObserver<"u"?new ResizeObserver(()=>w()):null;C?.observe(M);const P=typeof MutationObserver<"u"?new MutationObserver(()=>w()):null;return P?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),C?.disconnect(),P?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[t,v,y,w]);const S=(M,C)=>{const P=t.current;P&&(h.current=!0,x.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:P.scrollTop,scrollLeft:P.scrollLeft},g.current=C,l(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},k=M=>{if(!h.current)return;const C=t.current;if(!C)return;const P=g.current;if(P==="vertical"){const{pointerY:E,scrollTop:I}=x.current,A=M.clientY-E,T=C.clientHeight,R=Math.max(T-c.length,1),K=Math.max(C.scrollHeight-C.clientHeight,1),Y=A/R*K;C.scrollTop=I+Y}else if(P==="horizontal"){const{pointerX:E,scrollLeft:I}=x.current,A=M.clientX-E,T=C.clientWidth,R=Math.max(T-u.length,1),K=Math.max(C.scrollWidth-C.clientWidth,1),Y=A/R*K;C.scrollLeft=I+Y}},b=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),y())},N=c.length>0,D=u.length>0;if(!N&&!D)return null;const j=8;return e.jsxs("div",{className:F("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[N&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${j+c.offset}px`,right:`${j/2}px`},onPointerDown:M=>S(M,"vertical"),onPointerMove:k,onPointerUp:b,onPointerCancel:b}),D&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${j+u.offset}px`,bottom:`${j/2}px`},onPointerDown:M=>S(M,"horizontal"),onPointerMove:k,onPointerUp:b,onPointerCancel:b})]})},ht=i.forwardRef(({className:t,outerClassName:r,children:s,style:n,minThumbSize:o,hideDelayMs:a,as:l="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const h=i.useRef(null);return i.useImperativeHandle(p,()=>h.current,[]),e.jsxs("div",{className:F("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(l,{ref:h,className:F("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",t),style:n,...f,children:s}),e.jsx(ql,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});ht.displayName="ScrollableOverlay";const cd="mobile-overlay-root",Vb=()=>{if(typeof document>"u")return null;let t=document.getElementById(cd);return t||(t=document.createElement("div"),t.id=cd,document.body.appendChild(t)),t},Bs=({open:t,title:r,onClose:s,children:n,footer:o,className:a,contentMaxHeightClassName:l,renderHeader:c})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Vb()),i.useEffect(()=>{if(!t)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=h=>{h.key==="Escape"&&s()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[t,s]),!t||!d.current)return null;const u=l??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:s,children:e.jsxs("div",{className:F("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:s,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(es,{className:"h-4 w-4"})});return c?c(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(ht,{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 nm.createPortal(m,d.current)},ul=({totalTokens:t,percentage:r,contextLimit:s,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[l,c]=i.useState(!1),d=i.useRef(void 0),u=w=>w>=1e6?`${(w/1e6).toFixed(1)}M`:w>=1e3?`${(w/1e3).toFixed(1)}K`:w.toFixed(1).replace(/\.0$/,""),m=w=>w>=90?"text-status-error":w>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(t)}`,`Context limit: ${u(s)}`,`Output limit: ${u(f)}`],h=i.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c(!0)},500)},[]),x=i.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=e.jsxs("div",{className:F("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?h:void 0,onTouchEnd:a?x:void 0,children:[!a&&e.jsx(Jp,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:F(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[g,e.jsx(Bs,{open:l,onClose:()=>c(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),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(s)})]}),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:F("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:g}),e.jsx(it,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(w=>e.jsx("p",{className:"typography-micro leading-tight",children:w},w))})})]})},oo={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},ff=(t,r,s)=>{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"),t?(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",s?"1":"0"),n.style.setProperty("--has-touch-input",s?"1":"0"),s?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function Mi(){const t=window.innerWidth,r=typeof window.matchMedia=="function",s=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=s?.matches??!1,a=n?.matches??!1,l=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||l>0,u=t>oo.md&&t<=oo.lg,m=t<=oo.md;let f=d&&m,p=d&&!f&&u,h=!d||t>oo.lg,x="desktop";c?(f=!1,p=!1,h=!0,x="desktop"):f?x="mobile":p?x="tablet":(h=!0,x="desktop"),ff(c,x,d);let g="xs";for(const[w,y]of Object.entries(oo))t>=y&&(g=w);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:x,screenWidth:t,breakpoint:g,hasTouchInput:d}}function Yt(){const[t,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Mi());return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Mi())};return window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const s=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(Mi())},a=[],l=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return l(s),l(n),()=>{a.forEach(c=>c())}},[]),i.useEffect(()=>{if(typeof window>"u")return;const s=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,l=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=l||c||d>0;ff(s,t.deviceType,u)},[t.deviceType,t.hasTouchInput]),t}const Uo=5e3,Gb=1e4,qb=5e3,Kb=1e4,Qb=25,Yb=4,dd=15e3,fr=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Xb=(t,r)=>{if(!t&&!r)return!1;if(!t||!r)return!0;const s=new Set([...Object.keys(t),...Object.keys(r)]);for(const n of s){const o=t[n],a=r[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},Jb=(t,r)=>{if(!t&&!r)return!1;if(!t||!r)return!0;const s=t.files??[],n=r.files??[];if(s.length!==n.length||t.ahead!==r.ahead||t.behind!==r.behind||t.current!==r.current||t.tracking!==r.tracking||t.isClean!==r.isClean)return!0;const o=new Set(s.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!!Xb(t.diffStats,r.diffStats)},Zb=(t,r)=>{const s=new Set;if(!r)return s;const n=t?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),l=new Map(o.map(f=>[f.path,f])),c=new Set([...a.keys(),...l.keys()]);for(const f of c){const p=a.get(f),h=l.get(f);if(!p||!h){s.add(f);continue}if(p.index!==h.index||p.working_dir!==h.working_dir){s.add(f);continue}}const d=t?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],h=u[f];if(!p||!h){s.add(f);continue}(p.insertions!==h.insertions||p.deletions!==h.deletions)&&s.add(f)}return s},ls=os()(us((t,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:Uo,setActiveDirectory:s=>{const{activeDirectory:n,directories:o}=r();if(n!==s)if(s&&!o.has(s)){const a=new Map(o);a.set(s,fr()),t({activeDirectory:s,directories:a})}else t({activeDirectory:s})},getDirectoryState:s=>r().directories.get(s)??null,fetchStatus:async(s,n,o={})=>{const{silent:a=!1}=o,{directories:l}=r();let c=l.get(s);c||(c=fr()),a||t({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(s)){const f=new Map(l);return f.set(s,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),t({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(s);if(Jb(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(s)??fr(),h=Zb(p.status,m),x=new Set((p.status?.files??[]).map(v=>v.path)),g=new Set((m.files??[]).map(v=>v.path)),w=new Map(p.diffCache);for(const v of x)g.has(v)||w.delete(v);for(const v of h)w.delete(v);const y=h.size>0;f.set(s,{...p,isGitRepo:!0,status:m,diffCache:w,lastStatusFetch:Date.now(),lastStatusChange:y?Date.now():p.lastStatusChange}),t({directories:f})}else{const f=new Map(r().directories),p=f.get(s)??fr();f.set(s,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),t({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||t({isLoadingStatus:!1})}return d},fetchBranches:async(s,n)=>{t({isLoadingBranches:!0});try{const o=await n.getGitBranches(s),a=new Map(r().directories),l=a.get(s)??fr();a.set(s,{...l,branches:o}),t({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{t({isLoadingBranches:!1})}},fetchLog:async(s,n,o)=>{const{directories:a}=r(),l=a.get(s),c=o??l?.logMaxCount??25;t({isLoadingLog:!0});try{const d=await n.getGitLog(s,{maxCount:c}),u=new Map(r().directories),m=u.get(s)??fr();u.set(s,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:c}),t({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{t({isLoadingLog:!1})}},fetchIdentity:async(s,n)=>{t({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(s),a=new Map(r().directories),l=a.get(s)??fr();a.set(s,{...l,identity:o}),t({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{t({isLoadingIdentity:!1})}},fetchAll:async(s,n,o={})=>{const{directories:a}=r();let l=a.get(s);if(!l){l=fr();const f=new Map(a);f.set(s,l),t({directories:f})}const{force:c=!1}=o,d=Date.now();await r().fetchStatus(s,n);const u=r().directories.get(s);if(!u?.isGitRepo)return;await r().fetchBranches(s,n);const m=d-(u.lastLogFetch||0);(c||m>Kb||!u.log)&&await r().fetchLog(s,n),await r().fetchIdentity(s,n),r().fetchAllDiffs(s,n)},getDiff:(s,n)=>r().directories.get(s)?.diffCache.get(n)??null,setDiff:(s,n,o)=>{const a=new Map(r().directories),l=a.get(s)??fr(),c=new Map(l.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(s,{...l,diffCache:c}),t({directories:a})},clearDiffCache:s=>{const n=new Map(r().directories),o=n.get(s);o&&(n.set(s,{...o,diffCache:new Map}),t({directories:n}))},fetchAllDiffs:async(s,n)=>{const o=r().directories.get(s);if(!o?.status?.files||o.status.files.length===0)return;const c=o.status.files.filter(v=>!o.diffCache.has(v.path)).slice(0,Qb);if(c.length===0)return;let d=0;const u=[],m=()=>{const v=d;return d+=1,v<c.length?c[v]:null},f=async v=>{const S=n.getGitFileDiff(s,{path:v}),k=new Promise((N,D)=>{setTimeout(()=>D(new Error(`Timed out after ${dd}ms`)),dd)}),b=await Promise.race([S,k]);return{path:v,diff:{original:b.original??"",modified:b.modified??""}}},p=async()=>{for(;;){const v=m();if(!v)return;try{u.push(await f(v.path))}catch{}}},h=Math.min(Yb,c.length);await Promise.allSettled(Array.from({length:h},()=>p()));const x=new Map(r().directories),g=x.get(s);if(!g)return;const w=new Map(g.diffCache),y=Date.now();u.forEach(v=>{w.set(v.path,{...v.diff,fetchedAt:y})}),x.set(s,{...g,diffCache:w}),t({directories:x})},setLogMaxCount:(s,n)=>{const o=new Map(r().directories),a=o.get(s)??fr();o.set(s,{...a,logMaxCount:n}),t({directories:o})},startPolling:s=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){t({pollIntervalId:o()});return}const{activeDirectory:c}=r();if(!c){t({pollIntervalId:o()});return}if(await r().fetchStatus(c,s,{silent:!0}))await r().fetchLog(c,s),r().fetchAllDiffs(c,s),t({currentPollInterval:Uo});else{const m=Math.min(a+qb,Gb);t({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&t({pollIntervalId:o()})},a)};t({pollIntervalId:o(),currentPollInterval:Uo})},stopPolling:()=>{const{pollIntervalId:s}=r();s&&(clearTimeout(s),t({pollIntervalId:null,currentPollInterval:Uo}))},refresh:async(s,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,s,n)}}),{name:"git-store"})),pf=t=>ls(r=>t?r.directories.get(t)?.status??null:null),hf=t=>ls(r=>t?r.directories.get(t)?.branches??null:null),ew=t=>ls(r=>t?r.directories.get(t)?.log??null:null),tw=t=>ls(r=>t?r.directories.get(t)?.identity??null:null),Kl=t=>ls(r=>t?r.directories.get(t)?.isGitRepo??null:null),sw=t=>ls(r=>t?r.directories.get(t)?.status?.files?.length??0:0);function ts({...t}){return e.jsx(Zp,{"data-slot":"dropdown-menu",...t})}function ss({...t}){return e.jsx(eh,{"data-slot":"dropdown-menu-trigger",...t})}function rs({className:t,sideOffset:r=4,...s}){return e.jsx(th,{children:e.jsx(sh,{"data-slot":"dropdown-menu-content",sideOffset:r,className:F("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",t),...s})})}function jt({className:t,inset:r,variant:s="default",...n}){return e.jsx(lh,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":s,className:F("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",t),...n})}function Pa({...t}){return e.jsx(nh,{"data-slot":"dropdown-menu-radio-group",...t})}function Ta({className:t,children:r,...s}){return e.jsxs(oh,{"data-slot":"dropdown-menu-radio-item",className:F("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",t),...s,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(ah,{children:e.jsx(Qt,{className:"size-3"})})}),r]})}function Wr({className:t,inset:r,...s}){return e.jsx(rh,{"data-slot":"dropdown-menu-label","data-inset":r,className:F("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",t),...s})}function Is({className:t,...r}){return e.jsx(ih,{"data-slot":"dropdown-menu-separator",className:F("bg-border -mx-1 my-0.5 h-px",t),...r})}const rw=ch("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 ve({className:t,variant:r,size:s,asChild:n=!1,...o}){const a=n?om:"button";return e.jsx(a,{"data-slot":"button",className:F(rw({variant:r,size:s,className:t})),...o})}const eo=dh,Io=({className:t,...r})=>e.jsx(uh,{className:F("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",t),...r}),to=({className:t,...r})=>e.jsx(mh,{className:F("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",t),...r}),nw={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"}]},apply_patch:{displayName:"Apply Patch",category:"file",outputLanguage:"diff",inputFields:[{key:"patchText",label:"Patch",type:"code",language:"diff"}]},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 Ql(t){return nw[t]||{displayName:t.charAt(0).toUpperCase()+t.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function ow(t,r,s){const n=Ql(t);if(n.outputLanguage==="auto"){if(s?.filePath||s?.file_path||s?.sourcePath){const o=s.filePath||s.file_path||s.sourcePath,a=_r(o);if(a)return a}if(t==="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 _r(t){const r=t.split(".").pop()?.toLowerCase(),s=t.split("/").pop()?.toLowerCase()||"",n={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return n[s]?n[s]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"elixir",heex:"elixir",leex:"elixir",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[r||""]||null}const aw=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Co(t){const r=t.split(".").pop()?.toLowerCase();return aw.includes(r||"")}function ml(t){const r=t.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 iw(t,r){if(!t)return"";const s=n=>{const o=t[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=s("command");if(n)return n}if(r==="task"){const n=s("prompt");if(n)return n;const o=s("description");if(o)return o}if(r==="apply_patch"&&typeof t=="object"){const n=s("patchText")||s("patch_text")||s("patch");if(n)return n}if((r==="edit"||r==="multiedit")&&typeof t=="object"){const n=s("filePath")||s("file_path")||s("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof t=="object"){const n=s("content");if(n)return n}return typeof t=="object"?Object.entries(t).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const l=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${l}: ${c}`}).join(`
12
- `):String(t)}const Yl=i.createContext(null),Zs=()=>{const t=i.useContext(Yl);if(!t)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return t},gf=t=>{const r=Zs();return t(r)},lw=()=>gf(t=>t.runtime.isDesktop),xf=()=>gf(t=>t.runtime.isVSCode),yf=({mode:t,onModeChange:r,className:s})=>{const n=i.useCallback(o=>{o.stopPropagation(),r(t==="side-by-side"?"unified":"side-by-side")},[t,r]);return e.jsx(ve,{size:"sm",variant:"ghost",className:F("h-5 w-5 p-0 opacity-60 hover:opacity-100",s),onClick:n,title:t==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:t==="side-by-side"?e.jsx(fh,{className:"h-3 w-3"}):e.jsx(ph,{className:"h-3 w-3"})})},Xl=Re.createContext(void 0);function en(){const t=Re.useContext(Xl);if(!t)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return t}function ti(){return Re.useContext(Xl)}const cw="Flexoki",dw="dark",uw={"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"},mw=[{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"}}],fw={name:cw,type:dw,colors:uw,tokenColors:mw},pw="Flexoki",hw="light",gw={"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"},xw=[{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"}}],yw={name:pw,type:hw,colors:gw,tokenColors:xw},Jl="flexoki-dark",Zl="flexoki-light",bw=fw,ww=yw;function bf(t,r){return Object.defineProperty(t,"toString",{value:()=>r,enumerable:!1,configurable:!0}),Object.defineProperty(t,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0}),t}function wf(t,r,s){const n=t.colors?.["editor.background"],o=t.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${r}" is missing editor.background/editor.foreground`);const a=t.tokenColors??[];return{...t,name:r,type:s,fg:o,bg:n,settings:a}}const ec=wf(bw,Jl,"dark"),tc=wf(ww,Zl,"light");bf(ec,Jl);bf(tc,Zl);const Gn={dark:Jl,light:Zl},ud=[tc,ec];let md=!1;function vf(){md||(jc(Gn.dark,async()=>ec),jc(Gn.light,async()=>tc),md=!0)}const Di=({...t})=>{const{theme:r="system"}=hh();return e.jsx(gh,{theme:r,className:"toaster group",closeButton:!1,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)"},...t})},fd=async t=>{try{await navigator.clipboard.writeText(t)}catch(r){console.error("Failed to copy to clipboard:",r)}},U={...gr,success:(t,r)=>gr.success(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),info:(t,r)=>gr.info(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),error:(t,r)=>gr.error(t,{...r,action:r?.action||{label:"Copy",onClick:()=>fd(String(t))}}),warning:(t,r)=>gr.warning(t,{...r,action:r?.action||{label:"Copy",onClick:()=>fd(String(t))}})},Rs=Re.forwardRef(({className:t,...r},s)=>e.jsx(ht,{as:"textarea",ref:s,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:F("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",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r}));Rs.displayName="Textarea";const vw=`
13
- :host {
14
- font-family: var(--font-mono);
15
- font-size: var(--text-code);
16
- }
17
-
18
- :host, pre, [data-diffs], [data-code] {
19
- transform: translateZ(0);
20
- -webkit-transform: translateZ(0);
21
- -webkit-backface-visibility: hidden;
22
- backface-visibility: hidden;
23
- }
24
-
25
- pre, [data-code] {
26
- font-family: var(--font-mono);
27
- font-size: var(--text-code);
28
- }
29
-
30
- [data-code] {
31
- -webkit-overflow-scrolling: touch;
32
- }
33
-
34
- /* Mobile touch selection support */
35
- [data-line-number] {
36
- touch-action: manipulation;
37
- -webkit-tap-highlight-color: transparent;
38
- cursor: pointer;
39
- }
40
-
41
- /* Ensure interactive line numbers work on touch */
42
- pre[data-interactive-line-numbers] [data-line-number] {
43
- touch-action: manipulation;
44
- }
45
- /* Reduce hunk separator height */
46
- [data-separator-content] {
47
- height: 24px !important;
48
- }
49
- [data-expand-button] {
50
- height: 24px !important;
51
- width: 24px !important;
52
- }
53
- [data-separator-multi-button] {
54
- row-gap: 0 !important;
55
- }
56
- [data-expand-up] {
57
- height: 12px !important;
58
- min-height: 12px !important;
59
- max-height: 12px !important;
60
- margin: 0 !important;
61
- margin-top: 3px !important;
62
- padding: 0 !important;
63
- border-radius: 4px 4px 0 0 !important;
64
- }
65
- [data-expand-down] {
66
- height: 12px !important;
67
- min-height: 12px !important;
68
- max-height: 12px !important;
69
- margin: 0 !important;
70
- margin-top: -3px !important;
71
- padding: 0 !important;
72
- border-radius: 0 0 4px 4px !important;
73
- }
74
- `;function jw(t,r,s){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s;return`${t}:${r.length}:${s.length}:${n.length}:${o.length}`}const Sw=(t,r,s)=>{const a=(s.side==="deletions"?t:r).split(`
75
- `),l=Math.max(1,s.start),c=Math.min(a.length,s.end);return l>c?"":a.slice(l-1,c).join(`
76
- `)},fl=({original:t,modified:r,language:s,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:l="fill"})=>{const{isMobile:c}=Yt(),{inputBarOffset:d,isKeyboardOpen:u}=ke(),f=ti()?.currentTheme?.metadata?.variant==="dark",p=ke(q=>q.setActiveMainTab),[h,x]=Re.useState(null),[g,w]=Re.useState(""),y=Re.useRef(null),v=Re.useCallback(()=>{if(c)return"50%";const q=document.querySelector("main.flex-1");if(q){const Q=q.getBoundingClientRect();return`${Q.left+Q.width/2}px`}return"50%"},[c]),[S,k]=Re.useState(v),b=fe(q=>q.sendMessage),N=fe(q=>q.currentSessionId),{currentProviderId:D,currentModelId:j,currentAgentName:M,currentVariant:C}=et(),P=at(q=>q.getSessionAgentSelection),E=at(q=>q.getAgentModelForSession),I=at(q=>q.getAgentModelVariantForSession);Re.useEffect(()=>{if(c)return;const q=()=>{k(v())};return window.addEventListener("resize",q),()=>window.removeEventListener("resize",q)},[c,v]);const A=Re.useCallback(q=>{if(c&&q&&h&&q.start===q.end){const Q=q.start,z=h.start,H=h.end,W=Math.min(z,H,Q),B=Math.max(z,H,Q);if(Q<z||Q>H){x({...q,start:W,end:B});return}}x(q),q||w("")},[c,h]);Re.useEffect(()=>{if(!h)return;const q=z=>{const H=z.target;if(y.current?.contains(H)||H.closest("[data-sonner-toast]")||H.closest("[data-sonner-toaster]"))return;z.composedPath().some(se=>se instanceof HTMLElement?se.hasAttribute("data-line-number")||se.closest?.("[data-line-number]"):!1)||(x(null),w(""))},Q=setTimeout(()=>{document.addEventListener("click",q)},100);return()=>{clearTimeout(Q),document.removeEventListener("click",q)}},[h]);const T=Re.useCallback(async()=>{if(!h||!g.trim())return;if(!N){U.error("Select a session to send comment");return}const q=P(N)||M,Q=q?E(N,q):null,z=Q?.providerId||D,H=Q?.modelId||j;if(!z||!H){U.error("Select a model to send comment");return}const W=q&&z&&H?I(N,q,z,H)??C:C,B=Sw(t,r,h),se=h.start,L=h.end,ae=h.side==="deletions"?"original":"modified",O=`Comment on \`${n}\` lines ${se}-${L} (${ae}):
77
- \`\`\`${s}
78
- ${B}
79
- \`\`\`
80
-
81
- ${g}`;w(""),x(null),p("chat");try{await b(O,z,H,q,void 0,void 0,void 0,W)}catch(V){console.error("Failed to send comment",V)}},[h,g,t,r,n,s,b,N,D,j,M,C,p,P,E,I]);vf();const R=Re.useRef(null),K=Re.useMemo(()=>{const q=jw(n,t,r);if(R.current?.key===q)return R.current.fileDiff;const Q={name:n,contents:t,cacheKey:`old-${q}`},z={name:n,contents:r,cacheKey:`new-${q}`},H=Ji(Q,z);return R.current={key:q,fileDiff:H},H},[n,t,r,s]),Y=Re.useMemo(()=>({theme:{dark:Gn.dark,light:Gn.light},themeType:f?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!0,enableHoverUtility:!1,onLineSelected:A,unsafeCSS:vw}),[f,o,a,A]);if(typeof window>"u")return null;const J=h?e.jsx("div",{className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-sidebar flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Rs,{value:g,onChange:q=>{w(q.target.value);const Q=q.target;Q.style.height="auto";const H=20*5+8;Q.style.height=`${Math.min(Q.scrollHeight,H)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!c,rows:1,onKeyDown:q=>{q.key==="Enter"&&(q.metaKey||q.ctrlKey)&&(q.preventDefault(),T()),q.key==="Escape"&&(q.preventDefault(),x(null),w(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.split("/").pop(),":",h.start,"-",h.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!c&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Zt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:q=>{g.trim()&&(q.preventDefault(),T())},onClick:()=>{c||T()},disabled:!g.trim(),className:F("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",g.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Ha,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return l==="fill"?e.jsxs("div",{className:F("flex flex-col relative","size-full"),style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":void 0},children:[e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(ht,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(Sc,{fileDiff:K,options:Y,selectedLines:h})})}),h&&e.jsx("div",{className:F("pointer-events-auto relative pb-2 transition-none z-50 flex justify-center",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:J})]}):e.jsxs("div",{className:F("relative","w-full"),children:[e.jsx(ht,{outerClassName:"pierre-diff-wrapper w-full",disableHorizontal:!1,fillContainer:!1,children:e.jsx(Sc,{fileDiff:K,options:Y,selectedLines:h})}),h&&nm.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col justify-end items-start pointer-events-none transition-none transform-gpu",style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":"0px",isolation:"isolate"},children:e.jsx("div",{className:F("pointer-events-auto relative pb-2 transition-none",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginLeft:S,transform:"translateX(-50%)",marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:J})}),document.body)]})},Nw=1100,jf=15e3,Sf={"?":{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"}},kw=Sf.M,pa=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],Cw=t=>{const r=t.index?.trim(),s=t.working_dir?.trim();return r&&r!=="?"?r.charAt(0):s?s.charAt(0):r?.charAt(0)||s?.charAt(0)||"M"},Nf=t=>{const r=Cw(t);return Sf[r]??kw},Mw=t=>{const{index:r,working_dir:s}=t;return r==="A"||s==="A"||r==="?"||s==="?"},Fa=(t,r)=>{const s=t??0,n=r??0;return!s&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[s?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",s]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},Dw=i.memo(({changedFiles:t,selectedFile:r,selectedFileEntry:s,onSelectFile:n,isMobile:o,showModeSelector:a=!1,mode:l,onModeChange:c})=>{const d=i.useCallback(u=>{if(!o)return u;const m=u.lastIndexOf("/");return m>=0?u.slice(m+1):u},[o]);return t.length===0?null:e.jsxs(ts,{children:[e.jsx(ss,{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:[s?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(s.path)}),Fa(s.insertions,s.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Ht,{className:"size-4 opacity-50"})]})}),e.jsxs(rs,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&l&&c?e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(Pa,{value:l,onValueChange:u=>c(u),children:pa.map(u=>e.jsx(Ta,{value:u.value,className:"items-center",children:e.jsx("span",{className:"typography-meta text-foreground",children:u.label})},u.value))}),e.jsx(Is,{})]}):null,e.jsx(Pa,{value:r??"",onValueChange:n,children:t.map(u=>e.jsx(Ta,{value:u.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(u.path)}),e.jsx("span",{className:"ml-auto",children:Fa(u.insertions,u.deletions)})]})},u.path))})]})]})}),Aw=i.memo(({mode:t,onModeChange:r})=>{const s=pa.find(n=>n.value===t)??pa[0];return e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:"min-w-0 truncate typography-meta",children:s.label}),e.jsx(Ht,{className:"size-4 opacity-50"})]})}),e.jsx(rs,{className:"min-w-[220px]",children:e.jsx(Pa,{value:t,onValueChange:n=>r(n),children:pa.map(n=>e.jsx(Ta,{value:n.value,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-meta text-foreground",children:n.label}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:n.description})]})},n.value))})})]})}),Ew=i.memo(({changedFiles:t,selectedFile:r,onSelectFile:s})=>t.length===0?null:e.jsx(ht,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:t.map(n=>{const o=Nf(n),a=r===n.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(n.path),className:F("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",a?"bg-accent/70 text-foreground":"text-muted-foreground hover:bg-accent/40 hover:text-foreground"),children:[e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:o.color},title:o.description,"aria-label":o.description,children:o.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:n.path,children:n.path}),Fa(n.insertions,n.deletions)]})},n.path)})})})),Iw=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!s)return e.jsx("div",{className:"absolute inset-0 hidden"});const l=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:l,children:[o&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Pw=i.memo(({filePath:t,diff:r,renderSideBySide:s})=>{const n=r.original.length>0,o=r.modified.length>0,a=s?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",l=s?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:a,children:[n&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${t}`,className:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:n?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${t}`,className:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Tw=i.memo(({filePath:t,diff:r,renderSideBySide:s,wrapLines:n})=>{const o=i.useMemo(()=>_r(t)||"text",[t]);return Co(t)?e.jsx(Pw,{filePath:t,diff:r,renderSideBySide:s}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(fl,{original:r.original,modified:r.modified,language:o,fileName:t,renderSideBySide:s,wrapLines:n,layout:"inline"})})}),Fw=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>_r(t)||"text",[t]);return Co(t)?e.jsx(Iw,{filePath:t,diff:r,isVisible:s,renderSideBySide:n}):s?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(fl,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(fl,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})})}),Rw=i.memo(({directory:t,filePath:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=ls(i.useCallback(c=>c.directories.get(t)?.diffCache.get(r)??null,[t,r])),l=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return l?e.jsx(Fw,{filePath:r,diff:l,isVisible:s,renderSideBySide:n,wrapLines:o}):null}),Lw=i.memo(({directory:t,file:r,layout:s,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:l,registerSectionRef:c})=>{const{git:d}=Zs(),u=ls(i.useCallback(A=>A.directories.get(t)?.diffCache.get(r.path)??null,[t,r.path])),m=ls(A=>A.setDiff),f=ke(A=>A.setDiffFileLayout),[p,h]=i.useState(!0),[x,g]=i.useState(!1),[w,y]=i.useState(0),[v,S]=i.useState(null),[k,b]=i.useState(!1),N=i.useRef(null),D=i.useRef(null),j=i.useMemo(()=>Nf(r),[r]),M=s==="side-by-side",C=i.useMemo(()=>u?{original:u.original,modified:u.modified}:null,[u]),P=i.useCallback(A=>{D.current=A,c(r.path,A)},[r.path,c]),E=i.useCallback(A=>{h(A),A&&g(!0)},[]),I=i.useCallback(()=>{l(r.path)},[r.path,l]);return i.useEffect(()=>{if(!p||x)return;const A=D.current;if(!A)return;if(!o.current||typeof IntersectionObserver>"u"){g(!0);return}const T=new IntersectionObserver(R=>{R.some(K=>K.isIntersecting)&&(g(!0),T.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return T.observe(A),()=>T.disconnect()},[x,p,o]),i.useEffect(()=>{if(!p||!x)return;if(!t||C){N.current=null,b(!1);return}const A=`${t}::${r.path}::${w}`;if(N.current===A)return;N.current=A,S(null),b(!0);let T=!1;return(async()=>{try{const R=d.getGitFileDiff(t,{path:r.path}),K=jf,Y=new Promise((J,q)=>{setTimeout(()=>q(new Error(`Timed out after ${K}ms`)),K)}),_=await Promise.race([R,Y]);if(T)return;m(t,r.path,{original:_.original??"",modified:_.modified??""}),b(!1)}catch(R){if(T)return;const K=R instanceof Error?R.message:String(R);S(K),b(!1)}})(),()=>{T=!0,N.current===A&&(N.current=null)}},[t,C,w,r.path,d,x,p,m]),e.jsx("div",{ref:P,className:"scroll-mt-4",children:e.jsxs(eo,{open:p,onOpenChange:E,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(Io,{onClick:I,className:F("relative flex w-full items-center gap-2 px-3 py-1.5 transition-colors rounded-t-xl border border-border/60 overflow-hidden","bg-background hover:bg-background",p?"rounded-b-none":"rounded-b-xl",a?"text-primary":"text-muted-foreground hover:text-foreground"),children:[e.jsx("div",{className:F("absolute inset-0 pointer-events-none transition-colors",a?"bg-primary/10":"group-hover:bg-accent/40")}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover:opacity-100 transition-opacity",children:p?e.jsx(Ht,{className:"size-4"}):e.jsx(zs,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:j.color},title:j.description,"aria-label":j.description,children:j.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path})]}),e.jsxs("div",{className:"relative flex items-center gap-2",children:[Fa(r.insertions,r.deletions),e.jsx(yf,{mode:M?"side-by-side":"unified",onModeChange:A=>{const T=A==="side-by-side"?"side-by-side":"inline";f(r.path,T)},className:"opacity-70"})]})]})}),e.jsx(to,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[v?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:v}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>y(A=>A+1),children:"Retry"})]}):null,k&&!C&&!v?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(Ft,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,C?e.jsx(Tw,{filePath:r.path,diff:C,renderSideBySide:M,wrapLines:n}):null]})})]})})}),Ow=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=fe(),{currentDirectory:n}=gt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??void 0},_w=()=>{const{git:t}=Zs(),r=Ow(),{screenWidth:s,isMobile:n}=Yt(),o=Kl(r??null),a=pf(r??null),l=ls(G=>G.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=ls(),[m,f]=i.useState(null),[p,h]=i.useState(0),[x,g]=i.useState(null),w=i.useRef(null),y=ke(G=>G.pendingDiffFile),v=ke(G=>G.setPendingDiffFile),S=ke(G=>G.diffLayoutPreference),k=ke(G=>G.diffFileLayout),b=ke(G=>G.setDiffFileLayout),N=ke(G=>G.diffWrapLines),D=ke(G=>G.setDiffWrapLines),j=ke(G=>G.diffViewMode),M=ke(G=>G.setDiffViewMode),C=n||N,P=j==="stacked",E=n||s<=768,I=!E&&s>=1024,A=i.useRef(null),T=i.useRef(new Map),R=i.useRef(null),K=i.useMemo(()=>{if(!a?.files)return[];const G=a.diffStats??{};return a.files.map(he=>({...he,insertions:G[he.path]?.insertions??0,deletions:G[he.path]?.deletions??0,isNew:Mw(he)})).sort((he,ye)=>he.path.localeCompare(ye.path))},[a]),Y=i.useMemo(()=>m?K.find(G=>G.path===m)??null:null,[K,m]),_=i.useCallback(G=>{const he=k[G.path];if(he)return he;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const ye=s<Nw;return G.isNew||ye?"inline":"side-by-side"},[k,S,s]),J=i.useMemo(()=>Y?_(Y):null,[_,Y]);i.useEffect(()=>{r&&(c(r),ls.getState().directories.get(r)?.status||d(r,t))},[r,c,d,t]),i.useEffect(()=>{y&&(f(y),v(null),P&&(R.current=y))},[P,y,v]),i.useEffect(()=>{!m&&!y&&K.length>0&&f(K[0].path)},[K,m,y]),i.useEffect(()=>{if(!P){R.current=null;return}const G=R.current;if(!G)return;const he=T.current.get(G);he&&(he.scrollIntoView({behavior:"smooth",block:"start"}),R.current=null)},[K,P]),i.useEffect(()=>{m&&K.length>0&&(K.some(he=>he.path===m)||f(K[0]?.path??null))},[K,m]);const q=i.useCallback((G,he)=>{const ye=T.current;he?ye.set(G,he):ye.delete(G)},[]),Q=i.useCallback((G,he="smooth")=>{const ye=T.current.get(G);return ye?(ye.scrollIntoView({behavior:he,block:"start"}),!0):!1},[]),z=i.useCallback(G=>{f(G)},[]),H=i.useCallback(G=>{f(G),P&&!Q(G)&&(R.current=G)},[P,Q]),W=i.useCallback(G=>{M(G),G==="stacked"&&m&&!Q(m,"auto")&&(R.current=m)},[Q,m,M]),B=i.useCallback(G=>{const he=G==="side-by-side"?"side-by-side":"inline";if(P){K.forEach(ye=>{b(ye.path,he)});return}Y&&b(Y.path,he)},[K,P,Y,b]),se=(J??"side-by-side")==="side-by-side",L=!P||!I,ae=ls(i.useCallback(G=>!r||!m?null:G.directories.get(r)?.diffCache.get(m)??null,[r,m])),O=!!ae,V=!P&&!!m&&!O;i.useEffect(()=>{if(P)return;if(g(null),!r||!m){w.current=null;return}if(ae){w.current=null;return}const G=`${r}::${m}::${p}`;if(w.current===G)return;w.current=G;let he=!1;return(async()=>{try{const ye=t.getGitFileDiff(r,{path:m}),ge=jf,$e=new Promise((Z,ie)=>{setTimeout(()=>ie(new Error(`Timed out after ${ge}ms`)),ge)}),ee=await Promise.race([ye,$e]);if(he)return;u(r,m,{original:ee.original??"",modified:ee.modified??""})}catch(ye){if(he)return;const ge=ye instanceof Error?ye.message:String(ye);g(ge)}})(),()=>{he=!0,w.current===G&&(w.current=null)}},[r,P,m,ae,t,u,p]);const X=()=>!r||K.length===0?null:K.map(G=>e.jsx(Rw,{directory:r,filePath:G.path,isVisible:G.path===m,renderSideBySide:se,wrapLines:C},G.path)),re=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 gap-3 px-3 pb-3 pt-2",children:[I&&e.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:K.length})]}),e.jsx(Ew,{changedFiles:K,selectedFile:m,onSelectFile:H})]}),e.jsx(ht,{ref:A,outerClassName:"flex-1 min-h-0",className:"pr-2",children:e.jsx("div",{className:"flex flex-col gap-3",children:K.map(G=>e.jsx(Lw,{directory:r,file:G,layout:_(G),wrapLines:C,scrollRootRef:A,isSelected:G.path===m,onSelect:z,registerSectionRef:q},G.path))})})]}):null,me=()=>r?l&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ft,{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."}):K.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"}):P?re():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[X(),V&&!O&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:x?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:x}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{g(null),h(G=>G+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ft,{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(Al,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:l&&!a?"Loading changes…":`${K.length} ${K.length===1?"file":"files"} changed`})]}),!E&&e.jsx(Aw,{mode:j,onModeChange:W}),L&&e.jsx(Dw,{changedFiles:K,selectedFile:m,selectedFileEntry:Y,onSelectFile:H,isMobile:E,showModeSelector:E,mode:j,onModeChange:W}),e.jsx("div",{className:"flex-1"}),Y&&e.jsx(ve,{variant:"ghost",size:"sm",onClick:()=>D(!N),className:F("h-5 w-5 p-0 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(am,{className:"size-4"})}),Y&&J&&e.jsx(yf,{mode:J==="side-by-side"?"side-by-side":"unified",onModeChange:B})]}),me()]})},$w=()=>{const{git:t}=Zs(),{currentSessionId:r,sessions:s,worktreeMetadata:n}=fe(),{currentDirectory:o}=gt(),a=r?n.get(r)??void 0:void 0,c=s.find(p=>p.id===r)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:u,fetchStatus:m}=ls(),f=sw(d??null);return i.useEffect(()=>{d&&(u(d),ls.getState().directories.get(d)?.status||m(d,t))},[d,u,m,t]),f},xo=Re.forwardRef(({className:t,...r},s)=>e.jsx(im,{className:F("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-foreground/30",t),style:{width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},...r,ref:s,children:e.jsx(xh,{className:F("pointer-events-none block rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),style:{width:"16px",height:"16px",minWidth:"16px",minHeight:"16px"}})}));xo.displayName=im.displayName;const Bw={},ha=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},pd=t=>ha(t)??"__global__",zw=t=>{const r=Object.entries(t??{}),s=r.filter(([,l])=>l?.status==="connected").length,n=r.length,o=r.some(([,l])=>l?.status==="failed"),a=r.some(([,l])=>l?.status==="needs_auth"||l?.status==="needs_client_registration");return{connected:s,total:n,hasFailed:o,hasAuthRequired:a}},co=os()(us((t,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:s=>{const n=pd(s??gt.getState().currentDirectory);return r().byDirectory[n]??Bw},refresh:async s=>{const n=ha(s?.directory??gt.getState().currentDirectory),o=pd(n);s?.silent||t(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const c=(await Fe.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};t(d=>({byDirectory:{...d.byDirectory,[o]:c},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const l=a instanceof Error?a.message:"Failed to load MCP status";t(c=>({loadingKeys:{...c.loadingKeys,[o]:!1},lastErrorKeys:{...c.lastErrorKeys,[o]:l}}))}},connect:async(s,n)=>{const o=ha(n??gt.getState().currentDirectory);await Fe.getApiClient().mcp.connect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(s,n)=>{const o=ha(n??gt.getState().currentDirectory);await Fe.getApiClient().mcp.disconnect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function Hw(t){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",...t,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 Ww=t=>{if(!t)return"Unknown";switch(t.status){case"connected":return"Connected";case"failed":return`Failed: ${t.error||"Unknown error"}`;case"needs_auth":return"Needs authentication";case"needs_client_registration":return`Needs registration: ${t.error||""}`;default:return t.status}},Uw=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},pl=({headerIconButtonClass:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:l}=Yt(),d=gt(j=>j.currentDirectory)??null,u=co(j=>j.getStatusForDirectory(d)),m=co(j=>j.refresh),f=co(j=>j.connect),p=co(j=>j.disconnect),h=i.useCallback(j=>{j||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),s(j)},[]),x=i.useCallback(j=>{a.current||o(j)},[]),[g,w]=i.useState(!1),[y,v]=i.useState(null);i.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),i.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const S=i.useMemo(()=>zw(u),[u]),k=i.useMemo(()=>Object.keys(u).sort((j,M)=>j.localeCompare(M)),[u]),b=i.useCallback(j=>{if(j?.preventDefault(),g)return;w(!0);const M=new Promise(C=>setTimeout(C,500));Promise.all([m({directory:d}),M]).finally(()=>{w(!1)})},[g,m,d]),N=()=>e.jsxs(e.Fragment,{children:[k.map(j=>{const M=u[j],C=Uw(M),P=M?.status==="connected",E=y===j,I=Ww(M);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l?e.jsx("span",{className:F("h-2 w-2 rounded-full flex-shrink-0",C==="success"&&"bg-status-success",C==="error"&&"bg-status-error",C==="warning"&&"bg-status-warning",C==="default"&&"bg-muted-foreground/40"),"aria-label":I}):e.jsxs(lt,{delayDuration:300,children:[e.jsx(ct,{asChild:!0,children:e.jsx("span",{className:F("h-2 w-2 rounded-full flex-shrink-0",C==="success"&&"bg-status-success",C==="error"&&"bg-status-error",C==="warning"&&"bg-status-warning",C==="default"&&"bg-muted-foreground/40"),"aria-label":I})}),e.jsx(it,{side:"left",children:e.jsx("p",{children:I})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:j})]})}),e.jsx(xo,{checked:P,disabled:E,className:"data-[state=checked]:bg-status-info",onCheckedChange:async A=>{v(j);try{A?await f(j,d):await p(j,d)}finally{v(null)}}})]},j)}),k.length===0&&e.jsx("div",{className:"px-2 py-3 typography-ui-label text-muted-foreground text-center",children:"Configure MCP servers in Opencode config."})]}),D=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:F(t,"relative"),onClick:l?()=>s(!0):void 0,children:[e.jsx(Hw,{className:"h-[1.0625rem] w-[1.0625rem]"}),S.total>0&&e.jsx("span",{className:F("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",S.hasFailed?"bg-status-error":S.hasAuthRequired?"bg-status-warning":S.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return l?e.jsxs(e.Fragment,{children:[D,e.jsxs(Bs,{open:r,title:"MCP Servers",onClose:()=>s(!1),renderHeader:j=>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:g,onClick:b,"aria-label":"Refresh",children:e.jsx(Gr,{className:F("h-4 w-4",g&&"animate-spin")})}),j]})]}),children:[e.jsx("div",{className:"py-1",children:N()}),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(ts,{open:r,onOpenChange:h,children:[e.jsxs(lt,{delayDuration:1e3,open:r?!1:n,onOpenChange:x,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:D})}),e.jsx(it,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(rs,{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:g,onClick:b,"aria-label":"Refresh",children:e.jsx(Gr,{className:F("h-4 w-4",g&&"animate-spin")})})]}),e.jsx(Is,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:N()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Is,{}),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})})]})]})]})},hd=()=>{const t=ke(_=>_.setSessionSwitcherOpen),r=ke(_=>_.toggleSidebar),s=ke(_=>_.setSettingsDialogOpen),n=ke(_=>_.toggleCommandPalette),o=ke(_=>_.toggleHelpDialog),a=ke(_=>_.activeMainTab),l=ke(_=>_.setActiveMainTab),{getCurrentModel:c}=et(),d=fe(_=>_.getContextUsage),{isMobile:u}=Yt(),m=$w(),f=Ka(_=>_.available),p=i.useRef(null),[h,x]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),g=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Re.useEffect(()=>{if(typeof window>"u")return;const _=typeof window.opencodeDesktop<"u";x(_)},[]);const w=c(),y=w&&typeof w.limit=="object"&&w.limit!==null?w.limit:null,v=y&&typeof y.context=="number"?y.context:0,S=y&&typeof y.output=="number"?y.output:0,k=d(v,S),b=ke(_=>_.isSessionSwitcherOpen),N=i.useCallback(()=>{if(typeof document>"u")return;const _=document.activeElement;if(!_)return;const J=_.tagName;(J==="INPUT"||J==="TEXTAREA"||J==="SELECT"||_.isContentEditable)&&_.blur()},[]),D=i.useCallback(()=>{if(u){N(),t(!b);return}r()},[N,u,b,t,r]),j=i.useCallback(()=>{u&&N(),t(!1),s(!0)},[N,u,t,s]),M="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md 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 hover:bg-secondary/50 transition-colors",C=i.useMemo(()=>h&&g?"pl-[5.75rem]":"pl-3",[h,g]),P=i.useCallback(()=>{if(typeof document>"u")return;const _=p.current?.getBoundingClientRect().height;_&&document.documentElement.style.setProperty("--oc-header-height",`${_}px`)},[]);Re.useEffect(()=>{if(typeof window>"u")return;P();const _=p.current;if(!_||typeof ResizeObserver>"u")return()=>{};const J=new ResizeObserver(()=>{P()});return J.observe(_),window.addEventListener("resize",P),window.addEventListener("orientationchange",P),()=>{J.disconnect(),window.removeEventListener("resize",P),window.removeEventListener("orientationchange",P)}},[P]),Re.useEffect(()=>{P()},[P,u]);const E=i.useCallback(async _=>{if(!_.target.closest("button, a, input, select, textarea")&&_.button===0&&h)try{const{getCurrentWindow:J}=await Ss(async()=>{const{getCurrentWindow:Q}=await import("./vendor-.bun-CaD8MAGl.js").then(z=>z.df);return{getCurrentWindow:Q}},__vite__mapDeps([0,1]));await J().startDragging()}catch(J){console.error("Failed to start window dragging:",J)}},[h]),I=i.useCallback(async _=>{if(_.button===0&&h)try{const{getCurrentWindow:J}=await Ss(async()=>{const{getCurrentWindow:Q}=await import("./vendor-.bun-CaD8MAGl.js").then(z=>z.df);return{getCurrentWindow:Q}},__vite__mapDeps([0,1]));await J().startDragging()}catch(J){console.error("Failed to start window dragging:",J)}},[h]),A=i.useMemo(()=>[{id:"chat",label:"Chat",icon:yh},{id:"diff",label:"Diff",icon:Ys,badge:!u&&m>0?m:void 0},{id:"files",label:"Files",icon:nr},{id:"terminal",label:"Terminal",icon:Qr},{id:"git",label:"Git",icon:Kt,showDot:u&&m>0}],[m,u]);Re.useEffect(()=>{const _=J=>{if(Ls(J)&&!J.shiftKey&&!J.altKey){const q=parseInt(J.key,10);q>=1&&q<=A.length&&(J.preventDefault(),l(A[q-1].id))}};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[A,l]);const T=_=>{const J=a===_.id,q=_.icon,Q=_.id==="chat";return e.jsxs("button",{type:"button",onClick:()=>l(_.id),onMouseDown:J?I:void 0,className:F("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",J?"app-region-drag bg-secondary text-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-secondary/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",Q&&!u&&"min-w-[100px] justify-center"),"aria-label":_.label,"aria-selected":J,role:"tab",children:[u?e.jsx(q,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16}),e.jsx("span",{className:"header-tab-label",children:_.label})]}),Q&&!u&&k&&k.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(ul,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})}),_.badge!==void 0&&_.badge>0&&e.jsx("span",{className:"ml-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-primary/10 px-1 text-[10px] font-bold text-primary",children:_.badge})]},_.id)},R=()=>e.jsxs("div",{onMouseDown:E,className:F("app-region-drag relative flex h-12 select-none items-center",C),role:"tablist","aria-label":"Main navigation",children:[e.jsx("button",{type:"button",onClick:D,"aria-label":"Open sessions",className:`${M} mr-2`,children:e.jsx(Il,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-background/50 rounded-lg",children:A.map(_=>T(_))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:M,children:e.jsx(vn,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Command Palette (",Zt(),"+K)"]})})]}),e.jsx(pl,{headerIconButtonClass:M}),e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:M,children:e.jsx(hn,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Zt(),"+.)"]})})]})]})]}),K=()=>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:[b?e.jsx("button",{onClick:()=>t(!1),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 rounded-md active:bg-secondary","aria-label":"Back",children:e.jsx(El,{className:"h-5 w-5"})}):e.jsx("button",{onClick:D,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 rounded-md active:bg-secondary","aria-label":"Open sessions",children:e.jsx(bh,{className:"h-5 w-5"})}),!b&&k&&k.totalTokens>0&&a==="chat"&&e.jsx(ul,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact",isMobile:!0}),b&&e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),!b&&e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1",children:[e.jsx("div",{className:"flex items-center gap-0.5",role:"tablist","aria-label":"Main navigation",children:A.map(_=>{const J=a===_.id,q=_.icon;return e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{u&&N(),l(_.id)},"aria-label":_.label,"aria-selected":J,role:"tab",className:F(M,"relative",J&&"text-foreground bg-secondary"),children:[e.jsx(q,{className:"h-5 w-5"}),_.badge!==void 0&&_.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:_.badge}),_.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(it,{children:e.jsx("p",{children:_.label})})]},_.id)})}),e.jsx(pl,{headerIconButtonClass:M}),e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:j,"aria-label":"Open settings",className:F(M,"relative"),children:[e.jsx(pn,{className:"h-5 w-5"}),f&&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(it,{children:e.jsx("p",{children:f?"Settings (Update available)":"Settings"})})]})]})]}),Y=F("header-safe-area border-b border-border/50 relative z-10",h?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:p,className:Y,style:{"--padding-scale":"1"},children:u?K():R()})};function sc({className:t,...r}){return e.jsx("div",{"data-slot":"card",className:F("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",t),...r})}function kf({className:t,...r}){return e.jsx("div",{"data-slot":"card-header",className:F("@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",t),...r})}function Cf({className:t,...r}){return e.jsx("div",{"data-slot":"card-title",className:F("leading-none font-semibold",t),...r})}function Mf({className:t,...r}){return e.jsx("div",{"data-slot":"card-content",className:F("px-6",t),...r})}class gs extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){this.setState({error:r,errorInfo:s})}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(sc,{className:"w-full max-w-md",children:[e.jsx(kf,{className:"text-center",children:e.jsxs(Cf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Zi,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Mf,{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(ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ts,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let Vo=0;function ps({...t}){return e.jsx(wh,{"data-slot":"dialog",...t})}function Vw({...t}){return e.jsx(Sh,{"data-slot":"dialog-portal",...t})}const Df=Re.forwardRef(({className:t,...r},s)=>(Re.useEffect(()=>(Vo+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Vo=Math.max(0,Vo-1),Vo===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(lm,{ref:s,"data-slot":"dialog-overlay",className:F("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",t),...r})));Df.displayName=lm.displayName;function hs({className:t,children:r,showCloseButton:s=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Vw,{"data-slot":"dialog-portal",children:[e.jsx(Df,{className:"rounded-none"}),e.jsxs(vh,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:F("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",t),...o,children:[r,s&&e.jsxs(jh,{"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(es,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ys({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:F("flex flex-col gap-2 text-center sm:text-left",t),...r})}function Us({className:t,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:F("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",t),...r})}function bs({className:t,...r}){return e.jsx(Nh,{"data-slot":"dialog-title",className:F("typography-markdown leading-none font-semibold text-foreground",t),...r})}function ks({className:t,...r}){return e.jsx(kh,{"data-slot":"dialog-description",className:F("text-muted-foreground typography-ui-label",t),...r})}const gd="https://github.com/btriapitsyn/openchamber/releases";async function Gw(){try{const t=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return t.ok?{success:!0}:{success:!1,error:(await t.json().catch(()=>({}))).error||`Server error: ${t.status}`}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Failed to install update"}}}async function qw(t=30,r=2e3){for(let s=0;s<t;s++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,r))}return!1}const hl=({open:t,onOpenChange:r,info:s,downloading:n,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Re.useState(!1),[p,h]=Re.useState("idle"),[x,g]=Re.useState(null),w=s?.version?`${gd}/tag/v${s.version}`:gd,y=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",S=s?.updateCommand||"openchamber update";Re.useEffect(()=>{t||(h("idle"),g(null))},[t]);const k=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},b=Re.useCallback(async()=>{h("updating"),g(null);const D=await Gw();if(!D.success){h("error"),g(D.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await qw()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),N=p!=="idle"&&p!=="error";return e.jsx(ps,{open:t,onOpenChange:N?void 0:r,children:e.jsxs(hs,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Ch,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(s?.currentVersion||s?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[s?.currentVersion&&e.jsx("span",{className:"font-mono",children:s.currentVersion}),s?.currentVersion&&s?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),s?.version&&e.jsx("span",{className:"font-mono text-primary",children:s.version})]}),v&&N&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(na,{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."})]}),s?.body&&!N&&e.jsx(ht,{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:s.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((D,j)=>/^\d+\.\d+\.\d+$/.test(D.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",D.trim(),`
82
- `]},j):D.replace(/^- /gm,"• ").trim()+`
83
-
84
- `)})}),v&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Mh,{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:S}),e.jsx("button",{onClick:k,className:F("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(Qt,{className:"h-4 w-4"}):e.jsx(cm,{className:"h-4 w-4"})})]})]}),!v&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[y,"%"]})]}),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:`${y}%`}})})]}),(l||x)&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:l||x})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:F("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(dr,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:c,className:F("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(qr,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:F("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(na,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:F("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(Ts,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!N&&e.jsxs("button",{onClick:b,className:F("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(qr,{className:"h-4 w-4"}),"Update Now"]}),v&&N&&e.jsxs("button",{disabled:!0,className:F("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(na,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},xd=264,yd=200,bd=500,wd="openchamber:check-for-updates",Kw=({isOpen:t,isMobile:r,children:s})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:l}=ke(),[c,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||xd),[f,p]=i.useState(!1),h=Ka(),x=i.useRef(!1),g=h.checkForUpdates,{available:w,downloaded:y,checking:v}=h,[S,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");if(i.useEffect(()=>{if(typeof window>"u")return;const D=typeof window.opencodeDesktop<"u";k(D)},[]),i.useEffect(()=>{if(typeof window>"u")return;const D=()=>{typeof window.opencodeDesktop<"u"&&(x.current=!0,g())};return window.addEventListener(wd,D),()=>{window.removeEventListener(wd,D)}},[g]),i.useEffect(()=>{x.current&&(v||(w||y?p(!0):U.success("No updates available",{description:"You are running the latest version."}),x.current=!1))},[w,y,v]),i.useEffect(()=>{if(r||!c)return;const D=M=>{const C=M.clientX-u.current,P=Math.min(bd,Math.max(yd,m.current+C));o(P)},j=()=>{d(!1)};return window.addEventListener("pointermove",D),window.addEventListener("pointerup",j,{once:!0}),()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",j)}},[r,c,o]),i.useEffect(()=>{r&&c&&d(!1)},[r,c]),r)return null;const b=t?Math.min(bd,Math.max(yd,n||xd)):0,N=D=>{t&&(d(!0),u.current=D.clientX,m.current=b,D.preventDefault())};return e.jsxs("aside",{className:F("relative flex h-full overflow-hidden border-r border-border",S?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",c?"transition-none":"transition-[width] duration-300 ease-in-out",!t&&"border-r-0"),style:{width:`${b}px`,minWidth:`${b}px`,maxWidth:`${b}px`,overflowX:"clip"},"aria-hidden":!t||b===0,children:[t&&e.jsx("div",{className:F("absolute right-0 top-0 z-20 h-full w-[4px] cursor-col-resize hover:bg-primary/50 transition-colors",c&&"bg-primary"),onPointerDown:N,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:F("relative z-10 flex h-full flex-col transition-opacity duration-300 ease-in-out",!t&&"pointer-events-none select-none opacity-0"),style:{width:`${b}px`,overflowX:"hidden"},"aria-hidden":!t,children:[e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(gs,{children:s})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border h-12 px-2 bg-sidebar-accent/10",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:F("flex h-8 items-center gap-2 rounded-md px-2","text-sm font-semibold text-sidebar-foreground/90","hover:text-sidebar-foreground hover:bg-sidebar-accent","transition-all duration-200"),children:[e.jsx(pn,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),w||y?e.jsxs("button",{onClick:()=>p(!0),className:F("flex items-center gap-1.5 rounded-md px-2 py-1","text-xs font-semibold","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(qr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!S&&e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{onClick:()=>l(!0),className:F("flex h-8 w-8 items-center justify-center rounded-md","text-sidebar-foreground/70","hover:text-sidebar-foreground hover:bg-sidebar-accent","transition-all duration-200"),children:e.jsx(xs,{className:"h-4 w-4"})})}),e.jsx(it,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(hl,{open:f,onOpenChange:p,info:h.info,downloading:h.downloading,downloaded:h.downloaded,progress:h.progress,error:h.error,onDownload:h.downloadUpdate,onRestart:h.restartToUpdate,runtimeType:h.runtimeType})]})]})};function rc({className:t,...r}){return e.jsx(jn,{"data-slot":"command",className:F("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",t),...r})}function Qw({title:t="Command Palette",description:r="Search for a command to run...",children:s,className:n,showCloseButton:o=!0,...a}){return e.jsxs(ps,{...a,children:[e.jsxs(ys,{className:"sr-only",children:[e.jsx(bs,{children:t}),e.jsx(ks,{children:r})]}),e.jsx(hs,{className:F("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(rc,{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:s})})]})}function nc({className:t,...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(Ws,{className:"size-4 shrink-0 opacity-50"}),e.jsx(jn.Input,{"data-slot":"command-input",className:F("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",t),...r})]})}function oc({className:t,children:r,scrollbarClassName:s,disableHorizontal:n,...o}){return e.jsx(ht,{as:jn.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:F("scroll-py-1 overflow-x-hidden h-full min-h-0",t),scrollbarClassName:s??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:r})}function ac({...t}){return e.jsx(jn.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...t})}function un({className:t,...r}){return e.jsx(jn.Group,{"data-slot":"command-group",className:F("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",t),...r})}function Ra({className:t,...r}){return e.jsx(jn.Separator,{"data-slot":"command-separator",className:F("bg-border -mx-1 h-px",t),...r})}function js({className:t,...r}){return e.jsx(jn.Item,{"data-slot":"command-item",className:F("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",t),...r})}function Cr({className:t,...r}){const s=a=>{const l=a.trim().toLowerCase();return l==="ctrl"||l==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):l==="cmd"||l==="⌘"||l==="command"||l==="meta"?e.jsx(vn,{className:"size-3.5"}):l==="shift"||l==="⇧"?e.jsx(Do,{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:F("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",t),...r,children:o.length>0?o.map((a,l)=>e.jsxs(Re.Fragment,{children:[l>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),s(a)]},`${a}-${l}`)):r.children})}const vd=["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"],jd=["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 Af(){const t=vd[Math.floor(Math.random()*vd.length)],r=jd[Math.floor(Math.random()*jd.length)];return`${t}-${r}`}function Sd(t){const r=Af();return t&&t.trim()?`${t.trim().replace(/\/+$/,"")}/${r}`:r}async function Yw(t,r,s=10){let n;try{const o=await Ja(t);n=new Set(o?.all??[])}catch{return Sd(r)}for(let o=0;o<s;o++){const a=Sd(r);if(!n.has(a))return a}return null}const ic=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Tr=!1;async function si(){if(Tr)return null;const t=zt.getState().getActiveProject();if(!t?.path)return U.error("No active project",{description:"Please select a project first."}),null;const r=t.path;let s=!1;try{s=await Or(r)}catch{}if(!s)return U.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Tr=!0,Hs("Creating new worktree session...");try{const n=t.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,l=await Yw(r,o);if(!l)return U.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const c=ic(l),u=await Za({projectDirectory:r,worktreeSlug:c,branch:l,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await Eo(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=fe.getState(),h=await p.createSession(void 0,u.path);if(!h)return await Ul({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),U.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const x=et.getState(),g=x.agents;p.initializeNewOpenChamberSession(h.id,g),p.setSessionDirectory(h.id,u.path),p.setWorktreeMetadata(h.id,f);try{const v=x.getVisibleAgents();let S;if(x.settingsDefaultAgent){const k=v.find(b=>b.name===x.settingsDefaultAgent);k&&(S=k.name)}if(S||(S=v.find(k=>k.name==="build")?.name||v[0]?.name),S){x.setAgent(S),at.getState().saveSessionAgentSelection(h.id,S);const k=x.settingsDefaultModel;if(k){const b=k.split("/");if(b.length===2){const[N,D]=b;if(x.getModelMetadata(N,D)){at.getState().saveSessionModelSelection(h.id,N,D),at.getState().saveAgentModelForSession(h.id,S,N,D);const M=x.settingsDefaultVariant;if(M){const E=x.providers.find(I=>I.id===N)?.models.find(I=>I.id===D)?.variants;E&&Object.prototype.hasOwnProperty.call(E,M)&&(x.setCurrentVariant(M),at.getState().saveAgentModelVariantForSession(h.id,S,N,D,M))}}}}}}catch{}gt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const y=(await Sn(r)).filter(v=>v.trim().length>0);return y.length>0?(U.success("Worktree created",{description:`Branch: ${l}. Running ${y.length} setup command${y.length===1?"":"s"}...`}),ei(u.path,r,y).then(v=>{if(v.success)U.success("Setup commands completed",{description:`All ${v.results.length} command${v.results.length===1?"":"s"} succeeded.`});else{const S=v.results.filter(b=>!b.success),k=v.results.filter(b=>b.success);U.error("Setup commands failed",{description:`${S.length} of ${v.results.length} command${v.results.length===1?"":"s"} failed.`+(k.length>0?` ${k.length} succeeded.`:"")})}}).catch(()=>{U.error("Setup commands failed",{description:"Could not execute setup commands."})})):U.success("Worktree created",{description:`Branch: ${l}`}),h}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return U.error("Failed to create worktree",{description:o}),null}finally{Fs(),Tr=!1}}async function Xw(t,r){if(Tr)return null;let s=!1;try{s=await Or(t)}catch{}if(!s)return U.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Tr=!0,Hs("Creating worktree session...");try{const n=ic(r),o=await Za({projectDirectory:t,worktreeSlug:n,branch:r,createBranch:!1}),a=await Eo(o.path).catch(()=>{}),l=a?{...o,status:a}:o,c=fe.getState(),d=await c.createSession(void 0,o.path);if(!d)return await Ul({projectDirectory:t,path:o.path,force:!0}).catch(()=>{}),U.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const u=et.getState(),m=u.agents;c.initializeNewOpenChamberSession(d.id,m),c.setSessionDirectory(d.id,o.path),c.setWorktreeMetadata(d.id,l);try{const h=u.getVisibleAgents();let x;if(u.settingsDefaultAgent){const g=h.find(w=>w.name===u.settingsDefaultAgent);g&&(x=g.name)}if(x||(x=h.find(g=>g.name==="build")?.name||h[0]?.name),x){u.setAgent(x),at.getState().saveSessionAgentSelection(d.id,x);const g=u.settingsDefaultModel;if(g){const w=g.split("/");if(w.length===2){const[y,v]=w;if(u.getModelMetadata(y,v)){at.getState().saveSessionModelSelection(d.id,y,v),at.getState().saveAgentModelForSession(d.id,x,y,v);const k=u.settingsDefaultVariant;if(k){const D=u.providers.find(j=>j.id===y)?.models.find(j=>j.id===v)?.variants;D&&Object.prototype.hasOwnProperty.call(D,k)&&(u.setCurrentVariant(k),at.getState().saveAgentModelVariantForSession(d.id,x,y,v,k))}}}}}}catch{}gt.getState().setDirectory(o.path,{showOverlay:!1});try{await c.loadSessions()}catch{}const p=(await Sn(t)).filter(h=>h.trim().length>0);return p.length>0?(U.success("Worktree created",{description:`Branch: ${r}. Running ${p.length} setup command${p.length===1?"":"s"}...`}),ei(o.path,t,p).then(h=>{if(h.success)U.success("Setup commands completed",{description:`All ${h.results.length} command${h.results.length===1?"":"s"} succeeded.`});else{const x=h.results.filter(w=>!w.success),g=h.results.filter(w=>w.success);U.error("Setup commands failed",{description:`${x.length} of ${h.results.length} command${h.results.length===1?"":"s"} failed.`+(g.length>0?` ${g.length} succeeded.`:"")})}}).catch(()=>{U.error("Setup commands failed",{description:"Could not execute setup commands."})})):U.success("Worktree created",{description:`Branch: ${r}`}),d}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return U.error("Failed to create worktree",{description:o}),null}finally{Fs(),Tr=!1}}async function Ef(t,r,s,n){if(Tr)return null;let o=!1;try{o=await Or(t)}catch{}if(!o)return U.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Tr=!0,Hs("Creating worktree session...");try{const a=s?.trim()||"HEAD",l=r?.trim();if(!l)throw new Error("Branch name is required");let c=null;const u=n?.allowSuffix!==!1?6:1;for(let f=0;f<u;f+=1){const p=f===0?l:`${l}-${f+1}`;try{const h=ic(p),x=await Za({projectDirectory:t,worktreeSlug:h,branch:p,createBranch:!0,startPoint:a}),g=await Eo(x.path).catch(()=>{}),w=g?{...x,status:g}:x,y=fe.getState(),v=await y.createSession(void 0,x.path);if(!v)throw await Ul({projectDirectory:t,path:x.path,force:!0}).catch(()=>{}),new Error("Could not create a session for the worktree.");const S=et.getState();y.initializeNewOpenChamberSession(v.id,S.agents),y.setSessionDirectory(v.id,x.path),y.setWorktreeMetadata(v.id,w);try{const N=S.getVisibleAgents();let D;if(S.settingsDefaultAgent){const j=N.find(M=>M.name===S.settingsDefaultAgent);j&&(D=j.name)}if(D||(D=N.find(j=>j.name==="build")?.name||N[0]?.name),D){S.setAgent(D),at.getState().saveSessionAgentSelection(v.id,D);const j=S.settingsDefaultModel;if(j){const M=j.split("/");if(M.length===2){const[C,P]=M;if(S.getModelMetadata(C,P)){at.getState().saveSessionModelSelection(v.id,C,P),at.getState().saveAgentModelForSession(v.id,D,C,P);const I=S.settingsDefaultVariant;if(I){const R=S.providers.find(K=>K.id===C)?.models.find(K=>K.id===P)?.variants;R&&Object.prototype.hasOwnProperty.call(R,I)&&(S.setCurrentVariant(I),at.getState().saveAgentModelVariantForSession(v.id,D,C,P,I))}}}}}}catch{}gt.getState().setDirectory(x.path,{showOverlay:!1});try{await y.loadSessions()}catch{}const b=(await Sn(t)).filter(N=>N.trim().length>0);return b.length>0?(U.success("Worktree created",{description:`Branch: ${p}. Running ${b.length} setup command${b.length===1?"":"s"}...`}),ei(x.path,t,b).then(N=>{if(N.success)U.success("Setup commands completed",{description:`All ${N.results.length} command${N.results.length===1?"":"s"} succeeded.`});else{const D=N.results.filter(M=>!M.success),j=N.results.filter(M=>M.success);U.error("Setup commands failed",{description:`${D.length} of ${N.results.length} command${N.results.length===1?"":"s"} failed.`+(j.length>0?` ${j.length} succeeded.`:"")})}}).catch(()=>{U.error("Setup commands failed",{description:"Could not execute setup commands."})})):U.success("Worktree created",{description:`Branch: ${p}`}),{id:v.id,branch:p}}catch(h){c=h}}const m=c instanceof Error?c.message:"Failed to create worktree session";return U.error("Failed to create worktree",{description:m}),null}finally{Fs(),Tr=!1}}async function Jw(t,r,s){return Ef(t,r,s,{allowSuffix:!1})}const Zw=()=>{const{isCommandPaletteOpen:t,setCommandPaletteOpen:r,setHelpDialogOpen:s,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:l,toggleSidebar:c}=ke(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=fe(),f=et(T=>T.settingsAutoCreateWorktree),{currentDirectory:p}=gt(),{themeMode:h,setThemeMode:x}=en(),g=()=>{r(!1)},w=async()=>{n("chat"),a(!1),d(),g()},y=T=>{u(T),g()},v=T=>{x(T),g()},S=()=>{s(!0),g()},k=()=>{g(),si()},{isMobile:b}=Yt(),N=()=>{if(b){const{isSessionSwitcherOpen:T}=ke.getState();a(!T)}else c();g()},D=()=>{n("diff"),g()},j=()=>{n("git"),g()},M=()=>{n("terminal"),g()},C=()=>{o(!0),g()},P=()=>{po(),g()},E=()=>{l(!0),g()},I=m(p??""),A=i.useMemo(()=>I.slice(0,5),[I]);return e.jsxs(Qw,{open:t,onOpenChange:r,children:[e.jsx(nc,{placeholder:"Type a command or search..."}),e.jsxs(oc,{children:[e.jsx(ac,{children:"No results found."}),e.jsxs(un,{heading:"Actions",children:[e.jsxs(js,{onSelect:N,children:[e.jsx(Il,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(Cr,{children:[Zt()," + L"]})]}),e.jsxs(js,{onSelect:w,children:[e.jsx(cs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Cr,{children:f?`Shift + ${Zt()} + N`:`${Zt()} + N`})]}),e.jsxs(js,{onSelect:k,children:[e.jsx(Kt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Cr,{children:f?`${Zt()} + N`:`Shift + ${Zt()} + N`})]}),e.jsxs(js,{onSelect:S,children:[e.jsx(hn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(Cr,{children:[Zt()," + ."]})]}),e.jsxs(js,{onSelect:D,children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(Cr,{children:[Zt()," + 2"]})]}),e.jsxs(js,{onSelect:M,children:[e.jsx(Qr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(Cr,{children:[Zt()," + 3"]})]}),e.jsxs(js,{onSelect:j,children:[e.jsx(Kt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(Cr,{children:[Zt()," + 4"]})]}),e.jsxs(js,{onSelect:E,children:[e.jsx(jr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(Cr,{children:[Zt()," + T"]})]}),e.jsxs(js,{onSelect:C,children:[e.jsx(pn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(Cr,{children:[Zt()," + ,"]})]}),e.jsxs(js,{onSelect:P,children:[e.jsx(Ts,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Ra,{}),e.jsxs(un,{heading:"Theme",children:[e.jsxs(js,{onSelect:()=>v("light"),children:[e.jsx(Dh,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Qt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(js,{onSelect:()=>v("dark"),children:[e.jsx(Ah,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Qt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(js,{onSelect:()=>v("system"),children:[e.jsx(dm,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Qt,{className:"ml-auto h-4 w-4"})]})]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ra,{}),e.jsx(un,{heading:"Recent Sessions",children:A.map(T=>e.jsxs(js,{onSelect:()=>y(T.id),children:[e.jsx(Pl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:T.title||"Untitled Session"})]},T.id))})]})]})]})},ev=(t,r)=>{const s=t.trim().toLowerCase();return s==="ctrl"||s==="control"?e.jsx(Wa,{className:"h-3.5 w-3.5"},`ctrl-${r}`):s==="⌘"||s==="cmd"||s==="command"||s==="meta"?e.jsx(vn,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:t.trim()},`key-${r}`)},tv=t=>{const r=t.split("+").map(s=>s.trim()).filter(Boolean);return r.length===0?t.trim():r.map((s,n)=>e.jsxs(i.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),ev(s,n)]},`${s}-${n}`))},sv=()=>{const{isHelpDialogOpen:t,setHelpDialogOpen:r}=ke(),s=et(a=>a.settingsAutoCreateWorktree),n=Zt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:vn},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:hn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:Il},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:gn},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:Tl},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:Sr}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:s?"Create New Session in Worktree":"Create New Session",icon:s?Kt:cs},{keys:[`Shift + ${n} + N`],description:s?"Create New Session":"Create New Session in Worktree",icon:s?cs:Kt},{keys:[`${n} + I`],description:"Focus Chat Input",icon:um},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:zn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Eh},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:Ys},{keys:[`${n} + 3`],description:"Open Files",icon:nr},{keys:[`${n} + 4`],description:"Open Terminal",icon:Qr},{keys:[`${n} + 5`],description:"Open Git Panel",icon:Kt},{keys:[`${n} + T`],description:"Open Timeline",icon:jr},{keys:[`${n} + ,`],description:"Open Settings",icon:pn}]}];return e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{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(pn,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(ks,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((l,c)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.icon&&e.jsx(l.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:l.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l.keys)?l.keys:l.keys.split(" / ")).map((d,u)=>e.jsxs(i.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:tv(d)})]},`${d}-${u}`))})]},c))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(hn,{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"})]})]})]})})]})]})})},rv={xs:{container:"gap-[1px]",dot:"h-[3px] w-[3px]"},sm:{container:"gap-0.5",dot:"h-1 w-1"},md:{container:"gap-1",dot:"h-1.5 w-1.5"},lg:{container:"gap-1.5",dot:"h-2 w-2"}},If=({className:t,size:r="md"})=>{const s=rv[r];return e.jsx("div",{className:F("grid grid-cols-3",s.container,t),"aria-label":"Loading",children:Array.from({length:9},(n,o)=>e.jsx("div",{className:F("rounded-full bg-current animate-grid-pulse",s.dot),style:{animationDelay:`${(o%3+Math.floor(o/3))*150}ms`}},o))})},Ai=new Set,Ei=new Set,Ii=new Set,qn={onDeleteRequest(t){return Ai.add(t),()=>{Ai.delete(t)}},requestDelete(t){!t.sessions.length&&t.mode!=="worktree"||Ai.forEach(r=>r(t))},onCreateRequest(t){return Ei.add(t),()=>{Ei.delete(t)}},requestCreate(t){const r=t??{};Ei.forEach(s=>s(r))},onDirectoryRequest(t){return Ii.add(t),()=>{Ii.delete(t)}},requestDirectoryDialog(){Ii.forEach(t=>t())}};function Pf(t){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...t,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)"})})}function bt({className:t,type:r,...s}){return e.jsx("input",{type:r,"data-slot":"input",className:F("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",t),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...s})}function nv({open:t,onOpenChange:r,projects:s,activeProjectId:n}){const[o,a]=i.useState(""),[l,c]=i.useState(new Map),[d,u]=i.useState(new Set),[m,f]=i.useState(null);i.useEffect(()=>{if(!t){a("");return}const w=s.find(y=>y.id===n);w&&u(new Set([w.id])),s.forEach(async y=>{c(v=>{const S=new Map(v);return S.set(y.id,{branches:null,worktrees:[],loading:!0,error:null}),S});try{const[v,S]=await Promise.all([Ja(y.path),Ym(y.path)]);c(k=>{const b=new Map(k);return b.set(y.id,{branches:v,worktrees:S,loading:!1,error:null}),b})}catch(v){c(S=>{const k=new Map(S);return k.set(y.id,{branches:null,worktrees:[],loading:!1,error:v instanceof Error?v.message:"Failed to load"}),k})}})},[t,s,n]);const p=w=>{u(y=>{const v=new Set(y);return v.has(w)?v.delete(w):v.add(w),v})},h=async(w,y)=>{const v=`${w.id}:${y}`;f(v);try{await Xw(w.path,y),r(!1)}catch(S){console.error("Failed to create worktree:",S)}finally{f(null)}},x=(w,y)=>{if(!y.trim())return w;const v=y.toLowerCase();return w.filter(S=>S.toLowerCase().includes(v))},g=s.filter(w=>{const y=l.get(w.id);return y&&!y.error&&(y.loading||y.branches)});return e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{className:"max-w-2xl max-h-[70vh] flex flex-col overflow-hidden gap-3",children:[e.jsxs(ys,{className:"flex-shrink-0",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Kt,{className:"h-5 w-5"}),"Branches & Worktrees"]}),e.jsx(ks,{children:"Start a new worktree session from any local branch"})]}),e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(bt,{placeholder:"Search branches...",value:o,onChange:w=>a(w.target.value),className:"pl-9"})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"space-y-1",children:g.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No git repositories found"}):g.map(w=>{const y=l.get(w.id),v=d.has(w.id),S=y?.branches,k=y?.worktrees||[],b=new Set(k.map(M=>M.branch).filter(Boolean)),N=S?.all||[],j=x(N,o).filter(M=>!M.startsWith("remotes/")).filter(M=>!b.has(M));return e.jsxs("div",{className:"rounded-md",children:[e.jsxs("button",{type:"button",onClick:()=>p(w.id),className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/30 transition-colors rounded-md",children:[e.jsx(zs,{className:F("h-4 w-4 text-muted-foreground transition-transform",v&&"rotate-90")}),e.jsx(ur,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm truncate flex-1 text-left",children:w.label||w.normalizedPath.split("/").pop()||w.normalizedPath}),y?.loading&&e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground animate-spin"}),S&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[j.length," branches"]})]}),v&&e.jsx("div",{className:"mt-1 space-y-1 pl-6",children:y?.loading?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading branches..."}):y?.error?e.jsx("div",{className:"px-2 py-2 text-destructive text-sm",children:y.error}):j.length===0?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:o?"No matching branches":"No branches found"}):j.map(M=>{const C=S?.branches[M],P=C?.current,E=m===`${w.id}:${M}`;return e.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5 hover:bg-muted/30 rounded-md overflow-hidden",children:[e.jsx(Kt,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:F("text-sm truncate",P&&"font-medium text-primary"),children:M}),P&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded flex-shrink-0 whitespace-nowrap",children:"current"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[C?.commit&&e.jsx("span",{className:"font-mono",children:C.commit.slice(0,7)}),C?.ahead!==void 0&&C.ahead>0&&e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["↑",C.ahead]}),C?.behind!==void 0&&C.behind>0&&e.jsxs("span",{className:"text-[color:var(--status-warning)]",children:["↓",C.behind]})]})]}),e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>h(w,M),disabled:E,className:"inline-flex h-7 px-2 items-center justify-center text-xs rounded-md bg-primary/10 hover:bg-primary/20 text-primary transition-colors disabled:opacity-50 flex-shrink-0",children:E?e.jsx(Ft,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"h-3.5 w-3.5 mr-1"}),"Worktree"]})})}),e.jsx(it,{side:"left",children:"Create worktree for this branch"})]})]},M)})})]},w.id)})})})]})})}const ov=t=>{const r=t.trim();if(!r)return null;const s=r.match(/\/issues\/(\d+)(?:\b|\/|$)/i);if(s){const o=Number(s[1]);return Number.isFinite(o)&&o>0?o:null}const n=r.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},av=t=>{const r={repo:t.repo??null,issue:t.issue,comments:t.comments};return`GitHub issue context (JSON)
85
- ${JSON.stringify(r,null,2)}`};function iv({open:t,onOpenChange:r}){const{github:s}=Zs(),n=ke(z=>z.setSettingsDialogOpen),o=ke(z=>z.setSidebarSection),a=zt(z=>z.getActiveProject()),l=a?.path??null,c=a?.worktreeDefaults?.baseBranch||"main",[d,u]=i.useState(""),[m,f]=i.useState(!1),[p,h]=i.useState(null),[x,g]=i.useState([]),[w,y]=i.useState(1),[v,S]=i.useState(!1),[k,b]=i.useState(null),[N,D]=i.useState(!1),[j,M]=i.useState(!1),[C,P]=i.useState(null),E=i.useCallback(async()=>{if(!l){h(null),P("No active project");return}if(!s?.issuesList){h(null),P("GitHub runtime API unavailable");return}D(!0),P(null);try{const z=await s.issuesList(l,{page:1});h(z),g(z.issues??[]),y(z.page??1),S(!!z.hasMore),z.connected===!1&&P(null)}catch(z){P(z instanceof Error?z.message:String(z))}finally{D(!1)}},[s,l]),I=i.useCallback(async()=>{if(l&&s?.issuesList&&!(j||N)&&v){M(!0);try{const z=w+1,H=await s.issuesList(l,{page:z});h(H),g(W=>[...W,...H.issues??[]]),y(H.page??z),S(!!H.hasMore)}catch(z){const H=z instanceof Error?z.message:String(z);U.error("Failed to load more issues",{description:H})}finally{M(!1)}}},[s,v,N,j,w,l]);i.useEffect(()=>{if(!t){u(""),f(!1),b(null),P(null),h(null),g([]),y(1),S(!1),D(!1);return}E()},[t,E]);const A=!!p?.connected,T=p?.repo?.url??null,R=i.useCallback(()=>{o("settings"),n(!0)},[n,o]),K=i.useMemo(()=>{const z=d.trim().toLowerCase();return z?x.filter(H=>String(H.number)===z.replace(/^#/,"")?!0:H.title.toLowerCase().includes(z)):x},[x,d]),Y=i.useMemo(()=>ov(d),[d]),_=i.useCallback(()=>{const z=et.getState(),H=z.getVisibleAgents();if(z.settingsDefaultAgent){const W=H.find(B=>B.name===z.settingsDefaultAgent);if(W)return W.name}return H.find(W=>W.name==="build")?.name||H[0]?.name},[]),J=i.useCallback(()=>{const z=et.getState(),H=z.settingsDefaultModel;if(!H)return null;const W=H.split("/");if(W.length!==2)return null;const[B,se]=W;return!B||!se||!z.getModelMetadata(B,se)?null:{providerID:B,modelID:se}},[]),q=i.useCallback((z,H)=>{const W=et.getState(),B=W.settingsDefaultVariant;if(!B)return;const ae=W.providers.find(O=>O.id===z)?.models.find(O=>O.id===H)?.variants;if(ae&&Object.prototype.hasOwnProperty.call(ae,B))return B},[]),Q=i.useCallback(async z=>{if(!l){U.error("No active project");return}if(!s?.issueGet||!s?.issueComments){U.error("GitHub runtime API unavailable");return}if(!k){b(z);try{const H=await s.issueGet(l,z);if(H.connected===!1){U.error("GitHub not connected");return}if(!H.repo){U.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}const W=H.issue;if(!W){U.error("Issue not found");return}const B=await s.issueComments(l,z);if(B.connected===!1){U.error("GitHub not connected");return}const se=B.comments??[],L=`#${W.number} ${W.title}`.trim(),ae=await(async()=>{if(m){const Z=`issue-${W.number}-${Af()}`,ie=await Ef(l,Z,c||"main");if(!ie?.id)throw new Error("Failed to create worktree session");return ie.id}const ee=await fe.getState().createSession(L,l,null);if(!ee?.id)throw new Error("Failed to create session");return ee.id})();fe.getState().updateSessionTitle(ae,L).catch(()=>{});try{fe.getState().initializeNewOpenChamberSession(ae,et.getState().agents)}catch{}r(!1);const O=et.getState(),V=kt.getState().lastUsedProvider,X=J(),re=X?.providerID||O.currentProviderId||V?.providerID,me=X?.modelID||O.currentModelId||V?.modelID,G=_()||O.currentAgentName||void 0;if(!re||!me){U.error("No model selected");return}const he=q(re,me);try{at.getState().saveSessionModelSelection(ae,re,me)}catch{}if(G){try{O.setAgent(G)}catch{}try{at.getState().saveSessionAgentSelection(ae,G)}catch{}try{at.getState().saveAgentModelForSession(ae,G,re,me)}catch{}if(he!==void 0){try{O.setCurrentVariant(he)}catch{}try{at.getState().saveAgentModelVariantForSession(ae,G,re,me,he)}catch{}}}const ye="Review this issue using the provided issue context: title, body, labels, assignees, comments, metadata.",ge=`Review this issue using the provided issue context.
86
-
87
- Process:
88
- - First classify the issue type (bug / feature request / question/support / refactor / ops) and state it as: Type: <one label>.
89
- - Gather any needed repository context (code, config, docs) to validate assumptions.
90
- - After gathering, if anything is still unclear or cannot be verified, do not speculate—state what’s missing and ask targeted questions.
91
-
92
- Output rules:
93
- - Compact output; pick ONE template below and omit the others.
94
- - No emojis. No code snippets. No fenced blocks.
95
- - Short inline code identifiers allowed.
96
- - Reference evidence with file paths and line ranges when applicable; if exact lines aren’t available, cite the file and say “approx” + why.
97
- - Keep the entire response under ~300 words.
98
-
99
- Templates (choose one):
100
- Bug:
101
- - Summary (1-2 sentences)
102
- - Likely cause (max 2)
103
- - Repro/diagnostics needed (max 3)
104
- - Fix approach (max 4 steps)
105
- - Verification (max 3)
106
-
107
- Feature:
108
- - Summary (1-2 sentences)
109
- - Requirements (max 4)
110
- - Unknowns/questions (max 4)
111
- - Proposed plan (max 5 steps)
112
- - Verification (max 3)
113
-
114
- Question/Support:
115
- - Summary (1-2 sentences)
116
- - Answer/guidance (max 6 lines)
117
- - Missing info (max 4)
118
-
119
- Do not implement changes until I confirm; end with: “Next actions: <1 sentence>”.`,$e=av({repo:H.repo,issue:W,comments:se});Fe.sendMessage({id:ae,providerID:re,modelID:me,agent:G,variant:he,text:ye,additionalParts:[{text:ge,synthetic:!0},{text:$e,synthetic:!0}]}).catch(ee=>{const Z=ee instanceof Error?ee.message:String(ee);U.error("Failed to send issue context",{description:Z})}),U.success("Session created from issue")}catch(H){const W=H instanceof Error?H.message:String(H);U.error("Failed to start session",{description:W})}finally{b(null)}}},[m,s,r,l,c,_,J,q,k]);return e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(ys,{className:"flex-shrink-0",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(mm,{className:"h-5 w-5"}),"New Session From GitHub Issue"]}),e.jsx(ks,{children:"Seeds a new session with hidden issue context (title/body/labels/comments)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(bt,{placeholder:"Search by title or #123, or paste issue URL",value:d,onChange:z=>u(z.target.value),className:"pl-9 w-full"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[l?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No active project selected."}),s?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),N?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 animate-spin"}),"Loading issues..."]}):null,A===!1?e.jsxs("div",{className:"text-center text-muted-foreground py-8 space-y-3",children:[e.jsx("div",{children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx("div",{className:"flex justify-center",children:e.jsx(ve,{variant:"outline",size:"sm",onClick:R,children:"Open settings"})})]}):null,C?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:C}):null,Y&&l&&s&&A?e.jsxs("div",{className:F("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",k===Y&&"bg-muted/30"),onClick:()=>{Q(Y)},children:[e.jsx("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:"#"}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:["Use issue #",Y]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:k===Y?e.jsx(Ft,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,K.length===0&&!N&&A&&s&&l?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:d?"No issues found":"No open issues found"}):null,K.map(z=>e.jsxs("div",{className:F("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",k===z.number&&"bg-muted/30"),onClick:()=>{Q(z.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",z.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:z.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:k===z.number?e.jsx(Ft,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:z.url,target:"_blank",rel:"noopener noreferrer",className:"hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:H=>H.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(dr,{className:"h-4 w-4"})})})]},z.number)),v&&A&&l&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{I()},disabled:j||!!k,className:F("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(j||!!k)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:j?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more"})}):null]}),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 items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":m,onClick:()=>f(z=>!z),onKeyDown:z=>{(z.key===" "||z.key==="Enter")&&(z.preventDefault(),f(H=>!H))},children:[e.jsx("button",{type:"button",onClick:z=>{z.preventDefault(),z.stopPropagation(),f(H=>!H)},"aria-label":"Toggle worktree",className:"flex h-5 w-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:m?e.jsx(xn,{className:"h-4 w-4 text-primary"}):e.jsx(yn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create in worktree"}),e.jsx("span",{className:"typography-meta text-muted-foreground/70",children:"(issue-<number>-<slug>)"})]}),e.jsx("div",{className:"flex-1"}),T?e.jsx(ve,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:T,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(dr,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(ve,{variant:"outline",size:"sm",onClick:E,disabled:N||!!k,children:"Refresh"})]})]})]})})}const lv=t=>{const r=t.trim();if(!r)return null;const s=r.match(/\/pull\/(\d+)(?:\b|\/|$)/i);if(s){const o=Number(s[1]);return Number.isFinite(o)&&o>0?o:null}const n=r.match(/^#?(\d+)$/);if(n){const o=Number(n[1]);return Number.isFinite(o)&&o>0?o:null}return null},cv=t=>`GitHub pull request context (JSON)
120
- ${JSON.stringify(t,null,2)}`;function dv({open:t,onOpenChange:r}){const{github:s}=Zs(),n=ke(W=>W.setSettingsDialogOpen),o=ke(W=>W.setSidebarSection),l=zt(W=>W.getActiveProject())?.path??null,[c,d]=i.useState(""),[u,m]=i.useState(!1),[f,p]=i.useState(!1),[h,x]=i.useState(null),[g,w]=i.useState([]),[y,v]=i.useState(1),[S,k]=i.useState(!1),[b,N]=i.useState(null),[D,j]=i.useState(!1),[M,C]=i.useState(!1),[P,E]=i.useState(null),I=i.useCallback(async()=>{if(!l){x(null),E("No active project");return}if(!s?.prsList){x(null),E("GitHub runtime API unavailable");return}j(!0),E(null);try{const W=await s.prsList(l,{page:1});x(W),w(W.prs??[]),v(W.page??1),k(!!W.hasMore),W.connected===!1&&E(null)}catch(W){E(W instanceof Error?W.message:String(W))}finally{j(!1)}},[s,l]),A=i.useCallback(async()=>{if(l&&s?.prsList&&!(M||D)&&S){C(!0);try{const W=y+1,B=await s.prsList(l,{page:W});x(B),w(se=>[...se,...B.prs??[]]),v(B.page??W),k(!!B.hasMore)}catch(W){const B=W instanceof Error?W.message:String(W);U.error("Failed to load more PRs",{description:B})}finally{C(!1)}}},[s,S,D,M,y,l]);i.useEffect(()=>{if(!t){d(""),m(!1),p(!1),x(null),w([]),v(1),k(!1),N(null),j(!1),E(null);return}I()},[t,I]);const T=!!h?.connected,R=h?.repo?.url??null,K=i.useCallback(()=>{o("settings"),n(!0)},[n,o]),Y=i.useMemo(()=>{const W=c.trim().toLowerCase();return W?g.filter(B=>String(B.number)===W.replace(/^#/,"")?!0:B.title.toLowerCase().includes(W)):g},[g,c]),_=i.useMemo(()=>lv(c),[c]),J=i.useCallback(()=>{const W=et.getState(),B=W.getVisibleAgents();if(W.settingsDefaultAgent){const se=B.find(L=>L.name===W.settingsDefaultAgent);if(se)return se.name}return B.find(se=>se.name==="build")?.name||B[0]?.name},[]),q=i.useCallback(()=>{const W=et.getState(),B=W.settingsDefaultModel;if(!B)return null;const se=B.split("/");if(se.length!==2)return null;const[L,ae]=se;return!L||!ae||!W.getModelMetadata(L,ae)?null:{providerID:L,modelID:ae}},[]),Q=i.useCallback((W,B)=>{const se=et.getState(),L=se.settingsDefaultVariant;if(!L)return;const V=se.providers.find(X=>X.id===W)?.models.find(X=>X.id===B)?.variants;if(V&&Object.prototype.hasOwnProperty.call(V,L))return L},[]),z=i.useCallback(async(W,B)=>{if(!l)return null;const se=B.head,L=B.headRepo;if(!se)throw new Error("PR head ref missing");const O=!!(L?.owner&&L?.repo&&W?.owner&&W?.repo&&(L.owner!==W.owner||L.repo!==W.repo))?L?.cloneUrl||L?.url||"":"origin";if(!O)throw new Error("PR head remote URL missing");const V=`refs/heads/${se}`;if(!(await tb(l,{remote:O,branch:V}))?.success)throw new Error("Failed to fetch PR head");const re=B.head,me=await Jw(l,re,"FETCH_HEAD");if(!me?.id)throw new Error("Failed to create PR worktree session");return{id:me.id}},[l]),H=i.useCallback(async W=>{if(!l){U.error("No active project");return}if(!s?.prContext){U.error("GitHub runtime API unavailable");return}if(!b){N(W);try{const B=await s.prContext(l,W,{includeDiff:f});if(B.connected===!1){U.error("GitHub not connected");return}if(!B.repo){U.error("Repo not resolvable",{description:"origin remote must be a GitHub URL"});return}if(!B.pr){U.error("PR not found");return}const se=B.pr,L=`#${se.number} ${se.title}`.trim(),ae=await(async()=>{if(u)try{return(await z(B.repo,se))?.id||null}catch(Z){const ie=Z instanceof Error?Z.message:String(Z);U.error("PR worktree failed",{description:ie})}return(await fe.getState().createSession(L,l,null))?.id||null})();if(!ae)throw new Error("Failed to create session");fe.getState().updateSessionTitle(ae,L).catch(()=>{});try{fe.getState().initializeNewOpenChamberSession(ae,et.getState().agents)}catch{}r(!1);const O=et.getState(),V=kt.getState().lastUsedProvider,X=q(),re=X?.providerID||O.currentProviderId||V?.providerID,me=X?.modelID||O.currentModelId||V?.modelID,G=J()||O.currentAgentName||void 0;if(!re||!me){U.error("No model selected");return}const he=Q(re,me);try{at.getState().saveSessionModelSelection(ae,re,me)}catch{}if(G){try{O.setAgent(G)}catch{}try{at.getState().saveSessionAgentSelection(ae,G)}catch{}try{at.getState().saveAgentModelForSession(ae,G,re,me)}catch{}if(he!==void 0){try{O.setCurrentVariant(he)}catch{}try{at.getState().saveAgentModelVariantForSession(ae,G,re,me,he)}catch{}}}const ye="Review this pull request using the provided PR context: description, comments, files, diff, checks.",ge=`Before reporting issues:
121
- - First identify the PR intent (what it’s trying to achieve) from title/body/diff, then evaluate whether the implementation matches that intent; call out missing pieces, incorrect behavior vs intent, and scope creep.
122
- - Gather any needed repository context (code, config, docs) to validate assumptions.
123
- - No speculation: if something is unclear or cannot be verified, say what’s missing and ask for it instead of guessing.
124
-
125
- Output rules:
126
- - Start with a 1-2 sentence summary.
127
- - Provide a single concise PR review comment.
128
- - No emojis. No code snippets. No fenced blocks.
129
- - Short inline code identifiers allowed, but no snippets or fenced blocks.
130
- - Reference evidence with file paths and line ranges (e.g., path/to/file.ts:120-138). If exact lines aren’t available, cite the file and say “approx” + why.
131
- - Keep the entire comment under ~300 words.
132
-
133
- Report:
134
- - Must-fix issues (blocking) — brief why and a one-line action each.
135
- - Nice-to-have improvements (optional) — brief why and a one-line action each.
136
-
137
- Quality & safety (general):
138
- - Call out correctness risks, edge cases, performance regressions, security/privacy concerns, and backwards-compatibility risks.
139
- - Call out missing tests/verification steps and suggest the minimal validation needed.
140
- - Note readability/maintainability issues when they materially affect future changes.
141
-
142
- Applicability (only if relevant):
143
- - If changes affect multiple components/targets/environments (e.g., client/server, OSs, deployments), state what is affected vs not, and why.
144
-
145
- Architecture:
146
- - Call out breakages, missing implementations across modules/targets, boundary violations, and cross-cutting concerns (errors, logging/observability, accessibility).
147
-
148
- Precedence:
149
- - If local precedent conflicts with best practices, state it and suggest a follow-up task.
150
-
151
- Do not implement changes until I confirm; end with a short “Next actions” sentence describing the recommended plan.
152
-
153
- Format exactly:
154
- Must-fix:
155
- - <issue> — <brief why> — <file:line-range> — Action: <one-line action>
156
- Nice-to-have:
157
- - <issue> — <brief why> — <file:line-range> — Action: <one-line action>
158
- If no issues, write:
159
- Must-fix:
160
- - None
161
- Nice-to-have:
162
- - None`,$e=cv(B);Fe.sendMessage({id:ae,providerID:re,modelID:me,agent:G,variant:he,text:ye,additionalParts:[{text:ge,synthetic:!0},{text:$e,synthetic:!0}]}).catch(ee=>{const Z=ee instanceof Error?ee.message:String(ee);U.error("Failed to send PR context",{description:Z})}),U.success("Session created from PR")}catch(B){const se=B instanceof Error?B.message:String(B);U.error("Failed to start session",{description:se})}finally{N(null)}}},[u,z,s,f,r,l,J,q,Q,b]);return e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(ys,{className:"flex-shrink-0",children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Fl,{className:"h-5 w-5"}),"New Session From GitHub PR"]}),e.jsx(ks,{children:"Seeds a new session with hidden PR context (title/body/comments/files/checks)."})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(bt,{placeholder:"Search by title or #123, or paste PR URL",value:c,onChange:W=>d(W.target.value),className:"pl-9 w-full"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-2",children:[l?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"No active project selected."}),s?null:e.jsx("div",{className:"text-center text-muted-foreground py-8",children:"GitHub runtime API unavailable."}),D?e.jsxs("div",{className:"text-center text-muted-foreground py-8 flex items-center justify-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 animate-spin"}),"Loading pull requests..."]}):null,T===!1?e.jsxs("div",{className:"text-center text-muted-foreground py-8 space-y-3",children:[e.jsx("div",{children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx("div",{className:"flex justify-center",children:e.jsx(ve,{variant:"outline",size:"sm",onClick:K,children:"Open settings"})})]}):null,P?e.jsx("div",{className:"text-center text-muted-foreground py-8 break-words",children:P}):null,_&&l&&s&&T?e.jsxs("div",{className:F("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",b===_&&"bg-muted/30"),onClick:()=>{H(_)},children:[e.jsx("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:"#"}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:["Use PR #",_]}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:b===_?e.jsx(Ft,{className:"h-4 w-4 animate-spin text-muted-foreground"}):null})]}):null,Y.length===0&&!D&&T&&s&&l?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:c?"No PRs found":"No open PRs found"}):null,Y.map(W=>e.jsxs("div",{className:F("group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",b===W.number&&"bg-muted/30"),onClick:()=>{H(W.number)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-12 text-right flex-shrink-0",children:["#",W.number]}),e.jsx("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:W.title}),e.jsx("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:b===W.number?e.jsx(Ft,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx("a",{href:W.url,target:"_blank",rel:"noopener noreferrer",className:"hidden group-hover:flex h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:B=>B.stopPropagation(),"aria-label":"Open in GitHub",children:e.jsx(dr,{className:"h-4 w-4"})})})]},W.number)),S&&T&&l&&s?e.jsx("div",{className:"py-2 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>{A()},disabled:M||!!b,className:F("typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4",(M||!!b)&&"opacity-50 cursor-not-allowed hover:text-muted-foreground"),children:M?e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ft,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Load more"})}):null]}),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 items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":u,onClick:()=>m(W=>!W),onKeyDown:W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),m(B=>!B))},children:[e.jsx("button",{type:"button",onClick:W=>{W.preventDefault(),W.stopPropagation(),m(B=>!B)},"aria-label":"Toggle worktree",className:"flex h-5 w-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:u?e.jsx(xn,{className:"h-4 w-4 text-primary"}):e.jsx(yn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Create session in PR worktree"})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":f,onClick:()=>p(W=>!W),onKeyDown:W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),p(B=>!B))},children:[e.jsx("button",{type:"button",onClick:W=>{W.preventDefault(),W.stopPropagation(),p(B=>!B)},"aria-label":"Toggle diff",className:"flex h-5 w-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:f?e.jsx(xn,{className:"h-4 w-4 text-primary"}):e.jsx(yn,{className:"h-4 w-4"})}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Include full diff"})]}),e.jsx("div",{className:"flex-1"}),R?e.jsx(ve,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:R,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(dr,{className:"size-4"}),"Open Repo"]})}):null,e.jsx(ve,{variant:"outline",size:"sm",onClick:I,disabled:D||!!b,children:"Refresh"})]})]})]})})}const Nd="oc.sessions.projectCollapse",kd="oc.sessions.expandedParents",Cd=t=>{const r=new Date(t),s=new Date,n=(l,c)=>l.getFullYear()===c.getFullYear()&&l.getMonth()===c.getMonth()&&l.getDate()===c.getDate(),o=new Date(s);return o.setDate(s.getDate()-1),n(r,s)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},pr=t=>{if(!t)return null;const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},Md=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),uv=({id:t,projectLabel:r,projectDescription:s,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:l,isDesktopRuntime:c,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onNewWorktreeSession:x,onOpenBranchPicker:g,onNewSessionFromGitHubIssue:w,onNewSessionFromGitHubPR:y,onOpenMultiRunLauncher:v,onClose:S,sentinelRef:k,children:b,settingsAutoCreateWorktree:N})=>{const{attributes:D,listeners:j,setNodeRef:M,isDragging:C}=Hh({id:t}),[P,E]=i.useState(!1);return e.jsxs("div",{ref:M,className:F("relative",C&&"opacity-40"),children:[c&&e.jsx("div",{ref:k,"data-project-id":t,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:F("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b select-none",!c&&"bg-sidebar"),style:{backgroundColor:c?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:l?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onContextMenu:I=>{I.preventDefault(),E(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...D,children:[e.jsxs(lt,{delayDuration:1500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...j,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:F("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(it,{side:"right",sideOffset:8,children:s})]}),e.jsxs(ts,{open:P,onOpenChange:E,children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:F("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:I=>I.stopPropagation(),children:e.jsx(Yr,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"min-w-[180px]",children:[a&&!u&&N&&h&&e.jsxs(jt,{onClick:h,children:[e.jsx(cs,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),a&&!u&&!N&&x&&e.jsxs(jt,{onClick:x,children:[e.jsx(Kt,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),a&&!u&&g&&e.jsxs(jt,{onClick:g,children:[e.jsx(fm,{className:"mr-1.5 h-4 w-4"}),"Browse Branches"]}),a&&!u&&w&&e.jsxs(jt,{onClick:w,children:[e.jsx(mm,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub issue"]}),a&&!u&&y&&e.jsxs(jt,{onClick:y,children:[e.jsx(Fl,{className:"mr-1.5 h-4 w-4"}),"New session from GitHub PR"]}),a&&!u&&e.jsxs(jt,{onClick:v,children:[e.jsx(Pf,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(jt,{onClick:S,className:"text-destructive focus:text-destructive",children:[e.jsx(es,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),a&&!u&&x&&N&&e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),x()},className:F("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground flex-shrink-0",m?"opacity-70":"opacity-100"),"aria-label":"New session in worktree",children:e.jsx(Kt,{className:"h-4 w-4"})})}),e.jsx(it,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session in worktree"})})]}),(!N||!a)&&e.jsxs(lt,{children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:I=>{I.stopPropagation(),h()},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(cs,{className:"h-4 w-4"})})}),e.jsx(it,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})}),b]})},mv=({projectLabel:t,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.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:F("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:t})})}),La=({mobileVariant:t=!1,onSessionSelected:r,allowReselect:s=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,l]=i.useState(null),[c,d]=i.useState(""),[u,m]=i.useState(null),f=i.useRef(null),[p,h]=i.useState(new Set),[x,g]=i.useState(()=>new Map),w=i.useRef(new Set),y=i.useMemo(()=>ws(),[]),[v,S]=i.useState(new Set),[k,b]=i.useState(new Map),[N,D]=i.useState(new Set),[j,M]=i.useState(null),[C,P]=i.useState(!1),[E,I]=i.useState(!1),[A,T]=i.useState(!1),[R,K]=i.useState(null),[Y,_]=i.useState(new Set),[J,q]=i.useState(null),Q=i.useRef(new Map),z=i.useRef(0),H=gt(ne=>ne.homeDirectory),W=gt(ne=>ne.currentDirectory),B=gt(ne=>ne.setDirectory),se=zt(ne=>ne.projects),L=zt(ne=>ne.activeProjectId),ae=zt(ne=>ne.addProject),O=zt(ne=>ne.removeProject),V=zt(ne=>ne.setActiveProject),X=zt(ne=>ne.setActiveProjectIdOnly),re=zt(ne=>ne.reorderProjects),me=ke(ne=>ne.setActiveMainTab),G=ke(ne=>ne.setSessionSwitcherOpen),he=ke(ne=>ne.openMultiRunLauncher),ye=et(ne=>ne.settingsAutoCreateWorktree),ge=fe(ne=>ne.sessions),$e=fe(ne=>ne.sessionsByDirectory),ee=fe(ne=>ne.currentSessionId),Z=fe(ne=>ne.setCurrentSession),ie=fe(ne=>ne.updateSessionTitle),Me=fe(ne=>ne.shareSession),oe=fe(ne=>ne.unshareSession),xe=fe(ne=>ne.sessionMemoryState),pe=fe(ne=>ne.sessionActivityPhase),je=fe(ne=>ne.permissions),ce=fe(ne=>ne.worktreeMetadata),Ye=fe(ne=>ne.availableWorktreesByProject),mt=fe(ne=>ne.getSessionsByDirectory),Ie=fe(ne=>ne.openNewSessionDraft),[le,Xe]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),Ne=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{try{const ne=y.getItem(kd);if(ne){const te=JSON.parse(ne);Array.isArray(te)&&h(new Set(te.filter(Ce=>typeof Ce=="string")))}const Ae=y.getItem(Nd);if(Ae){const te=JSON.parse(Ae);Array.isArray(te)&&S(new Set(te.filter(Ce=>typeof Ce=="string")))}}catch{}},[y]),i.useEffect(()=>{typeof window>"u"||Xe(typeof window.opencodeDesktop<"u")},[]);const Se=i.useMemo(()=>[...ge].sort((ne,Ae)=>(Ae.time?.updated||0)-(ne.time?.updated||0)),[ge]);i.useEffect(()=>{let ne=!1;const Ae=se.map(te=>({id:te.id,path:pr(te.path)})).filter(te=>!!te.path);return b(new Map),Ae.length===0?()=>{ne=!0}:(Ae.forEach(te=>{Or(te.path).then(Ce=>{ne||b(De=>{const He=new Map(De);return He.set(te.id,Ce),He})}).catch(()=>{ne||b(Ce=>{const De=new Map(Ce);return De.set(te.id,null),De})})}),()=>{ne=!0})},[se]);const qe=i.useMemo(()=>{const ne=new Map;return Se.forEach(Ae=>{const te=Ae.parentID;te&&ne.set(Ae.id,te)}),ne},[Se]),rt=i.useMemo(()=>{const ne=new Map;return Se.forEach(Ae=>{const te=Ae.parentID;if(!te)return;const Ce=ne.get(te)??[];Ce.push(Ae),ne.set(te,Ce)}),ne.forEach(Ae=>Ae.sort((te,Ce)=>(Ce.time?.updated||0)-(te.time?.updated||0))),ne},[Se]);i.useEffect(()=>{ee&&h(ne=>{const Ae=new Set(ne);let te=qe.get(ee)||null,Ce=!1;for(;te;)Ae.has(te)||(Ae.add(te),Ce=!0),te=qe.get(te)||null;return Ce?Ae:ne})},[ee,qe]),i.useEffect(()=>{const ne=new Set;Se.forEach(Ae=>{const te=pr(Ae.directory??null);te&&ne.add(te)}),se.forEach(Ae=>{const te=pr(Ae.path);te&&ne.add(te)}),ne.forEach(Ae=>{const te=x.get(Ae);te&&te!=="unknown"||w.current.has(Ae)||(w.current.add(Ae),Fe.listLocalDirectory(Ae).then(()=>{g(Ce=>{const De=new Map(Ce);return De.get(Ae)==="exists"?Ce:(De.set(Ae,"exists"),De)})}).catch(()=>{g(Ce=>{const De=new Map(Ce);return De.get(Ae)==="missing"?Ce:(De.set(Ae,"missing"),De)})}).finally(()=>{w.current.delete(Ae)}))})},[Se,se,x]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const We=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."})]}),_e=i.useCallback((ne,Ae,te,Ce)=>{if(!te){if(Ce&&Ce!==L&&X(Ce),Ae&&Ae!==W&&B(Ae,{showOverlay:!1}),t&&(me("chat"),G(!1)),!s&&ne===ee){r?.(ne);return}Z(ne),r?.(ne)}},[L,s,W,ee,t,r,me,X,Z,B,G]),Ke=i.useCallback(async()=>{a&&c.trim()&&(await ie(a,c.trim()),l(null),d(""))},[a,c,ie]),xt=i.useCallback(()=>{l(null),d("")},[]),nt=i.useCallback(async ne=>{const Ae=await Me(ne.id);Ae&&Ae.share?.url?U.success("Session shared",{description:"You can copy the link from the menu."}):U.error("Unable to share session")},[Me]),Pt=i.useCallback((ne,Ae)=>{navigator.clipboard.writeText(ne).then(()=>{m(Ae),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{U.error("Failed to copy URL")})},[]),Tt=i.useCallback(async ne=>{await oe(ne)?U.success("Session unshared"):U.error("Unable to unshare session")},[oe]),_t=i.useCallback(ne=>{const Ae=[],te=Ce=>{(rt.get(Ce)??[]).forEach(He=>{Ae.push(He),te(He.id)})};return te(ne),Ae},[rt]),Ve=fe(ne=>ne.deleteSession),dt=fe(ne=>ne.deleteSessions),vt=i.useCallback(async ne=>{const Ae=_t(ne.id),te=ce.get(ne.id);if(te){const Ce=te.path,De=[],He=new Set;ge.forEach(wt=>{const Nt=ce.get(wt.id);Nt&&Nt.path===Ce&&!He.has(wt.id)&&(De.push(wt),He.add(wt.id),_t(wt.id).forEach(we=>{He.has(we.id)||(De.push(we),He.add(we.id))}))}),qn.requestDelete({sessions:De,mode:"worktree",worktree:te});return}if(Ae.length===0)await Ve(ne.id)?U.success("Session deleted",{action:{label:"OK",onClick:()=>{}}}):U.error("Failed to delete session");else{const Ce=[ne.id,...Ae.map(wt=>wt.id)],{deletedIds:De,failedIds:He}=await dt(Ce);De.length>0&&U.success(`Deleted ${De.length} session${De.length===1?"":"s"}`,{action:{label:"OK",onClick:()=>{}}}),He.length>0&&U.error(`Failed to delete ${He.length} session${He.length===1?"":"s"}`)}},[_t,Ve,dt,ce,ge]),ut=i.useCallback(()=>{le&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(ne=>{ne.success&&ne.path?ae(ne.path,{id:ne.projectId})||U.error("Failed to add project",{description:"Please select a valid directory."}):ne.error&&ne.error!=="Directory selection cancelled"&&U.error("Failed to select directory",{description:ne.error})}).catch(ne=>{console.error("Desktop: Error selecting directory:",ne),U.error("Failed to select directory")}):qn.requestDirectoryDialog()},[ae,le]),At=i.useCallback(ne=>{h(Ae=>{const te=new Set(Ae);te.has(ne)?te.delete(ne):te.add(ne);try{y.setItem(kd,JSON.stringify(Array.from(te)))}catch{}return te})},[y]),Rt=i.useCallback(ne=>{const Ae=rt.get(ne.id)??[];return{session:ne,children:Ae.map(te=>Rt(te)),worktree:ce.get(ne.id)??null}},[rt,ce]),as=i.useCallback((ne,Ae,te)=>{const Ce=pr(Ae??null),De=[...ne].sort((Ee,ot)=>(ot.time?.updated||0)-(Ee.time?.updated||0)),He=new Map(De.map(Ee=>[Ee.id,Ee])),wt=new Map;De.forEach(Ee=>{const ot=Ee.parentID;if(!ot)return;const ft=wt.get(ot)??[];ft.push(Ee),wt.set(ot,ft)}),wt.forEach(Ee=>Ee.sort((ot,ft)=>(ft.time?.updated||0)-(ot.time?.updated||0)));const Nt=new Map;te.forEach(Ee=>{if(Ee.path){const ot=pr(Ee.path)??Ee.path;Nt.set(ot,Ee)}});const Xt=Ee=>{const ot=pr(Ee.directory??null),ft=ce.get(Ee.id)??null;if(ft)return ft;if(ot){const Bt=Nt.get(ot)??null;if(Bt&&ot!==Ce)return Bt}return null},we=Ee=>{const ot=wt.get(Ee.id)??[];return{session:Ee,children:ot.map(ft=>we(ft)),worktree:Xt(Ee)}},tt=De.filter(Ee=>{const ot=Ee.parentID;return ot?!He.has(ot):!0}).map(Ee=>we(Ee));return[{id:"all",label:"All sessions",description:Ce?cn(Ce,H):null,isMain:!0,worktree:null,directory:Ce,sessions:tt}]},[H,ce]),Ct=i.useCallback(ne=>{D(Ae=>{const te=new Set(Ae);return te.has(ne)?te.delete(ne):te.add(ne),te})},[]),$t=i.useCallback(ne=>{z.current=Date.now()+150,S(Ae=>{const te=new Set(Ae);te.has(ne)?te.delete(ne):te.add(ne);try{y.setItem(Nd,JSON.stringify(Array.from(te)))}catch{}return te})},[y]),Mt=i.useMemo(()=>se.map(ne=>({...ne,normalizedPath:pr(ne.path)})).filter(ne=>!!ne.normalizedPath),[se]),Gt=i.useCallback(ne=>{const Ae=Ne?[]:Ye.get(ne.normalizedPath)??[],te=[ne.normalizedPath,...Ae.map(He=>pr(He.path)??He.path).filter(He=>!!He)],Ce=new Set,De=[];return te.forEach(He=>{($e.get(He)??mt(He)).forEach(Nt=>{Ce.has(Nt.id)||(Ce.add(Nt.id),De.push(Nt))})}),De},[Ye,mt,$e,Ne]),Dt=i.useMemo(()=>Mt.map(ne=>{const Ae=Gt(ne),te=Ye.get(ne.normalizedPath)??[],Ce=as(Ae,ne.normalizedPath,te);return{project:ne,groups:Ce}}),[Mt,Gt,as,Ye]);i.useEffect(()=>{if(!le)return;const ne=new IntersectionObserver(Ae=>{Ae.forEach(te=>{const Ce=te.target.dataset.projectId;Ce&&_(De=>{const He=new Set(De);return te.isIntersecting?He.delete(Ce):He.add(Ce),He})})},{threshold:0});return Q.current.forEach(Ae=>{Ae&&ne.observe(Ae)}),()=>ne.disconnect()},[le,Dt]);const qt=i.useCallback((ne,Ae=0,te,Ce)=>{const De=ne.session,He=pr(De.directory??null)??pr(te??null),Nt=(He?x.get(He):null)==="missing",Xt=xe.get(De.id),we=ee===De.id,ze=De.title||"Untitled Session",tt=ne.children.length>0,Ee=p.has(De.id),ot=De.summary?.additions,ft=De.summary?.deletions,Bt=typeof ot=="number"||typeof ft=="number";if(a===De.id)return e.jsx("div",{className:F("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",Ae>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(),Ke()},children:[e.jsx("input",{value:c,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"&&xt()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Qt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:xt,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(es,{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:Ee?e.jsx(Ht,{className:"h-3 w-3"}):e.jsx(zs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Cd(De.time?.created||Date.now())}),De.share?e.jsx(ui,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Bt&&((ot??0)!==0||(ft??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,ot??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,ft??0)]})]}):null,tt?e.jsxs("span",{className:"truncate",children:[ne.children.length," ",ne.children.length===1?"task":"tasks"]}):null]})]})},De.id);const Wt=pe?.get(De.id)??"idle",vs=Wt==="busy"||Wt==="cooldown",is=je.get(De.id)?.length??0,Jt=Xt&&Xt.isZombie?e.jsx(Zi,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(i.Fragment,{children:[e.jsx("div",{className:F("group relative flex items-center rounded-md px-1.5 py-1",we?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",Nt?"opacity-75":"",Ae>0&&"pl-[20px]"),onContextMenu:Ot=>{Ot.preventDefault(),q(De.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:Nt,onClick:()=>_e(De.id,He,Nt,Ce),className:F("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 select-none"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[vs?e.jsx(If,{size:"xs",className:"text-primary flex-shrink-0"}):null,e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:ze}),is>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(Ih,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:is})]}):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(),At(De.id)},onKeyDown:Ot=>{(Ot.key==="Enter"||Ot.key===" ")&&(Ot.preventDefault(),Ot.stopPropagation(),At(De.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":Ee?"Collapse subsessions":"Expand subsessions",children:Ee?e.jsx(Ht,{className:"h-3 w-3"}):e.jsx(zs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Cd(De.time?.created||Date.now())}),De.share?e.jsx(ui,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,ne.worktree?e.jsxs(lt,{delayDuration:700,children:[e.jsx(ct,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Kt,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(it,{side:"top",className:"text-xs",children:ne.worktree.branch||ne.worktree.label||"Worktree"})]}):null,Bt&&((ot??0)!==0||(ft??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,ot??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,ft??0)]})]}):null,tt?e.jsxs("span",{className:"truncate",children:[ne.children.length," ",ne.children.length===1?"task":"tasks"]}):null,Nt?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Zi,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Jt,e.jsxs(ts,{open:J===De.id,onOpenChange:Ot=>q(Ot?De.id:null),children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:F("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",t?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:Ot=>Ot.stopPropagation(),onKeyDown:Ot=>Ot.stopPropagation(),children:e.jsx(Yr,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"min-w-[180px]",children:[e.jsxs(jt,{onClick:()=>{l(De.id),d(ze)},className:"[&>svg]:mr-1",children:[e.jsx(Dr,{className:"mr-1 h-4 w-4"}),"Rename"]}),De.share?e.jsxs(e.Fragment,{children:[e.jsx(jt,{onClick:()=>{De.share?.url&&Pt(De.share.url,De.id)},className:"[&>svg]:mr-1",children:u===De.id?e.jsxs(e.Fragment,{children:[e.jsx(Qt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Js,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(jt,{onClick:()=>Tt(De.id),className:"[&>svg]:mr-1",children:[e.jsx(Ph,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(jt,{onClick:()=>nt(De),className:"[&>svg]:mr-1",children:[e.jsx(ui,{className:"mr-1 h-4 w-4"}),"Share"]}),ne.worktree?e.jsxs(jt,{onClick:()=>{Ce&&Ce!==L&&V(Ce),me("chat"),t&&G(!1),Ie({directoryOverride:ne.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(Kt,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(jt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>vt(De),children:[e.jsx(qs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),tt&&Ee?ne.children.map(Ot=>qt(Ot,Ae+1,He??te,Ce)):null]},De.id)},[x,xe,pe,je,ee,p,a,c,Ke,xt,At,_e,nt,Pt,Tt,vt,u,t,L,V,me,G,Ie,J]),St=i.useCallback((ne,Ae,te)=>{const Ce=N.has(Ae),De=n?10:5,He=ne.sessions.length,wt=Ce?ne.sessions:ne.sessions.slice(0,De),Nt=He-wt.length;return e.jsxs(e.Fragment,{children:[wt.map(Xt=>qt(Xt,0,ne.directory,te)),He===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,Nt>0&&!Ce?e.jsxs("button",{type:"button",onClick:()=>Ct(Ae),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 ",Nt," more ",Nt===1?"session":"sessions"]}):null,Ce&&He>De?e.jsx("button",{type:"button",onClick:()=>Ct(Ae),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]})},[N,n,qt,Ct]),Lt=Th(Nc(zh,{activationConstraint:{distance:8}}),Nc(Bh,{coordinateGetter:$h})),be=i.useCallback(ne=>{K(ne.active.id)},[]),Pe=i.useCallback(ne=>{const{active:Ae,over:te}=ne;if(K(null),!te||Ae.id===te.id)return;const Ce=Mt.findIndex(He=>He.id===Ae.id),De=Mt.findIndex(He=>He.id===te.id);Ce!==-1&&De!==-1&&re(Ce,De)},[Mt,re]),Oe=i.useCallback(()=>{K(null)},[]),st=i.useMemo(()=>{if(!R)return null;const ne=Dt.find(te=>te.project.id===R);if(!ne)return null;const Ae=ne.project;return{id:Ae.id,label:Md(Ae.label?.trim()||Ac(Ae.normalizedPath,H)||Ae.normalizedPath),isActive:Ae.id===L}},[R,Dt,H,L]);return e.jsxs("div",{className:F("flex h-full flex-col text-foreground overflow-x-hidden",t?"":le?"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:se.length})]}),e.jsx("button",{type:"button",onClick:ut,className:F("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",!le&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(el,{className:"h-4.5 w-4.5"})})]})}),e.jsx(ht,{outerClassName:"flex-1 min-h-0",className:F("space-y-1 pb-1 pl-2.5 pr-1",""),children:Dt.length===0?We:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const ne=Dt.find(Ce=>Ce.project.id===L)??Dt[0];if(!ne)return We;const Ae=ne.groups.find(Ce=>Ce.isMain&&Ce.sessions.length>0)??ne.groups.find(Ce=>Ce.sessions.length>0)??ne.groups.find(Ce=>Ce.isMain)??ne.groups[0];if(!Ae)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const te=`${ne.project.id}:${Ae.id}`;return St(Ae,te,ne.project.id)})()}):e.jsxs(Fh,{sensors:Lt,collisionDetection:Rh,onDragStart:be,onDragEnd:Pe,onDragCancel:Oe,children:[e.jsx(Lh,{items:Mt.map(ne=>ne.id),strategy:Oh,children:Dt.map(ne=>{const Ae=ne.project,te=Ae.id,Ce=Md(Ae.label?.trim()||Ac(Ae.normalizedPath,H)||Ae.normalizedPath),De=cn(Ae.normalizedPath,H),He=v.has(te),wt=te===L,Nt=k.get(te),Xt=j===te;return e.jsx(uv,{id:te,projectLabel:Ce,projectDescription:De,isCollapsed:He,isActiveProject:wt,isRepo:!!Nt,isHovered:Xt,isDesktopRuntime:le,isStuck:Y.has(te),hideDirectoryControls:n,mobileVariant:t,onToggle:()=>$t(te),onHoverChange:we=>M(we?te:null),onNewSession:()=>{te!==L&&V(te),me("chat"),t&&G(!1),Ie({directoryOverride:Ae.normalizedPath})},onNewWorktreeSession:()=>{te!==L&&V(te),me("chat"),t&&G(!1),si()},onOpenBranchPicker:()=>P(!0),onNewSessionFromGitHubIssue:()=>{te!==L&&V(te),me("chat"),t&&G(!1),I(!0)},onNewSessionFromGitHubPR:()=>{te!==L&&V(te),me("chat"),t&&G(!1),T(!0)},onOpenMultiRunLauncher:()=>{te!==L&&V(te),he()},onClose:()=>O(te),sentinelRef:we=>{Q.current.set(te,we)},settingsAutoCreateWorktree:ye,children:He?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:ne.groups[0]?St(ne.groups[0],`${te}:all`,te):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},te)})}),e.jsx(_h,{children:st?e.jsx(mv,{projectLabel:st.label,isActiveProject:st.isActive}):null})]})}),e.jsx(nv,{open:C,onOpenChange:P,projects:Mt,activeProjectId:L}),e.jsx(iv,{open:E,onOpenChange:I}),e.jsx(dv,{open:A,onOpenChange:T})]})},ri=()=>{const[t,r]=Re.useState(!1);Re.useEffect(()=>{r(ds())},[]);const s=Re.useCallback(async a=>t?await Rx(a):{success:!0,path:a},[t]),n=Re.useCallback(async a=>t?await Lx(a):{success:!0},[t]),o=Re.useCallback(async a=>t?await Ox(a):{success:!0},[t]);return{isDesktop:t,requestAccess:s,startAccessing:n,stopAccessing:o}},Dd=({currentPath:t,onSelectPath:r,triggerClassName:s,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:l,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=i.useMemo(()=>ds(),[]),{isMobile:p}=Yt(),[h,x]=i.useState([]),[g,w]=i.useState(new Set),[y,v]=i.useState(!0),[S,k]=i.useState(!1),[b,N]=i.useState(""),[D,j]=i.useState(new Set),[M,C]=i.useState(null),[P,E]=i.useState(""),[I,A]=i.useState(!0),T=i.useRef(null),{requestAccess:R,startAccessing:K,isDesktop:Y}=ri(),_=i.useRef(c),J=i.useCallback(ee=>{if(!ee)return ee;if(ee==="/"||ee.length===0)return"/";let Z=ee;for(;Z.length>1&&Z.endsWith("/");)Z=Z.slice(0,-1);return Z.length===0?"/":Z},[]),q=i.useMemo(()=>{if(!b)return null;const ee=b.replace(/\\/g,"/");return J(ee)},[b,J]),Q=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const ee=d.replace(/\\/g,"/"),Z=J(ee);if(Z&&Z!=="/")return Z}return q&&q!=="/"?q:null},[d,q,J]),z=i.useMemo(()=>typeof u=="boolean"?!!(u&&Q):!!Q,[u,Q]);i.useEffect(()=>{z||(v(!0),x([]))},[z]);const H=i.useCallback(ee=>{if(!ee||!z||!Q)return!1;const Z=ee.replace(/\\/g,"/"),ie=J(Z)??Z;if(ie===Q)return!0;const Me=`${Q}/`;return ie.startsWith(Me)},[z,Q,J]),W=async ee=>{if(z){if(a==="deferred"){r(ee);return}if(Y){const Z=await R(ee);Z.success&&Z.path?(await K(Z.path),r(Z.path)):(console.error("Failed to get directory access:",Z.error),r(ee))}else r(ee)}};i.useEffect(()=>{let ee=!1;const Z=oe=>{if(!oe)return!1;const xe=J(oe.replace(/\\/g,"/"));return!xe||xe==="/"?!1:(N(typeof xe=="string"?xe:oe.replace(/\\/g,"/")),!0)};return d&&Z(d)||(async()=>{try{const oe=await Fe.getFilesystemHome();if(!ee&&Z(oe))return}catch(oe){console.warn("Failed to resolve filesystem home directory:",oe)}try{const oe=await Fe.getSystemInfo();if(!ee&&Z(oe?.homeDirectory))return}catch(oe){console.warn("Failed to resolve home directory from system info:",oe)}})(),()=>{ee=!0}},[d,J]),i.useEffect(()=>{let ee=!1;const Z=xe=>{if(ee)return;const pe=xe.filter(je=>typeof je=="string"&&je.length>0).map(je=>{const ce=je.replace(/\\/g,"/");return J(ce)??ce});j(new Set(pe))},ie=()=>{try{const xe=localStorage.getItem("pinnedDirectories");if(!xe)return;const pe=JSON.parse(xe);Array.isArray(pe)&&Z(pe)}catch(xe){console.warn("Failed to load pinned directories from local storage:",xe)}},Me=async()=>{try{let xe=[];if(f){const pe=await Lr();xe=Array.isArray(pe?.pinnedDirectories)?pe.pinnedDirectories:[]}else{const pe=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(pe.ok){const je=await pe.json();xe=Array.isArray(je?.pinnedDirectories)?je.pinnedDirectories:[]}}if(ee)return;Z(xe)}catch(xe){console.warn("Failed to load pinned directories:",xe)}};ie();const oe=xe=>{const pe=xe.detail;pe&&Array.isArray(pe.pinnedDirectories)&&Z(pe.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",oe),Me(),()=>{ee=!0,window.removeEventListener("openchamber:settings-synced",oe)}},[f,J]);const B=i.useRef(!0);i.useEffect(()=>{if(B.current){B.current=!1;return}const ee={pinnedDirectories:Array.from(D)};fs(ee)},[D]),i.useEffect(()=>{Q&&j(ee=>{const Z=Array.from(ee).map(ie=>J(ie.replace(/\\/g,"/"))??ie).filter(ie=>H(ie));return new Set(Z)})},[Q,H,J]),i.useEffect(()=>{_.current!==c&&(_.current=c)},[c]);const se=ee=>{j(Z=>{if(!H(ee))return Z;const ie=J(ee.replace(/\\/g,"/"))??ee.replace(/\\/g,"/"),Me=new Set(Z);return Me.has(ie)?Me.delete(ie):Me.add(ie),Me})},L=i.useMemo(()=>Array.from(D).map(ee=>J(ee.replace(/\\/g,"/"))??ee).filter(ee=>H(ee)).map(ee=>({path:ee,name:ee.split("/").pop()||ee})).sort((ee,Z)=>ee.name.localeCompare(Z.name)),[D,H,J]),ae=i.useCallback(async ee=>{const Z=pe=>c||!pe.startsWith("."),ie=Q;if(!z||!ie)return[];const Me=ee&&ee.length>0?ee:ie,oe=Me?Me.replace(/\\/g,"/"):null,xe=oe?J(oe)??oe:null;if(xe){const pe=`${ie}/`;if(!(xe===ie||xe.startsWith(pe)))return[]}try{return(await Fe.listLocalDirectory(ee)).filter(je=>{if(!je.isDirectory||!Z(je.name))return!1;const ce=je.path.replace(/\\/g,"/"),Ye=J(ce)??ce,mt=Ye===ie?ie:`${ie}/`;return Ye===ie||Ye.startsWith(mt)}).map(je=>({name:je.name,path:je.path.replace(/\\/g,"/"),isDirectory:!0})).sort((je,ce)=>je.name.localeCompare(ce.name))}catch{try{const je=await Fe.getApiClient().file.list({path:".",directory:ee});return je.data?je.data.filter(ce=>{if(ce.type!=="directory"||!ce.name||!Z(ce.name))return!1;const Ye=String(ce.absolute||ce.path||ce.name).replace(/\\/g,"/"),mt=J(Ye)??Ye,Ie=mt===ie?ie:`${ie}/`;return mt===ie||mt.startsWith(Ie)}).map(ce=>({name:ce.name||"",path:String(ce.absolute||ce.path||ce.name).replace(/\\/g,"/"),isDirectory:!0})).filter(ce=>ce.name!=="").sort((ce,Ye)=>ce.name.localeCompare(Ye.name)):[]}catch{return[]}}},[c,Q,J,z]),O=i.useRef(!1),V=i.useCallback(async()=>{if(!z||!Q){v(!0),x([]);return}O.current||v(!0);try{const ee=await ae(Q);x(ee),O.current=!0}catch{}finally{v(!1)}},[z,Q,ae]);i.useEffect(()=>{z&&(n==="inline"||S)&&V()},[n,S,z,V]);const X=async ee=>{if(!z)return;const Z=g.has(ee.path),ie=new Set(g);if(Z){ie.delete(ee.path),w(ie);return}ie.add(ee.path),w(ie);const Me=await ae(ee.path),oe=xe=>xe.map(pe=>pe.path===ee.path?{...pe,children:Me}:pe.children?{...pe,children:oe(pe.children)}:pe);x(xe=>oe(xe))};i.useEffect(()=>{M&&T.current&&(T.current.focus(),T.current.select())},[M]);const re=(ee,Z=[])=>{const ie="new_directory",Me=Z.map(je=>je.name);if(!Me.includes(ie))return ie;let oe=1;const xe=new RegExp(`^${ie}(\\d+)$`);for(const je of Me){const ce=je.match(xe);if(ce){const Ye=parseInt(ce[1],10);Ye>oe&&(oe=Ye)}}let pe=2;for(;Me.includes(`${ie}${pe}`);)pe++;return`${ie}${Math.max(pe,oe+1)}`},me=async ee=>{if(z){if(g.has(ee.path)){const Z=re(ee.path,ee.children);E(Z)}else{const Z=new Set(g);if(Z.add(ee.path),w(Z),ee.children){const ie=re(ee.path,ee.children);E(ie)}else{const ie=await ae(ee.path),Me=xe=>xe.map(pe=>pe.path===ee.path?{...pe,children:ie}:pe.children?{...pe,children:Me(pe.children)}:pe);x(xe=>Me(xe));const oe=re(ee.path,ie);E(oe)}}C(ee.path)}},G=async()=>{if(!M||!z)return;const ee=P.trim()||"new_directory",Z=`${M}/${ee}`;try{await Fe.createDirectory(Z);const ie=await ae(M),Me=oe=>oe.map(xe=>xe.path===M?{...xe,children:ie}:xe.children?{...xe,children:Me(xe.children)}:xe);x(oe=>Me(oe)),C(null),E("")}catch(ie){console.error("Failed to create directory:",ie)}},he=()=>{C(null),E("")},ye=(ee,Z=0)=>{const ie=g.has(ee.path),Me=ee.isDirectory,oe=D.has(ee.path),xe=t===ee.path,pe=n==="inline",je=e.jsxs(e.Fragment,{children:[Me&&e.jsx("button",{onClick:ce=>{ce.stopPropagation(),X(ee)},className:F("hover:bg-accent rounded","p-0.5"),children:ie?e.jsx(Ht,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(zs,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!Me&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:ce=>{ce.stopPropagation(),W(ee.path),n==="dropdown"&&a==="immediate"&&k(!1)},onDoubleClick:ce=>{ce.stopPropagation(),l&&l(ee.path)},className:F("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",pe&&xe?"text-primary":"text-foreground"),children:[e.jsx(nr,{className:F("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",pe&&xe&&"text-primary")}),e.jsx("span",{className:F("font-medium truncate","typography-ui-label",pe&&xe?"text-primary":"text-foreground"),children:ee.name})]}),e.jsx("button",{onClick:ce=>{ce.stopPropagation(),me(ee)},className:F("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(cs,{className:F("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:ce=>{ce.stopPropagation(),se(ee.path)},className:F("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:oe?"Unpin directory":"Pin directory",children:oe?e.jsx(mi,{className:F("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Wh,{className:F("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:F("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",xe?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${Z*(p?12:14)+(p?4:6)}px`},children:je}),ie&&e.jsxs(e.Fragment,{children:[M===ee.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(Z+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(nr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{ref:T,value:P,onChange:ce=>E(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"?(ce.preventDefault(),ce.stopPropagation(),G()):ce.key==="Escape"&&(ce.preventDefault(),ce.stopPropagation(),he())},onBlur:G,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(),G()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Qt,{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(es,{className:"h-3 w-3 text-muted-foreground"})})]}),ee.children&&ee.children.map(ce=>ye(ce,Z+1))]})]},ee.path):e.jsxs("div",{children:[e.jsxs(jt,{className:F("flex items-center gap-1 cursor-pointer group",t===ee.path&&"bg-accent"),style:{paddingLeft:`${Z*12+8}px`},onSelect:ce=>{ce.preventDefault()},children:[Me&&e.jsx("button",{onClick:ce=>{ce.stopPropagation(),X(ee)},className:"p-0.5 hover:bg-accent rounded",children:ie?e.jsx(Ht,{className:"h-3 w-3"}):e.jsx(zs,{className:"h-3 w-3"})}),!Me&&e.jsx("div",{className:"w-4"}),je]}),ie&&e.jsxs("div",{children:[M===ee.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(Z+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(nr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{ref:T,value:P,onChange:ce=>E(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"?(ce.preventDefault(),ce.stopPropagation(),G()):ce.key==="Escape"&&(ce.preventDefault(),ce.stopPropagation(),he())},onBlur:G,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(),G()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Qt,{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(es,{className:"h-3 w-3 text-muted-foreground"})})]}),ee.children&&ee.children.map(ce=>ye(ce,Z+1))]})]},ee.path)},ge=(ee,Z)=>{if(n==="inline"){const ie=t===Z;return e.jsxs("div",{className:F("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",ie?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>W(Z),onDoubleClick:Me=>{Me.stopPropagation(),l&&l(Z)},className:F("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",ie?"text-primary":"text-foreground"),children:[e.jsx(nr,{className:F("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",ie?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:F("typography-ui-label font-medium truncate flex-shrink-0",ie?"text-primary":"text-foreground"),children:ee}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:cn(Z,b)})]}),e.jsx("button",{onClick:()=>se(Z),className:F("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(mi,{className:F("text-primary","h-3.5 w-3.5")})})]},Z)}return e.jsxs(jt,{onSelect:ie=>{ie.preventDefault(),W(Z),a==="immediate"&&k(!1)},className:F("flex items-start gap-2 cursor-pointer group py-2",t===Z&&"bg-accent"),children:[e.jsx(nr,{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:ee}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:cn(Z,b)})]}),e.jsx("button",{onClick:ie=>{ie.stopPropagation(),ie.preventDefault(),se(Z)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(mi,{className:"h-3 w-3 text-primary"})})]},Z)},$e=e.jsx(e.Fragment,{children:z?e.jsxs(e.Fragment,{children:[L.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>A(ee=>!ee),className:F("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:[I?e.jsx(Ht,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(zs,{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:L.length})]}),I&&L.map(({name:ee,path:Z})=>ge(ee,Z)),n==="dropdown"&&e.jsx(Is,{}),n==="inline"&&I&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:F("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"}),y?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):h.map(ee=>ye(ee)),!y&&h.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:F("overflow-hidden flex flex-col",o),children:e.jsx(ht,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:$e})}):e.jsxs(ts,{open:S,onOpenChange:k,children:[e.jsx(ss,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",className:F("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",s),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(nr,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:t,children:cn(t,b)})]}),e.jsx(Ht,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(rs,{align:"start",className:"w-[350px]",children:e.jsx(ht,{outerClassName:"h-full",className:"w-full",children:$e})})]})},ni=(t,r=200)=>{const[s,n]=Re.useState(t);return Re.useEffect(()=>{const o=window.setTimeout(()=>{n(t)},r);return()=>{window.clearTimeout(o)}},[t,r]),s},Tf=i.forwardRef(({inputValue:t,homeDirectory:r,onSelectSuggestion:s,visible:n,onClose:o,showHidden:a},l)=>{const[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(0),h=i.useRef(null),x=i.useRef([]),g=i.useCallback((b,N)=>{const D=b.trim().toLowerCase();if(!D)return 0;const j=N.toLowerCase();let M=0,C=-1,P=0;for(let E=0;E<D.length;E+=1){const I=D[E];if(!I||I===" ")continue;const A=j.indexOf(I,C+1);if(A===-1)return null;const T=A-C-1;if(T===0?P+=1:P=0,M+=10,M+=Math.max(0,18-A),M-=Math.max(0,T),A===0)M+=12;else{const R=j[A-1];(R==="/"||R==="_"||R==="-"||R==="."||R===" ")&&(M+=10)}M+=P>0?12:0,C=A}return M+=Math.max(0,24-Math.round(j.length/3)),M},[]),w=i.useCallback(b=>b.startsWith("~")&&r?b.replace(/^~/,r):b,[r]),y=i.useCallback(b=>{const N=w(b);if(N.endsWith("/"))return N;const D=N.lastIndexOf("/");return D===-1?"":D===0?"/":N.substring(0,D+1)},[w]),v=i.useCallback(b=>{const N=w(b);if(N.endsWith("/"))return"";const D=N.lastIndexOf("/");return D===-1?N:N.substring(D+1)},[w]),S=ni(t,150);i.useEffect(()=>{if(!n||!S){d([]);return}const b=y(S),N=v(S).toLowerCase();if(!b){d([]);return}let D=!1;return m(!0),Fe.listLocalDirectory(b).then(j=>{if(D)return;const M=j.filter(P=>!(!P.isDirectory||!a&&P.name.startsWith("."))),C=N?M.map(P=>{const E=g(N,P.name);return E!==null?{entry:P,score:E}:null}).filter(P=>P!==null).sort((P,E)=>E.score-P.score||P.entry.name.localeCompare(E.entry.name)).map(P=>P.entry):M.sort((P,E)=>P.name.localeCompare(E.name));d(C.slice(0,10)),p(0)}).catch(()=>{D||d([])}).finally(()=>{D||m(!1)}),()=>{D=!0}},[n,S,y,v,a,g]),i.useEffect(()=>{x.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const b=N=>{const D=N.target;!D||!h.current||h.current.contains(D)||o()};return document.addEventListener("pointerdown",b,!0),()=>{document.removeEventListener("pointerdown",b,!0)}},[n,o]);const k=i.useCallback(b=>{const N=b.path.endsWith("/")?b.path:b.path+"/";s(N)},[s]);return i.useImperativeHandle(l,()=>({handleKeyDown:b=>{if(!n||c.length===0)return!1;const N=c.length;if(b.key==="Tab"){if(b.preventDefault(),b.shiftKey)p(D=>(D-1+N)%N);else if(N===1){const D=c[0];D&&k(D)}else p(D=>(D+1)%N);return!0}if(b.key==="ArrowDown")return b.preventDefault(),p(D=>(D+1)%N),!0;if(b.key==="ArrowUp")return b.preventDefault(),p(D=>(D-1+N)%N),!0;if(b.key==="Enter"){b.preventDefault();const D=(f%N+N)%N,j=c[D];return j&&k(j),o(),!0}return b.key==="Escape"?(b.preventDefault(),o(),!0):!1}}),[n,c,f,k,o]),!n||c.length===0&&!u?null:e.jsxs("div",{ref:h,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(Gr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:c.map((b,N)=>{const D=f===N;return e.jsxs("div",{ref:j=>{x.current[N]=j},className:F("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",D&&"bg-muted"),onClick:()=>{k(b),o()},onMouseEnter:()=>p(N),children:[e.jsx(ur,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:b.name})]},b.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"})]})});Tf.displayName="DirectoryAutocomplete";const Ff="directoryTreeShowHidden",gl="directory-show-hidden-change",Ad=()=>{if(typeof window>"u")return!1;try{return ws().getItem(Ff)==="true"}catch{return!1}},fv=()=>{typeof window>"u"||window.dispatchEvent(new Event(gl))},Rf=t=>{if(!(typeof window>"u"))try{ws().setItem(Ff,t?"true":"false"),fv()}catch{}},Po=()=>{const[t,r]=i.useState(Ad);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Ad())};return window.addEventListener("storage",s),window.addEventListener(gl,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(gl,s)}},[]),t},pv=({open:t,onOpenChange:r})=>{const{currentDirectory:s,homeDirectory:n,isHomeReady:o}=gt(),{addProject:a,getActiveProject:l}=zt(),[c,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(!1),g=Po(),{isDesktop:w,requestAccess:y,startAccessing:v}=ri(),{isMobile:S}=Yt(),[k,b]=i.useState(!1),N=i.useRef(null),D=i.useCallback(W=>W?cn(W,n):"",[n]);i.useEffect(()=>{if(t){p(!1),x(!1),b(!1);const B=l()?.path||s||n||"";d(B),m(D(B))}},[t,s,n,D,l]),i.useEffect(()=>{!t||f||c||n&&o&&(d(n),p(!0),m("~"))},[t,f,c,n,o]);const j=i.useCallback(()=>{r(!1)},[r]),M=i.useCallback(async W=>{if(!(!W||h)){x(!0);try{let B=W,se;if(w){const ae=await y(W);if(!ae.success){U.error("Unable to access directory",{description:ae.error||"Desktop denied directory access."});return}B=ae.path??W,se=ae.projectId;const O=await v(B);if(!O.success){U.error("Failed to open directory",{description:O.error||"Desktop could not grant file access."});return}}if(!a(B,{id:se})){U.error("Failed to add project",{description:"Please select a valid directory path."});return}j()}catch(B){U.error("Failed to select directory",{description:B instanceof Error?B.message:"Unknown error occurred."})}finally{x(!1)}}},[a,j,w,y,v,h]),C=i.useCallback(async()=>{const W=u.trim()||c;W&&await M(W)},[M,u,c]),P=i.useCallback(W=>{d(W),p(!0),m(D(W))},[D]),E=i.useCallback(async W=>{d(W),p(!0),m(D(W)),await M(W)},[M,D]),I=i.useCallback(W=>{const B=W.target.value;if(m(B),p(!0),b(B.startsWith("/")||B.startsWith("~")),B.startsWith("/")||B.startsWith("~")){const se=B.startsWith("~")&&n?B.replace(/^~/,n):B;d(se)}},[n]),A=i.useCallback(W=>{N.current?.handleKeyDown(W)||W.key==="Enter"&&(W.preventDefault(),C())},[C]),T=i.useCallback(W=>{d(W),p(!0),m(D(W))},[D]),R=i.useCallback(()=>{b(!1)},[]),K=i.useCallback(()=>{Rf(!g)},[g]),Y=e.jsxs("button",{type:"button",onClick:K,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:[g?e.jsx(xn,{className:"h-4 w-4 text-primary"}):e.jsx(yn,{className:"h-4 w-4"}),"Show hidden"]}),_=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(ks,{className:"flex-1",children:"Choose a folder to add as a project."}),Y]})]}),J=e.jsxs("div",{className:"relative",children:[e.jsx(bt,{value:u,onChange:I,onKeyDown:A,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(Tf,{ref:N,inputValue:u,homeDirectory:n,onSelectSuggestion:T,visible:k,onClose:R,showHidden:g})]}),q=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(Dd,{variant:"inline",currentPath:c??s,onSelectPath:P,onDoubleClickPath:E,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o})}),Q=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:J}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:Y}),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(Dd,{variant:"inline",currentPath:c??s,onSelectPath:P,onDoubleClickPath:E,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),z=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[J,q]}),H=()=>e.jsxs(e.Fragment,{children:[e.jsx(ve,{variant:"ghost",onClick:j,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(ve,{onClick:C,disabled:h||!f||!c&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:h?"Adding...":"Add Project"})]});return S?e.jsx(Bs,{open:t,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:H()}),children:Q}):e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{className:F("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:W=>{W.preventDefault()},children:[_,z,e.jsx(Us,{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:H()})]})})},Go=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,hv=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},gv=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=i.useRef(new Set),[a,l]=i.useState(null),[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(!1),{deleteSession:h,deleteSessions:x,loadSessions:g,getWorktreeMetadata:w}=fe(),{currentDirectory:y,homeDirectory:v,isHomeReady:S}=gt(),{projects:k,addProject:b,activeProjectId:N}=zt(),{requestAccess:D,startAccessing:j}=ri(),{isMobile:M,isTablet:C,hasTouchInput:P}=Yt(),E=M||C||P,I=i.useMemo(()=>{const V=(N?k.find(X=>X.id===N)??null:null)?.path??y;return hv(V)},[N,y,k]),A=i.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||c.some(O=>O.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,c]),T=i.useMemo(()=>{const O=a?.worktree;return O&&typeof O.branch=="string"&&O.branch.trim().length>0?!0:c.length>0&&c.every(({metadata:V})=>typeof V.branch=="string"&&V.branch.trim().length>0)},[a?.worktree,c]),R=a?.mode==="worktree",K=R,Y=f||!R||!T;i.useEffect(()=>{I&&(o.current.has(I)||eb(I).then(()=>o.current.add(I)).catch(O=>{console.warn("Failed to ensure .openchamber directory is ignored:",O),o.current.delete(I)}))},[I]),i.useEffect(()=>{g()},[g,y]);const _=i.useMemo(()=>k.map(O=>`${O.id}:${O.path}`).join("|"),[k]),J=i.useRef(_);i.useEffect(()=>{_!==J.current&&(J.current=_,g())},[g,_]),i.useEffect(()=>{if(!(s||!S||k.length>0)){if(n(!0),ds()){D("").then(async O=>{if(!O.success||!O.path){O.error&&O.error!=="Directory selection cancelled"&&U.error("Failed to select directory",{description:O.error});return}const V=await j(O.path);if(!V.success){U.error("Failed to open directory",{description:V.error||"Desktop could not grant file access."});return}b(O.path,{id:O.projectId})||U.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(O=>{console.error("Desktop: Error selecting directory:",O),U.error("Failed to select directory")});return}r(!0)}},[b,s,S,k.length,D,j]);const q=i.useCallback(O=>{l({sessions:O.sessions,dateLabel:O.dateLabel,mode:O.mode??"session",worktree:O.worktree??null})},[]),Q=i.useCallback(()=>{l(null),d([]),m(!1),p(!1)},[]);i.useEffect(()=>qn.onDeleteRequest(O=>{q(O)}),[q]),i.useEffect(()=>qn.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1);return}const O=a.sessions.map(X=>{const re=w(X.id);return re?{session:X,metadata:re}:null}).filter(X=>!!X);if(d(O),m(!1),O.length===0)return;let V=!1;return(async()=>{const X=await Promise.all(O.map(async({metadata:re})=>{if(re.status&&typeof re.status.isDirty=="boolean")return re.status;try{return await Eo(re.path)}catch{return re.status}})).catch(re=>(console.warn("Failed to inspect worktree status before deletion:",re),O.map(({metadata:me})=>me.status)));V||!Array.isArray(X)||d(re=>re.map((me,G)=>({session:me.session,metadata:{...me.metadata,status:X[G]??me.metadata.status}})))})(),()=>{V=!0}},[a,w]),i.useEffect(()=>{T||m(!1)},[T]);const z=i.useCallback(async()=>{if(a){p(!0);try{const O=K,V=O&&u;if(a.sessions.length===0&&R&&a.worktree){const X=u&&T;await of({projectDirectory:I,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:X});const re=X?"Worktree and remote branch removed.":"Worktree removed.";U.success("Worktree removed",{description:Go(re)}),Q(),g();return}if(a.sessions.length===1){const X=a.sessions[0];if(!await h(X.id,{archiveWorktree:O,deleteRemoteBranch:V})){U.error("Failed to delete session"),p(!1);return}const me=O?V?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;U.success("Session deleted",{description:Go(me),action:{label:"OK",onClick:()=>{}}})}else{const X=a.sessions.map(G=>G.id),{deletedIds:re,failedIds:me}=await x(X,{archiveWorktree:O,deleteRemoteBranch:V});if(re.length>0){const G=O?V?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,ye=[me.length>0?`${me.length} session${me.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,G].filter(Boolean).join(" ");U.success(`Deleted ${re.length} session${re.length===1?"":"s"}`,{description:Go(ye||void 0),action:{label:"OK",onClick:()=>{}}})}if(me.length>0&&(U.error(`Failed to delete ${me.length} session${me.length===1?"":"s"}`,{description:Go("Please try again in a moment.")}),re.length===0)){p(!1);return}}Q()}finally{p(!1)}}},[a,u,h,x,Q,K,R,T,I,g]),H=a?.worktree??c[0]?.metadata??null,W=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}`:""}.`:"",B=a?e.jsxs("div",{className:F(R?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&e.jsxs("div",{className:F(R?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[R&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:a.sessions.length===1?"Linked session":"Linked sessions"}),e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:a.sessions.length})]}),e.jsxs("ul",{className:F(R?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(O=>e.jsxs("li",{className:F(R?"flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground":"typography-micro text-muted-foreground/80"),children:[e.jsx("span",{className:F(!R&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:O.title||"Untitled Session"})]},O.id)),a.sessions.length>5&&e.jsxs("li",{className:F(R?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",a.sessions.length-5," more"]})]})]}),R?e.jsxs("div",{className:"space-y-2 rounded-lg bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),H?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:H.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:H?cn(H.path,v):"Worktree path unavailable."}),A&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."})]}):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,se=R?T?e.jsxs("button",{type:"button",onClick:()=>{Y||m(O=>!O)},disabled:Y,className:F("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",Y?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?e.jsx(xn,{className:"size-4 text-primary"}):e.jsx(yn,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,L=R?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[se,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve,{variant:"ghost",onClick:Q,disabled:f,children:"Cancel"}),e.jsx(ve,{variant:"destructive",onClick:z,disabled:f,children:f?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ve,{variant:"ghost",onClick:Q,disabled:f,children:"Cancel"}),e.jsx(ve,{variant:"destructive",onClick:z,disabled:f,children:f?"Deleting…":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),ae=R?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[E?e.jsx(Bs,{open:!!a,onClose:()=>{f||Q()},title:ae,footer:e.jsx("div",{className:"flex justify-end gap-2",children:L}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[W&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:W}),B]})}):e.jsx(ps,{open:!!a,onOpenChange:O=>{if(!O){if(f)return;Q()}},children:e.jsxs(hs,{className:F(R?"max-w-xl max-h-[70vh] flex flex-col overflow-hidden gap-3":"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2"),children:[e.jsxs(ys,{children:[e.jsxs(bs,{className:F(R&&"flex items-center gap-2"),children:[R&&e.jsx(qs,{className:"h-5 w-5"}),ae]}),W&&e.jsx(ks,{children:W})]}),e.jsx("div",{className:F(R&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:B}),e.jsx(Us,{className:"mt-2 gap-2 pt-1 pb-1",children:L})]})}),e.jsx(pv,{open:t,onOpenChange:r})]})};function xv(){return new Worker(Uh,{type:"module"})}const yv=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function bv(t,r,s){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s;return`${t}:${r.length}:${s.length}:${n.length}:${o.length}`}function Ed(t){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>t(void 0),0);return()=>window.clearTimeout(r)}const wv=({children:t})=>{const r=Gh(),s=ls(c=>c.activeDirectory),n=ls(c=>s?c.directories.get(s)?.lastStatusChange??0:0),o=ls(c=>s?c.directories.get(s)?.diffCache.size??0:0),a=Re.useRef(!1),l=Re.useRef(new Map);return Re.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Ji(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Re.useEffect(()=>{if(!r||!s||!n||o===0)return;const c=ls.getState().directories.get(s);if(!c||c.diffCache.size===0||(l.current.get(s)??0)>=c.lastStatusChange)return;l.current.set(s,c.lastStatusChange);let u=!1,m=null;const f=Array.from(c.diffCache.entries());let p=0;const h=x=>{if(u)return;const g=Date.now();for(;p<f.length&&!(x&&x.timeRemaining()<8||!x&&Date.now()-g>8);){const[w,y]=f[p];p+=1,_r(w);const v=bv(w,y.original,y.modified),S={name:w,contents:y.original,cacheKey:`old-${v}`},k={name:w,contents:y.modified,cacheKey:`new-${v}`},b=Ji(S,k),N={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(N,b)}p<f.length&&(m=Ed(h))};return h(void 0),p<f.length&&(m=Ed(h)),()=>{u=!0,m?.()}},[r,s,n,o]),e.jsx(e.Fragment,{children:t})},vv=({children:t})=>{const s=ti()?.currentTheme?.metadata?.variant==="dark";vf();const n=Re.useMemo(()=>({theme:{dark:Gn.dark,light:Gn.light},themeType:s?"dark":"light",langs:yv}),[s]);return e.jsx(Vh,{poolOptions:{workerFactory:xv,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(wv,{children:t})})},xl=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),jv=(t,r)=>{const s=xl(t),n=xl(r);return`${s}-${n}`.substring(0,60)},Id=(t,r)=>`${t}/${r}`,Sv=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Nv=()=>{const t=zt.getState(),r=t.activeProjectId,s=r?t.projects.find(c=>c.id===r)?.path:void 0;if(typeof s=="string"&&s.trim().length>0)return s;const n=gt.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,l=o.indexOf("/.openchamber/");return l>0?o.slice(0,l):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},yo=os()(us(t=>({isLoading:!1,error:null,createMultiRun:async r=>{const s=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:l,setupCommands:c}=r;if(!s)return t({error:"Group name is required"}),null;if(!n)return t({error:"Prompt is required"}),null;if(o.length<1)return t({error:"Select at least 1 model"}),null;if(o.length>5)return t({error:"Maximum 5 models allowed"}),null;t({isLoading:!0,error:null});try{const d=Nv();if(!d)return t({error:"No directory selected",isLoading:!1}),null;if(!await Or(d))return t({error:"Not in a git repository",isLoading:!1}),null;const m=xl(s),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,h=[],x=c?.filter(b=>b.trim().length>0)??[],g=new Map;for(const b of o){const N=`${b.providerID}:${b.modelID}`;g.set(N,(g.get(N)||0)+1)}const w=new Map;for(const b of o){const N=`${b.providerID}:${b.modelID}`,D=g.get(N)||1,j=(w.get(N)||0)+1;w.set(N,j);const M=jv(b.providerID,b.modelID),C=D>1?Id(m,`${M}/${j}`):Id(m,M);if(!C)return t({error:"Branch name is required for worktree creation",isLoading:!1}),null;const P=Sv(C);if(!P)return t({error:`Invalid branch name: ${C}`,isLoading:!1}),null;try{const E=await Za({projectDirectory:d,worktreeSlug:P,branch:C,createBranch:!0,startPoint:p}),I=D>1?`${m}/${b.providerID}/${b.modelID}/${j}`:`${m}/${b.providerID}/${b.modelID}`,A=await Fe.withDirectory(E.path,()=>Fe.createSession({title:I}));pt.getState().setWorktreeMetadata(A.id,E),h.push({sessionId:A.id,worktreePath:E.path,providerID:b.providerID,modelID:b.modelID,variant:b.variant})}catch(E){console.warn("[MultiRun] Failed to create session:",E)}}const y=c?.filter(b=>b.trim().length>0)??[];y.length>0&&sf(d,y).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const v=h.map(b=>b.sessionId),S=h[0]?.sessionId??null;if(v.length===0)return t({error:"Failed to create any sessions",isLoading:!1}),null;const k=l?.map(b=>({type:"file",mime:b.mime,filename:b.filename,url:b.url}));try{await pt.getState().loadSessions()}catch{}if(x.length>0)for(const b of h)ei(b.worktreePath,d,x).then(N=>{if(!N.success){const D=N.results.filter(j=>!j.success);console.warn(`[MultiRun] Setup commands failed for ${b.worktreePath}:`,D)}}).catch(N=>{console.warn(`[MultiRun] Setup commands error for ${b.worktreePath}:`,N)});return(async()=>{try{await Promise.allSettled(h.map(async b=>{try{await Fe.withDirectory(b.worktreePath,()=>Fe.sendMessage({id:b.sessionId,providerID:b.providerID,modelID:b.modelID,variant:b.variant,text:n,agent:a,files:k}))}catch(N){console.warn("[MultiRun] Failed to start run:",N)}}))}catch(b){console.warn("[MultiRun] Failed to start runs:",b)}})(),t({isLoading:!1}),{groupSlug:m,sessionIds:v,firstSessionId:S}}catch(d){return t({error:d instanceof Error?d.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{t({error:null})}}),{name:"multirun-store"}));function Os({...t}){return e.jsx(qh,{"data-slot":"select",...t})}function mn({...t}){return e.jsx(eg,{"data-slot":"select-group",...t})}function bn({...t}){return e.jsx(Yh,{"data-slot":"select-value",...t})}function _s({className:t,size:r="default",children:s,...n}){return e.jsxs(Kh,{"data-slot":"select-trigger","data-size":r,className:F("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",t),...n,children:[s,e.jsx(Qh,{asChild:!0,children:e.jsx(Ht,{className:"size-4 opacity-50"})})]})}function $s({className:t,children:r,position:s="popper",fitContent:n=!1,...o}){return e.jsx(Xh,{children:e.jsx(Jh,{"data-slot":"select-content",className:F("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",s==="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",t),position:s,...o,children:e.jsx(ht,{as:Zh,outerClassName:F("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:F("p-1",s==="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 Bn({className:t,...r}){return e.jsx(tg,{"data-slot":"select-label",className:F("text-muted-foreground px-2 py-1.5 typography-meta",t),...r})}function ns({className:t,children:r,...s}){return e.jsxs(sg,{"data-slot":"select-item",className:F("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",t),...s,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(rg,{children:e.jsx(Qt,{className:"size-4"})})}),e.jsx(ng,{children:r})]})}function Oa({className:t,...r}){return e.jsx(og,{"data-slot":"select-separator",className:F("bg-border pointer-events-none -mx-1 my-1 h-px",t),...r})}const kv="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",Cv=Object.assign({"../assets/provider-logos/gocode.svg":kv}),yl=new Map;for(const[t,r]of Object.entries(Cv)){const s=t.match(/provider-logos\/([^/]+)\.svg$/i);s?.[1]&&r&&yl.set(s[1].toLowerCase(),r)}function Lf(t){const r=t?.toLowerCase()??null,s=r?yl.has(r):!1,n=r?yl.get(r)??null:null,[o,a]=Re.useState(s?"local":"remote");Re.useEffect(()=>{a(s?"local":"remote")},[s,r]);const l=Re.useCallback(()=>{a(c=>c==="local"&&s?"remote":"none")},[s]);return r?o==="local"&&n?{src:n,onError:l,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}:{src:null,onError:l,hasLogo:!1}}const Ns=({providerId:t,alt:r,className:s,onError:n})=>{const{src:o,onError:a,hasLogo:l}=Lf(t),c=i.useCallback(()=>{a(),n?.()},[a,n]);return!l||!o?null:e.jsx("img",{src:o,alt:r||`${t} logo`,className:F("dark:invert",s),onError:c})},lc=t=>t.nativeEvent.isComposing||t.nativeEvent.keyCode===229,cc=()=>{const{providers:t}=et(),{favoriteModels:r,recentModels:s}=ke(),n=i.useMemo(()=>r.map(({providerID:a,modelID:l})=>{const c=t.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null),[r,t]),o=i.useMemo(()=>s.map(({providerID:a,modelID:l})=>{const c=t.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!r.some(c=>c.providerID===a&&c.modelID===l)),[s,t,r]);return{favoriteModelsList:n,recentModelsList:o}},Of="h-7",_a=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Mv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Dv=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=Mv.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Av=({model:t,instanceIndex:r,totalSameModel:s,onRemove:n})=>{const o=t.displayName||`${t.providerID}/${t.modelID}`,a=s>1?`${o} (${r})`:o;return e.jsxs("div",{className:F("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",Of),children:[e.jsx(Ns,{providerId:t.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(es,{className:"h-3.5 w-3.5"})})]})},_f=({selectedModels:t,onAdd:r,onRemove:s,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:l=!0,maxModels:c})=>{const{providers:d,modelsMetadata:u}=et(),{favoriteModelsList:m,recentModelsList:f}=cc(),[p,h]=i.useState(!1),[x,g]=i.useState(""),[w,y]=i.useState(0),[v,S]=i.useState(null),k=i.useRef(null),b=i.useRef(null),N=i.useRef(null),D=i.useRef([]),j=i.useMemo(()=>{const Y=new Map;for(const _ of t){const J=`${_.providerID}:${_.modelID}`;Y.set(J,(Y.get(J)||0)+1)}return Y},[t]),M=i.useCallback(Y=>t.filter(J=>J.providerID===Y.providerID&&J.modelID===Y.modelID).findIndex(J=>J.instanceId===Y.instanceId)+1,[t]),C=(Y,_)=>{const J=`${Y}/${_}`;return u.get(J)},P=Y=>{const _=Y?.name||Y?.id||"",J=String(_);return J.length>40?J.substring(0,37)+"...":J},E=i.useCallback((Y,_)=>{if(!x.trim())return!0;const J=x.toLowerCase();return Y.toLowerCase().includes(J)||_.toLowerCase().includes(J)},[x]),I=i.useMemo(()=>m.filter(({model:Y,providerID:_})=>{const q=d.find(z=>z.id===_)?.name||_,Q=P(Y);return E(Q,q)}),[m,d,E]),A=i.useMemo(()=>f.filter(({model:Y,providerID:_})=>{const q=d.find(z=>z.id===_)?.name||_,Q=P(Y);return E(Q,q)}),[f,d,E]),T=i.useMemo(()=>d.map(Y=>{const J=(Array.isArray(Y.models)?Y.models:[]).filter(q=>{const Q=P(q);return E(Q,Y.name||Y.id||"")});return{...Y,models:J}}).filter(Y=>Y.models.length>0),[d,E]),R=I.length>0||A.length>0||T.length>0;i.useEffect(()=>{if(p&&N.current){const _=N.current.getBoundingClientRect().top-100;S(Math.max(150,Math.min(400,_)))}},[p]),i.useEffect(()=>{p&&k.current&&k.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const Y=_=>{b.current&&!b.current.contains(_.target)&&(h(!1),g(""),y(0))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[p]),i.useEffect(()=>{y(0)},[x]);const K=(Y,_,J,q,Q,z)=>{const H=`${_}:${J}`,W=j.get(H)||0,B=C(_,J),se=Dv(B?.limit?.context);return e.jsxs("button",{ref:L=>{D.current[Q]=L},type:"button",onClick:()=>{r({providerID:_,modelID:J,displayName:Y.name||J,instanceId:_a()})},onMouseEnter:()=>y(Q),className:F("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",z?"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:P(Y)}),se&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:se})]}),W>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",W]})]},`${q}-${H}`)};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:b,children:[e.jsxs(ve,{ref:N,type:"button",variant:"outline",size:"sm",className:Of,onClick:()=>h(!p),children:[e.jsx(cs,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const Y=[];I.forEach(({model:Q,providerID:z,modelID:H})=>{Y.push({model:Q,providerID:z,modelID:H,section:"fav"})}),A.forEach(({model:Q,providerID:z,modelID:H})=>{Y.push({model:Q,providerID:z,modelID:H,section:"recent"})}),T.forEach(Q=>{Q.models.forEach(z=>{Y.push({model:z,providerID:Q.id,modelID:z.id,section:"provider"})})});const _=Y.length,J=Q=>{if(!lc(Q))if(Q.key==="ArrowDown"){Q.preventDefault(),Q.stopPropagation();const z=(w+1)%Math.max(1,_);y(z),setTimeout(()=>{D.current[z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Q.key==="ArrowUp"){Q.preventDefault(),Q.stopPropagation();const z=(w-1+Math.max(1,_))%Math.max(1,_);y(z),setTimeout(()=>{D.current[z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Q.key==="Enter"){Q.preventDefault(),Q.stopPropagation();const z=Y[w];z&&r({providerID:z.providerID,modelID:z.modelID,displayName:z.model.name||z.modelID,instanceId:_a()})}else Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),h(!1),g(""),y(0))};let q=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(Ws,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{ref:k,type:"text",placeholder:"Search models",value:x,onChange:Q=>g(Q.target.value),onKeyDown:J,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(ht,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!R&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),I.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(Ar,{className:"h-4 w-4 text-primary"}),"Favorites"]}),I.map(({model:Q,providerID:z,modelID:H})=>{const W=q++;return K(Q,z,H,"fav",W,w===W)})]}),A.length>0&&e.jsxs(e.Fragment,{children:[I.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(jr,{className:"h-4 w-4"}),"Recent"]}),A.map(({model:Q,providerID:z,modelID:H})=>{const W=q++;return K(Q,z,H,"recent",W,w===W)})]}),(I.length>0||A.length>0)&&T.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),T.map((Q,z)=>e.jsxs(i.Fragment,{children:[z>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(Ns,{providerId:Q.id,className:"h-4 w-4 flex-shrink-0"}),Q.name]}),Q.models.map(H=>{const W=q++;return K(H,Q.id,H.id,"provider",W,w===W)})]},Q.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),l&&t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:t.map((Y,_)=>{const J=`${Y.providerID}:${Y.modelID}`,q=j.get(J)||1,Q=M(Y),H=d.find(ae=>ae.id===Y.providerID)?.models.find(ae=>ae.id===Y.modelID),W=H?.variants?Object.keys(H.variants):[],B=W.length>0,se="__default__",L=Y.variant??se;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Av,{model:Y,instanceIndex:Q,totalSameModel:q,onRemove:()=>s(_)}),B&&e.jsxs(Os,{value:L,onValueChange:ae=>{if(!n)return;n(_,{...Y,variant:ae===se?void 0:ae})},children:[e.jsxs(_s,{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(Sr,{className:F("h-3.5 w-3.5 flex-shrink-0",L===se?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(bn,{placeholder:"Thinking"})]}),e.jsxs($s,{fitContent:!0,children:[e.jsx(ns,{value:se,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),W.map(ae=>e.jsx(ns,{value:ae,className:"pr-2 [&>span:first-child]:hidden",children:ae},ae))]})]})]},Y.instanceId)})})]}),o!==void 0&&t.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",c!==void 0?`to ${c} models`:"","."]})]})};function dc(t){const[r,s]=i.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=i.useState(!1),[a,l]=i.useState(null);return i.useEffect(()=>{let c=!1;if(!t){l(null),o(!1),s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),l(null),(async()=>{try{const d=await Or(t);if(c)return;if(l(d),!d){s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await Ja(t).catch(()=>null);if(c)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(x=>!x.startsWith("remotes/")).sort((x,g)=>x.localeCompare(g)).forEach(x=>{m.push({value:x,label:x,group:"local"})}),u.all.filter(x=>x.startsWith("remotes/")).map(x=>x.replace(/^remotes\//,"")).sort((x,g)=>x.localeCompare(g)).forEach(x=>{m.push({value:x,label:x,group:"remote"})})),s(m)}finally{c||o(!1)}})(),()=>{c=!0}},[t]),{branches:r,isLoading:n,isGitRepository:a}}const $f=({directory:t,value:r,onChange:s,className:n,disabled:o,id:a})=>{const{branches:l,isLoading:c,isGitRepository:d}=dc(t),u=i.useMemo(()=>l.find(f=>f.value===r)?.label??null,[l,r]);i.useEffect(()=>{!l.some(p=>p.value===r)&&l.length>0&&s("HEAD")},[l,r,s]);const m=o||!d||c;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Os,{value:r,onValueChange:s,disabled:m,children:[e.jsx(_s,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(bn,{children:u}):e.jsx(bn,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs($s,{fitContent:!0,children:[e.jsxs(mn,{children:[e.jsx(Bn,{children:"Default"}),l.filter(f=>f.group==="special").map(f=>e.jsx(ns,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),l.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(Oa,{}),e.jsxs(mn,{children:[e.jsx(Bn,{children:"Local branches"}),l.filter(f=>f.group==="local").map(f=>e.jsx(ns,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,l.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(Oa,{}),e.jsxs(mn,{children:[e.jsx(Bn,{children:"Remote branches"}),l.filter(f=>f.group==="remote").map(f=>e.jsx(ns,{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."})]})},Bf=({value:t,onChange:r,className:s,disabled:n,id:o})=>{const a=et(f=>f.getVisibleAgents),l=et(f=>f.loadAgents),c=et(f=>f.currentAgentName),d=a(),u=i.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(n)return;const f=t.trim();if(f.length>0&&u.some(x=>x.name===f))return;const p=typeof c=="string"&&c.trim().length>0?c.trim():null;if(p&&u.some(x=>x.name===p)){r(p);return}const h=u[0]?.name;h&&r(h)},[c,n,r,u,t]);const m=t.trim().length>0?t:void 0;return e.jsxs(Os,{value:m,onValueChange:r,disabled:n,children:[e.jsx(_s,{id:o,size:"lg",className:s??"max-w-full typography-meta text-foreground",children:e.jsx(bn,{placeholder:"Select an agent"})}),e.jsx($s,{fitContent:!0,children:u.length>0&&e.jsx(mn,{children:u.map(f=>e.jsx(ns,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},Ev=10*1024*1024,Pd=5,Td=({initialPrompt:t,onCreated:r,onCancel:s})=>{const[n,o]=i.useState(""),[a,l]=i.useState(()=>t??""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState([]),[h,x]=i.useState(!1),[g,w]=i.useState([]),[y,v]=i.useState(!1),[S,k]=i.useState(!1),b=i.useRef(null),N=gt(O=>O.currentDirectory??null),D=i.useMemo(()=>{if(typeof window>"u")return null;const O=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof O=="string"&&O.trim().length>0?O.trim():null},[]),j=zt(O=>O.activeProjectId),M=zt(O=>O.projects),C=i.useMemo(()=>{if(j){const me=M.find(G=>G.id===j);if(me?.path)return me.path}const O=N??D;if(!O)return null;const V=O.replace(/\\/g,"/").replace(/\/+$/,"")||O,re=V.indexOf("/.openchamber/");return re>0?V.slice(0,re):V.endsWith("/.openchamber")?V.slice(0,V.length-13):V},[j,M,N,D]),P=ke(O=>O.isSidebarOpen),[E,I]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),A=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const O=typeof window.opencodeDesktop<"u";I(O)},[]);const T=i.useMemo(()=>E&&A?P?"pl-0":"pl-[8.0rem]":"pl-3",[E,A,P]),[R,K]=i.useState("HEAD"),{isLoading:Y,isGitRepository:_}=dc(N),J=yo(O=>O.createMultiRun),q=yo(O=>O.error),Q=yo(O=>O.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&l(O=>O.trim().length>0?O:t)},[t]),i.useEffect(()=>{if(!C)return;let O=!1;return k(!0),(async()=>{try{const V=await Sn(C);O||w(V)}catch{}finally{O||k(!1)}})(),()=>{O=!0}},[C]);const z=O=>{c.length>=Pd||(d(V=>[...V,O]),Q())},H=O=>{d(V=>V.filter((X,re)=>re!==O)),Q()},W=i.useCallback((O,V)=>{d(X=>X.map((re,me)=>me===O?V:re))},[]),B=async O=>{const V=O.target.files;if(!V)return;let X=0;for(let re=0;re<V.length;re++){const me=V[re];if(me.size>Ev){U.error(`File "${me.name}" is too large (max 10MB)`);continue}try{const G=await new Promise((ye,ge)=>{const $e=new FileReader;$e.onload=()=>ye($e.result),$e.onerror=ge,$e.readAsDataURL(me)}),he={id:_a(),filename:me.name,mimeType:me.type||"application/octet-stream",size:me.size,dataUrl:G};p(ye=>[...ye,he]),X++}catch(G){console.error("File attach failed",G),U.error(`Failed to attach "${me.name}"`)}}X>0&&U.success(`Attached ${X} file${X>1?"s":""}`),b.current&&(b.current.value="")},se=O=>{p(V=>V.filter(X=>X.id!==O))},L=async O=>{if(O.preventDefault(),!!a.trim()&&!(c.length<2)){x(!0),Q();try{const V=c.map(({instanceId:he,...ye})=>ye),X=f.map(he=>({mime:he.mimeType,filename:he.filename,url:he.dataUrl})),re=g.filter(he=>he.trim().length>0),me={name:n.trim(),prompt:a.trim(),models:V,agent:u||void 0,worktreeBaseBranch:R,files:X.length>0?X:void 0,setupCommands:re.length>0?re:void 0},G=await J(me);G&&(G.firstSessionId&&fe.getState().setCurrentSession(G.firstSessionId),r?.())}finally{x(!1)}}},ae=!!(n.trim()&&a.trim()&&c.length>=2&&_&&!Y);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:F("flex h-12 items-center justify-between border-b app-region-drag",T),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:F("flex items-center gap-3",E&&A&&P&&"pl-4"),children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),s&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"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(es,{className:"h-5 w-5"})})}),e.jsx(it,{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:L,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(bt,{id:"group-name",value:n,onChange:O=>o(O.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($f,{directory:N,value:R,onChange:K,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:R||"HEAD"}),"."]})]}),e.jsxs(eo,{open:y,onOpenChange:v,children:[e.jsxs(Io,{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",g.filter(O=>O.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",g.filter(O=>O.trim()).length," configured)"]})]}),e.jsx(Ht,{className:F("h-4 w-4 text-muted-foreground transition-transform duration-200",y&&"rotate-180")})]}),e.jsx(to,{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."]}),S?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[g.map((O,V)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(bt,{value:O,onChange:X=>{const re=[...g];re[V]=X.target.value,w(re)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const X=g.filter((re,me)=>me!==V);w(X)},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(es,{className:"h-4 w-4"})})]},V)),e.jsxs("button",{type:"button",onClick:()=>w([...g,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(cs,{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(Bf,{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(Rs,{id:"prompt",value:a,onChange:O=>l(O.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:b,type:"file",multiple:!0,className:"hidden",onChange:B,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(ve,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>b.current?.click(),children:[e.jsx(va,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(O=>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:[O.mimeType.startsWith("image/")?e.jsx(Nr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(yr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:O.filename,children:O.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",O.size<1024?`${O.size}B`:O.size<1024*1024?`${(O.size/1024).toFixed(1)}KB`:`${(O.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>se(O.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(es,{className:"h-3.5 w-3.5"})})]},O.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(_f,{selectedModels:c,onAdd:z,onRemove:H,onUpdate:W,minModels:2,maxModels:Pd})]}),q&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:q}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(ve,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),e.jsx(ve,{type:"submit",disabled:!ae||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(ag,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},Iv=(t={})=>{const{edgeThreshold:r=30,minSwipeDistance:s=50,maxSwipeTime:n=300,enabled:o=!0}=t,{isMobile:a,setSessionSwitcherOpen:l,isSessionSwitcherOpen:c}=ke(),d=Re.useRef(null),u=Re.useRef(null);return Re.useEffect(()=>{if(!o||!a)return;const m=x=>{const g=x.touches[0];if(!g){d.current=null;return}g.clientX<=r?d.current={x:g.clientX,y:g.clientY,time:Date.now()}:d.current=null},f=x=>{if(!d.current)return;const g=x.touches[0];if(!g)return;g.clientX-d.current.x>10&&x.preventDefault()},p=x=>{if(!d.current)return;const g=x.changedTouches[0];if(!g){d.current=null,u.current=null;return}u.current={x:g.clientX,y:g.clientY,time:Date.now()};const{x:w,y,time:v}=d.current,{x:S,y:k,time:b}=u.current,N=S-w,D=k-y,j=b-v,M=Math.abs(D)<Math.abs(N),C=j<=n,P=Math.abs(D)<s;N>=s&&M&&C&&P&&!c&&l(!0),d.current=null,u.current=null},h=()=>{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",h,{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",h,{capture:!0})}},[o,a,r,s,n,l,c]),null},uo=t=>t==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:t==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;Re.memo(()=>{const t=Re.useRef(null),{addAttachedFile:r}=fe(),{isMobile:s}=ke(),n=xf(),o=s?"h-9 w-9":"h-7 w-7",a=s?"h-5 w-5":"h-[18px] w-[18px]",l=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],h=fe.getState().attachedFiles.length;try{await r(p),fe.getState().attachedFiles.length>h&&m++}catch(x){console.error("File attach failed",x),U.error(x instanceof Error?x.message:"Failed to attach file")}}m>0&&U.success(`Attached ${m} file${m>1?"s":""}`)},c=async u=>{const m=u.target.files;m&&(await l(m),t.current&&(t.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 x=p.map(g=>`${g?.name||"file"}: ${g?.reason||"skipped"}`).join(`
163
- `);U.error(`Some files were skipped:
164
- ${x}`)}const h=f.map(x=>{if(!x?.dataUrl)return null;try{const[g,w]=x.dataUrl.split(","),y=x.mimeType||g?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!w)return null;const v=atob(w),S=new Uint8Array(v.length);for(let b=0;b<v.length;b++)S[b]=v.charCodeAt(b);const k=new Blob([S],{type:y});return new File([k],x.name||"file",{type:y})}catch(g){return console.error("Failed to decode VS Code picked file",g),null}}).filter(Boolean);h.length>0&&await l(h)}catch(u){console.error("VS Code file pick failed",u),U.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:t,type:"file",multiple:!0,className:"hidden",onChange:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():t.current?.click()},className:F(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(va,{className:F(a,"text-current")})})]})});const Pv=Re.memo(({file:t,onRemove:r})=>{const s=()=>t.mimeType.startsWith("image/")?e.jsx(Nr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("text")||t.mimeType.includes("code")?e.jsx(yr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("json")||t.mimeType.includes("xml")?e.jsx(Ua,{className:"h-3.5 w-3.5"}):e.jsx(yr,{className:"h-3.5 w-3.5"}),n=l=>l<1024?l+" B":l<1048576?(l/1024).toFixed(1)+" KB":(l/1048576).toFixed(1)+" MB",a=(l=>{const d=l.replace(/\\/g,"/").split("/");return d[d.length-1]||l})(t.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:t.source==="server"?"Server file":"Local file",children:t.source==="server"?e.jsx(ig,{className:"h-3 w-3 text-primary"}):e.jsx(dm,{className:"h-3 w-3 text-muted-foreground"})}),s(),e.jsx("div",{className:"overflow-hidden max-w-[200px]",children:e.jsx("span",{className:"marquee-text",title:t.serverPath||a,children:a})}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",n(t.size),")"]}),e.jsx("button",{onClick:r,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(es,{className:"h-3 w-3"})})]})}),Tv=Re.memo(()=>{const{attachedFiles:t,removeAttachedFile:r}=fe();return t.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:"}),t.map(s=>e.jsx(Pv,{file:s,onRemove:()=>r(s.id)},s.id))]})})}),zf=Re.memo(({files:t,onShowPopup:r})=>{const s=t.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(Nr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(yr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Ua,{className:"h-3.5 w-3.5"}):e.jsx(yr,{className:"h-3.5 w-3.5"}):e.jsx(yr,{className:"h-3.5 w-3.5"}),a=s.filter(d=>d.mime?.startsWith("image/")&&d.url),l=s.filter(d=>!d.mime?.startsWith("image/")),c=i.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return s.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("div",{className:"overflow-hidden max-w-[200px]",children:e.jsx("span",{className:"marquee-text",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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>c(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(Nr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(it,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Hf=Re.memo(({message:t,sessionId:r,onEdit:s})=>{const n=xr(l=>l.removeFromQueue),o=i.useMemo(()=>{const l=t.content.split(`
165
- `),c=l[0]||"",d=50;return c.length>d?c.substring(0,d)+"...":c+(l.length>1?"...":"")},[t.content]),a=t.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(lg,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>s(t),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,t.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(es,{className:"h-3 w-3"})})]})});Hf.displayName="QueuedMessageChip";const Fd=[],Wf=Re.memo(({onEditMessage:t})=>{const r=fe(a=>a.currentSessionId),s=xr(i.useCallback(a=>r?a.queuedMessages[r]??Fd:Fd,[r])),n=xr(a=>a.popToInput),o=i.useCallback(a=>{if(!r)return;const l=n(r,a.id);if(l){if(l.attachments&&l.attachments.length>0){const c=lr.getState().attachedFiles;lr.setState({attachedFiles:[...c,...l.attachments]})}t(l.content,l.attachments)}},[r,n,t]);return s.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:"}),s.map(a=>e.jsx(Hf,{message:a,sessionId:r,onEdit:o},a.id))]})})});Wf.displayName="QueuedMessageChips";const Uf="filesViewShowGitignored",bl="files-view-show-gitignored-change",Rd=()=>{if(typeof window>"u")return!1;try{return ws().getItem(Uf)==="true"}catch{return!1}},Fv=()=>{typeof window>"u"||window.dispatchEvent(new Event(bl))},Rv=t=>{if(!(typeof window>"u"))try{ws().setItem(Uf,t?"true":"false"),Fv()}catch{}},oi=()=>{const[t,r]=i.useState(Rd);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Rd())};return window.addEventListener("storage",s),window.addEventListener(bl,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(bl,s)}},[]),t},Lv=i.forwardRef(({searchQuery:t,onFileSelect:r,onClose:s},n)=>{const{currentDirectory:o}=gt(),{addServerFile:a}=fe(),l=Ya(I=>I.searchFiles),c=ni(t,180),d=Po(),u=oi(),[m,f]=i.useState([]),[p,h]=i.useState(!1),[x,g]=i.useState(0),[w,y]=i.useState(360),[v,S]=i.useState({}),[k,b]=i.useState({}),N=i.useRef([]),D=i.useRef([]),j=i.useRef([]),M=i.useRef(null),C=i.useCallback((I,A)=>{const T=I.trim().toLowerCase();if(!T)return 0;const R=A.toLowerCase();let K=0,Y=-1,_=0;for(let J=0;J<T.length;J+=1){const q=T[J];if(!q||q===" ")continue;const Q=R.indexOf(q,Y+1);if(Q===-1)return null;const z=Q-Y-1;if(z===0?_+=1:_=0,K+=10,K+=Math.max(0,18-Q),K-=Math.max(0,z),Q===0)K+=12;else{const H=R[Q-1];(H==="/"||H==="_"||H==="-"||H==="."||H===" ")&&(K+=10)}K+=_>0?12:0,Y=Q}return K+=Math.max(0,24-Math.round(R.length/3)),K},[]);i.useEffect(()=>{const I=A=>{const T=A.target;!T||!M.current||M.current.contains(T)||s()};return document.addEventListener("pointerdown",I,!0),()=>{document.removeEventListener("pointerdown",I,!0)}},[s]),i.useEffect(()=>{if(!o){f([]);return}const A=(c??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();let T=!1;return h(!0),l(o,A,80,{includeHidden:d,respectGitignore:!u}).then(R=>{if(T)return;const K=A?R.map(Y=>{const _=Y.relativePath||Y.name||Y.path,J=C(A,_);return J===null?null:{file:Y,score:J,labelLength:_.length}}).filter(Boolean):R.map(Y=>({file:Y,score:0,labelLength:(Y.relativePath||Y.name||Y.path).length}));K.sort((Y,_)=>_.score-Y.score||Y.labelLength-_.labelLength||Y.file.path.localeCompare(_.file.path)),f(K.slice(0,15).map(Y=>Y.file))}).catch(()=>{T||f([])}).finally(()=>{T||h(!1)}),()=>{T=!0}},[o,c,C,l,d,u]),i.useEffect(()=>{g(0),S({}),b({})},[m]),i.useEffect(()=>{N.current[x]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]),i.useEffect(()=>{let I=null;const A=()=>{I!==null&&cancelAnimationFrame(I),I=requestAnimationFrame(()=>{const T={},R={};D.current.forEach((K,Y)=>{if(!K)return;const J=j.current[Y]?.offsetWidth??K.scrollWidth,q=Math.max(0,J-K.clientWidth),Q=q>8;if(T[Y]=Q,Q){const z=Math.max(.6,q/110);R[Y]=z}}),S(T),b(R)})};return A(),window.addEventListener("resize",A),()=>{I!==null&&cancelAnimationFrame(I),window.removeEventListener("resize",A)}},[m]),i.useEffect(()=>{const I=D.current[x];if(!I)return;const A=()=>{const R=I.clientWidth;R>0&&y(R)};if(A(),typeof ResizeObserver>"u")return;const T=new ResizeObserver(A);return T.observe(I),()=>{T.disconnect()}},[x]);const P=i.useCallback(async I=>{await a(I.path,I.name),r(I)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:I=>{if(I==="Escape"){s();return}const A=m.length;if(A!==0){if(I==="ArrowDown"){g(T=>(T+1)%A);return}if(I==="ArrowUp"){g(T=>(T-1+A)%A);return}if(I==="Enter"||I==="Tab"){const T=(x%A+A)%A,R=m[T];R&&P(R)}}}}),[m,x,s,P]);const E=I=>{switch(I.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(Ys,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Ys,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(yr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Nr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Ua,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:M,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(ht,{outerClassName:"flex-1 min-h-0",className:"px-0",children:p?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Gr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[m.map((I,A)=>{const T=I.relativePath||I.name,R=Rm(T,{maxLength:45}),K=x===A,Y=v[A]??!1,_=k[A]??2.6,J=e.jsxs("div",{ref:q=>{N.current[A]=q},className:F("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",K&&"bg-muted"),onClick:()=>P(I),onMouseEnter:()=>g(A),children:[E(I),e.jsxs("span",{ref:q=>{D.current[A]=q},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:K?{"--file-mention-marquee-width":`${w}px`,"--file-mention-marquee-duration":`${_}s`}:void 0,"aria-label":T,children:[e.jsx("span",{ref:q=>{j.current[A]=q},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:T}),Y&&K?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:T}):e.jsx("span",{className:"block truncate",children:R})]})]});return e.jsx(i.Fragment,{children:J},I.path)}),m.length>0&&e.jsx("div",{className:"h-2"}),m.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"})]})}),Vf=i.forwardRef(({searchQuery:t,onCommandSelect:r,onClose:s},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=fe(Rl(v=>{const S=v.currentSessionId;return{hasMessagesInCurrentSession:(S?v.messages.get(S)?.length??0:0)>0,currentSessionId:S}})),l=!!a,[c,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=Jr(),[h,x]=i.useState(0),g=i.useRef([]),w=i.useRef(null);i.useEffect(()=>{const v=S=>{const k=S.target;!k||!w.current||w.current.contains(k)||s()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[s]),i.useEffect(()=>{p()},[p]),i.useEffect(()=>{(async()=>{m(!0);try{const S=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})),k=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],b=new Map;k.forEach(M=>b.set(M.name,M)),S.forEach(M=>b.set(M.name,M));const N=Array.from(b.values()),D=!o,j=(t?N.filter(M=>Ks(M.name,t)||M.description&&Ks(M.description,t)):N).filter(M=>D||M.name!=="init");j.sort((M,C)=>{const P=M.name.toLowerCase().startsWith(t.toLowerCase()),E=C.name.toLowerCase().startsWith(t.toLowerCase());return P&&!E?-1:!P&&E?1:M.name.localeCompare(C.name)}),d(j)}catch{const S=!o,k=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],b=(t?k.filter(N=>Ks(N.name,t)||N.description&&Ks(N.description,t)):k).filter(N=>S||N.name!=="init");d(b)}finally{m(!1)}})()},[t,o,l,f]),i.useEffect(()=>{x(0)},[c]),i.useEffect(()=>{g.current[h]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[h]),i.useImperativeHandle(n,()=>({handleKeyDown:v=>{const S=c.length;if(v==="Escape"){s();return}if(S!==0){if(v==="ArrowDown"){x(k=>(k+1)%S);return}if(v==="ArrowUp"){x(k=>(k-1+S)%S);return}if(v==="Enter"||v==="Tab"){const k=(h%S+S)%S,b=c[k];b&&r(b)}}}}),[c,h,s,r]);const y=v=>{switch(v.name){case"init":return e.jsx(yr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Hn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(ug,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(jr,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(dg,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Qr,{className:"h-3.5 w-3.5 text-cyan-500"});default:return v.isBuiltIn?e.jsx(cg,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(vn,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:w,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(ht,{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(Gr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((v,S)=>{const k=v.isBuiltIn,b=v.scope==="project";return e.jsxs("div",{ref:N=>{g.current[S]=N},className:F("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",S===h&&"bg-muted"),onClick:()=>r(v),onMouseEnter:()=>x(S),children:[e.jsx("div",{className:"mt-0.5",children:y(v)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-medium",children:["/",v.name]}),k?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):v.scope?e.jsx("span",{className:F("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",b?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:v.scope}):null,v.agent&&e.jsx("span",{className:"text-[10px] leading-none font-bold tracking-tight bg-[var(--surface-subtle)] text-[var(--surface-foreground)] border-[var(--interactive-border)] px-1.5 py-1 rounded border flex-shrink-0",children:v.agent})]}),v.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:v.description})]})]},v.name)}),c.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Vf.displayName="CommandAutocomplete";const Ov=t=>t?t!=="primary":!1,Gf=i.forwardRef(({searchQuery:t,onAgentSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{getVisibleAgents:m}=et(),{agents:f,loadAgents:p}=Zr();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const g=m().filter(v=>Ov(v.mode)).map(v=>{const S=f.find(k=>k.name===v.name);return{name:v.name,description:v.description,mode:v.mode??void 0,scope:S?.scope,isBuiltIn:S?on(S):!1}}),w=t.trim(),y=w.length?g.filter(v=>Ks(v.name,w)):g;y.sort((v,S)=>v.name.localeCompare(S.name)),d(y),l(0)},[m,t,f]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const x=g=>{const w=g.target;!w||!o.current||o.current.contains(w)||s()};return document.addEventListener("pointerdown",x,!0),()=>{document.removeEventListener("pointerdown",x,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:x=>{if(x==="Escape"){s();return}if(c.length){if(x==="ArrowDown"){l(g=>(g+1)%c.length);return}if(x==="ArrowUp"){l(g=>(g-1+c.length)%c.length);return}if(x==="Enter"||x==="Tab"){const g=c[(a+c.length)%c.length];g&&r(g.name)}}}}),[c,r,s,a]);const h=(x,g)=>{const w=x.isBuiltIn,y=x.scope==="project";return e.jsx("div",{ref:v=>{u.current[g]=v},className:F("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",g===a&&"bg-muted"),onClick:()=>r(x.name),onMouseEnter:()=>l(g),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:["#",x.name]}),w?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):x.scope?e.jsx("span",{className:F("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",y?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:x.scope}):null]}),x.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:x.description})]})},x.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(ht,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((x,g)=>h(x,g))}):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"})]})});Gf.displayName="AgentMentionAutocomplete";const qf=i.forwardRef(({searchQuery:t,onSkillSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=ir();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=t.trim(),g=[...h.length?m.filter(w=>Ks(w.name,h)):m].sort((w,y)=>w.scope==="project"&&y.scope!=="project"?-1:w.scope!=="project"&&y.scope==="project"?1:w.name.localeCompare(y.name));d(g),l(0)},[m,t]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const h=x=>{const g=x.target;!g||!o.current||o.current.contains(g)||s()};return document.addEventListener("pointerdown",h,!0),()=>{document.removeEventListener("pointerdown",h,!0)}},[s]),i.useImperativeHandle(n,()=>({handleKeyDown:h=>{if(h==="Escape"){s();return}if(c.length){if(h==="ArrowDown"){l(x=>(x+1)%c.length);return}if(h==="ArrowUp"){l(x=>(x-1+c.length)%c.length);return}if(h==="Enter"||h==="Tab"){const x=c[a];x&&r(x.name)}}}}),[c,r,s,a]);const p=(h,x)=>{const g=h.scope==="project";return e.jsx("div",{ref:w=>{u.current[x]=w},className:F("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",x===a&&"bg-muted"),onClick:()=>r(h.name),onMouseEnter:()=>l(x),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:h.name}),e.jsx("span",{className:F("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 transition-colors",g?"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:h.scope})]}),h.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:h.description})]})},`${h.name}-${h.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(ht,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((h,x)=>p(h,x))}):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"})]})});qf.displayName="SkillAutocomplete";function _v({className:t,children:r,...s}){return e.jsxs(mg,{"data-slot":"scroll-area",className:F("relative",t),...s,children:[e.jsx(fg,{"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($v,{}),e.jsx(pg,{})]})}function $v({className:t,orientation:r="vertical",...s}){return e.jsx(hg,{"data-slot":"scroll-area-scrollbar",orientation:r,className:F("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",t),...s,children:e.jsx(gg,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Bv=({onFilesSelected:t,multiSelect:r=!1,children:s,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:l}=Yt(),c=l,{currentDirectory:d}=gt(),u=Ya(oe=>oe.searchFiles),m=Po(),f=oi(),[p,h]=i.useState(!1),[x,g]=i.useState(0),[w,y]=i.useState(!1),[v,S]=i.useState(""),k=ni(v,200),[b,N]=i.useState(new Set),[D,j]=i.useState(new Set),[M,C]=i.useState({}),P=i.useRef(new Set),E=i.useRef(new Set),[I,A]=i.useState([]),[T,R]=i.useState(!1),[K,Y]=i.useState(!1),[_,J]=i.useState(!1),[q,Q]=i.useState(null),z=n??p,H=o??h,W=i.useCallback(oe=>oe.slice().sort((xe,pe)=>xe.type!==pe.type?xe.type==="directory"?-1:1:xe.name.localeCompare(pe.name)),[]),B=i.useCallback((oe,xe)=>W(xe.filter(pe=>m||!pe.name.startsWith(".")).map(pe=>{const je=pe.name,ce=!pe.isDirectory&&je.includes(".")?je.split(".").pop()?.toLowerCase():void 0;return{name:je,path:pe.path||`${oe}/${je}`,type:pe.isDirectory?"directory":"file",size:0,extension:ce}})),[W,m]),se=i.useCallback(async oe=>{Y(!0),Q(null);try{const xe=await Fe.listLocalDirectory(oe,{respectGitignore:!f}),pe=B(oe,xe.map(je=>({name:je.name,path:je.path,isDirectory:je.isDirectory})));P.current=new Set([oe]),E.current=new Set,C({[oe]:pe}),j(new Set)}catch{Q("Failed to load directory contents"),P.current=new Set([oe]),E.current=new Set,C({[oe]:[]}),j(new Set)}finally{Y(!1)}},[B,f]),L=i.useCallback(async oe=>{const xe=oe.trim();if(!xe)return;const pe=`${xe}::${x}`;if(!P.current.has(pe)&&!E.current.has(pe)){E.current=new Set(E.current),E.current.add(pe);try{const je=await Fe.listLocalDirectory(xe,{respectGitignore:!f}),ce=B(xe,je.map(Ye=>({name:Ye.name,path:Ye.path,isDirectory:Ye.isDirectory})));P.current=new Set(P.current),P.current.add(pe),C(Ye=>({...Ye,[xe]:ce}))}catch{C(je=>je[xe]?je:{...je,[xe]:[]})}finally{E.current=new Set(E.current),E.current.delete(pe)}}},[B,f,x]);i.useEffect(()=>{(z||w)&&d&&se(d)},[z,w,d,se]),i.useEffect(()=>{g(oe=>oe+1)},[m,f]),i.useEffect(()=>{if(!(z||w)||!d){A([]),R(!1);return}const oe=k.trim().replace(/^\.\//,"").replace(/^\/+/,"");if(!oe){A([]),R(!1);return}const xe=oe.toLowerCase();let pe=!1;return R(!0),u(d,xe,150,{includeHidden:m,respectGitignore:!f}).then(je=>{if(pe)return;const ce=je.map(Ye=>({name:Ye.name,path:Ye.path,type:"file",extension:Ye.extension,relativePath:Ye.relativePath,size:0}));A(ce)}).catch(()=>{pe||A([])}).finally(()=>{pe||R(!1)}),()=>{pe=!0}},[z,w,d,k,u,m,f]),i.useEffect(()=>{!z&&!w&&(N(new Set),S(""),A([]),R(!1),P.current=new Set,E.current=new Set,C({}),j(new Set))},[z,w]);const ae=oe=>{if(oe.type==="directory")return D.has(oe.path)?e.jsx(nr,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(nr,{className:"h-3.5 w-3.5 text-primary/60"});switch(oe.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(Ys,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Ys,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(wo,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Nr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(wo,{className:"h-3.5 w-3.5 text-muted-foreground"})}},O=async oe=>{D.has(oe)?j(pe=>{const je=new Set(pe);return je.delete(oe),je}):(j(pe=>{const je=new Set(pe);return je.add(oe),je}),await L(oe))},V=oe=>{N(r?xe=>{const pe=new Set(xe);return pe.has(oe)?pe.delete(oe):pe.add(oe),pe}:new Set([oe]))},X=async()=>{const oe=new Map;Object.values(M).forEach(je=>{je.forEach(ce=>{ce.type==="file"&&oe.set(ce.path,ce)})});const xe=new Map(I.map(je=>[je.path,je])),pe=Array.from(b).map(je=>oe.get(je)??xe.get(je)).filter(je=>!!je);J(!0);try{await t(pe),N(new Set),H(!1),y(!1)}finally{J(!1)}},re=i.useMemo(()=>d?M[d]??[]:[],[M,d]),me=v.trim().length>0,G=oe=>M[oe]??[],he=oe=>{if(d&&oe.startsWith(d)){const xe=oe.substring(d.length);return xe.startsWith("/")?xe.substring(1):xe}return oe.split("/").pop()||oe},ye=(oe,xe)=>{const pe=me?oe.relativePath||he(oe.path):oe.name,je=me&&pe.includes("/")&&pe.length>45,ce=je?Rm(pe,{maxLength:c?42:48}):pe,Ye=e.jsxs("div",{className:F("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",oe.type==="file"&&b.has(oe.path)&&"bg-primary/10"),style:{paddingLeft:`${xe*12}px`},onClick:mt=>{mt.preventDefault(),mt.stopPropagation(),oe.type==="file"&&V(oe.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ae(oe)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":pe,children:ce})]}),oe.type==="file"&&b.has(oe.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return je?e.jsxs(lt,{delayDuration:120,children:[e.jsx(ct,{asChild:!0,children:Ye}),e.jsx(it,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:pe})})]},oe.path):i.cloneElement(Ye,{key:oe.path})},ge=(oe,xe)=>{const pe=oe.type==="directory",je=pe?G(oe.path):[],ce=D.has(oe.path),Ye=pe&&ce&&E.current.has(oe.path)&&je.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:F("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!pe&&b.has(oe.path)&&"bg-primary/10"),style:{paddingLeft:`${xe*12}px`},onClick:mt=>{mt.preventDefault(),mt.stopPropagation(),pe?O(oe.path):V(oe.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ae(oe)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:oe.name}),!pe&&b.has(oe.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),pe&&ce&&je.length>0&&e.jsx("div",{children:je.map(mt=>ge(mt,xe+1))}),pe&&ce&&Ye&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(xe+1)*12}px`},children:"Loading…"})]},oe.path)},$e=b.size>0?`${b.size} file${b.size!==1?"s":""} selected`:"No files selected",ee=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:$e}),e.jsx(ve,{size:"sm",onClick:X,disabled:b.size===0||_,className:"h-6 typography-meta",children:_?"Attaching...":"Attach Files"})]}),Z=c?"flex-1 min-h-[240px]":"h-[300px]",ie=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(Ws,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{value:v,onChange:oe=>S(oe.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:oe=>oe.stopPropagation()}),v&&e.jsx("button",{onClick:oe=>{oe.stopPropagation(),S("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(es,{className:"h-3 w-3"})})]})}),e.jsxs(_v,{className:Z,children:[K&&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..."})}),q&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:q})}),!K&&!q&&e.jsxs("div",{className:"py-1 px-2",children:[me?T?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):I.map(oe=>ye(oe,0)):re.map(oe=>ge(oe,0)),!me&&re.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),me&&!T&&I.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),Me=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),y(!0)},children:s});return a==="modal"?e.jsxs(e.Fragment,{children:[s?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),H(!0)},children:s}):null,e.jsx(Bs,{open:z,onClose:()=>H(!1),title:"Select Project Files",footer:ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:ie})})]}):c?e.jsxs(e.Fragment,{children:[Me,e.jsx(Bs,{open:w,onClose:()=>y(!1),title:"Select Project Files",footer:ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:ie})})]}):e.jsxs(ts,{open:z,onOpenChange:H,children:[e.jsx(ss,{asChild:!0,children:s}),e.jsxs(rs,{className:F("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[ie,e.jsx(Is,{}),ee]})]})},qo=[{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 zr(t){if(!t||t==="build")return qo[0];let r=0;for(let n=0;n<t.length;n++){const o=t.charCodeAt(n);r=(r<<5)-r+o,r=r&r}const s=1+Math.abs(r)%(qo.length-1);return qo[s]}const zv=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Kf=t=>zv(t),Hv=t=>t?typeof t=="string"?t==="ask":Kf(t)?Object.values(t).some(r=>r==="ask"):!1:!1,Wv=t=>t?typeof t=="string"?t==="deny":Kf(t)?Object.values(t).some(r=>r==="deny"):!1:!1,Qf=({agentDefaultEditMode:t,webfetchPermission:r,bashPermission:s})=>{const n=Hv(s),o=Wv(s),a=!n&&!o,l=r==="allow",c=r!=="deny",d=t==="allow"||t==="full",u=t==="ask";let m=t;d&&l&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:t!=="deny"&&c&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:l,webfetchNotDeny:c}},Ko=t=>t==="primary"||t==="all"||t===void 0||t===null,$a=t=>{if(!Array.isArray(t))return null;const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;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},Qo=(t,r)=>{const s=$a(t);if(!(!s||s.length===0)){for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Uv=(t,r)=>{const s=$a(t);if(!s||s.length===0)return;const n={};for(const o of s)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},Vv=[{key:"tool_call",icon:Va,label:"Tool calling",isActive:t=>t?.tool_call===!0},{key:"reasoning",icon:Sr,label:"Reasoning",isActive:t=>t?.reasoning===!0}],Gv={text:{icon:um,label:"Text"},image:{icon:Nr,label:"Image"},video:{icon:yg,label:"Video"},audio:{icon:xg,label:"Audio"},pdf:{icon:Ua,label:"PDF"}},qv=t=>t.trim().toLowerCase(),ao=(t,r)=>{const s=r==="input"?t?.modalities?.input:t?.modalities?.output;return!Array.isArray(s)||s.length===0?[]:Array.from(new Set(s.map(o=>qv(o)))).map(o=>{const a=Gv[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Kv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Qv=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),tr=t=>{if(typeof t!="number"||Number.isNaN(t))return"—";if(t===0)return"0";const r=Kv.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Yo=t=>typeof t!="number"||!Number.isFinite(t)?"—":Qv.format(t),Pi=t=>Vv.filter(r=>r.isActive(t)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Ld=t=>{if(!t)return"—";const r=t.match(/^(\d{4})-(\d{2})$/);if(r){const s=Number.parseInt(r[1],10),n=Number.parseInt(r[2],10)-1,o=new Date(Date.UTC(s,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return t},Od=t=>{if(!t)return"—";const r=new Date(t);return Number.isNaN(r.getTime())?t:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(r)},_d=({className:t})=>{const{providers:r,currentProviderId:s,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:l,setProvider:c,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:h,getCurrentAgent:x,getVisibleAgents:g}=et(),w=g(),{currentSessionId:y,messages:v,saveSessionAgentSelection:S,getSessionAgentSelection:k,saveAgentModelForSession:b,getAgentModelForSession:N,saveAgentModelVariantForSession:D,getAgentModelVariantForSession:j,analyzeAndSaveExternalSessionChoices:M,getSessionAgentEditMode:C,setSessionAgentEditMode:P}=fe(),E=at($=>$.hasHydrated),{toggleFavoriteModel:I,isFavoriteModel:A,addRecentModel:T,isModelSelectorOpen:R,setModelSelectorOpen:K}=ke(),{favoriteModelsList:Y,recentModelsList:_}=cc(),{isMobile:J}=Yt(),q=lw(),Q=xf(),z=J,[H,W]=i.useState(null),[B,se]=i.useState(null),[L,ae]=i.useState(""),O=i.useCallback(()=>W(null),[]),V=i.useCallback(()=>se(null),[]),X=i.useRef(void 0),[re,me]=i.useState(()=>{const $=new Set;return s&&$.add(s),$}),[G,he]=i.useState(!1),ye=R,ge=K,[$e,ee]=i.useState(!1),Z=i.useId(),[ie,Me]=i.useState(""),[oe,xe]=i.useState(0),pe=i.useRef([]);i.useEffect(()=>{H==="model"&&me(()=>{const $=new Set;return s&&$.add(s),$})},[H,s]),i.useEffect(()=>{H!=="agent"&&he(!1),H!=="model"&&ae("")},[H]);const je=i.useRef(ye);i.useEffect(()=>{const $=je.current;je.current=ye,ye||(ee(!1),Me(""),xe(0),$&&!z&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[ye,z]),i.useEffect(()=>{xe(0)},[ie]);const ce=x?.(),Ye=i.useMemo(()=>ce?Qo(ce.permission,"edit")??"ask":"deny",[ce]),mt=i.useMemo(()=>{if(ce)return Qo(ce.permission,"webfetch")},[ce]),Ie=i.useMemo(()=>{if(!ce)return;const $=Uv(ce.permission,"bash");return $||void 0},[ce]),le=i.useMemo(()=>Qf({agentDefaultEditMode:Ye,webfetchPermission:mt,bashPermission:Ie}),[Ye,mt,Ie]),{cascadeDefaultMode:Xe,modeAvailability:Ne,autoApproveAvailable:Se}=le,qe=!!(y&&a),rt=qe&&y&&a?C(y,a,Xe):Xe,We={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},_e=i.useCallback($=>!Ne[$],[Ne]),Ke=i.useMemo(()=>!qe||_e(rt)&&rt!==Xe?Xe:rt,[Xe,_e,qe,rt]),xt=[{mode:"ask",label:We.ask,disabled:_e("ask")},{mode:"allow",label:We.allow,disabled:_e("allow")},{mode:"full",label:We.full,disabled:_e("full")}],nt=i.useMemo(()=>uo(Ke),[Ke]),Pt=!qe||!Se;i.useEffect(()=>{Pt&&(he(!1),ee(!1))},[Pt]);const Tt=J?"mobile":Q?"vscode":"default",_t=Tt==="mobile"?"h-9":Tt==="vscode"?"h-6":"h-8",Ve=Tt==="mobile"?"h-5 w-5":"h-4 w-4",dt=Tt==="mobile"?"h-5 w-5":"h-4 w-4",vt=z?"typography-micro":"typography-meta",ut=Tt==="mobile"||Tt==="vscode"?"gap-x-1":"gap-x-3",At=We[Ke],Rt=i.useCallback(($,ue=Ve)=>{const de=F(ue,"flex-shrink-0"),Le=uo($),Qe={color:Le?Le.text:"var(--foreground)"};return $==="full"?e.jsx(Dr,{className:de,style:Qe}):$==="allow"?e.jsx(oa,{className:de,style:Qe}):$==="deny"?e.jsx(zn,{className:de,style:Qe}):e.jsx(hn,{className:de,style:Qe})},[Ve]),as=i.useCallback($=>{Pt||!y||!a||_e($)||(P(y,a,$,Xe),ge(!1),he(!1),ee(!1))},[Xe,Pt,y,a,P,ge,ee,_e]),Ct=p(),$t=Array.isArray(Ct?.models)?Ct.models:[],Mt=s&&n?h(s,n):void 0,Gt=Pi(Mt),Dt=ao(Mt,"input"),qt=ao(Mt,"output"),St=i.useMemo(()=>`${s}/${n}`?m():[],[m,s,n]),Lt=St.length>0,be=[{label:"Input",value:Yo(Mt?.cost?.input)},{label:"Output",value:Yo(Mt?.cost?.output)},{label:"Cache read",value:Yo(Mt?.cost?.cache_read)},{label:"Cache write",value:Yo(Mt?.cost?.cache_write)}],Pe=[{label:"Context",value:tr(Mt?.limit?.context)},{label:"Output",value:tr(Mt?.limit?.output)}],Oe=i.useRef(void 0),st=y?v.get(y)?.length??-1:-1,ne=i.useRef(null),Ae=i.useCallback(($,ue,de)=>{if(!$||!ue)return"model-missing";const Le=r.find(Te=>Te.id===$);return Le?(Array.isArray(Le.models)?Le.models:[]).find(Te=>Te.id===ue)?(c($),d(ue),y&&de&&b(y,de,$,ue),"applied"):"model-missing":"provider-missing"},[r,c,d,y,b]);i.useEffect(()=>{if(!y){ne.current=null;return}if(!E||r.length===0||w.length===0)return;(!ne.current||ne.current.sessionId!==y)&&(ne.current={sessionId:y,resolved:!1,inFlight:!1});const $=ne.current;if(!$||$.resolved||$.inFlight)return;let ue=!1;const de=()=>{if(ue)return;const Te=ne.current;Te&&Te.sessionId===y&&(Te.resolved=!0,Te.inFlight=!1)},Le=()=>{const Te=k(y);if(Te){a!==Te&&f(Te);const Ge=N(y,Te);if(Ge){const Be=Ae(Ge.providerId,Ge.modelId,Te);if(Be==="applied")return"resolved";if(Be==="provider-missing")return"waiting"}else return"resolved"}for(const Ge of w){const Be=N(y,Ge.name);if(!Be)continue;a!==Ge.name&&f(Ge.name),S(y,Ge.name);const Je=Ae(Be.providerId,Be.modelId,Ge.name);if(Je==="applied")return"resolved";if(Je==="provider-missing")return"waiting"}return"continue"},Ue=()=>{if(w.length===0)return;const Te=w.filter(Be=>Ko(Be.mode)),Ge=w.find(Be=>Be.name==="build")||Te[0]||w[0];Ge&&(S(y,Ge.name),a!==Ge.name&&f(Ge.name),Ge.model?.providerID&&Ge.model?.modelID&&Ae(Ge.model.providerID,Ge.model.modelID,Ge.name))};return(async()=>{try{const Te=Le();if(Te==="resolved"){de();return}if(Te==="waiting"||st===-1)return;if(st>0){$.inFlight=!0;try{const Ge=await M(y,w);if(ue)return;if(Ge.size>0){let Be=null,Je=-1/0;for(const[yt,Et]of Ge)Et.timestamp>Je&&(Je=Et.timestamp,Be=yt);if(Be){S(y,Be),a!==Be&&f(Be);const yt=Ge.get(Be);if(yt){const Et=Ae(yt.providerId,yt.modelId,Be);if(Et==="applied"){de();return}if(Et==="provider-missing")return}else{de();return}}}}catch(Ge){ue||console.error("[ModelControls] Error resolving session from messages:",Ge)}finally{const Ge=ne.current;!ue&&Ge&&Ge.sessionId===y&&(Ge.inFlight=!1)}}Ue(),de()}catch(Te){ue||console.error("[ModelControls] Error in session switch:",Te)}})(),()=>{ue=!0}},[y,st,w,a,k,N,f,Ae,M,S,E,r]),i.useEffect(()=>{if(!E||!y||r.length===0||w.length===0)return;const ue=k(y)||a;if(!ue)return;const de=N(y,ue);if(!de)return;const Le=r.find(Ge=>Ge.id===de.providerId);if(!Le||!(Array.isArray(Le.models)?Le.models.some(Ge=>Ge.id===de.modelId):!1))return;const Qe=s===de.providerId,Te=n===de.modelId;Qe&&Te||(ue!==a&&f(ue),Ae(de.providerId,de.modelId,ue))},[E,y,a,s,n,r,w,k,N,Ae,f]),i.useEffect(()=>{if(!E)return;(async()=>{try{if(a!==Oe.current&&(Oe.current=a,a&&y)){await new Promise(Le=>setTimeout(Le,50));const ue=N(y,a);if(ue){const Le=Ae(ue.providerId,ue.modelId,a);if(Le==="applied"||Le==="provider-missing")return}const de=w.find(Le=>Le.name===a);if(de?.model?.providerID&&de?.model?.modelID&&Ae(de.model.providerID,de.model.modelID,a)==="provider-missing")return}}catch(ue){console.error("[ModelControls] Agent change error:",ue)}})()},[a,y,N,Ae,w,E]),i.useEffect(()=>{if(!E||!a){u(void 0);return}if(!s||!n){u(void 0);return}if(St.length===0){u(void 0);return}if(o&&!St.includes(o)){u(void 0);return}if(!y){if(!o){const de=l&&St.includes(l)?l:void 0;u(de)}return}const $=j(y,a,s,n),ue=$&&St.includes($)?$:void 0;u(ue)},[St,E,y,a,s,n,o,j,u,l]);const te=i.useCallback($=>{u($),y&&a&&s&&n&&D(y,a,s,n,$)},[a,n,s,y,D,u]),Ce=$=>{try{f($),ge(!1),y&&S(y,$),z&&O()}catch(ue){console.error("[ModelControls] Handle agent change error:",ue)}},De=($,ue)=>{try{const de=Ae($,ue,a||void 0);if(de!=="applied"){de==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",$):de==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:$,modelId:ue});return}T($,ue),ge(!1),z&&O(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(de){console.error("[ModelControls] Handle model change error:",de)}},He=$=>{const ue=typeof $?.name=="string"?$.name:typeof $?.id=="string"?$.id:"";return ue.length>40?ue.substring(0,37)+"...":ue},wt=()=>r.find(ue=>ue.id===s)?.name||s,Nt=()=>{if(!s||!n||$t.length===0)return"Not selected";const $=$t.find(ue=>ue.id===n);return He($)},Xt=()=>{if(!a){const ue=w.filter(Ue=>Ko(Ue.mode)),Le=ue.find(Ue=>Ue.name==="build")||ue[0];return Le?we(Le.name):"Select Agent"}const $=w.find(ue=>ue.name===a);return we($?$.name:a)},we=$=>$.charAt(0).toUpperCase()+$.slice(1),ze=($,ue,de)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:ue,"aria-label":ue,role:"img",children:e.jsx($,{className:"h-3.5 w-3.5"})},de),tt=i.useCallback($=>{me(ue=>{const de=new Set(ue);return de.has($)?de.delete($):de.add($),de})},[]),Ee=i.useCallback($=>{X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{se($)},500)},[]),ot=i.useCallback(()=>{X.current&&clearTimeout(X.current)},[]);i.useEffect(()=>()=>{X.current&&clearTimeout(X.current)},[]);const ft=()=>!z||B!=="model"?null:e.jsx(Bs,{open:!0,onClose:V,title:Mt?.name||Nt(),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()})]}),Gt.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:Gt.map(({key:$,icon:ue,label:de})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[ze(ue,de,`cap-${$}`),e.jsx("span",{className:"typography-meta text-foreground",children:de})]},$))})]}),(Dt.length>0||qt.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:[Dt.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:Dt.map(({key:$,icon:ue,label:de})=>ze(ue,`${de} input`,`input-${$}`))})]}),qt.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:qt.map(({key:$,icon:ue,label:de})=>ze(ue,`${de} output`,`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:"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:tr(Mt?.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:tr(Mt?.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:Ld(Mt?.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:Od(Mt?.release_date)})]})]})]})]})}),Bt=()=>{if(!z||B!=="agent"||!ce)return null;const $=!!(ce.prompt&&ce.prompt.trim().length>0),ue=ce.model?.providerID&&ce.model?.modelID,de=ce.temperature!==void 0||ce.topP!==void 0,Le=Ge=>{const Be=$a(ce.permission)??[],Je=Be.some(Et=>Et.permission===Ge&&Et.pattern!=="*"),yt=Qo(Be,Ge)??"ask";return Je?{mode:"ask",label:"Custom"}:yt==="allow"?{mode:"allow",label:"Allow"}:yt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ue=Le("edit"),Qe=Le("bash"),Te=Le("webfetch");return e.jsx(Bs,{open:!0,onClose:V,title:we(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":"—"})]}),(ue||de)&&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"}),ue&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ce.model.providerID," / ",ce.model.modelID]}),de&&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:[Rt(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:[Rt(Qe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Qe.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Rt(Te.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Te.label})]})]})]})]}),$&&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(oa,{className:"h-4 w-4 text-foreground"})]})})]})})},Wt=()=>{if(!z)return null;const $=L.trim(),ue=r.map(de=>{const Le=Array.isArray(de.models)?de.models:[],Ue=$.length===0?!0:Ks(de.name,$)||Ks(de.id,$),Qe=$.length===0?Le:Le.filter(Te=>{const Ge=He(Te),Be=typeof Te.id=="string"?Te.id:"";return Ks(Ge,$)||Ks(Be,$)});return{provider:de,providerModels:Qe,matchesProvider:Ue}}).filter(({matchesProvider:de,providerModels:Le})=>de||Le.length>0);return e.jsx(Bs,{open:H==="model",onClose:O,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(Ws,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{value:L,onChange:de=>ae(de.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),L&&e.jsx("button",{type:"button",onClick:()=>ae(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(zn,{className:"h-4 w-4"})})]})}),ue.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."}),!L&&Y.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(Ar,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Y.map(({model:de,providerID:Le,modelID:Ue})=>{const Qe=Le===s&&Ue===n,Te=h(Le,Ue);return e.jsxs("button",{type:"button",onClick:()=>De(Le,Ue),className:F("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",Qe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ns,{providerId:Le,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:He(de)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Te?.limit?.context||Te?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Te?.limit?.context?`${tr(Te?.limit?.context)} ctx`:"",Te?.limit?.context&&Te?.limit?.output?" • ":"",Te?.limit?.output?`${tr(Te?.limit?.output)} out`:""]})})]},`fav-mobile-${Le}-${Ue}`)})})]}),!L&&_.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(jr,{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:de,providerID:Le,modelID:Ue})=>{const Qe=Le===s&&Ue===n,Te=h(Le,Ue);return e.jsxs("button",{type:"button",onClick:()=>De(Le,Ue),className:F("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",Qe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ns,{providerId:Le,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:He(de)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Te?.limit?.context||Te?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Te?.limit?.context?`${tr(Te?.limit?.context)} ctx`:"",Te?.limit?.context&&Te?.limit?.output?" • ":"",Te?.limit?.output?`${tr(Te?.limit?.output)} out`:""]})})]},`recent-mobile-${Le}-${Ue}`)})})]}),ue.map(({provider:de,providerModels:Le})=>{if(Le.length===0&&!$.length)return null;const Ue=de.id===s,Qe=re.has(de.id)||$.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:()=>tt(de.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Qe,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{providerId:de.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:de.name}),Ue&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Qe?e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(zs,{className:"h-3 w-3 text-muted-foreground"})]}),Qe&&Le.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Le.map(Te=>{const Ge=Ue&&Te.id===n,Be=h(de.id,Te.id),Je=Pi(Be).slice(0,3),yt=ao(Be,"input");return e.jsxs("div",{className:F("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:()=>De(de.id,Te.id),className:F("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:He(Te)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Be?.limit?.context||Be?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Be?.limit?.context?e.jsxs("span",{children:[tr(Be?.limit?.context)," ctx"]}):null,Be?.limit?.context&&Be?.limit?.output?e.jsx("span",{children:"•"}):null,Be?.limit?.output?e.jsxs("span",{children:[tr(Be?.limit?.output)," out"]}):null]}),(Je.length>0||yt.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Je,...yt].map(({key:Et,icon:Cs,label:As})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:As,"aria-label":As,children:e.jsx(Cs,{className:"h-3 w-3"})},`meta-${de.id}-${Te.id}-${Et}`))})]})]}),e.jsx("button",{type:"button",onClick:Et=>{Et.preventDefault(),Et.stopPropagation(),I(de.id,Te.id)},className:F("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",A(de.id,Te.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":A(de.id,Te.id)?"Unfavorite":"Favorite",title:A(de.id,Te.id)?"Remove from favorites":"Add to favorites",children:A(de.id,Te.id)?e.jsx(Ar,{className:"h-4 w-4"}):e.jsx(On,{className:"h-4 w-4"})})]},Te.id)})})]},de.id)})]})})},vs=()=>{if(!z||!Lt)return null;const $=!o,ue=de=>{te(de),O(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(Bs,{open:H==="variant",onClose:O,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:F("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",$?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ue(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),$&&e.jsx(Qt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),St.map(de=>{const Le=o===de,Ue=de.charAt(0).toUpperCase()+de.slice(1);return e.jsxs("button",{type:"button",className:F("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",Le?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ue(de),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ue}),Le&&e.jsx(Qt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},de)})]})})},is=()=>{if(!z)return null;const $=w.filter(ue=>Ko(ue.mode));return e.jsx(Bs,{open:H==="agent",onClose:O,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[$.map(ue=>{const de=ue.name===a,Le=zr(ue.name);return e.jsxs("button",{type:"button",className:F("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",Le.class,de?"active":"border-border/40"),onClick:()=>Ce(ue.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:F("h-2 w-2 rounded-full",Le.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:de?{color:`var(${Le.var})`}:void 0,children:we(ue.name)})]}),ue.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:ue.description})]},ue.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:Pt,onClick:()=>{Pt||he(ue=>!ue)},className:F("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",Pt?"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:nt?nt.text:"var(--foreground)",mixBlendMode:"normal"},children:At})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:F("flex items-center justify-center p-1",!nt&&"text-muted-foreground"),style:nt?{color:nt.text}:void 0,children:Rt(Ke,Ve)}),e.jsx(Ht,{className:F("h-4 w-4 text-muted-foreground transition-transform",G?"rotate-180":"")})]})]}),G&&!Pt&&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:xt.map(ue=>{const de=ue.mode===Ke,Le=uo(ue.mode);return e.jsxs("button",{type:"button",disabled:ue.disabled,onClick:()=>as(ue.mode),className:F("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",ue.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",de?"bg-primary/10":void 0),style:de&&Le?{backgroundColor:Le.background??void 0}:void 0,children:[Rt(ue.mode,Ve),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:Le?Le.text:"var(--foreground)"},children:ue.label})})]},ue.mode)})})})]})]})})},Jt=()=>e.jsx(it,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Mt?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:Mt.name||Nt()}),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:Gt.length>0?Gt.map(({key:$,icon:ue,label:de})=>ze(ue,de,`cap-${$}`)):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:Dt.length>0?Dt.map(({key:$,icon:ue,label:de})=>ze(ue,`${de} input`,`input-${$}`)):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:qt.length>0?qt.map(({key:$,icon:ue,label:de})=>ze(ue,`${de} output`,`output-${$}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),be.map($=>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:$.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:$.value})]},$.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"}),Pe.map($=>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:$.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:$.value})]},$.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:Ld(Mt.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:Od(Mt.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Ot=($,ue,de,Le,Ue,Qe)=>{const Te=h(ue,de),Ge=Pi(Te).map(Ps=>({...Ps,id:`cap-${Ps.key}`})),Be=[...ao(Te,"input"),...ao(Te,"output")],Je=Array.from(new Map(Be.map(Ps=>[Ps.key,Ps])).values()).map(Ps=>({...Ps,id:`mod-${Ps.key}`})),yt=[...Ge,...Je],Et=tr(Te?.limit?.context),Cs=s===ue&&n===de,As=A(ue,de);return e.jsxs("div",{ref:Ps=>{pe.current[Ue]=Ps},className:F("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Qe?"bg-accent":"hover:bg-accent/50"),onClick:()=>De(ue,de),onMouseEnter:()=>xe(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:He($)}),Te?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Et}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[yt.length>0&&e.jsx("div",{className:F("items-center gap-0.5",Qe?"flex":"hidden group-hover:flex"),children:yt.map(({id:Ps,icon:zp,label:vc})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":vc,role:"img",title:vc,children:e.jsx(zp,{className:"h-2.5 w-2.5"})},Ps))}),Cs&&e.jsx(Qt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Ps=>{Ps.preventDefault(),Ps.stopPropagation(),I(ue,de)},className:F("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",As?"text-yellow-500":"text-muted-foreground"),"aria-label":As?"Unfavorite":"Favorite",title:As?"Remove from favorites":"Add to favorites",children:As?e.jsx(Ar,{className:"h-3.5 w-3.5"}):e.jsx(On,{className:"h-3.5 w-3.5"})})]})]},`${Le}-${ue}-${de}`)},Nn=($,ue,de)=>de.trim()?Ks($,de)||Ks(ue,de):!0,ii=()=>{const $=Y.filter(({model:Be,providerID:Je})=>{const Et=r.find(As=>As.id===Je)?.name||Je,Cs=He(Be);return Nn(Cs,Et,ie)}),ue=_.filter(({model:Be,providerID:Je})=>{const Et=r.find(As=>As.id===Je)?.name||Je,Cs=He(Be);return Nn(Cs,Et,ie)}),de=r.map(Be=>{const yt=(Array.isArray(Be.models)?Be.models:[]).filter(Et=>{const Cs=He(Et);return Nn(Cs,Be.name||Be.id||"",ie)});return{...Be,models:yt}}).filter(Be=>Be.models.length>0),Le=$.length>0||ue.length>0||de.length>0,Ue=[];$.forEach(({model:Be,providerID:Je,modelID:yt})=>{Ue.push({model:Be,providerID:Je,modelID:yt,section:"fav"})}),ue.forEach(({model:Be,providerID:Je,modelID:yt})=>{Ue.push({model:Be,providerID:Je,modelID:yt,section:"recent"})}),de.forEach(Be=>{Be.models.forEach(Je=>{Ue.push({model:Je,providerID:Be.id,modelID:Je.id,section:"provider"})})});const Qe=Ue.length,Te=Be=>{if(Be.key==="ArrowDown")Be.preventDefault(),Be.stopPropagation(),xe(Je=>(Je+1)%Math.max(1,Qe)),setTimeout(()=>{const Je=(oe+1)%Math.max(1,Qe);pe.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Be.key==="ArrowUp")Be.preventDefault(),Be.stopPropagation(),xe(Je=>(Je-1+Math.max(1,Qe))%Math.max(1,Qe)),setTimeout(()=>{const Je=(oe-1+Math.max(1,Qe))%Math.max(1,Qe);pe.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Be.key==="Enter"){Be.preventDefault(),Be.stopPropagation();const Je=Ue[oe];Je&&De(Je.providerID,Je.modelID)}else Be.key==="Escape"&&(Be.preventDefault(),Be.stopPropagation(),ge(!1))};let Ge=0;return e.jsxs(lt,{delayDuration:1e3,children:[z?e.jsxs("button",{type:"button",onClick:()=>W("model"),onTouchStart:()=>Ee("model"),onTouchEnd:ot,onTouchCancel:ot,className:F("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",_t),children:[s?e.jsx(Ns,{providerId:s,className:F(dt,"flex-shrink-0")}):e.jsx(Dr,{className:F(dt,"text-muted-foreground")}),e.jsx("span",{className:F("model-controls__model-label typography-micro font-medium overflow-hidden min-w-0",J?"max-w-[120px]":"max-w-[220px]"),children:e.jsx("span",{className:"marquee-text",children:Nt()})})]}):e.jsxs(ts,{open:ye,onOpenChange:ge,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:F("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",_t),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{providerId:s,className:F(dt,"flex-shrink-0")}),e.jsx(Dr,{className:F(dt,"text-primary/60 hidden")})]}):e.jsx(Dr,{className:F(dt,"text-muted-foreground")}),e.jsx("span",{className:F("model-controls__model-label overflow-hidden",vt,"font-medium whitespace-nowrap text-foreground min-w-0","max-w-[260px]"),children:e.jsx("span",{className:"marquee-text",children:Nt()})},`${s}-${n}`)]})})}),e.jsxs(rs,{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(Ws,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{type:"text",placeholder:"Search models",value:ie,onChange:Be=>Me(Be.target.value),onKeyDown:Te,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(ht,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Le&&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(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Ar,{className:"h-4 w-4 text-primary"}),"Favorites"]}),$.map(({model:Be,providerID:Je,modelID:yt})=>{const Et=Ge++;return Ot(Be,Je,yt,"fav",Et,oe===Et)})]}),ue.length>0&&e.jsxs(e.Fragment,{children:[$.length>0&&e.jsx(Is,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(jr,{className:"h-4 w-4"}),"Recent"]}),ue.map(({model:Be,providerID:Je,modelID:yt})=>{const Et=Ge++;return Ot(Be,Je,yt,"recent",Et,oe===Et)})]}),($.length>0||ue.length>0)&&de.length>0&&e.jsx(Is,{}),de.map((Be,Je)=>e.jsxs(i.Fragment,{children:[Je>0&&e.jsx(Is,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Ns,{providerId:Be.id,className:"h-4 w-4 flex-shrink-0"}),Be.name]}),Be.models.map(yt=>{const Et=Ge++;return Ot(yt,Be.id,yt.id,"provider",Et,oe===Et)})]},Be.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"})]})]}),Jt()]})},li=()=>{if(!ce)return e.jsx(it,{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 $=!!(ce.prompt&&ce.prompt.trim().length>0),ue=ce.model?.providerID&&ce.model?.modelID,de=ce.temperature!==void 0||ce.topP!==void 0,Le=Ge=>{const Be=$a(ce.permission)??[],Je=Be.some(Et=>Et.permission===Ge&&Et.pattern!=="*"),yt=Qo(Be,Ge)??"ask";return Je?{mode:"ask",label:"Custom"}:yt==="allow"?{mode:"allow",label:"Allow"}:yt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ue=Le("edit"),Qe=Le("bash"),Te=Le("webfetch");return e.jsx(it,{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:we(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":"—"})]}),(ue||de)&&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"}),ue?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:"—"}),de&&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:[Rt(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:[Rt(Qe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Qe.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Rt(Te.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Te.label})]})]})]}),$&&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(oa,{className:"h-4 w-4 text-foreground"})]})]})})},To=()=>{if(!Lt)return null;const $=o??"Default",ue=!o,de=ue?"text-muted-foreground":"text-[color:var(--status-info)]";return z?e.jsxs("button",{type:"button",onClick:()=>W("variant"),className:F("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",_t,"cursor-pointer hover:opacity-70"),children:[e.jsx(Sr,{className:F(dt,"flex-shrink-0",de)}),e.jsx("span",{className:F("model-controls__variant-label",vt,"font-medium truncate min-w-0",J&&"max-w-[60px]",de),children:$})]}):e.jsxs(lt,{delayDuration:800,children:[e.jsxs(ts,{children:[e.jsx(ct,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:F("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",_t),children:[e.jsx(Sr,{className:F(dt,"flex-shrink-0",de)}),e.jsx("span",{className:F("model-controls__variant-label",vt,"font-medium min-w-0 truncate",q?"max-w-[180px]":void 0,de),children:$})]})})}),e.jsxs(rs,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Wr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(jt,{className:"typography-meta",onSelect:()=>te(void 0),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:"Default"}),ue&&e.jsx(Qt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),St.length>0&&e.jsx(Is,{}),St.map(Le=>{const Ue=o===Le,Qe=Le.charAt(0).toUpperCase()+Le.slice(1);return e.jsx(jt,{className:"typography-meta",onSelect:()=>te(Le),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:Qe}),Ue&&e.jsx(Qt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},Le)})]})]}),e.jsx(it,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",$]})})]})},ci=()=>z?e.jsxs("button",{type:"button",onClick:()=>W("agent"),onTouchStart:()=>Ee("agent"),onTouchEnd:ot,onTouchCancel:ot,className:F("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",_t,"cursor-pointer hover:opacity-70"),children:[e.jsx(gn,{className:F(dt,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${zr(a).var})`}:void 0}),e.jsx("span",{className:F("model-controls__agent-label",vt,"font-medium truncate min-w-0",J&&"max-w-[60px]"),style:a?{color:`var(${zr(a).var})`}:void 0,children:Xt()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(lt,{delayDuration:1e3,children:[e.jsxs(ts,{children:[e.jsx(ct,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:F("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",_t),children:[e.jsx(gn,{className:F(dt,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${zr(a).var})`}:void 0}),e.jsx("span",{className:F("model-controls__agent-label",vt,"font-medium min-w-0 truncate",q?"max-w-[220px]":void 0),style:a?{color:`var(${zr(a).var})`}:void 0,children:Xt()})]})})}),e.jsxs(rs,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[w.filter($=>Ko($.mode)).map($=>e.jsx(jt,{className:"typography-meta",onSelect:()=>Ce($.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:F("h-1 w-1 rounded-full agent-dot",zr($.name).class)}),e.jsx("span",{className:"font-medium",children:we($.name)})]}),$.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:$.description})]})},$.name)),e.jsx(Is,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:Pt,onClick:()=>{Pt||ee($=>!$)},className:F("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",Pt?"cursor-not-allowed opacity-60":void 0),"aria-expanded":$e,"aria-controls":Z,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:nt?nt.text:"var(--foreground)"},children:At})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:F("flex items-center justify-center p-1",!nt&&"text-muted-foreground"),style:nt?{color:nt.text}:void 0,children:Rt(Ke)}),e.jsx(Ht,{className:F("h-3.5 w-3.5 transition-transform text-muted-foreground",$e?"rotate-180":"")})]})]}),$e&&!Pt&&e.jsx("div",{id:Z,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:xt.map($=>{const ue=$.mode===Ke,de=uo($.mode);return e.jsxs("button",{type:"button",disabled:$.disabled,onClick:()=>as($.mode),className:F("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",$.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",ue?"bg-primary/10":void 0),style:ue&&de?{backgroundColor:de.background??void 0}:void 0,children:[Rt($.mode,Ve),e.jsx("span",{className:"typography-meta font-medium",style:{color:de?de.text:"var(--foreground)"},children:$.label})]},$.mode)})})]})]})]}),li()]})}),di=F("@container/model-controls flex items-center min-w-0",J&&"w-full",t);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:di,children:e.jsxs("div",{className:F("flex items-center min-w-0 flex-1 justify-end",ut,J&&"overflow-hidden"),children:[To(),ii(),ci()]})}),Wt(),vs(),is(),ft(),Bt()]})},Yv=t=>t?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(t):!0,$d=(t,r)=>{if(typeof t!="string"||t.length===0)return{sanitizedText:t,mention:null};const s=r.filter(o=>o.mode&&o.mode!=="primary");if(s.length===0||!t.includes("#"))return{sanitizedText:t,mention:null};let n=null;for(const o of s){const a=new RegExp(`#${o.name}\\b`,"gi");let l;for(;(l=a.exec(t))!==null;){const c=l.index,d=c+l[0].length,u=c>0?t[c-1]:null;if(!Yv(u))continue;const m={name:o.name,source:{value:l[0],start:c,end:d}};n||(n=m)}}return n?{sanitizedText:t,mention:n}:{sanitizedText:t,mention:null}},Yf=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),wl=os()(us((t,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async s=>{if(s){t({isLoading:!0});try{const n=fe.getState().getDirectoryForSession(s),a=(n?await Fe.withDirectory(n,()=>Fe.getSessionTodos(s)):await Fe.getSessionTodos(s)).map(Yf);t(l=>{const c=new Map(l.sessionTodos);return c.set(s,a),{sessionTodos:c,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),t({isLoading:!1})}}},updateTodos:(s,n)=>{t(o=>{const a=new Map(o.sessionTodos);return a.set(s,n),{sessionTodos:a}})},getTodosForSession:s=>r().sessionTodos.get(s)||[],clearTodos:s=>{t(n=>{const o=new Map(n.sessionTodos);return o.delete(s),{sessionTodos:o}})}}),{name:"todo-store"})),Xv=(t,r)=>{const s=r.map(Yf);wl.getState().updateTodos(t,s)},Bd=[{variant:"shine",component:({children:t,className:r,...s})=>e.jsx(In.span,{...s,className:F("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:t})},{variant:"generate-effect",component:({children:t,className:r,...s})=>typeof t!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:t.split("").map((n,o)=>Re.createElement(In.span,{...s,key:n+String(o),className:F("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:t,className:r,...s})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...s,className:F("invisible",r),children:t}),e.jsx("span",{...s,className:F("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:t}),e.jsx("span",{...s,className:F("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:t})]})},{variant:"hover-enter",component:({children:t,className:r,...s})=>{if(typeof t!="string")return null;const n=.25,o=.025,a=t.split("").map(l=>l===" "?" ":l);return e.jsxs(In.span,{...s,className:F("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((l,c)=>e.jsx(In.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))}),e.jsx("div",{className:F("absolute inset-0"),children:a.map((l,c)=>e.jsx(In.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))})]})}},{variant:"shake",component:({children:t,className:r,...s})=>e.jsx("span",{...s,className:F("text-primary-muted hover:animate-text-shake",r),children:t})},{variant:"hover-decoration",component:({children:t,className:r,...s})=>e.jsx("div",{className:F("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",{...s,className:F("text-primary-muted",r),children:t})})}];function Ti({variant:t="shine",className:r,...s}){const a=Bd.find(l=>l.variant===t)?.component||Bd[0].component;return e.jsx(om,{children:e.jsx(a,{...s,className:r})})}const zd=1500,Jv=2e3;function Zv({statusText:t,isGenericStatus:r,isWaitingForPermission:s,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:l}){const[c,d]=Re.useState("idle"),[u,m]=Re.useState(null),[f,p]=Re.useState(!1),h=Re.useRef(0),x=Re.useRef(null),g=Re.useRef(null),w=Re.useRef(null),y=Re.useRef(null),v=Re.useRef(!1),S=Re.useRef(!1),k=Re.useRef(!1),b=Re.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),w.current&&(clearTimeout(w.current),w.current=null)},[]),N=Re.useCallback((I,A)=>{b(),x.current=null,m(I),p(A),d("showing"),h.current=Date.now(),v.current=!0},[b]),D=Re.useCallback(()=>{if(g.current)return;const I=Date.now()-h.current,A=Math.max(0,zd-I);g.current=setTimeout(()=>{g.current=null;const T=x.current;T&&N(T.text,T.permission)},A)},[N]),j=Re.useCallback(I=>{if(b(),x.current=null,!v.current){d("idle"),m(null),l?.(!1);return}if(I==="done"&&o&&y.current===o){d("idle"),m(null),v.current=!1,l?.(!1);return}I==="done"&&o&&(y.current=o),d(I),m(null),l?.(!0),w.current=setTimeout(()=>{w.current=null,d("idle"),v.current=!1,l?.(!1)},Jv)},[b,o,l]);if(Re.useEffect(()=>{if(n&&!k.current){k.current=!0,j("aborted");return}if(k.current=!!n,a&&!S.current){S.current=!0,j("done");return}if(!a&&S.current&&(S.current=!1),!(c==="done"||c==="aborted")&&t){const A=Date.now()-h.current;if(c==="idle"||!u)N(t,!!s);else if(t!==u||!!s!==f){if(r)return;A>=zd?N(t,!!s):(x.current={text:t,permission:!!s},D())}}},[t,s,n,a,c,u,f,N,j,D,r]),Re.useEffect(()=>()=>b(),[b]),Re.useEffect(()=>{const I=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(b(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",I),()=>document.removeEventListener("visibilitychange",I)},[c,b]),c==="idle"&&!u)return null;let M,C=!0;c==="done"?(M="Done",C=!1):c==="aborted"?(M="Aborted",C=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const P=C?`${M}...`:M,E=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${E?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(Ti,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(Ti,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(Ti,{variant:"shine",className:"typography-ui-header",children:P})})})}const Hd={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},ej=({todo:t})=>{const r=Hd[t.status]||Hd.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:F("flex-1 typography-ui-label",r.textClassName),children:t.content})})},Wd=[],tj=({isWorking:t,statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:l,isComplete:c,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=i.useState(!1),h=fe(A=>A.currentSessionId),x=wl(A=>h?A.sessionTodos.get(h)??Wd:Wd),g=wl(A=>A.loadTodos),{isMobile:w}=ke(),y=w||Vt();i.useEffect(()=>{h&&g(h)},[h,g]);const v=i.useMemo(()=>{const A={in_progress:0,pending:1,completed:2,cancelled:3};return[...x].filter(T=>T.status!=="cancelled").sort((T,R)=>A[T.status]-A[R.status])},[x]),S=i.useMemo(()=>v.find(A=>A.status==="in_progress")||v.find(A=>A.status==="pending")||null,[v]),k=i.useMemo(()=>{const A=x.filter(R=>R.status!=="cancelled").length;return{completed:x.filter(R=>R.status==="completed").length,total:A}},[x]),b=v.some(A=>A.status==="in_progress"||A.status==="pending"),N=!m&&(o||!a),[D,j]=i.useState(!1),M=t||c||o||D||b||m,C=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const A=T=>{C.current&&!C.current.contains(T.target)&&p(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[f]),!M)return null;const P=()=>p(A=>!A),E=d&&u?e.jsx("button",{type:"button",onClick:u,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(zn,{size:18,"aria-hidden":"true"})}):null,I=b?e.jsxs("button",{type:"button",onClick:P,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!y&&S?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:S.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[k.completed,"/",k.total]}),f?e.jsx(Wa,{className:"h-3.5 w-3.5"}):e.jsx(Ht,{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(zn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):N?e.jsx(Zv,{statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,completionId:l??null,isComplete:c,onResultVisibilityChange:j},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:C,children:[E,I,f&&b&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:F("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:[k.completed,"/",k.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:v.map(A=>e.jsx(ej,{todo:A},A.id))})]})]})]})})},ga=t=>!t||typeof t!="object"?!1:!!t.synthetic,Ud=t=>!Array.isArray(t)||t.length===0?!1:t.every(r=>ga(r)),sj=t=>!Array.isArray(t)||t.length===0?[]:t.some(s=>!ga(s))&&t.some(n=>ga(n))?t.filter(n=>!ga(n)):t,rj={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function nj(t){const r=fe(s=>!t||!s.sessionActivityPhase?"idle":s.sessionActivityPhase.get(t)??"idle");return i.useMemo(()=>{if(r==="idle")return rj;const s=r==="busy",n=r==="cooldown";return{phase:r,isWorking:s||n,isBusy:s,isCooldown:n}},[r])}function uc(){const t=fe(r=>r.currentSessionId);return nj(t)}const oj={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},Vd=t=>t.role==="assistant",aj=t=>t.type==="reasoning",Xf=t=>t.type==="text",Gd=t=>{if(Xf(t))return t.text;const r=t;if(typeof r.text=="string")return r.text;if(typeof r.content=="string")return r.content;if(typeof r.value=="string")return r.value},qd=t=>(Xf(t)||aj(t),t.time),ij=t=>{if(t.tool)return t.tool;const r=t;return typeof r.name=="string"?r.name:"tool"};function Jf(){const{currentSessionId:t,messages:r,permissions:s,sessionAbortFlags:n}=fe(Rl(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:l}=uc(),c=i.useMemo(()=>t?r.get(t)??[]:[],[t,r]),d=i.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=c.filter(M=>Vd(M.info)&&!Ud(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const x=[...h].sort((M,C)=>{const P=typeof M.info.time?.created=="number"?M.info.time.created:null,E=typeof C.info.time?.created=="number"?C.info.time.created:null;return P!==null&&E!==null&&P!==E?P-E:M.info.id.localeCompare(C.info.id)}),g=x[x.length-1];let w,y;const v=new Set(["edit","write","apply_patch"]);for(let M=(g.parts??[]).length-1;M>=0;M-=1){const C=g.parts?.[M];if(C)switch(C.type){case"reasoning":{const P=C.time??qd(C);(!P||typeof P.end>"u")&&!w&&(w="reasoning");break}case"tool":{const P=C.state?.status;if((P==="running"||P==="pending")&&!w){const E=ij(C);v.has(E)?w="editing":(w="tool",y=E)}break}case"text":{const P=Gd(C)??"";if(typeof P=="string"&&P.trim().length>0){const E=qd(C);(!E||typeof E.end>"u")&&!w&&(w="text")}break}}}const S={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",apply_patch:"applying patch",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"},k=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],b=M=>S[M]??`using ${M}`,N=()=>k[Math.floor(Math.random()*k.length)],D=w===void 0,j=w==="editing"?"editing file":w==="tool"&&y?b(y):w==="reasoning"?"thinking":w==="text"?"composing":N();return{activePartType:w,activeToolName:y,statusText:j,isGenericStatus:D}},[c]),u=i.useMemo(()=>{const h=t,x=h?n?.get(h)??null:null,g=!!(x&&!x.acknowledged);return{wasAborted:g,abortActive:g}},[t,n]),m=i.useMemo(()=>{if(u.wasAborted)return{...oj,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,x=o==="busy",g=l;let w="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?w="tooling":w=g?"cooldown":"streaming"),{activity:w,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:x,isCooldown:g,lifecyclePhase:x?"streaming":g?"cooldown":null,statusText:h?d.statusText:null,isGenericStatus:h?d.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:h,compactionDeadline:null,activePartType:h?d.activePartType:void 0,activeToolName:h?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:g}},[o,a,l,d,u]),f=i.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const x=c.filter(y=>Vd(y.info)&&!Ud(y.parts));if(x.length===0)return{isActive:h,characterCount:0};const g=x[x.length-1];let w=0;return(g.parts??[]).forEach(y=>{if(y.type!=="text")return;const v=Gd(y)??"";typeof v=="string"&&v.trim().length>0&&(w+=v.length)}),{isActive:h,characterCount:w}},[c,a,d.activePartType]),p=i.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const h=t;return(h?s?.get(h)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[t,s,m]);return{forming:f,working:p}}const lj=8,Kd=[],cj=t=>t==="primary"||t==="all"||t===void 0||t===null,Zf=t=>{if(!Array.isArray(t))return null;const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;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},Qd=(t,r)=>{const s=Zf(t);if(!(!s||s.length===0)){for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=s.length-1;n>=0;n-=1){const o=s[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},dj=(t,r)=>{const s=Zf(t);if(!s||s.length===0)return;const n={};for(const o of s)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},Xo=({onOpenSettings:t,scrollToBottom:r})=>{const[s,n]=i.useState(""),[o,a]=i.useState(!1),[l,c]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState(!1),[p,h]=i.useState(""),[x,g]=i.useState(!1),[w,y]=i.useState(""),[v,S]=i.useState(!1),[k,b]=i.useState(""),[N,D]=i.useState(null),j=i.useRef(null),M=i.useRef(null),C=i.useRef(null),P=i.useRef(null),E=i.useRef(null),I=i.useRef(null),A=fe($=>$.sendMessage),T=fe($=>$.currentSessionId),R=fe($=>$.newSessionDraft?.open),K=fe($=>$.abortCurrentOperation),Y=fe($=>$.acknowledgeSessionAbort),_=fe($=>$.abortPromptSessionId),J=fe($=>$.abortPromptExpiresAt),q=fe($=>$.clearAbortPrompt),Q=fe($=>$.sessionAbortFlags),z=fe($=>$.attachedFiles),H=fe($=>$.addAttachedFile),W=fe($=>$.addServerFile),B=fe($=>$.clearAttachedFiles),se=fe($=>$.saveSessionAgentSelection),L=fe($=>$.consumePendingInputText),ae=fe($=>$.pendingInputText),{currentProviderId:O,currentModelId:V,currentVariant:X,currentAgentName:re,setAgent:me,getVisibleAgents:G}=et(),he=G(),{isMobile:ye,inputBarOffset:ge,isKeyboardOpen:$e,setTimelineDialogOpen:ee,cornerRadius:Z}=ke(),{working:ie}=Jf(),[Me,oe]=i.useState(!1),xe=i.useRef(null),pe=i.useRef(!1),je=i.useRef(!1),ce=xr($=>$.queueModeEnabled),Ye=xr(i.useCallback($=>T?$.queuedMessages[T]??Kd:Kd,[T])),mt=xr($=>$.addToQueue),Ie=xr($=>$.clearQueue),{phase:le}=uc(),Xe=i.useRef(le),Ne=i.useRef(!1),Se=i.useCallback($=>{if(!ye||$.pointerType!=="touch")return;const ue=j.current;if(!ue||document.activeElement===ue)return;$.preventDefault(),$.stopPropagation();const de=document.scrollingElement;de&&de.scrollTop!==0&&(de.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{ue.focus({preventScroll:!0})}catch{ue.focus()}const Le=ue.value.length;try{ue.setSelectionRange(Le,Le)}catch{}},[ye]);i.useEffect(()=>{if(ae!==null){const $=L();$&&(n($),setTimeout(()=>{j.current?.focus()},0))}},[ae,L]);const qe=i.useMemo(()=>{if(re)return he.find($=>$.name===re)},[he,re]),rt=i.useMemo(()=>qe?Qd(qe.permission,"edit")??"ask":"deny",[qe]),We=fe(i.useCallback($=>!T||!re?void 0:$.sessionAgentEditModes.get(T)?.get(re),[T,re])),_e=i.useMemo(()=>{if(qe)return Qd(qe.permission,"webfetch")},[qe]),Ke=i.useMemo(()=>{if(!qe)return;const $=dj(qe.permission,"bash");return $||void 0},[qe]),xt=i.useMemo(()=>Qf({agentDefaultEditMode:rt,webfetchPermission:_e,bashPermission:Ke}),[rt,_e,Ke]),nt=!!(T&&re),Pt=i.useMemo(()=>nt&&We&&xt.modeAvailability[We]?We:xt.cascadeDefaultMode,[xt,nt,We]),Tt=i.useMemo(()=>uo(Pt),[Pt]),_t=i.useCallback($=>Vt()?`color-mix(in srgb, ${$} 55%, transparent)`:$,[]),Ve=i.useMemo(()=>{const $=Vt()?1:2,ue={borderRadius:Z};if(!Tt)return{...ue,borderWidth:$};const de=Tt.border??Tt.text;return{...ue,borderColor:_t(de),borderWidth:$}},[Tt,_t,Z]),dt=s.trim()||z.length>0,vt=Ye.length>0,ut=dt||vt,At=ie.isWorking,Rt=i.useMemo(()=>T?_===T&&!!J:!1,[_,J,T]),as=i.useCallback(()=>{if(!dt||!T)return;const $=s.replace(/^\n+|\n+$/g,""),ue=z.map(de=>({...de}));mt(T,{content:$,attachments:ue.length>0?ue:void 0}),n(""),ue.length>0&&B(),ye||j.current?.focus()},[dt,T,s,z,mt,B,ye]),Ct=async $=>{if($?.preventDefault(),!ut||!T&&!R)return;if(r?.({instant:!0,force:!0}),!O||!V){console.warn("Cannot send message: provider or model not selected");return}let ue="",de=[],Le;const Ue=[];for(let Ge=0;Ge<Ye.length;Ge++){const Be=Ye[Ge],{sanitizedText:Je,mention:yt}=$d(Be.content,he);!Le&&yt?.name&&(Le=yt.name),Ge===0?(ue=Je,de=Be.attachments??[]):Ue.push({text:Je,attachments:Be.attachments})}if(dt){const Ge=s.replace(/^\n+|\n+$/g,""),{sanitizedText:Be,mention:Je}=$d(Ge,he),yt=z.map(Et=>({...Et}));!Le&&Je?.name&&(Le=Je.name),Ye.length===0?(ue=Be,de=yt):Ue.push({text:Be,attachments:yt.length>0?yt:void 0})}if(!ue&&Ue.length===0)return;T&&vt&&Ie(T),n(""),z.length>0&&B(),ye&&j.current?.blur();const Qe=ue.trimStart();if(Qe.startsWith("/")){const Ge=Qe.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Ge==="undo"&&T){await fe.getState().handleSlashUndo(T),r?.({instant:!0,force:!0});return}else if(Ge==="redo"&&T){await fe.getState().handleSlashRedo(T),r?.({instant:!0,force:!0});return}else if(Ge==="timeline"&&T){ee(!0),n("");return}else if(Ge==="compact"&&T){try{const{opencodeClient:Be}=await Ss(async()=>{const{opencodeClient:Et}=await Promise.resolve().then(()=>Xx);return{opencodeClient:Et}},void 0),Je=Be.getDirectory();if((await Be.getApiClient().session.summarize({sessionID:T,directory:Je||void 0,providerID:O,modelID:V})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Be){console.error("Failed to compact session:",Be),U.error("Failed to compact session")}n("");return}}const Te=[...de,...Ue.flatMap(Ge=>Ge.attachments??[])];await A(ue,O,V,re,de,Le,Ue.length>0?Ue:void 0,X).catch(Ge=>{const Be=Ge instanceof Error?Ge.message:typeof Ge=="string"?Ge:String(Ge??""),Je=Be.toLowerCase();console.error("Message send failed:",Be||Ge);const yt=Je.includes("timeout")||Je.includes("timed out")||Je.includes("may still be processing")||Je.includes("being processed")||Je.includes("failed to fetch")||Je.includes("networkerror")||Je.includes("network error")||Je.includes("gateway timeout")||Je==="failed to send message";if(Je.includes("payload too large")||Je.includes("413")||Je.includes("entity too large")){U.error("Attachments are too large to send. Please try reducing the number or size of images."),Te.length>0&&lr.setState({attachedFiles:Te});return}yt||(Te.length>0&&lr.setState({attachedFiles:Te}),U.error(Be||"Message failed to send. Attachments restored."))}),ye||j.current?.focus()},$t=i.useRef(Ct);$t.current=Ct,i.useEffect(()=>{const $=Xe.current==="busy"||Xe.current==="cooldown",ue=le==="idle",de=T&&Q.has(T)&&(()=>{const Le=Q.get(T);return Le?Date.now()-Le.timestamp<2e3:!1})();$&&ue&&Ye.length>0&&!Ne.current&&!de&&(Ne.current=!0,setTimeout(()=>{T&&O&&V&&$t.current(),Ne.current=!1},100)),Xe.current=le},[le,Ye.length,T,O,V,Q]);const Mt=$=>{if(!lc($)){if(m&&P.current&&($.key==="Enter"||$.key==="ArrowUp"||$.key==="ArrowDown"||$.key==="Escape"||$.key==="Tab")){$.preventDefault(),P.current.handleKeyDown($.key);return}if(x&&E.current&&($.key==="Enter"||$.key==="ArrowUp"||$.key==="ArrowDown"||$.key==="Escape"||$.key==="Tab")){$.preventDefault(),E.current.handleKeyDown($.key);return}if(v&&I.current&&($.key==="Enter"||$.key==="ArrowUp"||$.key==="ArrowDown"||$.key==="Escape"||$.key==="Tab")){$.preventDefault(),I.current.handleKeyDown($.key);return}if(l&&C.current&&($.key==="Enter"||$.key==="ArrowUp"||$.key==="ArrowDown"||$.key==="Escape"||$.key==="Tab")){$.preventDefault(),C.current.handleKeyDown($.key);return}if($.key==="Tab"&&!m&&!x&&!l){$.preventDefault(),qt();return}if($.key==="Enter"&&!$.shiftKey&&!ye){$.preventDefault();const ue=$.ctrlKey||$.metaKey,de=dt&&T&&le!=="idle";ce?ue||!de?Ct():as():ue&&de?as():Ct()}}},Gt=i.useCallback(()=>{xe.current&&(clearTimeout(xe.current),xe.current=null),oe(!0),xe.current=setTimeout(()=>{oe(!1),xe.current=null},1800)},[]),Dt=i.useCallback(()=>{q(),Gt(),K()},[K,q,Gt]),qt=()=>{const $=he.filter(Ue=>cj(Ue.mode));if($.length<=1)return;const de=($.findIndex(Ue=>Ue.name===re)+1)%$.length,Le=$[de];me(Le.name),T&&se(T,Le.name)},St=i.useCallback(()=>{const $=j.current;if(!$)return;$.style.height="auto";const ue=$.ownerDocument?.defaultView,de=ue?ue.getComputedStyle($):null,Le=de?parseFloat(de.lineHeight):NaN,Ue=de?parseFloat(de.paddingTop):NaN,Qe=de?parseFloat(de.paddingBottom):NaN,Te=22,Be=Number.isNaN(Ue)||Number.isNaN(Qe)?16:Ue+Qe,yt=(Number.isNaN(Le)?Te:Le)*lj+Be,Et=$.scrollHeight||$.offsetHeight,Cs=Math.min(Et,yt);$.style.height=`${Cs}px`,$.style.maxHeight=`${yt}px`,D(As=>As&&As.height===Cs&&As.maxHeight===yt?As:{height:Cs,maxHeight:yt})},[]);i.useLayoutEffect(()=>{St()},[St,s,ye]);const Lt=i.useCallback(($,ue)=>{if($.startsWith("/")){const Te=$.indexOf(" "),Ge=$.indexOf(`
166
- `),Be=Math.min(Te===-1?$.length:Te,Ge===-1?$.length:Ge);if(ue<=Be&&Te===-1){const Je=$.substring(1,Be);h(Je),f(!0),c(!1),g(!1),S(!1);return}}f(!1);const de=$.substring(0,ue),Le=de.lastIndexOf("#");if(Le!==-1){const Te=Le>0?de[Le-1]:null,Ge=de.substring(Le+1),Be=Ge.includes(" ")||Ge.includes(`
167
- `);if((!Te||/\s/.test(Te))&&!Be){y(Ge),g(!0),c(!1);return}}g(!1),y("");const Ue=de.lastIndexOf("/");if(Ue!==-1){const Te=Ue>0?de[Ue-1]:null,Ge=de.substring(Ue+1),Be=Ge.includes(" ")||Ge.includes(`
168
- `);if((!Te||/\s/.test(Te))&&!Be){b(Ge),S(!0),c(!1),g(!1);return}}S(!1),b("");const Qe=de.lastIndexOf("@");if(Qe!==-1){const Te=de.substring(Qe+1);!Te.includes(" ")&&!Te.includes(`
169
- `)?(u(Te),c(!0)):c(!1)}else c(!1)},[y,h,u,g,f,c,S,b]),be=i.useCallback($=>{if(!$)return;const ue=j.current;if(!ue){const Te=s+$;n(Te),Lt(Te,Te.length),requestAnimationFrame(()=>St());return}const de=ue.selectionStart??s.length,Le=ue.selectionEnd??s.length,Ue=`${s.substring(0,de)}${$}${s.substring(Le)}`;n(Ue);const Qe=de+$.length;requestAnimationFrame(()=>{const Te=j.current;Te&&(Te.selectionStart=Qe,Te.selectionEnd=Qe),St()}),Lt(Ue,Qe)},[St,s,Lt]),Pe=$=>{const ue=$.target.value,de=$.target.selectionStart??ue.length;n(ue),St(),Lt(ue,de)},Oe=i.useCallback(async $=>{const ue=new Map;Array.from($.clipboardData.files||[]).forEach(Qe=>{Qe.type.startsWith("image/")&&ue.set(`${Qe.name}-${Qe.size}`,Qe)}),Array.from($.clipboardData.items||[]).forEach(Qe=>{if(Qe.kind==="file"&&Qe.type.startsWith("image/")){const Te=Qe.getAsFile();Te&&ue.set(`${Te.name}-${Te.size}`,Te)}});const de=Array.from(ue.values());if(de.length===0||!T&&!R)return;$.preventDefault();const Le=$.clipboardData.getData("text");Le&&be(Le);let Ue=0;for(const Qe of de){const Te=fe.getState().attachedFiles.length;try{await H(Qe),fe.getState().attachedFiles.length>Te&&(Ue+=1)}catch(Ge){console.error("Clipboard image attach failed",Ge),U.error(Ge instanceof Error?Ge.message:"Failed to attach image from clipboard")}}Ue>0&&U.success(`Attached ${Ue} image${Ue>1?"s":""} from clipboard`)},[H,T,R,be]),st=$=>{const ue=j.current?.selectionStart||0,Le=s.substring(0,ue).lastIndexOf("@");if(Le!==-1){const Ue=s.substring(0,Le)+$.name+s.substring(ue);n(Ue)}c(!1),u(""),j.current?.focus()},ne=$=>{const de=j.current?.selectionStart??s.length,Ue=s.substring(0,de).lastIndexOf("#");if(Ue!==-1){const Qe=s.substring(0,Ue)+`#${$} `+s.substring(de);n(Qe);const Te=Ue+$.length+2;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Te,j.current.selectionEnd=Te),St(),Lt(Qe,Te)})}g(!1),y(""),j.current?.focus()},Ae=$=>{const de=j.current?.selectionStart??s.length,Ue=s.substring(0,de).lastIndexOf("/");if(Ue!==-1){const Qe=s.substring(0,Ue)+`${$} `+s.substring(de);n(Qe);const Te=Ue+$.length+1;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Te,j.current.selectionEnd=Te),St(),Lt(Qe,Te)})}S(!1),b(""),j.current?.focus()},te=$=>{n(`/${$.name} `);const ue=j.current;ue&&(ue._commandMetadata=$),f(!1),h(""),setTimeout(()=>{j.current&&(j.current.focus(),j.current.setSelectionRange(j.current.value.length,j.current.value.length))},0)};i.useEffect(()=>{T&&j.current&&!ye&&j.current.focus()},[T,ye]),i.useEffect(()=>{_&&_!==T&&q()},[_,T,q]);const Ce=$=>{$.preventDefault(),$.stopPropagation(),(T||R)&&!o&&a(!0)},De=$=>{$.preventDefault(),$.stopPropagation(),$.currentTarget===$.target&&a(!1)},He=async $=>{if($.preventDefault(),$.stopPropagation(),a(!1),!T&&!R)return;const ue=Array.from($.dataTransfer.files);let de=0;for(const Le of ue){const Ue=fe.getState().attachedFiles.length;try{await H(Le),fe.getState().attachedFiles.length>Ue&&(de+=1)}catch(Qe){console.error("File attach failed",Qe),U.error(Qe instanceof Error?Qe.message:"Failed to attach file")}}de>0&&U.success(`Attached ${de} file${de>1?"s":""}`)},wt=i.useCallback(async $=>{let ue=0;for(const de of $){const Le=fe.getState().attachedFiles.length;try{await W(de.path,de.name),fe.getState().attachedFiles.length>Le&&(ue+=1)}catch(Ue){console.error("Server file attach failed",Ue),U.error(Ue instanceof Error?Ue.message:"Failed to attach file")}}ue>0&&U.success(`Attached ${ue} file${ue>1?"s":""}`)},[W]),Nt=i.useRef(null),[Xt,we]=i.useState(!1),ze=i.useCallback(async $=>{let ue=0;const de=Array.isArray($)?$:Array.from($);for(const Le of de){const Ue=fe.getState().attachedFiles.length;try{await H(Le),fe.getState().attachedFiles.length>Ue&&(ue+=1)}catch(Qe){console.error("File attach failed",Qe),U.error(Qe instanceof Error?Qe.message:"Failed to attach file")}}ue>0&&U.success(`Attached ${ue} file${ue>1?"s":""}`)},[H]),tt=i.useCallback(async()=>{try{const ue=await(await fetch("/api/vscode/pick-files")).json(),de=Array.isArray(ue?.files)?ue.files:[],Le=Array.isArray(ue?.skipped)?ue.skipped:[];if(Le.length>0){const Qe=Le.map(Te=>`${Te?.name||"file"}: ${Te?.reason||"skipped"}`).join(`
170
- `);U.error(`Some files were skipped:
171
- ${Qe}`)}const Ue=de.map(Qe=>{if(!Qe?.dataUrl)return null;try{const[Te,Ge]=Qe.dataUrl.split(","),Be=Qe.mimeType||Te?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Ge)return null;const Je=atob(Ge),yt=new Uint8Array(Je.length);for(let Cs=0;Cs<Je.length;Cs++)yt[Cs]=Je.charCodeAt(Cs);const Et=new Blob([yt],{type:Be});return new File([Et],Qe.name||"file",{type:Be})}catch(Te){return console.error("Failed to decode VS Code picked file",Te),null}}).filter(Boolean);Ue.length>0&&await ze(Ue)}catch($){console.error("VS Code file pick failed",$),U.error($ instanceof Error?$.message:"Failed to pick files in VS Code")}},[ze]),Ee=i.useCallback(()=>{if(Vt()){tt();return}Nt.current?.click()},[tt]),ot=i.useCallback(async $=>{const ue=$.target.files;ue&&(await ze(ue),$.target.value="")},[ze]),ft="gap-x-1.5 gap-y-0",Bt=Vt(),Wt=ye?"px-1.5 py-1.5":Bt?"px-1.5 py-1":"px-2.5 py-1.5",vs=ye?"h-9 w-9":Bt?"h-[22px] w-[22px]":"h-7 w-7",is=ye?"h-5 w-5":Bt?"h-4 w-4":"h-[18px] w-[18px]",Jt=F(vs,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Nn=!ye&&Rt&&At?e.jsx("button",{type:"button",onClick:Dt,className:F(Jt,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(zn,{className:F(is)})}):e.jsx("button",{type:ye?"button":"submit",disabled:!ut||!T&&!R,onPointerDownCapture:$=>{!ye||$.pointerType!=="touch"||!ut||!T&&!R||(je.current=!0,$.preventDefault(),$.stopPropagation(),Ct())},onClick:$=>{if(ye){if(je.current){je.current=!1;return}$.preventDefault(),Ct()}},className:F(Jt,ut&&(T||R)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Ha,{className:F(is)})}),ii=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Nt,type:"file",multiple:!0,className:"hidden",onChange:ot,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(Bv,{onFilesSelected:wt,multiSelect:!0,presentation:ye?"modal":"dropdown",open:Xt,onOpenChange:we,children:ye?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:Jt,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(pm,{className:F(is,"text-current")})})}),e.jsxs(rs,{align:"start",children:[e.jsxs(jt,{onSelect:()=>{requestAnimationFrame(()=>Ee())},children:[e.jsx(va,{}),"Attach files"]}),e.jsxs(jt,{onSelect:()=>{requestAnimationFrame(()=>{we(!0)})},children:[e.jsx(bg,{}),"Attach from project"]})]})]})]})]}),li=t?e.jsx("button",{type:"button",onClick:t,className:Jt,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(gn,{className:F(is,"text-current")})}):null,To=e.jsxs(e.Fragment,{children:[ii,li]}),ci=ie.statusText;i.useEffect(()=>{const $=!!ie.wasAborted;!pe.current&&$&&!Me&&(Gt(),T&&Y(T)),pe.current=$},[Y,T,Me,Gt,ie.wasAborted]),i.useEffect(()=>()=>{xe.current&&(clearTimeout(xe.current),xe.current=null)},[]);const di=ye&&At;return e.jsxs("form",{onSubmit:Ct,className:F("relative pt-0 pb-2 md:pb-4",ye&&$e?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:ye&&ge>0&&!$e?{marginBottom:`${ge}px`}:void 0,children:[e.jsx("div",{className:"absolute bottom-full left-0 right-0",children:e.jsx(tj,{isWorking:ie.isWorking,statusText:ci,isGenericStatus:ie.isGenericStatus,isWaitingForPermission:ie.isWaitingForPermission,wasAborted:ie.wasAborted,abortActive:ie.abortActive,completionId:ie.lastCompletionId,isComplete:ie.isComplete,showAbort:di,onAbort:Dt,showAbortStatus:Me})}),e.jsxs("div",{ref:M,className:F("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Ce,onDragLeave:De,onDrop:He,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:Jt,onClick:()=>Ee(),title:"Attach files","aria-label":"Attach files",children:e.jsx(va,{className:F(is,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Tv,{}),e.jsx(Wf,{onEditMessage:$=>{n($),setTimeout(()=>{j.current?.focus()},0)}}),e.jsxs("div",{className:F("border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Ve,children:[m&&e.jsx(Vf,{ref:P,searchQuery:p,onCommandSelect:te,onClose:()=>f(!1)}),x&&e.jsx(Gf,{ref:E,searchQuery:w,onAgentSelect:ne,onClose:()=>g(!1)}),v&&e.jsx(qf,{ref:I,searchQuery:k,onSkillSelect:Ae,onClose:()=>S(!1)}),l&&e.jsx(Lv,{ref:C,searchQuery:d,onFileSelect:st,onClose:()=>c(!1)}),e.jsx(Rs,{ref:j,"data-chat-input":"true",value:s,onChange:Pe,onKeyDown:Mt,onPaste:Oe,onPointerDownCapture:Se,placeholder:T||R?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!T&&!R,className:F("min-h-[52px] resize-none border-0 px-3 shadow-none 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",ye?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:N?`${N.height}px`:void 0,maxHeight:N?`${N.maxHeight}px`:void 0,borderTopLeftRadius:Z,borderTopRightRadius:Z},rows:1}),e.jsx("div",{className:F("bg-transparent",Wt,ye?"flex items-center gap-x-1.5":F("flex items-center justify-between",ft)),style:{borderBottomLeftRadius:Z,borderBottomRightRadius:Z},"data-chat-input-footer":"true",children:ye?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:To}),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(_d,{className:F("w-full flex items-center justify-end min-w-0")})}),Nn]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("flex items-center flex-shrink-0",ft),children:To}),e.jsxs("div",{className:F("flex items-center flex-1 justify-end",ft,"md:gap-x-3"),children:[e.jsx(_d,{className:F("flex-1 min-w-0 justify-end")}),Nn]})]})})]})]})]})};function Fi({className:t,...r}){return e.jsx("div",{"data-slot":"skeleton",className:F("bg-accent animate-pulse rounded-xl",t),...r})}const Yd=(t,r,s,n,o=4)=>{const a=[];for(let l=0;l<o;l++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,m=l/o,f=(l+1)/o,p=(v,S,k)=>v+(S-v)*k,h=(v,S,k,b,N,D)=>{const j=p(v,S,N),M=p(b,k,N);return p(j,M,D)},x={x:h(t.x,r.x,s.x,n.x,d,m),y:h(t.y,r.y,s.y,n.y,d,m)},g={x:h(t.x,r.x,s.x,n.x,u,m),y:h(t.y,r.y,s.y,n.y,u,m)},w={x:h(t.x,r.x,s.x,n.x,u,f),y:h(t.y,r.y,s.y,n.y,u,f)},y={x:h(t.x,r.x,s.x,n.x,d,f),y:h(t.y,r.y,s.y,n.y,d,f)};a.push({path:`M${x.x} ${x.y} L${g.x} ${g.y} L${w.x} ${w.y} L${y.x} ${y.y} Z`,row:l,col:c})}return a},mc=({className:t="",width:r=70,height:s=70,isAnimated:n=!1})=>{const o=ti();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const l=a?"white":"black",c=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,h=50,x={x:50,y:h-m},g={x:50-m*f,y:h-m*p},w={x:50+m*f,y:h-m*p},y={x:50,y:h},v={x:50-m*f,y:h+m*p},S={x:50+m*f,y:h+m*p},k={x:50,y:h+m},N=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(x.y+g.y+y.y+w.y)/4})`,D=Yd(g,y,k,v),j=Yd(y,w,S,k),M=Re.useMemo(()=>{const C=[];for(let P=0;P<32;P++)C.push(.1+Math.random()*.5);return C},[]);return e.jsxs("svg",{width:r,height:s,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${y.x} ${y.y} L${g.x} ${g.y} L${v.x} ${v.y} L${k.x} ${k.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),D.map((C,P)=>e.jsx("path",{d:C.path,fill:u,opacity:M[P]},`left-${P}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${w.x} ${w.y} L${S.x} ${S.y} L${k.x} ${k.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),j.map((C,P)=>e.jsx("path",{d:C.path,fill:u,opacity:M[P+16]},`right-${P}`)),e.jsx("path",{d:`M${x.x} ${x.y} L${g.x} ${g.y} L${y.x} ${y.y} L${w.x} ${w.y} Z`,fill:"none",stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${N} 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 uj({children:t,className:r,interval:s=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:l=!0,mode:c="popLayout"}){const[d,u]=Re.useState(0),m=Re.Children.toArray(t);Re.useEffect(()=>{if(!l)return;const p=s*1e3,h=setInterval(()=>{u(x=>{const g=(x+1)%m.length;return a?.(g),g})},p);return()=>clearInterval(h)},[m.length,s,a,l]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:F("relative",r),children:[e.jsx("div",{className:"invisible whitespace-nowrap",children:m.map((p,h)=>e.jsx("div",{className:h===0?"":"absolute",children:p},h))}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(wg,{mode:c,initial:!1,children:e.jsx(In.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const mj=["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"],fj=()=>{const t=ti();let r=!0;t?r=t.currentTheme.metadata.variant!=="light":typeof window<"u"&&(r=window.matchMedia("(prefers-color-scheme: dark)").matches);const s=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(mc,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(uj,{className:"text-body-md",interval:4,transition:{duration:.5},children:mj.map(n=>e.jsxs("span",{style:{color:s},children:['"',n,'…"']},n))})]})},Ri=i.memo(fj),pj={'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"}},hj={'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 Ur{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Ur.instance||(Ur.instance=new Ur),Ur.instance}recordSessionStart(r){this.sessionStartTimes.set(r,Date.now())}getSessionStartTime(r){return this.sessionStartTimes.get(r)}shouldAnimateMessage(r,s){if(r.role!=="assistant"||this.seenMessageIds.has(r.id))return!1;const n=this.sessionStartTimes.get(s);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,s){this.seenMessageIds.add(r),this.messageCreationTimes.set(r,s)}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 fc(t){const r=t.colors.syntax,s=t.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||s.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:t.colors.status.error,backgroundColor:t.colors.status.errorBackground},inserted:{color:t.colors.status.success,backgroundColor:t.colors.status.successBackground},title:{color:t.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:s.mutedForeground},table:{color:r.base.function},blockquote:{color:s.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 cr=({children:t,className:r,skipAnimation:s})=>{const[n,o]=i.useState(s??!1);return i.useEffect(()=>{if(s)return;let a=null;const l=()=>o(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?a=window.requestAnimationFrame(l):l(),()=>{a!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(a)}},[s]),s?e.jsx(e.Fragment,{children:t}):e.jsx("div",{className:F("w-full transition-all duration-300 ease-out",n?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:t})},gj=({isUser:t,providerID:r,agentName:s,modelName:n,variant:o,isDarkTheme:a})=>{const{src:l,onError:c,hasLogo:d}=Lf(r);return e.jsx(cr,{children:e.jsx("div",{className:F("mb-2"),children:e.jsx("div",{className:F("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:t?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Xs,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&l?e.jsx("img",{src:l,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:c}):e.jsx(Sr,{className:"h-4 w-4",style:{color:`var(${zr(s).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:F("font-bold typography-ui-header tracking-tight leading-none",t?"text-primary":"text-foreground"),children:t?"You":n||"Assistant"}),!t&&s&&e.jsxs("div",{className:F("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)]",zr(s).class),children:[e.jsx(gn,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:s})]}),!t&&o&&e.jsxs("div",{className:F("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(Sr,{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})]})]})]})})})})},xj=i.memo(gj),yj=t=>`https://opencode.ai/docs/agents/#${encodeURIComponent(t)}`,bj=({part:t,messageId:r,agentMention:s})=>{const n=t,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[l,c]=i.useState(!1),[d,u]=i.useState(!1),m=i.useRef(null);i.useEffect(()=>{const h=m.current;if(!h||l)return;const x=()=>{u(h.scrollHeight>h.clientHeight)};x();const g=new ResizeObserver(x);return g.observe(h),()=>g.disconnect()},[a,l]);const f=i.useCallback(()=>{(d||l)&&c(h=>!h)},[d,l]);if(!a||a.trim().length===0)return null;const p=()=>{if(!s?.token||!a.includes(s.token))return a;const h=a.indexOf(s.token),x=a.slice(0,h),g=a.slice(h+s.token.length);return e.jsxs(e.Fragment,{children:[x,e.jsx("a",{href:yj(s.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:w=>w.stopPropagation(),children:s.token}),g]})};return e.jsx("div",{className:F("break-words whitespace-pre-wrap font-sans typography-markdown",!l&&"line-clamp-3",(d||l)&&"cursor-pointer"),ref:m,onClick:f,children:p()},t.id||`${r}-user-text`)},wj=i.memo(bj),Xd=(t,r)=>{const s=t[Symbol.toPrimitive];if(typeof s=="function")try{if(s()===r)return t}catch{}try{Object.defineProperty(t,"toString",{value:()=>r,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(t,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0})}catch{}return t},Jd=()=>{if(!Vt()||typeof window>"u")return ud;const t=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(t?.light&&t?.dark){const r=Xd({...t.light},`vscode-shiki-light:${String(t.light?.name??"theme")}`),s=Xd({...t.dark},`vscode-shiki-dark:${String(t.dark?.name??"theme")}`);return[r,s]}return ud},vj=()=>{const[t,r]=i.useState(Jd);return i.useEffect(()=>{if(!Vt()||typeof window>"u")return;const s=n=>{r(Jd())};return window.addEventListener("openchamber:vscode-shiki-themes",s),()=>window.removeEventListener("openchamber:vscode-shiki-themes",s)},[]),t},ep=t=>{const r=[],s=[],n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach(l=>r.push(l.innerText.trim()));const o=t.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(l=>{const c=l.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),s.push(d)}),{headers:r,rows:s}},tp=({headers:t,rows:r})=>{const s=o=>o.includes(",")||o.includes('"')||o.includes(`
172
- `)?`"${o.replace(/"/g,'""')}"`:o,n=[];return t.length>0&&n.push(t.map(s).join(",")),r.forEach(o=>n.push(o.map(s).join(","))),n.join(`
173
- `)},jj=({headers:t,rows:r})=>{const s=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return t.length>0&&n.push(t.map(s).join(" ")),r.forEach(o=>n.push(o.map(s).join(" "))),n.join(`
174
- `)},Sj=({headers:t,rows:r})=>{if(t.length===0)return"";const s=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${t.map(s).join(" | ")} |`),n.push(`| ${t.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=t.map((l,c)=>s(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
175
- `)},Nj=(t,r,s)=>{const n=new Blob([r],{type:s}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},kj=({tableRef:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const l=async c=>{const d=t.current?.querySelector("table");if(d)try{const u=ep(d),m=c==="csv"?tp(u):jj(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([m],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),s(!0),o(!1),setTimeout(()=>s(!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(Qt,{className:"size-3.5"}):e.jsx(Js,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("tsv"),children:"TSV"})]})]})},Cj=({tableRef:t})=>{const[r,s]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=l=>{n.current&&!n.current.contains(l.target)&&s(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const l=t.current?.querySelector("table");if(l)try{const c=ep(l),d=a==="csv"?tp(c):Sj(c);Nj(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),s(!1)}catch(c){console.error("Failed to download table:",c)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>s(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(qr,{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"})]})]})},Mj=({children:t,className:r})=>{const s=i.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:s,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(kj,{tableRef:s}),e.jsx(Cj,{tableRef:s})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:F("w-full border-collapse border border-border",r),"data-streamdown":"table",children:t})})]})},Dj=({children:t,className:r,style:s,...n})=>{const[o,a]=i.useState(!1),l=i.useRef(null),c=i.useMemo(()=>{if(!s)return s;const m={...s},f=x=>{if(typeof x!="string")return{value:void 0,vars:{}};const[g,...w]=x.split(";").map(v=>v.trim()).filter(Boolean),y={};for(const v of w){const S=v.indexOf(":");if(S===-1)continue;const k=v.slice(0,S).trim(),b=v.slice(S+1).trim();!k.startsWith("--")||b.length===0||(y[k]=b)}return{value:g,vars:y}},p=f(s.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[x,g]of Object.entries(p.vars))m[x]=g;const h=f(s.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[x,g]of Object.entries(h.vars))m[x]=g;return m},[s]),d=()=>l.current&&l.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:l,children:[e.jsx("pre",{...n,className:F(r),style:c,children:t}),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(Qt,{className:"size-3.5"}):e.jsx(Js,{className:"size-3.5"})})})]})},Aj={pre:Dj,table:Mj},fn=({content:t,className:r,variant:s="assistant"})=>{const n=vj(),o=s==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:F("break-words",r),children:e.jsx(vg,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:Aj,children:t})})},Ej=t=>{let r=t.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},Ij=t=>t?t.includes("<file_diagnostics>")||t.includes("This file has errors")||t.includes("please fix"):!1,Pj=t=>t?t.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Zd=(t,r)=>!t||typeof t!="object"?String(t):iw(t,r||""),Li=(t,r,s)=>{let n=Ej(t);if((r==="edit"||r==="multiedit")&&Ij(n)&&(n=Pj(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&s?.diff){const o=s.diff;return typeof o=="string"?o:String(o)}return n},Tj=(t,r)=>{try{const s=t.trim().split(`
176
- `).filter(Boolean);if(s.length===0)return null;const n=[];return s.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,l,c]=a,d=Math.floor(l.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:F("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:Er.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}},Fj=(t,r,s)=>{try{const n=t.trim().split(`
177
- `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const l=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(l){const[,c,d,u]=l,m=u!==void 0?d:"",f=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:m,content:f})}}),e.jsxs("div",{className:F("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Er.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,l])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:F("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:l.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:F("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},Rj=(t,r,s)=>{try{const n=t.trim().split(`
178
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(l=>{const c=l.lastIndexOf("/"),d=c>0?l.substring(0,c):"/",u=c>=0?l.substring(c+1):l;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:F("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Er.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(l=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:F("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[l,"/"]}),e.jsx("div",{className:F("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[l].sort().map(c=>e.jsxs("div",{className:F("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},l))]})}catch{return null}},Lj=(t,r)=>{try{const s=JSON.parse(t);if(!Array.isArray(s))return null;const n={in_progress:s.filter(a=>a.status==="in_progress"),pending:s.filter(a=>a.status==="pending"),completed:s.filter(a=>a.status==="completed"),cancelled:s.filter(a=>a.status==="cancelled")},o=a=>{const l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:l,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:F("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Er.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: ",s.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qt,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qt,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||l))})]})]})}catch{return null}},Oj=(t,r,s)=>{try{return e.jsx("div",{className:F("typography-code max-w-none w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Er.tool.popup,children:e.jsx(fn,{content:t,variant:"tool"})})}catch{return null}},sp=t=>{const r=t.split(`
179
- `);let s="";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:")&&(s=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const l=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=l?parseInt(l[1]):0,d=l?parseInt(l[2]):0,u=[];let m=c,f=d,p=o+1;for(;p<r.length&&!r[p].startsWith("@@")&&!r[p].startsWith("Index:");){const h=r[p];h.startsWith("+")?(u.push({type:"added",lineNumber:f,content:h.substring(1)}),f++):h.startsWith("-")?(u.push({type:"removed",lineNumber:m,content:h.substring(1)}),m++):h.startsWith(" ")&&(u.push({type:"context",lineNumber:f,content:h.substring(1)}),m++,f++),p++}n.push({file:s,oldStart:c,newStart:d,lines:u}),o=p;continue}o++}return n},vl=(t,r,s)=>ow(r,t,s),rp=t=>{const r="h-3.5 w-3.5 flex-shrink-0",s=t.toLowerCase();return s==="edit"||s==="multiedit"||s==="apply_patch"||s==="str_replace"||s==="str_replace_based_edit_tool"?e.jsx(jg,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(hm,{className:r}):s==="read"||s==="view"||s==="file_read"||s==="cat"?e.jsx(wo,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"?e.jsx(Qr,{className:r}):s==="list"||s==="ls"||s==="dir"||s==="list_files"?e.jsx(nr,{className:r}):s==="search"||s==="grep"||s==="find"||s==="ripgrep"?e.jsx(Sg,{className:r}):s==="glob"?e.jsx(Ng,{className:r}):s==="fetch"||s==="curl"||s==="wget"||s==="webfetch"?e.jsx(tl,{className:r}):s==="web-search"||s==="websearch"||s==="search_web"||s==="codesearch"||s==="google"||s==="bing"||s==="duckduckgo"||s==="perplexity"?e.jsx(tl,{className:r}):s==="todowrite"||s==="todoread"?e.jsx(gm,{className:r}):s==="skill"?e.jsx(xm,{className:r}):s==="question"?e.jsx(kg,{className:r}):s.startsWith("git")?e.jsx(Kt,{className:r}):e.jsx(Va,{className:r})},_j=(t,r,s=Date.now())=>{const o=(r?r-t:s-t)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},$j=({start:t,end:r,active:s})=>{const[n,o]=i.useState(()=>Date.now());return i.useEffect(()=>{if(!s)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[s]),e.jsx(e.Fragment,{children:_j(t,r,n)})},Bj=t=>{if(!t?.diff||typeof t.diff!="string")return null;const r=t.diff.split(`
180
- `);let s=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&s++,o.startsWith("-")&&!o.startsWith("---")&&n++;return s===0&&n===0?null:{added:s,removed:n}},xa=(t,r,s)=>{if(s)return t.split("/").pop()||t;if(t.startsWith(r)){const n=t.substring(r.length);return n.startsWith("/")?n.substring(1):n}return t},zj=t=>{const r=t.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!r)return null;const s=[],n=r[1],o=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let a;for(;(a=o.exec(n))!==null;)s.push({question:a[1],answer:a[2]});return s.length>0?s:null},Hj=(t,r,s,n)=>{const o=r,a=o.metadata,l=o.input;if(t.tool==="apply_patch"){const d=Array.isArray(a?.files)?a?.files:[],u=d[0],m=u?.relativePath||u?.filePath;return d.length>1?`${d.length} files`:typeof m=="string"?xa(m,n,s):"Patch"}if(t.tool==="question"&&l?.questions&&Array.isArray(l.questions)){const d=l.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((t.tool==="edit"||t.tool==="multiedit")&&l){const d=l?.filePath||l?.file_path||l?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return xa(d,n,s)}if((t.tool==="read"||t.tool==="write")&&l){const d=l?.filePath||l?.file_path||l?.path;if(typeof d=="string")return xa(d,n,s)}if(t.tool==="bash"&&l?.command&&typeof l.command=="string"){const d=l.command.split(`
181
- `)[0];return s?d.substring(0,50):d.substring(0,100)}if(t.tool==="task"&&l?.description&&typeof l.description=="string")return s?l.description.substring(0,40):l.description.substring(0,80);if(t.tool==="skill"&&l?.name&&typeof l.name=="string")return l.name;const c=l?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},jl=({children:t,maxHeightClass:r="max-h-[60vh]",className:s,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(ht,{outerClassName:F("w-full min-w-0 flex-none overflow-hidden",r,n),className:F("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",s),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:t})}),Wj=t=>{const r=t.state?.title;return typeof r=="string"&&r.trim().length>0?r:typeof t.tool=="string"&&t.tool.trim().length>0?t.tool:"tool"},Uj=t=>t.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Vj=({entries:t,isExpanded:r,hasPrevTool:s,hasNextTool:n,output:o,sessionId:a})=>{const l=fe(g=>g.setCurrentSession),c=i.useMemo(()=>t.filter(g=>g.state?.status==="completed"),[t]),d=typeof o=="string"?Uj(o):"",u=d.length>0,[m,f]=i.useState(!1),p=g=>{g.stopPropagation(),a&&l(a)};if(c.length===0&&!u&&!a)return null;const h=r?c:c.slice(-6),x=Math.max(0,c.length-h.length);return e.jsxs("div",{className:F("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-[""]',s?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[c.length>0?e.jsx(jl,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[x>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",x," more…"]}):null,h.map((g,w)=>{const y=typeof g.tool=="string"&&g.tool.trim().length>0?g.tool:"tool",v=Wj(g),S=Ql(y).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:rp(y)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:S}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:v})]},g.id??`${y}-${w}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:g=>g.stopPropagation(),onClick:p,children:[e.jsx(dr,{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:F("space-y-1",(c.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:g=>g.stopPropagation(),onClick:g=>{g.stopPropagation(),f(w=>!w)},children:[m?e.jsx(Ht,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(zs,{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(jl,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(fn,{content:d,variant:"tool"})})}):null]}):null]})},Gj=({diff:t,syntaxTheme:r,input:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:sp(t).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,l)=>e.jsxs("div",{className:F("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(Ir,{style:r,language:_r(typeof s?.file_path=="string"?s.file_path:typeof s?.filePath=="string"?s.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},l))})]},o))}),qj=({content:t,syntaxTheme:r,filePath:s,displayPath:n})=>{const o=t.split(`
182
- `),a=_r(s??"")||vl(t,"write",s?{filePath:s}:void 0),l=Math.max(o.length,1),c=l===1?"line 1":`lines 1-${l}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ir,{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))})]})},Kj=({content:t,filePath:r,displayPath:s})=>{const n=ml(r),o=r.toLowerCase().endsWith(".svg"),a=i.useMemo(()=>o&&!t.startsWith("data:")?`data:image/svg+xml;base64,${btoa(t)}`:t.startsWith("data:")?t:`data:${n};base64,${t}`,[t,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:s}),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:s,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})},Qj=({part:t,state:r,syntaxTheme:s,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:l})=>{const c=r,d=c.metadata,u=c.input,m=c.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",h=typeof d?.diff=="string"?d.diff:null,x=t.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,g=t.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,w=t.tool==="write"&&!!g,y=x?Co(x):!1,v=w?x?xa(x,o,n):"New file":null,S=i.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&t.tool==="bash"?Zd(u,t.tool):typeof u.content=="string"?u.content??"":Zd(u,t.tool),[u,t.tool]),k=t.tool!=="apply_patch"&&S.trim().length>0,b=(D,j)=>e.jsx(jl,{maxHeightClass:j?.maxHeightClass,className:j?.className,disableHorizontal:j?.disableHorizontal,outerClassName:j?.outerClassName,children:D}),N=()=>{if(t.tool==="question"){if(r.status==="completed"&&f){const D=zj(p);if(D&&D.length>0)return b(e.jsx("div",{className:"space-y-2",children:D.map((j,M)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:j.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:j.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(t.tool==="todowrite"||t.tool==="todoread"){if(r.status==="completed"&&f){const D=Lj(p,{unstyled:!0});return b(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(t.tool==="list"&&f){const D=Tj(p,{unstyled:!0});return b(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="grep"&&f){const D=Fj(p,n,{unstyled:!0});return b(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="glob"&&f){const D=Rj(p,n,{unstyled:!0});return b(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="task"&&f)return b(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(fn,{content:p,variant:"tool"})}));if((t.tool==="web-search"||t.tool==="websearch"||t.tool==="search_web")&&f){const D=Oj(p,s,{unstyled:!0});return b(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(t.tool==="codesearch"&&f)return b(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(fn,{content:p,variant:"tool"})}));if(t.tool==="skill"&&f)return b(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(fn,{content:p,variant:"tool"})}));if((t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch")&&h)return b(e.jsx(Gj,{diff:h,syntaxTheme:s,input:u}),{className:"p-1"});if(f&&p.trim()){if(t.tool==="read"){const D=Li(p,t.tool,d),j=D.split(`
183
- `),M=typeof u?.offset=="number"?u.offset:0,C=typeof u?.limit=="number"?u.limit:void 0,P=E=>E.trim().startsWith("(");return b(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:j.map((E,I)=>{const A=P(E),T=M+I+1,R=!A&&(C===void 0||I<C);return e.jsxs("div",{className:F("typography-code font-mono flex w-full min-w-0",A&&"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:R?T:""}),e.jsx("div",{className:"flex-1 min-w-0",children:A?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(Ir,{style:s,language:vl(D,t.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:E})})]},I)})}),{className:"p-1"})}return b(e.jsx(Ir,{style:s,language:vl(Li(p,t.tool,d),t.tool,u),PreTag:"div",customStyle:{...aa.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Li(p,t.tool,d)}),{className:"p-1"})}return b(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:F("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",l?"before:bottom-[-0.6rem]":"before:bottom-0"),children:t.tool==="todowrite"||t.tool==="todoread"||t.tool==="question"?N():e.jsxs(e.Fragment,{children:[w&&y?e.jsx("div",{className:"my-1",children:b(e.jsx(Kj,{content:g,filePath:x,displayPath:v??"New file"}))}):w?e.jsx("div",{className:"my-1",children:b(e.jsx(qj,{content:g,syntaxTheme:s,filePath:x,displayPath:v??"New file"}))}):k?e.jsx("div",{className:"my-1",children:b(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:S}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,t.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:"}),N()]}),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})]})]})})},Sl=({part:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:l=!1,hasNextTool:c=!1})=>{const d=t.state,u=gt(T=>T.currentDirectory),m=t.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",h=d.status==="error",x=i.useRef(r);i.useEffect(()=>{!f&&!m||x.current!==r&&(x.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const g=d,w=g.metadata,y=g.input,v=g.time,S=i.useRef({}),k=i.useRef(t.id);if(k.current!==t.id&&(k.current=t.id,S.current={}),m){if(typeof v?.start=="number"){const T=S.current.start;(typeof T!="number"||v.start<T)&&(S.current.start=v.start)}typeof v?.end=="number"&&(S.current.end=v.end)}const b=m?S.current.start??v?.start:v?.start,N=m?S.current.end??v?.end:v?.end,D=i.useMemo(()=>{if(!m)return;const T=w;return typeof T?.sessionId=="string"?T.sessionId:void 0},[m,w]),j=i.useMemo(()=>{if(!m)return[];const T=w?.summary;return Array.isArray(T)?T.filter(R=>typeof R=="object"&&R!==null):[]},[m,w]),M=i.useRef(j.length);i.useEffect(()=>{m&&M.current!==j.length&&(M.current=j.length,a?.("structural"))},[m,a,j.length]);const C=t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch"?Bj(w):null,P=Hj(t,d,o,u),E=Ql(t.tool).displayName,I=i.useContext(Yl),A=T=>{if(m||!I?.editor){s(t.id);return}let R;if((t.tool==="edit"||t.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(t.tool))&&(R=y?.filePath||y?.file_path||y?.path||w?.filePath||w?.file_path||w?.path),typeof R=="string"){T.stopPropagation();let K=R;R.startsWith("/")||(K=u.endsWith("/")?u+R:u+"/"+R),I.editor.openFile(K)}else s(t.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:F("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:A,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:T=>{T.stopPropagation(),s(t.id)},children:[e.jsx("div",{className:F("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:rp(t.tool)}),e.jsx("div",{className:F("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(Ht,{className:"h-3.5 w-3.5"}):e.jsx(zs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:E})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[P&&e.jsx("span",{className:F("truncate",o&&"max-w-[120px]"),children:P}),C&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",C.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",C.removed]})]}),typeof b=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx($j,{start:b,end:typeof N=="number"?N:void 0,active:!!(m&&p&&typeof N!="number")})})]})]}),m&&(j.length>0||p||f||D)?e.jsx(Vj,{entries:j,isExpanded:r,hasPrevTool:l,hasNextTool:c,output:typeof g.output=="string"?g.output:void 0,sessionId:D}):null,!m&&r?e.jsx(Qj,{part:t,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:l,hasNextTool:c}):null]})},Yj={thinking:{label:"Thinking",Icon:Sr},justification:{label:"Justification",Icon:Pl}},Xj=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
184
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
185
- `).trim(),Jj=t=>{if(!t)return"";const r=t.trim(),s=r.indexOf(`
186
- `),n=r.indexOf("."),o=[s>=0?s:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},np=({text:t,variant:r,onContentChange:s,blockId:n})=>{const[o,a]=i.useState(!1),l=i.useMemo(()=>Jj(t),[t]),{label:c,Icon:d}=Yj[r];return i.useEffect(()=>{t.trim().length!==0&&s?.("structural")},[s,o,t]),!t||t.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:F("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:F("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:F("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(Ht,{className:"h-3.5 w-3.5"}):e.jsx(zs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),l&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:l})})]}),o&&e.jsx("div",{className:F("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(ht,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:t})})]})},Zj=({part:t,onContentChange:r,messageId:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>Xj(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(np,{text:a,variant:"thinking",onContentChange:r,blockId:t.id||`${s}-reasoning`}):null},e0=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
187
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
188
- `).trim(),t0=({part:t,messageId:r,onContentChange:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>e0(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(np,{text:a,variant:"justification",onContentChange:s,blockId:t.id||`${r}-justification`}):null},s0=i.memo(t0),eu=6,r0=t=>[...t].sort((r,s)=>{const n=typeof r.endedAt=="number"?r.endedAt:void 0,o=typeof s.endedAt=="number"?s.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),tu=t=>{const r={},s=t.filter(n=>n.kind==="tool");return s.forEach((n,o)=>{const a=n.part.id;a&&(r[a]={hasPrev:o>0,hasNext:o<s.length-1})}),r},n0=({parts:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:l,onContentChange:c,diffStats:d})=>{const u=i.useRef(r),[m,f]=i.useState(!1),[p,h]=i.useState(0);i.useEffect(()=>{if(u.current===r)return;const D=u.current===!1;if(u.current=r,c?.("structural"),r&&D){h(M=>M+1),f(!0);const j=setTimeout(()=>f(!1),50);return()=>clearTimeout(j)}else f(!1)},[r,c]);const x=i.useMemo(()=>r0(t),[t]),g=tu(x),w=i.useMemo(()=>x.slice(-eu),[x]),y=i.useMemo(()=>{const D=new Set;return w.forEach(j=>{j.part.id&&D.add(j.part.id)}),D},[w]),v=i.useMemo(()=>tu(w),[w]),S=Math.max(0,x.length-eu);if(x.length===0)return null;const k=r?x:w,b=r?g:v,N=S>0;return e.jsx(cr,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:F("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl",N&&"cursor-pointer"),onClick:N?s:void 0,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:N?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(Wn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:F("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(Ht,{className:"h-3.5 w-3.5"}):e.jsx(zs,{className:"h-3.5 w-3.5"})})]}):e.jsx(Wn,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),d&&(d.additions>0||d.deletions>0)&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,d.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,d.deletions)]})]})})]}),e.jsxs("div",{className:F("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:[!r&&S>0&&e.jsxs("div",{className:"typography-micro text-muted-foreground/70 mb-1 cursor-pointer hover:text-muted-foreground",onClick:s,children:["+",S," more..."]}),k.map((D,j)=>{const M=D.part.id||`group-part-${j}`,C=b[M],P=`${M}-exp${p}`,E=D.part.id?y.has(D.part.id):!1,I=m&&E;switch(D.kind){case"tool":return e.jsx(cr,{skipAnimation:I,children:e.jsx(Sl,{part:D.part,isExpanded:a.has(M),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:C?.hasPrev??!1,hasNextTool:C?.hasNext??!1})},P);case"reasoning":return e.jsx(cr,{skipAnimation:I,children:e.jsx(Zj,{part:D.part,messageId:D.messageId,onContentChange:c})},P);case"justification":return e.jsx(cr,{skipAnimation:I,children:e.jsx(s0,{part:D.part,messageId:D.messageId,onContentChange:c})},P);default:return null}})]})]})})},o0=i.memo(n0),op=t=>{const r=t,s=r.text;return typeof s=="string"?s:r.content||r.value||""},ap=t=>{if(t.type!=="text")return!1;const r=op(t);return!r||r.trim().length===0},a0=(t,r={})=>{const{includeReasoning:s=!0}=r,n=t.some(o=>!o.synthetic);return t.filter(o=>!!o.synthetic&&n||!s&&o.type==="reasoning"?!1:!(o.type==="patch"))},i0=t=>{const r=t/1e3;if(r<60)return`${r.toFixed(1)}s`;const s=Math.floor(r/60),n=Math.round(r%60);return`${s}m ${n}s`},l0=new Set(["task"]),Jo=t=>typeof t=="string"&&l0.has(t.toLowerCase()),c0=({messageId:t,parts:r,isMobile:s,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:l,onShowPopup:c,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=i.useState(!1),h=i.useRef(null),x=i.useMemo(()=>r.filter(j=>j.type!=="text"?!1:!ap(j)),[r]),g=d?.token;let w=!1;const y=!!a,v=!!l,S=!!(n??s),k=!!o,b=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),N=i.useCallback(()=>{!S||!y||!k||typeof window>"u"||(b(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[y,b,k,S]);i.useEffect(()=>{k||(p(!1),b())},[b,k]);const D=i.useCallback(j=>{!a||!k||(j.stopPropagation(),j.preventDefault(),a(),S&&N())},[k,S,a,N]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&y&&k?N:void 0,children:[e.jsx("div",{className:"leading-relaxed overflow-hidden text-foreground/90 text-base",children:x.map((j,M)=>{let C;return d&&g&&!w&&op(j).includes(g)&&(C=d,w=!0),e.jsx(cr,{children:e.jsx(wj,{part:j,messageId:t,isMobile:s,agentMention:C})},`user-text-${M}`)})}),e.jsx(zf,{files:r,onShowPopup:c}),y&&k||u||m?e.jsxs("div",{className:F("mt-1 flex items-center justify-end gap-2"),children:[u&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{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:j=>j.stopPropagation(),onClick:j=>{j.stopPropagation(),u()},children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{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:j=>j.stopPropagation(),onClick:j=>{j.stopPropagation(),m()},children:e.jsx(Kt,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Fork from here"})]}),y&&k&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":f||v?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:j=>j.stopPropagation(),onClick:D,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(Qt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Js,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Copy message"})]})]}):null]})},d0=({messageId:t,parts:r,isMessageCompleted:s,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:l,hasTouchInput:c,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:h,hasTextContent:x=!1,onCopyMessage:g,copiedMessage:w=!1,onAuxiliaryContentComplete:y,showReasoningTraces:v=!1,turnGroupingContext:S,errorMessage:k})=>{const[b,N]=i.useState(!1),D=i.useRef(null),j=!!g,M=!!w,C=!!(c??l),P=!s,E=i.useMemo(()=>r.filter(Ve=>!ap(Ve)).filter(Ve=>Ve.type!=="compaction"),[r]),I=i.useMemo(()=>E.filter(Ve=>Ve.type==="tool"),[E]),A=i.useMemo(()=>E.filter(Ve=>Ve.type==="text"),[E]),T=fe(Ve=>Ve.createSessionFromAssistantMessage),R=ke(Ve=>Ve.openMultiRunLauncherWithPrompt),K=S?.isLastAssistantInTurn??!1,Y=n==="stop",_=I.length>0,J=i.useMemo(()=>I.some(Ve=>{const vt=(Ve.state??{})?.status;return vt==="pending"||vt==="running"||vt==="started"}),[I]),q=i.useCallback(Ve=>{const dt=Ve.state??{},vt=dt?.status;if(vt==="pending"||vt==="running"||vt==="started")return!1;const ut=dt?.time??{},At=typeof ut?.end=="number"?ut.end:void 0,Rt=typeof ut?.start=="number"?ut.start:void 0;return!(typeof At!="number"||typeof Rt=="number"&&At<Rt)},[]),Q=i.useMemo(()=>I.length===0?!0:J?!1:I.every(Ve=>q(Ve)),[I,J,q]),z=i.useMemo(()=>E.filter(Ve=>Ve.type==="reasoning"),[E]),H=i.useMemo(()=>z.length===0?!0:z.every(Ve=>typeof Ve.time?.end=="number"),[z]),W=typeof n!="string",B=z.length>0&&_&&(J||W||!Q),se=P||_&&(J||W||!Q),L=P||B,ae=_||z.length>0,O=A.length===0,V=ae&&O&&!se&&!L&&Q&&H,X=i.useRef(!1),re=i.useRef(!1);i.useEffect(()=>{re.current=!1},[t]),i.useEffect(()=>{if(!V){X.current=!1;return}X.current||(X.current=!0,y?.())},[V,y]),i.useEffect(()=>{if(P){re.current=!1;return}if(_){re.current=!1;return}z.length!==0&&(L||!H||re.current||(re.current=!0,h?.("structural")))},[P,_,h,H,z.length,L]);const me=!!x&&!P,G=i.useCallback(()=>{D.current!==null&&typeof window<"u"&&(window.clearTimeout(D.current),D.current=null)},[]),he=i.useCallback(()=>{!C||!j||!me||typeof window>"u"||(G(),N(!0),D.current=window.setTimeout(()=>{N(!1),D.current=null},1800))},[j,G,me,C]);i.useEffect(()=>{me||(N(!1),G())},[G,me]);const ye=i.useCallback(Ve=>{!g||!me||(Ve.stopPropagation(),Ve.preventDefault(),g(),C&&he())},[me,C,g,he]),ge=i.useCallback(Ve=>{Ve.stopPropagation(),Ve.preventDefault(),T&&T(t)},[T,t]),$e=i.useCallback(Ve=>{Ve.stopPropagation(),Ve.preventDefault();const dt=Gl(A);if(!dt.trim())return;const vt=`${vb}
189
-
190
- ${dt}`;R(vt)},[A,R]);i.useEffect(()=>()=>{G()},[G]);const ee=i.useMemo(()=>{const Ve={},dt=I.filter(vt=>Jo(vt.tool)||se?!1:q(vt));return dt.forEach((vt,ut)=>{Ve[vt.id]={hasPrev:ut>0,hasNext:ut<dt.length-1}}),Ve},[I,se,q]),Z=i.useMemo(()=>S?.activityParts??[],[S]),ie=i.useMemo(()=>S?Z.filter(Ve=>Ve.messageId===t):[],[Z,t,S]),Me=i.useMemo(()=>S?S.activityGroupSegments.filter(Ve=>Ve.anchorMessageId===t):[],[t,S]),oe=i.useMemo(()=>{const Ve=new Map;return ie.forEach(dt=>{Ve.set(dt.part,dt)}),Ve},[ie]),xe=i.useMemo(()=>S?(v?Z:Z.filter(dt=>dt.kind==="tool")).filter(dt=>{if(dt.kind!=="tool")return!0;const vt=dt.part.tool;return!Jo(vt)}):[],[Z,v,S]),[pe,je]=i.useState(!1);i.useEffect(()=>{if(!S)return;const Ve=S.activityGroupSegments.some(dt=>dt.afterToolPartId!==null);(xe.length>1||Ve&&xe.length>0)&&je(!0)},[S,xe.length]);const ce=!!(S&&pe),Ye=!!(S&&ce&&xe.length>0&&Me.length>0),mt=i.useMemo(()=>I.filter(Ve=>Jo(Ve.tool)),[I]),Ie=i.useMemo(()=>{const Ve=[],dt=ut=>{!S||!Ye||Me.filter(At=>(At.afterToolPartId??null)===ut).forEach(At=>{const Rt=v?At.parts:At.parts.filter(as=>as.kind==="tool");Rt.length!==0&&Ve.push(e.jsx(o0,{parts:Rt,isExpanded:S.isGroupExpanded,onToggle:S.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:S.diffStats},`progressive-group-${At.id}`))})};dt(null),mt.forEach(ut=>{Ve.push(e.jsx(cr,{children:e.jsx(Sl,{part:ut,isExpanded:d.has(ut.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${ut.id}`)),dt(ut.id)});const vt=[];return E.forEach((ut,At)=>{const Rt=oe.get(ut);if(!Rt||!S)return;let as=null,Ct=null;if(!ce){if(Rt.kind==="tool"){const $t=ut;if(Jo($t.tool))return;const Gt=$t.state?.time,Dt=q($t);if(!(!se&&Dt))return;const St=ee[$t.id];Ct=e.jsx(cr,{children:e.jsx(Sl,{part:$t,isExpanded:d.has($t.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:St?.hasPrev??!1,hasNextTool:St?.hasNext??!1})},`tool-${$t.id}`),as=Dt&&typeof Gt?.end=="number"?Gt.end:null}Ct&&vt.push({part:ut,index:At,endTime:as,element:Ct})}}),vt.sort((ut,At)=>ut.endTime===null&&At.endTime===null?ut.index-At.index:ut.endTime===null?1:At.endTime===null?-1:ut.endTime-At.endTime),vt.forEach(({element:ut})=>{Ve.push(ut)}),Ve},[oe,Me,d,l,q,h,m,u,se,ce,v,a,ee,S,E,mt,Ye]),le=S?.turnId,Xe=fe(Ve=>Ve.currentSessionId),Ne=kt(Ve=>{if(!le||!Xe)return;const dt=Ve.messages.get(Xe);if(!dt)return;const vt=dt.find(Rt=>Rt.info?.id===le);if(!vt)return;const At=vt.info.summary?.body;return typeof At=="string"&&At.trim().length>0?At:void 0}),Se=typeof S?.summaryBody=="string"&&S.summaryBody.trim().length>0?S.summaryBody:Ne,qe=i.useRef(void 0);Se&&Se.trim().length>0&&(qe.current=Se);const rt=i.useRef(le);rt.current!==le&&(rt.current=le,qe.current=void 0);const We=qe.current,_e=S?.isLastAssistantInTurn&&We&&We.trim().length>0,Ke=!!k,xt=K&&x&&(Y||!!k),[nt,Pt]=i.useState(!1),Tt=i.useMemo(()=>{if(!K||!Y)return;const Ve=S?.userMessageCreatedAt;if(!(typeof Ve!="number"||typeof o!="number")&&!(o<=Ve))return i0(o-Ve)},[K,Y,S?.userMessageCreatedAt,o]),_t=e.jsxs(e.Fragment,{children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{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:Ve=>Ve.stopPropagation(),onClick:ge,children:e.jsx(Cg,{className:"h-4 w-4"})})}),e.jsx(it,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{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:Ve=>Ve.stopPropagation(),onClick:$e,children:e.jsx(Pf,{className:"h-4 w-4"})})}),e.jsx(it,{sideOffset:6,children:"Start new multi-run from this answer"})]}),g&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":b||M?"true":void 0,className:F("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",!me&&"opacity-50"),disabled:!me,"aria-label":"Copy message text","aria-hidden":!me,onPointerDown:Ve=>Ve.stopPropagation(),onClick:ye,onFocus:()=>{me&&N(!0)},onBlur:()=>{M||N(!1)},children:M?e.jsx(Qt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Js,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:F("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:C&&j&&me?he:void 0,children:e.jsxs("div",{children:[e.jsxs("div",{className:"leading-relaxed overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ie,Ke&&e.jsx(cr,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(fn,{content:k??""})})},"assistant-error"),_e&&e.jsx(cr,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Pt(!0),onMouseLeave:()=>Pt(!1),children:[e.jsx(fn,{content:We}),xt&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Tt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(kc,{className:"h-3.5 w-3.5"}),Tt]}):e.jsx("span",{}),e.jsx("div",{className:F("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",nt&&"opacity-100 pointer-events-auto"),children:_t})]})]})},"summary-body")]}),e.jsx(zf,{files:r,onShowPopup:m}),!_e&&xt&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Tt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(kc,{className:"h-3.5 w-3.5"}),Tt]}):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:_t})]})]})})},u0=({isUser:t,...r})=>t?e.jsx(c0,{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(d0,{...r}),su=i.memo(u0),Oi=t=>{const r=t,s=r?.clientRole,n=r?.role;return r?.userMessageMarker===!0||s==="user"||n==="user"||r?.origin==="user"||r?.source==="user"?{role:"user",isUser:!0}:{role:s||n||"assistant",isUser:!1}},m0=i.lazy(()=>Ss(()=>import("./ToolOutputDialog-C4dfK_Ah.js"),__vite__mapDeps([2,0,1,3,4]))),f0=new Set(["task","edit","multiedit","write","bash"]),ru=t=>typeof t=="string"&&f0.has(t.toLowerCase());function _i(t){const r=i.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&t!==void 0&&t!==null&&(r.current={hasValue:!0,value:t}),r.current.hasValue?r.current.value:t}const hr=(t,r)=>{if(typeof t=="object"&&t!==null)return t[r]},p0=({message:t,previousMessage:r,nextMessage:s,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:l,hasTouchInput:c}=Yt(),{currentTheme:d}=en(),u=i.useRef(null),m=fe(Rl(te=>({lifecyclePhase:te.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const Ce=t.info.sessionID??te.currentSessionId??null;return Ce?(te.streamingMessageIds.get(Ce)??null)===t.info.id:!1})(),currentSessionId:te.currentSessionId,getCurrentAgent:te.getCurrentAgent,getSessionAgentSelection:te.getSessionAgentSelection,getAgentModelForSession:te.getAgentModelForSession,getSessionModelSelection:te.getSessionModelSelection}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getCurrentAgent:x,getSessionAgentSelection:g,getAgentModelForSession:w,getSessionModelSelection:y}=m,v=et(te=>te.providers),S=ke(te=>te.showReasoningTraces),k=ke(te=>te.toolCallExpansion);i.useEffect(()=>{h&&Ur.getInstance().recordSessionStart(h)},[h]);const[b,N]=i.useState(null),[D,j]=i.useState(!1),[M,C]=i.useState(new Set),[P,E]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{C(new Set)},[t.info.id,k]);const A=i.useMemo(()=>Oi(t.info),[t.info]).isUser,T=i.useMemo(()=>A?t.parts.map(te=>te.type==="compaction"?{type:"text",text:"/compact"}:te):t.parts,[A,t.parts]),R=i.useMemo(()=>{if(A||!r)return null;const te=hr(r.info,"clientRole"),Ce=hr(r.info,"role");if((typeof te=="string"?te:typeof Ce=="string"?Ce:void 0)!=="user")return null;const He=hr(r.info,"mode"),wt=hr(r.info,"providerID"),Nt=hr(r.info,"modelID"),Xt=hr(r.info,"variant"),we=typeof He=="string"&&He.trim().length>0?He:void 0,ze=typeof wt=="string"&&wt.trim().length>0?wt:void 0,tt=typeof Nt=="string"&&Nt.trim().length>0?Nt:void 0,Ee=typeof Xt=="string"&&Xt.trim().length>0?Xt:void 0;return!we&&!ze&&!tt&&!Ee?null:{agentName:we,providerId:ze,modelId:tt,variant:Ee}},[A,r]),K=i.useMemo(()=>{if(A)return;const te=hr(t.info,"mode");if(typeof te=="string"&&te.trim().length>0)return te;if(R?.agentName)return R.agentName;const Ce=t.info.sessionID;if(!Ce)return;const De=x(Ce);return De||(g(Ce)??void 0)},[A,t.info,R,x,g]),Y=t.info.sessionID,_=A?null:hr(t.info,"providerID"),J=A?null:hr(t.info,"modelID"),q=i.useMemo(()=>{if(A||!Y)return null;if(R?.providerId&&R?.modelId)return{providerId:R.providerId,modelId:R.modelId};if(K){const Ce=w(Y,K);if(Ce?.providerId&&Ce?.modelId)return Ce}const te=y(Y);return te?.providerId&&te?.modelId?te:null},[A,Y,K,R,w,y]),Q=i.useMemo(()=>A?null:typeof _=="string"&&_.trim().length>0?_:q?.providerId??null,[A,_,q]),z=i.useMemo(()=>A?null:typeof J=="string"&&J.trim().length>0?J:q?.modelId??null,[A,J,q]),H=i.useMemo(()=>{if(!A&&Q&&z&&v.length>0){const te=v.find(Ce=>Ce.id===Q);if(te?.models&&Array.isArray(te.models)){const He=te.models.find(wt=>wt.id===z)?.name;return typeof He=="string"?He:void 0}}},[A,Q,z,v]),W=i.useMemo(()=>{if(A||!Q||!z)return!1;const te=v.find(He=>He.id===Q);if(!te?.models||!Array.isArray(te.models))return!1;const De=te.models.find(He=>He.id===z)?.variants;return!!(De&&Object.keys(De).length>0)},[A,z,Q,v]),B=_i(K),se=_i(Q??void 0),L=_i(H),ae=B??void 0,O=se??null,V=L??void 0,X=i.useMemo(()=>{const te=t.info.time;return typeof te?.completed=="number"?te.completed:null},[t.info.time]),re=i.useMemo(()=>A?!0:!!(X&&X>0),[A,X]),me=i.useMemo(()=>{const te=t.info.finish;return typeof te=="string"?te:void 0},[t.info]),G=i.useMemo(()=>a0(T,{includeReasoning:S}),[T,S]),he=i.useMemo(()=>A||re?G:[],[A,re,G]),ye=i.useMemo(()=>A?[]:G.filter(te=>te.type==="text"),[A,G]),ge=i.useMemo(()=>A?[]:G.filter(Ce=>Ce.type==="tool"),[A,G]),$e=i.useMemo(()=>{if(k==="collapsed"||k==="activity")return M;const te=new Set;for(const De of ge){const He=De.tool;De.id&&ru(He)&&te.add(De.id)}if(a?.isFirstAssistantInTurn)for(const De of a.activityParts){if(De.kind!=="tool")continue;const He=De.part;He.id&&ru(He.tool)&&te.add(He.id)}const Ce=new Set(te);for(const De of M)Ce.has(De)?Ce.delete(De):Ce.add(De);return Ce},[M,k,ge,a]),ee=i.useMemo(()=>{if(!A)return;const te=t.parts.find(wt=>wt.type==="agent");if(!te)return;const Ce=te,De=typeof Ce.name=="string"?Ce.name:void 0;if(!De)return;const He=Ce.source&&typeof Ce.source.value=="string"&&Ce.source.value.trim().length>0?Ce.source.value:`#${De}`;return{name:De,token:He}},[A,t.parts]),Z=typeof me!="string",ie=i.useMemo(()=>A?!1:ye.length===0||ge.length===0?Z:!0,[ye.length,ge.length,Z,A]),Me=d?.metadata.variant,oe=i.useMemo(()=>Me?Me==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[Me]),xe=i.useMemo(()=>d?fc(d):oe?pj:hj,[d,oe]),pe=i.useMemo(()=>A?!1:Ur.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,A]),je=i.useRef(!1),ce=i.useMemo(()=>r?Oi(r.info):null,[r]),Ye=i.useMemo(()=>s?Oi(s.info):null,[s]),mt=i.useMemo(()=>A||!Ye?!1:!Ye.isUser&&Ye.role==="assistant",[A,Ye]),Ie=i.useMemo(()=>re?"completed":f||(p?"streaming":"completed"),[re,f,p]),le=i.useMemo(()=>{if(A)return!0;const te=a?.headerMessageId;if(te){if(t.info.id===te){if(Ie==="completed")return!0;const De=Ie==="streaming"||Ie==="cooldown",He=je.current;return De&&!He&&(je.current=!0),He||De}return!1}return ce?ce.isUser:!0},[A,ce,a,Ie,t.info]),Xe=i.useCallback(te=>{navigator.clipboard.writeText(te),N(te),setTimeout(()=>N(null),2e3)},[]),Ne=a?.turnId,Se=kt(te=>{if(!Ne)return;const Ce=t.info.sessionID;if(!Ce)return;const De=te.messages.get(Ce);if(!De)return;const He=De.find(Xt=>Xt.info?.id===Ne);if(!He)return;const Nt=He.info.summary?.body;return typeof Nt=="string"&&Nt.trim().length>0?Nt:void 0}),qe=kt(te=>{if(!Ne)return;const Ce=t.info.sessionID;if(!Ce)return;const De=te.messages.get(Ce);if(!De)return;const He=De.find(Nt=>Nt.info?.id===Ne);if(!He)return;const wt=He.info.variant;return typeof wt=="string"&&wt.trim().length>0?wt:void 0}),rt=A?void 0:qe??R?.variant,We=!A&&W?rt??"Default":void 0,_e=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:Se,Ke=i.useRef(void 0);_e&&_e.trim().length>0&&(Ke.current=_e);const xt=i.useRef(Ne);xt.current!==Ne&&(xt.current=Ne,Ke.current=void 0);const nt=Ke.current,Pt=i.useMemo(()=>{if(A)return;const te=t.info?.error;if(!te)return;const Ce=typeof te.data?.message=="string"?te.data.message:void 0,De=typeof te.message=="string"?te.message:void 0,He=typeof te.name=="string"?te.name:void 0,wt=Ce||De||He;if(wt)return`Opencode failed to send message with error:
191
- \`${wt}\``},[A,t.info]),Tt=i.useMemo(()=>A?he.filter(De=>De.type==="text").map(De=>(De.text||De.content||"").trim()).filter(De=>De.length>0).join(`
192
- `).replace(/\n\s*\n+/g,`
193
- `):Pt&&Pt.trim().length>0?Pt:nt&&nt.trim().length>0?nt:Gl(he),[Pt,nt,he,A]),_t=Tt.length>0,Ve=i.useCallback(async te=>{if(!te)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(te),!0}catch{}if(typeof document>"u")return!1;const Ce=document.createElement("textarea");Ce.value=te,Ce.setAttribute("readonly",""),Ce.style.position="fixed",Ce.style.top="-1000px",Ce.style.left="-1000px",document.body.appendChild(Ce),Ce.select(),Ce.setSelectionRange(0,Ce.value.length);const De=document.execCommand("copy");return document.body.removeChild(Ce),De},[]),dt=i.useCallback(async()=>{await Ve(Tt)&&(j(!0),setTimeout(()=>j(!1),2e3))},[Ve,Tt]),vt=fe(te=>te.revertToMessage),ut=fe(te=>te.forkFromMessage),At=i.useCallback(()=>{!Y||!t.info.id||vt(Y,t.info.id)},[Y,t.info.id,vt]),Rt=i.useCallback(()=>{!Y||!t.info.id||ut(Y,t.info.id)},[Y,t.info.id,ut]),as=i.useCallback(te=>{C(Ce=>{const De=new Set(Ce);return De.has(te)?De.delete(te):De.add(te),De})},[]),Ct=o??null,$t=i.useRef(!1),Mt=i.useRef(!1),Gt=i.useRef(!1),Dt=i.useRef(!1),qt=i.useRef(!1);i.useEffect(()=>{Mt.current=!1,Gt.current=!1,Dt.current=!1,qt.current=!1,$t.current=!1},[t.info.id]);const St=i.useCallback(()=>{A||$t.current||($t.current=!0,n?.("structural"))},[A,n]),Lt=i.useCallback(te=>{te.image&&E(te)},[]),be=i.useCallback(te=>{E(Ce=>({...Ce,open:te}))},[]),Pe=!!hr(t.info,"animationSettled"),Oe=Ie==="streaming",st=i.useMemo(()=>A?!1:G.some(te=>te.type==="reasoning"),[A,G]),ne=pe&&!Pe&&!Oe,Ae=!A&&pe&&ye.length>0&&!ie;return i.useEffect(()=>{if(Ct?.onStreamingCandidate){if(!Ae){Gt.current&&(st&&Ct?.onReasoningBlock?Ct.onReasoningBlock():Ct?.onReservationCancelled&&Ct.onReservationCancelled(),Gt.current=!1);return}qt.current||(qt.current=!0,Ct.onStreamingCandidate(),Gt.current=!0)}},[Ct,Ae,st]),i.useEffect(()=>{Ct?.onAnimationStart&&ne&&(Dt.current||(Ct.onAnimationStart(),Dt.current=!0))},[Ct,ne]),i.useEffect(()=>{if(A)return;const te=Ct?.onAnimatedHeightChange;if(!te||!(ne||Ae))return;const De=u.current;if(!De)return;if(typeof window>"u"||typeof ResizeObserver>"u"){te(De.getBoundingClientRect().height);return}let He=null;const wt=Xt=>{if(typeof window>"u"){te(Xt);return}He!==null&&window.cancelAnimationFrame(He),He=window.requestAnimationFrame(()=>{te(Xt)})},Nt=new ResizeObserver(Xt=>{const we=Xt[0];we&&wt(we.contentRect.height)});return Nt.observe(De),wt(De.getBoundingClientRect().height),()=>{He!==null&&(window.cancelAnimationFrame(He),He=null),Nt.disconnect()}},[ne,A,Ct,Ae]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("group w-full",le?"pt-6":"pt-0",A?"pb-4":mt?"pb-0":"pb-8"),"data-message-id":t.info.id,ref:u,children:e.jsx("div",{className:"chat-message-column relative",children:A?e.jsx(cr,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-primary/10 dark:bg-primary/10 px-5 py-3 shadow-sm border border-primary/5",children:e.jsx(su,{messageId:t.info.id,parts:G,isUser:A,isMessageCompleted:re,messageFinish:me,syntaxTheme:xe,isMobile:l,hasTouchInput:c,copiedCode:b,onCopyCode:Xe,expandedTools:M,onToggleTool:as,onShowPopup:Lt,streamPhase:Ie,allowAnimation:ne,onContentChange:n,shouldShowHeader:!1,hasTextContent:_t,onCopyMessage:dt,copiedMessage:D,showReasoningTraces:S,onAuxiliaryContentComplete:St,agentMention:ee,onRevert:At,onFork:A?Rt:void 0,errorMessage:Pt})})})}):e.jsxs("div",{className:"relative pl-4 ml-1",children:[le&&e.jsx(xj,{isUser:A,providerID:O,agentName:ae,modelName:V,variant:We,isDarkTheme:oe}),e.jsx(su,{messageId:t.info.id,parts:G,isUser:A,isMessageCompleted:re,messageFinish:me,messageCompletedAt:X??void 0,syntaxTheme:xe,isMobile:l,hasTouchInput:c,copiedCode:b,onCopyCode:Xe,expandedTools:$e,onToggleTool:as,onShowPopup:Lt,streamPhase:Ie,allowAnimation:ne,onContentChange:n,shouldShowHeader:le,hasTextContent:_t,onCopyMessage:dt,copiedMessage:D,onAuxiliaryContentComplete:St,showReasoningTraces:S,agentMention:ee,turnGroupingContext:a,errorMessage:Pt})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(m0,{popup:P,onOpenChange:be,syntaxTheme:xe,isMobile:l})})]})},h0=i.memo(p0),g0=({diff:t,syntaxTheme:r,filePath:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:sp(t).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||s?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,l)=>e.jsxs("div",{className:F("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(Ir,{style:r,language:_r(s||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},l))})]},o))}),x0=({content:t,syntaxTheme:r,filePath:s})=>{const n=t.split(`
194
- `),o=_r(s??"")||"text",a=s?.split("/").pop()||"New file",l=Math.max(n.length,1),c=l===1?"line 1":`lines 1-${l}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${c})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ir,{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))})]})},y0=t=>{const r="h-3 w-3",s=t.toLowerCase();return s==="edit"||s==="multiedit"||s==="str_replace"||s==="str_replace_based_edit_tool"?e.jsx(Dr,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(hm,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?e.jsx(Qr,{className:r}):s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?e.jsx(tl,{className:r}):e.jsx(Va,{className:r})},b0=t=>{const r=t.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":t},w0=({permission:t,onResponse:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:l}=fe(),{currentTheme:c}=en(),d=i.useMemo(()=>fc(c),[c]),u=async y=>{n(!0);try{await l(t.sessionID,t.id,y),a(!0),r?.(y)}catch{}finally{n(!1)}};if(o)return null;const m=t.permission||"unknown",f=m.toLowerCase(),p=(y,v="")=>{const S=t.metadata[y];return typeof S=="string"?S:typeof S=="number"?String(S):v},h=y=>{const v=t.metadata[y];return typeof v=="number"?v:void 0},x=y=>!!t.metadata[y],g=b0(m),w=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),k=p("description"),b=p("cwd")||p("working_directory")||p("directory")||p("path"),N=h("timeout");return e.jsxs(e.Fragment,{children:[k&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:k}),b&&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:b})]}),N&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",N,"ms"]}),S&&e.jsx("div",{children:e.jsx(Ir,{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:S})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),k=p("changes")||p("diff"),b=x("replace_all")||x("replaceAll");return e.jsxs(e.Fragment,{children:[b&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),k&&e.jsx(ht,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(g0,{diff:k,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),k=p("content")||p("text")||p("data");return k?e.jsx(ht,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(x0,{content:k,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),k=p("method")||"GET",b=t.metadata.headers&&typeof t.metadata.headers=="object"?t.metadata.headers:void 0,N=p("body")||p("data")||p("payload"),D=h("timeout"),j=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[S&&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:k}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:S})]})]}),b&&Object.keys(b).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(ht,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Ir,{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(b,null,2)})})]}),N&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(ht,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Ir,{language:typeof N=="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 N=="object"?JSON.stringify(N,null,2):String(N)})})]}),(D||j)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[D&&e.jsxs("span",{children:["Timeout: ",D,"ms"]}),D&&j&&e.jsx("span",{children:" • "}),j&&e.jsxs("span",{children:["Response format: ",j]})]})]})}const y=p("command")||p("content")||p("action")||p("operation"),v=p("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(ht,{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(y)})})]}),Object.keys(t.metadata).length>0&&!y&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(ht,{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(t.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(hn,{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:[y0(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:g})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[t.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:t.patterns.join(", ")})]}),w()]}),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:s,className:F("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:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Qt,{className:"h-3 w-3"}),"Allow Once"]}),t.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:F("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:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(jr,{className:"h-3 w-3"}),(()=>{const y=t.always||t.metadata.always||[];if(y.length===0)return"Always Allow";const S=y.slice(0,2).join(", ");return y.length>2?`Always: ${S}...`:`Always: ${S}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:s,className:F("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:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(jr,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:s,className:F("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:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(es,{className:"h-3 w-3"}),"Deny"]}),s&&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"})})]})]})})})},$i="summary",v0=({question:t})=>{const{respondToQuestion:r,rejectQuestion:s}=fe(),[n,o]=i.useState("0"),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState({}),[f,p]=i.useState({}),[h,x]=i.useState({}),g=i.useMemo(()=>t.questions??[],[t.questions]),w=n===$i,y=w?-1:Math.max(0,Math.min(g.length-1,Number(n)||0)),v=w?null:g[y];i.useEffect(()=>{o("0"),m({}),p({}),x({}),d(!1)},[t.id]);const S=i.useMemo(()=>{const A=g.map((T,R)=>({value:String(R),label:T.header?.trim()||`Q${R+1}`}));return g.length>1&&A.push({value:$i,label:"Summary"}),A},[g]),k=i.useCallback(A=>{if(!!f[A])return(h[A]??"").trim()||"(no answer)";const R=u[A]??[];return R.length>0?R.join(", "):"(no answer)"},[f,h,u]),b=!!v?.multiple,N=u[y]??[],D=!!f[y],j=i.useMemo(()=>{if(g.length===0)return!1;for(let A=0;A<g.length;A+=1){if(!!f[A]){if(!(h[A]??"").trim())return!1;continue}if((u[A]??[]).length===0)return!1}return!0},[f,h,g.length,u]),M=i.useCallback(()=>{const A=[];for(let T=0;T<g.length;T+=1){if(!!f[T]){const K=(h[T]??"").trim();A.push(K?[K]:[]);continue}A.push(u[T]??[])}return A},[f,h,g.length,u]),C=i.useCallback(A=>{v&&(p(T=>({...T,[y]:!1})),m(T=>{const R=T[y]??[];if(b){const Y=R.includes(A)?R.filter(_=>_!==A):[...R,A];return{...T,[y]:Y}}return{...T,[y]:[A]}}))},[y,v,b]),P=i.useCallback(()=>{p(A=>({...A,[y]:!0})),m(A=>({...A,[y]:[]}))},[y]),E=i.useCallback(async()=>{if(j){l(!0);try{const A=M();await r(t.sessionID,t.id,A),d(!0)}catch{}finally{l(!1)}}},[M,t.id,t.sessionID,j,r]),I=i.useCallback(async()=>{l(!0);try{await s(t.sessionID,t.id),d(!0)}catch{}finally{l(!1)}},[t.id,t.sessionID,s]);return c||g.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(hn,{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:[S.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:S.map(A=>{const T=n===A.value,R=A.value===$i;return e.jsxs("button",{type:"button",onClick:()=>o(A.value),className:F("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",T?"bg-muted/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-muted/20"),children:[R?e.jsx(gm,{className:"h-3 w-3"}):null,A.label]},A.value)})}):null,w?e.jsx("div",{className:"space-y-2",children:g.map((A,T)=>{const R=k(T),K=R!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(T)),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:A.header||`Question ${T+1}`}),e.jsx("div",{className:F("typography-meta",K?"text-foreground":"text-muted-foreground/50 italic"),children:R})]},T)})}):v?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:v.question}),b?e.jsx("div",{className:"typography-micro text-muted-foreground mb-1.5",children:"Select multiple"}):null,e.jsxs("div",{className:"space-y-0.5",children:[v.options.map((A,T)=>{const R=N.includes(A.label),K=/\(recommended\)/i.test(A.label);return e.jsx("button",{type:"button",onClick:()=>C(A.label),disabled:a,className:F("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",R?"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:R?e.jsx(Mg,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(sl,{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:F("typography-meta break-all",R?"text-foreground font-medium":"text-foreground/80"),children:A.label}),K?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),A.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:A.description}):null]})]})},`${T}:${A.label}`)}),e.jsx("button",{type:"button",onClick:P,disabled:a,className:F("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(Xn,{className:F("h-3.5 w-3.5",D?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:F("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:A=>{if(A){A.style.height="auto";const T=20,R=T*2,K=T*4;A.style.height=`${Math.min(Math.max(A.scrollHeight,R),K)}px`}},value:h[y]??"",onChange:A=>{const T=A.target;T.style.height="auto";const R=20,K=R*2,Y=R*4;T.style.height=`${Math.min(Math.max(T.scrollHeight,K),Y)}px`,x(_=>({..._,[y]:T.value}))},placeholder:"Your answer",disabled:a,rows:2,className:"w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none overflow-hidden",autoFocus:!0})}):null]})]}):null]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{type:"button",onClick:E,disabled:a||!j,className:F("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(Qt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:I,disabled:a,className:F("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(es,{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]})]})})})},j0=new Set(["task"]),nu=t=>typeof t=="string"&&j0.has(t.toLowerCase()),S0=t=>{const r=[];let s=null;return t.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(s={turnId:n.info.id,userMessage:n,assistantMessages:[]},r.push(s)):o==="assistant"&&s&&s.assistantMessages.push(n)}),r},N0=t=>{for(const r of t.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}}},k0=t=>{const r=N0(t);let s;const o=t.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let y=0,v=0,S=0;o.forEach(k=>{if(!k)return;const b=typeof k.additions=="number"?k.additions:0,N=typeof k.deletions=="number"?k.deletions:0;(b!==0||N!==0)&&(S+=1),y+=b,v+=N}),S>0&&(s={additions:y,deletions:v,files:S})}let a=!1,l=!1;t.assistantMessages.forEach(y=>{y.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(l=!0)})});const c=[];let d=0;t.assistantMessages.forEach(y=>{const v=y.info.id;y.info.finish,y.parts.forEach(S=>{const k=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-activity-${d++}`;if(S.type==="tool"){const N=S.state?.time,D=typeof N?.end=="number"?N.end:void 0;c.push({id:k,turnId:t.turnId,messageId:v,kind:"tool",part:S,endedAt:D});return}if(S.type==="reasoning"){const b=S.text??S.content;if(typeof b!="string"||b.trim().length===0)return;const N=S.time,D=typeof N?.end=="number"?N.end:void 0;c.push({id:k,turnId:t.turnId,messageId:v,kind:"reasoning",part:S,endedAt:D});return}})});const u=[],m=new WeakMap;c.forEach(y=>{m.set(y.part,y)});const f=new Map,p=[],h=new Map;let x=null;t.assistantMessages.forEach(y=>{const v=y.info.id;y.parts.forEach(S=>{if(S.type==="tool"){const N=S.tool;if(nu(N)){const D=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-task-${p.length+1}`;f.has(D)||(f.set(D,v),p.push(D)),x=D;return}}const k=m.get(S);if(!k)return;if(k.kind==="tool"){const N=k.part.tool;if(nu(N))return}const b=h.get(x)??[];b.push(k),h.set(x,b)})});const g=y=>{if(y.length===0)return;const v=new Map;y.forEach(b=>{v.set(b.messageId,(v.get(b.messageId)??0)+1)});let S,k=0;for(const b of t.assistantMessages){const N=v.get(b.info.id)??0;if(N>0&&!S&&(S=b.info.id),k+=N,k>=2)return b.info.id}return S};return[null,...p].forEach(y=>{const v=h.get(y)??[];if(v.length===0)return;const S=y===null?g(v):f.get(y);S&&u.push({id:`${t.turnId}:${S}:${y??"start"}`,anchorMessageId:S,afterToolPartId:y,parts:v})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:l,summaryBody:r,diffStats:s}},C0=t=>{const{isWorking:r}=uc(),s=i.useMemo(()=>S0(t),[t]),n=i.useMemo(()=>s.length===0?null:s[s.length-1].turnId,[s]),o=i.useMemo(()=>{const x=new Map;return s.forEach(g=>{x.set(g.userMessage.info.id,g),g.assistantMessages.forEach(w=>{x.set(w.info.id,g)})}),x},[s]),a=i.useMemo(()=>{const x=new Map;return s.forEach(g=>{x.set(g.turnId,k0(g))}),x},[s]),[l,c]=i.useState(()=>new Map),d=ke(x=>x.toolCallExpansion),u=d==="activity"||d==="detailed";i.useEffect(()=>{c(new Map)},[d]);const m=i.useCallback(x=>{const g=l.get(x);return g||{isExpanded:u}},[l,u]),f=i.useCallback(x=>{c(g=>{const w=new Map(g),y=w.get(x)??{isExpanded:u};return w.set(x,{isExpanded:!y.isExpanded}),w})},[u]),p=i.useCallback(x=>o.get(x),[o]),h=i.useCallback(x=>{const g=o.get(x);if(!g||!g.assistantMessages.some(K=>K.info.id===x))return;const y=a.get(g.turnId),v=y?.activityParts??[],S=y?.activityGroupSegments??[],k=!!y?.hasTools,b=!!y?.hasReasoning,N=y?.summaryBody,D=y?.diffStats,j=g.assistantMessages[0]?.info.id,M=x===j,C=g.assistantMessages[g.assistantMessages.length-1]?.info.id,P=x===C,E=j,I=m(g.turnId),A=r&&n===g.turnId,T=g.userMessage.info.time,R=typeof T?.created=="number"?T.created:void 0;return{turnId:g.turnId,isFirstAssistantInTurn:M,isLastAssistantInTurn:P,summaryBody:N,activityParts:v,activityGroupSegments:S,headerMessageId:E,hasTools:k,hasReasoning:b,diffStats:D,userMessageCreatedAt:R,isWorking:A,isGroupExpanded:I.isExpanded,toggleGroup:()=>f(g.turnId)}},[m,n,o,r,f,a]);return{turns:s,getTurnForMessage:p,getContextForMessage:h}},M0=({messages:t,permissions:r,questions:s,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:l,onLoadOlder:c,scrollToBottom:d})=>{i.useEffect(()=>{r.length===0&&s.length===0||n("permission")},[r,s,n]);const u=i.useMemo(()=>{const f=new Set;return t.filter(p=>{const h=p.info?.id;if(typeof h=="string"){if(f.has(h))return!1;f.add(h)}return!0}).map(p=>{const h=sj(p.parts);return h===p.parts?p:{...p,parts:h}})},[t]),{getContextForMessage:m}=C0(u);return e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:l?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:c,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((f,p)=>e.jsx(h0,{message:f,previousMessage:p>0?u[p-1]:void 0,nextMessage:p<u.length-1?u[p+1]:void 0,onContentChange:n,animationHandlers:o(f.info.id),scrollToBottom:d,turnGroupingContext:m(f.info.id)},f.info.id))}),(s.length>0||r.length>0)&&e.jsxs("div",{children:[s.map(f=>e.jsx(v0,{question:f},f.id)),r.map(f=>e.jsx(w0,{permission:f},f.id))]}),e.jsx("div",{className:"flex-shrink-0",style:{height:"10vh"},"aria-hidden":"true"})]})},D0=i.memo(M0);function A0(...t){return r=>{t.forEach(s=>{typeof s=="function"?s(r):s&&typeof s=="object"&&(s.current=r)})}}const ip=i.forwardRef(({orientation:t="vertical",offset:r=72,size:s=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:l,className:c,children:d,...u},m)=>{const f=i.useRef(null),p=i.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const x=i.useMemo(()=>{const v={...l};return v["--scroll-shadow-size"]=`${s}px`,v},[s,l]),g=i.useCallback((v,S,k,b,N)=>{const D=`${b}${N.charAt(0).toUpperCase()}${N.slice(1)}Scroll`;S&&k?(v.dataset[D]="true",v.removeAttribute(`data-${b}-scroll`),v.removeAttribute(`data-${N}-scroll`)):(v.dataset[`${b}Scroll`]=String(S),v.dataset[`${N}Scroll`]=String(k),v.removeAttribute(`data-${b}-${N}-scroll`))},[]),w=i.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{v.removeAttribute(`data-${S}-scroll`)})},[]),y=i.useCallback(()=>{const v=f.current;if(!v)return;if(!n){w(v);return}const S=t==="vertical"?v.scrollTop>r:v.scrollLeft>r;let k=t==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&t==="vertical"&&(k=!1),g(v,S,k,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const b=S&&k?"both":S?t==="vertical"?"top":"left":k?t==="vertical"?"bottom":"right":"none";b!==p.current&&(p.current=b,a?.(b))},[w,o,n,r,a,t,g]);return i.useEffect(()=>{const v=f.current;if(!v)return;const S=()=>y(),k=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null,b=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return y(),v.addEventListener("scroll",S,{passive:!0}),k?.observe(v),b?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",S),k?.disconnect(),b?.disconnect()}},[y]),e.jsx("div",{...u,ref:A0(f,m),className:c,"data-orientation":t,"data-scroll-shadow":h??!0,style:x,children:d})});ip.displayName="ScrollShadow";const E0=160,I0=({containerRef:t})=>{const[r,s]=i.useState(!0),n=i.useRef(!0),o=i.useRef(!1),a=i.useRef(null),l=i.useRef(null),c=i.useRef(0),d=i.useRef(0),u=i.useRef(!1),m=i.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,l.current=null,u.current=!1},[]),f=i.useCallback(k=>{const b=t.current;if(!b){m();return}l.current===null&&(l.current=k),u.current&&(d.current=b.scrollHeight-b.clientHeight);const N=Math.min(1,(k-l.current)/E0),D=1-Math.pow(1-N,3),j=c.current,M=d.current,C=j+(M-j)*D;if(b.scrollTop=C,N<1){a.current=window.requestAnimationFrame(f);return}b.scrollTop=M,m(),n.current&&(n.current=!1,s(!1))},[m,t,s]),p=i.useCallback((k,b)=>{const N=t.current;if(!N)return;const D=Math.max(0,k),j=b?.instant??!1,M=b?.followBottom??!1;if(o.current=!1,typeof window>"u"||j){m(),N.scrollTop=D;const P=D<=1;n.current!==P&&(n.current=P,s(P));return}if(M&&u.current&&a.current!==null)return;if(m(),Math.abs(D-N.scrollTop)<=.5){N.scrollTop=D;const P=D<=1;n.current!==P&&(n.current=P,s(P));return}c.current=N.scrollTop,d.current=D,l.current=null,u.current=M,a.current=window.requestAnimationFrame(f)},[m,t,f,s]),h=i.useCallback(()=>{o.current=!0},[]),x=i.useCallback(()=>{o.current=!0},[]),g=i.useCallback(()=>o.current,[]),w=i.useCallback(()=>t.current?.scrollTop??0,[t]),y=i.useCallback(()=>t.current?.scrollHeight??0,[t]),v=i.useCallback(()=>t.current?.clientHeight??0,[t]),S=i.useCallback(()=>{const k=t.current;if(!k)return;o.current&&a.current!==null&&m();const b=k.scrollTop<=1;n.current!==b&&(n.current=b,s(b))},[m,t]);return i.useEffect(()=>{const k=t.current;if(k)return k.addEventListener("wheel",x,{passive:!0}),k.addEventListener("touchstart",x,{passive:!0}),()=>{k.removeEventListener("wheel",x),k.removeEventListener("touchstart",x)}},[t,x]),i.useEffect(()=>()=>{m()},[m]),i.useMemo(()=>({handleScroll:S,scrollToPosition:p,forceManualMode:h,isAtTop:r,isManualOverrideActive:g,getScrollTop:w,getScrollHeight:y,getClientHeight:v}),[S,p,h,r,g,w,y,v])},P0=typeof window<"u"?i.useLayoutEffect:i.useEffect,T0=200,F0=250,R0=.1,L0=({currentSessionId:t,sessionMessages:r,updateViewportAnchor:s,isSyncing:n,isMobile:o})=>{const a=i.useRef(null),l=I0({containerRef:a}),c=i.useCallback(()=>{const I=a.current;if(!I||I.clientHeight<=0)return 0;const A=I.clientHeight*R0;return Math.max(24,Math.min(200,A))},[]),[d,u]=i.useState(!1),[m,f]=i.useState(!0),p=i.useRef(null),h=i.useRef(t??null),x=i.useRef(0),g=i.useRef(0),w=i.useRef(!0),y=i.useRef(0);i.useEffect(()=>{h.current=t??null},[t]);const v=i.useCallback(()=>{x.current=Date.now()+T0},[]),S=i.useCallback(()=>{const I=a.current;return I?I.scrollHeight-I.scrollTop-I.clientHeight:0},[]),k=i.useCallback(I=>{w.current!==I&&(w.current=I,f(I))},[]),b=i.useCallback(I=>{const A=a.current;if(!A)return;const T=A.scrollHeight-A.clientHeight;v(),l.scrollToPosition(Math.max(0,T),I)},[v,l]),N=i.useCallback(()=>{const I=a.current;if(!I){u(!1);return}if(!(I.scrollHeight>I.clientHeight)){u(!1);return}const T=S();u(T>c())},[S,c]),D=i.useCallback((I,A)=>{a.current&&(v(),l.scrollToPosition(Math.max(0,I),A))},[v,l]),j=i.useCallback(I=>{a.current&&(k(!0),b(I),u(!1))},[b,k]),M=i.useCallback(I=>{const A=a.current;if(!A||!t)return;const T=Date.now(),R=T<x.current,K=T-g.current<=F0;l.handleScroll(),N();const Y=A.scrollTop;I?.isTrusted&&!R&&K&&Y<y.current&&w.current&&k(!1),w.current||S()<=c()&&k(!0),y.current=Y;const{scrollTop:_,scrollHeight:J,clientHeight:q}=A,Q=(_+q/2)/Math.max(J,1),z=Math.floor(Q*r.length);s(t,z)},[t,S,c,l,r.length,k,N,s]);i.useEffect(()=>{const I=a.current;if(!I)return;const A=()=>{g.current=Date.now()};return I.addEventListener("scroll",M,{passive:!0}),I.addEventListener("wheel",A,{passive:!0}),I.addEventListener("touchmove",A,{passive:!0}),()=>{I.removeEventListener("scroll",M),I.removeEventListener("wheel",A),I.removeEventListener("touchmove",A)}},[M]),P0(()=>{if(!t||t===p.current)return;p.current=t,Ur.getInstance().recordSessionStart(t),k(!0),u(!1),a.current&&(v(),b({instant:!0}))},[t,v,b,k]),i.useEffect(()=>{if(!w.current||n||!a.current)return;S()>c()&&(v(),b({instant:!0}))},[S,c,n,v,b,r]),i.useEffect(()=>{const I=a.current;if(!I||typeof ResizeObserver>"u")return;const A=new ResizeObserver(()=>{N(),w.current&&S()>c()&&b({instant:!0})});A.observe(I);const T=new MutationObserver(()=>{w.current&&S()>c()&&b({instant:!0})});return T.observe(I,{childList:!0,subtree:!0}),()=>{A.disconnect(),T.disconnect()}},[S,c,b,N]),i.useEffect(()=>{if(typeof window>"u"){N();return}const I=window.requestAnimationFrame(()=>{N()});return()=>{window.cancelAnimationFrame(I)}},[t,r.length,N]);const C=i.useRef(new Map),P=i.useCallback(()=>{N(),w.current&&S()>c()&&b({instant:!0})},[S,c,b,N]),E=i.useCallback(I=>{const A=C.current.get(I);if(A)return A;const T={onChunk:()=>{N(),w.current&&S()>c()&&b({instant:!0})},onComplete:()=>{N()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{N(),w.current&&S()>c()&&b({instant:!0})},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return C.current.set(I,T),T},[S,c,b,N]);return{scrollRef:a,handleMessageContentChange:P,getAnimationHandlers:E,showScrollButton:d,scrollToBottom:j,scrollToPosition:D,isPinned:m}};function O0(t){const s=Date.now()-t,n=Math.floor(s/1e3),o=Math.floor(n/60),a=Math.floor(o/60),l=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:l<7?`${l}d ago`:new Date(t).toLocaleDateString()}const _0=({open:t,onOpenChange:r,onScrollToMessage:s})=>{const n=fe(g=>g.currentSessionId),o=kt(g=>n?g.messages.get(n)||[]:[]),a=fe(g=>g.revertToMessage),l=fe(g=>g.forkFromMessage),c=fe(g=>g.loadSessions),[d,u]=i.useState(null),[m,f]=i.useState(""),p=i.useMemo(()=>o.filter(w=>w.info.role==="user").reverse(),[o]),h=i.useMemo(()=>{if(!m.trim())return p;const g=m.toLowerCase();return p.filter(w=>ou(w.parts).toLowerCase().includes(g))},[p,m]),x=async g=>{if(n){u(g);try{await l(n,g),await c(),r(!1)}finally{u(null)}}};return n?e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{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(jr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(ks,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Ws,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(bt,{placeholder:"Search messages...",value:m,onChange:g=>f(g.target.value),className:"pl-9 w-full"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:h.length===0?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No messages found":"No messages in this session yet"}):h.map(g=>{const w=ou(g.parts),y=g.info.time.created,v=O0(y),S=p.length-p.indexOf(g);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",onClick:()=>{s?.(g.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[S,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[w||"[No text content]",w&&w.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:v}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{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 k=>{k.stopPropagation(),await a(n,g.info.id),r(!1)},children:e.jsx(Hn,{className:"h-4 w-4"})})}),e.jsx(it,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{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:k=>{k.stopPropagation(),x(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(Ft,{className:"h-4 w-4 animate-spin"}):e.jsx(Kt,{className:"h-4 w-4"})})}),e.jsx(it,{sideOffset:6,children:"Fork from here"})]})]})]})]},g.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(Hn,{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(Kt,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function ou(t){const r=t.find(s=>s.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const lp=()=>{const{currentSessionId:t,messages:r,permissions:s,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:l,loadMoreMessages:c,updateViewportAnchor:d,sessionMemoryState:u,openNewSessionDraft:m,isSyncing:f,messageStreamStates:p,trimToViewportWindow:h,sessionActivityPhase:x,newSessionDraft:g}=fe(),{isTimelineDialogOpen:w,setTimelineDialogOpen:y}=ke(),v=i.useMemo(()=>t?o.get(t)??null:null,[t,o]),{isMobile:S}=Yt(),k=!!g?.open;i.useEffect(()=>{!t&&!k&&m()},[t,k,m]);const b=i.useMemo(()=>t?r.get(t)||[]:[],[t,r]),N=i.useMemo(()=>t?s.get(t)||[]:[],[t,s]),D=i.useMemo(()=>t?n.get(t)||[]:[],[t,n]);i.useMemo(()=>[...N,...D],[N,D]);const{scrollRef:j,handleMessageContentChange:M,getAnimationHandlers:C,showScrollButton:P,scrollToBottom:E,scrollToPosition:I,isPinned:A}=L0({currentSessionId:t,sessionMessages:b,updateViewportAnchor:d,isSyncing:f,isMobile:S}),R=!!i.useMemo(()=>t?u.get(t)??null:null,[t,u])?.hasMoreAbove,[K,Y]=i.useState(!1);i.useEffect(()=>{Y(!1)},[t]);const _=i.useCallback(async()=>{if(!t||K)return;const q=j.current,Q=q?.scrollHeight??null,z=q?.scrollTop??null;Y(!0);try{if(await c(t,"up"),q&&Q!==null&&z!==null){const H=q.scrollHeight-Q;I(z+H,{instant:!0})}}finally{Y(!1)}},[t,K,c,j,I]),J=i.useCallback(q=>{const Q=j.current;if(!Q)return;const z=Q.querySelector(`[data-message-id="${q}"]`);if(z){const H=Q.getBoundingClientRect(),se=z.getBoundingClientRect().top-H.top+Q.scrollTop-50;Q.scrollTo({top:se,behavior:"smooth"})}},[j]);return i.useEffect(()=>{if(!t||(r.has(t)?r.get(t)??[]:[]).length>0)return;(async()=>{try{await l(t)}finally{const H=x?.get(t)??"idle";(H==="busy"||H==="cooldown")&&A||(typeof window>"u"?E():window.requestAnimationFrame(()=>{E()}))}})()},[t,A,l,r,E,x]),!t&&!k?e.jsx("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(Ri,{})}):!t&&k?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Ri,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Xo,{scrollToBottom:E})})]}):t?a&&b.length===0&&!v&&!r.has(t)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:S?{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-message-column space-y-4",children:[1,2,3].map(Q=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Fi,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Fi,{className:"h-4 w-24"}),e.jsx(Fi,{className:"h-20 w-full"})]})]},Q))})}),e.jsx(Xo,{scrollToBottom:E})]}):b.length===0&&!v?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Ri,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Xo,{scrollToBottom:E})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:S?{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(ip,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:j,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",children:e.jsx("div",{className:"relative z-0 min-h-full",children:e.jsx(D0,{messages:b,permissions:N,questions:D,onMessageContentChange:M,getAnimationHandlers:C,hasMoreAbove:R,isLoadingOlder:K,onLoadOlder:_,scrollToBottom:E})})}),e.jsx(ql,{containerRef:j})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[P&&b.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>E({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(Jn,{className:"h-4 w-4"})})}),e.jsx(Xo,{scrollToBottom:E})]}),e.jsx(_0,{open:w,onOpenChange:y,onScrollToMessage:J})]}):null};class cp extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){this.setState({error:r,errorInfo:s})}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(sc,{className:"w-full max-w-md",children:[e.jsx(kf,{className:"text-center",children:e.jsxs(Cf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Dg,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Mf,{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(ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ts,{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 bo=()=>{const t=fe(r=>r.currentSessionId);return e.jsx(cp,{sessionId:t||void 0,children:e.jsx(lp,{})})},au=12,$0=[{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"}],B0=({isActive:t,burstKey:r=0,className:s,durationMs:n=900,bursts:o=$0,onComplete:a})=>{const l=Re.useRef(!1);Re.useEffect(()=>{!t&&l.current&&a?.(),t&&(l.current=!0)},[t,a]);const c=Re.useMemo(()=>Array.from({length:au},(d,u)=>{const m=Math.PI*2*u/au;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return t?e.jsx("div",{className:F("fireworks-overlay pointer-events-none",s),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:c.map((m,f)=>{const p=m.x*d.radius,h=m.y*d.radius,x={"--translate-x":`${p}px`,"--translate-y":`${h}px`,"--particle-delay":`${m.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:x},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},z0=({durationMs:t=3400}={})=>{const[r,s]=Re.useState({isActive:!1,cycle:0}),n=Re.useRef(null),o=Re.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Re.useCallback(()=>{o(),s(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Re.useCallback(()=>{o(),s(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{s(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},t)},[o,t]);return Re.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:l,dismissFireworks:a}},dp=i.createContext(void 0),iu=({children:t})=>{const{isActive:r,burstKey:s,triggerFireworks:n,dismissFireworks:o}=z0(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(dp.Provider,{value:a,children:[t,e.jsx(B0,{isActive:r,burstKey:s})]})},H0=()=>{const t=i.useContext(dp);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Kn=os()(us(Vs((t,r)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:s=>{t({selectedProfileId:s})},loadProfiles:async()=>{t({isLoading:!0});const s=r().profiles;try{const n=await sb();return t({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),t({profiles:s,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const s=await ib();if(s&&s.userName&&s.userEmail){const n={id:"global",name:"Global Identity",userName:s.userName,userEmail:s.userEmail,authType:s.sshCommand?"ssh":void 0,sshKey:s.sshCommand?s.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};t({globalIdentity:n})}else t({globalIdentity:null});return!0}catch(s){return console.error("Failed to load global git identity:",s),t({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const s=await ab();return t({discoveredCredentials:s}),!0}catch(s){return console.error("Failed to discover git credentials:",s),t({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const s=n=>{if(typeof n!="string")return null;const o=n.trim();return o.length>0?o:null};try{let n=null;if(ds()){const o=await Lr();n=s(o?.defaultGitIdentityId)}else{const o=Ms()?.settings;if(o)try{const l=(await o.load())?.settings||{};n=s(l.defaultGitIdentityId)}catch{}if(n===null)try{const a=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(a.ok){const l=await a.json().catch(()=>null);n=s(l?.defaultGitIdentityId)}}catch{}}return t({defaultGitIdentityId:n}),!0}catch(n){return console.error("Failed to load default git identity setting:",n),!1}},setDefaultGitIdentityId:async s=>{try{const n=typeof s=="string"?s.trim():"",o=n.length>0?n:"";return await fs({defaultGitIdentityId:o}),t({defaultGitIdentityId:o.length>0?o:null}),!0}catch(n){return console.error("Failed to save default git identity setting:",n),!1}},createProfile:async s=>{try{const n={...s,id:s.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:s.color||"keyword",icon:s.icon||"branch"};return await rb(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(s,n)=>{try{const o=r().profiles.find(l=>l.id===s);if(!o)throw new Error("Profile not found");const a={...o,...n};return await nb(s,a),await r().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async s=>{try{return await ob(s),r().selectedProfileId===s&&t({selectedProfileId:null}),await r().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:s=>{const{profiles:n,globalIdentity:o}=r();return s==="global"?o||void 0:n.find(a=>a.id===s)},getUnimportedCredentials:()=>{const{profiles:s,discoveredCredentials:n}=r();return n.filter(o=>!s.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Gs(()=>ws()),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Kn);const W0=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),U0=({currentBranch:t,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:o,onCreate:a,disabled:l=!1})=>{const[c,d]=i.useState(!1),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(""),[g,w]=i.useState(!1),y=i.useRef(null),v=i.useMemo(()=>W0(h),[h]),S=i.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(C=>C.toLowerCase().includes(M)):r},[u,r]),k=i.useMemo(()=>{const M=u.toLowerCase();return M?s.filter(C=>C.toLowerCase().includes(M)):s},[u,s]),b=M=>{if(M===t){d(!1);return}o(M),d(!1),m("")},N=()=>{p(!0),setTimeout(()=>y.current?.focus(),50)},D=async()=>{if(!(!v||g)){w(!0);try{await a(v),x(""),p(!1),d(!1)}finally{w(!1)}}},j=()=>{x(""),p(!1)};return i.useEffect(()=>{c||(m(""),p(!1),x(""))},[c]),e.jsxs(ts,{open:c,onOpenChange:d,children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:l,children:[e.jsx(Kt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:t||"Detached HEAD"}),e.jsx(Ht,{className:"size-4 opacity-60"})]})})}),e.jsxs(it,{sideOffset:8,children:["Switch branch (",r.length," local · ",s.length," remote)"]})]}),e.jsx(rs,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(rc,{className:"h-full min-h-0",children:[e.jsx(nc,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(oc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(ac,{children:"No branches found."}),e.jsx(un,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:y,placeholder:"New branch name",value:h,onChange:M=>x(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),D()):M.key==="Escape"&&(M.preventDefault(),j())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:D,disabled:!v||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(cs,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:j,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(es,{className:"size-4"})})]}):e.jsxs(js,{onSelect:N,children:[e.jsx(cs,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Ra,{}),e.jsxs(un,{heading:"Local branches",children:[S.map(M=>e.jsxs(js,{onSelect:()=>b(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"]})]}),t===M&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${M}`)),S.length===0&&e.jsx(js,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Ra,{}),e.jsxs(un,{heading:"Remote branches",children:[k.map(M=>e.jsx(js,{onSelect:()=>b(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),k.length===0&&e.jsx(js,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},V0=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),G0=({currentBranch:t,onRename:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(t||""),[l,c]=i.useState(!1),d=i.useRef(null),u=()=>{!t||!r||(a(t),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!t||!r||!o.trim())return;const h=V0(o);if(h===t){n(!1);return}c(!0);try{await r(t,h),n(!1),a("")}finally{c(!1)}},f=()=>{n(!1),a("")},p=h=>{h.key==="Enter"?(h.preventDefault(),m()):h.key==="Escape"&&(h.preventDefault(),f())};return s?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:h=>{h.preventDefault(),m()},children:[e.jsx(Kt,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:h=>a(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:l?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Qt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(es,{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(Kt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate typography-ui-label font-normal text-foreground",children:t||"Detached HEAD"})]}),r&&t&&e.jsx(ve,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(Xn,{className:"size-4"})})]})},q0=({syncAction:t,onFetch:r,onPull:s,onPush:n,disabled:o})=>{const a=o||t!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[t==="fetch"?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Gr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(it,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[t==="pull"?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Jn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(it,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[t==="push"?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Do,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(it,{sideOffset:8,children:"Push changes"})]})]})},K0={branch:Kt,briefcase:_l,house:Ol,graduation:Ll,code:Ys,heart:ym,user:Xs},Q0={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 up(t){return t&&Q0[t]||"var(--primary)"}const lu=({icon:t,className:r,colorToken:s})=>{const n=K0[t??"branch"]??Xs;return e.jsx(n,{className:r,style:{color:up(s)}})},Y0=({activeProfile:t,identities:r,onSelect:s,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(ts,{children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ss,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:up(t?.color)},disabled:o,children:[n?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(lu,{icon:t?.icon,colorToken:t?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:t?.name||"No identity"}),e.jsx(Ht,{className:"size-4 opacity-60"})]})})}),e.jsxs(it,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:t?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:t?.userEmail||"No email configured"})]})]}),e.jsx(rs,{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(jt,{onSelect:()=>s(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(lu,{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))})]})},X0=({status:t,localBranches:r,remoteBranches:s,branchInfo:n,syncAction:o,onFetch:a,onPull:l,onPush:c,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:h,isApplyingIdentity:x,isWorktreeMode:g})=>t?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[g?e.jsx(G0,{currentBranch:t.current,onRename:m}):e.jsx(U0,{currentBranch:t.current,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:d,onCreate:u}),(!!t.tracking||t.ahead>0||t.behind>0)&&e.jsxs(lt,{delayDuration:800,children:[e.jsx(ct,{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(Do,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.ahead})]}),!!t.tracking&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Jn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:t.behind})]})]})}),e.jsx(it,{sideOffset:8,children:t.tracking?`Upstream: ${t.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(q0,{syncAction:o,onFetch:a,onPull:l,onPush:c,disabled:!t}),e.jsx("div",{className:"flex-1"}),e.jsx(Y0,{activeProfile:f,identities:p,onSelect:h,isApplying:x})]}):null,J0=({behind:t,onPull:r,isPulling:s})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(Al,{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"}),t>0&&e.jsxs(ve,{variant:"outline",onClick:r,disabled:s,children:[s?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Jn,{className:"size-4"}),"Pull ",t," commit",t===1?"":"s"]})]}),mp={"?":{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"}},Z0=mp.M;function eS(t){const r=t.index?.trim(),s=t.working_dir?.trim();return r&&r!=="?"?r.charAt(0):s?s.charAt(0):r?.charAt(0)||s?.charAt(0)||"M"}function tS(t){const r=eS(t);return mp[r]??Z0}const sS=i.memo(function({file:r,checked:s,onToggle:n,onViewDiff:o,onRevert:a,isReverting:l,stats:c}){const d=Re.useMemo(()=>tS(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=Re.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=Re.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),x=Re.useCallback(g=>{g.preventDefault(),g.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:h,"aria-pressed":s,"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:s?e.jsx(xn,{className:"size-4 text-primary"}):e.jsx(yn,{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(lt,{delayDuration:200,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:x,disabled:l,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:l?e.jsx(Ft,{className:"size-3.5 animate-spin"}):e.jsx(Hn,{className:"size-3.5"})})}),e.jsx(it,{sideOffset:8,children:"Revert changes"})]})]})})}),rS=({changeEntries:t,selectedPaths:r,diffStats:s,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:l,onViewDiff:c,onRevertFile:d})=>{const u=r.size,m=t.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(ve,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(ve,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:l,disabled:u===0,children:"None"})]})]})]}),e.jsx(ht,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:t.map(f=>e.jsx(sS,{file:f,checked:r.has(f.path),stats:s?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>c(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function wn({className:t,variant:r,...s}){return e.jsx(ve,{variant:r,size:"sm",className:F("h-7 px-2 py-0",t),...s})}const Bi=38,cu=200,nS=({value:t,onChange:r,placeholder:s="Commit message",disabled:n=!1})=>{const o=i.useRef(null);return i.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${Bi}px`;const l=Math.min(Math.max(a.scrollHeight,Bi),cu);a.style.height=`${l}px`},[t]),e.jsx(Rs,{ref:o,value:t,onChange:a=>r(a.target.value),placeholder:s,rows:1,disabled:n,className:F("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:Bi,maxHeight:cu}})},oS=({highlights:t,onInsert:r,onClear:s})=>{if(t.length===0)return null;const n=()=>{r(),s()};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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(Jn,{className:"size-4"})})}),e.jsx(it,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:t.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},aS=({selectedCount:t,commitMessage:r,onCommitMessageChange:s,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:l,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f,gitmojiEnabled:p,onOpenGitmojiPicker:h})=>{const x=t>0,g=r.trim()&&x&&m===null;return e.jsxs(eo,{open:x,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:x?`${t} file${t===1?"":"s"} selected`:"No files selected"})]}),e.jsx(to,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(oS,{highlights:n,onInsert:o,onClear:a}),e.jsx(nS,{value:r,onChange:s,placeholder:"Commit message",disabled:m!==null}),p&&e.jsxs(ve,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[e.jsx(Ag,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ve,{variant:"outline",size:"sm",onClick:l,disabled:c||m!==null||t===0||f,type:"button",children:[c?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Tl,{className:"size-4 text-primary"}),"Generate"]}),e.jsx("div",{className:"flex-1"}),e.jsx(wn,{variant:"outline",onClick:d,disabled:!g||c,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Ft,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Al,{className:"size-4"}),"Commit"]})}),e.jsx(wn,{variant:"default",onClick:u,disabled:!g||c,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Ft,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Do,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function du(t){const r=new Date(t);return Number.isNaN(r.getTime())?t:r.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function iS(t){switch(t){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 lS=({entry:t,isExpanded:r,onToggle:s,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:s,className:F("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:t.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:t.author_name,children:t.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:du(t.date),children:du(t.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:t.hash.slice(0,8)}),e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:l=>{l.stopPropagation(),a(t.hash)},children:e.jsx(Js,{className:"size-3"})})}),e.jsx(it,{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(Ft,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(l=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:F("font-semibold w-3 text-center",iS(l.changeType)),children:l.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:l.path,children:l.path}),!l.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",l.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",l.deletions]})]}),l.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},l.path))})})]}),cS=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],dS=({log:t,isLogLoading:r,logMaxCount:s,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:l,loadingCommitHashes:c,onCopyHash:d})=>{const[u,m]=i.useState(!0);return t?e.jsxs(eo,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Io,{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(Os,{value:String(s),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(_s,{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(bn,{placeholder:"Commits"})}),e.jsx($s,{children:cS.map(f=>e.jsx(ns,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Wa,{className:"size-4 text-muted-foreground"}):e.jsx(Ht,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(to,{children:e.jsx(ht,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:t.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:t.all.map(f=>e.jsx(lS,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:l.get(f.hash)??[],isLoadingFiles:c.has(f.hash),onCopyHash:d},f.hash))})})})]}):null},uS=t=>{switch(t){case"success":return"bg-[color:var(--status-success)]";case"failure":return"bg-[color:var(--status-error)]";case"pending":return"bg-[color:var(--status-warning)]";default:return"bg-muted-foreground/40"}},uu=t=>t.replace(/^refs\/heads\//,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,r=>r.toUpperCase()),mu=async t=>{if(typeof window>"u")return;const r=window.opencodeDesktop;if(r?.openExternal)try{const s=await r.openExternal(t);if(s&&typeof s=="object"&&"success"in s&&s.success===!0)return}catch{}try{window.open(t,"_blank","noopener,noreferrer")}catch{}},mS=({directory:t,branch:r,baseBranch:s})=>{const{github:n}=Zs(),o=ke(B=>B.setSettingsDialogOpen),a=ke(B=>B.setSidebarSection),l=i.useCallback(()=>{a("settings"),o(!0)},[o,a]),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[f,p]=i.useState(null),[h,x]=i.useState(null),[g,w]=i.useState(()=>uu(r)),[y,v]=i.useState(""),[S,k]=i.useState(!1),[b,N]=i.useState("squash"),[D,j]=i.useState(!1),[M,C]=i.useState(!1),[P,E]=i.useState(!1),[I,A]=i.useState(!1),T=!!(t&&r&&s&&r!==s),R=i.useCallback(async()=>{if(T){if(!n?.prStatus){p(null),x("GitHub runtime API unavailable");return}m(!0),x(null);try{const B=await n.prStatus(t,r);p(B),B.connected===!1&&x(null)}catch(B){const se=B instanceof Error?B.message:String(B);x(se||"Failed to load PR status")}finally{m(!1)}}},[r,T,t,n]);i.useEffect(()=>{w(uu(r)),v(""),k(!1),R()},[r,R]);const K=i.useCallback(async()=>{if(!D&&t){j(!0);try{const B=await Jy(t,{base:s,head:r});B.title?.trim()&&w(B.title.trim()),B.body?.trim()&&v(B.body.trim()),U.success("PR description generated")}catch(B){const se=B instanceof Error?B.message:String(B);U.error("Failed to generate description",{description:se})}finally{j(!1)}}},[s,r,t,D]),Y=i.useCallback(async()=>{if(!n?.prCreate){U.error("GitHub runtime API unavailable");return}const B=g.trim();if(!B){U.error("Title is required");return}C(!0);try{const se=await n.prCreate({directory:t,title:B,head:r,base:s,...y.trim()?{body:y}:{},draft:S});U.success("PR created"),p(L=>L&&{...L,pr:se}),await R()}catch(se){const L=se instanceof Error?se.message:String(se);U.error("Failed to create PR",{description:L})}finally{C(!1)}},[s,y,r,t,S,n,R,g]),_=i.useCallback(async B=>{if(!n?.prMerge){U.error("GitHub runtime API unavailable");return}E(!0);try{const se=await n.prMerge({directory:t,number:B.number,method:b});se.merged?U.success("PR merged"):U.message("PR not merged",{description:se.message||"Not mergeable"}),await R()}catch(se){const L=se instanceof Error?se.message:String(se);U.error("Merge failed",{description:L}),B.url&&mu(B.url)}finally{E(!1)}},[t,n,b,R]),J=i.useCallback(async B=>{if(!n?.prReady){U.error("GitHub runtime API unavailable");return}A(!0);try{await n.prReady({directory:t,number:B.number}),U.success("Marked ready for review"),await R()}catch(se){const L=se instanceof Error?se.message:String(se);U.error("Failed to mark ready",{description:L}),B.url&&mu(B.url)}finally{A(!1)}},[t,n,R]);if(!T)return null;const q=f?.pr??null,Q=f?.repo?.url||null,z=f?.checks??null,H=!!f?.canMerge,W=!!f?.connected;return e.jsxs(eo,{open:c,onOpenChange:d,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Io,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Fl,{className:"size-4 text-muted-foreground"}),e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:"Pull Request"}),q?e.jsxs("span",{className:"typography-meta text-muted-foreground truncate",children:["#",q.number]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[u?e.jsx(Ft,{className:"size-4 animate-spin text-muted-foreground"}):null,z?e.jsxs("span",{className:"inline-flex items-center gap-2 typography-micro text-muted-foreground",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${uS(z.state)}`}),z.total>0?`${z.success}/${z.total} checks`:`${z.state} checks`]}):null]})]}),e.jsx(to,{children:e.jsx("div",{className:"border-t border-border/40",children:e.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[W?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:"GitHub not connected. Connect your GitHub account in settings."}),e.jsx(ve,{variant:"outline",size:"sm",onClick:l,className:"w-fit",children:"Open settings"})]}),h?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"PR status unavailable"}),e.jsx("div",{className:"typography-meta text-muted-foreground break-words",children:h}),Q?e.jsx(ve,{variant:"outline",size:"sm",asChild:!0,className:"w-fit",children:e.jsxs("a",{href:Q,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(dr,{className:"size-4"}),"Open Repo"]})}):null]}):null,q?e.jsx("div",{className:"flex flex-col gap-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground truncate",children:q.title}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[q.state,q.draft?" (draft)":"",q.mergeable===!1?" · not mergeable":"",typeof q.mergeableState=="string"&&q.mergeableState?` · ${q.mergeableState}`:""]}),H&&q.draft?e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Draft PRs must be marked ready before merge."}):null,H?null:e.jsx("div",{className:"typography-micro text-muted-foreground",children:"No merge permission; use Open in GitHub."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:q.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(dr,{className:"size-4"}),"Open"]})}),H&&q.draft&&q.state==="open"?e.jsxs(ve,{variant:"outline",size:"sm",onClick:()=>J(q),disabled:I||P,children:[I?e.jsx(Ft,{className:"size-4 animate-spin"}):null,"Ready"]}):null,H?e.jsxs(e.Fragment,{children:[e.jsxs("select",{className:"h-8 rounded-md border border-border bg-background px-2 typography-meta",value:b,onChange:B=>N(B.target.value),disabled:P||q.state!=="open",children:[e.jsx("option",{value:"squash",children:"Squash"}),e.jsx("option",{value:"merge",children:"Merge"}),e.jsx("option",{value:"rebase",children:"Rebase"})]}),e.jsxs(ve,{size:"sm",onClick:()=>_(q),disabled:P||I||q.state!=="open"||q.draft,children:[P?e.jsx(Ft,{className:"size-4 animate-spin"}):null,"Merge"]})]}):null]})]})}):e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Create PR"}),e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[r," → ",s]})]}),Q?e.jsx(ve,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:Q,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(dr,{className:"size-4"}),"Repo"]})}):null]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Title"}),e.jsx(bt,{value:g,onChange:B=>w(B.target.value),placeholder:"PR title"})]}),e.jsxs("label",{className:"space-y-1",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Description"}),e.jsx(Rs,{value:y,onChange:B=>v(B.target.value),className:"min-h-[110px] bg-background/80",placeholder:"What changed and why"})]}),e.jsxs("div",{className:"flex items-center gap-2 cursor-pointer",role:"button",tabIndex:0,"aria-pressed":S,onClick:()=>k(B=>!B),onKeyDown:B=>{(B.key===" "||B.key==="Enter")&&(B.preventDefault(),k(se=>!se))},children:[e.jsx("button",{type:"button",onClick:B=>{B.preventDefault(),B.stopPropagation(),k(se=>!se)},"aria-label":"Toggle draft PR",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:S?e.jsx(xn,{className:"size-4 text-primary"}):e.jsx(yn,{className:"size-4"})}),e.jsx("span",{className:"typography-ui-label text-foreground select-none",children:"Draft"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ve,{variant:"outline",size:"sm",onClick:K,disabled:D||M,children:[D?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Tl,{className:"size-4 text-primary"}),"Generate"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(ve,{size:"sm",onClick:Y,disabled:M||!W,children:[M?e.jsx(Ft,{className:"size-4 animate-spin"}):null,"Create PR"]})]})]})]})})})]})},fp="gitmojiCache",fS=1e3*60*60*24*7,pp="1",pS="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",fu={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},hp=t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},hS=()=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(fp);if(!t)return null;const r=JSON.parse(t);return!r||r.version!==pp||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(hp),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},gS=t=>{if(!(typeof window>"u"))try{const r={gitmojis:t,fetchedAt:Date.now(),version:pp};localStorage.setItem(fp,JSON.stringify(r))}catch{return}},xS=t=>Date.now()-t.fetchedAt<fS,yS=(t,r)=>{const s=t.toLowerCase(),n=/^([a-z]+)(?:\(.*\))?!?:/,o=s.match(n);if(o){const c=o[1],d=fu[c];if(d)return r.find(u=>u.code===d)||null}const a=s.split(" ")[0],l=fu[a];return l&&r.find(c=>c.code===l)||null};let io=null;const bS=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=fe(),{currentDirectory:n}=gt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??void 0},wS=()=>{const{git:t}=Zs(),r=bS(),{currentSessionId:s,worktreeMetadata:n}=fe(),o=s?n.get(s)??void 0:void 0,{profiles:a,globalIdentity:l,defaultGitIdentityId:c,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=Kn(),f=Kl(r??null),p=pf(r??null),h=hf(r??null),x=ew(r??null),g=tw(r??null),w=ls(be=>be.isLoadingStatus),y=ls(be=>be.isLoadingLog),{setActiveDirectory:v,fetchAll:S,fetchStatus:k,fetchBranches:b,fetchLog:N,fetchIdentity:D,setLogMaxCount:j}=ls(),M=i.useMemo(()=>!io||io.directory!==r?null:io,[r]),C=et(be=>be.settingsGitmojiEnabled),P=zt(be=>be.getActiveProject()),E=i.useMemo(()=>{const be=P?.worktreeDefaults?.baseBranch;return typeof be=="string"&&be.trim().length>0?be.trim():"main"},[P?.worktreeDefaults?.baseBranch]),[I,A]=i.useState(M?.commitMessage??""),[T,R]=i.useState(!1),[K,Y]=i.useState(null),[_,J]=i.useState(null),[q,Q]=i.useState(25),[z,H]=i.useState(!1),{triggerFireworks:W}=H0(),B=i.useRef(new Map),se=i.useRef(0),L=i.useCallback(()=>{se.current+=1,H(!0)},[]),ae=i.useCallback(()=>{se.current=Math.max(0,se.current-1),se.current===0&&H(!1)},[]),[O,V]=i.useState(()=>new Set(M?.selectedPaths??[])),[X,re]=i.useState(!1),[me,G]=i.useState(new Set),[he,ye]=i.useState(!1),[ge,$e]=i.useState([]),ee=i.useCallback(()=>{$e([])},[]),[Z,ie]=i.useState(new Set),[Me,oe]=i.useState(new Map),[xe,pe]=i.useState(new Set),[je,ce]=i.useState(null),[Ye,mt]=i.useState([]),[Ie,le]=i.useState(""),Xe=i.useCallback(be=>{navigator.clipboard.writeText(be).then(()=>{U.success("Commit hash copied")}).catch(()=>{U.error("Failed to copy")})},[]),Ne=i.useCallback(be=>{ie(Pe=>{const Oe=new Set(Pe);return Oe.has(be)?Oe.delete(be):Oe.add(be),Oe})},[]);i.useEffect(()=>{if(!r||!t)return;const be=Array.from(Z).filter(Pe=>!Me.has(Pe)&&!xe.has(Pe));if(be.length!==0){pe(Pe=>{const Oe=new Set(Pe);for(const st of be)Oe.add(st);return Oe});for(const Pe of be)t.getCommitFiles(r,Pe).then(Oe=>{oe(st=>new Map(st).set(Pe,Oe.files))}).catch(Oe=>{console.error("Failed to fetch commit files:",Oe),oe(st=>new Map(st).set(Pe,[]))}).finally(()=>{pe(Oe=>{const st=new Set(Oe);return st.delete(Pe),st})})}},[Z,r,t,Me,xe]),i.useEffect(()=>()=>{if(!r){io=null;return}io={directory:r,selectedPaths:Array.from(O),commitMessage:I}},[I,r,O]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!t?.getRemoteUrl){ce(null);return}t.getRemoteUrl(r).then(ce).catch(()=>ce(null))},[r,t]),i.useEffect(()=>{if(!C){mt([]);return}let be=!1;const Pe=hS();return Pe&&(mt(Pe.gitmojis),xS(Pe))?()=>{be=!0}:((async()=>{try{const st=await fetch(pS);if(!st.ok)throw new Error(`Failed to load gitmojis: ${st.statusText}`);const ne=await st.json(),Ae=Array.isArray(ne.gitmojis)?ne.gitmojis.filter(hp):[];be||(mt(Ae),gS(Ae))}catch(st){be||console.warn("Failed to load gitmoji list:",st)}})(),()=>{be=!0})},[C]),i.useEffect(()=>{r&&(v(r),ls.getState().directories.get(r)?.status||S(r,t,{force:!0}))},[r,v,S,t]);const Se=i.useCallback(async(be=!0)=>{if(r)try{await Promise.all([k(r,t),b(r,t)])}catch(Pe){if(be){const Oe=Pe instanceof Error?Pe.message:"Failed to refresh repository state";U.error(Oe)}}},[r,t,k,b]),qe=i.useCallback(async()=>{r&&await N(r,t,q)},[r,t,N,q]),rt=i.useCallback(async()=>{r&&await D(r,t)},[r,t,D]);i.useEffect(()=>{if(!r||!t?.hasLocalIdentity||f!==!0)return;const be=typeof c=="string"?c.trim():"";if(!be||be==="global"||B.current.get(r)===be)return;let Oe=!1;return(async()=>{try{const ne=await t.hasLocalIdentity?.(r);if(Oe||ne===!0)return;L(),await t.setGitIdentity(r,be),B.current.set(r,be),await rt()}catch(ne){console.warn("Failed to auto-apply default git identity:",ne)}finally{Oe||ae()}})(),()=>{Oe=!0}},[L,r,c,ae,t,f,rt]);const We=i.useMemo(()=>{if(!p)return[];const be=p.files??[],Pe=new Map;for(const Oe of be)Pe.set(Oe.path,Oe);return Array.from(Pe.values()).sort((Oe,st)=>Oe.path.localeCompare(st.path))},[p]);i.useEffect(()=>{if(!p||We.length===0){V(new Set),re(!1);return}V(be=>{const Pe=new Set,Oe=be??new Set;for(const st of We)Oe.has(st.path)?Pe.add(st.path):X||Pe.add(st.path);return Pe})},[p,We,X]);const _e=async be=>{if(r){Y(be);try{if(be==="fetch")await t.gitFetch(r),U.success("Fetched latest updates");else if(be==="pull"){const Pe=await t.gitPull(r);U.success(`Pulled ${Pe.files.length} file${Pe.files.length===1?"":"s"}`)}else be==="push"&&(await t.gitPush(r),U.success("Pushed to remote"));await Se(!1),await qe()}catch(Pe){const Oe=Pe instanceof Error?Pe.message:`Failed to ${be==="pull"?"pull":be}`;U.error(Oe)}finally{Y(null)}}},Ke=async(be={})=>{if(!r)return;if(!I.trim()){U.error("Please enter a commit message");return}const Pe=Array.from(O).sort();if(Pe.length===0){U.error("Select at least one file to commit");return}const Oe=be.pushAfter?"commitAndPush":"commit";J(Oe);try{await t.createGitCommit(r,I.trim(),{files:Pe}),U.success("Commit created successfully"),A(""),V(new Set),re(!1),ee(),await Se(),be.pushAfter?(await t.gitPush(r),U.success("Pushed to remote"),W(),await Se(!1)):await Se(!1),await qe()}catch(st){const ne=st instanceof Error?st.message:"Failed to create commit";U.error(ne)}finally{J(null)}},xt=i.useCallback(async()=>{if(r){if(O.size===0){U.error("Select at least one file to describe");return}ye(!0);try{const{message:be}=await t.generateCommitMessage(r,Array.from(O)),Pe=be.subject?.trim()??"",Oe=Array.isArray(be.highlights)?be.highlights:[];if(Pe){let st=Pe;if(C&&Ye.length>0){const ne=yS(Pe,Ye);if(ne){const{code:Ae,emoji:te}=ne;!Pe.startsWith(Ae)&&!Pe.startsWith(te)&&(st=`${Ae} ${Pe}`)}}A(st)}$e(Oe),U.success("Commit message generated")}catch(be){const Pe=be instanceof Error?be.message:"Failed to generate commit message";U.error(Pe)}finally{ye(!1)}}},[r,O,t,C,Ye]),nt=async be=>{if(!r||!p)return;const Pe=p.current??null;try{await t.createBranch(r,be,Pe??"HEAD"),U.success(`Created branch ${be}`);let Oe=!1;try{await t.checkoutBranch(r,be),await t.gitPush(r,{remote:"origin",branch:be,options:["--set-upstream"]}),Oe=!0}catch(st){const ne=st instanceof Error?st.message:"Unable to push new branch to origin.";U.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",ne]})})}finally{if(Pe)try{await t.checkoutBranch(r,Pe)}catch(st){console.warn("Failed to restore original branch after creation:",st)}}await Se(),await qe(),Oe&&U.success(`Upstream set for ${be}`)}catch(Oe){const st=Oe instanceof Error?Oe.message:"Failed to create branch";throw U.error(st),Oe}},Pt=async(be,Pe)=>{if(r)try{await t.renameBranch(r,be,Pe),U.success(`Renamed branch ${be} to ${Pe}`),await Se(),await qe()}catch(Oe){const st=Oe instanceof Error?Oe.message:`Failed to rename branch ${be} to ${Pe}`;U.error(st)}},Tt=async be=>{if(!r)return;const Pe=be.replace(/^remotes\//,"");if(p?.current!==Pe)try{await t.checkoutBranch(r,Pe),U.success(`Checked out ${Pe}`),await Se(),await qe()}catch(Oe){const st=Oe instanceof Error?Oe.message:`Failed to checkout ${Pe}`;U.error(st)}},_t=async be=>{if(r){L();try{await t.setGitIdentity(r,be.id),U.success(`Applied "${be.name}" to repository`),await rt()}catch(Pe){const Oe=Pe instanceof Error?Pe.message:"Failed to apply git identity";U.error(Oe)}finally{ae()}}},Ve=i.useMemo(()=>h?.all?h.all.filter(be=>!be.startsWith("remotes/")).sort():[],[h]),dt=i.useMemo(()=>h?.all?h.all.filter(be=>be.startsWith("remotes/")).map(be=>be.replace(/^remotes\//,"")).sort():[],[h]),vt=i.useMemo(()=>{const be=new Map;l&&be.set(l.id,l);let Pe=null;if(je)try{let Oe=je.trim();Oe.startsWith("git@")&&(Oe=`https://${Oe.slice(4).replace(":","/")}`),Oe.endsWith(".git")&&(Oe=Oe.slice(0,-4));const st=new URL(Oe);Pe=st.hostname+st.pathname}catch{}for(const Oe of a){if(Oe.authType!=="token"){be.set(Oe.id,Oe);continue}const st=Oe.host;if(!st){be.set(Oe.id,Oe);continue}if(!st.includes("/")){be.set(Oe.id,Oe);continue}Pe&&Pe===st&&be.set(Oe.id,Oe)}return Array.from(be.values())},[a,l,je]),ut=i.useMemo(()=>{if(g?.userName&&g?.userEmail){const be=a.find(Pe=>Pe.userName===g.userName&&Pe.userEmail===g.userEmail);return be||(l&&l.userName===g.userName&&l.userEmail===g.userEmail?l:{id:"local-config",name:g.userName,userName:g.userName,userEmail:g.userEmail,sshKey:g.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return l??null},[g,a,l]),At=We.length,Rt=O.size,as=w||K!==null||_!==null,Ct=At>0,$t=be=>{V(Pe=>{const Oe=new Set(Pe);return Oe.has(be)?Oe.delete(be):Oe.add(be),Oe}),re(!0)},Mt=()=>{const be=new Set(We.map(Pe=>Pe.path));V(be),re(!0)},Gt=()=>{V(new Set),re(!0)},Dt=i.useCallback(async be=>{if(r){G(Pe=>{const Oe=new Set(Pe);return Oe.add(be),Oe});try{await t.revertGitFile(r,be),U.success(`Reverted ${be}`),await Se(!1)}catch(Pe){const Oe=Pe instanceof Error?Pe.message:"Failed to revert changes";U.error(Oe)}finally{G(Pe=>{const Oe=new Set(Pe);return Oe.delete(be),Oe})}}},[r,Se,t]),qt=i.useCallback(()=>{if(ge.length===0)return;const be=ge.map(Pe=>Pe.trim()).filter(Boolean);if(be.length===0){ee();return}A(Pe=>{const Oe=Pe.trim(),st=Oe.length>0?`
195
-
196
- `:"";return`${Oe}${st}${be.join(`
197
- `)}`.trim()})},[ge,ee]),St=i.useCallback((be,Pe)=>{const Oe=Pe||be;A(st=>{const ne=st.trimStart();return ne.startsWith(be)||Pe&&ne.startsWith(Pe)?st:`${Oe.endsWith(" ")?Oe:`${Oe} `}${st}`.trimStart()}),le(""),R(!1)},[]),Lt=i.useCallback(be=>{Q(be),r&&(j(r,be),N(r,t,be))},[r,j,N,t]);return r?w&&f===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ft,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):f===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Kt,{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(X0,{status:p,localBranches:Ve,remoteBranches:dt,branchInfo:h?.branches,syncAction:K,onFetch:()=>_e("fetch"),onPull:()=>_e("pull"),onPush:()=>_e("push"),onCheckoutBranch:Tt,onCreateBranch:nt,onRenameBranch:Pt,activeIdentityProfile:ut,availableIdentities:vt,onSelectIdentity:_t,isApplyingIdentity:z,isWorktreeMode:!!o}),e.jsx(ht,{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:[Ct?e.jsx(rS,{changeEntries:We,selectedPaths:O,diffStats:p?.diffStats,revertingPaths:me,onToggleFile:$t,onSelectAll:Mt,onClearSelection:Gt,onViewDiff:be=>ke.getState().navigateToDiff(be),onRevertFile:Dt}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(J0,{behind:p?.behind??0,onPull:()=>_e("pull"),isPulling:K==="pull"})}),We.length>0&&e.jsx(aS,{selectedCount:Rt,commitMessage:I,onCommitMessageChange:A,generatedHighlights:ge,onInsertHighlights:qt,onClearHighlights:ee,onGenerateMessage:xt,isGeneratingMessage:he,onCommit:()=>Ke({pushAfter:!1}),onCommitAndPush:()=>Ke({pushAfter:!0}),commitAction:_,isBusy:as,gitmojiEnabled:C,onOpenGitmojiPicker:()=>R(!0)})]}),r&&p?.current?e.jsx(mS,{directory:r,branch:p.current,baseBranch:E}):null,e.jsx(dS,{log:x,isLogLoading:y,logMaxCount:q,onLogMaxCountChange:Lt,expandedCommitHashes:Z,onToggleCommit:Ne,commitFilesMap:Me,loadingCommitHashes:xe,onCopyHash:Xe})]})}),e.jsx(ps,{open:T,onOpenChange:R,children:e.jsxs(hs,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(ys,{className:"px-4 pt-4",children:e.jsx(bs,{children:"Pick a gitmoji"})}),e.jsxs(rc,{className:"h-[420px]",children:[e.jsx(nc,{placeholder:"Search gitmojis...",value:Ie,onValueChange:le}),e.jsxs(oc,{children:[e.jsx(ac,{children:"No gitmojis found."}),e.jsx(un,{children:(Ye.length===0?[]:Ye.filter(be=>{const Pe=Ie.trim().toLowerCase();return Pe?be.emoji.includes(Pe)||be.code.toLowerCase().includes(Pe)||be.description.toLowerCase().includes(Pe):!0})).map(be=>e.jsxs(js,{onSelect:()=>St(be.emoji,be.code),children:[e.jsx("span",{className:"text-lg",children:be.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:be.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:be.description})]},be.code))})]})]})]})})]}):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."})})},vS=1e6;function rn(t){let r=t.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const Zo=t=>({directory:t,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),pu=os((t,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:s=>{const n=rn(s);return r().sessions.get(n)},setTerminalSession:(s,n)=>{const o=rn(s);t(a=>{const l=new Map(a.sessions),c=l.get(o),u=!c||c.terminalSessionId!==n.sessionId?Zo(o):c??Zo(o);return l.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:l}})},setConnecting:(s,n)=>{const o=rn(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??Zo(o);return l.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(s,n)=>{if(!n)return;const o=rn(s);t(a=>{const l=new Map(a.sessions),c=l.get(o)??Zo(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>vS&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return l.set(o,{...c,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:l,nextChunkId:d+1}})},clearTerminalSession:s=>{const n=rn(s);t(o=>{const a=new Map(o.sessions),l=a.get(n);return l&&a.set(n,{...l,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:s=>{const n=rn(s);t(o=>{const a=new Map(o.sessions),l=a.get(n);return l?(a.set(n,{...l,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:s=>{const n=rn(s);t(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{t({sessions:new Map,nextChunkId:1})}})),gp=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),jS=[{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'}],SS=[{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'}],xp=t=>Object.fromEntries(t.map(r=>[r.id,r])),hu=xp(jS),nn=xp(SS),NS="ibm-plex-sans",ya="ibm-plex-mono";function kS(t){const{colors:r}=t,s=r.syntax.base;return{background:r.surface.background,foreground:s.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:s.function,magenta:s.keyword,cyan:s.type,white:s.foreground,brightBlack:s.comment,brightRed:r.status.error,brightGreen:r.status.success,brightYellow:r.status.warning,brightBlue:s.function,brightMagenta:s.keyword,brightCyan:s.type,brightWhite:r.surface.elevatedForeground}}function CS(t,r,s,n){const a=`${t}, "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:s.background,foreground:s.foreground,cursor:s.cursor,cursorAccent:s.cursorAccent,selectionBackground:s.selectionBackground,selectionForeground:s.selectionForeground,black:s.black,red:s.red,green:s.green,yellow:s.yellow,blue:s.blue,magenta:s.magenta,cyan:s.cyan,white:s.white,brightBlack:s.brightBlack,brightRed:s.brightRed,brightGreen:s.brightGreen,brightYellow:s.brightYellow,brightBlue:s.brightBlue,brightMagenta:s.brightMagenta,brightCyan:s.brightCyan,brightWhite:s.brightWhite},scrollback:5e4,ghostty:n}}let zi=null;function MS(){return zi||(zi=Pg.load()),zi}function DS(t){if(typeof window>"u")return null;const r=[t,...Array.from(t.querySelectorAll("*"))];let s=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;s||(s=n)}}return s}const Nl=i.forwardRef(({sessionKey:t,chunks:r,onInput:s,onResize:n,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d},u)=>{const m=i.useRef(null),f=i.useRef(null),p=i.useRef(null),h=i.useRef(null),x=i.useRef(s),g=i.useRef(n),w=i.useRef(null),y=i.useRef(""),v=i.useRef(null),S=i.useRef(!1),k=i.useRef(null),b=i.useRef(null),N=i.useRef(null),D=i.useRef(0),j=i.useRef(null),[,M]=i.useReducer(_=>_+1,0),[C,P]=i.useReducer(_=>_+1,0);x.current=s,g.current=n;const E=i.useCallback((_,J)=>{const q=j.current,Q=m.current;if(!q||!Q)return;const z=Q.getBoundingClientRect(),H=z.left+z.width/2,W=z.top+z.height-12,B=typeof _=="number"?_:H,se=typeof J=="number"?J:W,L=8,ae=Math.max(L,Math.min(z.width-L,B-z.left)),O=Math.max(L,Math.min(z.height-L,se-z.top));q.style.left=`${ae}px`,q.style.top=`${O}px`,q.style.bottom="";try{q.focus({preventScroll:!0})}catch{try{q.focus()}catch{}}},[]),I=i.useCallback(()=>{y.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,S.current=!1,k.current=null},[]),A=i.useCallback(()=>{const _=h.current,J=p.current,q=m.current;if(!_||!J||!q)return;const Q=q.getBoundingClientRect();if(!(Q.width<24||Q.height<24))try{_.fit();const z={cols:J.cols,rows:J.rows},H=w.current;(!H||H.cols!==z.cols||H.rows!==z.rows)&&(w.current=z,g.current(z.cols,z.rows))}catch{}},[]),T=i.useCallback(()=>{if(S.current)return;const _=p.current;if(!_){I();return}if(!y.current)return;const J=y.current;y.current="",S.current=!0,_.write(J,()=>{S.current=!1,y.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,T()}):T())})},[I]),R=i.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,T()}):T())},[T]),K=i.useCallback(_=>{_&&(y.current+=_,R())},[R]),Y=i.useCallback(()=>{if(b.current?.(),b.current=null,N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),!d){D.current=0;return}const _=m.current;if(!_)return;const J=p.current;if(!J)return;D.current=0;const q=2.2,Q=2.8,z=25,H=.25,W=8,B=.05,se=.015,L={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},ae=()=>typeof performance<"u"?performance.now():Date.now(),O=Math.max(12,Math.round(l*1.35));let V=0;const X=Z=>{if(!Z)return!1;const ie=J.getViewportY(),Me=V+Z,oe=Math.trunc(Me/O);return V=Me-oe*O,oe!==0&&J.scrollLines(oe),J.getViewportY()!==ie},re=()=>{L.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(L.rafId),L.rafId=null},me={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const Z=Object.assign(L,{pointerId:null,startX:null,startY:null,moved:!1}),ie=6,Me=je=>{if(je.pointerType==="touch"){re(),Z.pointerId=je.pointerId,Z.startX=je.clientX,Z.startY=je.clientY,Z.moved=!1,Z.lastY=je.clientY,Z.lastTime=ae(),Z.velocity=0;try{_.setPointerCapture(je.pointerId)}catch{}}},oe=je=>{if(je.pointerType!=="touch"||Z.pointerId!==je.pointerId)return;if(Z.startX!==null&&Z.startY!==null&&!Z.moved){const qe=je.clientX-Z.startX,rt=je.clientY-Z.startY;Math.hypot(qe,rt)>=ie&&(Z.moved=!0)}if(Z.lastY===null){Z.lastY=je.clientY,Z.lastTime=ae();return}const ce=Z.lastY,Ye=Z.lastTime??ae(),mt=ae();Z.lastY=je.clientY,Z.lastTime=mt;const Ie=ce-je.clientY;if(Math.abs(Ie)<1)return;const le=Math.max(mt-Ye,8),Xe=q+Math.min(Q,Math.abs(Ie)/z),Ne=Ie*Xe,Se=Ne/le;Z.velocity=Z.velocity*(1-H)+Se*H,Z.velocity>W?Z.velocity=W:Z.velocity<-W&&(Z.velocity=-W),Z.moved&&(je.cancelable&&je.preventDefault(),je.stopPropagation()),X(Ne)},xe=je=>{if(je.pointerType!=="touch"||Z.pointerId!==je.pointerId)return;const ce=!Z.moved;Z.pointerId=null,Z.startX=null,Z.startY=null,Z.moved=!1,Z.lastY=null,Z.lastTime=null;try{_.releasePointerCapture(je.pointerId)}catch{}if(ce){E(je.clientX,je.clientY);return}if(typeof window>"u")return;if(Math.abs(Z.velocity)<B){Z.velocity=0;return}let Ye=ae();const mt=()=>{const Ie=ae(),le=Math.max(Ie-Ye,8);Ye=Ie;const Xe=X(Z.velocity*le)??!1,Ne=Math.sign(Z.velocity),Se=Math.max(0,Math.abs(Z.velocity)-se*le);if(Z.velocity=Se*Ne,!Xe||Se<=B){re(),Z.velocity=0;return}Z.rafId=window.requestAnimationFrame(mt)};Z.rafId=window.requestAnimationFrame(mt)};_.addEventListener("pointerdown",Me,me),_.addEventListener("pointermove",oe,me),_.addEventListener("pointerup",xe,me),_.addEventListener("pointercancel",xe,me);const pe=_.style.touchAction;_.style.touchAction="manipulation",b.current=()=>{re(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),D.current=0,_.removeEventListener("pointerdown",Me,me),_.removeEventListener("pointermove",oe,me),_.removeEventListener("pointerup",xe,me),_.removeEventListener("pointercancel",xe,me),_.style.touchAction=pe};return}const he=6,ye=Z=>{Z.touches.length===1&&(re(),L.lastY=Z.touches[0].clientY,L.lastTime=ae(),L.velocity=0,L.startX=Z.touches[0].clientX,L.startY=Z.touches[0].clientY,L.didMove=!1)},ge=Z=>{if(Z.touches.length!==1){L.lastY=null,L.lastTime=null,L.velocity=0,L.startX=null,L.startY=null,L.didMove=!1,re();return}const ie=Z.touches[0].clientX,Me=Z.touches[0].clientY;if(L.startX!==null&&L.startY!==null&&!L.didMove){const le=ie-L.startX,Xe=Me-L.startY;Math.hypot(le,Xe)>=he&&(L.didMove=!0)}if(L.lastY===null){L.lastY=Me,L.lastTime=ae();return}const oe=L.lastY,xe=L.lastTime??ae(),pe=ae();L.lastY=Me,L.lastTime=pe;const je=oe-Me;if(Math.abs(je)<1)return;const ce=Math.max(pe-xe,8),Ye=q+Math.min(Q,Math.abs(je)/z),mt=je*Ye,Ie=mt/ce;L.velocity=L.velocity*(1-H)+Ie*H,L.velocity>W?L.velocity=W:L.velocity<-W&&(L.velocity=-W),L.didMove&&(Z.preventDefault(),Z.stopPropagation()),X(mt)},$e=Z=>{const ie=!L.didMove;L.lastY=null,L.lastTime=null;const Me=L.velocity;if(L.startX=null,L.startY=null,L.didMove=!1,ie){const pe=Z.changedTouches?.[0];E(pe?.clientX,pe?.clientY);return}if(typeof window>"u")return;if(Math.abs(Me)<B){L.velocity=0;return}let oe=ae();const xe=()=>{const pe=ae(),je=Math.max(pe-oe,8);oe=pe;const ce=X(L.velocity*je)??!1,Ye=Math.sign(L.velocity),mt=Math.max(0,Math.abs(L.velocity)-se*je);if(L.velocity=mt*Ye,!ce||mt<=B){re(),L.velocity=0;return}L.rafId=window.requestAnimationFrame(xe)};L.rafId=window.requestAnimationFrame(xe)};_.addEventListener("touchstart",ye,me),_.addEventListener("touchmove",ge,me),_.addEventListener("touchend",$e,me),_.addEventListener("touchcancel",$e,me);const ee=_.style.touchAction;_.style.touchAction="manipulation",b.current=()=>{re(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),D.current=0,_.removeEventListener("touchstart",ye,me),_.removeEventListener("touchmove",ge,me),_.removeEventListener("touchend",$e,me),_.removeEventListener("touchcancel",$e,me),_.style.touchAction=ee}},[d,E,l]);return i.useEffect(()=>{let _=!1,J=null,q=null,Q=[];const z=m.current;return z?(z.tabIndex=0,(async()=>{try{const W=await MS();if(_)return;const B=CS(a,l,o,W),se=new Eg(B),L=new Ig;J=se,p.current=se,h.current=L,se.loadAddon(L),se.open(z),P();const ae=DS(z);ae?(ae.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=ae,M()):f.current=null,A(),Y(),se.focus(),Q=[se.onData(O=>{x.current(O)})],q=new ResizeObserver(()=>{A()}),q.observe(z),typeof window<"u"&&window.setTimeout(()=>{A()},0)}catch{}})(),()=>{_=!0,b.current?.(),b.current=null,Q.forEach(W=>W.dispose()),q?.disconnect(),J?.dispose(),p.current=null,h.current=null,f.current=null,w.current=null,I()}):void 0},[A,a,l,Y,o,I]),i.useEffect(()=>{const _=p.current;_&&(_.reset(),I(),w.current=null,A(),_.focus())},[t,C,A,I]),i.useEffect(()=>(Y(),()=>{b.current?.(),b.current=null}),[Y,t]),i.useEffect(()=>{const _=p.current;if(!_)return;if(r.length===0){k.current!==null&&(_.reset(),I(),A());return}const J=k.current;let q;if(J===null)q=r;else{const Q=r.findIndex(z=>z.id===J);q=Q>=0?r.slice(Q+1):r}q.length>0&&K(q.map(Q=>Q.data).join("")),k.current=r[r.length-1].id},[r,C,K,A,I]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){E();return}p.current?.focus()},clear:()=>{const _=p.current;_&&(_.reset(),I(),A())},fit:()=>{A()}}),[d,E,A,I]),e.jsxs("div",{ref:m,className:F("relative h-full w-full terminal-viewport-container",c),style:{backgroundColor:o.background},onClick:_=>{d?E(_.clientX,_.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:j,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 J=String(_.currentTarget.value||"");if(!J)return;const q=J.replace(/\r\n|\r|\n/g,"\r");x.current(q),_.currentTarget.value=""},onKeyDown:_=>{_.key==="Backspace"&&(_.currentTarget.value||x.current(""))}}):null,f.current&&!d?e.jsx(ql,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Nl.displayName="TerminalViewport";const gu=13,AS={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},ea={ctrl:"5",cmd:"3"},ES={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},IS=(t,r)=>{if(r)switch(t){case"arrow-up":return`\x1B[1;${ea[r]}A`;case"arrow-down":return`\x1B[1;${ea[r]}B`;case"arrow-right":return`\x1B[1;${ea[r]}C`;case"arrow-left":return`\x1B[1;${ea[r]}D`}return AS[t]??null},PS=()=>{const{terminal:t}=Zs(),{currentTheme:r}=en(),{monoFont:s}=gp(),{isMobile:n,hasTouchInput:o}=Yt(),{currentSessionId:a,sessions:l,worktreeMetadata:c}=fe(),d=a?c.get(a)??void 0:void 0,u=i.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const ie=l.find(oe=>oe.id===a),Me=typeof ie?.directory=="string"?ie.directory:null;return Me&&Me.length>0?Me:null},[a,l,d]),{currentDirectory:m,homeDirectory:f}=gt(),p=u||m||null,h=i.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),x=pu(),g=x.sessions,w=x.setTerminalSession,y=x.setConnecting,v=x.appendToBuffer,S=x.clearTerminalSession,k=x.removeTerminalSession,b=x.clearBuffer,N=i.useMemo(()=>{if(p)return g.get(p)},[g,p]),D=N?.terminalSessionId??null,j=N?.bufferChunks??[],M=N?.bufferLength??0,C=N?.isConnecting??!1,P=D,[E,I]=i.useState(null),[A,T]=i.useState(!1),[R,K]=i.useState(null),[Y,_]=i.useState(!1),J=i.useRef(null),q=i.useRef(null),Q=i.useRef(P),z=i.useRef(p),H=i.useRef(null),B=ke(ie=>ie.activeMainTab)==="terminal";i.useEffect(()=>{Q.current=P},[P]),i.useEffect(()=>{z.current=p},[p]),i.useEffect(()=>{!n&&R!==null&&K(null)},[n,R,K]),i.useEffect(()=>{!P&&R!==null&&K(null)},[P,R,K]);const se=i.useCallback(()=>{J.current?.(),J.current=null,q.current=null},[]);i.useEffect(()=>()=>{se(),Q.current=null},[se]);const L=i.useCallback(ie=>{if(q.current===ie)return;se();const Me=t.connect(ie,{onEvent:oe=>{const xe=z.current;if(xe)switch(oe.type){case"connected":{(oe.runtime||oe.ptyBackend)&&console.log(`[Terminal] connected runtime=${oe.runtime??"unknown"} pty=${oe.ptyBackend??"unknown"}`),y(xe,!1),I(null),T(!1),H.current?.focus();break}case"reconnecting":{const pe=oe.attempt??0,je=oe.maxAttempts??3;I(`Reconnecting (${pe}/${je})...`),T(!1);break}case"data":{oe.data&&v(xe,oe.data);break}case"exit":{const pe=typeof oe.exitCode=="number"?oe.exitCode:null,je=typeof oe.signal=="number"?oe.signal:null;v(xe,`\r
198
- [Process exited${pe!==null?` with code ${pe}`:""}${je!==null?` (signal ${je})`:""}]\r
199
- `),S(xe),y(xe,!1),I("Terminal session ended"),T(!1),se();break}}},onError:(oe,xe)=>{const pe=z.current;if(!pe)return;const je=xe?`Connection failed: ${oe.message}`:oe.message||"Terminal stream connection error";I(je),T(!!xe),xe&&(y(pe,!1),se(),k(pe))}},ES);J.current=()=>{Me.close(),q.current=null},q.current=ie},[v,S,se,k,y,t,I]);i.useEffect(()=>{let ie=!1;if(!p){I(a?"No working directory available for terminal.":"Select a session to open the terminal."),se();return}return(async()=>{const oe=p;if(!z.current||z.current!==oe)return;let pe=pu.getState().getTerminalSession(oe)?.terminalSessionId??null;if(!pe){I(null),T(!1),y(oe,!0);try{const je=await t.createSession({cwd:oe});if(ie){try{await t.close(je.sessionId)}catch{}return}w(oe,je),pe=je.sessionId}catch(je){ie||(I(je instanceof Error?je.message:"Failed to start terminal session"),T(!0),y(oe,!1));return}}!pe||ie||(Q.current=pe,L(pe))})(),()=>{ie=!0,Q.current=null,se()}},[a,p,P,k,y,w,L,se,t]);const ae=i.useCallback(async()=>{if(!p||Y)return;_(!0),I(null),T(!1),se();const ie=Q.current;try{if(t.restartSession&&ie){const Me=await t.restartSession(ie,{cwd:p});w(p,Me),Q.current=Me.sessionId,L(Me.sessionId)}else{if(ie)try{await t.close(ie)}catch{}k(p)}}catch(Me){I(Me instanceof Error?Me.message:"Failed to restart terminal"),T(!0)}finally{_(!1)}},[p,Y,se,t,w,L,k]),O=i.useCallback(async()=>{if(p&&!Y){_(!0),I(null),T(!1),se();try{t.forceKill&&await t.forceKill({cwd:p})}catch{}k(p),b(p),H.current?.clear(),await new Promise(ie=>setTimeout(ie,100));try{y(p,!0);const ie=await t.createSession({cwd:p});w(p,ie),Q.current=ie.sessionId,L(ie.sessionId)}catch(ie){I(ie instanceof Error?ie.message:"Failed to create terminal"),T(!0),y(p,!1)}finally{_(!1)}}},[p,Y,se,t,k,b,y,w,L]),V=i.useCallback(()=>{if(!p)return;b(p),H.current?.clear(),H.current?.focus();const ie=Q.current;ie&&t.sendInput(ie,"\f").catch(Me=>{I(Me instanceof Error?Me.message:"Failed to refresh prompt")})},[b,p,I,t]),X=i.useCallback(ie=>{if(!ie)return;let Me=ie,oe=!1;if(R&&ie.length>0){const pe=ie[0];if(pe.length===1&&/[a-zA-Z]/.test(pe)){const je=pe.toUpperCase();(R==="ctrl"||R==="cmd")&&(Me=String.fromCharCode(je.charCodeAt(0)&31),oe=!0)}oe||(oe=!0)}const xe=Q.current;xe&&(t.sendInput(xe,Me).catch(pe=>{I(pe instanceof Error?pe.message:"Failed to send input")}),oe&&(K(null),H.current?.focus()))},[R,K,t]),re=i.useCallback((ie,Me)=>{const oe=Q.current;oe&&t.resize({sessionId:oe,cols:ie,rows:Me}).catch(()=>{})},[t]),me=i.useCallback(ie=>{K(Me=>Me===ie?null:ie),H.current?.focus()},[K]),G=i.useCallback(ie=>{const Me=IS(ie,R);Me&&(X(Me),K(null),H.current?.focus())},[R,X,K]);i.useEffect(()=>{if(!n||!R||!P)return;const ie=Me=>{if(Me.repeat)return;const oe=Me.key;if(!oe||oe==="Control"||oe==="Meta"||oe==="Alt"||oe==="Shift")return;const xe=oe.length===1?oe.toLowerCase():oe,pe=Me.code??"",je=pe.startsWith("Key")&&pe.length===4?pe.slice(3).toUpperCase():null,ce=oe.length===1&&/[a-zA-Z]/.test(oe)?oe.toUpperCase():je,Ye={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc",tab:"tab",enter:"enter",arrowup:"arrow-up",arrowdown:"arrow-down",arrowleft:"arrow-left",arrowright:"arrow-right",escape:"esc"};if(xe in Ye){Me.preventDefault(),Me.stopPropagation(),G(Ye[xe]);return}if(R==="ctrl"&&ce&&ce.length===1&&ce>="A"&&ce<="Z"){const mt=String.fromCharCode(ce.charCodeAt(0)&31);Me.preventDefault(),Me.stopPropagation(),X(mt),K(null),H.current?.focus()}};return window.addEventListener("keydown",ie),()=>{window.removeEventListener("keydown",ie)}},[R,G,X,n,K,P]);const he=i.useMemo(()=>{const ie=nn[ya].stack;if(typeof window>"u")return(nn[s]??nn[ya]).stack;const oe=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return oe&&oe.trim().length>0?oe.trim():(nn[s]??nn[ya]).stack??ie},[s]),ye=i.useMemo(()=>kS(r),[r]),ge=i.useMemo(()=>`${p??"no-dir"}::${P??"pending"}`,[p,P]);i.useEffect(()=>{if(!B)return;const ie=H.current;if(!ie)return;const Me=()=>{ie.fit()};if(typeof window<"u"){const oe=window.requestAnimationFrame(()=>{Me(),ie.focus()}),xe=[220,400].map(pe=>window.setTimeout(Me,pe));return()=>{window.cancelAnimationFrame(oe),xe.forEach(pe=>window.clearTimeout(pe))}}Me()},[B,ge,P]);const $e=E?.includes("Reconnecting"),ee=E?$e?e.jsx(Tg,{size:20,className:"text-amber-400"}):e.jsx(es,{size:20,className:"text-destructive"}):P&&!C&&!Y?e.jsx(oa,{size:20,className:"text-emerald-400"}):C||Y?e.jsx(sl,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(sl,{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:ae,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Z=!P||C||Y;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee,e.jsxs(ve,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:V,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(qs,{size:16}),"Clear"]}),e.jsxs(ve,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:ae,disabled:Y,title:"Restart terminal session",type:"button",children:[e.jsx(Ts,{size:16,className:F((C||Y)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>G("esc"),disabled:Z,children:"Esc"}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>G("tab"),disabled:Z,children:[e.jsx(Cc,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:R==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>me("ctrl"),disabled:Z,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:R==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>me("cmd"),disabled:Z,children:[e.jsx(vn,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>G("arrow-up"),disabled:Z,children:[e.jsx(Do,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>G("arrow-left"),disabled:Z,children:[e.jsx(bm,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>G("arrow-down"),disabled:Z,children:[e.jsx(Jn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>G("arrow-right"),disabled:Z,children:[e.jsx(Cc,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>G("enter"),disabled:Z,children:[e.jsx(Hn,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:ye.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:B?n?e.jsx(Nl,{ref:ie=>{H.current=ie},sessionKey:ge,chunks:j,onInput:X,onResize:re,theme:ye,fontFamily:he,fontSize:gu,enableTouchScroll:o},ge):e.jsx(ht,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Nl,{ref:ie=>{H.current=ie},sessionKey:ge,chunks:j,onInput:X,onResize:re,theme:ye,fontFamily:he,fontSize:gu,enableTouchScroll:o},ge)}):null}),E&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:E}),A&&e.jsx(ve,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:O,disabled:Y,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},xu=new Ga,yu=new Ga,bu=new Ga,wu=new Ga,vu=t=>{if(!t)return[];const r=Math.max(1,t.start),s=Math.max(r,t.end);return Hg.fromClass(class{decorations;constructor(n){this.decorations=this.build(n)}update(n){(n.docChanged||n.viewportChanged)&&(this.decorations=this.build(n.view))}build(n){const o=new Wg;for(let a=r;a<=s&&a<=n.state.doc.lines;a+=1){const l=n.state.doc.line(a);o.add(l.from,l.from,Ug.line({class:"oc-cm-selected-line"}))}return o.finish()}},{decorations:n=>n.decorations})};function TS({value:t,onChange:r,extensions:s,className:n,readOnly:o,lineNumbersConfig:a,highlightLines:l}){const c=i.useRef(null),d=i.useRef(null),u=i.useRef(t),m=i.useRef(r);return i.useEffect(()=>{u.current=t},[t]),i.useEffect(()=>{m.current=r},[r]),i.useEffect(()=>{if(!c.current)return;const f=Fg.create({doc:u.current,extensions:[Rg({fixed:!0}),xu.of(Mc(a)),Lg(),Og.of(" "),_g.of([$g,...Bg,...zg]),Pn.updateListener.of(p=>{if(!p.docChanged)return;const h=p.state.doc.toString();u.current=h,m.current(h)}),yu.of(Pn.editable.of(!o)),bu.of(s??[]),wu.of(vu(l))]});return d.current=new Pn({state:f,parent:c.current}),()=>{d.current?.destroy(),d.current=null}},[]),i.useEffect(()=>{const f=d.current;f&&f.dispatch({effects:[xu.reconfigure(Mc(a)),yu.reconfigure(Pn.editable.of(!o)),bu.reconfigure(s??[]),wu.reconfigure(vu(l))]})},[s,l,a,o]),i.useEffect(()=>{const f=d.current;if(!f)return;const p=f.state.doc.toString();p!==t&&f.dispatch({changes:{from:0,to:p.length,insert:t}})},[t]),e.jsx("div",{ref:c,className:F("h-full w-full","[&_.cm-editor]:h-full [&_.cm-editor]:w-full","[&_.cm-scroller]:font-mono [&_.cm-scroller]:text-[var(--text-code)] [&_.cm-scroller]:leading-6",n)})}const kl=Zn.define(Vg),yp=Zn.define(Gg),FS=Zn.define(qg),RS=Zn.define(Kg),LS=Zn.define(Qg),OS=Zn.define(Yg);function _S(t){const r=t.trim().toLowerCase();switch(r){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return kl;case"toml":return yp;case"diff":case"patch":return FS;case"json":case"jsonc":case"json5":return Mm().language;case"js":case"javascript":return Tn().language;case"jsx":return Tn({jsx:!0}).language;case"ts":case"typescript":return Tn({typescript:!0}).language;case"tsx":return Tn({typescript:!0,jsx:!0}).language;case"yaml":case"yml":return Nm().language;case"html":return km().language;case"css":return Cm().language;case"xml":case"svg":return vm().language;case"py":case"python":return Sm().language;case"sql":return jm().language;case"rs":case"rust":return wm().language;default:return Jg.matchLanguageName(Zg,r,!0)}}const $S=t=>t.split("/").pop()?.toLowerCase()??"";function BS(t){const r=t.toLowerCase();switch($S(r)){case"dockerfile":return RS;case"makefile":case"gnumakefile":return kl}const n=r.lastIndexOf("."),o=n>=0?r.slice(n+1):"";switch(o){case"ts":case"tsx":case"mts":case"cts":return Tn({typescript:!0,jsx:o==="tsx"});case"js":case"jsx":case"mjs":case"cjs":return Tn({typescript:!1,jsx:o==="jsx"});case"json":case"jsonc":case"json5":case"jsonl":case"ndjson":case"geojson":return Mm();case"css":case"scss":case"sass":case"less":return Cm();case"html":case"htm":return km();case"md":case"mdx":case"markdown":case"mdown":case"mkd":return Xg({codeLanguages:_S});case"yml":case"yaml":return Nm();case"toml":return yp;case"ini":case"cfg":case"conf":case"config":case"properties":return OS;case"sh":case"bash":case"zsh":case"fish":case"env":return kl;case"py":case"pyw":case"pyi":return Sm();case"sql":case"psql":case"plsql":return jm();case"xml":case"xsl":case"xslt":case"xsd":case"dtd":case"plist":case"svg":return vm();case"rs":return wm();case"rb":case"erb":case"rake":case"gemspec":return LS;default:return null}}function ju(t){const r=t.metadata.variant==="dark",s=t.config?.fonts?.mono||"monospace",n=t.colors.syntax.highlights||{},o=t.colors.syntax.tokens||{},a=Pn.theme({"&":{backgroundColor:"var(--background)",color:t.colors.syntax.base.foreground,fontSize:"var(--text-code)",lineHeight:"1.5rem"},".cm-scroller":{fontFamily:s,backgroundColor:"var(--background)"},".cm-comment":{color:t.colors.syntax.base.comment},".cm-keyword":{color:t.colors.syntax.base.keyword},".cm-string":{color:t.colors.syntax.base.string},".cm-string-2":{color:o.stringEscape||t.colors.syntax.base.string},".cm-number":{color:t.colors.syntax.base.number},".cm-atom":{color:o.boolean||t.colors.syntax.base.number},".cm-builtin":{color:o.functionCall||t.colors.syntax.base.function},".cm-def":{color:o.variableGlobal||t.colors.syntax.base.variable},".cm-attribute":{color:o.variableOther||o.variableProperty||t.colors.syntax.base.operator},".cm-meta":{color:t.colors.syntax.base.comment},".cm-property":{color:o.variableProperty||t.colors.syntax.base.keyword},".cm-variable":{color:t.colors.syntax.base.variable},".cm-variable-2":{color:o.variableOther||t.colors.syntax.base.function},".cm-variable-3":{color:o.variableGlobal||t.colors.syntax.base.type},".cm-tag":{color:o.tag||t.colors.syntax.base.keyword},".cm-link":{color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"},".cm-content":{caretColor:t.colors.interactive.cursor},".cm-cursor, .cm-dropCursor":{borderLeftColor:t.colors.interactive.cursor},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:t.colors.interactive.selection},".cm-gutters":{backgroundColor:"var(--background)",color:n.lineNumber||t.colors.syntax.base.comment,borderRight:`1px solid ${t.colors.interactive.border}`,position:"sticky",paddingRight:"8px",left:0,zIndex:2,boxShadow:"0 0 0 var(--background)"},".cm-gutter":{backgroundColor:"var(--background)"},".cm-gutterElement":{backgroundColor:"var(--background)"},".cm-lineNumbers":{backgroundColor:"var(--background)"},".cm-lineNumbers .cm-gutterElement":{paddingLeft:"8px",paddingRight:"8px",minWidth:"42px"},".cm-activeLineGutter":{color:n.lineNumberActive||t.colors.syntax.base.foreground},".cm-activeLine":{backgroundColor:t.colors.surface.overlay},"&.cm-focused":{outline:"none"}},{dark:r}),l=ex.define([{tag:Ze.comment,color:t.colors.syntax.base.comment},{tag:Ze.docComment,color:o.commentDoc||t.colors.syntax.base.comment},{tag:Ze.keyword,color:t.colors.syntax.base.keyword},{tag:Ze.controlKeyword,color:t.colors.syntax.base.keyword},{tag:Ze.operatorKeyword,color:t.colors.syntax.base.operator},{tag:Ze.moduleKeyword,color:o.keywordImport||t.colors.syntax.base.keyword},{tag:[Ze.definitionKeyword,Ze.modifier],color:o.storageModifier||t.colors.syntax.base.keyword},{tag:Ze.atom,color:o.boolean||t.colors.syntax.base.number},{tag:[Ze.null,Ze.self],color:t.colors.syntax.base.number},{tag:[Ze.meta,Ze.documentMeta],color:t.colors.syntax.base.comment},{tag:Ze.string,color:t.colors.syntax.base.string},{tag:Ze.escape,color:o.stringEscape||t.colors.syntax.base.foreground},{tag:Ze.regexp,color:o.regex||t.colors.syntax.base.string},{tag:Ze.number,color:t.colors.syntax.base.number},{tag:Ze.bool,color:o.boolean||t.colors.syntax.base.number},{tag:Ze.operator,color:t.colors.syntax.base.operator},{tag:[Ze.derefOperator,Ze.updateOperator,Ze.definitionOperator,Ze.typeOperator,Ze.controlOperator],color:t.colors.syntax.base.operator},{tag:[Ze.logicOperator,Ze.bitwiseOperator,Ze.arithmeticOperator],color:t.colors.syntax.base.operator},{tag:[Ze.compareOperator],color:o.diffModified||t.colors.syntax.base.operator},{tag:[Ze.punctuation,Ze.separator,Ze.bracket,Ze.paren,Ze.brace,Ze.squareBracket,Ze.angleBracket],color:o.punctuation||t.colors.syntax.base.comment},{tag:Ze.function(Ze.variableName),color:o.functionCall||t.colors.syntax.base.function},{tag:Ze.function(Ze.definition(Ze.variableName)),color:t.colors.syntax.base.function},{tag:Ze.function(Ze.propertyName),color:o.method||o.functionCall||t.colors.syntax.base.function},{tag:Ze.namespace,color:o.namespace||t.colors.syntax.base.type},{tag:Ze.moduleKeyword,color:o.module||t.colors.syntax.base.keyword},{tag:Ze.macroName,color:o.macro||t.colors.syntax.base.keyword},{tag:Ze.labelName,color:o.label||t.colors.syntax.base.keyword},{tag:Ze.annotation,color:o.decorator||t.colors.syntax.base.keyword},{tag:Ze.propertyName,color:o.variableProperty||t.colors.syntax.base.keyword},{tag:Ze.attributeName,color:o.tagAttribute||t.colors.syntax.base.keyword},{tag:Ze.standard(Ze.variableName),color:o.method||t.colors.syntax.base.function},{tag:Ze.definition(Ze.variableName),color:t.colors.syntax.base.variable},{tag:Ze.local(Ze.variableName),color:t.colors.syntax.base.variable},{tag:Ze.special(Ze.variableName),color:o.variableOther||t.colors.syntax.base.function},{tag:Ze.variableName,color:t.colors.syntax.base.variable},{tag:Ze.special(Ze.string),color:t.colors.syntax.base.string},{tag:Ze.className,color:o.className||t.colors.syntax.base.type},{tag:Ze.typeName,color:t.colors.syntax.base.type},{tag:Ze.constant(Ze.variableName),color:o.constant||t.colors.syntax.base.variable},{tag:Ze.literal,color:o.constant||t.colors.syntax.base.variable},{tag:Ze.tagName,color:o.tag||t.colors.syntax.base.keyword},{tag:Ze.attributeValue,color:o.tagAttributeValue||t.colors.syntax.base.string},{tag:[Ze.heading,Ze.heading1,Ze.heading2,Ze.heading3,Ze.heading4,Ze.heading5,Ze.heading6],color:t.colors.syntax.base.keyword,fontWeight:"600"},{tag:Ze.monospace,color:t.colors.syntax.base.string},{tag:Ze.link,color:o.url||t.colors.syntax.base.keyword,textDecoration:"underline"}]);return[a,tx(l)]}const zS=t=>t.slice().sort((r,s)=>r.type!==s.type?r.type==="directory"?-1:1:r.name.localeCompare(s.name)),sr=t=>t.replace(/\\/g,"/"),HS=new Set(["node_modules"]),WS=t=>HS.has(t),US=t=>{const r=sr(t);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},VS=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=fe(),{currentDirectory:n}=gt(),o=t?s.get(t)??void 0:void 0,l=r.find(c=>c.id===t)?.directory;return o?.path??l??n??""},lo=2e5,GS=new Set(["js","jsx","ts","tsx","mjs","cjs","mts","cts","html","htm","xhtml","css","scss","sass","less","styl","stylus","vue","svelte","astro","sh","bash","zsh","fish","ps1","psm1","bat","cmd","py","pyw","pyx","pxd","pxi","rb","erb","rake","gemspec","php","phtml","php3","php4","php5","phps","java","kt","kts","scala","sc","groovy","gradle","c","h","cpp","cc","cxx","hpp","hxx","hh","m","mm","cs","fs","fsx","fsi","go","rs","swift","dart","lua","pl","pm","pod","r","R","rmd","jl","hs","lhs","ex","exs","erl","hrl","clj","cljs","cljc","edn","lisp","cl","el","scm","ss","rkt","ml","mli","re","rei","nim","zig","v","cr","main.kts","sql","psql","plsql","graphql","gql","sol","asm","s","S","mk","nix","tf","tfvars","pp","ansible"]),qS=new Set(["json","jsonc","json5","jsonl","ndjson","geojson","yaml","yml","toml","xml","xsl","xslt","xsd","dtd","plist","ini","cfg","conf","config","env","properties","csv","tsv","lock"]),KS=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),QS=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),Su=t=>{const r=t?.toLowerCase();return r&&GS.has(r)?e.jsx(Ys,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&qS.has(r)?e.jsx(Ys,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&KS.has(r)?e.jsx(Nr,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&QS.has(r)?e.jsx(wo,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(wo,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},YS=()=>{const{files:t,runtime:r}=Zs(),{currentTheme:s}=en();i.useMemo(()=>fc(s),[s]);const{isMobile:n,screenWidth:o}=Yt(),a=Po(),l=oi(),c=VS(),d=sr(c),u=Ya(we=>we.searchFiles),[m,f]=i.useState(""),p=ni(m,200),h=i.useRef(null),[x,g]=i.useState(!1),[w,y]=i.useState(n),[v,S]=i.useState(new Set),[k,b]=i.useState({}),N=i.useRef(new Set),D=i.useRef(new Set),[j,M]=i.useState([]),[C,P]=i.useState(!1),[E,I]=i.useState(null),[A,T]=i.useState(""),[R,K]=i.useState(!1),[Y,_]=i.useState(null),[J,q]=i.useState(""),[Q,z]=i.useState(""),[H,W]=i.useState(!1),[B,se]=i.useState(!1),L=i.useRef(null),ae=i.useRef(null),O=i.useRef(!1),[V,X]=i.useState(null),[re,me]=i.useState(null),[G,he]=i.useState(""),[ye,ge]=i.useState(!1),[$e,ee]=i.useState(null),Z=!!t.writeFile,ie=!!t.createDirectory,Me=!!t.rename,oe=!!t.delete,xe=i.useCallback((we,ze)=>{X(we),me(ze),he(we==="rename"&&ze.name||""),ge(!1)},[]),[pe,je]=i.useState(null),[ce,Ye]=i.useState(""),mt=i.useRef(!1),Ie=i.useRef(null),le=fe(we=>we.sendMessage),Xe=fe(we=>we.currentSessionId),{currentProviderId:Ne,currentModelId:Se,currentAgentName:qe,currentVariant:rt}=et(),We=at(we=>we.getSessionAgentSelection),_e=at(we=>we.getAgentModelForSession),Ke=at(we=>we.getAgentModelVariantForSession),xt=ke(we=>we.setActiveMainTab),nt=ke(we=>we.setMainTabGuard),{inputBarOffset:Pt,isKeyboardOpen:Tt}=ke();i.useEffect(()=>{const we=()=>{mt.current=!1,Ie.current=null};return document.addEventListener("mouseup",we),()=>document.removeEventListener("mouseup",we)},[]),i.useEffect(()=>{je(null),Ye(""),nt(null),z(""),W(!1)},[E?.path,nt]),i.useEffect(()=>{if(!pe)return;const we=tt=>{const Ee=tt.target;document.querySelector("[data-comment-ui]")?.contains(Ee)||Ee.closest(".cm-gutterElement")||Ee.closest("[data-sonner-toast]")||Ee.closest("[data-sonner-toaster]")||(je(null),Ye(""))},ze=setTimeout(()=>{document.addEventListener("click",we)},100);return()=>{clearTimeout(ze),document.removeEventListener("click",we)}},[pe]);const _t=i.useCallback((we,ze)=>{const tt=we.split(`
200
- `),Ee=Math.max(1,ze.start),ot=Math.min(tt.length,ze.end);return Ee>ot?"":tt.slice(Ee-1,ot).join(`
201
- `)},[]),Ve=i.useCallback(async()=>{if(!pe||!ce.trim()||!E)return;if(!Xe){U.error("Select a session to send comment");return}const we=We(Xe)||qe,ze=we?_e(Xe,we):null,tt=ze?.providerId||Ne,Ee=ze?.modelId||Se;if(!tt||!Ee){U.error("Select a model to send comment");return}const ot=we&&tt&&Ee?Ke(Xe,we,tt,Ee)??rt:rt,ft=_t(A,pe),Bt=_r(E.path)||"text",Wt=E.name,vs=pe.start,is=pe.end,Jt=`Comment on \`${Wt}\` lines ${vs}-${is}:
202
- \`\`\`${Bt}
203
- ${ft}
204
- \`\`\`
205
-
206
- ${ce}`;Ye(""),je(null),xt("chat");try{await le(Jt,tt,Ee,we,void 0,void 0,void 0,ot)}catch(Ot){console.error("Failed to send comment",Ot)}},[pe,ce,E,A,Xe,Ne,Se,qe,rt,_t,le,xt,We,_e,Ke]),dt=i.useCallback((we,ze)=>{const tt=ze.filter(Ee=>Ee&&typeof Ee.name=="string"&&Ee.name.length>0).filter(Ee=>a||!Ee.name.startsWith(".")).filter(Ee=>l||!WS(Ee.name)).map(Ee=>{const ot=Ee.name,ft=sr(Ee.path||`${we}/${ot}`),Bt=Ee.isDirectory?"directory":"file",Wt=Bt==="file"&&ot.includes(".")?ot.split(".").pop()?.toLowerCase():void 0;return{name:ot,path:ft,type:Bt,extension:Wt}});return zS(tt)},[l,a]),vt=i.useCallback(async we=>{const ze=sr(we.trim());if(ze&&!(N.current.has(ze)||D.current.has(ze))){D.current=new Set(D.current),D.current.add(ze);try{const tt=!l;let Ee;r.isDesktop?Ee=(await t.listDirectory(ze,{respectGitignore:tt})).entries.map(Bt=>({name:Bt.name,path:Bt.path,isDirectory:Bt.isDirectory})):Ee=(await Fe.listLocalDirectory(ze,{respectGitignore:tt})).map(Bt=>({name:Bt.name,path:Bt.path,isDirectory:Bt.isDirectory}));const ot=dt(ze,Ee);N.current=new Set(N.current),N.current.add(ze),b(ft=>({...ft,[ze]:ot}))}catch{b(tt=>({...tt,[ze]:tt[ze]??[]}))}finally{D.current=new Set(D.current),D.current.delete(ze)}}},[t,dt,r.isDesktop,l]),ut=i.useCallback(async()=>{const we=sr(c.trim());we&&(N.current=new Set,D.current=new Set,S(new Set),b({}),await vt(we))},[c,vt]);i.useEffect(()=>{c&&(ut(),I(null),T(""),_(null),q(""),g(!1))},[c,ut]),i.useEffect(()=>{c&&ut()},[c,ut,l]);const At=i.useCallback(async we=>{if(we?.preventDefault(),!(!re||!V)){ge(!0);try{if(V==="createFile"){if(!G.trim())throw new Error("Filename is required");const ze=re.path,tt=ze?`${ze}/`:"",Ee=sr(`${tt}${G.trim()}`);if(!t.writeFile)throw new Error("Write not supported");(await t.writeFile(Ee,"")).success&&(U.success("File created"),await ut())}else if(V==="createFolder"){if(!G.trim())throw new Error("Folder name is required");const ze=re.path,tt=ze?`${ze}/`:"",Ee=sr(`${tt}${G.trim()}`);(await t.createDirectory(Ee)).success&&(U.success("Folder created"),await ut())}else if(V==="rename"){if(!G.trim())throw new Error("Name is required");const ze=re.path,tt=ze.split("/").slice(0,-1).join("/"),Ee=tt?`${tt}/`:"",ot=sr(`${Ee}${G.trim()}`);t.rename?(await t.rename(ze,ot)).success&&(U.success("Renamed successfully"),await ut(),E?.path===ze&&I(null)):U.error("Rename not supported")}else V==="delete"&&(t.delete?(await t.delete(re.path)).success&&(U.success("Deleted successfully"),await ut(),(E?.path===re.path||E?.path.startsWith(re.path+"/"))&&(I(null),T(""))):U.error("Delete not supported"));X(null)}catch(ze){U.error(ze instanceof Error?ze.message:"Operation failed")}finally{ge(!1)}}},[V,re,G,t,ut,E]),Rt=i.useCallback((we,ze)=>{const tt=we.trim().toLowerCase();if(!tt)return 0;const Ee=ze.toLowerCase();let ot=0,ft=-1,Bt=0;for(let Wt=0;Wt<tt.length;Wt+=1){const vs=tt[Wt];if(!vs||vs===" ")continue;const is=Ee.indexOf(vs,ft+1);if(is===-1)return null;const Jt=is-ft-1;if(Jt===0?Bt+=1:Bt=0,ot+=10,ot+=Math.max(0,18-is),ot-=Math.max(0,Jt),is===0)ot+=12;else{const Ot=Ee[is-1];(Ot==="/"||Ot==="_"||Ot==="-"||Ot==="."||Ot===" ")&&(ot+=10)}ot+=Bt>0?12:0,ft=is}return ot+=Math.max(0,24-Math.round(Ee.length/3)),ot},[]);i.useEffect(()=>{c&&ut()},[c,ut,l]),i.useEffect(()=>{if(!c){M([]),P(!1);return}const we=p.trim();if(!we){M([]),P(!1);return}const ze=we.toLowerCase();let tt=!1;return P(!0),u(c,we,150,{includeHidden:a,respectGitignore:!l}).then(Ee=>{if(tt)return;const ft=Ee.filter(Wt=>l||!US(Wt.path)).map(Wt=>{const vs=Wt.relativePath||Wt.name||Wt.path,is=Rt(ze,vs);return is===null?null:{hit:Wt,score:is,labelLength:vs.length}}).filter(Boolean);ft.sort((Wt,vs)=>vs.score-Wt.score||Wt.labelLength-vs.labelLength||Wt.hit.path.localeCompare(vs.hit.path));const Bt=ft.map(({hit:Wt})=>({name:Wt.name,path:sr(Wt.path),type:"file",extension:Wt.extension,relativePath:Wt.relativePath}));M(Bt)}).catch(()=>{tt||M([])}).finally(()=>{tt||P(!1)}),()=>{tt=!0}},[c,p,Rt,u,a,l]);const as=i.useCallback(async we=>{if(t.readFile)return(await t.readFile(we)).content??"";const ze=await fetch(`/api/fs/read?path=${encodeURIComponent(we)}`);if(!ze.ok){const tt=await ze.json().catch(()=>({error:ze.statusText}));throw new Error(tt.error||"Failed to read file")}return ze.text()},[t]),Ct=i.useMemo(()=>A.length>lo?`${A.slice(0,lo)}
207
-
208
- … truncated …`:A,[A]),$t=i.useMemo(()=>Q!==Ct,[Q,Ct]),Mt=i.useCallback(async()=>{if(!E||!t.writeFile){U.error("Saving not supported");return}if($t){W(!0);try{if(!(await t.writeFile(E.path,Q))?.success)throw new Error("Failed to write file");T(Q)}catch(we){U.error(we instanceof Error?we.message:"Save failed")}finally{W(!1)}}},[Q,t,$t,E]);i.useEffect(()=>{if(!$t){nt(null);return}const we=ze=>O.current?(O.current=!1,!0):(se(!0),ae.current=ze,!1);return nt(we),()=>{ke.getState().mainTabGuard===we&&nt(null)}},[$t,nt]),i.useEffect(()=>{const we=ze=>{Ls(ze)&&ze.key.toLowerCase()==="s"&&(ze.preventDefault(),H||Mt())};return window.addEventListener("keydown",we),()=>window.removeEventListener("keydown",we)},[H,Mt]);const Gt=i.useCallback(async we=>{if(O.current)O.current=!1;else if($t){se(!0),L.current=we;return}I(we),_(null),q("");const ze=Co(we.path);n&&g(!0);const tt=we.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&ze&&!tt){T(""),K(!0);return}if(!r.isDesktop&&ze&&!tt){T(""),K(!1);return}K(!0);try{const Ee=await as(we.path);T(Ee),z(Ee.length>lo?`${Ee.slice(0,lo)}
209
-
210
- … truncated …`:Ee)}catch(Ee){T(""),z(""),_(Ee instanceof Error?Ee.message:"Failed to read file")}finally{K(!1)}},[$t,n,as,r.isDesktop]),Dt=i.useCallback(()=>{const we=L.current,ze=ae.current;if(L.current=null,ae.current=null,O.current=!0,se(!1),z(Ct),we){Gt(we);return}ze&&(nt(null),ke.getState().setActiveMainTab(ze))},[Ct,Gt,nt]),qt=i.useCallback(async()=>{const we=L.current,ze=ae.current;if(L.current=null,ae.current=null,O.current=!0,se(!1),await Mt(),we){await Gt(we);return}ze&&(nt(null),ke.getState().setActiveMainTab(ze))},[Gt,Mt,nt]),St=i.useCallback(async we=>{const ze=sr(we);S(tt=>{const Ee=new Set(tt);return Ee.has(ze)?Ee.delete(ze):Ee.add(ze),Ee}),N.current.has(ze)||await vt(ze)},[vt]),Lt=i.useCallback((we,ze)=>{const tt=k[we]??[];return tt.map((Ee,ot)=>{const ft=Ee.type==="directory",Bt=ft&&v.has(Ee.path),Wt=E?.path===Ee.path,vs=ft&&D.current.has(Ee.path),is=ot===tt.length-1;return e.jsxs("li",{className:"relative",children:[ze>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),is&&e.jsx("span",{className:"absolute top-3.5 bottom-0 left-[-13px] w-[2px] bg-background"})]}),e.jsxs("div",{className:"group relative flex items-center",onContextMenu:Jt=>{!Me&&!Z&&!ie&&!oe||(Jt.preventDefault(),ee(Ee.path))},children:[e.jsxs("button",{type:"button",onClick:()=>{ft?St(Ee.path):Gt(Ee)},className:F("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors pr-8 select-none",Wt?"bg-accent/70":"hover:bg-accent/40"),children:[ft?vs?e.jsx(Ft,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):Bt?e.jsx(sx,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(rx,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Su(Ee.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:Ee.path,children:Ee.name})]}),(Me||Z||ie||oe)&&e.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 focus-within:opacity-100",children:e.jsxs(ts,{open:$e===Ee.path,onOpenChange:Jt=>ee(Jt?Ee.path:null),children:[e.jsx(ss,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(nx,{className:"h-4 w-4"})})}),e.jsxs(rs,{align:"end",onCloseAutoFocus:()=>ee(null),children:[Me&&e.jsxs(jt,{onClick:Jt=>{Jt.stopPropagation(),xe("rename",Ee)},children:[e.jsx(Xn,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(jt,{onClick:Jt=>{Jt.stopPropagation(),navigator.clipboard.writeText(Ee.path),U.success("Path copied")},children:[e.jsx(Js,{className:"mr-2 h-4 w-4"})," Copy Path"]}),ft&&(Z||ie)&&e.jsxs(e.Fragment,{children:[e.jsx(Is,{}),Z&&e.jsxs(jt,{onClick:Jt=>{Jt.stopPropagation(),xe("createFile",Ee)},children:[e.jsx(Dc,{className:"mr-2 h-4 w-4"})," New File"]}),ie&&e.jsxs(jt,{onClick:Jt=>{Jt.stopPropagation(),xe("createFolder",Ee)},children:[e.jsx(el,{className:"mr-2 h-4 w-4"})," New Folder"]})]}),oe&&e.jsxs(e.Fragment,{children:[e.jsx(Is,{}),e.jsxs(jt,{onClick:Jt=>{Jt.stopPropagation(),xe("delete",Ee)},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]})})]}),ft&&Bt&&e.jsx("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:Lt(Ee.path,ze+1)})]},Ee.path)})},[k,v,Gt,E?.path,St,xe,Z,ie,Me,oe,$e,ee]),be=!!(E?.path&&Co(E.path)),Pe=!!(E?.path&&E.path.toLowerCase().endsWith(".svg")),Oe=i.useMemo(()=>{if(!E?.path)return"";const we=sr(E.path);if(d&&we.startsWith(d)){const ze=we.slice(d.length);return ze.startsWith("/")?ze.slice(1):ze}return we},[E?.path,d]),st=!!(E&&(!be||Pe)&&A.length>0),ne=!!(E&&Oe.length>0),Ae=!!(E&&!be&&t.writeFile&&A.length<=lo),te=i.useMemo(()=>{if(!E?.path)return[ju(s)];const we=[ju(s)],ze=BS(E.path);return ze&&we.push(ze),w&&we.push(Pn.lineWrapping),we},[s,E?.path,w]),Ce=E?.path&&be?r.isDesktop?Pe?`data:${ml(E.path)};utf8,${encodeURIComponent(A)}`:J:Pe?`data:${ml(E.path)};utf8,${encodeURIComponent(A)}`:`/api/fs/raw?path=${encodeURIComponent(E.path)}`:"";i.useEffect(()=>{let we=!1;return(async()=>{if(!r.isDesktop||!E?.path||!be||Pe){q("");return}_(null);try{if(t.readFileBinary){const ft=await t.readFileBinary(E.path);we||q(ft.dataUrl);return}const Ee=(await Ss(()=>import("./vendor-.bun-CaD8MAGl.js").then(ft=>ft.de),__vite__mapDeps([0,1]))).convertFileSrc;if(!Ee)return;const ot=Ee(E.path,"asset");we||q(ot)}catch(tt){we||(q(""),_(tt instanceof Error?tt.message:"Failed to read file"))}finally{we||K(!1)}})(),()=>{we=!0}},[t,be,Pe,r.isDesktop,E?.path]);const De=()=>e.jsx(ps,{open:!!V,onOpenChange:we=>!we&&X(null),children:e.jsxs(hs,{children:[e.jsxs(ys,{children:[e.jsxs(bs,{children:[V==="createFile"&&"Create File",V==="createFolder"&&"Create Folder",V==="rename"&&"Rename",V==="delete"&&"Delete"]}),e.jsxs(ks,{children:[V==="createFile"&&`Create a new file in ${re?.path??"root"}`,V==="createFolder"&&`Create a new folder in ${re?.path??"root"}`,V==="rename"&&`Rename ${re?.name}`,V==="delete"&&`Are you sure you want to delete ${re?.name}? This action cannot be undone.`]})]}),V!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(bt,{value:G,onChange:we=>he(we.target.value),placeholder:V==="rename"?"New name":"Name",onKeyDown:we=>{we.key==="Enter"&&At()},autoFocus:!0})}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"outline",onClick:()=>X(null),disabled:ye,children:"Cancel"}),e.jsx(ve,{variant:V==="delete"?"destructive":"default",onClick:()=>{At()},disabled:ye||V!=="delete"&&!G.trim(),children:ye?e.jsx(Ft,{className:"animate-spin"}):V==="delete"?"Delete":"Confirm"})]})]})}),He=()=>!pe||!E?null:e.jsx("div",{"data-comment-ui":!0,className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-background flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Rs,{value:ce,onChange:we=>{Ye(we.target.value);const ze=we.target;ze.style.height="auto";const Ee=20*5+8;ze.style.height=`${Math.min(ze.scrollHeight,Ee)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!n,rows:1,onKeyDown:we=>{we.key==="Enter"&&(we.metaKey||we.ctrlKey)&&(we.preventDefault(),Ve()),we.key==="Escape"&&(we.preventDefault(),je(null),Ye(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[E.name,":",pe.start,"-",pe.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!n&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Zt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:we=>{ce.trim()&&(we.preventDefault(),Ve())},onClick:()=>{n||Ve()},disabled:!ce.trim(),className:F("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",ce.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Ha,{className:"h-[18px] w-[18px]"})})]})]})]})}),wt=e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[e.jsx(ps,{open:B,onOpenChange:we=>{we||se(!0)},children:e.jsxs(hs,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Unsaved changes"}),e.jsx(ks,{children:"Save your edits before continuing?"})]}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"outline",onClick:()=>{qt()},disabled:H,className:"border-[var(--status-success-border)] bg-[var(--status-success-background)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]",children:"Save changes"}),e.jsx(ve,{variant:"destructive",onClick:Dt,children:"Discard"})]})]})}),e.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[n&&x&&e.jsx("button",{type:"button",onClick:()=>g(!1),"aria-label":"Back",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(El,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:E?E.name:"Select a file"}),E&&!n&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:Oe,children:Oe})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Ae&&e.jsx(ve,{variant:"ghost",size:"sm",onClick:()=>{Mt()},disabled:!$t||H,className:"h-5 w-5 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Zt()}+S)`,"aria-label":`Save (${Zt()}+S)`,children:H?e.jsx(Ft,{className:"h-4 w-4 animate-spin"}):e.jsx(ox,{className:"h-4 w-4"})}),Ae&&E&&!be&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),E&&!be&&e.jsx(ve,{variant:"ghost",size:"sm",onClick:()=>y(!w),className:F("h-5 w-5 p-0 transition-opacity",w?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:w?"Disable line wrap":"Enable line wrap",children:e.jsx(am,{className:"size-4"})}),(st||ne)&&(Ae||E&&!be)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),st&&e.jsx(ve,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(A),U.success("Copied")}catch{U.error("Copy failed")}},className:"h-5 w-5 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:e.jsx(cm,{className:"h-4 w-4"})}),ne&&e.jsx(ve,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(Oe),U.success("Copied")}catch{U.error("Copy failed")}},className:"h-5 w-5 p-0",title:`Copy file path (${Oe})`,"aria-label":`Copy file path (${Oe})`,children:e.jsx(ax,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(ht,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:E?R?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Ft,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):Y?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:Y}):be?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:Ce,alt:E?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):e.jsx("div",{className:"h-full",children:e.jsx(TS,{value:Q,onChange:z,extensions:te,className:"h-full",highlightLines:pe?{start:Math.min(pe.start,pe.end),end:Math.max(pe.start,pe.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(we,ze,tt)=>{if(!(tt instanceof MouseEvent)||tt.button!==0)return!1;tt.preventDefault();const Ee=we.state.doc.lineAt(ze.from).number;if(n&&pe&&!tt.shiftKey){const ot=Math.min(pe.start,pe.end,Ee),ft=Math.max(pe.start,pe.end,Ee);return je({start:ot,end:ft}),mt.current=!1,Ie.current=null,!0}if(mt.current=!0,Ie.current=Ee,pe&&tt.shiftKey){const ot=Math.min(pe.start,Ee),ft=Math.max(pe.end,Ee);je({start:ot,end:ft})}else je({start:Ee,end:Ee});return!0},mouseover:(we,ze,tt)=>{if(!(tt instanceof MouseEvent)||tt.buttons!==1||!mt.current||Ie.current===null)return!1;const Ee=we.state.doc.lineAt(ze.from).number,ot=Math.min(Ie.current,Ee),ft=Math.max(Ie.current,Ee);return je({start:ot,end:ft}),!1},mouseup:()=>(mt.current=!1,Ie.current=null,!1)}}})}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),pe&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:n?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:F("pointer-events-auto pb-2 transition-none w-full flex justify-center",n&&Tt?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:n&&!Tt&&Pt>0?`${Pt}px`:"16px"},"data-keyboard-avoid":"true",children:He()})})]}),Nt=!!(d&&k[d]),Xt=e.jsxs("section",{className:F("flex min-h-0 flex-col overflow-hidden",n?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[e.jsx("div",{className:F("flex flex-col gap-2 py-2",n?"px-3":"px-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Ws,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(bt,{ref:h,value:m,onChange:we=>f(we.target.value),placeholder:"Search files…",className:"h-8 pl-8 pr-8 typography-meta"}),m.trim().length>0&&e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{f(""),h.current?.focus()},children:e.jsx(es,{className:"h-4 w-4"})})]}),e.jsx(ve,{variant:"ghost",size:"sm",onClick:()=>xe("createFile",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File",children:e.jsx(Dc,{className:"h-4 w-4"})}),e.jsx(ve,{variant:"ghost",size:"sm",onClick:()=>xe("createFolder",{path:c,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder",children:e.jsx(el,{className:"h-4 w-4"})}),e.jsx(ve,{variant:"ghost",size:"sm",onClick:()=>{ut()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(Gr,{className:"h-4 w-4"})})]})}),e.jsx(ht,{outerClassName:"flex-1 min-h-0",className:F("py-2",n?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:C?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(Ft,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):j.length>0?j.map(we=>{const ze=E?.path===we.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{Gt(we)},className:F("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",ze?"bg-accent/70":"hover:bg-accent/40"),children:[Su(we.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:we.path,children:we.relativePath??we.path})]})},we.path)}):Nt?Lt(d,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading…"})})})]});return e.jsxs("div",{className:"flex h-full min-h-0 overflow-hidden bg-background",children:[De(),n?x?wt:Xt:e.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[o>=1024&&e.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:Xt}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:wt})]})]})},bp=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Pl},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Sr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:vn},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:xm},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:Wn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Kt},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:pn}],XS={},JS={},ZS={};bp.forEach(t=>{XS[t.id]=t.label,JS[t.id]=t.description,ZS[t.id]=t});const eN=t=>t==="doom_loop"||t==="external_directory"?"ask":"allow",tN=t=>{if(!Array.isArray(t))return[];const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;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},Nu=t=>{const r=tN(t);if(r.length===0)return;const s={};for(const l of r)l.permission&&((s[l.permission]||={})[l.pattern]=l.action);const n=s["*"]?.["*"],o=Object.keys(s);if(o.length===1&&o[0]==="*"&&Object.keys(s["*"]||{}).length===1&&s["*"]?.["*"])return s["*"]["*"];const a={};for(const l of o){const c=s[l],d=Object.keys(c);if(d.length===1&&d[0]==="*"&&l!=="*"){const u=c["*"],m=eN(l);if(n){if(u===n)continue}else if(u===m)continue;a[l]=u}else l==="*"&&d.length===1&&d[0]==="*"?a[l]=c["*"]:a[l]=c}return Object.keys(a).length>0?a:void 0},sN=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedAgentName:a,agents:l,setSelectedAgent:c,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=Zr(),{setSidebarOpen:p}=ke(),{isMobile:h}=Yt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=x?"bg-transparent":w?"bg-background":"bg-sidebar",v=()=>{const E="new-agent";let I=E,A=1;for(;l.some(T=>T.name===I);)I=`${E}-${A}`,A++;d({name:I,scope:"user"}),c(I),t?.(),h&&p(!1)},S=async E=>{if(on(E)){U.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${E.name}"?`)&&(await m(E.name)?U.success(`Agent "${E.name}" deleted successfully`):U.error("Failed to delete agent"))},k=async E=>{on(E)&&window.confirm(`Are you sure you want to reset agent "${E.name}" to its default configuration?`)&&(await m(E.name)?U.success(`Agent "${E.name}" reset to default`):U.error("Failed to reset agent"))},b=E=>{const I=E.name;let A=1,T=`${I}-copy`;for(;l.some(_=>_.name===T);)A++,T=`${I}-copy-${A}`;const R=E,K=E.model?.providerID&&E.model?.modelID?`${E.model.providerID}/${E.model.modelID}`:null,Y=E;d({name:T,scope:R.scope||"user",description:E.description,model:K,temperature:E.temperature,top_p:E.topP,prompt:E.prompt,mode:E.mode,permission:Nu(E.permission),disable:Y.disable}),c(T),h&&p(!1)},N=E=>{o(E.name),s(E)},D=async()=>{if(!r)return;const E=n.trim().replace(/\s+/g,"-");if(!E){U.error("Agent name is required");return}if(E===r.name){s(null);return}if(l.some(R=>R.name===E)){U.error("An agent with this name already exists");return}const I=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,A=r;await u({name:E,description:r.description,model:I,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:Nu(r.permission),disable:A.disable,scope:A.scope})?await m(r.name)?(U.success(`Agent renamed to "${E}"`),c(E)):U.error("Failed to remove old agent after rename"):U.error("Failed to rename agent"),s(null)},j=E=>{switch(E){case"primary":return e.jsx(gn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Am,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(Dm,{className:"h-3 w-3 text-primary"});default:return null}},M=l.filter(E=>!qm(E)),C=M.filter(on),P=M.filter(E=>!on(E));return e.jsxs("div",{className:F("flex h-full flex-col",y),children:[e.jsx("div",{className:F("border-b px-3",h?"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(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(cs,{className:"size-4"})})]})}),e.jsx(ht,{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(vo,{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:[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 Agents"}),C.map(E=>e.jsx(ku,{agent:E,isSelected:a===E.name,onSelect:()=>{c(E.name),t?.(),h&&p(!1)},onReset:()=>k(E),onDuplicate:()=>b(E),getAgentModeIcon:j},E.name))]}),P.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"}),P.map(E=>e.jsx(ku,{agent:E,isSelected:a===E.name,onSelect:()=>{c(E.name),t?.(),h&&p(!1)},onRename:()=>N(E),onDelete:()=>S(E),onDuplicate:()=>b(E),getAgentModeIcon:j},E.name))]})]})}),e.jsx(ps,{open:r!==null,onOpenChange:E=>!E&&s(null),children:e.jsxs(hs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Agent"}),e.jsxs(ks,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(bt,{value:n,onChange:E=>o(E.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:E=>{E.key==="Enter"&&D()}}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(wn,{onClick:D,children:"Rename"})]})]})})]})},ku=({agent:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l,getAgentModeIcon:c})=>{const d=t;return e.jsx("div",{className:F("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:s,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:t.name}),c(t.mode),(d.scope||on(t))&&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:on(t)?"system":d.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(ve,{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(Yr,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(jt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(Xn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(jt,{onClick:u=>{u.stopPropagation(),l()},children:[e.jsx(Js,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(jt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Ts,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(jt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Es({className:t,variant:r,...s}){return e.jsx(ve,{variant:r,size:"sm",className:F("h-6 px-2 text-xs",t),...s})}const rN=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),nN=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=rN.format(t);return r.endsWith(".0")?r.slice(0,-2):r},pc=({providerId:t,modelId:r,onChange:s,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:l}=et(),c=ke(H=>H.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=ke(),{favoriteModelsList:f,recentModelsList:p}=cc(),{isMobile:h}=Yt(),x=c||h,[g,w]=i.useState(!1),[y,v]=i.useState(new Set),[S,k]=i.useState(!1),[b,N]=i.useState(""),[D,j]=i.useState(0),M=i.useRef([]),C=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),P=i.useMemo(()=>C?a.filter(H=>C.has(String(H.id))):a,[a,C]),E=()=>w(!1),I=H=>{v(W=>{const B=new Set(W);return B.has(H)?B.delete(H):B.add(H),B})};i.useEffect(()=>{S||(N(""),j(0))},[S]),i.useEffect(()=>{j(0)},[b]);const A=H=>{const W=H?.name||H?.id||"",B=String(W);return B.length>40?B.substring(0,37)+"...":B},T=(H,W)=>{const B=`${H}/${W}`;return l.get(B)},R=(H,W)=>{s(H,W),H&&W&&m(H,W),k(!1)},K=(H,W)=>{if(!b.trim())return!0;const B=b.toLowerCase();return H.toLowerCase().includes(B)||W.toLowerCase().includes(B)},Y=(H,W,B,se,L,ae)=>{const O=T(W,B),V=nN(O?.limit?.context),X=t===W&&r===B,re=u(W,B);return e.jsxs("div",{ref:me=>{M.current[L]=me},className:F("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",ae?"bg-accent":"hover:bg-accent/50"),onClick:()=>R(W,B),onMouseEnter:()=>j(L),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(H)}),V?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:V}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[X&&e.jsx(Qt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),d(W,B)},className:F("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",re?"text-yellow-500":"text-muted-foreground"),"aria-label":re?"Unfavorite":"Favorite",title:re?"Remove from favorites":"Add to favorites",children:re?e.jsx(Ar,{className:"h-3.5 w-3.5"}):e.jsx(On,{className:"h-3.5 w-3.5"})})]})]},`${se}-${W}-${B}`)},_=f.filter(({model:H,providerID:W})=>{if(C&&!C.has(W))return!1;const se=a.find(ae=>ae.id===W)?.name||W,L=A(H);return K(L,se)}),J=p.filter(({model:H,providerID:W})=>{if(C&&!C.has(W))return!1;const se=a.find(ae=>ae.id===W)?.name||W,L=A(H);return K(L,se)}),q=P.map(H=>{const B=(Array.isArray(H.models)?H.models:[]).filter(se=>{const L=A(se);return K(L,H.name||H.id||"")});return{...H,models:B}}).filter(H=>H.models.length>0),Q=_.length>0||J.length>0||q.length>0,z=()=>x?e.jsx(Bs,{open:g,onClose:E,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:H,providerID:W,modelID:B})=>{const se=W===t&&B===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",se?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(W,B),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{providerId:W,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(H)})]})}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),d(W,B)},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(Ar,{className:"h-4 w-4"})})]},`fav-mobile-${W}-${B}`)})})]}),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:H,providerID:W,modelID:B})=>{const se=W===t&&B===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",se?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(W,B),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{providerId:W,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(H)})]})}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),d(W,B)},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(On,{className:"h-4 w-4"})})]},`recent-mobile-${W}-${B}`)})})]}),P.map(H=>{const W=Array.isArray(H.models)?H.models:[];if(W.length===0)return null;const B=H.id===t,se=y.has(H.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:()=>I(H.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ns,{providerId:H.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:H.name}),B&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),se?e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(zs,{className:"h-3 w-3 text-muted-foreground"})]}),se&&e.jsx("div",{className:"border-t border-border/20",children:W.map(L=>{const ae=H.id===t&&L.id===r;return e.jsxs("div",{className:F("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:()=>{R(H.id,L.id),E()},children:e.jsx("span",{className:"font-medium truncate",children:A(L)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),d(H.id,L.id)},className:F("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(H.id,L.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(H.id,L.id)?"Unfavorite":"Favorite",children:u(H.id,L.id)?e.jsx(Ar,{className:"h-4 w-4"}):e.jsx(On,{className:"h-4 w-4"})}),ae&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},L.id)})})]},H.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{R("",""),E()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[x?e.jsxs("button",{type:"button",onClick:()=>w(!0),className:F("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:[t?e.jsx(Ns,{providerId:t,className:"h-3.5 w-3.5"}):e.jsx(Dr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:t&&r?`${t}/${r}`:"Select model..."})]}),e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(ts,{open:S,onOpenChange:k,children:[e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:F("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:[t?e.jsxs(e.Fragment,{children:[e.jsx(Ns,{providerId:t,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Dr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Dr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:t&&r?`${t}/${r}`:"Not selected"}),e.jsx(Ht,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(rs,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const H=[];_.forEach(({model:L,providerID:ae,modelID:O})=>{H.push({model:L,providerID:ae,modelID:O,section:"fav"})}),J.forEach(({model:L,providerID:ae,modelID:O})=>{H.push({model:L,providerID:ae,modelID:O,section:"recent"})}),q.forEach(L=>{L.models.forEach(ae=>{H.push({model:ae,providerID:L.id,modelID:ae.id,section:"provider"})})});const W=H.length,B=L=>{if(L.key==="ArrowDown"){L.preventDefault(),L.stopPropagation();const ae=(D+1)%Math.max(1,W);j(ae),setTimeout(()=>{M.current[ae]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(L.key==="ArrowUp"){L.preventDefault(),L.stopPropagation();const ae=(D-1+Math.max(1,W))%Math.max(1,W);j(ae),setTimeout(()=>{M.current[ae]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(L.key==="Enter"){L.preventDefault(),L.stopPropagation();const ae=H[D];ae&&R(ae.providerID,ae.modelID)}else L.key==="Escape"&&(L.preventDefault(),L.stopPropagation(),k(!1))};let se=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(Ws,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{type:"text",placeholder:"Search models",value:b,onChange:L=>N(L.target.value),onKeyDown:B,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(ht,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:F("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>R("",""),children:[e.jsx(es,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!t&&!r&&e.jsx(Qt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Is,{}),!Q&&b&&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(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Ar,{className:"h-4 w-4 text-primary"}),"Favorites"]}),_.map(({model:L,providerID:ae,modelID:O})=>{const V=se++;return Y(L,ae,O,"fav",V,D===V)})]}),J.length>0&&e.jsxs(e.Fragment,{children:[_.length>0&&e.jsx(Is,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(jr,{className:"h-4 w-4"}),"Recent"]}),J.map(({model:L,providerID:ae,modelID:O})=>{const V=se++;return Y(L,ae,O,"recent",V,D===V)})]}),(_.length>0||J.length>0)&&q.length>0&&e.jsx(Is,{}),q.map((L,ae)=>e.jsxs(i.Fragment,{children:[ae>0&&e.jsx(Is,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Ns,{providerId:L.id,className:"h-4 w-4 flex-shrink-0"}),L.name]}),L.models.map(O=>{const V=se++;return Y(O,L.id,O.id,"provider",V,D===V)})]},L.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"})]})})()})]}),z()]})},oN=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],Fr=t=>t==="allow"||t==="ask"||t==="deny",aN=t=>{if(Fr(t))return t;if(t&&typeof t=="object"&&!Array.isArray(t)){const r=t["*"];if(Fr(r))return r}},iN=t=>{if(Fr(t))return{entries:{"*":t}};if(!t||typeof t!="object"||Array.isArray(t))return{entries:{}};const r={};for(const[s,n]of Object.entries(t)){const o=aN(n);o!==void 0&&(r[s]=o)}return{entries:r}},lN=t=>{const r={...t},s=r["*"];return Fr(s)?(delete r["*"],{defaultOverride:s,overrides:r}):{defaultOverride:"default",overrides:r}},ai=t=>t==="doom_loop"||t==="external_directory"?"ask":"allow",ba=(t,r)=>r==="default"?ai(t):r,Cu=(t,r)=>{const s={...t};for(const[n,o]of Object.entries(t)){if(n==="*")continue;const a=ba(n,r),l=ai(n);if(!(Fr(o)&&o!==l)){if(Fr(o)&&o===a){delete s[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const c=o,d=Object.keys(c),u=c["*"];if(u!==void 0&&u!==l)continue;d.length===1&&d[0]==="*"&&u===a&&delete s[n]}}}return s},wp=t=>{if(!Array.isArray(t))return null;const r=[];for(const s of t){if(!s||typeof s!="object")continue;const n=s;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},cN=t=>{const r=wp(t);if(!r||r.length===0)return{entries:{}};const s={};for(const a of r)!a.permission||a.permission==="invalid"||a.pattern==="*"&&(s[a.permission]=a.action);const n=s["*"],o={};for(const[a,l]of Object.entries(s)){if(a==="*"){o[a]=l;continue}const c=ai(a);if(n){if(l===n)continue}else if(l===c)continue;o[a]=l}return{entries:o}},dN=()=>{const{selectedAgentName:t,getAgentByName:r,createAgent:s,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:l}=Zr();et();const c=t?r(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,x]=i.useState(""),[g,w]=i.useState("subagent"),[y,v]=i.useState(""),[S,k]=i.useState(void 0),[b,N]=i.useState(void 0),[D,j]=i.useState(""),[M,C]=i.useState("default"),[P,E]=i.useState({}),[I,A]=i.useState(""),[T,R]=i.useState(!1),K=gt(V=>V.currentDirectory??null),[Y,_]=i.useState([]),J=ko(V=>V.permissions);i.useEffect(()=>{let V=!1;return(async()=>{const re=await Fe.listToolIds({directory:K});if(V)return;const me=new Set(["write","patch","multiedit"]),G=re.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(G)).sort((he,ye)=>he.localeCompare(ye)))})(),()=>{V=!0}},[K]);const q=i.useMemo(()=>{const V=new Set;for(const X of o){const re=wp(X.permission);if(re)for(const me of re)me.permission&&me.permission!=="*"&&me.permission!=="invalid"&&V.add(me.permission)}for(const X of J.values())for(const re of X){const me=re.permission?.trim();me&&me!=="invalid"&&V.add(me)}for(const X of Y)V.add(X);return Array.from(V).sort((X,re)=>X.localeCompare(re))},[o,J,Y]),Q=i.useCallback(V=>{const X=P[V];if(Fr(X))return X;if(X&&typeof X=="object"&&!Array.isArray(X)){const re=X["*"];if(Fr(re))return re}},[P]),z=i.useCallback(V=>{const X=P[V];return!X||typeof X!="object"||Array.isArray(X)?0:Object.keys(X).filter(me=>me!=="*").length},[P]),H=i.useCallback((V,X)=>{V!=="*"&&E(re=>{const me={...re},G=me[V],he=ba(V,M),ye=ai(V),ge=X===he&&X===ye;if(G&&typeof G=="object"&&!Array.isArray(G)){const $e={...G};$e["*"]=X;const ee=Object.keys($e).filter(Z=>Z!=="*");return ge&&ee.length===0?(delete me[V],me):(me[V]=$e,me)}return ge?(delete me[V],me):(me[V]=X,me)})},[M]),W=i.useCallback(V=>{E(X=>{if(!(V in X))return X;const re={...X};return delete re[V],re})},[]),B=i.useMemo(()=>{const V=Object.entries(P).filter(([X])=>X!=="*");return V.sort(([X],[re])=>X.localeCompare(re)),V},[P]),se=i.useMemo(()=>{const V=new Set;for(const X of oN)V.add(X);for(const X of q)V.add(X);for(const X of Object.keys(P))V.delete(X);return Array.from(V).sort((X,re)=>X.localeCompare(re))},[q,P]),L=i.useCallback(V=>{const X=I.trim();if(!X)return;const re=ba(X,M);if(V===re){const me=M==="default"?"OpenCode defaults":`Default Permissions ("${M}")`;U.message(`"${X}" already matches ${me} (${re}).`),A("");return}H(X,V),A("")},[I,H,M]),ae=i.useCallback(V=>V==="webfetch"?"WebFetch":V==="websearch"?"WebSearch":V==="codesearch"?"CodeSearch":V==="doom_loop"?"Doom Loop":V==="external_directory"?"External Directory":V==="todowrite"?"TodoWrite":V==="todoread"?"TodoRead":V.split(/[_-]+/g).filter(Boolean).map(X=>X.charAt(0).toUpperCase()+X.slice(1)).join(" "),[]);i.useEffect(()=>{A("");const V=X=>{const re=lN(X);C(re.defaultOverride),E(Cu(re.overrides,re.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),x(a.description||""),w(a.mode||"subagent"),v(a.model||""),k(a.temperature),N(a.top_p),j(a.prompt||"");const X=iN(a.permission);V(X.entries);return}if(c&&t===c.name){x(c.description||""),w(c.mode||"subagent"),c.model?.providerID&&c.model?.modelID?v(`${c.model.providerID}/${c.model.modelID}`):v(""),k(c.temperature),N(c.topP),j(c.prompt||"");const X=cN(c.permission);V(X.entries)}},[a,d,c,t]);const O=async()=>{const V=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!V){U.error("Agent name is required");return}if(d&&o.some(X=>X.name===V)){U.error("An agent with this name already exists");return}R(!0);try{const X=y.trim(),re={name:V,description:h.trim()||void 0,mode:g,model:X===""?null:X,temperature:S,top_p:b,prompt:D.trim()||void 0,permission:(()=>{const G=Cu(P,M),he=M==="default"?G:{"*":M,...G},ye=["doom_loop","external_directory"];for(const $e of ye)if(!($e in he)){const ee=P[$e];Fr(ee)?he[$e]=ee:he[$e]=ba($e,M)}return Object.keys(he).length===0?d?void 0:null:he})(),scope:d?f:void 0};let me;d?(me=await s(re),me&&l(null)):me=await n(V,re),me?U.success(d?"Agent created successfully":"Agent updated successfully"):U.error(d?"Failed to create agent":"Failed to update agent")}catch(X){console.error("Error saving agent:",X);const re=X instanceof Error&&X.message?X.message:"An error occurred while saving";U.error(re)}finally{R(!1)}};return t?e.jsx(ht,{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":t})}),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(bt,{value:u,onChange:V=>m(V.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Os,{value:f,onValueChange:V=>p(V),children:[e.jsxs(_s,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Xs,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs($s,{align:"end",children:[e.jsx(ns,{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(Xs,{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(ns,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Rs,{value:h,onChange:V=>x(V.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(Es,{variant:g==="primary"?"default":"outline",onClick:()=>w("primary"),className:F("gap-2",g==="primary"?void 0:"text-foreground"),children:[e.jsx(gn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Es,{variant:g==="subagent"?"default":"outline",onClick:()=>w("subagent"),className:F("gap-2",g==="subagent"?void 0:"text-foreground"),children:[e.jsx(Dm,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Es,{variant:g==="all"?"default":"outline",onClick:()=>w("all"),className:F("gap-2",g==="all"?void 0:"text-foreground"),children:[e.jsx(Am,{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(pc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(V,X)=>{v(V&&X?`${V}/${X}`:"")}})]}),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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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 X=Math.max(0,(S!==void 0?S:.7)-.1);k(parseFloat(X.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(fi,{className:"h-3.5 w-3.5"})}),e.jsx(bt,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:V=>{const X=V.target.value;if(X===""){k(void 0);return}const re=parseFloat(X);!isNaN(re)&&re>=0&&re<=2&&k(re)},onBlur:V=>{const X=V.target.value;if(X!==""){const re=parseFloat(X);if(!isNaN(re)){const me=Math.max(0,Math.min(2,re));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 X=Math.min(2,(S!==void 0?S:.7)+.1);k(parseFloat(X.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(cs,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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 X=Math.max(0,(b!==void 0?b:.9)-.1);N(parseFloat(X.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(fi,{className:"h-3.5 w-3.5"})}),e.jsx(bt,{type:"text",inputMode:"decimal",value:b!==void 0?b:"",onChange:V=>{const X=V.target.value;if(X===""){N(void 0);return}const re=parseFloat(X);!isNaN(re)&&re>=0&&re<=1&&N(re)},onBlur:V=>{const X=V.target.value;if(X!==""){const re=parseFloat(X);if(!isNaN(re)){const me=Math.max(0,Math.min(1,re));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 X=Math.min(1,(b!==void 0?b:.9)+.1);N(parseFloat(X.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(cs,{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(Rs,{value:D,onChange:V=>j(V.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(ve,{size:"sm",variant:M==="default"?"default":"outline",onClick:()=>C("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(ve,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>C("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>C("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:M==="deny"?"default":"outline",onClick:()=>C("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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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(Os,{value:I,onValueChange:A,children:[e.jsx(_s,{className:"h-8 w-full sm:w-72",children:I?e.jsx("span",{className:"truncate",children:ae(I)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx($s,{children:se.map(V=>e.jsx(ns,{value:V,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:ae(V)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:V})]})},V))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:"outline",disabled:!I,onClick:()=>L("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:"outline",disabled:!I,onClick:()=>L("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:"outline",disabled:!I,onClick:()=>L("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),B.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:B.map(([V])=>{const X=Q(V),re=z(V),me=ae(V);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:V}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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']}),re>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",re," pattern rules preserved"]}):null]})})]})]}),e.jsxs(ve,{size:"sm",variant:"outline",onClick:()=>W(V),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(fi,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:X==="allow"?"default":"outline",onClick:()=>H(V,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:X==="ask"?"default":"outline",onClick:()=>H(V,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:X==="deny"?"default":"outline",onClick:()=>H(V,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},V)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ve,{size:"sm",variant:"default",onClick:O,disabled:T,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(qa,{className:"h-3 w-3"}),T?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(vo,{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"})]})})},uN=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedCommandName:a,commands:l,setSelectedCommand:c,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=Jr(),{setSidebarOpen:p}=ke(),{isMobile:h}=Yt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const y=x?"bg-transparent":w?"bg-background":"bg-sidebar",v=()=>{const C="new-command";let P=C,E=1;for(;l.some(I=>I.name===P);)P=`${C}-${E}`,E++;d({name:P,scope:"user"}),c(P),t?.(),h&&p(!1)},S=async C=>{if(Fn(C)){U.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${C.name}"?`)&&(await m(C.name)?U.success(`Command "${C.name}" deleted successfully`):U.error("Failed to delete command"))},k=async C=>{Fn(C)&&window.confirm(`Are you sure you want to reset command "${C.name}" to its default configuration?`)&&(await m(C.name)?U.success(`Command "${C.name}" reset to default`):U.error("Failed to reset command"))},b=C=>{const P=C.name;let E=1,I=`${P}-copy`;for(;l.some(A=>A.name===I);)E++,I=`${P}-copy-${E}`;d({name:I,scope:C.scope||"user",description:C.description,template:C.template,agent:C.agent,model:C.model,subtask:C.subtask}),c(I),h&&p(!1)},N=C=>{o(C.name),s(C)},D=async()=>{if(!r)return;const C=n.trim().replace(/\s+/g,"-");if(!C){U.error("Command name is required");return}if(C===r.name){s(null);return}if(l.some(E=>E.name===C)){U.error("A command with this name already exists");return}await u({name:C,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(U.success(`Command renamed to "${C}"`),c(C)):U.error("Failed to remove old command after rename"):U.error("Failed to rename command"),s(null)},j=l.filter(Fn),M=l.filter(C=>!Fn(C));return e.jsxs("div",{className:F("flex h-full flex-col",y),children:[e.jsx("div",{className:F("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",l.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(cs,{className:"size-4"})})]})}),e.jsx(ht,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Qr,{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:[j.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"}),[...j].sort((C,P)=>C.name.localeCompare(P.name)).map(C=>e.jsx(Mu,{command:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),h&&p(!1)},onReset:()=>k(C),onDuplicate:()=>b(C)},C.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((C,P)=>C.name.localeCompare(P.name)).map(C=>e.jsx(Mu,{command:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),h&&p(!1)},onRename:()=>N(C),onDelete:()=>S(C),onDuplicate:()=>b(C)},C.name))]})]})}),e.jsx(ps,{open:r!==null,onOpenChange:C=>!C&&s(null),children:e.jsxs(hs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Command"}),e.jsxs(ks,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(bt,{value:n,onChange:C=>o(C.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:C=>{C.key==="Enter"&&D()}}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(wn,{onClick:D,children:"Rename"})]})]})})]})},Mu=({command:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:l})=>e.jsx("div",{className:F("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:s,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:["/",t.name]}),(t.scope||Fn(t))&&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:Fn(t)?"system":t.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(ve,{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(Yr,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(jt,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(Xn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(jt,{onClick:c=>{c.stopPropagation(),l()},children:[e.jsx(Js,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(jt,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(Ts,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(jt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),vp=({agentName:t,onChange:r,className:s})=>{const{loadAgents:n,getVisibleAgents:o}=Zr(),a=o(),l=ke(x=>x.isMobile),{isMobile:c}=Yt(),d=l||c,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=x=>{r(x)},h=()=>d?e.jsx(Bs,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(x=>{const g=x.name===t;return e.jsxs("button",{type:"button",className:F("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",g?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(x.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:x.name}),x.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:x.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},x.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:F("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",s),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vo,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:t||"Select agent..."})]}),e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs("div",{className:F("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",s),children:[e.jsx(vo,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:t||"Not selected"}),e.jsx(Ht,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(rs,{className:"max-w-[300px]",children:[a.map(x=>e.jsx(jt,{className:"typography-meta",onSelect:()=>p(x.name),children:e.jsx("span",{className:"font-medium",children:x.name})},x.name)),e.jsx(jt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},mN=()=>{const{selectedCommandName:t,getCommandByName:r,createCommand:s,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:l}=Jr(),c=t?r(t):null,d=!!(a&&a.name===t&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,x]=i.useState(""),[g,w]=i.useState(""),[y,v]=i.useState(""),[S,k]=i.useState(""),[b,N]=i.useState(!1),[D,j]=i.useState(!1);i.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),x(a.description||""),w(a.agent||""),v(a.model||""),k(a.template||""),N(a.subtask||!1)):c&&(x(c.description||""),w(c.agent||""),v(c.model||""),k(c.template||""),N(c.subtask||!1))},[c,d,t,o,a]);const M=async()=>{const C=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!C){U.error("Command name is required");return}if(!S.trim()){U.error("Command template is required");return}if(d&&o.some(P=>P.name===C)){U.error("A command with this name already exists");return}j(!0);try{const P=g.trim(),E=y.trim(),I=S.trim(),A={name:C,description:h.trim()||void 0,agent:P===""?null:P,model:E===""?null:E,template:I,subtask:b,scope:d?f:void 0};let T;d?(T=await s(A),T&&l(null)):T=await n(C,A),T?U.success(d?"Command created successfully":"Command updated successfully"):U.error(d?"Failed to create command":"Failed to update command")}catch(P){console.error("Error saving command:",P),U.error("An error occurred while saving")}finally{j(!1)}};return t?e.jsx(ht,{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":`/${t}`})}),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(bt,{value:u,onChange:C=>m(C.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Os,{value:f,onValueChange:C=>p(C),children:[e.jsxs(_s,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Xs,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs($s,{align:"end",children:[e.jsx(ns,{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(Xs,{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(ns,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Rs,{value:h,onChange:C=>x(C.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(vp,{agentName:g,onChange:C=>w(C)}),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(pc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(C,P)=>{v(C&&P?`${C}/${P}`:"")}}),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:b,onChange:C=>N(C.target.checked),className:"sr-only"}),e.jsx("div",{className:F("w-5 h-5 rounded border-2 flex items-center justify-center",b?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:b&&e.jsx(Qt,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(Rs,{value:S,onChange:C=>k(C.target.value),placeholder:`Your command template here...
211
-
212
- Use $ARGUMENTS to reference user input.
213
- Use !\`shell command\` to inject shell output.
214
- 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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(ve,{size:"sm",variant:"default",onClick:M,disabled:D,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(qa,{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(Qr,{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"})]})})},fN=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:l,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=ir(),{setSidebarOpen:h}=ke(),{isMobile:x}=Yt(),[g,w]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||w(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const v=g?"bg-transparent":y?"bg-background":"bg-sidebar",S=()=>{const C="new-skill";let P=C,E=1;for(;l.some(I=>I.name===P);)P=`${C}-${E}`,E++;d({name:P,scope:"user",description:""}),c(P),t?.(),x&&h(!1)},k=async C=>{window.confirm(`Are you sure you want to delete skill "${C.name}"?`)&&(await m(C.name)?U.success(`Skill "${C.name}" deleted successfully`):U.error("Failed to delete skill"))},b=async C=>{const P=C.name;let E=1,I=`${P}-copy`;for(;l.some(T=>T.name===I);)E++,I=`${P}-copy-${E}`;const A=await p(C.name);if(!A){U.error("Failed to load skill details for duplication");return}d({name:I,scope:C.scope||"user",description:(A.sources.md.fields.includes("description"),""),instructions:""}),c(I),x&&h(!1)},N=C=>{o(C.name),s(C)},D=async()=>{if(!r)return;const C=n.trim().replace(/\s+/g,"-").toLowerCase();if(!C){U.error("Skill name is required");return}if(C===r.name){s(null);return}if(l.some(I=>I.name===C)){U.error("A skill with this name already exists");return}if(!await p(r.name)){U.error("Failed to load skill details"),s(null);return}await u({name:C,description:"Renamed skill",scope:r.scope})?await m(r.name)?(U.success(`Skill renamed to "${C}"`),c(C)):U.error("Failed to remove old skill after rename"):U.error("Failed to rename skill"),s(null)},j=l.filter(C=>C.scope==="project"),M=l.filter(C=>C.scope==="user");return e.jsxs("div",{className:F("flex h-full flex-col",v),children:[e.jsx("div",{className:F("border-b px-3",x?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",l.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(cs,{className:"size-4"})})]})}),e.jsx(ht,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Em,{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:[j.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"}),j.map(C=>e.jsx(Du,{skill:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),x&&h(!1)},onRename:()=>N(C),onDelete:()=>k(C),onDuplicate:()=>b(C)},C.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(C=>e.jsx(Du,{skill:C,isSelected:a===C.name,onSelect:()=>{c(C.name),t?.(),x&&h(!1)},onRename:()=>N(C),onDelete:()=>k(C),onDuplicate:()=>b(C)},C.name))]})]})}),e.jsx(ps,{open:r!==null,onOpenChange:C=>!C&&s(null),children:e.jsxs(hs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Skill"}),e.jsxs(ks,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(bt,{value:n,onChange:C=>o(C.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:C=>{C.key==="Enter"&&D()}}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(wn,{onClick:D,children:"Rename"})]})]})})]})},Du=({skill:t,isSelected:r,onSelect:s,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:F("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:s,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:t.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:t.scope}),t.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(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(ve,{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(Yr,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(jt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(Xn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(jt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Js,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(jt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function jp({tabs:t,value:r,onValueChange:s,className:n,isInteractive:o=!0,animate:a=!0}){const l=i.useRef(null),c=i.useRef(null),d=i.useCallback(()=>{const u=l.current,m=c.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:h}=m,x=Math.max(0,Math.min(100,p/f*100)),g=Math.max(0,Math.min(100,(p+h)/f*100));u.style.clipPath=`inset(0 ${Number(100-g).toFixed(2)}% 0 ${Number(x).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{d()},[d,r,t.length]),i.useEffect(()=>{const u=l.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:F("relative isolate w-full",n),children:[e.jsx("div",{ref:l,"aria-hidden":!0,className:F("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:t.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:t.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?c:null,type:"button",onClick:()=>{o&&s(u.value)},className:F("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:F("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const pN=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,hN=t=>{const r=t.trim(),s=r.match(/^git@github\.com:([^/\s]+)\/([^\s#]+)$/i);if(s)return`${s[1]}/${s[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},gN=async()=>{try{if(ds())return await Lr();const t=Ms()?.settings;if(t)return(await t.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}},xN=({open:t,onOpenChange:r})=>{const{scanRepo:s,loadCatalog:n,isScanning:o}=Ao(),a=Kn(C=>C.defaultGitIdentityId),l=Kn(C=>C.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[h,x]=i.useState([]),[g,w]=i.useState(null),[y,v]=i.useState(!1),[S,k]=i.useState([]),[b,N]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),w(null),v(!1),k([]),N(null),l(),(async()=>{const C=await gN(),P=Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[];x(P||[])})())},[t,l]);const D=i.useMemo(()=>{const C=u.trim(),P=f.trim();return h.some(E=>{const I=(E.source||"").trim(),A=(E.subpath||"").trim();return I===C&&A===P})},[h,u,f]),j=async()=>{const C=u.trim();if(!C){U.error("Repository source is required");return}c.trim()||d(hN(C)),v(!1),w(null);const P=await s({source:C,subpath:f.trim()||void 0,gitIdentityId:b||void 0});if(!P.ok){if(P.error?.kind==="authRequired"){if(Vt()){U.error("Private repositories are not supported in VS Code yet");return}const I=P.error.identities||[];if(k(I),!b&&I.length>0){const A=a&&a!=="global"&&I.some(T=>T.id===a)?a:I[0].id;N(A)}U.error("Authentication required. Select a Git identity and scan again.");return}U.error(P.error?.message||"Failed to scan repository");return}const E=P.items?.length||0;if(w(E),E===0){U.error("No skills found in this repository"),v(!1);return}k([]),v(!0),U.success(`Found ${E} skill(s)`)},M=async()=>{const C=c.trim(),P=u.trim(),E=f.trim();if(!C){U.error("Catalog name is required");return}if(!P){U.error("Repository source is required");return}if(!y){U.error("Scan the repository before adding this catalog");return}if(D){U.error("This catalog already exists");return}const I={id:pN(),label:C,source:P,...E?{subpath:E}:{},...b?{gitIdentityId:b}:{}},A=[...h,I];try{await fs({skillCatalogs:A}),x(A),U.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(T){U.error(T instanceof Error?T.message:"Failed to save catalog")}};return e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Add skills catalog"}),e.jsxs(ks,{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(bt,{value:c,onChange:C=>d(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(bt,{value:u,onChange:C=>{m(C.target.value),v(!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(bt,{value:f,onChange:C=>{p(C.target.value),v(!1),w(null)},placeholder:"e.g. skills"})]}),S.length>0&&!Vt()?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(Os,{value:b||"",onValueChange:C=>N(C),children:[e.jsx(_s,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:S.find(C=>C.id===b)?.name||"Choose identity"})}),e.jsx($s,{align:"start",children:S.map(C=>e.jsx(ns,{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,D?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(ve,{variant:"outline",onClick:()=>{j()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(fm,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(ve,{variant:"default",onClick:()=>{M()},disabled:!y||D||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},yN=({open:t,onOpenChange:r,conflicts:s,onConfirm:n})=>{const[o,a]=i.useState({});i.useEffect(()=>{if(!t)return;const d={};for(const u of s)d[u.skillName]="skip";a(d)},[t,s]);const l=d=>{const u={};for(const m of s)u[m.skillName]=d;a(u)},c=s.length>0&&s.every(d=>o[d.skillName]);return e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{className:"max-w-2xl",children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Skills already exist"}),e.jsx(ks,{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:[s.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>l("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:s.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(Os,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(_s,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs($s,{align:"end",children:[e.jsx(ns,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(ns,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(wn,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},bN=({open:t,onOpenChange:r,item:s})=>{const{installSkills:n,isInstalling:o}=Ao(),[a,l]=i.useState("user"),[c,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{t&&(l("user"),d(!1),m([]),p(null))},[t]);const h=async x=>{const g={skillDir:x.skillDir};s?.clawdhub&&(g.clawdhub={slug:s.clawdhub.slug,version:s.clawdhub.version});const w=await n({source:x.source,subpath:x.subpath,gitIdentityId:s?.gitIdentityId,scope:x.scope,selections:[g],conflictPolicy:"prompt",conflictDecisions:x.conflictDecisions});if(w.ok){U.success("Skill installed successfully"),r(!1);return}if(w.error?.kind==="conflicts"){p({source:x.source,subpath:x.subpath,scope:x.scope,skillDir:x.skillDir}),m(w.error.conflicts),d(!0);return}if(w.error?.kind==="authRequired"){U.error(w.error.message||"Authentication required");return}U.error(w.error?.message||"Failed to install skill")};return s?e.jsxs(e.Fragment,{children:[e.jsx(ps,{open:t,onOpenChange:r,children:e.jsxs(hs,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Install skill"}),e.jsxs(ks,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:s.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:s.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:s.warnings.map(x=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:x},x))})]}):null}),e.jsxs(Us,{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(Os,{value:a,onValueChange:x=>l(x),children:[e.jsx(_s,{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(Xs,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs($s,{align:"start",children:[e.jsx(ns,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(ns,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]})})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(ve,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(ve,{className:"w-full sm:w-auto",variant:"default",disabled:o||!s.installable,onClick:()=>{h({source:s.repoSource,subpath:s.repoSubpath,scope:a,skillDir:s.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(yN,{open:c,onOpenChange:d,conflicts:u,onConfirm:x=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:x}),d(!1))}})]}):null},wN=async()=>{try{if(ds())return await Lr();const t=Ms()?.settings;if(t)return(await t.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}},vN=({mode:t,onModeChange:r})=>{const{sources:s,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,isLoadingCatalog:c,lastCatalogError:d}=Ao(),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(!1),[g,w]=i.useState(null),[y,v]=i.useState(!1);i.useEffect(()=>{l()},[l]);const S=i.useMemo(()=>o?n[o]||[]:[],[n,o]),k=i.useMemo(()=>{const j=u.trim().toLowerCase();return j?S.filter(M=>{const C=M.skillName.toLowerCase(),P=(M.description||"").toLowerCase(),E=(M.frontmatterName||"").toLowerCase();return C.includes(j)||P.includes(j)||E.includes(j)}):S},[S,u]),b=i.useMemo(()=>s.find(j=>j.id===o)||null,[s,o]),N=!!(o&&o.startsWith("custom:")),D=async()=>{if(!(!o||!N)&&window.confirm("Remove this catalog?")){v(!0);try{const j=await wN(),C=(Array.isArray(j?.skillCatalogs)?j?.skillCatalogs:[]).filter(P=>P.id!==o);await fs({skillCatalogs:C}),await l({refresh:!0})}finally{v(!1)}}};return e.jsx(ht,{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(jp,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:t,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(Os,{value:o||"",onValueChange:j=>a(j),children:[e.jsx(_s,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:b?.label||"Select source"})}),e.jsx($s,{align:"start",children:s.map(j=>e.jsx(ns,{value:j.id,className:"pr-2 [&>span:first-child]:hidden",children:j.label},j.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ve,{type:"button",variant:"outline",onClick:()=>{l({refresh:!0})},disabled:c,className:"gap-2",children:[e.jsx(Gr,{className:"h-4 w-4"}),"Refresh"]}),N?e.jsxs(ve,{type:"button",variant:"outline",onClick:()=>{D()},disabled:y,className:"gap-2",children:[e.jsx(qs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(ve,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(cs,{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(bt,{value:u,onChange:j=>m(j.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:c?"Loading…":`${k.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:k.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"})]}):k.map(j=>{const M=j.installed?.isInstalled,C=j.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:j.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 (",C||"unknown",")"]}):null,j.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"})]}),j.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:j.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),j.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[j.clawdhub.owner?e.jsxs("span",{children:["by ",j.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qr,{className:"h-3 w-3"}),j.clawdhub.downloads?.toLocaleString()??0]}),(j.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(On,{className:"h-3 w-3"}),j.clawdhub.stars]}):null,e.jsxs("span",{children:["v",j.clawdhub.version]})]}):null,j.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:j.warnings.join(" · ")}):null]}),e.jsx(ve,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!j.installable,onClick:()=>{w(j),x(!0)},children:"Install"})]})},`${j.sourceId}:${j.skillDir}`)})}),e.jsx(xN,{open:f,onOpenChange:p}),e.jsx(bN,{open:h,onOpenChange:x,item:g})]})})},jN=()=>{const{selectedSkillName:t,getSkillByName:r,getSkillDetail:s,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=ir(),u=t?r(t):null,m=!!(l&&l.name===t&&!u),f=!!(t&&!u&&!l),[p,h]=i.useState("manual");i.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),i.useEffect(()=>{f&&d(null)},[f,d]);const x=m?e.jsx(jp,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,w]=i.useState(""),[y,v]=i.useState("user"),[S,k]=i.useState(""),[b,N]=i.useState(""),[D,j]=i.useState([]),[M,C]=i.useState([]),[P,E]=i.useState(!1),[I,A]=i.useState(!1),[T,R]=i.useState(""),[K,Y]=i.useState(""),[_,J]=i.useState(!1),[q,Q]=i.useState(""),[z,H]=i.useState(""),[W,B]=i.useState(null),[se,L]=i.useState(!1),[ae,O]=i.useState(""),V=m?g.trim()!==""||S.trim()!==""||b.trim()!==""||M.length>0:S!==T||b!==K,X=W?z!==ae:q.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)w(l.name||""),v(l.scope||"user"),k(l.description||""),N(l.instructions||""),R(""),Y(""),j([]),C(l.pendingFiles||[]);else if(t&&u){A(!0);try{const $e=await s(t);if($e){const ee=$e.sources.md;k(ee.description||""),N(ee.instructions||""),R(ee.description||""),Y(ee.instructions||""),j(ee.supportingFiles||[])}}catch($e){console.error("Failed to load skill details:",$e)}finally{A(!1)}}})()},[u,m,t,a,l,s,p]);const re=async()=>{const ge=m?g.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!ge){U.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(ge)||ge.length>64){U.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){U.error("Description is required");return}if(m&&a.some($e=>$e.name===ge)){U.error("A skill with this name already exists");return}E(!0);try{const $e={name:ge,description:S.trim(),instructions:b.trim()||void 0,scope:m?y:void 0,supportingFiles:m&&M.length>0?M:void 0};let ee;m?(ee=await n($e),ee&&(c(null),C([]),d(ge))):(ee=await o(ge,$e),ee&&(R(S.trim()),Y(b.trim()))),ee?U.success(m?"Skill created successfully":"Skill updated successfully"):U.error(m?"Failed to create skill":"Failed to update skill")}catch($e){console.error("Error saving skill:",$e),U.error("An error occurred while saving")}finally{E(!1)}},me=()=>{B(null),Q(""),H(""),O(""),J(!0)},G=async ge=>{if(B(ge),Q(ge),m){const ee=M.find(Z=>Z.path===ge)?.content||"";H(ee),O(ee),J(!0);return}if(t){L(!0),J(!0);try{const{readSupportingFile:$e}=ir.getState(),ee=await $e(t,ge);H(ee||""),O(ee||"")}catch{U.error("Failed to load file content"),H(""),O("")}finally{L(!1)}}},he=async()=>{if(!q.trim()){U.error("File name is required");return}const ge=q.trim(),$e=W!==null;if(m){if($e)C(ie=>ie.map(Me=>Me.path===W?{path:ge,content:z}:Me)),U.success(`File "${ge}" updated`);else{if(M.some(ie=>ie.path===ge)){U.error("A file with this name already exists");return}C(ie=>[...ie,{path:ge,content:z}]),U.success(`File "${ge}" added`)}J(!1),B(null);return}if(!t){U.error("No skill selected");return}const{writeSupportingFile:ee}=ir.getState();if(await ee(t,ge,z)){U.success($e?`File "${ge}" updated`:`File "${ge}" created`),J(!1),B(null);const ie=await s(t);ie&&j(ie.sources.md.supportingFiles||[])}else U.error($e?"Failed to update file":"Failed to create file")},ye=async ge=>{if(m){C($e=>$e.filter(ee=>ee.path!==ge)),U.success(`File "${ge}" removed`);return}if(t&&window.confirm(`Are you sure you want to delete "${ge}"?`)){const{deleteSupportingFile:$e}=ir.getState();if(await $e(t,ge)){U.success(`File "${ge}" deleted`);const Z=await s(t);Z&&j(Z.sources.md.supportingFiles||[])}else U.error("Failed to delete file")}};return m&&p==="external"?e.jsx(vN,{mode:p,onModeChange:h}):!t&&!l||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Em,{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"})]})}):I?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(ht,{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?x:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":t}),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(bt,{value:g,onChange:ge=>w(ge.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(Os,{value:y,onValueChange:ge=>v(ge),children:[e.jsxs(_s,{className:"!h-9 w-auto gap-1.5",children:[y==="user"?e.jsx(Xs,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:y})]}),e.jsxs($s,{align:"end",children:[e.jsx(ns,{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(Xs,{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(ns,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Lowercase letters, numbers, and hyphens only. Cannot start or end with hyphen."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Description ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Rs,{value:S,onChange:ge=>k(ge.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(Rs,{value:b,onChange:ge=>N(ge.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(ve,{variant:"outline",size:"sm",onClick:me,className:"gap-1.5",children:[e.jsx(cs,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const ge=m?M:D;return ge.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:ge.map($e=>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:()=>G($e.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:$e.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(ve,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:ee=>{ee.stopPropagation(),ye($e.path)},children:e.jsx(qs,{className:"h-3.5 w-3.5"})})]},$e.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ve,{size:"sm",variant:"default",onClick:re,disabled:P||!V,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(qa,{className:"h-3 w-3"}),P?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(ps,{open:_,onOpenChange:ge=>{J(ge),ge||B(null)},children:e.jsxs(hs,{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:W?"Edit Supporting File":"Add Supporting File"}),e.jsx(ks,{children:W?"Modify the file content":"Create a new file in the skill directory"})]}),se?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(bt,{value:q,onChange:ge=>Q(ge.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:W!==null}),!W&&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(Rs,{value:z,onChange:ge=>H(ge.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>{J(!1),B(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(wn,{onClick:he,disabled:se||!X,children:W?"Save Changes":"Create File"})]})]})})]})})},SN="__add_provider__",NN=({onItemSelect:t})=>{const r=et(u=>u.providers),s=et(u=>u.selectedProviderId),n=et(u=>u.setSelectedProvider),{isMobile:o}=Yt(),[a,l]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||l(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:F("flex h-full flex-col",d),children:[e.jsx("div",{className:F("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(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(SN),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(cs,{className:"size-4"})})]})}),e.jsx(ht,{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(Wn,{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===s;return e.jsx("div",{className:F("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),t?.()},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(Ns,{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)})})]})},kN=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Au=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const r=kN.format(t);return r.endsWith(".0")?r.slice(0,-2):r},En="__add_provider__",Qn=t=>typeof t=="object"&&t!==null,Eu=t=>{const r=typeof t.type=="string"?t.type:"",s=`${t.name??""} ${t.label??""}`.toLowerCase(),n=`${r} ${s}`.toLowerCase();return n.includes("oauth")?"oauth":n.includes("api")?"api":r.toLowerCase()},CN=t=>{if(!Qn(t))return{};const r={};for(const[s,n]of Object.entries(t))Array.isArray(n)&&(r[s]=n.filter(o=>Qn(o)));return r},MN=t=>{if(typeof t=="string")return{id:t};if(!Qn(t))return null;const r=typeof t.id=="string"&&t.id||typeof t.providerID=="string"&&t.providerID||typeof t.slug=="string"&&t.slug||typeof t.name=="string"&&t.name;if(!r)return null;const s=typeof t.name=="string"?t.name:void 0;return{id:r,name:s}},DN=t=>{let r=[];Array.isArray(t)?r=t:Qn(t)&&(Array.isArray(t.all)?r=t.all:Array.isArray(t.providers)&&(r=t.providers));const s=r.map(o=>MN(o)).filter(o=>!!o),n=new Set;return s.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},AN=()=>{const t=et(G=>G.providers),r=et(G=>G.selectedProviderId),s=et(G=>G.setSelectedProvider),n=et(G=>G.getModelMetadata),[o,a]=i.useState({}),[l,c]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,h]=i.useState(""),[x,g]=i.useState(null),[w,y]=i.useState({}),[v,S]=i.useState({}),[k,b]=i.useState([]),[N,D]=i.useState(!1),[j,M]=i.useState(null),[C,P]=i.useState(""),[E,I]=i.useState(""),[A,T]=i.useState(!1),[R,K]=i.useState({}),[Y,_]=i.useState(!1);i.useEffect(()=>{!r&&t.length>0&&s(t[0].id)},[t,r,s]),i.useEffect(()=>{let G=!0;return(async()=>{c(!0);try{const ye=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!ye.ok)throw new Error(`Auth methods request failed (${ye.status})`);const ge=await ye.json().catch(()=>({}));if(!G)return;a(CN(ge))}catch(ye){if(!G)return;console.error("Failed to load provider auth methods:",ye),U.error("Failed to load provider authentication methods")}finally{G&&c(!1)}})(),()=>{G=!1}},[]),i.useEffect(()=>{let G=!0;return(async()=>{D(!0),M(null);try{const ye=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!ye.ok)throw new Error(`Provider list request failed (${ye.status})`);const ge=await ye.json().catch(()=>({}));if(!G)return;b(DN(ge))}catch(ye){if(!G)return;console.error("Failed to load available providers:",ye),M("Unable to load provider list")}finally{G&&D(!1)}})(),()=>{G=!1}},[]);const J=i.useMemo(()=>new Set(t.map(G=>G.id)),[t]),q=i.useMemo(()=>k.filter(G=>!J.has(G.id)),[k,J]);i.useEffect(()=>{if(r===En){if(!C&&q.length>0){P(q[0].id);return}C&&!q.some(G=>G.id===C)&&P(q[0]?.id??"")}},[r,C,q]),i.useEffect(()=>{if(r===En){_(!0);return}_(!1)},[r]),i.useEffect(()=>{if(!r||r===En)return;let G=!1;return(async()=>{try{const ye=await fetch(`/api/provider/${encodeURIComponent(r)}/source`,{method:"GET",headers:{Accept:"application/json"}}),ge=await ye.json().catch(()=>null);if(!ye.ok)throw new Error(ge?.error||"Failed to load provider sources");const $e=ge?.sources??ge?.data?.sources;!G&&$e&&K(ee=>({...ee,[r]:$e}))}catch(ye){G||console.error("Failed to load provider sources:",ye)}})(),()=>{G=!0}},[r]);const Q=t.find(G=>G.id===r),z=r?R[r]:void 0,H=async G=>{const he=d[G]?.trim()??"";if(!he){U.error("API key is required");return}const ye=`api:${G}`;f(ye);try{const ge=await fetch(`/api/auth/${encodeURIComponent(G)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:he})}),$e=await ge.json().catch(()=>null);if(!ge.ok){const ee=$e?.error||"Failed to save API key";throw new Error(ee)}U.success("API key saved"),u(ee=>({...ee,[G]:""})),await po({scopes:["providers"],mode:"active"}),s(G)}catch(ge){console.error("Failed to save API key:",ge),U.error("Failed to save API key")}finally{f(null)}},W=async(G,he)=>{const ye=`oauth:${G}:${he}`;f(ye);try{const ge=await fetch(`/api/provider/${encodeURIComponent(G)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:he})}),$e=await ge.json().catch(()=>null);if(!ge.ok){const pe=$e?.error||"Failed to start OAuth flow";throw new Error(pe)}const ee=Qn($e)?$e:{},Z=Qn(ee.data)?ee.data:ee,ie=typeof Z.url=="string"&&Z.url||typeof Z.verification_uri_complete=="string"&&Z.verification_uri_complete||typeof Z.verification_uri=="string"&&Z.verification_uri||void 0,Me=typeof Z.instructions=="string"&&Z.instructions||typeof Z.message=="string"&&Z.message||void 0,oe=typeof Z.user_code=="string"&&Z.user_code||typeof Z.code=="string"&&Z.code||typeof Z.userCode=="string"&&Z.userCode||void 0;if(!ie&&!Me&&!oe)throw new Error("No OAuth details returned");const xe=`${G}:${he}`;S(pe=>({...pe,[xe]:{url:ie,instructions:Me,userCode:oe}})),ie&&window.open(ie,"_blank","noopener,noreferrer"),g({providerId:G,methodIndex:he}),U.message("Complete the OAuth flow in your browser")}catch(ge){console.error("Failed to start OAuth flow:",ge),U.error("Failed to start OAuth flow")}finally{f(null)}},B=async(G,he)=>{const ye=`${G}:${he}`,ge=w[ye]?.trim(),$e=`oauth-complete:${G}:${he}`;f($e);try{const ee={method:he};ge&&(ee.code=ge);const Z=await fetch(`/api/provider/${encodeURIComponent(G)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee)}),ie=await Z.json().catch(()=>null);if(!Z.ok){const Me=ie?.error||"Failed to complete OAuth flow";throw new Error(Me)}U.success("OAuth connection completed"),y(Me=>({...Me,[ye]:""})),g(null),await po({scopes:["providers"],mode:"active"}),s(G)}catch(ee){console.error("Failed to complete OAuth flow:",ee),U.error("Failed to complete OAuth flow")}finally{f(null)}},se=async G=>{try{await navigator.clipboard.writeText(G),U.success("OAuth link copied")}catch(he){console.error("Failed to copy OAuth link:",he),U.error("Failed to copy OAuth link")}},L=async G=>{try{await navigator.clipboard.writeText(G),U.success("Device code copied")}catch(he){console.error("Failed to copy device code:",he),U.error("Failed to copy device code")}},ae=async G=>{const he=`disconnect:${G}`;f(he);try{const ye=await fetch(`/api/provider/${encodeURIComponent(G)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),ge=await ye.json().catch(()=>null);if(!ye.ok){const $e=ge?.error||"Failed to disconnect provider";throw new Error($e)}U.success("Provider disconnected"),await po({scopes:["providers"],mode:"active"})}catch(ye){console.error("Failed to disconnect provider:",ye),U.error("Failed to disconnect provider")}finally{f(null)}},O=r===En;if(!O&&t.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(Wn,{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(O)return e.jsx(ht,{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."})]}),N?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:j}):q.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(ts,{open:A,onOpenChange:G=>{T(G),G||I("")},children:[e.jsx(ss,{asChild:!0,children:e.jsxs("button",{type:"button",className:F("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:C?"text-foreground":"text-muted-foreground",children:C?q.find(G=>G.id===C)?.name||C:"Select provider"}),e.jsx(Ht,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(rs,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:G=>G.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:G=>G.stopPropagation(),children:[e.jsx(Ws,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:G=>I(G.target.value),onKeyDown:G=>G.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(ht,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const G=q.filter(he=>{const ye=E.toLowerCase();return(he.name||he.id).toLowerCase().includes(ye)||he.id.toLowerCase().includes(ye)});return G.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):G.map(he=>e.jsxs(jt,{onSelect:()=>{P(he.id),T(!1),I("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:he.name||he.id}),C===he.id&&e.jsx(Qt,{className:"h-4 w-4 text-primary"})]},he.id))})()})]})]})]}),C&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),l?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{type:"password",value:d[C]??"",onChange:G=>u(he=>({...he,[C]:G.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>H(C),disabled:m===`api:${C}`,className:"h-8",children:m===`api:${C}`?"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 he=(o[C]??[]).filter(ye=>Eu(ye)==="oauth");return he.length===0?null:e.jsx("div",{className:"space-y-3",children:he.map((ye,ge)=>{const $e=ye.label||ye.name||`OAuth method ${ge+1}`,ee=`${C}:${ge}`,Z=x?.providerId===C&&x?.methodIndex===ge;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:$e}),(ye.description||ye.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(ye.description||ye.help)})]}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>W(C,ge),disabled:m===`oauth:${C}:${ge}`,className:"h-8",children:"Connect"})]}),v[ee]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[ee]?.instructions}),v[ee]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{value:v[ee]?.userCode,readOnly:!0}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>L(v[ee]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[ee]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{value:v[ee]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ve,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[ee]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>se(v[ee]?.url??""),className:"h-8",children:"Copy link"})]})]}),Z&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{value:w[ee]??"",onChange:ie=>y(Me=>({...Me,[ee]:ie.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(ve,{size:"sm",onClick:()=>B(C,ge),disabled:m===`oauth-complete:${C}:${ge}`,className:"h-8",children:m===`oauth-complete:${C}:${ge}`?"Saving…":"Complete"})]})]},`${C}-${$e}`)})})})()]})]})]})});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(Wn,{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:[],re=(o[Q.id]??[]).filter(G=>Eu(G)==="oauth"),me=V.filter(G=>{const he=typeof G?.name=="string"?G.name:"",ye=typeof G?.id=="string"?G.id:"",ge=p.trim().toLowerCase();return ge?he.toLowerCase().includes(ge)||ye.toLowerCase().includes(ge):!0});return e.jsx(ht,{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(Ns,{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.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),r!==En&&e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>_(G=>!G),className:"h-8",children:Y?"Hide":"Reconnect"})]}),!Y&&r!==En?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connected. Use Reconnect to update credentials."}):l?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{type:"password",value:d[Q.id]??"",onChange:G=>u(he=>({...he,[Q.id]:G.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>H(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."})]}),re.length>0&&e.jsx("div",{className:"space-y-3",children:re.map((G,he)=>{const ye=G.label||G.name||`OAuth method ${he+1}`,ge=`${Q.id}:${he}`,$e=x?.providerId===Q.id&&x?.methodIndex===he;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:ye}),(G.description||G.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(G.description||G.help)})]}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>W(Q.id,he),disabled:m===`oauth:${Q.id}:${he}`,className:"h-8",children:"Connect"})]}),v[ge]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[ge]?.instructions}),v[ge]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{value:v[ge]?.userCode,readOnly:!0}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>L(v[ge]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[ge]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{value:v[ge]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ve,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[ge]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>se(v[ge]?.url??""),className:"h-8",children:"Copy link"})]})]}),$e&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(bt,{value:w[ge]??"",onChange:ee=>y(Z=>({...Z,[ge]:ee.target.value})),placeholder:"Paste authorization code"}),e.jsx(ve,{size:"sm",onClick:()=>B(Q.id,he),disabled:m===`oauth-complete:${Q.id}:${he}`,className:"h-8",children:m===`oauth-complete:${Q.id}:${he}`?"Saving…":"Complete"})]})]},`${Q.id}-${ye}`)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Connection"}),z&&(z.auth.exists||z.user.exists||z.project.exists||z.custom?.exists)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Configured in: ",[z.auth.exists?"auth credentials":null,z.user.exists?"user config":null,z.project.exists?"project config":null,z.custom?.exists?"custom config":null].filter(Boolean).join(", ")]}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>ae(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.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(bt,{value:p,onChange:G=>h(G.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:me.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):me.map(G=>{const he=typeof G?.id=="string"?G.id:"",ye=typeof G?.name=="string"?G.name:he,ge=he?n(Q.id,he):void 0,$e=Au(ge?.limit?.context),ee=Au(ge?.limit?.output),Z=[];return ge?.tool_call&&Z.push({key:"tools",icon:Va,label:"Tool calling"}),ge?.reasoning&&Z.push({key:"reasoning",icon:Sr,label:"Reasoning"}),ge?.attachment&&Z.push({key:"image",icon:Nr,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:ye}),($e||ee)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[$e?`${$e} ctx`:"",$e&&ee?" · ":"",ee?`${ee} out`:""]}),Z.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:Z.map(({key:ie,icon:Me,label:oe})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:oe,"aria-label":oe,children:e.jsx(Me,{className:"h-3 w-3"})},ie))})]},he)})})]})]})})},EN={branch:Kt,briefcase:_l,house:Ol,graduation:Ll,code:Ys,heart:ym},IN={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},PN=({onItemSelect:t})=>{const{selectedProfileId:r,defaultGitIdentityId:s,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:l,loadProfiles:c,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=Kn(),{setSidebarOpen:h}=ke(),{isMobile:x}=Yt(),[g,w]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{typeof window>"u"||w(typeof window.opencodeDesktop<"u")},[]);const v=p();i.useEffect(()=>{c(),d(),u(),m()},[c,d,u,m]);const S=j=>{a(`import:${j.host}:${j.username}`),t?.(),x&&h(!1)},k=g?"bg-transparent":y?"bg-background":"bg-sidebar",b=()=>{a("new"),t?.(),x&&h(!1)},N=async j=>{window.confirm(`Are you sure you want to delete profile "${j.name}"?`)&&(await l(j.id)?U.success(`Profile "${j.name}" deleted successfully`):U.error("Failed to delete profile"))},D=async j=>{const M=s===j?null:j;if(!await f(M)){U.error("Failed to update default identity");return}U.success(M?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:F("flex h-full flex-col",k),children:[e.jsx("div",{className:F("border-b px-3",x?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",n.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:b,"aria-label":"Create new profile",children:e.jsx(cs,{className:"size-4"})})]})}),e.jsxs(ht,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"System Default"}),e.jsx(Iu,{profile:o,isSelected:r==="global",isDefault:s==="global",onSelect:()=>{a("global"),t?.(),x&&h(!1)},onToggleDefault:()=>D("global"),onDelete:void 0,isReadOnly:!0})]}),n.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),n.length===0&&!o&&v.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Kt,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:n.map(j=>e.jsx(Iu,{profile:j,isSelected:r===j.id,isDefault:s===j.id,onSelect:()=>{a(j.id),t?.(),x&&h(!1)},onToggleDefault:()=>D(j.id),onDelete:()=>N(j)},j.id))}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Discovered Credentials"}),e.jsx("p",{className:"px-2 pb-2 typography-micro text-muted-foreground/60",children:"Found in ~/.git-credentials"}),v.map(j=>e.jsx(FN,{credential:j,onImport:()=>S(j)},`${j.host}-${j.username}`))]})]})]})},Iu=({profile:t,isSelected:r,isDefault:s=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=EN[t.icon||"branch"]||Kt,d=IN[t.color||""],u=t.authType||"ssh";return e.jsx("div",{className:F("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:n,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(c,{className:"w-4 h-4 flex-shrink-0",style:{color:d}}),e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:u}),s&&e.jsx("span",{className:"typography-micro text-primary bg-primary/12 px-1 rounded flex-shrink-0 leading-none pb-px border border-primary/25",children:"default"})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:u==="token"&&t.host?t.host:t.userEmail})]}),(o||!l&&a)&&e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(ve,{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","aria-label":"Profile actions",children:e.jsx(Yr,{className:"h-3.5 w-3.5"})})}),e.jsxs(rs,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(jt,{onClick:m=>{m.stopPropagation(),o()},children:s?"Unset default":"Set as default"}),!l&&a&&e.jsxs(jt,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},TN=t=>{const r=t.split("/");return r.length>=3?r[r.length-1]:t},FN=({credential:t,onImport:r})=>{const s=TN(t.host),n=t.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:s})}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n?t.host:t.username})]}),e.jsxs(ve,{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(qr,{className:"h-3 w-3"}),"Import"]})]})})},Pu=[{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)"}],RN=[{key:"branch",Icon:Kt,label:"Branch"},{key:"briefcase",Icon:_l,label:"Work"},{key:"house",Icon:Ol,label:"Personal"},{key:"graduation",Icon:Ll,label:"School"},{key:"code",Icon:Ys,label:"Code"}],LN=()=>{const{selectedProfileId:t,getProfileById:r,createProfile:s,updateProfile:n,deleteProfile:o}=Kn(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,A,T]=t.split(":");return{host:A,username:T}}return null},[t]),l=i.useMemo(()=>t&&t!=="new"&&!a?r(t):null,[t,r,a]),c=t==="new"||a!==null,d=t==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[h,x]=i.useState(""),[g,w]=i.useState("ssh"),[y,v]=i.useState(""),[S,k]=i.useState(""),[b,N]=i.useState("keyword"),[D,j]=i.useState("branch"),[M,C]=i.useState(!1);i.useEffect(()=>{if(a){const A=a.host.split("/"),T=A.length>=3?A[A.length-1]:a.host;m(T),p(a.username),x(""),w("token"),v(""),k(a.host),N("string"),j("code")}else c?(m(""),p(""),x(""),w("ssh"),v(""),k(""),N("keyword"),j("branch")):l&&(m(l.name),p(l.userName),x(l.userEmail),w(l.authType||"ssh"),v(l.sshKey||""),k(l.host||""),N(l.color||"keyword"),j(l.icon||"branch"))},[l,c,t,a]);const P=async()=>{if(!f.trim()||!h.trim()){U.error("User name and email are required");return}if(g==="token"&&!S.trim()){U.error("Host is required for token-based authentication");return}C(!0);try{const A={name:u.trim()||f.trim(),userName:f.trim(),userEmail:h.trim(),authType:g,sshKey:g==="ssh"&&y.trim()||null,host:g==="token"&&S.trim()||null,color:b,icon:D};let T;if(c)T=await s(A);else if(t)T=await n(t,A);else return;T?U.success(c?"Profile created successfully":"Profile updated successfully"):U.error(c?"Failed to create profile":"Failed to update profile")}catch(A){console.error("Error saving profile:",A),U.error("An error occurred while saving")}finally{C(!1)}},E=async()=>{if(!(!t||c)&&confirm("Are you sure you want to delete this profile?"))try{await o(t)?U.success("Profile deleted successfully"):U.error("Failed to delete profile")}catch(A){console.error("Error deleting profile:",A),U.error("An error occurred while deleting")}},I=i.useMemo(()=>Pu.find(T=>T.key===b)?.cssVar||"var(--syntax-keyword)",[b]);return t?e.jsx(ht,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:a?"Import Credential":c?"New Git Profile":d?"Global Identity":u||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:a?`Import token credential for ${a.host} - please fill in your email address`:c?"Create a new Git identity profile for your repositories":d?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!d&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(bt,{value:u,onChange:A=>m(A.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:Pu.map(A=>e.jsx("button",{onClick:()=>N(A.key),className:F("w-8 h-8 rounded-lg border-2 transition-all",b===A.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:A.cssVar},title:A.label},A.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:RN.map(A=>{const T=A.Icon;return e.jsx("button",{onClick:()=>j(A.key),className:F("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",D===A.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:A.label,children:e.jsx(T,{className:"w-4 h-4",style:{color:I}})},A.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(bt,{value:f,onChange:A=>p(A.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(bt,{type:"email",value:h,onChange:A=>x(A.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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:()=>w("ssh"),className:F("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",g==="ssh"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(ix,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>w("token"),className:F("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",g==="token"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(lx,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"Token (HTTPS)"})]})]})]}),g==="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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(bt,{value:y,onChange:A=>v(A.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)"})]}),g==="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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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(bt,{value:S,onChange:A=>k(A.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!c&&e.jsxs(ve,{size:"sm",variant:"destructive",onClick:E,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(qs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:F("flex gap-2",c&&"ml-auto"),children:e.jsxs(ve,{size:"sm",variant:"default",onClick:P,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(qa,{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(Xs,{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 Hi(t,r,s){return Math.min(s,Math.max(r,t))}const ln=Re.forwardRef(({value:t,onValueChange:r,min:s=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:l,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=Re.useRef(null);Re.useImperativeHandle(f,()=>p.current);const[h,x]=Re.useState(()=>String(t));Re.useEffect(()=>{document.activeElement!==p.current&&x(String(t))},[t]);const g=Re.useCallback(()=>{p.current?.focus()},[]),w=Re.useCallback(C=>{const P=Hi(C,s,n);r(P),x(String(P))},[n,s,r]),y=Re.useCallback(()=>{const C=Number(h);return Number.isFinite(C)?C:t},[h,t]),v=Re.useCallback(()=>{w(y()+o),g()},[w,y,g,o]),S=Re.useCallback(()=>{w(y()-o),g()},[w,y,g,o]),k=C=>{const P=C.target.value;x(P);const E=Number(P);Number.isFinite(E)&&r(Hi(E,s,n))},b=C=>{const P=Number(h);if(!Number.isFinite(P))x(String(t));else{const E=Hi(P,s,n);E!==P&&r(E),x(String(E))}c?.(C)},N=C=>{if(C.key==="ArrowUp"){C.preventDefault(),v();return}if(C.key==="ArrowDown"){C.preventDefault(),S();return}d?.(C)},D=y(),j=u||D<=s,M=u||D>=n;return e.jsxs("div",{className:F("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",l),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(s)?s:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:k,onBlur:b,onKeyDown:N,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:F("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:M,onClick:v,className:F("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(Wa,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:j,onClick:S,className:F("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(Ht,{className:"h-3.5 w-3.5"})})]})]})});ln.displayName="NumberInput";const ON=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Tu=[{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"}],Fu=[{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."}],Ru=[{id:"single",label:"Single file",description:"Show one file at a time in the Diff tab."},{id:"stacked",label:"All files",description:"Stack all changed files together in the Diff tab."}],hc=({visibleSettings:t})=>{const{isMobile:r}=Yt(),s=Po(),n=ke(j=>j.showReasoningTraces),o=ke(j=>j.setShowReasoningTraces),a=ke(j=>j.toolCallExpansion),l=ke(j=>j.setToolCallExpansion),c=ke(j=>j.fontSize),d=ke(j=>j.setFontSize),u=ke(j=>j.padding),m=ke(j=>j.setPadding),f=ke(j=>j.cornerRadius),p=ke(j=>j.setCornerRadius),h=ke(j=>j.inputBarOffset),x=ke(j=>j.setInputBarOffset),g=ke(j=>j.diffLayoutPreference),w=ke(j=>j.setDiffLayoutPreference),y=ke(j=>j.diffViewMode),v=ke(j=>j.setDiffViewMode),S=xr(j=>j.queueModeEnabled),k=xr(j=>j.setQueueMode),{themeMode:b,setThemeMode:N}=en(),D=j=>t?t.includes(j):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[D("theme")&&!Vt()&&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:ON.map(j=>e.jsx(Es,{variant:b===j.value?"default":"outline",className:F(b===j.value?void 0:"text-foreground"),onClick:()=>N(j.value),children:j.label},j.value))})]}),D("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:c,onChange:j=>d(Number(j.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(ln,{value:c,onValueChange:d,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Es,{type:"button",variant:"ghost",onClick:()=>d(100),disabled:c===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(Ts,{className:"h-3.5 w-3.5"})})]})]}),D("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:u,onChange:j=>m(Number(j.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:u}),e.jsx(Es,{type:"button",variant:"ghost",onClick:()=>m(100),disabled:u===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(Ts,{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:u,onChange:j=>m(Number(j.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(ln,{value:u,onValueChange:m,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Es,{type:"button",variant:"ghost",onClick:()=>m(100),disabled:u===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(Ts,{className:"h-3.5 w-3.5"})})]})]}),D("cornerRadius")&&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:"Input Field Corner Radius"})}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"32",step:"1",value:f,onChange:j=>p(Number(j.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":"Corner radius 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:[f,"px"]}),e.jsx(Es,{type:"button",variant:"ghost",onClick:()=>p(12),disabled:f===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(Ts,{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:"0",max:"32",step:"1",value:f,onChange:j=>p(Number(j.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","aria-label":"Corner radius in pixels"}),e.jsx(ln,{value:f,onValueChange:p,min:0,max:32,step:1,"aria-label":"Corner radius in pixels"}),e.jsx(Es,{type:"button",variant:"ghost",onClick:()=>p(12),disabled:f===12,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset corner radius",title:"Reset",children:e.jsx(Ts,{className:"h-3.5 w-3.5"})})]})]}),D("inputBarOffset")&&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 to avoid screen obstructions."})]}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:h,onChange:j=>x(Number(j.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:[h,"px"]}),e.jsx(Es,{type:"button",variant:"ghost",onClick:()=>x(0),disabled:h===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(Ts,{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:"0",max:"100",step:"5",value:h,onChange:j=>x(Number(j.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","aria-label":"Input bar offset in pixels"}),e.jsx(ln,{value:h,onValueChange:x,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(Es,{type:"button",variant:"ghost",onClick:()=>x(0),disabled:h===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(Ts,{className:"h-3.5 w-3.5"})})]})]}),D("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:Tu.find(j=>j.value===a)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Tu.map(j=>e.jsx(Es,{variant:a===j.value?"default":"outline",className:F(a===j.value?void 0:"text-foreground"),onClick:()=>l(j.value),children:j.label},j.value))})]}),D("diffLayout")&&!r&&!Vt()&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:Fu.map(j=>e.jsx(Es,{variant:g===j.id?"default":"outline",className:F(g===j.id?void 0:"text-foreground"),onClick:()=>w(j.id),children:j.label},j.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Fu.find(j=>j.id===g)?.description})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff view (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose whether the Diff tab defaults to a single file or all files."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:Ru.map(j=>e.jsx(Es,{variant:y===j.id?"default":"outline",className:F(y===j.id?void 0:"text-foreground"),onClick:()=>v(j.id),children:j.label},j.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Ru.find(j=>j.id===y)?.description})]})]}),D("dotfiles")&&!Vt()&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Hidden files (Chat)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Show or hide dotfiles in file lists and directory pickers."})]}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx("div",{className:"flex gap-1 w-fit",children:[{id:"hide",label:"Hide",value:!1},{id:"show",label:"Show",value:!0}].map(j=>e.jsx(Es,{variant:s===j.value?"default":"outline",className:F(s===j.value?void 0:"text-foreground"),onClick:()=>Rf(j.value),children:j.label},j.id))})})]}),D("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:n,onChange:j=>o(j.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),D("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:S,onChange:j=>k(j.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:S?`Enter queues messages, ${Zt()}+Enter sends immediately.`:`Enter sends immediately, ${Zt()}+Enter queues messages.`})]})]})},Lu="https://github.com/btriapitsyn/openchamber",_N=800,Sp=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=Ka(),{isMobile:a}=Yt(),l=o.info?.currentVersion||"unknown",c=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(s){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(U.success("You are on the latest version"),c.current=!1)},_N);return()=>clearTimeout(u)}},[o.checking,s,o.available,o.error]);const d=o.checking||s;return a?e.jsxs("div",{className:"w-full space-y-2",children:[e.jsxs("button",{onClick:()=>po(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ts,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",l]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:F("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(qr,{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:Lu,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ja,{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(Im,{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(rl,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(hl,{open:t,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]}):e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:l})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(na,{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:F("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(qr,{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:F("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:Lu,target:"_blank",rel:"noopener noreferrer",className:F("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(ja,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:F("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(rl,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(hl,{open:t,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})]})},$N=1440*60*1e3,Np=5,Ou=1440*60*1e3,Wi=t=>t.time?.updated??t.time?.created??0,_u=({sessions:t,currentSessionId:r,cutoffDays:s,keepRecent:n=Np,now:o=Date.now()})=>{if(!Array.isArray(t)||s<=0)return[];const a=o-s*$N,l=[...t].sort((d,u)=>Wi(u)-Wi(d)),c=new Set(l.slice(0,n).map(d=>d.id));return l.filter(d=>{if(!d?.id||c.has(d.id)||d.id===r||d.share)return!1;const u=Wi(d);return u?u<a:!1}).map(d=>d.id)},kp=t=>{const r=t?.autoRun!==!1,s=fe(g=>g.sessions),n=fe(g=>g.currentSessionId),o=fe(g=>g.isLoading),a=fe(g=>g.deleteSessions),l=ke(g=>g.autoDeleteEnabled),c=ke(g=>g.autoDeleteAfterDays),d=ke(g=>g.autoDeleteLastRunAt),u=ke(g=>g.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>c<=0?[]:_u({sessions:s,currentSessionId:n,cutoffDays:c}),[c,n,s]),x=i.useCallback(async({force:g=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!l||c<=0)&&!g)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const w=Date.now();if(!g&&d&&w-d<Ou)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(s.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const y=_u({sessions:s,currentSessionId:n,cutoffDays:c,now:w});if(y.length===0)return u(w),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(y,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[c,l,d,n,a,o,s,u]);return i.useEffect(()=>{if(!r||!l||c<=0||o||s.length===0)return;const g=Date.now();d&&g-d<Ou||x()},[c,l,d,r,o,s.length,x]),{candidates:h,isRunning:m,runCleanup:x,keepRecentCount:Np}},Ui=1,Vi=365,Cp=()=>{const{isMobile:t}=Yt(),r=ke(p=>p.autoDeleteEnabled),s=ke(p=>p.autoDeleteAfterDays),n=ke(p=>p.setAutoDeleteEnabled),o=ke(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(s));i.useEffect(()=>{l(String(s))},[s]);const{candidates:c,isRunning:d,runCleanup:u}=kp({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){U.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&U.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&U.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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:[t?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const h=p.target.value;if(l(h),h.trim()==="")return;const x=Number(h);if(!Number.isFinite(x))return;const g=Math.min(Vi,Math.max(Ui,Math.round(x)));o(g)},onBlur:()=>{if(a.trim()===""){l(String(s));return}const p=Number(a);if(!Number.isFinite(p)){l(String(s));return}const h=Math.min(Vi,Math.max(Ui,Math.round(p)));o(h),l(String(h))},"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(ln,{value:s,onValueChange:o,min:Ui,max:Vi,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(Es,{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]})]})},BN=10,zN=500,HN=20,WN=500,UN=30,VN=1e3,GN=()=>{const{isMobile:t}=Yt(),r=ke(h=>h.memoryLimitHistorical),s=ke(h=>h.memoryLimitViewport),n=ke(h=>h.memoryLimitActiveSession),o=ke(h=>h.setMemoryLimitHistorical),a=ke(h=>h.setMemoryLimitViewport),l=ke(h=>h.setMemoryLimitActiveSession),[c,d]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let x=null;if(ds())x=await Lr();else{const g=Ms()?.settings;if(g)try{const y=(await g.load())?.settings;y&&(x={memoryLimitHistorical:typeof y.memoryLimitHistorical=="number"?y.memoryLimitHistorical:void 0,memoryLimitViewport:typeof y.memoryLimitViewport=="number"?y.memoryLimitViewport:void 0,memoryLimitActiveSession:typeof y.memoryLimitActiveSession=="number"?y.memoryLimitActiveSession:void 0})}catch{}if(!x){const w=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});w.ok&&(x=await w.json())}}x&&(typeof x.memoryLimitHistorical=="number"&&o(x.memoryLimitHistorical),typeof x.memoryLimitViewport=="number"&&a(x.memoryLimitViewport),typeof x.memoryLimitActiveSession=="number"&&l(x.memoryLimitActiveSession))}catch(x){console.warn("Failed to load memory limits settings:",x)}finally{d(!1)}})()},[o,a,l]);const u=i.useCallback(async(h,x)=>{try{if(await fs({[h]:x}),!ds()){const g=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({[h]:x})});g.ok||console.warn(`Failed to save ${h} to server:`,g.status,g.statusText)}}catch(g){console.warn(`Failed to save ${h}:`,g)}},[]),m=i.useCallback(h=>{o(h),u("memoryLimitHistorical",h)},[o,u]),f=i.useCallback(h=>{a(h),u("memoryLimitViewport",h)},[a,u]),p=i.useCallback(h=>{l(h),u("memoryLimitActiveSession",h)},[l,u]);return c?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:"Message Memory"}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{sideOffset:8,className:"max-w-xs",children:["Control how many messages are kept in memory for performance optimization.",e.jsx("br",{}),"Lower values use less memory but may require reloading older messages."]})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Gi,{label:"Initial load limit",description:"Messages loaded when opening a session",value:r,defaultValue:an.HISTORICAL_MESSAGES,min:BN,max:zN,onChange:m,isMobile:t}),e.jsx(Gi,{label:"Background trim limit",description:"Max messages kept when switching away",value:s,defaultValue:an.VIEWPORT_MESSAGES,min:HN,max:WN,onChange:f,isMobile:t}),e.jsx(Gi,{label:"Active session limit",description:"Max messages for active session",value:n,defaultValue:ll,min:UN,max:VN,onChange:p,isMobile:t})]})]})},Gi=({label:t,description:r,value:s,defaultValue:n,min:o,max:a,onChange:l,isMobile:c})=>{const[d,u]=i.useState(String(s));i.useEffect(()=>{u(String(s))},[s]);const m=i.useCallback(h=>{const x=h.target.value;if(u(x),x.trim()==="")return;const g=Number(x);if(!Number.isFinite(g))return;const w=Math.min(a,Math.max(o,Math.round(g)));l(w)},[o,a,l]),f=i.useCallback(()=>{if(d.trim()===""){u(String(s));return}const h=Number(d);if(!Number.isFinite(h)){u(String(s));return}const x=Math.min(a,Math.max(o,Math.round(h)));l(x),u(String(x))},[d,s,o,a,l]),p=s===n;return e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:t}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:r})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!p&&e.jsxs("span",{className:"typography-meta text-muted-foreground/60",children:["(default: ",n,")"]}),c?e.jsx("input",{type:"number",inputMode:"numeric",value:d,onChange:m,onBlur:f,"aria-label":t,className:"h-8 w-20 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(ln,{value:s,onValueChange:l,min:o,max:a,step:10,"aria-label":t})]})]})})},$u="opencode",Bu="big-pickle",qN=(t,r)=>{if(t){const o=t.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===$u)?.models.some(o=>o.id===Bu))return{providerId:$u,modelId:Bu};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},Mp=()=>{const t=et(P=>P.setProvider),r=et(P=>P.setModel),s=et(P=>P.setAgent),n=et(P=>P.setCurrentVariant),o=et(P=>P.setSettingsDefaultModel),a=et(P=>P.setSettingsDefaultVariant),l=et(P=>P.setSettingsDefaultAgent),c=et(P=>P.settingsAutoCreateWorktree),d=et(P=>P.setSettingsAutoCreateWorktree),u=et(P=>P.providers),[m,f]=i.useState(),[p,h]=i.useState(),[x,g]=i.useState(),[w,y]=i.useState(!0),v=i.useMemo(()=>qN(m,u),[m,u]),S=i.useMemo(()=>Vt(),[]);i.useEffect(()=>{(async()=>{try{let E=null;if(ds())E=await Lr();else{const I=Ms()?.settings;if(I)try{const T=(await I.load())?.settings;T&&(E={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(!E){const A=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});A.ok&&(E=await A.json())}}if(E){const I=typeof E.defaultModel=="string"&&E.defaultModel.trim().length>0?E.defaultModel.trim():void 0,A=typeof E.defaultVariant=="string"&&E.defaultVariant.trim().length>0?E.defaultVariant.trim():void 0,T=typeof E.defaultAgent=="string"&&E.defaultAgent.trim().length>0?E.defaultAgent.trim():void 0;I!==void 0&&f(I),A!==void 0&&h(A),T!==void 0&&g(T)}}catch(E){console.warn("Failed to load defaults settings:",E)}finally{y(!1)}})()},[]);const k=i.useCallback(async(P,E)=>{const I=P&&E?`${P}/${E}`:void 0;f(I),h(void 0),a(void 0),n(void 0),o(I),P&&E&&u.find(T=>T.id===P)&&(t(P),r(E));try{if(await fs({defaultModel:I??"",defaultVariant:""}),!ds()){const A=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:I})});A.ok||console.warn("Failed to save default model to server:",A.status,A.statusText)}}catch(A){console.warn("Failed to save default model:",A)}},[u,n,t,r,o,a]),b="__default__",N=i.useCallback(async P=>{const E=P===b?void 0:P||void 0;h(E),a(E),n(E);try{await fs({defaultVariant:E??""})}catch(I){console.warn("Failed to save default variant:",I)}},[n,a]),D=i.useCallback(async P=>{const E=P||void 0;g(E),l(E),P&&s(P);try{await fs({defaultAgent:E??""})}catch(I){console.warn("Failed to save default agent:",I)}},[s,l]),j=i.useMemo(()=>{if(!v.providerId||!v.modelId)return[];const I=u.find(A=>A.id===v.providerId)?.models.find(A=>A.id===v.modelId)?.variants;return I?Object.keys(I):[]},[v.modelId,v.providerId,u]),M=j.length>0;i.useEffect(()=>{!M&&p&&(h(void 0),a(void 0),n(void 0),fs({defaultVariant:""}).catch(()=>{}))},[p,n,a,M]);const C=i.useCallback(async P=>{const E=P.target.checked;d(E);try{await fs({autoCreateWorktree:E})}catch(I){console.warn("Failed to save auto create worktree setting:",I)}},[d]);return w?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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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(pc,{providerId:v.providerId,modelId:v.modelId,onChange:k})]}),M&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default thinking"}),e.jsxs(Os,{value:p??b,onValueChange:N,children:[e.jsx(_s,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(bn,{placeholder:"Thinking"})}),e.jsxs($s,{children:[e.jsx(ns,{value:b,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),j.map(P=>e.jsx(ns,{value:P,className:"pr-2 [&>span:first-child]:hidden",children:P},P))]})]})]}),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(vp,{agentName:x||"",onChange:D})]})]}),(v.providerId||x)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",v.providerId&&e.jsxs("span",{className:"text-foreground",children:[v.providerId,"/",v.modelId,M?` (${p??"default"})`:""]}),v.providerId&&x&&" / ",x&&e.jsx("span",{className:"text-foreground",children:x})]}),!S&&e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:c,onChange:C}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Always create worktree for new sessions"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5 mt-1",children:c?`New session (Worktree): ${Zt()} + N • New session (Standard): Shift + ${Zt()} + N`:`New session (Standard): ${Zt()} + N • New session (Worktree): Shift + ${Zt()} + N`})]})]})},KN=()=>{const t=et(l=>l.settingsGitmojiEnabled),r=et(l=>l.setSettingsGitmojiEnabled),s=oi(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let c=null;if(ds())c=await Lr();else{const d=Ms()?.settings;if(d)try{const m=(await d.load())?.settings;m&&(c={gitmojiEnabled:typeof m.gitmojiEnabled=="boolean"?m.gitmojiEnabled:void 0})}catch{}if(!c){const u=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});u.ok&&(c=await u.json())}}c&&typeof c.gitmojiEnabled=="boolean"&&r(c.gitmojiEnabled)}catch(c){console.warn("Failed to load git settings:",c)}finally{o(!1)}})()},[r]);const a=i.useCallback(async l=>{const c=l.target.checked;r(c);try{await fs({gitmojiEnabled:c})}catch(d){console.warn("Failed to save gitmoji setting:",d)}},[r]);return n?null:e.jsxs("div",{className:"space-y-6",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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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-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:t,onChange:a}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Enable gitmoji picker"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5",children:"Adds a gitmoji selector to the Git commit message input."})]})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Files Overview"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Show gitignored files in the Files browser pane only."})]}),e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{className:"flex flex-col gap-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:s,onChange:l=>Rv(l.target.checked)}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Display gitignored files"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5",children:"Toggles gitignored files in the Files tree and search results."})]})})]})},QN=()=>{const t=zt(L=>L.getActiveProject()),r=zt(L=>L.updateWorktreeDefaults),s=t?.path??null,n=t?.worktreeDefaults,o=Kl(s),a=hf(s),{sessions:l,getWorktreeMetadata:c}=fe(),[d,u]=i.useState(n?.branchPrefix??""),[m,f]=i.useState(n?.baseBranch??"HEAD"),[p,h]=i.useState([]),[x,g]=i.useState(!1),[w,y]=i.useState(!1),[v,S]=i.useState(null),[k,b]=i.useState(null),[N,D]=i.useState([]),[j,M]=i.useState(!1),C=".openchamber",P=i.useCallback((L,ae)=>{const O=L.replace(/\\/g,"/").replace(/\/+$/,""),V=!O||O==="/"?`/${C}`:`${O}/${C}`;return ae?`${V}/${ae}`:V},[]),E=i.useCallback(async()=>{if(!(!s||v===!1))try{const ae=(await Un(s)).map(re=>Vn(s,re)),V=`${P(s,"")}/`,X=ae.filter(re=>re.path.startsWith(V));D(X)}catch{}},[s,v,P]);i.useEffect(()=>{if(!s)return;let L=!1;return y(!0),M(!0),S(null),b(null),D([]),(async()=>{try{const ae=await Or(s);if(L)return;if(S(ae),ae){const[O,V]=await Promise.all([Ja(s),Un(s).catch(()=>[])]);if(!L){O&&b({all:O.all,current:O.current});const X=V.map(he=>Vn(s,he)),me=`${`${s.replace(/\\/g,"/").replace(/\/+$/,"")}/${C}`}/`,G=X.filter(he=>he.path.startsWith(me));D(G)}}}catch{}finally{L||(y(!1),M(!1))}})(),()=>{L=!0}},[s]),i.useEffect(()=>{if(!s)return;let L=!1;return g(!0),(async()=>{try{const ae=await Sn(s);L||h(ae.length>0?ae:[""])}catch{L||h([""])}finally{L||g(!1)}})(),()=>{L=!0}},[s]),i.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const I=k??a,A=v??o,T=i.useMemo(()=>{const L=[],ae=I?.current?`Current (HEAD: ${I.current})`:"Current (HEAD)";return L.push({value:"HEAD",label:ae,group:"special"}),I&&(I.all.filter(X=>!X.startsWith("remotes/")).sort((X,re)=>X.localeCompare(re)).forEach(X=>{L.push({value:X,label:X,group:"local"})}),I.all.filter(X=>X.startsWith("remotes/")).map(X=>X.replace(/^remotes\//,"")).sort((X,re)=>X.localeCompare(re)).forEach(X=>{L.push({value:X,label:X,group:"remote"})})),L},[I]),R=i.useRef(null),K=i.useCallback(L=>{u(L),R.current=L},[]),Y=i.useCallback(L=>{t?.id&&(r(t.id,{branchPrefix:L}),R.current=null)},[t?.id,r]),_=i.useCallback(()=>{Y(d)},[d,Y]);i.useEffect(()=>()=>{R.current!==null&&t?.id&&r(t.id,{branchPrefix:R.current})},[t?.id,r]);const J=i.useCallback(L=>{f(L),t?.id&&r(t.id,{baseBranch:L})},[t?.id,r]),q=i.useCallback((L,ae)=>{h(O=>{const V=[...O];return V[L]=ae,V})},[]),Q=i.useCallback(()=>{h(L=>[...L,""])},[]),z=i.useCallback(L=>{h(ae=>ae.filter((O,V)=>V!==L))},[]),H=i.useCallback(async()=>{if(!s)return;const L=p.filter(ae=>ae.trim().length>0);await sf(s,L)},[s,p]),W=i.useCallback(()=>{H()},[H]),B=i.useCallback(L=>{const ae=L.path.replace(/\\/g,"/").replace(/\/+$/,""),O=l.filter(he=>{if(c(he.id)?.path===L.path)return!0;const ge=he.directory;return!!(ge&&ge.replace(/\\/g,"/").replace(/\/+$/,"")===ae)}),V=new Set(O.map(he=>he.id)),X=he=>{const ye=l.filter($e=>{const ee=$e.parentID;return ee&&he.has(ee)});if(ye.length===0)return[];const ge=new Set(ye.map($e=>$e.id));return[...ye,...X(ge)]},re=X(V),me=new Set,G=[...O,...re].filter(he=>me.has(he.id)?!1:(me.add(he.id),!0));qn.requestDelete({sessions:G,mode:"worktree",worktree:L})},[l,c]),se=i.useMemo(()=>l.map(L=>L.id).join(","),[l]);return i.useEffect(()=>{v&&s&&E()},[se,v,s,E]),s?w?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):A===!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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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(bt,{value:d,onChange:L=>K(L.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(it,{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(Os,{value:m,onValueChange:J,children:[e.jsx(_s,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(bn,{placeholder:"Select a branch"})}),e.jsxs($s,{children:[e.jsxs(mn,{children:[e.jsx(Bn,{children:"Default"}),T.filter(L=>L.group==="special").map(L=>e.jsx(ns,{value:L.value,children:L.label},L.value))]}),T.some(L=>L.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(Oa,{}),e.jsxs(mn,{children:[e.jsx(Bn,{children:"Local branches"}),T.filter(L=>L.group==="local").map(L=>e.jsx(ns,{value:L.value,children:L.label},L.value))]})]}),T.some(L=>L.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(Oa,{}),e.jsxs(mn,{children:[e.jsx(Bn,{children:"Remote branches"}),T.filter(L=>L.group==="remote").map(L=>e.jsx(ns,{value:L.value,children:L.label},L.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."]})]}),x?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((L,ae)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(bt,{value:L,onChange:O=>q(ae,O.target.value),onBlur:W,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{z(ae),setTimeout(H,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(es,{className:"h-4 w-4"})})]},ae)),e.jsxs("button",{type:"button",onClick:Q,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(cs,{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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(xs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(it,{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"})]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):N.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:N.map(L=>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:L.label||L.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:L.relativePath||L.path})]}),e.jsx("button",{type:"button",onClick:()=>B(L),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 ${L.branch||L.label}`,children:e.jsx(qs,{className:"h-4 w-4"})})]},L.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},YN=()=>{const t=ke(N=>N.nativeNotificationsEnabled),r=ke(N=>N.setNativeNotificationsEnabled),s=ke(N=>N.notificationMode),n=ke(N=>N.setNotificationMode),[o,a]=i.useState("default"),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,f]=i.useState(!1);i.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission);const N=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;c(N),(async()=>{if(!N){u(!1);return}try{const j=await navigator.serviceWorker.getRegistration();if(!j){u(!1);return}const M=await j.pushManager.getSubscription();u(!!M)}catch{u(!1)}})()},[]);const p=async N=>{if(N&&typeof Notification<"u"&&Notification.permission==="default")try{const D=await Notification.requestPermission();a(D),D==="granted"?r(!0):U.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(D){console.error("Failed to request notification permission:",D),U.error("Failed to request notification permission")}else r(!!(N&&o==="granted"))},h=typeof Notification<"u"&&Notification.permission==="granted",x=N=>{const D="=".repeat((4-N.length%4)%4),j=(N+D).replace(/-/g,"+").replace(/_/g,"/"),M=atob(j),C=new Uint8Array(M.length);for(let P=0;P<M.length;P+=1)C[P]=M.charCodeAt(P);return C},g=async(N,D,j)=>{let M=null;const C=new Promise((P,E)=>{M=setTimeout(()=>{E(new Error(j))},D)});try{return await Promise.race([N,C])}finally{M&&clearTimeout(M)}},w=async N=>{if(N.active)return;const D=N.installing||N.waiting;D&&D.state!=="activated"&&await g(new Promise(j=>{const M=()=>{D.state==="activated"&&(D.removeEventListener("statechange",M),j())};D.addEventListener("statechange",M),M()}),15e3,"Service worker activation timed out")},y=async()=>{if(typeof navigator.serviceWorker.register!="function")throw new Error("navigator.serviceWorker.register unavailable");const N=[{label:"no-options",opts:null},{label:"scope-root",opts:{scope:"/"}},{label:"type-classic",opts:{type:"classic"}},{label:"type-classic-scope",opts:{type:"classic",scope:"/"}},{label:"updateViaCache-none",opts:{type:"classic",updateViaCache:"none",scope:"/"}}];let D=null;for(const j of N)try{const M=j.opts?navigator.serviceWorker.register("/sw.js",j.opts):navigator.serviceWorker.register("/sw.js");return await g(M,1e4,`Service worker registration timed out (${j.label})`)}catch(M){D=M}throw D instanceof Error?D:new Error("Service worker registration failed")},v=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const N=await navigator.serviceWorker.getRegistration();if(N)return N;const D=await y();try{await D.update()}catch{}return await w(D),D},S=N=>{const D=N,j=[`type=${typeof N}`,`toString=${String(N)}`,`name=${String(D?.name??"")}`,`message=${String(D?.message??"")}`];let M="";try{M=JSON.stringify(N)}catch{}return{summary:j.filter(Boolean).join(" | "),json:M,stack:typeof D?.stack=="string"?D.stack:""}},k=async()=>{if(!l){U.error("Push notifications not supported");return}const N=Ms();if(!N?.push){U.error("Push API not available");return}f(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const A=await Notification.requestPermission();if(a(A),A!=="granted"){U.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){U.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const D=await N.push.getVapidPublicKey();if(!D?.publicKey){U.error("Failed to load push key");return}const j=await v();await w(j);const M=await j.pushManager.getSubscription();if(!("pushManager"in j)||!j.pushManager)throw new Error("PushManager unavailable (requires installed PWA + iOS 16.4+)");const P=(M??await g(j.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x(D.publicKey)}),15e3,"Push subscription timed out")).toJSON(),E=P.keys;if(!P.endpoint||!E?.p256dh||!E.auth)throw new Error("Push subscription missing keys");if(!(await g(N.push.subscribe({endpoint:P.endpoint,keys:{p256dh:E.p256dh,auth:E.auth},origin:typeof window<"u"?window.location.origin:void 0}),15e3,"Push subscribe request timed out"))?.ok){U.error("Failed to enable background notifications");return}u(!0),U.success("Background notifications enabled")}catch(D){console.error("[Push] Enable failed:",D);const j=S(D);U.error("Failed to enable background notifications",{description:j.summary})}finally{f(!1)}},b=async()=>{if(!l){u(!1);return}const N=Ms();if(!N?.push){U.error("Push API not available");return}f(!0);try{const j=await(await v()).pushManager.getSubscription();if(!j){u(!1);return}const M=j.endpoint;await j.unsubscribe(),await N.push.unsubscribe({endpoint:M}),u(!1),U.success("Background notifications disabled")}finally{f(!1)}};return br()?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Foreground Notifications"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Uses the browser Notification API while OpenChamber is open."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable foreground notifications"}),e.jsx(xo,{checked:t&&h,onCheckedChange:p,className:"data-[state=checked]:bg-status-info"})]}),t&&h&&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:"Notify even when visible"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"When off, only notifies when the tab is hidden or the window is not focused."})]}),e.jsx(xo,{checked:s==="always",onCheckedChange:N=>n(N?"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"&&!t&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Permission granted, but foreground notifications are disabled."}),e.jsxs("div",{className:"space-y-1 pt-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Background Notifications (Push)"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Uses push notifications; works when OpenChamber is closed."})]}),l?e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Desktop Chrome/Edge and Android support push in the browser. iOS requires an installed PWA."}):e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Push not supported in this browser."}),l&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable background notifications"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Opens chat with /?session=<id> deep link."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[m&&e.jsx("div",{className:"text-muted-foreground",children:e.jsx(If,{size:"sm"})}),e.jsx(xo,{checked:d,disabled:m,onCheckedChange:N=>{N?k():b()},className:"data-[state=checked]:bg-status-info"})]})]})]}):null},XN=()=>{const t=Ms()?.github,r=i.useCallback(async k=>{if(typeof window>"u")return;const b=window.opencodeDesktop;if(b?.openExternal)try{const N=await b.openExternal(k);if(N&&typeof N=="object"&&"success"in N&&N.success===!0)return}catch{}try{window.open(k,"_blank","noopener,noreferrer")}catch{}},[]),[s,n]=i.useState(!0),[o,a]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(null),[m,f]=i.useState(null),p=i.useRef(null),h=i.useCallback(()=>{p.current!=null&&(window.clearInterval(p.current),p.current=null),f(null)},[]),x=i.useCallback(async()=>{if(t){const N=await t.authStatus();return c(N),N}const k=await fetch("/api/github/auth/status",{method:"GET",headers:{Accept:"application/json"}}),b=await k.json().catch(()=>null);if(!k.ok||!b)throw new Error(b?.error||k.statusText||"Failed to load GitHub status");return c(b),b},[t]);i.useEffect(()=>{let k=!0;return(async()=>{try{await x()}catch(b){console.warn("Failed to load GitHub auth status:",b)}finally{k&&n(!1)}})(),()=>{k=!1,h()}},[x,h]);const g=i.useCallback(async()=>{a(!0);try{const k=t?await t.authStart():await(async()=>{const N=await fetch("/api/github/auth/start",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({})}),D=await N.json().catch(()=>null);if(!N.ok||!D||!("deviceCode"in D))throw new Error(D?.error||N.statusText);return D})();u(k),f(Math.max(1,k.interval)*1e3);const b=k.verificationUriComplete||k.verificationUri;r(b)}catch(k){console.error("Failed to start GitHub connect:",k),gr.error("Failed to start GitHub connect")}finally{a(!1)}},[r,t]),w=i.useCallback(async k=>{if(t)return t.authComplete(k);const b=await fetch("/api/github/auth/complete",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({deviceCode:k})}),N=await b.json().catch(()=>null);if(!b.ok||!N)throw new Error(N?.error||b.statusText);return N},[t]);i.useEffect(()=>{if(!(!d?.deviceCode||!m)&&p.current==null)return p.current=window.setInterval(()=>{(async()=>{try{const k=await w(d.deviceCode);if(k.connected){gr.success("GitHub connected"),u(null),h(),await x();return}k.status==="slow_down"&&f(b=>b?b+5e3:5e3),(k.status==="expired_token"||k.status==="access_denied")&&(gr.error(k.error||"GitHub authorization failed"),u(null),h())}catch(k){console.warn("GitHub polling failed:",k)}})()},m),()=>{p.current!=null&&(window.clearInterval(p.current),p.current=null)}},[d,m,w,x,h]);const y=i.useCallback(async()=>{a(!0);try{if(h(),u(null),t)await t.authDisconnect();else{const k=await fetch("/api/github/auth",{method:"DELETE",headers:{Accept:"application/json"}});if(!k.ok)throw new Error(k.statusText)}gr.success("GitHub disconnected"),await x()}catch(k){console.error("Failed to disconnect GitHub:",k),gr.error("Failed to disconnect GitHub")}finally{a(!1)}},[x,h,t]);if(s)return null;const v=!!l?.connected,S=l?.user;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"GitHub"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connect a GitHub account for in-app PR and issue workflows."})]}),v?e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border bg-background/50 px-4 py-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-4",children:[S?.avatarUrl?e.jsx("img",{src:S.avatarUrl,alt:S.login?`${S.login} avatar`:"GitHub avatar",className:"h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-header font-semibold text-foreground truncate",children:S?.name?.trim()||S?.login||"GitHub"}),S?.email?e.jsx("div",{className:"typography-body text-muted-foreground truncate",children:S.email}):null,e.jsxs("div",{className:"mt-1 flex items-center gap-2 typography-meta text-muted-foreground truncate",children:[e.jsx(ja,{className:"h-4 w-4"}),e.jsx("span",{className:"font-mono",children:S?.login||"unknown"})]}),l?.scope?e.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:["Scopes: ",l.scope]}):null]})]}),e.jsx(ve,{variant:"outline",onClick:y,disabled:o,children:"Disconnect"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-background/50 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Not connected"}),e.jsx(ve,{onClick:g,disabled:o,children:"Connect"})]}),d?e.jsxs("div",{className:"space-y-3 rounded-lg border bg-background/50 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Authorize OpenChamber"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:"In GitHub, enter this code:"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-mono text-lg tracking-widest text-foreground",children:d.userCode}),e.jsx(ve,{variant:"outline",asChild:!0,children:e.jsx("a",{href:d.verificationUriComplete||d.verificationUri,target:"_blank",rel:"noopener noreferrer",children:"Open GitHub"})})]}),e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Waiting for approval… (auto-refresh)"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(ve,{variant:"ghost",disabled:o,onClick:()=>{h(),u(null)},children:"Cancel"})})]}):null]})},JN=({section:t})=>{const{isMobile:r}=Yt(),s=r&&br();if(!t)return e.jsxs(ht,{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(hc,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Mp,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Cp,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Sp,{})})]});const n=()=>{switch(t){case"visual":return e.jsx(ZN,{});case"chat":return e.jsx(ek,{});case"sessions":return e.jsx(tk,{});case"git":return e.jsx(sk,{});case"github":return e.jsx(rk,{});case"notifications":return e.jsx(nk,{});default:return null}};return e.jsx(ht,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},ZN=()=>e.jsx(hc,{visibleSettings:["theme","fontSize","spacing","cornerRadius","inputBarOffset"]}),ek=()=>e.jsx(hc,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","queueMode"]}),tk=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Mp,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Cp,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(GN,{})})]}),sk=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(KN,{}),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(QN,{})]})]}),rk=()=>Vt()?null:e.jsx(XN,{}),nk=()=>e.jsx(YN,{}),ok=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"git",label:"Git",items:["Commit Messages","Worktree"],hideInVSCode:!0},{id:"github",label:"GitHub",items:["Connect","PRs","Issues"],hideInVSCode:!0},{id:"notifications",label:"Notifications",items:["Native"],webOnly:!0}],ak=({selectedSection:t,onSelectSection:r})=>{const{isMobile:s}=Yt(),n=s&&br(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>Vt(),[]),c=i.useMemo(()=>br(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>ok.filter(m=>!(m.webOnly&&!c||m.hideInVSCode&&l)),[c,l]),u=o?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:F("flex h-full flex-col",u),children:[e.jsx(ht,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:d.map(m=>{const f=t===m.id;return e.jsx("div",{className:F("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(Sp,{})})]})},ik=t=>{let r=bp.filter(o=>o.id!=="sessions");t&&(r=r.filter(o=>o.id!=="git-identities"));const s=r.find(o=>o.id==="settings"),n=r.filter(o=>o.id!=="settings");return s?[s,...n]:r},qi=200,Ki=500,lk=264,ck=940,Cl=({onClose:t,forceMobile:r})=>{const s=Yt(),n=r??s.isMobile,o=ke(O=>O.sidebarSection),a=ke(O=>O.setSidebarSection),l=i.useMemo(()=>o!=="sessions"?o:"settings",[o]),c=i.useCallback(O=>{a(O)},[a]),[d,u]=i.useState("visual"),[m,f]=i.useState(!1),[p,h]=i.useState(()=>typeof window<"u"?Math.min(Ki,Math.max(qi,Math.floor(window.innerWidth*.2))):lk),[x,g]=i.useState(!1),[w,y]=i.useState(!1),[v,S]=i.useState(0),k=i.useRef(null),b=i.useRef(0),N=i.useRef(p),[D,j]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),M=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),C=i.useMemo(()=>Vt(),[]),P=i.useMemo(()=>ik(C),[C]);i.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const O=k.current;if(!O)return;const V=new ResizeObserver(X=>{for(const re of X)S(re.contentRect.width)});return V.observe(O),S(O.clientWidth),()=>V.disconnect()},[]);const E=zt(O=>O.projects),I=zt(O=>O.activeProjectId),A=zt(O=>O.setActiveProject),T=i.useMemo(()=>[...E].sort((O,V)=>(O.label||O.path).localeCompare(V.label||V.path)),[E]),R=i.useMemo(()=>T.length===0?null:T.find(O=>O.id===I)??T[0],[I,T]),K=i.useCallback(O=>O.replace(/[-_]/g," ").replace(/\b\w/g,V=>V.toUpperCase()),[]),Y=i.useMemo(()=>{if(!R)return"Project";const O=R.label&&R.label.trim().length>0?R.label:R.path.split("/").filter(Boolean).pop()||R.path;return K(O)},[R,K]),_=T.length>0&&!C,J=v===0||v>=ck;i.useEffect(()=>{if(l==="agents"){setTimeout(()=>{Zr.getState().loadAgents()},0);return}if(l==="commands"){setTimeout(()=>{Jr.getState().loadCommands()},0);return}l==="skills"&&(ir.getState().loadSkills(),Ao.getState().loadCatalog())},[I,l]),i.useEffect(()=>{if(typeof window>"u")return;const O=()=>{if(!x){const V=Math.min(Ki,Math.max(qi,Math.floor(window.innerWidth*.2)));h(V)}};return window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[x]),i.useEffect(()=>{if(!w)return;const O=X=>{const re=X.clientX-b.current,me=Math.min(Ki,Math.max(qi,N.current+re));h(me),g(!0)},V=()=>y(!1);return window.addEventListener("pointermove",O),window.addEventListener("pointerup",V,{once:!0}),()=>{window.removeEventListener("pointermove",O),window.removeEventListener("pointerup",V)}},[w]);const q=O=>{y(!0),b.current=O.clientX,N.current=p,O.preventDefault()},Q=i.useCallback(async O=>{if(!O.target.closest("button, a, input, select, textarea")&&O.button===0&&D)try{const{getCurrentWindow:V}=await Ss(async()=>{const{getCurrentWindow:re}=await import("./vendor-.bun-CaD8MAGl.js").then(me=>me.df);return{getCurrentWindow:re}},__vite__mapDeps([0,1]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[D]),z=i.useCallback(async O=>{if(O.button===0&&D)try{const{getCurrentWindow:V}=await Ss(async()=>{const{getCurrentWindow:re}=await import("./vendor-.bun-CaD8MAGl.js").then(me=>me.df);return{getCurrentWindow:re}},__vite__mapDeps([0,1]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[D]),H=i.useCallback(O=>{c(O),f(!1)},[c]),W=i.useCallback(()=>{n&&f(!0)},[n]),B=()=>{switch(l){case"settings":return e.jsx(ak,{selectedSection:d,onSelectSection:O=>{u(O),W()}});case"agents":return e.jsx(sN,{onItemSelect:W});case"commands":return e.jsx(uN,{onItemSelect:W});case"skills":return e.jsx(fN,{onItemSelect:W});case"providers":return e.jsx(NN,{onItemSelect:W});case"git-identities":return e.jsx(PN,{onItemSelect:W});default:return null}},se=()=>{switch(l){case"agents":return e.jsx(dN,{});case"commands":return e.jsx(mN,{});case"skills":return e.jsx(jN,{});case"providers":return e.jsx(AN,{});case"git-identities":return e.jsx(LN,{});case"settings":return e.jsx(JN,{section:d});default:return null}},L=Zt(),ae=i.useMemo(()=>D&&M?"pl-[5.75rem]":"",[D,M]);return e.jsxs("div",{ref:k,className:F("flex h-full flex-col overflow-hidden",D?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:Q,className:F("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&ae,D?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[n&&m&&e.jsx("button",{type:"button",onClick:()=>f(!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(El,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsx("div",{className:F("flex items-center",n?"gap-1":"h-full"),children:e.jsx("div",{className:F("flex items-center gap-1",!n&&"p-1 bg-background/50 rounded-lg"),children:P.map(({id:O,label:V,icon:X})=>{const re=l===O,me=X;return n?e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{onClick:()=>H(O),className:F("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",re?"bg-secondary text-foreground shadow-sm":"text-muted-foreground"),"aria-pressed":re,"aria-label":V,children:e.jsx(me,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(it,{children:e.jsx("p",{children:V})})]},O):e.jsxs("button",{onClick:()=>H(O),onMouseDown:re?z:void 0,className:F("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",re?"app-region-drag bg-secondary text-foreground shadow-sm":"app-region-no-drag text-muted-foreground hover:bg-secondary/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-pressed":re,"aria-label":V,children:[e.jsx(me,{className:"h-4 w-4",weight:"regular"}),J&&e.jsx("span",{children:V})]},O)})})}),(t||_)&&e.jsxs("div",{className:F("flex items-center gap-2",n?"":"pr-3"),children:[_&&e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:Y,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(ur,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:Y,className:F("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:Y}),e.jsx(Ht,{className:"size-4 opacity-50"})]})}),e.jsx(rs,{align:"end",className:"w-auto",children:e.jsx(Pa,{value:R?.id??"",onValueChange:O=>{O&&A(O)},children:T.map(O=>{const V=O.label?.trim()?O.label.trim():O.path.split("/").filter(Boolean).pop()||O.path,X=K(V);return e.jsx(Ta,{value:O.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:X})},O.id)})})})]}),t&&e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close settings",className:F("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(es,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Close Settings (",L,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:n?m?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(gs,{children:se()})}):e.jsx("div",{className:F("flex-1 overflow-hidden",C?"bg-background":"bg-sidebar"),children:e.jsx(gs,{children:B()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:F("relative overflow-hidden border-r",D?"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:`${p}px`,minWidth:`${p}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:F("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(gs,{children:B()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(gs,{children:se()})})]})})]})},dk=()=>{const{isSidebarOpen:t,activeMainTab:r,setIsMobile:s,isSessionSwitcherOpen:n,isSettingsDialogOpen:o,setSettingsDialogOpen:a,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:c,multiRunLauncherPrefillPrompt:d}=ke(),{isMobile:u}=Yt(),[m,f]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");i.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),Iv({enabled:!0});const p=Ka(w=>w.checkForUpdates);i.useEffect(()=>{const w=setTimeout(()=>{p()},3e3);return()=>clearTimeout(w)},[p]),i.useEffect(()=>{ke.getState().isMobile!==u&&s(u)},[u,s]),i.useEffect(()=>{if(typeof window>"u")return;let w;const y=()=>{w!==void 0&&window.clearTimeout(w),w=window.setTimeout(()=>{ke.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",y),()=>{window.removeEventListener("resize",y),w!==void 0&&window.clearTimeout(w)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const w=document.documentElement;let y=0,v=!1,S=0,k=null;const b=ke.getState().setKeyboardOpen,N=()=>{k&&(k.style.setProperty("--oc-keyboard-avoid-offset","0px"),k.removeAttribute("data-keyboard-avoid-active"),k=null)},D=I=>{if(!I)return null;const A=I.closest("[data-keyboard-avoid]");if(A)return A;if(I.classList.contains("overlay-scrollbar-container")){const T=I.parentElement;if(T instanceof HTMLElement)return T}return I},j=()=>{y=0,v=!0,w.style.setProperty("--oc-keyboard-inset","0px"),b(!1)},M=()=>{const I=window.visualViewport,A=I?Math.round(I.height):window.innerHeight,T=I?Math.max(0,Math.round(I.offsetTop)):0;w.style.setProperty("--oc-visual-viewport-offset-top",`${T}px`);const R=document.activeElement,K=R?.tagName,_=K==="INPUT"||K==="TEXTAREA"||K==="SELECT"||!!R?.isContentEditable,J=Math.round(w.clientHeight||window.innerHeight),q=A+T,Q=Math.max(0,J-q),H=Q>=(_?120:180)?Q:0;if(v)H===0&&(v=!1),y=0;else if(y===0)H>0&&_&&(y=H);else{const L=!_&&A>S+6;H===0?(y=0,b(!1)):L?j():(H>0&&_||H>y)&&(y=H,b(!0))}w.style.setProperty("--oc-keyboard-inset",`${y}px`),S=A;const B=/iPad|iPhone|iPod/.test(navigator.userAgent)&&y>0?34:0;w.style.setProperty("--oc-keyboard-home-indicator",`${B}px`);const se=_?D(R):null;if(!u||!se||!R)N();else{se!==k&&(N(),k=se);const L=T+A,O=R.getBoundingClientRect().bottom-L,V=8,X=Math.max(y,H),re=O>V&&X>0?Math.min(O,X):0,me=k;me&&(me.style.setProperty("--oc-keyboard-avoid-offset",`${re}px`),me.setAttribute("data-keyboard-avoid-active","true"))}if(u&&_){const L=document.scrollingElement;L&&L.scrollTop!==0&&(L.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};M();const C=window.visualViewport;C?.addEventListener("resize",M),C?.addEventListener("scroll",M),window.addEventListener("resize",M),window.addEventListener("orientationchange",M);const P=I=>{const A=I.target;if(!A)return;const T=A.tagName;(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||A.isContentEditable)&&(v=!1),M()};document.addEventListener("focusin",P,!0);const E=I=>{const A=I.target;if(!A)return;const T=A.tagName;if(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||A.isContentEditable){const K=I.relatedTarget,Y=K?.tagName;if(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||K?.isContentEditable)return;j()}};return document.addEventListener("focusout",E,!0),()=>{C?.removeEventListener("resize",M),C?.removeEventListener("scroll",M),window.removeEventListener("resize",M),window.removeEventListener("orientationchange",M),document.removeEventListener("focusin",P,!0),document.removeEventListener("focusout",E,!0),N()}},[u]);const h=i.useMemo(()=>{switch(r){case"git":return e.jsx(wS,{});case"diff":return e.jsx(_w,{});case"terminal":return e.jsx(PS,{});case"files":return e.jsx(YS,{});default:return null}},[r]),x=r==="chat",g=o&&!u;return e.jsx(vv,{children:e.jsxs("div",{className:F("main-content-safe-area h-[100dvh]",u?"flex flex-col":"flex",m?"bg-transparent":"bg-background"),children:[e.jsx(Zw,{}),e.jsx(sv,{}),e.jsx(gv,{}),u?e.jsxs(e.Fragment,{children:[!(o||l)&&e.jsx(hd,{}),e.jsx("div",{className:F("flex flex-1 overflow-hidden",(o||l)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:n?e.jsx("div",{className:"flex-1 overflow-hidden bg-sidebar",children:e.jsx(gs,{children:e.jsx(La,{mobileVariant:!0})})}):e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:F("absolute inset-0",!x&&"invisible"),children:e.jsx(gs,{children:e.jsx(bo,{})})}),h&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(gs,{children:h})})]})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(gs,{children:e.jsx(Td,{initialPrompt:d,onCreated:()=>c(!1),onCancel:()=>c(!1)})})}),o&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(gs,{children:e.jsx(Cl,{onClose:()=>a(!1)})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:F("absolute inset-0 flex flex-col",(g||l)&&"invisible"),children:[e.jsx(hd,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(Kw,{isOpen:t,isMobile:u,children:e.jsx(La,{})}),e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:F("absolute inset-0",!x&&"invisible"),children:e.jsx(gs,{children:e.jsx(bo,{})})}),h&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(gs,{children:h})})]})]})]}),l&&e.jsx("div",{className:F("absolute inset-0 z-10",m?"bg-transparent":"bg-background"),children:e.jsx(gs,{children:e.jsx(Td,{initialPrompt:d,onCreated:()=>c(!1),onCancel:()=>c(!1)})})})]}),g&&e.jsx("div",{className:F("absolute inset-0 z-10",m?"bg-transparent":"bg-background"),children:e.jsx(gs,{children:e.jsx(Cl,{onClose:()=>a(!1)})})})]})]})})},uk=550,mk=1400,fk=280,pk=()=>{const t=Zs(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),s=i.useMemo(()=>{const I=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof I=="string"&&I.trim().length>0?I.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[l,c]=i.useState(0),d=i.useRef(null),u=fe(I=>I.currentSessionId),m=fe(I=>I.sessions),f=i.useMemo(()=>u?m.find(I=>I.id===u)?.title||"Session":null,[u,m]),p=fe(I=>!!I.newSessionDraft?.open),h=fe(I=>I.openNewSessionDraft),[x,g]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),w=et(I=>I.isInitialized),y=et(I=>I.initializeApp),v=fe(I=>I.loadSessions),S=fe(I=>I.loadMessages),k=fe(I=>I.messages),[b,N]=i.useState(()=>w),[D,j]=i.useState(!1),M=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const I=t.vscode;I&&I.executeCommand("openchamber.setActiveSession",u,f)},[f,u,t.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const C=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const I=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(I==="connected"||I==="connecting"||I==="error"||I==="disconnected")&&g(I);const A=T=>{const K=T.detail?.status;(K==="connected"||K==="connecting"||K==="error"||K==="disconnected")&&g(K)};return window.addEventListener("openchamber:connection-status",A),()=>window.removeEventListener("openchamber:connection-status",A)},[]),i.useEffect(()=>{const I=A=>{const R=A.detail?.view;R==="settings"?a("settings"):R==="chat"?a("chat"):R==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",I),()=>window.removeEventListener("openchamber:navigate",I)},[]),i.useEffect(()=>{(async()=>{if(D||b||x!=="connected")return;const A=Date.now();if(!(A-M.current<750)){M.current=A,j(!0);try{const T=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();T&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:w}),w||await y();const R=et.getState();if(!R.isInitialized||!R.isConnected||R.providers.length===0||R.agents.length===0)return;await v();const K=fe.getState().error;if(T&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:R.providers.length,agents:R.agents.length,sessions:fe.getState().sessions.length,sessionsError:K}),typeof K=="string"&&K.length>0)return;N(!0)}catch{}finally{j(!1)}}})()},[x,w,b,y,D,v]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!b||x!=="connected")){if(!s){n.current=!0,h();return}m.some(I=>I.id===s)&&(n.current=!0,fe.getState().setCurrentSession(s))}},[x,b,s,h,m,r]),i.useEffect(()=>{(async()=>{if(!b||x!=="connected"||o!=="chat"||p||!u)return;if(!(k.has(u)&&(k.get(u)?.length||0)>0))try{await S(u)}catch{}})()},[x,u,o,b,S,k,p]),i.useEffect(()=>{const I=d.current;if(!I)return;const A=new ResizeObserver(T=>{for(const R of T)c(R.contentRect.width)});return A.observe(I),c(I.clientWidth),()=>A.disconnect()},[]);const P=l>0&&l<uk,E=l>=mk;return i.useEffect(()=>{E&&o==="sessions"&&r==="sidebar"&&a("chat")},[E,o,r]),e.jsx("div",{ref:d,className:"h-full w-full bg-background text-foreground flex flex-col",children:r==="editor"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ta,{title:m.find(I=>I.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(gs,{children:e.jsx(bo,{})})})]}):o==="settings"?e.jsx(Cl,{onClose:()=>a(E?"chat":"sessions"),forceMobile:P}):E?e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"h-full border-r border-border overflow-hidden flex-shrink-0",style:{width:fk},children:e.jsx(La,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(ta,{title:p&&!u?"New session":m.find(I=>I.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(gs,{children:e.jsx(bo,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ta,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(La,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ta,{title:p&&!u?"New session":m.find(I=>I.id===u)?.title||"Chat",showBack:!0,onBack:C,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(gs,{children:e.jsx(bo,{})})})]})})},ta=({title:t,showBack:r,onBack:s,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c})=>{const{getCurrentModel:d}=et(),u=fe(g=>g.getContextUsage),m=d(),f=m?.limit&&typeof m.limit=="object"?m.limit:null,p=typeof f?.context=="number"?f.context:0,h=typeof f?.output=="number"?f.output:0,x=u(p,h);return e.jsxs("div",{className:"flex items-center gap-1.5 pl-1 pr-2 py-1 border-b border-border bg-background shrink-0",children:[r&&s&&e.jsx("button",{onClick:s,className:"inline-flex h-7 w-7 items-center justify-center text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(bm,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:t,children:t}),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(cs,{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(vo,{className:"h-5 w-5"})}),l&&e.jsx(pl,{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(pn,{className:"h-5 w-5"})}),c&&x&&x.totalTokens>0&&e.jsx(ul,{totalTokens:x.totalTokens,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit??0,size:"compact"})]})},Ml=".openchamber",sa=t=>{const r=zt.getState(),s=r.activeProjectId,n=s?r.projects.find(c=>c.id===s)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof t=="string"?Ut(t):"",a=`/${Ml}/`,l=o.indexOf(a);return l>0?o.slice(0,l):t?Ut(t):null},Ut=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},zu=t=>{const r=Ut(t);return!r||r==="/"?`/${Ml}`:`${r}/${Ml}`},hk=(t,r)=>{const s=Ut(t);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const l=Ut(o);if(l)return l}const a=typeof n.name=="string"?n.name.trim():"";return!a||!s?null:`${s}/${a}`}).filter(n=>!!n)},gk=async t=>{const r=Ut(t);if(!r)return[];try{const n=(await Fe.listLocalDirectory(r)).filter(o=>o.isDirectory);return hk(r,n)}catch{return[]}},Hr=(t,r)=>{const s=Ut(t),n=Ut(r);if(!s||!n)return!1;if(s===n)return!0;const o=n==="/"?"/":`${n}/`;return s.startsWith(o)},Dp=async(t,r)=>{const s=Ut(r);if(!s)return s;try{const n=await t.path.get({directory:s});return Ut(n.data?.directory??"")||s}catch{return s}},Ap=async(t,r)=>{const s=Ut(r);if(!s)return[];const n=await Dp(t,s),o=l=>l.filter(c=>{const d=Ut(c.directory??"");return d?Hr(d,s)||n!==s&&Hr(d,n):!1}),a=async l=>{const c=await t.session.list({directory:l});return Array.isArray(c.data)?c.data:[]};try{const l=o(await a(s));if(l.length>0)return l}catch{}if(n&&n!==s)try{const l=o(await a(n));if(l.length>0)return l}catch{}try{const l=await t.session.list(void 0),c=Array.isArray(l.data)?l.data:[];return o(c)}catch{return[]}},xk=async(t,r)=>{const s=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&s.set(Ut(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>Ut(o.path)))).filter(Boolean).filter(o=>!s.has(o));if(n.length===0)return s;try{const o=await Un(r),a=new Map(o.map(l=>[Ut(l.worktree),l]));n.forEach(l=>{const c=a.get(l);c&&s.set(l,Vn(r,c))})}catch{}return s},Qi=async t=>{const{apiClient:r,group:s,projectDirectory:n,worktreePaths:o}=t,a=await xk(s,n),l=fe.getState(),c=Array.from(new Set(o.map(p=>Ut(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<c.length;){const p=c[u];u+=1;const h=s.sessions.filter(v=>Ut(v.path)===p).map(v=>v.id),x=l.getSessionsByDirectory(p),g=Array.isArray(x)?x.map(v=>v.id):[];let w=[];if(g.length===0)try{w=(await Ap(r,p)).map(S=>S.id)}catch{w=[]}const y=Array.from(new Set([...g,...w,...h].filter(Boolean)));m.push({worktreePath:p,sessionIds:y,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,c.length)},f)),m};function yk(t){if(!t)return null;const r=t.split("/");if(r.length<3)return null;const s=r[0];if(!s||s.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),l=r.length>=4&&!isNaN(a)&&String(a)===o,c=l?r.slice(2,-1):r.slice(2);if(c.length===0)return null;const d=c.join("/");return{groupSlug:s,provider:n,model:d,index:l?a:1}}const Vr=os()(us((t,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const s=gt.getState().currentDirectory,n=sa(s);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Ut(n),a=zu(o),l=r().groups;t({isLoading:!0,error:null});try{const c=Fe.getApiClient(),d=await Dp(c,o),u=zu(d);let m=new Map,f=[];try{f=await Un(o),m=new Map(f.map(S=>[Ut(S.worktree),S]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const k=await c.session.list({directory:o}),b=Array.isArray(k.data)?k.data:[];if(b.some(N=>{const D=Ut(N.directory??"");return Hr(D,a)||Hr(D,u)}))return b}catch{}const S=await c.session.list(void 0);return Array.isArray(S.data)?S.data:[]},h=async S=>{const k=new Map,b=5;let N=0;const D=async()=>{for(;N<S.length;){const j=S[N];N+=1;const M=Ut(j);if(M)try{(await Ap(c,M)).forEach(P=>k.set(P.id,P))}catch(C){console.debug("Failed to fetch sessions from worktree:",M,C)}}};return await Promise.all(Array.from({length:Math.min(b,S.length)},D)),Array.from(k.values())};let g=(await p()).filter(S=>{const k=Ut(S.directory??"");return k?Hr(k,a)||Hr(k,u):!1});if(g.length===0){const S=new Set;f.map(b=>Ut(b.worktree)).filter(b=>Hr(b,a)||Hr(b,u)).forEach(b=>S.add(b));const k=Array.from(new Set([a,u].map(b=>Ut(b)).filter(Boolean)));await Promise.all(k.map(async b=>{(await gk(b)).forEach(D=>S.add(D))})),S.size>0&&(g=await h(Array.from(S)))}const w=new Map;for(const S of g){const k=S.time?.updated??0;w.set(S.id,typeof k=="number"?k:0)}const y=new Map;for(const S of g){const k=yk(S.title);if(!k)continue;const b=Ut(S.directory),N=m.get(b),D={id:S.id,path:b,providerId:k.provider,modelId:k.model,instanceNumber:k.index,branch:N?.branch??"",displayLabel:`${k.provider}/${k.model}`,worktreeMetadata:N?Vn(o,N):void 0},j=y.get(k.groupSlug);j?j.push(D):y.set(k.groupSlug,[D])}const v=Array.from(y.entries()).map(([S,k])=>{const b=k.reduce((N,D)=>{const j=w.get(D.id)??0;return Math.max(N,j)},0);return{name:S,sessions:k.sort((N,D)=>{const j=N.providerId.localeCompare(D.providerId);if(j!==0)return j;const M=N.modelId.localeCompare(D.modelId);return M!==0?M:N.instanceNumber-D.instanceNumber}),lastActive:b||Date.now(),sessionCount:k.length}});v.sort((S,k)=>S.name.localeCompare(k.name)),t({groups:v,isLoading:!1,error:null})}catch(c){console.error("Failed to load agent groups:",c),t({groups:l.length>0?l:[],isLoading:!1,error:c instanceof Error?c.message:"Failed to load agent groups"})}},selectGroup:s=>{const{groups:n}=r(),o=n.find(a=>a.name===s);t({selectedGroupName:s,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:s=>{t({selectedSessionId:s})},deleteGroup:async s=>{const n=r().groups.find(l=>l.name===s);if(!n)return!1;const o=gt.getState().currentDirectory,a=sa(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const l=Fe.getApiClient(),c=await Qi({apiClient:l,group:n,projectDirectory:Ut(a),worktreePaths:n.sessions.map(f=>f.path)}),d=fe.getState(),u=new Set;c.forEach(({worktreePath:f,sessionIds:p,metadata:h})=>{p.forEach(x=>{u.add(x),h&&(d.setWorktreeMetadata(x,h),d.setSessionDirectory(x,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&t({error:"Failed to delete some sessions"}),r().selectedGroupName===s&&t({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(l){return t({error:l instanceof Error?l.message:"Failed to delete group"}),!1}finally{t({isLoading:!1})}},deleteGroupWorktree:async(s,n)=>{const o=r().groups.find(d=>d.name===s);if(!o)return!1;const a=Ut(n);if(!a)return!1;const l=gt.getState().currentDirectory,c=sa(l);if(!c)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const d=Fe.getApiClient(),u=await Qi({apiClient:d,group:o,projectDirectory:Ut(c),worktreePaths:[a]}),m=fe.getState(),f=new Set;u.forEach(({worktreePath:x,sessionIds:g,metadata:w})=>{g.forEach(y=>{f.add(y),w&&(m.setWorktreeMetadata(y,w),m.setSessionDirectory(y,x))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&t({error:"Failed to delete some sessions"}),await r().loadGroups();const h=r().groups.find(x=>x.name===s);if(!h)return r().selectedGroupName===s&&t({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===s){const x=r().selectedSessionId,g=new Set(h.sessions.map(w=>w.id));(!x||!g.has(x))&&t({selectedSessionId:h.sessions[0]?.id??null})}return p.length===0}catch(d){return t({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{t({isLoading:!1})}},keepOnlyGroupWorktree:async(s,n)=>{const o=r().groups.find(m=>m.name===s);if(!o)return!1;const a=Ut(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Ut(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=gt.getState().currentDirectory,u=sa(d);if(!u)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const m=Fe.getApiClient(),f=await Qi({apiClient:m,group:o,projectDirectory:Ut(u),worktreePaths:c}),p=fe.getState(),h=new Set;f.forEach(({worktreePath:g,sessionIds:w,metadata:y})=>{w.forEach(v=>{h.add(v),y&&(p.setWorktreeMetadata(v,y),p.setSessionDirectory(v,g))})});const{failedIds:x}=await p.deleteSessions(Array.from(h),{archiveWorktree:!0,silent:!0});if(x.length>0&&t({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===s){const g=r().groups.find(y=>y.name===s),w=g?.sessions.find(y=>Ut(y.path)===a)??g?.sessions[0]??null;t({selectedSessionId:w?.id??null})}return x.length===0}catch(m){return t({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{t({isLoading:!1})}},getSelectedGroup:()=>{const{groups:s,selectedGroupName:n}=r();return n?s.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:s}=r(),n=r().getSelectedGroup();return!n||!s?null:n.sessions.find(o=>o.id===s)??null},clearError:()=>{t({error:null})}}),{name:"agent-groups-store"})),bk=t=>{const s=Date.now()-t,n=Math.floor(s/(60*1e3)),o=Math.floor(s/(3600*1e3)),a=Math.floor(s/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},wk=({group:t,isSelected:r,onSelect:s})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=Vr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),U.info(`Deleting "${t.name}"...`),await u(t.name))U.success(`Deleted "${t.name}"`);else{const p=Vr.getState().error;U.error(p||`Failed to delete "${t.name}"`)}d(!1),l(!1)},[u,t.name,c]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("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:s,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:t.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(Kt,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:bk(t.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(ts,{open:n,onOpenChange:o,children:[e.jsx(ss,{asChild:!0,children:e.jsx("button",{type:"button",className:F("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(Yr,{className:"h-3.5 w-3.5"})})}),e.jsx(rs,{align:"end",className:"min-w-[140px]",children:e.jsx(jt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(ps,{open:a,onOpenChange:l,children:e.jsxs(hs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Delete agent group"}),e.jsxs(ks,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(ve,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},vk=({className:t,selectedGroupName:r,onGroupSelect:s,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Vr(),f=gt(w=>w.currentDirectory);i.useEffect(()=>{f&&m()},[f,m]);const p=5,h=i.useMemo(()=>{if(!o.trim())return d;const w=o.toLowerCase();return d.filter(y=>y.name.toLowerCase().includes(w))},[o,d]),x=l?h:h.slice(0,p),g=h.length-p;return e.jsxs("div",{className:F("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",t),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Ws,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(bt,{value:o,onChange:w=>a(w.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(ve,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(cs,{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(Ht,{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(ht,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[x.map(w=>e.jsx(wk,{group:w,isSelected:r===w.name,onSelect:()=>s?.(w.name)},w.name)),!l&&g>0&&e.jsxs("button",{type:"button",onClick:()=>c(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",g,")"]}),l&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>c(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&h.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"})]})]})]})},jk=10*1024*1024,Sk=5,Nk=({className:t,onCreateGroup:r,isCreating:s=!1})=>{const[n,o]=i.useState(""),[a,l]=i.useState(""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState("HEAD"),[h,x]=i.useState([]),[g,w]=i.useState(!1),[y,v]=i.useState([]),[S,k]=i.useState(!1),[b,N]=i.useState(!1),D=i.useRef(null),j=i.useRef(null),M=gt(B=>B.currentDirectory??null),{isGitRepository:C,isLoading:P}=dc(M),E=i.useMemo(()=>{if(typeof window>"u")return null;const B=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof B=="string"&&B.trim().length>0?B.trim():null},[]),I=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),A=zt(B=>B.activeProjectId),T=zt(B=>B.projects),R=i.useMemo(()=>{if(I&&E)return E;if(A){const O=T.find(V=>V.id===A);if(O?.path)return O.path}const B=M??E;if(!B)return null;const se=B.replace(/\\/g,"/").replace(/\/+$/,"")||B,ae=se.indexOf("/.openchamber/");return ae>0?se.slice(0,ae):se.endsWith("/.openchamber")?se.slice(0,se.length-13):se},[A,T,M,E,I]);i.useEffect(()=>{if(!R)return;let B=!1;return N(!0),(async()=>{try{const se=await Sn(R);B||v(se)}catch{}finally{B||N(!1)}})(),()=>{B=!0}},[R]);const K=i.useCallback(B=>{c.length>=Sk||d(se=>[...se,B])},[c.length]),Y=i.useCallback(B=>{d(se=>se.filter((L,ae)=>ae!==B))},[]),_=i.useCallback((B,se)=>{d(L=>L.map((ae,O)=>O===B?se:ae))},[]),J=async B=>{const se=B.target.files;if(!se)return;let L=0;for(let ae=0;ae<se.length;ae++){const O=se[ae];if(O.size>jk){U.error(`File "${O.name}" is too large (max 10MB)`);continue}try{const V=await new Promise((re,me)=>{const G=new FileReader;G.onload=()=>re(G.result),G.onerror=me,G.readAsDataURL(O)}),X={id:_a(),filename:O.name,mimeType:O.type||"application/octet-stream",size:O.size,dataUrl:V};x(re=>[...re,X]),L++}catch(V){console.error("File attach failed",V),U.error(`Failed to attach "${O.name}"`)}}L>0&&U.success(`Attached ${L} file${L>1?"s":""}`),D.current&&(D.current.value="")},q=B=>{x(se=>se.filter(L=>L.id!==B))},Q=g||s,z=!!(n.trim()&&a.trim()&&c.length>=1&&C&&!P),H=async B=>{if(B.preventDefault(),!(!z||Q)){w(!0);try{const se=c.map(({providerID:O,modelID:V,displayName:X,variant:re})=>({providerID:O,modelID:V,displayName:X,variant:re})),L=h.length>0?h.map(O=>({mime:O.mimeType,filename:O.filename,url:O.dataUrl})):void 0,ae=y.filter(O=>O.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:se,agent:u||void 0,worktreeBaseBranch:f,files:L,setupCommands:ae.length>0?ae:void 0}),o(""),l(""),d([]),m(""),x([]),p("HEAD")}catch(se){console.error("Failed to create agent group:",se),U.error("Failed to create agent group")}finally{w(!1)}}},W=B=>{lc(B)||B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),z&&!Q&&H(B))};return e.jsx("div",{className:F("flex flex-col items-center justify-center h-full w-full p-4",t),children:e.jsxs("form",{onSubmit:H,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(bt,{id:"group-name",value:n,onChange:B=>o(B.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(Kt,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx($f,{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(eo,{open:S,onOpenChange:k,children:[e.jsxs(Io,{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",y.filter(B=>B.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(B=>B.trim()).length," configured)"]})]}),e.jsx(Ht,{className:F("h-4 w-4 text-muted-foreground transition-transform duration-200",S&&"rotate-180")})]}),e.jsx(to,{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:[y.map((B,se)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(bt,{value:B,onChange:L=>{const ae=[...y];ae[se]=L.target.value,v(ae)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const L=y.filter((ae,O)=>O!==se);v(L)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(es,{className:"h-4 w-4"})})]},se)),e.jsxs("button",{type:"button",onClick:()=>v([...y,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(cs,{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(Bf,{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(_f,{selectedModels:c,onAdd:K,onRemove:Y,onUpdate:_,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-input/10 dark:bg-input/30 overflow-hidden",children:[e.jsx(Rs,{ref:j,id:"prompt",value:a,onChange:B=>l(B.target.value),onKeyDown:W,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"}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:h.map(B=>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:[B.mimeType.startsWith("image/")?e.jsx(Nr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(yr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:B.filename,children:B.filename}),e.jsx("button",{type:"button",onClick:()=>q(B.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(es,{className:"h-3.5 w-3.5"})})]},B.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:J,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(pm,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[c.length," model",c.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!z||Q,className:F("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",z?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:Q?e.jsx(cx,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Ha,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},kk=({group:t,className:r})=>{const{selectedSessionId:s,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Vr(),{setCurrentSession:l,currentSessionId:c}=fe(),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useMemo(()=>s?t.sessions.find(S=>S.id===s)??t.sessions[0]??null:t.sessions[0]??null,[t.sessions,s]),h=i.useCallback(S=>{n(S.id),l(S.id)},[n,l]);i.useEffect(()=>{if(t.sessions.length>0){const S=s?t.sessions.find(k=>k.id===s)??t.sessions[0]:t.sessions[0];S&&(S.id!==c&&l(S.id),s||n(S.id))}},[t.name,t.sessions,s,c,n,l]);const x=p?.id===c,g=i.useCallback(()=>{if(!p?.path){U.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{U.success("Worktree path copied")}).catch(()=>{U.error("Failed to copy path")})},[p?.path]),w=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),y=i.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),v=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(U.info("Removing worktree..."),await o(t.name,d.path))U.success("Worktree removed");else{const k=Vr.getState().error;U.error(k||"Failed to remove worktree");return}else if(U.info("Removing other worktrees..."),await a(t.name,d.path))U.success("Removed other worktrees");else{const k=Vr.getState().error;U.error(k||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,t.name,m,a,d]);return e.jsxs("div",{className:F("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:t.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),t.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(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsxs(ve,{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(Ns,{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(Ht,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(rs,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(S=>e.jsxs(jt,{onClick:()=>h(S),className:"flex items-center gap-2 py-2",children:[e.jsx(Ns,{providerId:S.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:S.modelId}),S.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",S.instanceNumber]})]}),S.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(Kt,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:S.worktreeMetadata?.label||S.branch})]})]}),p?.id===S.id&&e.jsx(Qt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},S.id))})]})}),e.jsxs(ts,{children:[e.jsx(ss,{asChild:!0,children:e.jsx(ve,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Yr,{className:"h-4 w-4"})})}),e.jsxs(rs,{align:"end",className:"min-w-[220px]",children:[e.jsx(jt,{onSelect:S=>{S.preventDefault(),w()},variant:"destructive",children:"Remove this worktree"}),e.jsx(jt,{onSelect:S=>{S.preventDefault(),y()},children:"Leave this one, remove others"}),e.jsxs(jt,{onClick:S=>{S.stopPropagation(),g()},disabled:!p?.path,children:[e.jsx(Js,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(ps,{open:!!d,onOpenChange:S=>{S||u(null)},children:e.jsxs(hs,{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(ks,{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:t.name}),"."]})})]}),e.jsxs(Us,{children:[e.jsx(ve,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(ve,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{v()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?x?e.jsx(cp,{sessionId:p.id,children:e.jsx(lp,{})}):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(Ns,{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"})})})]})},Ck=({className:t})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[s,n]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=et(S=>S.isInitialized),a=et(S=>S.initializeApp),l=fe(S=>S.loadSessions),c=gt(S=>S.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Vr(),{createMultiRun:h,isLoading:x}=yo();i.useEffect(()=>{if(!r)return;const S=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(S==="connected"||S==="connecting"||S==="error"||S==="disconnected")&&n(S);const k=b=>{const D=b.detail?.status;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&n(D)};return window.addEventListener("openchamber:connection-status",k),()=>window.removeEventListener("openchamber:connection-status",k)},[r]),i.useEffect(()=>{if(!r||s!=="connected")return;const S=Date.now();if(S-d.current<750)return;d.current=S;const k=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof k=="string"&&k.trim().length>0)try{c(k,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const N=et.getState();if(!N.isInitialized||!N.isConnected||N.providers.length===0||N.agents.length===0)return;await l(),ms()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:N.providers.length,agents:N.agents.length,sessions:fe.getState().sessions.length})}catch{}})()},[s,o,a,r,l,c]);const g=i.useCallback(S=>{m(S)},[m]),w=i.useCallback(()=>{m(null)},[m]),y=i.useCallback(async S=>{U.info(`Creating agent group "${S.name}" with ${S.models.length} model(s)...`);const k=await h(S);if(k){U.success(`Agent group "${S.name}" created with ${k.sessionIds.length} session(s)`);const b=k.groupSlug,N=async(D=6)=>{for(let j=0;j<D;j+=1){if(await p(),Vr.getState().groups.some(C=>C.name===b))return!0;await new Promise(C=>setTimeout(C,500))}return!1};try{await fe.getState().loadSessions()}catch{}await N(),m(b)}else{const b=yo.getState().error;U.error(b||"Failed to create agent group")}},[h,p,m]),v=f();return e.jsxs("div",{className:F("flex h-full w-full bg-background",t),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(vk,{selectedGroupName:u,onGroupSelect:g,onNewAgent:w})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(kk,{group:v}):e.jsx(Nk,{onCreateGroup:y,isCreating:x})})]})},Mk=(t=5e3)=>{const[r,s]=Re.useState(null);return Re.useEffect(()=>{if(!ds())return;let n=!1,o=null;const a=async()=>{const l=await Px();n||(s(l),o=setTimeout(a,t))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[t]),r},Dk=({onClose:t})=>{const{sessions:r,messages:s,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=fe(),c=Mk(4e3),d=i.useMemo(()=>{let f=0;return s.forEach(p=>{f+=p.length}),f},[s]),u=i.useMemo(()=>r.map(f=>{const p=s.get(f.id)?.length||0,h=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,s,n,o]),m=s.size;return e.jsxs(sc,{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(dx,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),t&&e.jsx(ve,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:t,children:e.jsx(es,{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," / ",Mr.MAX_SESSIONS]})]})]}),c&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:c.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[c.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:c.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[Mr.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:[Mr.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:[Mr.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(ht,{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(ux,{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>Mr.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(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsxs(ve,{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(it,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(it,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ve,{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(s.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(it,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},Ak="openchamber-message-cursors",Yn="cursors",Ek=1,Ep="openchamber.messageCursors",gc=()=>typeof window<"u",xc=()=>gc()&&typeof indexedDB<"u",Ip=()=>xc()?new Promise((t,r)=>{const s=indexedDB.open(Ak,Ek);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(Yn)||n.createObjectStore(Yn)},s.onerror=()=>{r(s.error??new Error("Failed to open IndexedDB"))},s.onsuccess=()=>{t(s.result)}}):Promise.reject(new Error("IndexedDB not supported")),Pp=()=>{if(!gc())return{};try{const t=window.localStorage.getItem(Ep);if(!t)return{};const r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Ik=t=>{if(gc())try{window.localStorage.setItem(Ep,JSON.stringify(t))}catch{}},Pk=async(t,r,s)=>{if(!t||!r)return;if(xc())try{const o=await Ip();await new Promise((a,l)=>{const c=o.transaction(Yn,"readwrite");c.objectStore(Yn).put({messageId:r,completedAt:s},t),c.oncomplete=()=>a(),c.onerror=()=>l(c.error??new Error("Cursor write failed")),c.onabort=()=>l(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=Pp();n[t]={messageId:r,completedAt:s},Ik(n)},Tk=async t=>{if(!t)return null;if(xc())try{const s=await Ip(),n=await new Promise((o,a)=>{const l=s.transaction(Yn,"readonly"),d=l.objectStore(Yn).get(t);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),l.onerror=()=>a(l.error??new Error("Cursor read failed")),l.onabort=()=>a(l.error??new Error("Cursor read aborted"))});return s.close(),n}catch{}return Pp()[t]??null},Fk=50,Rk=750,Hu=new WeakMap,Wu=t=>{if(!t||!Array.isArray(t))return 0;const r=Hu.get(t);if(r!==void 0)return r;let s=0;for(let n=0;n<t.length;n++){const o=t[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(s+=a.length)}}return Hu.set(t,s),s},Lk=10,Uu=t=>{if(typeof t!="string")return null;const r=t.trim();if(!r)return null;const s=r.indexOf("_"),n=s>=0?r.slice(s+1):r;return!n||n.length<Lk?null:n},Vu=(t,r)=>{const s=Uu(t),n=Uu(r);return!s||!n||s.length!==n.length?!0:s>n},Dl=new Map,Gu=(t,r)=>{const s=`${t}:${r}`,n=Dl.get(s);if(n&&n.sessionId===t)return n.message;const l=(fe.getState().messages.get(t)||[]).find(c=>c.info.id===r)||null;return Dl.set(s,{sessionId:t,message:l}),l},Ok=t=>{const r=t.split(/[-_]/),s=[];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]}`;s.push(a),n+=2;continue}s.push(o),n+=1}return s.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")},_k=()=>{const{addStreamingPart:t,completeStreamingMessage:r,updateMessageInfo:s,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,getWorktreeMetadata:u,loadMessages:m,loadSessions:f,updateSession:p,removeSessionFromStore:h}=fe(),{checkConnection:x}=et(),g=ke(Ie=>Ie.nativeNotificationsEnabled),w=ke(Ie=>Ie.notificationMode),y=gt(Ie=>Ie.currentDirectory),v=i.useMemo(()=>{if(!c)return;try{const Xe=u?.(c);if(Xe?.path)return Xe.path}catch(Xe){console.warn("Failed to inspect worktree metadata for session directory:",Xe)}const le=fe.getState().sessions.find(Xe=>Xe.id===c);if(le&&typeof le.directory=="string"&&le.directory.trim().length>0)return le.directory.trim()},[c,u]),S=i.useMemo(()=>{if(v&&v.length>0)return v;if(typeof y=="string"&&y.trim().length>0)return y.trim()},[v,y]);i.useEffect(()=>{let Ie=!1;const le=async()=>{try{const Ne=await Fe.listPendingPermissions();if(Ie||Ne.length===0)return;for(const Se of Ne)o(Se)}catch{}},Xe=async()=>{try{const Se=zt.getState().projects.map(Ke=>Ke.path),rt=fe.getState().sessions.map(Ke=>Ke.directory),We=[S,...Se,...rt],_e=await Fe.listPendingQuestions({directories:We});if(Ie||_e.length===0)return;for(const Ke of _e)a(Ke)}catch{}};return le(),Xe(),()=>{Ie=!0}},[o,a,S]);const k=i.useCallback(Ie=>{if(typeof Ie!="string")return null;const le=Ie.trim();if(!le)return null;const Xe=le.replace(/\\/g,"/");return Xe.length>1?Xe.replace(/\/+$/,""):Xe},[]),b=i.useCallback(Ie=>{if(!Ie)return null;try{const Ne=u?.(Ie),Se=k(Ne?.path??null);if(Se)return Se}catch{}const Xe=fe.getState().sessions.find(Ne=>Ne.id===Ie);return k(Xe?.directory??null)},[u,k]),N=ke(Ie=>Ie.setEventStreamStatus),D=i.useRef(null),j=i.useCallback((Ie,le)=>{const Xe=le??null,Ne=D.current;if(!(Ne&&Ne.status===Ie&&Ne.hint===Xe)){if(D.current={status:Ie,hint:Xe},ms()){const qe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[Ie]??"[INFO]",rt=Xe?`${qe} SSE ${Ie}: ${Xe}`:`${qe} SSE ${Ie}`;console.info(rt)}N(Ie,Xe)}},[N]),M=i.useCallback((Ie,le,Xe)=>{if(!Ie)return Promise.resolve();const Ne=Date.now();if(_.current)return _.current;if(Ne-J.current<Rk)return Promise.resolve();const Se=m(Ie,Xe).catch(qe=>{console.warn(`[useEventStream] Failed to resync messages (${le}):`,qe)}).finally(()=>{_.current=null,J.current=Date.now()});return _.current=Se,Se},[m]),C=i.useCallback(async Ie=>{ms()&&console.info("[useEventStream] Bootstrapping state:",Ie);try{await Promise.all([f(),c?M(c,Ie,1/0):Promise.resolve()])}catch(le){console.warn("[useEventStream] Bootstrap failed:",Ie,le)}},[c,f,M]),P=i.useCallback((Ie,le,Xe)=>{ms()&&console.debug(`[MessageTracker] ${Ie}: ${le}`,Xe)},[]),E=i.useCallback(Ie=>{ms()&&console.debug(`[MessageTracker] ${Ie}: reported`)},[]),I=i.useRef(null),A=i.useRef(null),T=i.useRef(0);i.useRef(new Set);const R=i.useRef(new Map),K=i.useRef(null),Y=i.useRef(!1),_=i.useRef(null),J=i.useRef(0),q=i.useRef(new Set),Q=i.useRef(new Set),z=i.useRef(new Set),H=i.useRef(new Set),W=i.useCallback(()=>{if(typeof document>"u")return"visible";const Ie=document.visibilityState;return Ie==="hidden"&&document.hasFocus()?"visible":Ie},[]),B=i.useRef(W()),se=i.useRef(typeof navigator>"u"?!0:navigator.onLine),L=i.useRef(!1),ae=i.useRef(null),O=i.useRef(null),V=i.useRef(Date.now()),X=i.useRef(!1),re=i.useCallback(Ie=>{const le=Date.now();le-V.current>25e3&&(C(Ie),V.current=le)},[C]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(X.current=!0)},[]);const me=i.useRef(new Map),G=i.useRef(new Map),he=i.useRef(0),ye=i.useRef(null),ge=i.useRef(c),$e=i.useRef(null),ee=i.useRef(null);i.useEffect(()=>{ge.current=c},[c]);const Z=i.useCallback((Ie,le)=>{if(!Ie)return;const Xe=Date.now(),Ne=R.current,Se=Ne.get(Ie);if(Se&&Xe-Se<3e3)return;Ne.set(Ie,Xe);const qe=rt=>{if(typeof le=="string"&&le.trim().length>0)return le.trim();try{const Ke=u?.(rt);if(Ke?.path)return Ke.path}catch{}const _e=fe.getState().sessions.find(Ke=>Ke.id===rt);return _e&&typeof _e.directory=="string"&&_e.directory.trim().length>0?_e.directory.trim():null};setTimeout(async()=>{try{const rt=qe(Ie),We=rt?await Fe.withDirectory(rt,()=>Fe.getSession(Ie)):await Fe.getSession(Ie);if(We){const _e={};typeof We.title=="string"&&We.title.length>0&&(_e.title=We.title),We.summary!==void 0&&(_e.summary=We.summary),Object.keys(_e).length>0&&d(Ie,_e)}}catch(rt){console.warn("Failed to refresh session metadata:",rt)}},100)},[d,u]),ie=i.useCallback((Ie,le)=>{if(fe.getState().sessionActivityPhase?.get(Ie)===le){G.current=new Map(fe.getState().sessionActivityPhase??new Map);return}const Ne=me.current.get(Ie);Ne&&(clearTimeout(Ne),me.current.delete(Ie));const Se=new Map(fe.getState().sessionActivityPhase??new Map);if(Se.set(Ie,le),G.current=Se,fe.setState({sessionActivityPhase:Se}),le==="cooldown"){const qe=setTimeout(()=>{if(me.current.delete(Ie),fe.getState().sessionActivityPhase?.get(Ie)==="cooldown"){const We=new Map(fe.getState().sessionActivityPhase??new Map);We.set(Ie,"idle"),G.current=We,fe.setState({sessionActivityPhase:We})}},2e3);me.current.set(Ie,qe)}},[]),Me=i.useCallback(async()=>{const Ie=Date.now();if(ye.current)return ye.current;if(Ie-he.current<1500)return;he.current=Ie;const le=Ne=>{const Se=new Set,qe=fe.getState().sessions,rt=new Set(qe.map(_e=>_e.id));for(const[_e,Ke]of Object.entries(Ne)){if(!_e||!Ke)continue;Se.add(_e);const xt=Ke.type==="busy"||Ke.type==="retry"?"busy":"idle";ie(_e,xt)}const We=fe.getState().sessionActivityPhase;if(We)for(const[_e,Ke]of We.entries())rt.has(_e)&&(Ke==="busy"||Ke==="cooldown")&&!Se.has(_e)&&ie(_e,"idle")},Xe=(async()=>{try{const Ne=await Fe.getGlobalSessionStatus();if(Ne&&Object.keys(Ne).length>0){le(Ne);return}const Se=new Set,qe=fe.getState().sessions;for(const xt of qe){const nt=b(xt.id);nt&&Se.add(nt)}const rt=k(S??null);rt&&Se.add(rt);const We=Array.from(Se);if(We.length===0){const xt=await Fe.getSessionStatus();xt&&le(xt);return}const _e=await Promise.allSettled(We.map(xt=>Fe.getSessionStatusForDirectory(xt))),Ke={};for(const xt of _e)xt.status!=="fulfilled"||!xt.value||Object.assign(Ke,xt.value);if(Object.keys(Ke).length===0&&Array.from(fe.getState().sessionActivityPhase?.values?.()??[]).some(nt=>nt==="busy"||nt==="cooldown")&&!await Fe.checkHealth().catch(()=>!1))return;le(Ke)}catch{}})().finally(()=>{ye.current=null});return ye.current=Xe,Xe},[S,k,b,ie]);i.useEffect(()=>{const Ie=c??null,le=$e.current,Xe=b(Ie),Ne=ee.current;le&&Ie&&le!==Ie&&Ne&&Xe&&Ne!==Xe&&Me(),$e.current=Ie,ee.current=Xe},[c,Me,b]);const oe=i.useCallback(Ie=>{if(V.current=Date.now(),ms()&&console.debug("[useEventStream] Received event:",Ie.type,Ie.properties),!Ie.properties)return;const le=Ie.properties;if(!new Set(["session.abort","session.error"]).has(Ie.type)){const Ne=(typeof le.session=="object"&&le.session!==null?le.session:null)||(typeof le.sessionInfo=="object"&&le.sessionInfo!==null?le.sessionInfo:null);if(Ne){const Se=Ne,qe=typeof Se.id=="string"&&Se.id.length>0?Se.id:typeof Se.sessionID=="string"&&Se.sessionID.length>0?Se.sessionID:typeof le.sessionID=="string"&&le.sessionID.length>0?le.sessionID:typeof le.id=="string"&&le.id.length>0?le.id:void 0;if(qe){const rt=typeof Se.title=="string"?Se.title:typeof le.title=="string"?le.title:void 0,We=typeof Se.summary=="object"&&Se.summary!==null?Se.summary:typeof le.summary=="object"&&le.summary!==null?le.summary:void 0;if(rt!==void 0||We!==void 0){const _e={};rt!==void 0&&(_e.title=rt),We!==void 0&&(_e.summary=We),d(qe,_e)}}}}switch(Ie.type){case"server.connected":x();break;case"global.disposed":case"server.instance.disposed":{C("server_disposed_event");break}case"openchamber:session-activity":{const Ne=typeof le.sessionId=="string"?le.sessionId:null,Se=typeof le.phase=="string"?le.phase:null;Ne&&(Se==="idle"||Se==="busy"||Se==="cooldown")&&(ie(Ne,Se),Z(Ne,typeof le.directory=="string"?le.directory:null));break}case"mcp.tools.changed":{const Ne=typeof le.directory=="string"?le.directory:S;co.getState().refresh({directory:Ne??null,silent:!0});break}case"session.status":if(X.current)break;{const Ne=typeof le.sessionID=="string"?le.sessionID:null,Se=typeof le.status=="object"&&le.status!==null?le.status:null,qe=typeof Se?.type=="string"?Se.type:null;Ne&&qe&&(ie(Ne,qe==="busy"||qe==="retry"?"busy":"idle"),Z(Ne,typeof le.directory=="string"?le.directory:null))}break;case"message.part.updated":{const Ne=typeof le.part=="object"&&le.part!==null?le.part:null;if(!Ne)break;const Se=Ne,qe=typeof le.info=="object"&&le.info!==null?le.info:le,rt=typeof qe.sessionID=="string"?qe.sessionID:null,We=typeof Se.sessionID=="string"&&Se.sessionID.length>0?Se.sessionID:typeof rt=="string"&&rt.length>0?rt:typeof le.sessionID=="string"&&le.sessionID.length>0?le.sessionID:null,_e=typeof qe.id=="string"?qe.id:null,Ke=typeof Se.messageID=="string"&&Se.messageID.length>0?Se.messageID:typeof _e=="string"&&_e.length>0?_e:typeof le.messageID=="string"&&le.messageID.length>0?le.messageID:null;if(!We||!Ke){ms()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:Se.sessionID??rt??le.sessionID,messageID:Se.messageID??_e??le.messageID});break}const xt=We,nt=Ke,Pt=fe.getState().sessionMemoryState.get(xt)?.trimmedHeadMaxId;if(Pt&&!Vu(nt,Pt)){ms()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:xt,messageId:nt,trimmedHeadMaxId:Pt});break}let Tt="assistant";if(qe&&typeof qe.role=="string")Tt=qe.role;else{const Ve=Gu(xt,nt);if(Ve){const dt=Ve.info.role;typeof dt=="string"&&(Tt=dt)}}if(P(nt,"part_received",{role:Tt}),Tt==="user"&&Se.synthetic===!0){P(nt,"skipped_synthetic_user_part");break}const _t={...Ne,type:Ne.type||"text"};P(nt,"addStreamingPart_called"),t(xt,nt,_t,Tt);break}case"message.updated":{const Ne=typeof le.info=="object"&&le.info!==null?le.info:le,Se=Ne,qe=typeof Se.sessionID=="string"&&Se.sessionID.length>0?Se.sessionID:typeof le.sessionID=="string"&&le.sessionID.length>0?le.sessionID:null,rt=typeof Se.id=="string"&&Se.id.length>0?Se.id:typeof le.messageID=="string"&&le.messageID.length>0?le.messageID:null;if(!qe||!rt){ms()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:Se.sessionID??le.sessionID,messageID:Se.id??le.messageID});break}const We=qe,_e=rt,Ke=fe.getState().sessionMemoryState.get(We)?.trimmedHeadMaxId;if(Ke&&!Vu(_e,Ke)){ms()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:We,messageId:_e,trimmedHeadMaxId:Ke});break}if(X.current&&ms())try{const Dt=le.parts||Se.parts||[],St=(Array.isArray(Dt)?Dt.filter(Lt=>Lt?.type==="text"):[]).map(Lt=>{const be=Lt;return typeof be?.text=="string"?be.text:typeof be?.content=="string"?be.content:""}).join(`
215
- `);console.info("[STREAM-TRACE] message.updated",{messageId:_e,role:Se.role,status:Se.status,textLen:St.length,textPreview:St.slice(0,120),partsCount:Array.isArray(Dt)?Dt.length:0})}catch{}if(P(_e,"message_updated",{role:Se.role}),Se.role==="user"){const Dt=le.parts||Se.parts,qt=Array.isArray(Dt)?Dt:[],St={...Ne,userMessageMarker:!0,clientRole:"user"};if(s(We,_e,St),qt.length>0)for(let Lt=0;Lt<qt.length;Lt++){const be=qt[Lt];if(be.synthetic===!0)continue;const Pe={...be,type:be?.type||"text",sessionID:be?.sessionID||We,messageID:be?.messageID||_e};t(We,_e,Pe,"user")}P(_e,"user_message_created_from_event",{partsCount:qt.length});break}const xt=Gu(We,_e),nt=Wu(xt?.parts||[]),Pt=xt?.info?.finish==="stop",Tt=le.parts||Se.parts,_t=Array.isArray(Tt)?Tt:[],Ve=_t.length>0,vt=typeof(Se.time||{})?.completed=="number";if(!Ve&&!vt)break;const ut=Ne.finish,At=typeof ut=="string"?ut:null,Rt=At==="stop";if(Se.role==="assistant"&&Ve){const Dt=Wu(_t);if(nt>0&&Dt+Fk<nt&&!Rt){P(_e,"skipped_shrinking_update",{incomingLen:Dt,existingLen:nt});break}if(X.current){const St=nt>0&&Dt<nt,Lt=_t.some(Pe=>{if(!Pe||Pe.type!=="text")return!1;const Oe=Pe;return typeof Oe.text=="string"&&Oe.text.length>0});if(St&&!(Rt&&Lt)){P(_e,"desktop_shrinking_update_suppressed",{incomingLen:Dt,existingLen:nt});break}}}if(s(We,_e,Ne),Ve&&Se.role!=="user"){const St=(fe.getState().messages.get(We)||[]).find(Pe=>Pe.info.id===_e),Lt=!St||St.parts.length===0;P(_e,Lt?"server_parts_injected":"server_parts_refreshed",{count:_t.length});const be=X.current&&Se.role==="assistant"?_t.filter(Pe=>Pe?.type!=="text"):_t;for(let Pe=0;Pe<be.length;Pe++){const Oe=be[Pe],st={...Oe,type:Oe?.type||"text",sessionID:Oe?.sessionID||We,messageID:Oe?.messageID||_e};t(We,_e,st,Se.role),P(_e,`server_part_${Pe}`)}}const as=Ne.time,Ct=as?.completed,$t=typeof Ct=="number"&&Number.isFinite(Ct),Mt=At==="stop"||Pt;if(Ne.role==="assistant"&&($t||Mt)&&Ne.role==="assistant"){const qt=fe.getState().messages.get(We)||[];let St=null,Lt="";for(let Ae=0;Ae<qt.length;Ae++){const te=qt[Ae];te.info.role==="assistant"&&te.info.id>Lt&&(Lt=te.info.id,St=te.info.id)}if(c===We&&_e!==St)break;if(!Mt&&X.current){P(_e,"desktop_completion_without_stop");break}const Pe=$t?Ct:Date.now();if($t||s(We,_e,{...Ne,time:{...as??{},completed:Pe}}),P(_e,"completed",{timeCompleted:Pe}),E(_e),Pk(We,_e,Pe),r(We,_e),At==="stop"&&br()&&g&&(w==="always"||B.current==="hidden")){const te=z.current;if(!te.has(_e)){te.add(_e);const Ce=Ms();if(Ce?.notifications){const De=Se.mode||"agent",He=Se.modelID||"assistant",wt=`${De.charAt(0).toUpperCase()+De.slice(1)} agent is ready`,Nt=`${Ok(He)} completed the task`;Ce.notifications.notifyAgentCompletion({title:wt,body:Nt,tag:_e})}}}X.current||At==="stop"&&fe.getState().sessionActivityPhase?.get(We)==="busy"&&ie(We,"cooldown");const Oe=Ne.sessionID,st=typeof Oe=="string"&&Oe.length>0?Oe:We;Z(st,typeof le.directory=="string"?le.directory:null),Ne.summary&&typeof st=="string"&&n(st,null)}break}case"session.created":case"session.updated":{const Ne=typeof le.info=="object"&&le.info!==null?le.info:typeof le.sessionInfo=="object"&&le.sessionInfo!==null?le.sessionInfo:typeof le.session=="object"&&le.session!==null?le.session:le,Se=typeof Ne.id=="string"&&Ne.id.length>0?Ne.id:typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof le.sessionID=="string"&&le.sessionID.length>0?le.sessionID:typeof le.id=="string"&&le.id.length>0?le.id:void 0;if(Se){const qe=typeof Ne.time=="object"&&Ne.time!==null?Ne.time:typeof le.time=="object"&&le.time!==null?le.time:null,rt=qe&&typeof qe.compacting=="number"?qe.compacting:null;n(Se,rt);const We=typeof Ne.directory=="string"?Ne.directory:typeof le.directory=="string"?le.directory:null,_e={...Ne,id:Se,...We?{directory:We}:{}};p(_e)}break}case"session.deleted":{const Ne=typeof le.sessionID=="string"?le.sessionID:typeof le.id=="string"?le.id:null;Ne&&h(Ne);break}case"session.abort":{const Ne=typeof le.sessionID=="string"&&le.sessionID.length>0?le.sessionID:null,Se=typeof le.messageID=="string"&&le.messageID.length>0?le.messageID:null;Ne&&Se&&r(Ne,Se);break}case"permission.asked":{if(!("sessionID"in le)||typeof le.sessionID!="string")break;const Ne=le;o(Ne);const Se=`${Ne.sessionID}:${Ne.id}`;q.current.has(Se)||setTimeout(()=>{if(ge.current===Ne.sessionID||!fe.getState().permissions.get(Ne.sessionID)?.some(_e=>_e.id===Ne.id))return;q.current.add(Se);const We=fe.getState().sessions.find(_e=>_e.id===Ne.sessionID)?.title||"Session";if(Ss(async()=>{const{toast:_e}=await import("./vendor-.bun-CaD8MAGl.js").then(Ke=>Ke.dd);return{toast:_e}},__vite__mapDeps([0,1])).then(({toast:_e})=>{_e.warning("Permission required",{description:We,action:{label:"Open",onClick:()=>{ke.getState().setActiveMainTab("chat"),fe.getState().setCurrentSession(Ne.sessionID)}}})}),br()&&g&&(w==="always"||B.current==="hidden")){const Ke=Ms();Ke?.notifications&&Ke.notifications.notifyAgentCompletion({title:"Permission required",body:We,tag:`permission-${Se}`})}},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in le)||typeof le.sessionID!="string")break;const Ne=le;a(Ne);const Se=`${Ne.sessionID}:${Ne.id}`;if(br()&&g&&(w==="always"||B.current==="hidden")){const rt=H.current;if(!rt.has(Se)){rt.add(Se);const We=Ms();We?.notifications&&We.notifications.notifyAgentCompletion({title:"Input needed",body:"Agent is waiting for your response",tag:Se})}}Q.current.has(Se)||setTimeout(()=>{if(ge.current===Ne.sessionID||!fe.getState().questions.get(Ne.sessionID)?.some(_e=>_e.id===Ne.id))return;Q.current.add(Se);const We=fe.getState().sessions.find(_e=>_e.id===Ne.sessionID)?.title||"Session";Ss(async()=>{const{toast:_e}=await import("./vendor-.bun-CaD8MAGl.js").then(Ke=>Ke.dd);return{toast:_e}},__vite__mapDeps([0,1])).then(({toast:_e})=>{_e.info("Input needed",{description:We,action:{label:"Open",onClick:()=>{ke.getState().setActiveMainTab("chat"),fe.getState().setCurrentSession(Ne.sessionID)}}})})},0);break}case"question.replied":{const Ne=typeof le.sessionID=="string"?le.sessionID:null,Se=typeof le.requestID=="string"?le.requestID:null;Ne&&Se&&l(Ne,Se);break}case"todo.updated":{const Ne=typeof le.sessionID=="string"?le.sessionID:null,Se=Array.isArray(le.todos)?le.todos:null;Ne&&Se&&Xv(Ne,Se);break}}},[c,g,w,t,r,s,o,a,l,x,Z,n,d,P,E,ie,p,h,C,S]),xe=i.useCallback(()=>{const Ie=W();return B.current=Ie,Ie==="visible"&&se.current},[W]),pe=i.useCallback(()=>{ms()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:X.current,hasUnsubscribe:!!I.current,currentSessionId:ge.current,effectiveDirectory:S,onlineStatus:se.current,visibilityState:B.current,lastEventTimestamp:V.current,reconnectAttempts:T.current})},[S]),je=i.useCallback(async()=>!0,[]),ce=i.useCallback(()=>{if(Y.current){ms()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(Y.current=!0,A.current&&(clearTimeout(A.current),A.current=null),I.current){const Ie=I.current;I.current=null;try{Ie()}catch(le){console.warn("[useEventStream] Error during unsubscribe:",le)}}Y.current=!1},[]),Ye=i.useCallback(async Ie=>{if(pe(),!xe()){L.current=!0,se.current?j("paused","Paused while hidden"):j("offline","Waiting for network");return}X.current&&(await je()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),Ie?.resetAttempts&&(T.current=0),ce(),V.current=Date.now(),j("connecting",null),ms()&&console.info("[useEventStream] Starting event stream...");const le=Ne=>{console.warn("Event stream error:",Ne)},Xe=()=>{const Ne=L.current;if(T.current=0,L.current=!1,V.current=Date.now(),j("connected",null),x(),Me(),Ne)C("sse_reconnected");else{const Se=ge.current;Se&&setTimeout(()=>{M(Se,"sse_reconnected",1/0).then(()=>Z(Se)).catch(qe=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",qe)})},0)}};if(ms()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:S,isCleaningUp:Y.current}),Y.current){ms()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Ne=Fe.subscribeToGlobalEvents(qe=>{const rt=qe.payload,We=qe.payload,_e=typeof We.properties=="object"&&We.properties!==null?We.properties:{},Ke=qe.directory&&qe.directory!=="global"?{..._e,directory:qe.directory}:_e;oe({type:typeof rt.type=="string"?rt.type:"",properties:Ke})},le,Xe),Se=()=>{try{Ne()}catch(qe){console.warn("[useEventStream] Error during unsubscribe:",qe)}};Y.current?Se():I.current=Se}catch(Ne){console.error("[useEventStream] Error during subscription:",Ne),le(Ne)}},[xe,ce,j,x,M,Z,oe,S,Me,je,pe,C]),mt=i.useCallback(Ie=>{if(!xe()){L.current=!0,ce(),se.current?j("paused","Paused while hidden"):j("offline","Waiting for network");return}const le=T.current+1;T.current=le;const Xe=Ie??`Retrying (${le})`;j("reconnecting",Xe);const Ne=le<=3?Math.min(1e3*Math.pow(2,le-1),8e3):Math.min(2e3*Math.pow(2,le-3),32e3),Se=Math.floor(Math.random()*250),qe=Ne+Se;A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{Ye({resetAttempts:!1})},qe)},[xe,ce,j,Ye]);i.useEffect(()=>{const Ie=me.current;typeof window<"u"&&(window.__messageTracker=P);let le=null;X.current&&typeof window<"u"&&(le=Ke=>{const xt=typeof Ke.detail?.sessionId=="string"?Ke.detail.sessionId:null,nt=typeof Ke.detail?.phase=="string"?Ke.detail.phase:null;xt&&(nt==="idle"||nt==="busy"||nt==="cooldown")&&(ie(xt,nt),Z(xt))},window.addEventListener("openchamber:session-activity",le));const Xe=()=>{ae.current&&(clearTimeout(ae.current),ae.current=null)},Ne=()=>{ae.current||(ae.current=setTimeout(()=>{const Ke=W();B.current=Ke,Ke!=="visible"?(ce(),L.current=!0,j("paused","Paused while hidden")):Xe()},5e3))},Se=()=>{if(B.current=W(),B.current==="visible"){if(Xe(),re("visibility_restore"),L.current||!I.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ke=ge.current;Ke&&(M(Ke,"visibility_restore",cl()).catch(()=>{}),Z(Ke)),Me(),j("connecting","Resuming stream"),Ye({resetAttempts:!0})}}else j("paused","Paused while hidden"),Ne()},qe=()=>{if(B.current=W(),B.current==="visible"&&(Xe(),re("window_focus"),L.current||!I.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ke=ge.current;Ke&&(Z(Ke),M(Ke,"window_focus",cl()).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(xt=>console.warn("[useEventStream] Failed to refresh messages:",xt))),Me(),j("connecting","Resuming stream"),Ye({resetAttempts:!0})}},rt=()=>{se.current=!0,re("network_restored"),(L.current||!I.current)&&(j("connecting","Network restored"),Ye({resetAttempts:!0}))},We=()=>{se.current=!1,L.current=!0,j("offline","Waiting for network"),ce()};typeof document<"u"&&document.addEventListener("visibilitychange",Se),typeof window<"u"&&(window.addEventListener("online",rt),window.addEventListener("offline",We),window.addEventListener("focus",qe));const _e=setTimeout(()=>{Ye({resetAttempts:!0})},100);return O.current&&clearInterval(O.current),O.current=setInterval(()=>{if(!xe())return;const Ke=Date.now();Array.from(fe.getState().sessionActivityPhase?.values?.()??[]).some(nt=>nt==="busy"||nt==="cooldown")&&Me(),Ke-V.current>45e3&&Promise.resolve().then(async()=>{try{await Fe.checkHealth()?V.current=Date.now():mt("Refreshing stalled stream")}catch(nt){console.warn("Health check after stale stream failed:",nt),mt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(_e),le&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",le),typeof document<"u"&&document.removeEventListener("visibilitychange",Se),typeof window<"u"&&(window.removeEventListener("online",rt),window.removeEventListener("offline",We),window.removeEventListener("focus",qe)),Xe(),O.current&&(clearInterval(O.current),O.current=null),Ie.forEach(Ke=>clearTimeout(Ke)),Ie.clear(),Dl.clear(),z.current.clear(),H.current.clear(),L.current=!1,B.current=W(),se.current=typeof navigator>"u"?!0:navigator.onLine,ce(),K.current&&(clearTimeout(K.current),K.current=null),j("idle",null)}},[S,P,W,ce,j,Ye,mt,m,Z,ie,Me,xe,f,re,M])},$k=()=>{const{openNewSessionDraft:t,abortCurrentOperation:r,armAbortPrompt:s,clearAbortPrompt:n,currentSessionId:o}=fe(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=ke(),{themeMode:p,setThemeMode:h}=en(),{working:x}=Jf(),g=i.useRef(null),w=i.useRef(null),y=i.useRef(!1),v=i.useCallback(()=>{w.current&&(clearTimeout(w.current),w.current=null),g.current=null,n()},[n]);i.useEffect(()=>{const S=k=>{if(Ls(k)&&k.key==="k"&&(k.preventDefault(),a()),Ls(k)&&k.shiftKey&&k.key.toLowerCase()==="l"){const N=Ms()?.diagnostics;if(!N||(k.preventDefault(),y.current))return;y.current=!0,N.downloadLogs().then(({fileName:D,content:j})=>{const M=D||"openchamber.log",C=new Blob([j],{type:"text/plain;charset=utf-8"}),P=URL.createObjectURL(C),E=document.createElement("a");E.href=P,E.download=M,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(P)}).finally(()=>{y.current=!1});return}if(Ls(k)&&k.key==="."&&(k.preventDefault(),l()),Ls(k)&&k.key.toLowerCase()==="n"){k.preventDefault();const b=Vt(),N=et.getState().settingsAutoCreateWorktree;if(b?!1:N?!k.shiftKey:k.shiftKey){u("chat"),d(!1),si();return}u("chat"),d(!1),t()}if(Ls(k)&&k.key==="/"){k.preventDefault();const b=["light","dark","system"],D=(b.indexOf(p)+1)%b.length;h(b[D])}if(Ls(k)&&!k.shiftKey&&k.key.toLowerCase()==="t"){k.preventDefault();const{isTimelineDialogOpen:b,setTimelineDialogOpen:N}=ke.getState();N(!b);return}if(Ls(k)&&!k.shiftKey&&k.key===","){k.preventDefault();const{isSettingsDialogOpen:b}=ke.getState();m(!b);return}if(Ls(k)&&!k.shiftKey&&k.key.toLowerCase()==="l"){k.preventDefault();const{isMobile:b,isSessionSwitcherOpen:N}=ke.getState();b?d(!N):c();return}if(Ls(k)&&!k.shiftKey&&k.key.toLowerCase()==="i"){k.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Ls(k)&&k.shiftKey&&k.key.toLowerCase()==="m"){const{isSettingsDialogOpen:b,isCommandPaletteOpen:N,isHelpDialogOpen:D,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C,isModelSelectorOpen:P}=ke.getState();if(b||N||D||j||M||!(C==="chat"))return;k.preventDefault(),f(!P);return}if(Ls(k)&&k.shiftKey&&k.key.toLowerCase()==="t"){const{isSettingsDialogOpen:b,isCommandPaletteOpen:N,isHelpDialogOpen:D,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C}=ke.getState();if(b||N||D||j||M||!(C==="chat"))return;const I=et.getState();if(I.getCurrentModelVariants().length===0)return;k.preventDefault(),I.cycleCurrentVariant();const T=et.getState().currentVariant,R=fe.getState(),K=R.currentSessionId,Y=et.getState().currentAgentName,_=et.getState().currentProviderId,J=et.getState().currentModelId;K&&Y&&_&&J&&R.saveAgentModelVariantForSession(K,Y,_,J,T);return}if(k.key==="Escape"){const{isSettingsDialogOpen:b,isCommandPaletteOpen:N,isHelpDialogOpen:D,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C}=ke.getState();if(b){k.preventDefault(),m(!1),v();return}if(N||D||j||M||!(C==="chat")){v();return}const I=o;if(!(x.canAbort&&!!I)){v();return}const T=Date.now(),R=g.current;if(R&&T<R){k.preventDefault(),v(),r();return}k.preventDefault();const K=s(3e3)??T+3e3;g.current=K,w.current&&clearTimeout(w.current);const Y=Math.max(K-T,0);w.current=setTimeout(()=>{g.current&&Date.now()>=g.current&&v()},Y||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[t,r,a,l,c,d,u,m,f,h,p,x,s,v,o]),i.useEffect(()=>()=>{v()},[v])},qu="openchamber:menu-action",Bk=t=>{const{openNewSessionDraft:r}=fe(),{toggleCommandPalette:s,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=ke(),{addProject:u}=zt(),{requestAccess:m,startAccessing:f}=ri(),{setThemeMode:p}=en(),h=i.useRef(!1),x=i.useCallback(()=>{ds()?m("").then(async g=>{if(!g.success||!g.path){g.error&&g.error!=="Directory selection cancelled"&&U.error("Failed to select directory",{description:g.error});return}const w=await f(g.path);if(!w.success){U.error("Failed to open directory",{description:w.error||"Desktop could not grant file access."});return}u(g.path,{id:g.projectId})||U.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(g=>{console.error("Desktop: Error selecting directory:",g),U.error("Failed to select directory")}):qn.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const g=w=>{switch(w.detail){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":s();break;case"new-session":l("chat"),a(!1),r();break;case"new-worktree-session":l("chat"),a(!1),si();break;case"change-workspace":x();break;case"open-git-tab":{const{activeMainTab:v}=ke.getState();l(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=ke.getState();l(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=ke.getState();l(v==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":t?.();break;case"help-dialog":n();break;case"download-logs":{const S=Ms()?.diagnostics;if(!S||h.current)break;h.current=!0,S.downloadLogs().then(({fileName:k,content:b})=>{const N=k||"openchamber.log",D=new Blob([b],{type:"text/plain;charset=utf-8"}),j=URL.createObjectURL(D),M=document.createElement("a");M.href=j,M.download=N,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(j),U.success("Logs saved",{description:`Downloaded to ~/Downloads/${N}`})}).catch(()=>{U.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(qu,g),()=>window.removeEventListener(qu,g)},[r,s,n,o,a,l,c,d,p,t,x])},zk=t=>t.role==="assistant",Ku=t=>{const r=t.info;if(!zk(r))return;const s=r.time?.completed;return typeof s=="number"?s:void 0},wa=t=>{if(!t)return!1;if(t.role==="user")return!0;const r=t;return r.clientRole==="user"?!0:!!r.userMessageMarker},Qu=t=>(Array.isArray(t?.parts)?t.parts:[]).map(n=>ho(n)).join(" ").replace(/\s+/g," ").trim(),Hk=(t,r)=>{if(!t||!wa(t.info))return-1;const s=Qu(t),n=typeof t.info?.time?.created=="number"?t.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((l,c)=>{if(!wa(l.info))return;const d=Qu(l),u=!!(s&&d&&d===s),m=typeof l.info?.time?.created=="number"?l.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=c,a=p);return}!s&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(l=>{if(!wa(l.info))return!1;const c=typeof l.info?.time?.created=="number"?l.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},Wk=()=>{const{currentSessionId:t,messages:r,streamingMessageIds:s}=fe(),n=i.useMemo(()=>t?s.get(t)??null:null,[t,s]),o=i.useRef(void 0),a=i.useRef(0),l=i.useCallback(async()=>{if(!t||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(t)||[],u=fe.getState().sessionMemoryState.get(t),m=Da(),f=u?.isStreaming?m.VIEWPORT_MESSAGES:m.HISTORICAL_MESSAGES,p=f+m.FETCH_BUFFER,h=await Fe.getSessionMessages(t,p),x=await Tk(t);if(!h)return;const g=d[d.length-1];if(g){const w=h.findIndex(S=>S.info.id===g.info.id),v=w===-1?Hk(g,h):w;if(v!==-1)if(v<h.length-1){const S=h.slice(v+1);console.log(`[SYNC] Found ${S.length} new messages to append`);const k=[...d,...S],{syncMessages:b}=fe.getState();b(t,k)}else{const S=h[v],k=d[d.length-1],b=Ku(S),N=Ku(k);if(b&&!N){console.log("[SYNC] Last message completed on server");const D=[...d.slice(0,-1),S],{syncMessages:j}=fe.getState();j(t,D)}}else if(wa(g.info)){const S=h.slice(-f);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:k}=fe.getState();k(t,S)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(x){const w=h.findIndex(y=>y.info.id===x.messageId);if(w!==-1){if(w<h.length-1){const v=h.slice(w+1).slice(-f);if(v.length>0){console.log(`[SYNC] Restoring ${v.length} messages after cursor`);const{syncMessages:S}=fe.getState();S(t,v)}}}else if(h.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const y=h.slice(-f),{syncMessages:v}=fe.getState();v(t,y)}}else if(h.length>0){const w=h.slice(-f);console.log(`[SYNC] Loading last ${w.length} messages`);const{syncMessages:y}=fe.getState();y(t,w)}}catch(d){console.debug("Background sync failed:",d)}}},[t,r,n]);i.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),l()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[l]),i.useEffect(()=>{if(!t||n)return;const c=()=>{document.visibilityState==="visible"&&l(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[t,n,l]),i.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),l())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[l])},Uk=()=>{i.useEffect(()=>{let t=!1;return(async()=>{try{const s=await Fe.getGlobalSessionStatus();if(t||!s)return;const n=new Map;Object.entries(s).forEach(([o,a])=>{if(!o||!a)return;const l=a,c=l.type==="busy"||l.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&fe.setState({sessionActivityPhase:n})}catch{}})(),()=>{t=!0}},[])},Vk=["chat","git","diff","terminal","files"],Gk=["settings","agents","commands","skills","providers","git-identities"],Qs={SESSION:"session",TAB:"tab",SETTINGS:"settings",FILE:"file"};function Yu(t){const r=qk();return{sessionId:Kk(r),tab:Qk(r),settingsSection:Yk(r),diffFile:Xk(r)}}function qk(){if(typeof window>"u")return new URLSearchParams;try{return new URLSearchParams(window.location.search)}catch{return new URLSearchParams}}function Kk(t){const r=t.get(Qs.SESSION);return!r||r.trim().length===0?null:r.trim()}function Qk(t){const r=t.get(Qs.TAB);if(!r)return null;const s=r.toLowerCase().trim();return Vk.includes(s)?s:null}function Yk(t){const r=t.get(Qs.SETTINGS);if(!r)return null;const s=r.toLowerCase().trim();return Gk.includes(s)?s:s==="openchamber"||s==="general"||s==="preferences"?"settings":null}function Xk(t){const r=t.get(Qs.FILE);if(!r||r.trim().length===0)return null;try{return decodeURIComponent(r.trim())}catch{return r.trim()}}function Xu(){if(typeof window>"u")return!1;try{const t=new URLSearchParams(window.location.search);return t.has(Qs.SESSION)||t.has(Qs.TAB)||t.has(Qs.SETTINGS)||t.has(Qs.FILE)}catch{return!1}}const Jk="chat";function Tp(t){const r=new URLSearchParams;if(t.sessionId&&t.sessionId.trim().length>0&&r.set(Qs.SESSION,t.sessionId),t.isSettingsOpen){const s=t.settingsSection==="sessions"?"settings":t.settingsSection;return r.set(Qs.SETTINGS,s),r}return t.tab!==Jk&&r.set(Qs.TAB,t.tab),t.tab==="diff"&&t.diffFile&&t.diffFile.trim().length>0&&r.set(Qs.FILE,t.diffFile),r}function Zk(t,r){const s=typeof window<"u"?window.location.pathname:"/",n=t.toString();return n?`${s}?${n}`:s}function eC(t){if(typeof window>"u")return!0;try{const r=new URLSearchParams(window.location.search),s=Tp(t),n=[...r.entries()].sort((a,l)=>a[0].localeCompare(l[0])),o=[...s.entries()].sort((a,l)=>a[0].localeCompare(l[0]));if(n.length!==o.length)return!1;for(let a=0;a<n.length;a++)if(n[a][0]!==o[a][0]||n[a][1]!==o[a][1])return!1;return!0}catch{return!0}}function tC(t,r={}){if(!(typeof window>"u")&&!sC()&&!(!r.force&&eC(t)))try{const s=Tp(t),n=Zk(s);r.replace?window.history.replaceState({...window.history.state,route:t},"",n):window.history.pushState({route:t},"",n)}catch{}}function sC(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function rC(){return typeof window>"u"?!1:window.__VSCODE_CONFIG__!==void 0}function nC(){const t=i.useMemo(()=>rC(),[]),r=i.useRef(!1),s=i.useRef(!1),n=fe(f=>f.setCurrentSession),o=ke(f=>f.setActiveMainTab),a=ke(f=>f.setSettingsDialogOpen),l=ke(f=>f.setSidebarSection),c=ke(f=>f.navigateToDiff),d=i.useCallback(async f=>{if(!s.current){s.current=!0;try{if(f.sessionId){const p=fe.getState().currentSessionId;f.sessionId!==p&&await n(f.sessionId)}if(f.settingsSection){l(f.settingsSection),a(!0);return}ke.getState().isSettingsDialogOpen&&a(!1),f.tab&&o(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&c(f.diffFile)}finally{s.current=!1}}},[n,o,a,l,c]),u=i.useCallback(()=>{const f=fe.getState(),p=ke.getState();return{sessionId:f.currentSessionId,tab:p.activeMainTab,isSettingsOpen:p.isSettingsDialogOpen,settingsSection:p.sidebarSection,diffFile:p.pendingDiffFile}},[]),m=i.useCallback((f={})=>{if(t||s.current)return;const p=u();tC(p,f)},[t,u]);i.useEffect(()=>{if(r.current||(r.current=!0,!Xu()))return;const f=Yu();(async()=>(await d(f),t||m({replace:!0})))()},[d,t,m]),i.useEffect(()=>{if(t)return;let f=fe.getState().currentSessionId;return fe.subscribe(h=>{const x=h.currentSessionId;x===f||s.current||(f=x,m())})},[t,m]),i.useEffect(()=>{if(t)return;let f=ke.getState().activeMainTab,p=ke.getState().isSettingsDialogOpen,h=ke.getState().sidebarSection,x=ke.getState().pendingDiffFile;return ke.subscribe(w=>{if(s.current)return;const y=w.activeMainTab!==f,v=w.isSettingsDialogOpen!==p,S=w.sidebarSection!==h,k=w.pendingDiffFile!==x&&w.activeMainTab==="diff";f=w.activeMainTab,p=w.isSettingsDialogOpen,h=w.sidebarSection,x=w.pendingDiffFile,(y||v||S||k)&&m()})},[t,m]),i.useEffect(()=>{if(typeof window>"u"||t)return;const f=()=>{const p=Yu();if(Xu())d(p);else{const h=ke.getState();h.isSettingsDialogOpen&&a(!1),h.activeMainTab!=="chat"&&o("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[d,t,o,a])}const oC=1e4,Ju=()=>{if(typeof document>"u")return"visible";const t=document.visibilityState;return t==="hidden"&&document.hasFocus()?"visible":t},Zu=t=>{if(!br())return;const r=Ms();r?.push?.setVisibility&&r.push.setVisibility({visible:t})},aC=()=>{i.useEffect(()=>{if(!br()||typeof document>"u")return;const t=()=>{Zu(Ju()==="visible")},r=()=>{Ju()==="visible"&&Zu(!0)};t();const s=window.setInterval(r,oC);return document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),window.addEventListener("blur",t),()=>{window.clearInterval(s),document.removeEventListener("visibilitychange",t),window.removeEventListener("pagehide",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t),window.removeEventListener("blur",t)}},[])};function iC(){const{git:t}=Zs(),r=gt(m=>m.currentDirectory),{currentSessionId:s,sessions:n,worktreeMetadata:o}=fe(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=ls(),u=i.useMemo(()=>{const m=s?o.get(s)??void 0:void 0,p=n.find(h=>h.id===s)?.directory??null;return m?.path??p??r??null},[s,n,o,r]);i.useEffect(()=>{if(!u||!t){c();return}return a(u),d(u,t),l(t),()=>{c()}},[u,t,a,l,c,d])}function lC({children:t}){return iC(),e.jsx(e.Fragment,{children:t})}const cC=()=>{const[{isUpdating:t,message:r},s]=i.useState(()=>Zx());return i.useEffect(()=>Jx(s),[]),t?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[e.jsx(mc,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Fp={getLastAssistantMessage(){const t=fe.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const s=t.messages.get(r);if(!s||s.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=s.length-1;n>=0;n--){const o=s[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const h={id:p.id,type:p.type};return p.type==="text"?(h.text=p.text,h.textLength=p.text?.length||0):p.type==="tool"?(h.tool=p.tool,h.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(h.isStepMarker=!0),h}),l=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),c=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!l&&!c&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:l,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!l&&!c}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!l&&!c&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(t,r=80){return!t||typeof t!="string"||t.length<=r?t:t.substring(0,r)+"…"},truncateMessages(t){return t.map(r=>({...r,parts:(r.parts||[]).map(s=>{const n={...s};return"text"in s&&(n.text=this.truncateString(s.text)),"textPreview"in s&&(n.textPreview=this.truncateString(s.textPreview)),s.state&&(n.state={...s.state},"output"in s.state&&(n.state.output=this.truncateString(s.state.output)),"error"in s.state&&(n.state.error=this.truncateString(s.state.error)),s.state.metadata&&"preview"in s.state.metadata&&(n.state.metadata={...s.state.metadata,preview:this.truncateString(s.state.metadata.preview)})),n})}))},getAllMessages(t=!1){const r=fe.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),[];const n=r.messages.get(s)||[];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`)}),t?this.truncateMessages(n):n},async getAppStatus(){const t=gt.getState(),r=fe.getState(),s=zt.getState(),n=t.currentDirectory||null,o=Fe.getDirectory()??null,a=r.sessions||[],l=new Set,c={};a.forEach(j=>{const M=j.directory;typeof M=="string"&&M.trim().length>0?(l.add(M),c[M]=(c[M]??0)+1):c["(none)"]=(c["(none)"]??0)+1});const d=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(j){return{available:!1,error:j instanceof Error?j.message:String(j)}}})(),u=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,m=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,f=!!(u?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),p=async j=>{try{return await j.json()}catch{return null}},h=async j=>{try{return await j.text()}catch{return null}},x=async j=>{try{const M=await fetch(j);return M.ok?await p(M):{status:M.status}}catch(M){return{error:M instanceof Error?M.message:String(M)}}};let g=null,w=null,y=null,v=null;const S=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";g=await x(S);const k=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";w=await x(k),y=await x("/api/config/settings");try{const j=await fetch("/api/health"),M=j.headers.get("content-type")||"",C=await h(j);v={status:j.status,ok:j.ok,contentType:M,type:M.includes("application/json")?"json":"html",preview:C?C.slice(0,120):null}}catch(j){v={error:j instanceof Error?j.message:String(j)}}let b={isGitRepo:null};if(n)try{b.isGitRepo=await Or(n)}catch(j){b={isGitRepo:null,error:j instanceof Error?j.message:String(j)}}const N=s.projects.map(j=>({id:j.id,path:j.path,label:j.label})),D={runtime:{platform:u?.runtime?.platform??null,isDesktop:f,isVSCode:!!u?.runtime?.isVSCode,hasRuntimeApis:!!u,desktopServerOrigin:m?.origin??null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:n,opencodeDirectory:g?.directory||g?.worktree||o,homeDirectory:t.homeDirectory||null,isHomeReady:t.isHomeReady,hasPersistedDirectory:t.hasPersistedDirectory,isSwitchingDirectory:t.isSwitchingDirectory},projects:{total:s.projects.length,activeProjectId:s.activeProjectId,samples:N},sessions:{total:a.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:l.size,directorySamples:Array.from(l).slice(0,5),directoryCounts:c},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:b,localStorage:d,opencode:{pathInfo:g,projectInfo:w,health:v},openchamber:{settingsInfo:y}};return console.log("[DEBUG] App status snapshot:",D),D},async buildDiagnosticsReport(){const t=await this.getAppStatus();return JSON.stringify(t,null,2)},async copyDiagnosticsReport(){const t=await this.buildDiagnosticsReport();return typeof navigator<"u"&&navigator.clipboard?(await navigator.clipboard.writeText(t),{ok:!0,report:t}):{ok:!1,report:t}},checkLastMessage(){const t=this.getLastAssistantMessage();if(!t)return!1;const r=t.isEmpty||t.isEmptyResponse;return r?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:t.messageId,isEmpty:t.isEmpty,isEmptyResponse:t.isEmptyResponse,partsCount:t.partsCount}),t.parts.length>0&&console.log("Parts:",t.parts)):console.log("[OK] Last message looks good!"),r},getStreamingState(){const t=fe.getState(),r=t.currentSessionId?t.streamingMessageIds.get(t.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:r,streamingMessageIds:Array.from(t.streamingMessageIds.entries()),messageStreamStates:Array.from(t.messageStreamStates.entries())}),{streamingMessageId:r,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){const t=fe.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(t.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],l=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!l&&!c});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
216
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
217
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
218
- `),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)
219
- `),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(t={}){const{includeNonAssistant:r=!1,verbose:s=!0,maxTableRows:n=25}=t,o=fe.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const l=o.messages.get(a)||[],c=r?l:l.filter(p=>p.info.role==="assistant"),d={totalMessages:l.length,analyzedMessages:c.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const h=p.filter(x=>typeof x=="number");return h.length>0?Math.max(...h):null},f=c.map((p,h)=>{const x=p.info??{},g=Array.isArray(p.parts)?p.parts:[],w=x.time??{},y=u(w.completed),v=y!==null,S=g.filter(E=>E.type==="tool"),k=g.filter(E=>E.type==="reasoning"),b=m(S.map(E=>u(E.state?.time?.end??E.state?.time?.start))),N=m(k.map(E=>u(E.time?.end??E.time?.start))),D=m([b,N].filter(E=>E!==null)),j=S.some(E=>["pending","running","started"].includes(E.state?.status)),M=k.some(E=>typeof E.time?.end!="number");S.length>0&&(d.withTools+=1),k.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const C=!!(v&&typeof b=="number"&&y<b);C&&(d.completedBeforeTool+=1);const P=!!(v&&typeof N=="number"&&y<N);return P&&(d.completedBeforeReasoning+=1),v&&j&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:x.id,role:x.role,completedAt:y,latestToolTimestamp:b,latestReasoningTimestamp:N,latestPartTimestamp:D,completed_missing:!v,completed_before_tool:C,completed_before_reasoning:P,running_tools_when_completed:!!(v&&j),reasoning_open_when_completed:!!(v&&M),has_tools:S.length>0,has_reasoning:k.length>0}});return s&&(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 t=fe.getState(),r=t.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(t.messages.get(r)||[]).filter(w=>w.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(w=>w.type==="step-finish"),l=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&l),p=t.messageStreamStates,h=o.info.sessionID?t.streamingMessageIds.get(o.info.sessionID)??null:null,x=p.get(o.info.id),g=o.info.id===h;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",l),console.log("messageIsComplete:",f),console.log("lifecycle phase:",x?.phase),console.log("isStreamingCandidate:",g),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:l,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Fp,ms()&&(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",t=>{try{const r=t.message||"",s=t.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(s))&&t.preventDefault()}catch{}}));const dC=({open:t,onOpenChange:r})=>{const[s,n]=i.useState(null),[o,a]=i.useState(!1),[l,c]=i.useState(!1),d=i.useCallback(async()=>{if(!o){a(!0),c(!1);try{(await Fp.copyDiagnosticsReport()).ok?(c(!0),U.success("Diagnostics copied")):U.error("Copy failed")}catch(m){U.error("Copy failed"),console.error("Failed to copy diagnostics:",m)}finally{a(!1)}}},[o]);i.useEffect(()=>{if(!t)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:p}=await Ss(async()=>{const{getVersion:x}=await import("./vendor-.bun-CaD8MAGl.js").then(g=>g.dg);return{getVersion:x}},__vite__mapDeps([0,1])),h=await p();n(h)}catch{n("1.5.6")}})():n("1.5.6")},[t]);const u=s;return e.jsx(ps,{open:t,onOpenChange:r,children:e.jsx(hs,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(mc,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",u]})]}),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 flex-col items-center gap-2 pt-2",children:[e.jsx("button",{onClick:d,disabled:o,className:F("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:l?"Diagnostics copied":"Copy diagnostics"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Includes OpenChamber state, OpenCode health, directories, and projects."})]}),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(ja,{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(Im,{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(rl,{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:t,children:r}){return e.jsx(Yl.Provider,{value:t,children:r})}const uC="curl -fsSL https://opencode.ai/install | bash",mC=3e3;function fC({onCopy:t}){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:t,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Js,{className:"h-4 w-4"})})]})}const pC=3e4;function hC({onCliAvailable:t}){const[r,s]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),pC);return()=>clearTimeout(m)},[]),i.useEffect(()=>{l(typeof window.opencodeDesktop<"u")},[]);const c=i.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await Ss(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-CaD8MAGl.js").then(x=>x.df);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=i.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=i.useCallback(async()=>{try{await navigator.clipboard.writeText(uC),s(!0),setTimeout(()=>s(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return i.useEffect(()=>{const m=async()=>{await d()&&t?.()},f=setInterval(m,mC);return m(),()=>clearInterval(f)},[d,t]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(dr,{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(Qt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(fC,{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(dr,{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 gC=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:r}=ke();return e.jsx(dC,{open:t,onOpenChange:r})};function xC({apis:t}){const{initializeApp:r,isInitialized:s,isConnected:n}=et(),{error:o,clearError:a,loadSessions:l}=fe(),c=gt(b=>b.currentDirectory),d=gt(b=>b.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=gp(),[h,x]=i.useState(()=>t.runtime.isDesktop),[g,w]=i.useState(()=>t.runtime.isVSCode),[y,v]=i.useState(()=>t.runtime.isDesktop?Tx():!0);i.useEffect(()=>{x(t.runtime.isDesktop),w(t.runtime.isVSCode)},[t.runtime.isDesktop,t.runtime.isVSCode]),i.useEffect(()=>(Fc(t),()=>Fc(null)),[t]),i.useEffect(()=>{if(typeof document>"u")return;const b=document.documentElement,N=hu[f]?.stack??hu[NS].stack,D=nn[p]?.stack??nn[ya].stack;b.style.setProperty("--font-sans",N),b.style.setProperty("--font-heading",N),b.style.setProperty("--font-family-sans",N),b.style.setProperty("--font-mono",D),b.style.setProperty("--font-family-mono",D),b.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=N)},[f,p]),i.useEffect(()=>{if(s){const N=setTimeout(()=>{const D=document.getElementById("initial-loading");D&&(D.classList.add("fade-out"),setTimeout(()=>{D.remove()},300))},150);return()=>clearTimeout(N)}},[s]),i.useEffect(()=>{const b=setTimeout(()=>{const N=document.getElementById("initial-loading");N&&!s&&(N.classList.add("fade-out"),setTimeout(()=>{N.remove()},300))},5e3);return()=>clearTimeout(b)},[s]),i.useEffect(()=>{(async()=>g||await r())()},[r,g]),i.useEffect(()=>{if(d)return;(async()=>g||n&&(Fe.setDirectory(c),await l()))()},[c,d,l,n,g]),_k(),aC(),nC(),$k();const S=i.useCallback(()=>{m(b=>!b)},[]);Bk(S),Wk(),Uk(),kp(),i.useEffect(()=>{const b=N=>{Ls(N)&&N.shiftKey&&N.key==="D"&&(N.preventDefault(),m(D=>!D))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const k=i.useCallback(()=>{v(!0),window.location.reload()},[]);return h&&!y?e.jsx(gs,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(hC,{onCliAvailable:k})})}):g?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(gs,{children:e.jsx(Yi,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Ck,{}),e.jsx(Di,{})]})})}):e.jsx(gs,{children:e.jsx(Yi,{apis:t,children:e.jsx(iu,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(pk,{}),e.jsx(Di,{})]})})})}):e.jsx(gs,{children:e.jsx(Yi,{apis:t,children:e.jsx(lC,{children:e.jsx(iu,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(dk,{}),e.jsx(Di,{}),e.jsx(cC,{}),e.jsx(gC,{}),u&&e.jsx(Dk,{onClose:()=>m(!1)})]})})})})})}const Rp=async()=>{if(typeof window>"u")return;let t=null,r=null;try{t=window.localStorage.getItem("homeDirectory"),r=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const s=gt.getState();t&&s.homeDirectory!==t&&s.synchronizeHomeDirectory(t),r&&!Vt()&&s.setDirectory(r,{showOverlay:!1})},Lp="/auth/session",yC=async()=>fetch(Lp,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),em=async t=>fetch(Lp,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})}),yc=({children:t})=>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:t})]}),bC=({message:t="Preparing workspace…"})=>e.jsx(yc,{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:t})})}),wC=({onRetry:t})=>e.jsx(yc,{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(ve,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})}),vC=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},jC=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},SC=({children:t})=>{const r=i.useMemo(()=>ds(),[]),s=i.useMemo(()=>Vt(),[]),n=r||s,[o,a]=i.useState(()=>n?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),h=i.useRef(n),x=i.useRef(!1),g=i.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await yC();if(y.ok){a("authenticated"),f("");return}if(y.status===401){a("locked");return}a("error")}catch(y){console.warn("Failed to check session status:",y),a("error")}},[n]);i.useEffect(()=>{n||g()},[g,n]),i.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),i.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),i.useEffect(()=>{if(n||o!=="locked"||x.current||d)return;const y=vC();y&&(x.current=!0,jC(),u(!0),f(""),em(y).then(v=>{if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(v=>{console.warn("Failed to submit URL token:",v),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),i.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await $m(),await Bm(),await Rp()))())},[n,o]);const w=async y=>{if(y.preventDefault(),!(!l||d)){u(!0),f("");try{const v=await em(l);if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(v){console.warn("Failed to submit UI password:",v),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(bC,{}):o==="error"?e.jsx(wC,{onRetry:()=>{g()}}):o==="locked"?e.jsx(yc,{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:w,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(mx,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(bt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:l,onChange:y=>{c(y.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(ve,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Ft,{className:"h-4 w-4 animate-spin"}):e.jsx(fx,{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:t})},Xi=t=>{if(!t||typeof t!="string")return null;const r=t.trim();if(!r.startsWith("#"))return null;let s=r.slice(1);if((s.length===3||s.length===4)&&(s=s.split("").map(c=>c+c).join("")),s.length===8&&(s=s.slice(0,6)),s.length!==6)return null;const n=Number.parseInt(s,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,l=n&255;return`${o} ${a} ${l}`};class NC{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const s=[];return s.push(...this.generateTailwindVariables(r)),s.push(...this.generatePrimaryColors(r.colors.primary)),s.push(...this.generateSurfaceColors(r.colors.surface)),s.push(...this.generateInteractiveColors(r.colors.interactive)),s.push(...this.generateStatusColors(r.colors.status)),s.push(...this.generateSyntaxColors(r.colors.syntax)),s.push(...this.generateComponentColors(r.colors,r)),s.push(...this.generateTypographyVariables()),r.config&&s.push(...this.generateConfigVariables(r.config)),s.join(`
220
- `)}generateTailwindVariables(r){const s=[];s.push(` --background: ${r.colors.surface.background} !important;`),s.push(` --foreground: ${r.colors.surface.foreground} !important;`),s.push(` --muted: ${r.colors.surface.muted} !important;`),s.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --card: ${r.colors.surface.elevated} !important;`),s.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),s.push(` --popover: ${r.colors.surface.elevated} !important;`),s.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),s.push(` --border: ${r.colors.interactive.border} !important;`),s.push(` --input: ${r.colors.interactive.border} !important;`),s.push(` --primary: ${r.colors.primary.base} !important;`),s.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),s.push(` --secondary: ${r.colors.surface.muted} !important;`),s.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --accent: ${r.colors.surface.subtle} !important;`),s.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),s.push(` --destructive: ${r.colors.status.error} !important;`),s.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),s.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&s.push(` --radius: ${r.config.radius.md} !important;`);const n=Xi(r.colors.surface.muted),o=Xi(r.colors.surface.subtle),a=Xi(r.colors.interactive.border);s.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&s.push(` --sidebar-base-rgb: ${n} !important;`),s.push(" --sidebar: var(--sidebar-base) !important;"),s.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),s.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),s.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),s.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&s.push(` --sidebar-accent-base-rgb: ${o} !important;`),s.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),s.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),s.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&s.push(` --sidebar-border-rgb: ${a} !important;`),s.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const l=r.metadata.variant==="dark",c=l?.8:.95,d=l?.7:.9;if(n)s.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),s.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;s.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),s.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)=>{s.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(s.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),s.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(s.push(` --loading-spinner: ${r.colors.primary.base};`),s.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),s}apply(r){const s=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
221
- ${s}
222
- }
223
-
224
- .dark {
225
- ${s}
226
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
227
- ${s}
228
- }
229
-
230
- :root:not(.dark) {
231
- ${s}
232
- }`,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 s=[];return s.push(` --primary-base: ${r.base};`),s.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),s.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),s.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),s.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),s.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),s}generateSurfaceColors(r){const s=[];return s.push(` --surface-background: ${r.background};`),s.push(` --surface-foreground: ${r.foreground};`),s.push(` --surface-muted: ${r.muted};`),s.push(` --surface-muted-foreground: ${r.mutedForeground};`),s.push(` --surface-elevated: ${r.elevated};`),s.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),s.push(` --surface-overlay: ${r.overlay};`),s.push(` --surface-subtle: ${r.subtle};`),s}generateInteractiveColors(r){const s=[];return s.push(` --interactive-border: ${r.border};`),s.push(` --interactive-border-hover: ${r.borderHover};`),s.push(` --interactive-border-focus: ${r.borderFocus};`),s.push(` --interactive-selection: ${r.selection};`),s.push(` --interactive-selection-foreground: ${r.selectionForeground};`),s.push(` --interactive-focus: ${r.focus};`),s.push(` --interactive-focus-ring: ${r.focusRing};`),s.push(` --interactive-cursor: ${r.cursor};`),s.push(` --interactive-hover: ${r.hover};`),s.push(` --interactive-active: ${r.active};`),s}generateStatusColors(r){const s=[];return s.push(` --status-error: ${r.error};`),s.push(` --status-error-foreground: ${r.errorForeground};`),s.push(` --status-error-background: ${r.errorBackground};`),s.push(` --status-error-border: ${r.errorBorder};`),s.push(` --status-warning: ${r.warning};`),s.push(` --status-warning-foreground: ${r.warningForeground};`),s.push(` --status-warning-background: ${r.warningBackground};`),s.push(` --status-warning-border: ${r.warningBorder};`),s.push(` --status-success: ${r.success};`),s.push(` --status-success-foreground: ${r.successForeground};`),s.push(` --status-success-background: ${r.successBackground};`),s.push(` --status-success-border: ${r.successBorder};`),s.push(` --status-info: ${r.info};`),s.push(` --status-info-foreground: ${r.infoForeground};`),s.push(` --status-info-background: ${r.infoBackground};`),s.push(` --status-info-border: ${r.infoBorder};`),s}generateSyntaxColors(r){const s=[];s.push(` --syntax-background: ${r.base.background};`),s.push(` --syntax-foreground: ${r.base.foreground};`),s.push(` --syntax-comment: ${r.base.comment};`),s.push(` --syntax-keyword: ${r.base.keyword};`),s.push(` --syntax-string: ${r.base.string};`),s.push(` --syntax-number: ${r.base.number};`),s.push(` --syntax-function: ${r.base.function};`),s.push(` --syntax-variable: ${r.base.variable};`),s.push(` --syntax-type: ${r.base.type};`),s.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))s.push(` --syntax-${this.kebabCase(o)}: ${a};`);return s}generateSyntaxTokens(r){const s=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(s.comment,10),stringEscape:n.stringEscape||this.darken(s.string,20),stringInterpolation:n.stringInterpolation||s.variable,stringRegex:n.stringRegex||this.adjustHue(s.string,15),keywordControl:n.keywordControl||s.keyword,keywordOperator:n.keywordOperator||s.operator,keywordImport:n.keywordImport||this.lighten(s.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(s.keyword),functionCall:n.functionCall||this.lighten(s.function,5),functionBuiltin:n.functionBuiltin||this.darken(s.function,10),method:n.method||s.function,methodCall:n.methodCall||this.lighten(s.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(s.variable),variableProperty:n.variableProperty||this.lighten(s.variable,10),variableReadonly:n.variableReadonly||s.number,parameter:n.parameter||s.variable,typePrimitive:n.typePrimitive||this.darken(s.type,10),typeInterface:n.typeInterface||s.type,className:n.className||this.emphasize(s.type),enum:n.enum||s.type,boolean:n.boolean||s.number,null:n.null||this.opacity(s.number,.7),constant:n.constant||s.number,punctuation:n.punctuation||this.opacity(s.foreground,.7),delimiter:n.delimiter||this.opacity(s.foreground,.8),bracket:n.bracket||s.foreground,tag:n.tag||s.keyword,tagAttribute:n.tagAttribute||s.variable,tagAttributeValue:n.tagAttributeValue||s.string,tagBracket:n.tagBracket||this.opacity(s.foreground,.8),decorator:n.decorator||s.function,annotation:n.annotation||s.function,namespace:n.namespace||this.opacity(s.type,.8),module:n.module||this.opacity(s.type,.8),...n}}generateComponentColors(r,s){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,s)):n.push(...this.generateDefaultMarkdownColors(s)),r.chat?n.push(...this.generateChatColors(r.chat,s)):n.push(...this.generateDefaultChatColors(s)),r.tools?n.push(...this.generateToolColors(r.tools,s)):n.push(...this.generateDefaultToolColors(s)),n}generateMarkdownColors(r,s){const n=[],o=s.colors.primary.base,a=s.colors.chat?.background||s.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||s.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||s.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||s.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||s.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||s.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||s.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(s.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||s.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||s.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const s=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return s.push(` --markdown-heading1: ${n};`),s.push(` --markdown-heading2: ${this.opacity(n,.9)};`),s.push(` --markdown-heading3: ${this.opacity(n,.8)};`),s.push(` --markdown-heading4: ${r.colors.surface.foreground};`),s.push(` --markdown-link: ${n};`),s.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),s.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),s.push(` --markdown-inline-code-bg: ${o};`),s.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),s.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),s.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),s.push(` --markdown-bold: ${r.colors.surface.foreground};`),s.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),s.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),s.push(` --markdown-hr: ${r.colors.interactive.border};`),s}generateChatColors(r,s){const n=[],o=r.background||s.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||s.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||s.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||s.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||s.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||s.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||s.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||s.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const s=[];return s.push(` --chat-background: ${r.colors.surface.background};`),s.push(` --chat-user-message: ${r.colors.surface.foreground};`),s.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),s.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),s.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),s.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),s.push(` --chat-divider: ${r.colors.interactive.border};`),s.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),s}generateToolColors(r,s){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(s.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(s.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(s.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||s.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||s.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(s.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||s.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||s.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||s.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||s.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||s.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||s.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(s.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${s.colors.status.success};`),n.push(` --tools-edit-added-bg: ${s.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${s.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${s.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${s.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${s.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(s.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const s=[];return s.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),s.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),s.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),s.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),s.push(` --tools-title: ${r.colors.surface.foreground};`),s.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),s.push(` --tools-edit-added: ${r.colors.status.success};`),s.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),s.push(` --tools-edit-removed: ${r.colors.status.error};`),s.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),s.push(` --tools-edit-modified: ${r.colors.status.info};`),s.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),s.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),s}generateConfigVariables(r){const s=[];return r&&(r.fonts&&(r.fonts.sans&&(s.push(` --font-sans: ${r.fonts.sans};`),s.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(s.push(` --font-mono: ${r.fonts.mono};`),s.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&s.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&s.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&s.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&s.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&s.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&s.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&s.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&s.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&s.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&s.push(` --transition-slow: ${r.transitions.slow};`))),s}generateTypographyVariables(){const r=[],s=Vt()?Wx:$l;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: ${s.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${s.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${s.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${s.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${s.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${s.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,s){return r.startsWith("#")?`${r}${Math.round(s*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${s})`):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,s){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),l=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${l}, ${s})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),l=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${l}, ${s})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${s})`):r}darken(r,s){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*s),a=(n>>16)-o,l=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return r}lighten(r,s){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*s),a=(n>>16)+o,l=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return r}adjustHue(r,s){return this.lighten(r,s/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const bc={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"}}},wc={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"}}},Mo=[bc,wc];function Ba(t){return Mo.find(r=>r.metadata.id===t)}const Op=bc.metadata.id,_p=wc.metadata.id,kC=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,$p=t=>t==="dark"?wc:bc,CC=t=>(Mo.find(s=>s.metadata.variant===t)??$p(t)).metadata.id,ra=(t,r)=>{const s=Ba(t);return s&&s.metadata.variant===r?s:Mo.find(o=>o.metadata.variant===r)??$p(r)},MC=typeof window<"u"?i.useLayoutEffect:i.useEffect,za=(t,r)=>{if(!t)return r==="light"?Op:_p;const s=Ba(t);return s&&s.metadata.variant===r?s.metadata.id:CC(r)},DC=t=>{let r=Op,s=_p,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),l=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const f=Ba(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?s=f.metadata.id:r=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);r=za(a,"light"),s=za(l,"dark")}if(t){const o=Ba(t);o&&(o.metadata.variant==="light"?r=o.metadata.id:s=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:s}};function AC({children:t,defaultThemeId:r}){const s=Re.useMemo(()=>new NC,[]),[n,o]=Re.useState(()=>DC(r)),[a,l]=Re.useState(()=>kC()),[c,d]=Re.useState(()=>typeof window>"u"||!Vt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Re.useMemo(()=>Vt(),[]),m=Re.useMemo(()=>u&&c?c:n.themeMode==="light"?ra(n.lightThemeId,"light"):n.themeMode==="dark"||a?ra(n.darkThemeId,"dark"):ra(n.lightThemeId,"light"),[u,n,a,c]),f=Re.useMemo(()=>u&&c?[c,...Mo]:Mo,[u,c]);Re.useEffect(()=>{if(!u)return;const k=D=>{d(D);const j=D.metadata.variant==="dark"?"dark":"light",M=ke.getState();M.theme!==j&&M.setTheme(j)},b=D=>{const j=D.detail;j?.theme&&k(j.theme)},N=window.__OPENCHAMBER_VSCODE_THEME__;return N&&k(N),window.addEventListener("openchamber:vscode-theme",b),()=>window.removeEventListener("openchamber:vscode-theme",b)},[u]);const p=Re.useCallback(k=>{if(typeof document>"u")return;const b=k.colors.surface.background;ds()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=b;let N=document.querySelector('meta[name="theme-color"]');N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),document.head.appendChild(N)),N.setAttribute("content",b);const D=k.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let j=document.querySelector(`meta[name="theme-color"][media="${D}"]`);j||(j=document.createElement("meta"),j.setAttribute("name","theme-color"),j.setAttribute("media",D),document.head.appendChild(j)),j.setAttribute("content",b)},[]),h=Re.useCallback(k=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",k)},[]);MC(()=>{if(typeof window>"u")return;s.apply(m),h(u),p(m);const k=document.documentElement;k.classList.remove("light","dark"),k.classList.add(m.metadata.variant)},[h,s,m,u,p]),Re.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const k=window.matchMedia("(prefers-color-scheme: dark)"),b=N=>{l(N.matches)};return l(k.matches),k.addEventListener("change",b),()=>k.removeEventListener("change",b)},[n.themeMode]),Re.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]),Re.useEffect(()=>{fs({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]),Re.useEffect(()=>{if(typeof window>"u")return;const k=b=>{const N=b.detail;N&&o(D=>{let j=D.themeMode;N.useSystemTheme===!0?j="system":N.useSystemTheme===!1&&(N.themeVariant==="dark"||N.themeVariant==="light")&&(j=N.themeVariant);let M=D.lightThemeId;typeof N.lightThemeId=="string"&&N.lightThemeId.length>0&&(M=za(N.lightThemeId,"light"));let C=D.darkThemeId;return typeof N.darkThemeId=="string"&&N.darkThemeId.length>0&&(C=za(N.darkThemeId,"dark")),j===D.themeMode&&M===D.lightThemeId&&C===D.darkThemeId?D:{themeMode:j,lightThemeId:M,darkThemeId:C}})};return window.addEventListener("openchamber:settings-synced",k),()=>window.removeEventListener("openchamber:settings-synced",k)},[]);const x=Re.useCallback(k=>{const b=f.find(N=>N.metadata.id===k);b&&o(N=>b.metadata.variant==="dark"?N.darkThemeId===b.metadata.id&&N.themeMode==="dark"?N:{...N,darkThemeId:b.metadata.id,themeMode:"dark"}:N.lightThemeId===b.metadata.id&&N.themeMode==="light"?N:{...N,lightThemeId:b.metadata.id,themeMode:"light"})},[f]),g=Re.useCallback(k=>{o(b=>b.themeMode===k?b:{...b,themeMode:k})},[]),w=Re.useCallback(k=>{if(k){o(N=>N.themeMode==="system"?N:{...N,themeMode:"system"});return}const b=m.metadata.variant==="dark"?"dark":"light";o(N=>N.themeMode===b?N:{...N,themeMode:b})},[m.metadata.variant]),y=Re.useCallback(k=>{const b=f.find(N=>N.metadata.id===k&&N.metadata.variant==="light");b&&o(N=>N.lightThemeId===b.metadata.id?N:{...N,lightThemeId:b.metadata.id})},[f]),v=Re.useCallback(k=>{const b=f.find(N=>N.metadata.id===k&&N.metadata.variant==="dark");b&&o(N=>N.darkThemeId===b.metadata.id?N:{...N,darkThemeId:b.metadata.id})},[f]),S={currentTheme:m,availableThemes:f,setTheme:x,isSystemPreference:n.themeMode==="system",setSystemPreference:w,themeMode:n.themeMode,setThemeMode:g,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:y,setDarkThemePreference:v};return e.jsx(Xl.Provider,{value:S,children:t})}const EC=({children:t})=>{const{theme:r,applyTheme:s,fontSize:n,applyTypography:o,padding:a,applyPadding:l}=ke();return i.useLayoutEffect(()=>{s(),o(),l()},[r,s,n,o,a,l]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&s()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[r,s]),e.jsx(e.Fragment,{children:t})};let tm=!1;const IC=()=>{if(tm||typeof window>"u")return;tm=!0;let t={showReasoningTraces:ke.getState().showReasoningTraces,autoDeleteEnabled:ke.getState().autoDeleteEnabled,autoDeleteAfterDays:ke.getState().autoDeleteAfterDays},r=null,s=null;const n=()=>{const a=r;r=null,s=null,a&&Object.keys(a).length>0&&fs(a)},o=a=>{r={...r??{},...a},!s&&(s=setTimeout(n,150))};ke.subscribe(a=>{const l={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};l.showReasoningTraces!==t.showReasoningTraces&&(c.showReasoningTraces=l.showReasoningTraces),l.autoDeleteEnabled!==t.autoDeleteEnabled&&(c.autoDeleteEnabled=l.autoDeleteEnabled),l.autoDeleteAfterDays!==t.autoDeleteAfterDays&&(c.autoDeleteAfterDays=l.autoDeleteAfterDays),t=l,Object.keys(c).length>0&&o(c)})};let sm=!1;const rm="openchamber-typography-base",PC=()=>{if(typeof document>"u")return;const r=`:root {
233
- ${Object.entries($l).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
234
- `)}
235
- }
236
- `,s=document.getElementById(rm);if(s){s.textContent=r;return}const n=document.createElement("style");n.id=rm,n.textContent=r,document.head.appendChild(n)},TC=()=>{sm||typeof window>"u"||(sm=!0,PC())},FC=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await $m();await Bm();IC();TC();await Rp();typeof window<"u"&&(window.debugContextTokens=()=>{const t=window.__zustand_session_store__;if(!t)return;const r=t.getState(),s=r.currentSessionId;if(!s)return;const o=(r.messages.get(s)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const l=o[o.length-1].info.tokens;l&&typeof l=="object"&&console.debug("Token breakdown:",{base:(l.input||0)+(l.output||0)+(l.reasoning||0),cache:l.cache?(l.cache.read||0)+(l.cache.write||0):0}),r.sessionContextUsage.get(s);const c=window.__zustand_config_store__;if(c){const d=c.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Bp=document.getElementById("root");if(!Bp)throw new Error("Root element not found");px.createRoot(Bp).render(e.jsx(Re.StrictMode,{children:e.jsx(AC,{children:e.jsx(EC,{children:e.jsx(SC,{children:e.jsx(xC,{apis:FC})})})})}));if(typeof window<"u"){const t=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(r){console.warn("Failed to notify desktop runtime that renderer is ready:",r)}};t(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}const OC=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ps as D,fn as S,hs as a,yf as b,F as c,Tj as d,Fj as e,Zd as f,_r as g,Rj as h,Oj as i,OC as m,sp as p,Lj as r,aa as t};