@openchamber/web 1.5.4 → 1.5.6

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,158 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-BrcdMJ39.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-PTbkCnSK.js","assets/index-X4_48EOB.js","assets/index-DMDb0aQz.css"])))=>i.map(i=>d[i]);
2
- import{t as Ip,c as Pp,F as Tp,j as e,R as Fp,T as Rp,P as Lp,C as Op,A as _p,a as $p,b as ns,d as cs,p as Ws,e as Hs,f as Bp,_ as bs,g as i,r as Ku,i as Zt,I as zp,k as Wp,l as Hp,m as Up,n as Vp,L as Gp,o as qp,q as Kp,s as Qp,u as Gt,S as Yp,v as Xp,w as Qu,x as Jp,y as Zp,z as eh,B as th,D as sh,E as rh,G as Pe,H as xc,J as nh,K as oh,M as Qn,N as Gi,O as yc,Q as La,U as Ot,V as Bs,W as Jt,X as kl,Y as Yu,Z as Xu,$ as ah,a0 as zr,a1 as ih,a2 as Ks,a3 as tr,a4 as Ur,a5 as Ht,a6 as Nl,a7 as lh,a8 as dn,a9 as Cl,aa as hn,ab as un,ac as qi,ad as Is,ae as Ju,af as ch,ag as dh,ah as uh,ai as mh,aj as fh,ak as ph,al as hh,am as Jo,an as gh,ao as Zu,ap as ha,aq as Wr,ar as ps,as as gn,at as ir,au as jo,av as is,aw as yr,ax as xh,ay as yh,az as em,aA as Ml,aB as mn,aC as tm,aD as br,aE as sm,aF as Rn,aG as bh,aH as Oa,aI as lr,aJ as oi,aK as wh,aL as Vr,aM as kr,aN as Ys,aO as vh,aP as Us,aQ as jh,aR as bc,aS as Ki,aT as Sh,aU as kh,aV as Nh,aW as Ch,aX as Mh,aY as Dh,aZ as Ah,a_ as Eh,a$ as Ih,b0 as rm,b1 as ai,b2 as Ph,b3 as Dl,b4 as Al,b5 as Th,b6 as Fh,b7 as Rh,b8 as Lh,b9 as Oh,ba as _h,bb as $h,bc as Bh,bd as zh,be as Wh,bf as Hh,bg as Uh,bh as Vh,bi as Gh,bj as qh,bk as Kh,bl as Nr,bm as ga,bn as wr,bo as pr,bp as Qh,bq as Yh,br as _a,bs as Xh,bt as El,bu as Jh,bv as Zh,bw as eg,bx as Ln,by as tg,bz as sg,bA as rg,bB as ng,bC as og,bD as po,bE as Zo,bF as $a,bG as ag,bH as ig,bI as En,bJ as kn,bK as nm,bL as lg,bM as cg,bN as Qs,bO as dg,bP as ug,bQ as om,bR as mg,bS as fg,bT as Qi,bU as am,bV as im,bW as pg,bX as Mr,bY as On,bZ as hg,b_ as wc,b$ as gg,c0 as Yi,c1 as Vn,c2 as Gn,c3 as xg,c4 as lm,c5 as Il,c6 as Pl,c7 as Tl,c8 as yg,c9 as bg,ca as wg,cb as vg,cc as vc,cd as cm,ce as jg,cf as Sg,cg as kg,ch as Ba,ci as Ng,cj as Cg,ck as Mg,cl as Nn,cm as jc,cn as Dg,co as Ag,cp as Eg,cq as Ig,cr as Pg,cs as Tg,ct as qn,cu as Fg,cv as Rg,cw as Lg,cx as Og,cy as _g,cz as $g,cA as dm,cB as um,cC as mm,cD as fm,cE as pm,cF as Bg,cG as hm,cH as gm,cI as xm,cJ as Cn,cK as zg,cL as Wg,cM as Hg,cN as Ze,cO as Ug,cP as Vg,cQ as Gg,cR as qg,cS as Sc,cT as Kg,cU as Qg,cV as ho,cW as ym,cX as bm,cY as ii,cZ as za,c_ as wm,c$ as Yg,d0 as Xg,d1 as Xi,d2 as vm,d3 as Ji,d4 as Jg,d5 as Zg,d6 as ex,d7 as tx,d8 as sx,d9 as rx}from"./vendor-.bun-BrcdMJ39.js";import{c as nx,l as ox,g as ax,r as ix,d as lx,a as cx,b as dx,e as ux,u as mx,f as fx,h as px,i as hx,j as gx,k as xx,m as yx}from"./index-X4_48EOB.js";const ls=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Wt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,hr=()=>typeof window>"u"?!1:!ls()&&!Wt(),Gr=()=>ls()?window.opencodeDesktop??null:null,jm=()=>{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},Sm=async()=>{const t=Gr();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},bx=async()=>{const t=Gr();if(!t)return null;try{return await t.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},wx=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Ir=async()=>{const t=jm();if(!t)return null;try{return await t.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},vx=async t=>{const r=jm();if(!r)return null;try{return await r.updateSettings(t)}catch(s){return console.warn("[desktop] Failed to update desktop settings",s),null}},jx=async t=>{const r=Gr();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)}}},Sx=async t=>{const r=Gr();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)}}},kx=async t=>{const r=Gr();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)}}},Nx=async()=>{const t=Gr();if(!t||!t.checkForUpdates)return null;try{return await t.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},Cx=async t=>{const r=Gr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(t),!0}catch(s){return console.warn("Failed to download update",s),!1}},Mx=async()=>{const t=Gr();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 Ip(Pp(t))}const km=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Ts=t=>km()&&ls()?t.metaKey:t.ctrlKey,Xt=()=>km()&&ls()?"⌘":"Ctrl",Nm=(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 c=Math.max(0,n-(a.length+2));if(c<=0)return`…/${a}`;let l="";for(const d of o){if(!d)continue;const u=l?`${l}/${d}`:d;if(u.length>c)break;l=u}if(!l){const d=o[0]??"";l=d?d.slice(0,c):""}return l?`${l}…/${a}`:`…/${a}`},xa=t=>t?t==="/"?"/":t.replace(/\/+$/,""):"";function nn(t,r){if(!t)return"";const s=xa(t);if(s==="/")return"/";const n=r?xa(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 kc(t,r){if(!t)return"/";const s=xa(t);if(!s||s==="/")return"/";const n=r?xa(r):void 0;return n&&n!=="/"&&s===n?"~":s.split("/").pop()||s||"/"}function Gs(t,r){return r?t?t.toLowerCase().includes(r.toLowerCase())?!0:new Tp([t],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function Dx({delayDuration:t=0,...r}){return e.jsx($p,{"data-slot":"tooltip-provider",delayDuration:t,...r})}function lt({delayDuration:t=0,...r}){return e.jsx(Dx,{delayDuration:t,children:e.jsx(Fp,{"data-slot":"tooltip",...r})})}function ct({...t}){return e.jsx(Rp,{"data-slot":"tooltip-trigger",...t})}function it({className:t,sideOffset:r=0,children:s,...n}){return e.jsx(Lp,{children:e.jsxs(Op,{"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(_p,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let li=null;const Nc=()=>{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}}},Ax=()=>{if(typeof window>"u"||!window.localStorage)return Nc();const t=window.localStorage,r=Nc();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}}},hs=()=>(li||(li=Ax()),li),Fl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Ex={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Cc(t){return`--text-${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Cr={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)"}}},ea={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Cr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:ea.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Cr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ea.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Cr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:ea.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Cr.tool.inline})},Te=ns()(cs(Ws((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(Fl);if(o===1){for(const[c]of a)n.style.removeProperty(Cc(c));return}for(const[c,l]of a){const d=parseFloat(l);Number.isFinite(d)&&n.style.setProperty(Cc(c),`${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 c=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*c).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*c).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*c).toFixed(3)),n.style.setProperty("--line-height-loose",(2*c).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(c=>c.providerID===s&&c.modelID===n)?{favoriteModels:o.favoriteModels.filter(c=>!(c.providerID===s&&c.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(c=>!(c.providerID===s&&c.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:Hs(()=>hs()),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 Ix(){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 Px(){return ls()?"desktop":hr()?"web":null}const Mc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Wa=ns()((t,r)=>({...Mc,checkForUpdates:async()=>{const s=Px();if(s){t({checking:!0,error:null,runtimeType:s});try{let n=null;s==="desktop"?n=await Nx():s==="web"&&(n=await Ix()),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 Cx(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 Mx()}catch(o){t({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{t({available:!1,downloaded:!1,info:null})},reset:()=>{t(Mc)}})),Tx="/api",Fx=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Rx=t=>{const r=typeof t=="string"&&t.trim().length>0?t.trim():"/api";if(Fx.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}},Lx=()=>{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},Do=t=>t.replace(/\\/g,"/"),ci=()=>{if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t&&t.runtime?.isDesktop&&t.files?t.files:null};class Ox{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=Tx){const n=Lx()||r;this.baseUrl=Rx(n),this.client=Bp({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],l=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,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 c=new Image;c.onload=()=>{let l=c.width,d=c.height;(l>o||d>o)&&(l>d?(d=Math.round(d*(o/l)),l=o):(l=Math.round(l*(o/d)),d=o));const u=document.createElement("canvas");u.width=l,u.height=d;const m=u.getContext("2d");if(!m){a(r);return}m.drawImage(c,0,0,l,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)}},c.onerror=()=>a(r),c.src=r})}async convertHeicToJpeg(r){try{const s=(await bs(async()=>{const{default:f}=await import("./vendor-.bun-BrcdMJ39.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),c=new Uint8Array(a.length);for(let f=0;f<a.length;f++)c[f]=a.charCodeAt(f);const l=new Blob([c],{type:r.mime}),d=await s({blob:l,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}),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 c=await this.normalizeFilePart(a),l={type:"file",mime:c.mime,filename:c.filename,url:c.url};o.push(l)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text}),a.files&&a.files.length>0)for(const c of a.files){const l=await this.normalizeFilePart(c),d={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,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 c=await a.json().catch(()=>null);return!c||typeof c!="object"?{}:c}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),c=[],l=new Set;for(const d of a)for(const u of d){if(!u||typeof u!="object")continue;const m=u.id;typeof m!="string"||m.length===0||l.has(m)||(l.add(m),c.push(u))}return c}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 c of s)if(c.startsWith("data:"))n.push(c.slice(5).replace(/^\s/,""));else if(c.startsWith("id:")){const l=c.slice(3).trim();l&&(o=l)}if(n.length===0)return null;const a=n.join(`
4
- `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const 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 c=a;if(typeof c.type=="string")return{directory:o&&o.length>0?o:"global",payload:c}}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 c=await fetch(s,{method:"GET",headers:a,signal:r.signal});if(!c.ok||!c.body)throw new Error(`Global SSE connect failed with status ${c.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const l=c.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await l.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
5
- `);const 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),c=l=>{a&&l.directory!==a||r(l)};return this.globalSseListeners.add(c),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),s&&this.globalSseErrorListeners.add(s),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(c),n&&this.globalSseOpenListeners.delete(n),s&&this.globalSseErrorListeners.delete(s),this.maybeStopGlobalSse()}}subscribeToEvents(r,s,n,o,a){const c=a?.key??"default",l=a?.scope??"directory",d=this.sseAbortControllers.get(c);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(c,u);let m;if(l==="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(c)===u&&this.sseAbortControllers.delete(c)};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,N=f(S);N&&r(N)}};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(c)===u&&this.sseAbortControllers.delete(c)}})(),()=>{this.sseAbortControllers.get(c)===u&&this.sseAbortControllers.delete(c),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=ci();if(s?.createDirectory)try{return await s.createDirectory(r)}catch(a){const c=a instanceof Error?a.message:String(a);throw new Error(c||"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=ci();if(n)try{const o=await n.listDirectory(r||"",s);return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:Do(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(),c=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!c.ok){const d=await c.json().catch(()=>({})),u=typeof d.error=="string"?d.error:"Failed to list directory";throw new Error(u)}const l=await c.json();return!l||!Array.isArray(l.entries)?[]:l.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(r,s){const n=ci(),o=typeof s?.directory=="string"&&s.directory.trim().length>0?s.directory.trim():this.currentDirectory,a=o?Do(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=Do(f.path),h=p.split("/").filter(Boolean).pop()||p,x=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Do(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 c=new URLSearchParams;o&&o.length>0&&c.set("directory",o),typeof r=="string"&&c.set("q",r),typeof s?.limit=="number"&&Number.isFinite(s.limit)&&c.set("limit",String(s.limit)),s?.includeHidden&&c.set("includeHidden","true"),s?.respectGitignore===!1&&c.set("respectGitignore","false");const l=`${this.baseUrl}/fs/search${c.toString()?`?${c.toString()}`:""}`,d=await fetch(l,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await Sm();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??{},c=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(c)}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 Ox,_x=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Fe},Symbol.toStringTag,{value:"Module"})),Zi=new Set;function Ha(t){return Zi.add(t),()=>{Zi.delete(t)}}function gr(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 Zi)try{const c=a(o);c instanceof Promise&&c.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(c){console.error("[ConfigSync] Listener threw:",c)}}function go(t,r){return t.scopes.includes("all")||t.scopes.includes(r)}const Rl="Updating OpenCode configuration...";let xr=0,Hr=Rl;const el=new Set;function ya(){const t={isUpdating:xr>0,message:Hr};el.forEach(r=>r(t))}function qs(t){xr+=1,xr===1?(Hr=t||Rl,ya()):t&&(Hr=t,ya())}function Fs(){xr!==0&&(xr-=1,xr===0&&(Hr=Rl,ya()))}function Dr(t){Hr===t&&xr>0||(Hr=t,xr>0&&ya())}function $x(t){return el.add(t),t({isUpdating:xr>0,message:Hr}),()=>{el.delete(t)}}function Bx(){return{isUpdating:xr>0,message:Hr}}const fr=ns()(cs(Ws((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(c=>{const l=c.queuedMessages[s]??[];return{queuedMessages:{...c.queuedMessages,[s]:[...l,a]}}})},removeFromQueue:(s,n)=>{t(o=>{const c=(o.queuedMessages[s]??[]).filter(l=>l.id!==n);if(c.length===0){const{[s]:l,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[s]:c}}})},popToInput:(s,n)=>{const c=(r().queuedMessages[s]??[]).find(l=>l.id===n);return c?(t(l=>{const u=(l.queuedMessages[s]??[]).filter(m=>m.id!==n);if(u.length===0){const{[s]:m,...f}=l.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...l.queuedMessages,[s]:u}}}),c):null},clearQueue:s=>{t(n=>{const{[s]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{t({queuedMessages:{}})},setQueueMode:s=>{t({queueModeEnabled:s}),us({queueModeEnabled:s})},getQueueForSession:s=>r().queuedMessages[s]??[]}),{name:"message-queue-store",storage:Hs(()=>hs()),partialize:t=>({queuedMessages:t.queuedMessages,queueModeEnabled:t.queueModeEnabled})}),{name:"message-queue-store"})),Dc=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},zx=t=>!t||typeof t!="object"?null:{showReasoningTraces:t.showReasoningTraces},Wx=t=>{const r=Te.getState();typeof t.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(t.showReasoningTraces)},Hx=async()=>{if(typeof window>"u")return null;if(ls()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const s=await r.load();return Dc(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=zx(r);return Dc(s)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Cm=null;const Ac=t=>{Cm=t},As=()=>Cm,ta=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"))},Ux=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():"",c=typeof o.label=="string"?o.label.trim():"",l=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!c||!l||s.has(a)||(s.add(a),r.push({id:a,label:c,source:l,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},Vx=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,c=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!c||!l)continue;const d=l==="/"?l:l.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||s.has(c)||n.has(d))continue;s.add(c),n.add(d);const u={id:c,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},Mm=()=>{const t=Te.persist;if(t&&typeof t=="object")return t},Dm=()=>As()?.settings??null,sa=t=>{const r=Te.getState(),s=fr.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)},Ec=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=Vx(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=Ux(r.skillCatalogs);return o&&(s.skillCatalogs=o),s},Gx=async()=>{const t=Dm();if(t)try{const r=await t.load();return Ec(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 Ec(s)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},Am=async()=>{if(typeof window>"u")return;const t=Mm(),r=s=>{ta(s);const n=()=>sa(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=ls()?await Ir():await Gx();s&&r(s)}catch(s){console.warn("Failed to synchronise settings:",s)}},us=async t=>{if(typeof window>"u")return;if(ls()){try{const s=await vx(t);s&&(ta(s),sa(s))}catch(s){console.warn("Failed to update desktop settings:",s)}return}const r=Dm();if(r)try{const s=await r.save(t);s&&(ta(s),sa(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&&(ta(n),sa(n))}catch(s){console.warn("Failed to update shared settings via API:",s)}},Em=async()=>{if(typeof window>"u")return;const t=Mm();try{const r=await Hx();if(!r)return;const s=()=>Wx(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)}},qx=3e4,Kx=40,Qx=60,Yx=(t,r,s,n,o)=>{const a=t.trim(),c=r.trim().toLowerCase();return`${a}::${c}::${s}::${n?"1":"0"}::${o?"1":"0"}`},Ua=ns()(cs((t,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(s,n,o=Qx,a){if(!s||s.trim().length===0)return[];const c=s.trim(),l=typeof n=="string"?n.trim():"",d=!!a?.includeHidden,u=a?.respectGitignore??!0,m=Yx(c,l,o,d,u),f=Date.now(),p=r().cache[m];if(p&&f-p.timestamp<qx)return p.files;const h=r().inFlight[m];if(h)return h;const x=Fe.searchFiles(l,{directory:c,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>Kx;){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 c={...a.cache},l=a.cacheKeys.filter(m=>m.startsWith(o)?(delete c[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:c,cacheKeys:l,inFlight:u}})}}),{name:"file-search-store"})),ds=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var Xx={};let rr=null;const sr=hs(),Ic=sr.getItem("lastDirectory"),Jx=typeof Ic=="string"&&Ic.length>0,Ao=t=>{try{Ua.getState().invalidateDirectory(t)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Im=t=>{const r=t.trim();if(!r)return r;const s=r.replace(/\\/g,"/");return s.length>1?s.replace(/\/+$/,""):s},Zx=(t,r)=>{const s=t.trim();return s.startsWith("~")?s==="~"?r||s:(s.startsWith("~/")||s.startsWith("~\\"))&&r?`${r}${s.slice(1)}`:s:s},ra=(t,r)=>{const s=Zx(t,r);return Im(s)},ba=()=>{if(typeof window<"u"){const r=sr.getItem("homeDirectory")||rr||null,s=sr.getItem("lastDirectory");if(s&&!Wt())return ra(s,r);if(rr)return rr;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 rr=n,sr.setItem("homeDirectory",n),n;if(r&&!Wt())return rr=r,r}const t=typeof process<"u"&&Xx?.HOME;return t||process?.cwd?.()||"/"},ey=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},ty=t=>(rr=t,typeof window<"u"&&sr.setItem("homeDirectory",t),us({homeDirectory:t}),t),Pm=async()=>{const t=n=>{const o=ey(n);return o?ty(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 Sm(),o=t(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=ba(),s=t(r);return s||r},sy=()=>{if(!Wt())return null;const t=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof t!="string"||t.trim().length===0)return null;const r=Im(t);return r.length>0?r:null},on=sy()||ba();on&&Fe.setDirectory(on);const ry=!!(on&&on!=="/"),bt=ns()(cs((t,r)=>({currentDirectory:on,directoryHistory:[on],historyIndex:0,homeDirectory:on,hasPersistedDirectory:Jx,isHomeReady:ry,isSwitchingDirectory:!1,setDirectory:(s,n)=>{const o=rr||r().homeDirectory||sr.getItem("homeDirectory"),a=ra(s,o);ds()&&console.log("[DirectoryStore] setDirectory called with path:",a),Fe.setDirectory(a),Ao(),t(c=>{const l=[...c.directoryHistory.slice(0,c.historyIndex+1),a];return sr.setItem("lastDirectory",a),us({lastDirectory:a}),{currentDirectory:a,directoryHistory:l,historyIndex:l.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),Ao(),sr.setItem("lastDirectory",o),us({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),Ao(),sr.setItem("lastDirectory",o),us({lastDirectory:o}),t({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:s,setDirectory:n}=r(),o=rr||r().homeDirectory||ba();if(s===o||s==="/")return;const a=s.endsWith("/")?s.slice(0,-1):s,c=a.lastIndexOf("/");if(c===-1){const l=rr||ba();n(l)}else n(c===0?"/":a.substring(0,c))},goHome:async()=>{const s=rr||r().homeDirectory||await Pm();r().setDirectory(s)},synchronizeHomeDirectory:s=>{const n=r(),o=s;rr=o;const a=n.homeDirectory!==o,c=sr.getItem("lastDirectory"),l=typeof c=="string"&&c.length>0,d=!l&&(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?ra(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>ra(g,o)),p=f.some((g,w)=>g!==n.directoryHistory[w]),h=!!(m&&m!==n.currentDirectory),x={homeDirectory:o,hasPersistedDirectory:l,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),Ao(),sr.setItem("lastDirectory",g),us({lastDirectory:g})}us({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Pm().then(t=>{bt.getState().synchronizeHomeDirectory(t)});const In=hs(),Tm="projects",tl="activeProjectId",ny=(t,r)=>{const s=t.trim();return!s.startsWith("~")||!r?s:s==="~"?r:s.startsWith("~/")||s.startsWith("~\\")?`${r}${s.slice(1)}`:s},Va=t=>{const r=t.trim();if(!r)return"";const s=In.getItem("homeDirectory")||bt.getState().homeDirectory||"",o=ny(r,s).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Fm=t=>{const r=Va(t);if(!r||r==="/")return"Root";const s=r.split("/").filter(Boolean);return s[s.length-1]||r},oy=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Rm=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,c=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!c||!l)continue;const d=Va(l);if(!d||s.has(c)||n.has(d))continue;s.add(c),n.add(d);const u={id:c,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},ay=()=>{try{const t=In.getItem(Tm);return t?Rm(JSON.parse(t)):[]}catch{return[]}},iy=()=>{try{const t=In.getItem(tl);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},Ll=(t,r)=>{try{In.setItem(Tm,JSON.stringify(t))}catch{}try{r?In.setItem(tl,r):In.removeItem(tl)}catch{}},yn=(t,r)=>{Ll(t,r),us({projects:t,activeProjectId:r??void 0})},ly=ay(),cy=()=>{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=Va(r);if(!s)return null;const n=`vscode:${s}`,o={id:n,path:s,label:Fm(s),addedAt:Date.now(),lastOpenedAt:Date.now()};return ds()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},er=cy(),Ol=er?.projects??ly,Lm=er?.activeProjectId??iy()??Ol[0]?.id??null;er&&Ll(Ol,Lm);const Vt=ns()(cs((t,r)=>({projects:Ol,activeProjectId:Lm,validateProjectPath:s=>{if(typeof s!="string"||s.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=Va(s);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(s,n)=>{if(er)return null;const{validateProjectPath:o}=r(),a=o(s);if(!a.ok||!a.normalizedPath)return null;const c=a.normalizedPath,l=r().projects.find(x=>x.path===c);if(l)return r().setActiveProject(l.id),l;const d=Date.now(),u=n?.label?.trim()||Fm(c),m=n?.id?.trim(),p={id:m&&!r().projects.some(x=>x.id===m)?m:oy(),path:c,label:u,addedAt:d,lastOpenedAt:d},h=[...r().projects,p];return t({projects:h}),ds()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:s=>{if(er)return;const n=r(),o=n.projects.filter(c=>c.id!==s);let a=n.activeProjectId;if(n.activeProjectId===s&&(a=o[0]?.id??null),t({projects:o,activeProjectId:a}),yn(o,a),a){const c=o.find(l=>l.id===a);c&&(Fe.setDirectory(c.path),bt.getState().setDirectory(c.path,{showOverlay:!1}))}else bt.getState().goHome()},setActiveProject:s=>{if(er)return;const{projects:n,activeProjectId:o}=r();if(o===s)return;const a=n.find(d=>d.id===s);if(!a)return;const c=Date.now(),l=n.map(d=>d.id===s?{...d,lastOpenedAt:c}:d);t({projects:l,activeProjectId:s}),yn(l,s),Fe.setDirectory(a.path),bt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:s=>{if(er)return;const{projects:n,activeProjectId:o}=r();if(o===s||!n.find(d=>d.id===s))return;const c=Date.now(),l=n.map(d=>d.id===s?{...d,lastOpenedAt:c}:d);t({projects:l,activeProjectId:s}),yn(l,s)},renameProject:(s,n)=>{if(er)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:c}=r(),l=a.map(d=>d.id===s?{...d,label:o}:d);t({projects:l}),yn(l,c)},reorderProjects:(s,n)=>{if(er)return;const{projects:o,activeProjectId:a}=r();if(s<0||s>=o.length||n<0||n>=o.length||s===n)return;const c=[...o],[l]=c.splice(s,1);c.splice(n,0,l),t({projects:c}),yn(c,a)},synchronizeFromSettings:s=>{if(er)return;const n=Rm(s.projects??[]),o=typeof s.activeProjectId=="string"&&s.activeProjectId.trim()?s.activeProjectId.trim():null,a=r(),c=JSON.stringify(a.projects)!==JSON.stringify(n),l=a.activeProjectId!==o;if(!(!c&&!l)&&(t({projects:n,activeProjectId:o}),Ll(n,o),o)){const d=n.find(u=>u.id===o);d&&(Fe.setDirectory(d.path),bt.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(er)return;const{projects:o,activeProjectId:a}=r(),c=o.find(u=>u.id===s);if(!c)return;const l={...c.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?l.branchPrefix=n.branchPrefix.trim():delete l.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?l.baseBranch=n.baseBranch.trim():delete l.baseBranch),n.autoCreateWorktree!==void 0&&(l.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===s?{...u,worktreeDefaults:Object.keys(l).length>0?l:void 0}:u);t({projects:d}),yn(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const r=t.detail;r&&typeof r=="object"&&Vt.getState().synchronizeFromSettings(r)});const dy=new Set(["init","review"]),Mn=t=>dy.has(t.name),oo="useCommandsStore",sl=t=>new Promise(r=>setTimeout(r,t)),Eo=()=>{try{const r=Vt.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},uy=2e4,Pc=300,Tc=4,my=800,fy=200,py=2e3,qr=ns()(cs(Ws((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=Eo(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await Fe.withDirectory(a,()=>Fe.listCommandsWithDetails()),d=await Promise.all(l.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${c}`,{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 c=200*(o+1);await new Promise(l=>setTimeout(l,c))}return console.error("Failed to load commands:",n),t({commands:s,isLoading:!1}),!1},createCommand:async s=>{qs("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=Eo(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(s.name)}${c}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await di({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&gr("commands",{source:oo}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Fs()}},updateCommand:async(s,n)=>{qs("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 c=Eo(),l=c?`?directory=${encodeURIComponent(c)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(s)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...c?{"x-opencode-directory":c}:{}},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 di({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&gr("commands",{source:oo}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Fs()}},deleteCommand:async s=>{qs("Deleting command configuration…");let n=!1;try{const o=Eo(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await c.json().catch(()=>null);if(!c.ok){const m=l?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),l?.requiresReload??!0)return n=!0,await di({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&gr("commands",{source:oo}),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:Hs(()=>hs()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=qr);async function hy(t){const r=typeof t=="number"&&t>0?Math.min(t,Pc):0;r>0&&await sl(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<uy;){n+=1,Dr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Fe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-s,c=n<=Tc&&a<1200?Pc:Math.min(my+Math.max(0,n-Tc)*fy,py);await sl(c)}throw o||new Error("OpenCode did not become ready in time")}async function di(t={}){const{message:r,delayMs:s}=t;try{Dr(r||"Refreshing commands…")}catch{}try{await hy(s),Dr("Refreshing commands…"),await qr.getState().loadCommands(),gr("commands",{source:oo})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Dr("OpenCode refresh failed. Please retry refreshing configuration manually."),await sl(1500)}finally{Fs()}}let Fc=null;Fc||(Fc=Ha(t=>{if(t.source!==oo&&go(t,"commands")){const{loadCommands:r}=qr.getState();r()}}));const Fr=()=>{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},na="useSkillsStore",nr=ns()(cs(Ws((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=Fr(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills${c}`);if(!l.ok)throw new Error(`Failed to list skills: ${l.status}`);const m=((await l.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return t({skills:m,isLoading:!1}),!0}catch(a){n=a;const c=200*(o+1);await new Promise(l=>setTimeout(l,c))}return console.error("Failed to load skills:",n),t({skills:s,isLoading:!1}),!1},getSkillDetail:async s=>{try{const n=Fr(),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=>{qs("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=Fr(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(s.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),l=await c.json().catch(()=>null);if(!c.ok){const u=l?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&gr("skills",{source:na}),d}catch{return!1}finally{Fs()}},updateSkill:async(s,n)=>{qs("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=Fr(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(s)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&gr("skills",{source:na}),u}catch{return!1}finally{Fs()}},deleteSkill:async s=>{qs("Deleting skill...");try{const n=Fr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(s)}${o}`,{method:"DELETE"}),c=await a.json().catch(()=>null);if(!a.ok){const d=c?.error||"Failed to delete skill";throw new Error(d)}const l=await r().loadSkills();return l&&gr("skills",{source:na}),r().selectedSkillName===s&&t({selectedSkillName:null}),l}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=Fr(),a=o?`&directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return c.ok?(await c.json()).content??null:null}catch{return null}},writeSupportingFile:async(s,n,o)=>{try{const a=Fr(),c=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(s)}/files/${encodeURIComponent(n)}${c}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(s,n)=>{try{const o=Fr(),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:Hs(()=>hs()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=nr);let Rc=null;Rc||(Rc=Ha(t=>{if(t.source!==na&&go(t,"skills")){const{loadSkills:r}=nr.getState();r()}}));const ui=()=>{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},So=ns()(cs((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 c=ui(),l=s?.refresh?"&refresh=true":"",d=c?`?directory=${encodeURIComponent(c)}${l}`:l?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const 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(c){o={kind:"unknown",message:c instanceof Error?c.message:String(c)};const l=200*(a+1);await new Promise(d=>setTimeout(d,l))}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=ui(),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)}),c=await a.json().catch(()=>null);if(!a.ok||!c){const l=c?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:l}),{ok:!1,error:l}}return c.ok?(t({scanResults:c.items||[]}),c):(t({lastScanError:c.error||{kind:"unknown",message:"Failed to scan repository"}}),c)}finally{t({isScanning:!1})}},installSkills:async s=>{t({isInstalling:!0,lastInstallError:null});try{const n=ui(),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)}),c=await a.json().catch(()=>null);if(!c){const l={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:l}),{ok:!1,error:l}}if(!a.ok||!c.ok){const l=c.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:l}),{ok:!1,error:l}}return nr.getState().loadSkills(),c}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"})),gy=()=>{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},Io=()=>{try{const r=Vt.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},tn=t=>{const r=t;return r.native===!0||r.builtIn===!0},Om=t=>{const r=t;return r.hidden===!0||r.options?.hidden===!0},_m=t=>t.filter(r=>!Om(r)),oa="useAgentsStore",wa=t=>new Promise(r=>setTimeout(r,t)),xy=2e4,Lc=300,Oc=4,yy=800,by=200,wy=2e3,Kr=ns()(cs(Ws((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=Io(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await Fe.withDirectory(o,()=>Fe.listAgents()),l=await Promise.all(c.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(l)?t({agents:l,isLoading:!1}):t({isLoading:!1}),!0}catch{}return t({isLoading:!1}),!1},createAgent:async s=>{qs("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=Io(),c=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(s.name)}${c}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await ao({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&gr("agents",{source:oa}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Fs()}},updateAgent:async(s,n)=>{qs("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 c=Io(),l=c?`?directory=${encodeURIComponent(c)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(s)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...c?{"x-opencode-directory":c}:{}},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 ao({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&gr("agents",{source:oa}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Fs()}},deleteAgent:async s=>{qs("Deleting agent configuration…");let n=!1;try{const o=Io(),a=o?`?directory=${encodeURIComponent(o)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(s)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await c.json().catch(()=>null);if(!c.ok){const m=l?.error||"Failed to delete agent";throw new Error(m)}if(l?.requiresReload??!0)return n=!0,await ao({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&gr("agents",{source:oa}),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 _m(s)}}),{name:"agents-store",storage:Hs(()=>hs()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Kr);async function vy(t){const r=typeof t=="number"&&t>0?Math.min(t,Lc):0;r>0&&await wa(r);const s=Date.now();let n=0,o=null;for(;Date.now()-s<xy;){n+=1,Dr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Fe.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-s,c=n<=Oc&&a<1200?Lc:Math.min(yy+Math.max(0,n-Oc)*by,wy);await wa(c)}throw o||new Error("OpenCode did not become ready in time")}const jy=t=>{if(!t||t.length===0)return["all"];const r=Array.from(new Set(t));return r.includes("all")?["all"]:r};async function Sy(t={}){const{message:r,delayMs:s}=t,n=jy(t.scopes),o=t.mode??(n.includes("all")?"projects":"active");try{Dr(r||"Refreshing configuration…")}catch{}try{await vy(s);const a=at.getState(),c=Kr.getState(),l=qr.getState(),d=nr.getState(),u=So.getState(),m=n.includes("all")||n.includes("providers"),f=n.includes("all")||n.includes("agents"),p=n.includes("all")||n.includes("agents"),h=n.includes("all")||n.includes("commands"),x=n.includes("all")||n.includes("skills"),g=gy(),w=o==="projects"?Vt.getState().projects:[],y=Array.from(new Set([...g?[g]:[],...w.map(N=>N.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&at.setState({directoryScoped:{}});const v=[];for(const N of y)m&&v.push(a.loadProviders({directory:N}).then(()=>{})),f&&v.push(a.loadAgents({directory:N}).then(()=>{}));const S=[];p&&S.push(c.loadAgents().then(()=>{})),h&&S.push(l.loadCommands().then(()=>{})),x&&(S.push(d.loadSkills().then(()=>{})),S.push(u.loadCatalog().then(()=>{}))),Dr("Refreshing configuration…"),await Promise.all([...v,...S])}catch{Dr("OpenCode refresh failed. Please retry."),await wa(1500)}finally{Fs()}}async function ao(t){await Sy(t)}async function io(t){qs(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 ao({...n,message:s.message,delayMs:s.reloadDelayMs}):await ao(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),Dr("Failed to reload configuration. Please try again."),await wa(2e3),Fs(),r}}let _c=null;_c||(_c=Ha(t=>{if(t.source!==oa&&go(t,"agents")){const{loadAgents:r}=Kr.getState();r()}}));const ky="https://models.dev/api.json",Ny="/api/openchamber/models-metadata",$c="opencode",Bc="big-pickle",Cy=async()=>{try{if(ls()){const l=await Ir();return{defaultModel:l?.defaultModel,defaultVariant:l?.defaultVariant,defaultAgent:l?.defaultAgent,autoCreateWorktree:l?.autoCreateWorktree,gitmojiEnabled:l?.gitmojiEnabled}}const t=As()?.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():"",c=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:c}}catch{return{}}},Po=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]}},My=t=>t?.toLowerCase?.()??"",Dy=t=>t==="primary"||t==="all"||t===void 0||t===null,xo=t=>typeof t=="object"&&t!==null,va=t=>Array.isArray(t)&&t.every(r=>typeof r=="string"),Ay=t=>{if(!xo(t))return!1;const r=t;if(r.modalities){const{input:s,output:n}=r.modalities;if(s&&!va(s)||n&&!va(n))return!1}return!0},Ey=t=>{if(!xo(t))return!1;const r=t;return r.models===void 0||xo(r.models)},$m=(t,r)=>{const s=My(t);return!s||!r?"":`${s}/${r}`},Iy=t=>{const r=new Map;if(!xo(t))return r;for(const[s,n]of Object.entries(t)){if(!Ey(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:s,a=n.models;if(!(!a||!xo(a)))for(const[c,l]of Object.entries(a)){if(!Ay(l))continue;const d=typeof c=="string"&&c.length>0?c:l.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof l.id=="string"&&l.id.length>0?l.id:d,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:va(l.modalities.input)?l.modalities.input:void 0,output:va(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},m=$m(o,d);m&&r.set(m,u)}}return r},Py=async()=>{if(typeof fetch!="function")return new Map;const t=[Ny,ky];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 c=await fetch(r,a);if(!c.ok)throw new Error(`Metadata request to ${r} returned status ${c.status}`);const l=await c.json();return Iy(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let mi=null;const Ty=(t,r)=>{t().size>0||mi||(mi=Py().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{mi=null}))},Fy=t=>new Promise(r=>setTimeout(r,t)),_l="__global__",Pn=t=>{const r=typeof t=="string"?t.trim():"";return r.length>0?r:_l},bn=t=>t===_l?null:t,Ry=()=>{if(typeof window>"u")return _l;const t=Fe.getDirectory()??bt.getState().currentDirectory;return Pn(t)},at=ns()(cs(Ws((t,r)=>({activeDirectoryKey:Ry(),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=Pn(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:bn(n)}),await r().loadAgents({directory:bn(n)}))},loadProviders:async s=>{const n=Pn(s?.directory??bn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),c=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let l=null;for(let d=0;d<3;d++)try{Ty(()=>r().modelsMetadata,h=>t({modelsMetadata:h}));const u=await Fe.withDirectory(bn(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=Po(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),N=h.settingsDefaultVariant&&S?.variants?.[h.settingsDefaultVariant]?h.settingsDefaultVariant:void 0;w.currentProviderId=y.providerId,w.currentModelId=y.modelId,w.currentVariant=N,w.selectedProviderId=y.providerId,g.currentProviderId=y.providerId,g.currentModelId=y.modelId,g.currentVariant=N,g.selectedProviderId=y.providerId}}}return w});return}catch(u){l=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",l),t(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:c},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=c,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=Po(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(l=>l.id===s);if(!o)return;const c=o.models[0]?.id||"";t(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:s,currentModelId:c,selectedProviderId:s};return{currentProviderId:s,currentModelId:c,selectedProviderId:s,directoryScoped:{...l.directoryScoped,[d]:m}}})},setModel:s=>{t(n=>{const o=n.activeDirectoryKey,c={...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]:c}}})},setCurrentVariant:s=>{t(n=>{if(n.currentVariant===s)return n;const o=n.activeDirectoryKey,c={...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]:c}}})},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,c={...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]:c}}})},saveAgentModelSelection:(s,n,o)=>{t(a=>{const c=a.activeDirectoryKey,l={...a.agentModelSelections,[s]:{providerId:n,modelId:o}},u={...a.directoryScoped[c]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:l};return{agentModelSelections:l,directoryScoped:{...a.directoryScoped,[c]:u}}})},getAgentModelSelection:s=>{const{agentModelSelections:n}=r();return n[s]||null},loadAgents:async s=>{const n=Pn(s?.directory??bn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let c=null;for(let l=0;l<3;l++)try{const[d,u]=await Promise.all([Fe.withDirectory(bn(n),()=>Fe.listAgents()),Cy()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(t(b=>{const A={...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]:A}};return b.activeDirectoryKey===n&&(j.agents=m),j}),m.length===0)return t(b=>{const A={...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]:A}};return b.activeDirectoryKey===n&&(j.currentAgentName=void 0),j}),!0;const p=(b,k)=>{const A=f.find(j=>j.id===b);return A?A.models.some(j=>j.id===k):!1},h=m.filter(b=>Dy(b.mode));let w=h.find(b=>b.name==="build")||h[0]||m[0];const y={};if(u.defaultAgent){const b=m.find(k=>k.name===u.defaultAgent);b?w=b:y.defaultAgent=""}let v,S,N;if(u.defaultModel){const b=Po(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)?N=u.defaultVariant:y.defaultVariant=""}}else y.defaultModel=""}if(!v&&w?.model?.providerID&&w?.model?.modelID){const{providerID:b,modelID:k}=w.model;p(b,k)&&(v=b,S=k)}if(!v)if(p($c,Bc))v=$c,S=Bc;else{const b=f[0],k=b?.models[0];b&&k&&(v=b.id,S=k.id)}return t(b=>{const k=b.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},A={...k,providers:f,agents:m,currentAgentName:w.name,currentProviderId:v??k.currentProviderId,currentModelId:S??k.currentModelId,currentVariant:N},j={directoryScoped:{...b.directoryScoped,[n]:A}};return b.activeDirectoryKey===n&&(j.currentAgentName=w.name,v&&S&&(j.currentProviderId=v,j.currentModelId=S,j.currentVariant=N)),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}),us(y).catch(()=>{})),!0}catch(d){c=d;const u=200*(l+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",c),t(l=>{const d=l.activeDirectoryKey===n?l.providers:l.directoryScoped[n]?.providers??[],m={...l.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...l.directoryScoped,[n]:m}};return l.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:s=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:c}=r();if(t(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentAgentName:s};return{currentAgentName:s,directoryScoped:{...l.directoryScoped,[d]:m}}}),s&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const d=l.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&l.setState(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 l=window.__zustand_session_store__;if(l?.getState){const{currentSessionId:m,getAgentModelForSession:f}=l.getState();if(m&&f(m,s))return}if(a){const m=Po(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(c){const S=o.find(N=>N.id===m.providerId)?.models.find(N=>N.id===m.modelId)?.variants;S&&Object.prototype.hasOwnProperty.call(S,c)&&(g=c)}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 c=400*n;await Fy(c)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1}),!1},initializeApp:async()=>{try{const s=ds();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=$m(s,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:s}=r();return _m(s)}}),{name:"config-store",storage:Hs(()=>hs()),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__=at);let zc=null;zc||(zc=Ha(async t=>{const r=[];if(go(t,"agents")){const{loadAgents:s}=at.getState();r.push(s().then(()=>{}))}if(go(t,"providers")){const{loadProviders:s}=at.getState();r.push(s())}r.length>0&&await Promise.all(r)}));let Wc=null;typeof window<"u"&&!Wc&&(Wc=bt.subscribe((t,r)=>{const s=Pn(t.currentDirectory),n=Pn(r.currentDirectory);s!==n&&at.getState().activateDirectory(t.currentDirectory)}));const sn={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,HISTORICAL_MESSAGES:90,FETCH_BUFFER:20,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},rl=180,ja=()=>{const t=Te.getState?.();return t?{...sn,HISTORICAL_MESSAGES:t.memoryLimitHistorical??sn.HISTORICAL_MESSAGES,VIEWPORT_MESSAGES:t.memoryLimitViewport??sn.VIEWPORT_MESSAGES}:sn},nl=()=>{const t=Te.getState?.();return t?t.memoryLimitActiveSession??rl:rl},Sr=sn,Ps=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Qr(t){const r=Ps();return r?r.checkIsGitRepository(t):nx(t)}async function Ly(t){const r=Ps();return r?r.getGitStatus(t):ax(t)}async function Ga(t){const r=Ps();return r?r.getGitBranches(t):yx(t)}async function Oy(t,r){const s=Ps();return s?s.deleteGitBranch(t,r):lx(t,r)}async function _y(t,r){const s=Ps();return s?s.deleteRemoteBranch(t,r):cx(t,r)}async function Bm(t){const r=Ps();return r?r.listGitWorktrees(t):ox(t)}async function $y(t,r){const s=Ps();return s?s.addGitWorktree(t,r):dx(t,r)}async function zm(t,r){const s=Ps();return s?s.removeGitWorktree(t,r):ix(t,r)}async function By(t){const r=Ps();return r?r.ensureOpenChamberIgnored(t):xx(t)}async function zy(){const t=Ps();return t?t.getGitIdentities():gx()}async function Wy(t){const r=Ps();return r?r.createGitIdentity(t):fx(t)}async function Hy(t,r){const s=Ps();return s?s.updateGitIdentity(t,r):mx(t,r)}async function Uy(t){const r=Ps();return r?r.deleteGitIdentity(t):ux(t)}async function Vy(){const t=Ps();return t?.discoverGitCredentials?t.discoverGitCredentials():px()}async function Gy(){const t=Ps();return t?.getGlobalGitIdentity?t.getGlobalGitIdentity():hx()}const qy="openchamber.json",Wm=".openchamber";function Hm(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Ky=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},ol=(t,r)=>{const s=Ky(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Um=t=>ol(ol(t,Wm),qy);async function Vm(t){const r=Um(t);try{const s=Hm();if(s?.readFile)try{const c=await s.readFile(r);if(!c.content.trim())return null;const l=JSON.parse(c.content);return!l||typeof l!="object"?null:l}catch{return null}const n=await fetch(`${qm()}/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 Qy(t,r){const s=Um(t),n=ol(t,Wm);try{await Fe.createDirectory(n);const o=Hm();if(o?.writeFile)try{return(await o.writeFile(s,JSON.stringify(r,null,2))).success}catch(c){return console.error("Failed to write openchamber config via runtime API:",c),!1}return(await fetch(`${qm()}/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 Yy(t,r){const n={...await Vm(t)||{},...r};return Qy(t,n)}async function Kn(t){return(await Vm(t))?.["setup-worktree"]??[]}async function Gm(t,r){const s=r.filter(n=>n.trim().length>0);return Yy(t,{"setup-worktree":s})}function Xy(t,r){return t.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function qm(){const t="/api";return t.startsWith("/"),t}const Jy=".openchamber",Hc="/api";function Zy(){if(typeof window>"u")return null;const t=window.__OPENCHAMBER_RUNTIME_APIS__;return t?.files?t.files:null}const Er=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Uc=(t,r)=>{const s=Er(t),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!s||s==="/"?`/${n}`:`${s}/${n}`},Km=t=>t?t.startsWith("refs/heads/")?t.substring(11):t.startsWith("heads/")?t.substring(6):t.startsWith("refs/")?t.substring(5):t:"",eb=async t=>{try{await Fe.createDirectory(t)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function tb(t,r){const s=Er(t),n=Uc(s,Jy);return await eb(n),Uc(n,r)}async function $l(t){const{projectDirectory:r,worktreeSlug:s,branch:n,createBranch:o,startPoint:a}=t,c=Er(r),l=await tb(c,s),d={path:l,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await $y(c,d),{path:l,branch:n,label:Km(n),projectDirectory:c,relativePath:l.startsWith(`${c}/`)?l.slice(c.length+1):l}}async function Qm(t){const{projectDirectory:r,path:s,force:n}=t,o=Er(r);await zm(o,{path:s,force:n})}async function Ym(t){const{projectDirectory:r,path:s,branch:n,force:o,deleteRemote:a,remote:c}=t,l=Er(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await zm(l,{path:s,force:o}),d&&(await Oy(l,{branch:d,force:!0}),a))try{await _y(l,{branch:d,remote:c})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function _n(t){const r=Er(t);return Bm(r)}async function qa(t){const r=Er(t),s=await Ly(r);return{isDirty:!s.isClean,ahead:s.ahead,behind:s.behind,upstream:s.tracking}}function $n(t,r){const s=Er(t),n=Er(r.worktree);return{path:n,branch:r.branch??"",label:Km(r.branch??""),projectDirectory:s,relativePath:n.startsWith(`${s}/`)?n.slice(s.length+1):n}}async function Bl(t,r,s){const n=s??await Kn(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>Xy(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:t,projectDirectory:r,commands:o});try{const a=Zy();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 c=await fetch(`${Hc}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:t,background:!0})}),l=await c.json().catch(()=>null);if(c.status===202&&l&&typeof l.jobId=="string"){const d=l.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(g=>setTimeout(g,u));const p=await fetch(`${Hc}/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(!c.ok){const d=l&&l.error||"Request failed";return console.error("[worktreeService] Web exec failed:",l),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",l),l}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(c=>({command:c,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const Xm=hs(),Jm="oc.sessionSelectionByDirectory",fi=".openchamber",sb=()=>{try{const t=Xm.getItem(Jm);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 aa=null;const zl=()=>(aa||(aa=sb()),aa),Zm=t=>{aa=t;try{Xm.setItem(Jm,JSON.stringify(t))}catch{}},ef=t=>{if(!t)return null;const s=zl()[t];return typeof s=="string"?s:null},vr=(t,r)=>{if(!t)return;const s={...zl()};r?s[t]=r:delete s[t],Zm(s)},rb=(t,r)=>{if(!t)return;const s=ef(t);if(!s)return;if(!new Set(r).has(s)){const o={...zl()};delete o[t],Zm(o)}},Vc=async(t,r)=>{const s=t.status??await qa(t.path).catch(()=>{});await Ym({projectDirectory:t.projectDirectory,path:t.path,branch:t.branch,force:!!s?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},At=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},Gc=()=>{if(typeof window>"u")return null;const t=window.__VSCODE_CONFIG__,r=typeof t?.workspaceFolder=="string"?t.workspaceFolder:null;return At(r)},nb=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,To=(...t)=>{ds()&&nb()&&console.log("[OpenChamber][VSCode][sessions]",...t)},Rr=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())},Xs=t=>{const r=new Map;t.forEach(s=>{const n=At(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,Rr(n));return r},wn=(t,r)=>{const s=t.find(n=>n.id===r);return s?At(s.directory??null):null},ob=async(t,r,s)=>{const n=At(r);if(!n||t.length===0)return null;const o=t.map(u=>({id:u.id,directory:At(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await _n(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 c=new Map;a.forEach(u=>{const m=$n(n,u),f=At(m.path)??m.path;f!==n&&c.set(f,m)});let l=!1;const d=new Map(s);return o.forEach(({id:u,directory:m})=>{const f=c.get(m);if(!f){d.delete(u)&&(l=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),l=!0)}),l?d:null},ft=ns()(cs(Ws((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=bt.getState(),n=Vt.getState(),o=Fe.getApiClient(),a=Gc(),c=!!a;To("loadSessions:start",{workspace:a,currentDirectory:s.currentDirectory,clientDirectory:Fe.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const l=new Map,d=async L=>{const V=At(L)??L,q=V,_=l.get(q);if(_)return _;try{const Y=await o.path.get({directory:L}),U=At(Y.data?.directory??null)??V;return l.set(q,U),U}catch{return l.set(q,V),V}},u=(L,V,q)=>{const _=At(V);if(!_)return L;const K=q?.includeDescendants===!0?`${_}/`:null,U=q?.includeMissingDirectory===!0;return L.filter(Q=>{const z=At(Q.directory??null);return z?!!(z===_||K&&z.startsWith(K)):U})},m=(L,V,q)=>{const _=At(V);if(!_)return L;const Y=At(q??null);if(!Y||Y===_)return L.map(Q=>At(Q.directory??null)?Q:{...Q,directory:_});const K=Y==="/"?"/":`${Y}/`,U=_==="/"?"/":`${_}/`;return L.map(Q=>{const z=At(Q.directory??null);if(!z)return{...Q,directory:_};if(z===Y)return{...Q,directory:_};if(K!=="/"&&z.startsWith(K)){const re=z.slice(K.length);return{...Q,directory:`${U}${re}`}}return Q})},f=async L=>{const V=At(L);if(!V)try{const z=await o.session.list(void 0);return Array.isArray(z.data)?z.data:[]}catch(z){throw console.debug("Failed to list sessions (global):",z),z}const q=await d(V),_=async()=>{const z=await o.session.list({directory:V});return Array.isArray(z.data)?z.data:[]};let Y=[],K=null,U=!1;try{Y=await _()}catch(z){console.debug("Failed to list sessions for directory:",V,z),K=z,Y=[]}if(Y.length===0){U=!0;try{const z=await o.session.list(void 0),re=Array.isArray(z.data)?z.data:[];Y=u(re,q,{includeDescendants:c,includeMissingDirectory:!1})}catch(z){throw console.debug("Failed to list sessions (global fallback):",z),K||z}}const Q=u(Y,q,{includeDescendants:c,includeMissingDirectory:!U});return To("fetchSessionsForDirectory",{requestedDirectory:V,canonicalDirectory:q,fetched:Y.length,filtered:Q.length}),m(Q,V,q)},p=At(s.currentDirectory??Fe.getDirectory()??null),h=n.projects.find(L=>L.id===n.activeProjectId)??null,x=At(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 L=>{const V=At(L.path);if(!V)return{projectId:L.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const q=await Qr(V).catch(()=>!1),_=await f(V||null);To("projectSessions",{projectId:L.id,projectPath:V,isGitRepo:q,parentSessions:_.length});const Y=[];let K=[];const U=new Set;if(U.add(V),q){const z=`${V}/${fi}`;try{const re=new Set;(await Fe.listLocalDirectory(V)).some(ee=>ee.isDirectory&&ee.name===fi)&&(await Fe.listLocalDirectory(z)).filter(B=>B.isDirectory).forEach(B=>{const X=/^([A-Za-z]:)?\//.test(B.path)?B.path:`${z}/${B.name}`,ie=At(X)??X;re.add(ie)});const R=await _n(V);Array.isArray(R)&&(K=R.map(ee=>$n(V,ee)).filter(ee=>ee.path.includes(`/${fi}/`)),K.forEach(ee=>re.add(ee.path))),re.forEach(ee=>{const B=At(ee)??ee;U.add(B)}),re.size>0&&(await Promise.allSettled(Array.from(re).map(B=>f(B)))).forEach(B=>{B.status==="fulfilled"&&Array.isArray(B.value)&&Y.push(...B.value)})}catch{K=[]}}const Q=Rr([..._,...Y]);return{projectId:L.id,projectPath:V,sessions:Q,discoveredWorktrees:K,validPaths:U}})),v=new Map;y.forEach(L=>{L.projectPath&&L.validPaths.forEach(V=>{const q=At(V)??V,_=L.sessions.filter(Y=>(At(Y.directory??null)??q)===q);v.set(q,Rr(_))})});const S=Rr(Array.from(v.values()).flat()),N=r();let b=N.worktreeMetadata;for(const L of y)if(L.projectPath)try{const V=await ob(L.sessions,L.projectPath,b);V&&(b=V)}catch(V){console.debug("Failed to refresh worktree metadata during session load:",V)}const k=new Map;y.forEach(L=>{L.projectPath&&k.set(L.projectPath,L.discoveredWorktrees)});const A=new Set;y.forEach(L=>{L.validPaths.forEach(V=>{const q=At(V)??V;q&&A.add(q)})});const j=p??x??null,M=j&&A.has(j)?j:x??j,C=M?v.get(M)??[]:S,I=new Set(S.map(L=>L.id));for(const[L,V]of v.entries())rb(L,V.map(q=>q.id));const E=(M??null)!==(N.lastLoadedDirectory??null);let P=N.currentSessionId;if((!P||!I.has(P)||E)&&(P=C[0]?.id??S[0]?.id??null),M){const L=ef(M);L&&I.has(L)&&(P=L)}const D=(()=>{if(!P)return M??null;const L=b.get(P)?.path;if(L)return At(L)??L;const V=wn(S,P);return V||(M??null)})();try{Fe.setDirectory(D??void 0)}catch(L){console.warn("Failed to sync OpenCode directory after session load:",L)}const T=x?y.find(L=>L.projectPath===x)?.discoveredWorktrees??[]:[];t({sessions:S,sessionsByDirectory:v,currentSessionId:P,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:b,availableWorktrees:T,availableWorktreesByProject:k}),M&&vr(M,P),D&&D!==M&&vr(D,P)}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=bt.getState(),c=At(a.currentDirectory),l=Gc(),d=l??At(n??Fe.getDirectory()??c);To("createSession:start",{title:s,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:l});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(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,Rr([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),N=new Map(v.sessionsByDirectory);if(d){const k=(N.get(d)??[]).map(A=>A.id===u?y:A);N.set(d,Rr(k))}return{sessions:S,sessionsByDirectory:Xs(S),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(b=>b!==u),y.id])}}),vr(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),N=(Array.isArray(v.data)?v.data:[]).find(b=>!(f.has(b.id)||s&&b.title&&b.title!==s));if(N)return N}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=wn(r().sessions,s),c=o?.path??a;let l=null;try{o&&n?.archiveWorktree&&(await Vc(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),l=o);const d=()=>Fe.deleteSession(s);if(!(c?await Fe.withDirectory(c,d):await d()))return t(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(l){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=>At(y.path)!==At(o.path)):p.availableWorktrees,w=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const y=At(o.projectDirectory)??o.projectDirectory,v=w.get(y)??[];w.set(y,v.filter(S=>At(S.path)!==At(o.path)))}return{sessions:h,sessionsByDirectory:Xs(h),currentSessionId:m,isLoading:!1,worktreeMetadata:x,availableWorktrees:g,availableWorktreesByProject:w}});const f=c??Fe.getDirectory()??null;return vr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return t(l?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 c=[],l=[],d=new Set,u=[],m=new Set;for(const w of o)try{const y=r().worktreeMetadata.get(w),v=wn(r().sessions,w),S=y?.path??v;y&&n?.archiveWorktree&&!m.has(y.path)&&(await Vc(y,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(w),u.push({path:y.path,projectDirectory:y.projectDirectory}),m.add(y.path));const N=()=>Fe.deleteSession(w);(S?await Fe.withDirectory(S,N):await N())?(c.push(w),y?.path&&!u.some(k=>k.path===y.path)&&u.push({path:y.path,projectDirectory:y.projectDirectory})):l.push(w)}catch{l.push(w)}const f=bt.getState();u.forEach(({path:w,projectDirectory:y})=>{f.currentDirectory===w&&f.setDirectory(y,{showOverlay:!1})});const p=new Set(c),h=l.length>0?l.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let x=null;t(w=>{const y=w.sessions.filter(k=>!p.has(k.id));w.currentSessionId&&p.has(w.currentSessionId)?x=null:x=w.currentSessionId;const v=new Map(w.worktreeMetadata);for(const k of p)v.delete(k);for(const k of d)v.delete(k);const S=new Set(u.map(k=>At(k.path)).filter(k=>!!k)),N=S.size>0?w.availableWorktrees.filter(k=>!S.has(At(k.path)??k.path)):w.availableWorktrees,b=new Map(w.availableWorktreesByProject);return u.length>0&&u.reduce((A,j)=>{const M=At(j.projectDirectory)??j.projectDirectory,C=At(j.path)??j.path;return A.has(M)||A.set(M,new Set),A.get(M)?.add(C),A},new Map).forEach((A,j)=>{const C=(b.get(j)??[]).filter(I=>!A.has(At(I.path)??I.path));b.set(j,C)}),{sessions:y,sessionsByDirectory:Xs(y),currentSessionId:x,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:N,availableWorktreesByProject:b}});const g=Fe.getDirectory()??null;return vr(g,x),{deletedIds:c,failedIds:l}},updateSessionTitle:async(s,n)=>{try{const o=wn(r().sessions,s),a=r().worktreeMetadata.get(s),c=()=>Fe.updateSession(s,n),l=a?.path??o,d=l?await Fe.withDirectory(l,c):await c();t(u=>{const m=u.sessions.map(f=>f.id===s?d:f);return{sessions:m,sessionsByDirectory:Xs(m)}})}catch(o){t({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async s=>{try{const n=wn(r().sessions,s),o=Fe.getApiClient(),c=r().worktreeMetadata.get(s)?.path??n,l=async()=>{const u=n??Fe.getDirectory();return o.session.share({sessionID:s,...u?{directory:u}:{}})},d=c?await Fe.withDirectory(c,l):await l();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:Xs(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=wn(r().sessions,s),o=Fe.getApiClient(),c=r().worktreeMetadata.get(s)?.path??n,l=async()=>{const u=n??Fe.getDirectory();return o.session.unshare({sessionID:s,...u?{directory:u}:{}})},d=c?await Fe.withDirectory(c,l):await l();return d.data?(t(u=>{const m=u.sessions.map(f=>f.id===s?d.data:f);return{sessions:m,sessionsByDirectory:Xs(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;vr(n,s)},clearError:()=>{t({error:null})},getSessionsByDirectory:s=>{const n=At(s)??s,{sessionsByDirectory:o,sessions:a}=r(),c=o.get(n);return c||a.filter(l=>(At(l.directory??null)??n)===n)},getDirectoryForSession:s=>{if(!s)return null;const n=r().worktreeMetadata.get(s);if(n?.path)return At(n.path)??n.path;const o=r().sessions.find(c=>c.id===s);return At(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 c=o.sessions[a],l=n.time?{...c.time,...n.time}:c.time,d=n.summary===void 0?c.summary:n.summary||void 0,u=n.share===void 0?c.share:n.share||void 0,m={...c,...n,time:l,summary:d,share:u},f=m.title!==c.title||m.parentID!==c.parentID||m.directory!==c.directory||m.version!==c.version||m.projectID!==c.projectID||JSON.stringify(m.time)!==JSON.stringify(c.time)||JSON.stringify(m.summary??null)!==JSON.stringify(c.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(c.share??null),p=[...o.sessions];return p[a]=f?m:c,{sessions:p,sessionsByDirectory:Xs(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 l=o[a].directory??null,d=n??void 0;l!==(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:Xs(m)}}),l&&vr(l,null),n&&vr(n,s))},updateSession:s=>{t(n=>{const a=n.sessions.findIndex(l=>l.id===s.id)===-1?[s,...n.sessions]:n.sessions.map(l=>l.id===s.id?s:l),c=Rr(a);return{sessions:c,sessionsByDirectory:Xs(c)}})},removeSessionFromStore:s=>{s&&t(n=>{const o=n.sessions.find(u=>u.id===s),a=At(o?.directory??null),c=n.sessions.filter(u=>u.id!==s);if(c.length===n.sessions.length)return n;const l=new Map(n.worktreeMetadata);l.delete(s);const d=n.currentSessionId===s?null:n.currentSessionId;return a&&vr(a,null),{sessions:c,sessionsByDirectory:Xs(c),currentSessionId:d,worktreeMetadata:l}})}}),{name:"session-store",storage:Hs(()=>hs()),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:[],c=Array.isArray(t.worktreeMetadata)?t.worktreeMetadata:[],l=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=Rr(n);return{...r,...t,sessions:f,sessionsByDirectory:Xs(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(c),availableWorktrees:l,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),tf="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.",ab="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: ",pi=t=>typeof t=="string"&&t.trim()===tf.trim(),hi=(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},Yn=(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},qc=new Map,sf=t=>{const r=qc.get(t);r&&(clearTimeout(r),qc.delete(t))},Xr=t=>{for(const r of t)sf(r)},yo=t=>{if(!t)return"";if(typeof t=="string")return t;if(Array.isArray(t))return t.map(r=>yo(r)).join("");if(typeof t=="object"){if(typeof t.text=="string")return t.text;if(Array.isArray(t.content))return t.content.map(r=>yo(r)).join("")}return""},lo=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:lo(n)).join("");const s=yo(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||yo(o.delta)||""}return""}).join(""):"")},Xn=(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=yo(t.delta);o?s.text=o:a?s.text=n?`${n}${a}`:a:n?s.text=n:s.text="",delete s.delta}return s},Kc=50*1024*1024,ib=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"}},lb=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"}},cb=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},db=t=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let s="";for(let n=0;n<t.length;n+=3){const o=t[n]??0,a=t[n+1],c=t[n+2],l=o<<16|(a??0)<<8|(c??0);s+=r[l>>18&63],s+=r[l>>12&63],s+=typeof a=="number"?r[l>>6&63]:"=",s+=typeof c=="number"?r[l&63]:"="}return s},or=ns()(cs(Ws((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=Kc;if(s.size>a)throw new Error(`File "${s.name}" is too large. Maximum size is 50MB.`);const c=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],l=lb(s);!c.some(x=>l.startsWith(x)||l===x||l==="")&&l!==""&&console.warn(`File type "${l}" 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:${l}`):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:l,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 l=o,d,u;if(!l)try{const y=Fe.getApiClient(),v=s.lastIndexOf("/"),S=v>0?s.substring(0,v):"/",N=v>0?s.substring(v+1):s,b=await y.file.read({path:N,directory:S});b.data&&"content"in b.data?(l=b.data.content,d=b.data.encoding??void 0,u=b.data.mimeType??void 0):l=""}catch(y){console.error("Failed to read server file:",y),l=`[File: ${n}]`}const m=u||ib(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return l||"";const v=new TextEncoder().encode(l||"");return db(v)})(),h=d==="base64"?cb(p):new TextEncoder().encode(l||"").length;if(h>Kc)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:Hs(()=>hs()),partialize:t=>({attachedFiles:t.attachedFiles})}),{name:"file-store"})),ub=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),mb=t=>t?ub.has(t.toLowerCase()):!1,fb=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},pb=t=>{if(t)try{const r=fb();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===t)}catch{}},hb=(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"},ia=t=>{const r=pb(t);return r?hb(r.permission,"edit"):"ask"},Qc=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},gi=t=>{const r=t.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return Qc(r);const s=t.parts.find(n=>typeof n.tokens<"u");return!s||typeof s.tokens>"u"?0:typeof s.tokens=="number"?s.tokens:Qc(s.tokens)},xi=(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,c=Math.min(o?a:32e3,32e3),l=Math.min(c,n),d=n>0?Math.max(n-l,1):0,u=d>0?t/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:l}},Jn=["ask","allow","full"],ht=ns()(cs(Ws((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 c=new Map(a.sessionModelSelections);return c.set(s,{providerId:n,modelId:o}),{sessionModelSelections:c}})},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(c=>{const l=new Map(c.sessionAgentModelSelections);let d=l.get(s);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),l.set(s,d),{sessionAgentModelSelections:l}})},getAgentModelForSession:(s,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(s);return a&&a.get(n)||null},saveAgentModelVariantForSession:(s,n,o,a,c)=>{t(l=>{const d=new Map(l.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 c===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,c),u.set(n,m),d.set(s,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(s,n,o,a)=>{const{sessionAgentModelVariantSelections:c}=r(),l=c.get(s);if(!l)return;const d=l.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(s,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:c}=r(),l=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(N=>N.info.role==="assistant").sort((N,b)=>N.info.time.created-b.info.time.created);for(let N=g-1;N>=0;N--){const k=S[N].info;if(k.providerID===x.providerID&&k.modelID===x.modelID){if(k.mode&&typeof k.mode=="string"&&n.find(M=>M.name===k.mode))return k.mode;const A=n.find(j=>j.model?.providerID===k.providerID&&j.model?.modelID===k.modelID);if(A)return A.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&&c(s,v,y.providerID,y.modelID,p);const S={providerId:y.providerID,modelId:y.modelID,timestamp:w.time.created},N=l.get(v);(!N||S.timestamp>N.timestamp)&&l.set(v,S)}}p=void 0,h=void 0}for(const[x,g]of l)a(s,x,g.providerId,g.modelId);return l},getContextUsage:(s,n,o,a)=>{if(!s)return null;const c=xi(0,n,o),l=c.contextLimit,d=c.normalizedOutput??0,u=c.thresholdLimit;if(l===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 N=()=>{t(b=>{const k=b.sessionContextUsage.get(s);if(k&&k.totalTokens===S.totalTokens&&k.percentage===S.percentage&&k.contextLimit===S.contextLimit&&(k.outputLimit??0)===(S.outputLimit??0)&&(k.normalizedOutput??0)===(S.normalizedOutput??0)&&k.thresholdLimit===S.thresholdLimit&&k.lastMessageId===S.lastMessageId)return b;const A=new Map(b.sessionContextUsage);return A.set(s,S),{sessionContextUsage:A}})};typeof queueMicrotask=="function"?queueMicrotask(N):typeof window<"u"?window.setTimeout(N,0):setTimeout(N,0)},g=r().sessionContextUsage.get(s);if(g&&g.lastMessageId===h){const S=g.normalizedOutput??g.outputLimit??0,N=g.contextLimit!==l||S!==d||g.thresholdLimit!==u;if(N&&g.totalTokens>0){const b=g.totalTokens/u*100,k={totalTokens:g.totalTokens,percentage:Math.min(b,100),contextLimit:l,outputLimit:c.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return x(k),k}if(!N&&g.totalTokens>0)return g}const w=gi(p);if(w===0)return g||null;const y=xi(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 l=(a.get(s)||[]).filter(f=>f.info.role==="assistant");if(l.length===0)return;const d=l[l.length-1],u=gi(d);if(u===0)return;const m=xi(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 l=r().sessionContextUsage.get(s);(!l||l.totalTokens===0)&&r().updateSessionContextUsage(s,n,o,a)},pollForTokenUpdates:(s,n,o,a=10)=>{let c=0;const l=()=>{c++;const u=(o.get(s)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&gi(u)>0){r().updateSessionContextUsage(s,0,0,o);return}c<a&&setTimeout(l,1e3)};setTimeout(l,2e3)},getCurrentAgent:s=>{const{currentAgentContext:n}=r();return n.get(s)},getSessionAgentEditMode:(s,n,o=ia(n))=>!s||!n?o:r().sessionAgentEditModes.get(s)?.get(n)??o,setSessionAgentEditMode:(s,n,o,a=ia(n))=>{if(!s||!n)return;const c=a??"ask";c==="deny"||o==="deny"||Jn.includes(o)&&t(l=>{const d=new Map(l.sessionAgentEditModes),u=new Map(d.get(s)??new Map);return o===c?(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=ia(n))=>{if(!s||!n)return;const a=o??"ask";if(a==="deny")return;const c=r().getSessionAgentEditMode(s,n,a),l=Jn.indexOf(c),d=Jn.indexOf(a),m=((l>=0?l:d>=0?d:0)+1)%Jn.length,f=Jn[m];r().setSessionAgentEditMode(s,n,f,a)}}),{name:"context-store",storage:Hs(()=>hs()),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,c])=>{s.set(a,new Map(c))});const n=new Map;t?.sessionAgentModelVariantSelections&&t.sessionAgentModelVariantSelections.forEach(([a,c])=>{const l=new Map;c.forEach(([d,u])=>{l.set(d,new Map(u))}),n.set(a,l)});const o=new Map;return t?.sessionAgentEditModes&&t.sessionAgentEditModes.forEach(([a,c])=>{o.set(a,new Map(c))}),{...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"})),Yc=(t,r)=>{const s=new Map(t);return s.delete(r),s};let yi=[],bi=null;const gb=50,xb=3e4,Jr=new Map,Fo=new Map,vn=new Map,yb=10,Sa=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<yb?null:n},Ro=(t,r)=>{const s=Sa(t),n=Sa(r);return!s||!n||s.length!==n.length?!0:s>n},bb=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Dn=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),ka=t=>t?.finish==="stop",Xc=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??""}`}}},Jc=new Set,Na=(t=[],r=[])=>{if(!r.length)return[...t];const s=[...t],n=new Set(t.map(Xc).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=Xc(o);a&&n.has(a)||(s.push(o),a&&n.add(a))}),s},wb=(t,r)=>{const s=Array.isArray(t.parts)?t.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=Dn(s),a=Dn(n),c=ka(t.info),l=ka(r.info);let d=n;return c&&o>=a?d=Na(s,n):l&&a>=o?d=Na(n,s):o>=a&&(d=s),{...r,info:{...t.info,...r.info},parts:d}},Lo=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]=wb(r[a],n)}return r},vb=(t,r)=>{let s=r,n=r?Sa(r):null;for(const o of t){const a=o?.info?.id,c=Sa(a);!a||!c||(!n||c>n)&&(n=c,s=a)}return s},cr=(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},jn=(t,r,s)=>{if(t.get(r)===s)return t;const o=new Map(t);return o.set(r,s),o},Oo=(t,r)=>{const s=new Map(t);let n=!1;for(const o of r)s.delete(o)&&(n=!0);return n?s:t},jb=(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},Zc=(t,r,s)=>t.streamingMessageIds.get(r)===s?!0:t.messageSessionIndex.get(s)===r&&t.messageStreamStates.has(s),Sb=async t=>{if(t)try{return ft.getState().getDirectoryForSession(t)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},ed=t=>{if(!t)return null;try{return ft.getState().sessions.find(n=>n.id===t)?.revert?.messageID??null}catch{return null}},td=(t,r)=>{if(!r)return t;const s=t.findIndex(n=>n.info.id===r);return s===-1?t:t.slice(0,s)},wi=async(t,r)=>{const s=await Sb(t);return s?Fe.withDirectory(s,r):r()},Et=ns()(cs(Ws((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=ja(),a=n===1/0,c=a?1/0:n??o.HISTORICAL_MESSAGES,l=r().sessionMemoryState.get(s)?.isStreaming,d=l?o.VIEWPORT_MESSAGES:c,u=l||a?void 0:d+o.FETCH_BUFFER,m=await wi(s,()=>Fe.getSessionMessages(s,u)),f=ed(s),p=td(m,f),h=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,g=(h?p.filter(w=>{const y=w?.info?.id;return y?Ro(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])),N=g.map(T=>{const L={...T.info,clientRole:T.info?.clientRole??T.info.role,userMessageMarker:T.info.role==="user"?!0:T.info?.userMessageMarker},V=(Array.isArray(T.parts)?T.parts:[]).map(_=>{if(_?.type==="text"){const Y=_.text??_.content??"";if(pi(Y))return{..._,synthetic:!0}}return _}),q=L?.id?S.get(L.id):void 0;if(q&&q.info.role==="assistant"){const _=Array.isArray(q.parts)?q.parts:[],Y=Dn(_),K=Dn(V);if(ka(q.info)&&Y>K){const Q=Na(_,V);return{...T,info:L,parts:Q}}}return{...T,info:L,parts:V}}),b=Lo(N),k=new Set(v.map(T=>T.info.id)),A=new Set(b.map(T=>T.info.id)),j=[];k.forEach(T=>{A.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 I={messages:y,sessionMemoryState:M};Xr(j);const E=Yn(w.messageStreamStates,j);if(E!==w.messageStreamStates&&(I.messageStreamStates=E),j.length>0){const T=w.streamingMessageIds.get(s);T&&j.includes(T)&&(I.streamingMessageIds=cr(I.streamingMessageIds??w.streamingMessageIds,s,null))}if(j.length>0){const T=Oo(I.messageSessionIndex??w.messageSessionIndex,j);T!==(I.messageSessionIndex??w.messageSessionIndex)&&(I.messageSessionIndex=T)}if(j.length>0){const T=new Map(w.pendingAssistantParts);let L=!1;j.forEach(V=>{T.delete(V)&&(L=!0)}),L&&(I.pendingAssistantParts=T)}const P=I.messageSessionIndex??w.messageSessionIndex;let D=P;return b.forEach(T=>{const L=T?.info?.id;typeof L=="string"&&L.length>0&&(D=jn(D,L,s))}),D!==P&&(I.messageSessionIndex=D),I})},sendMessage:async(s,n,o,a,c,l,d,u,m)=>{if(!c)throw new Error("No session selected");const f=c;r().sessionAbortFlags.has(f)&&t(p=>{const h=new Map(p.sessionAbortFlags);return h.delete(f),{sessionAbortFlags:h}}),await wi(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=vn.get(f);w&&(clearTimeout(w),vn.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=(l??[]).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{or.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 l=jb(n,s);if(l.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")){l.add(p.info.id);break}}l.size===0&&m&&l.add(m)}for(const u of l){const m=Jr.get(u);m&&(clearTimeout(m),Jr.delete(u),Fo.delete(u))}l.size>0&&Xr(l);const d=Date.now();t(u=>{const m=Yn(u.messageStreamStates,l),f=u.messages.get(s)??[];let p=!1,h=u.messages;if(f.length>0&&l.size>0){const y=f.map(v=>{if(!l.has(v.info.id)&&l.size>0)return v;const S=(v.parts??[]).map(N=>{if(N.type==="reasoning"){const b=N,k={...b.time??{}};return typeof k.end!="number"&&(k.end=d),{...b,time:k}}if(N.type==="tool"){const b=N,k={...b.state??{}};return(k.status==="running"||k.status==="pending")&&(k.status="aborted"),{...b,state:k}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts: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:cr(u.streamingMessageIds,s,null),...p?{messages:h}:{}}}),Fe.abortSession(s).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(s,n,o,a,c)=>{const l=r();if(Jc.has(n))return;const d=l.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!Ro(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=l.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>Sr.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=jn(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 I=new Map(h.sessionAbortFlags);return I.delete(s),{...M,sessionAbortFlags:I}},S=M=>{const C=M||"",I=Fo.get(n);if(C&&I===C){const D=r();if(Zc(D,s,n)){const T=Jr.get(n);T&&(clearTimeout(T),Jr.delete(n)),setTimeout(()=>{const L=r();typeof L.forceCompleteMessage=="function"&&L.forceCompleteMessage(s,n,"timeout"),L.completeStreamingMessage(s,n)},100)}}Fo.set(n,C);const E=Jr.get(n);E&&clearTimeout(E);const P=setTimeout(()=>{const D=r();typeof D.forceCompleteMessage=="function"&&D.forceCompleteMessage(s,n,"timeout"),Zc(D,s,n)&&D.completeStreamingMessage(s,n),Jr.delete(n),Fo.delete(n)},8e3);Jr.set(n,P)},N=s!==c,b=h.sessionMemoryState.get(s);if(N&&b?.isStreaming){g.length>=Sr.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(),I=new Map(h.sessionMemoryState);I.set(s,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??C,lastAccessedAt:C,isZombie:!1}),h.sessionMemoryState=I}}const k=lo(o);if(pi(k)&&(o.synthetic=!0),bb()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:k.length,snapshotParts:u.length})}catch{}const A=w.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=cr(A,s,n);M!==A&&(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 I=Xn(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`user_part_type:${I.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((T,L)=>L===C?I:T):E.parts=[...E.parts,I];const P=[...g];P[j]=E;const D=new Map(h.messages);return D.set(s,P),v({messages:D})}if(f==="assistant"&&j!==-1){const M=g[j],C=M.parts.findIndex(L=>L.id===o.id),I=Xn(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${I.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((L,V)=>V===C?I:L):E.parts=[...E.parts,I];const P=[...g];P[j]=E;const D=new Map(h.messages);D.set(s,P),w.messageStreamStates=hi(h.messageStreamStates,n);const T=cr(w.streamingMessageIds??h.streamingMessageIds,s,n);return T!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set")),I.type==="text"?S(I.text||""):S(""),v({messages:D,...w})}if(j===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const te=Xn(o);window.__messageTracker?.(n,`new_user_part_type:${te.type||"unknown"}`);const pe=h.pendingUserMessageMetaBySession.get(s),R=ht.getState(),ee=pe?.mode??R.getSessionAgentSelection(s)??R.getCurrentAgent(s),B=typeof ee=="string"&&ee.trim().length>0?ee.trim():void 0,W=pe?.providerID??(h.lastUsedProvider?.providerID||void 0),X=pe?.modelID??(h.lastUsedProvider?.modelID||void 0);pe&&(w.pendingUserMessageMetaBySession=Yc(h.pendingUserMessageMetaBySession,s));const ie={info:{id:n,sessionID:s,role:"user",clientRole:"user",userMessageMarker:!0,...B?{mode:B}:{},...W?{providerID:W}:{},...X?{modelID:X}:{},time:{created:Date.now()}},parts:[te]},be=[...g,ie];be.sort((me,we)=>{const he=me.info?.time?.created||0,_e=we.info?.time?.created||0;return he-_e});const H=new Map(h.messages);return H.set(s,be),v({messages:H})}if(o?.type==="text"){const te=lo(o).trim();if(te.length>0){const pe=[...g].reverse().find(R=>R.info.role==="user");if(pe){const R=pe.parts.map(ee=>lo(ee)).join("").trim();if(R.length>0&&R===te)return Jc.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=Xn(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?S(M.text||""):S("");const C=h.pendingAssistantParts.get(n),I=C?[...C.parts]:[],E=I.findIndex(te=>te.id===M.id);E!==-1?I[E]=M:I.push(M);const P=new Map(h.pendingAssistantParts);P.set(n,{sessionId:s,parts:I});const D=h.lastUsedProvider?.providerID||"",T=h.lastUsedProvider?.modelID||"",L=Date.now(),V=Fe.getDirectory()??"/",q=ht.getState(),_=q.getSessionAgentSelection(s)??q.getCurrentAgent(s),Y=typeof _=="string"&&_.trim().length>0?_.trim():void 0,K=h.pendingAssistantHeaderSessions.has(s);if(K){const te=new Set(h.pendingAssistantHeaderSessions);te.delete(s),w.pendingAssistantHeaderSessions=te}const Q={info:f==="user"?{id:n,sessionID:s,role:"user",time:{created:L},agent:Y||"default",model:{providerID:D,modelID:T},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:s,role:"assistant",time:{created:L},parentID:n,modelID:T,providerID:D,mode:Y||"default",...K?{openchamberHeaderAnchor:!0}:{},path:{cwd:V,root:V},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:I},z=[...g,Q],re=new Map(h.messages);if(re.set(s,z),f==="assistant"){w.messageStreamStates=hi(h.messageStreamStates,n);const te=cr(w.streamingMessageIds??h.streamingMessageIds,s,n);te!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=te,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:re,pendingAssistantParts:P,...w})}else{const M=g[j],C=M.parts.findIndex(T=>T.id===o.id),I=Xn(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${I.type||"unknown"}`);const E={...M};C!==-1?E.parts=E.parts.map((T,L)=>L===C?I:T):E.parts=[...E.parts,I];const P=[...g];P[j]=E;const D=new Map(h.messages);if(D.set(s,P),E.info.role==="assistant"){w.messageStreamStates=hi(h.messageStreamStates,n);const T=cr(w.streamingMessageIds??h.streamingMessageIds,s,n);T!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set"))}return I.type==="text"?S(I.text||""):S(""),v({messages:D,...w})}})},addStreamingPart:(s,n,o,a,c)=>{if(a!=="user"){r()._addStreamingPartImmediate(s,n,o,a,c);return}yi.push({sessionId:s,messageId:n,part:o,role:a,currentSessionId:c}),bi||(bi=setTimeout(()=>{const l=[...yi];yi=[],bi=null;const d=r();for(const u of l)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},gb))},forceCompleteMessage:(s,n,o="timeout")=>{const a=c=>{if(s)return s;for(const[l,d]of c.messages.entries())if(d.some(u=>u.info.id===n))return l;return null};t(c=>{const l=a(c);if(!l)return c;const d=c.messages.get(l)??[],u=d.findIndex(b=>b.info.id===n);if(u===-1)return c;const m=d[u];if(!m)return c;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 k=b.state;if(!k)return b;const A=k.status,j=A==="running"||A==="pending"||A==="started",M=!k.time||typeof k.time?.end!="number";if(j||M){const C={...k};return j&&(C.status="completed"),M&&(C.time={...k.time??{},end:f}),w=!0,{...b,state:C}}return b}if(b.type==="reasoning"){const k=b.time;return!k||typeof k.end!="number"?(w=!0,{...b,time:{...k??{},end:f}}):b}if(b.type==="text"){const k=b.time;return k&&typeof k.end!="number"?(w=!0,{...b,time:{...k,end:f}}):b}return b});if(!x&&!w)return c;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:g,parts:w?y:m.parts},S=[...d];S[u]=v;const N=new Map(c.messages);return N.set(l,S),{messages:N}})},markMessageStreamSettled:s=>{t(n=>{sf(s);const o=new Map(n.messageStreamStates);o.delete(s);let a=n.messages,c=!1;return n.messages.forEach((d,u)=>{if(c)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,c=!0}),{messageStreamStates:o,...c?{messages:a}:{}}}),Xr([s])},updateMessageInfo:(s,n,o)=>{t(l=>{const d=l.sessionMemoryState.get(s)?.trimmedHeadMaxId;if(d&&!Ro(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),l;const m=[...l.messages.get(s)??[]],f=m.findIndex(j=>j.info.id===n),p=l.pendingAssistantParts.get(n),h=(j=[],M=[])=>{if(!M.length)return j;const C=[...j];return M.forEach(I=>{const E=C.findIndex(P=>P.id===I.id);E===-1?C.push(I):C[E]=I}),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 V=m[0]?.info,q=typeof V?.time?.created=="number"?V.time.created:null,_=typeof V?.id=="string"?V.id:null,Y=o,K=typeof Y?.time?.created=="number"?Y.time.created:null,U=typeof Y?.id=="string"?Y.id:n;let Q=!1;if(K!==null&&q!==null&&(Q=K<q),!Q&&U&&_&&(Q=U.localeCompare(_)<0),Q)return window.__messageTracker?.(n,"skipped_evicted_message_update"),l}const j=x(o);if(j&&j.role==="user"){const L=p?.parts??[],V=l.pendingUserMessageMetaBySession.get(s),q={info:{...j,userMessageMarker:!0,clientRole:"user",...V?.mode?{mode:V.mode}:{},...V?.providerID?{providerID:V.providerID}:{},...V?.modelID?{modelID:V.modelID}:{}},parts:L.length>0?[...L]:[]},_=new Map(l.messages),Y=[...m,q];Y.sort((Q,z)=>{const re=Q.info?.time?.created||0,te=z.info?.time?.created||0;return re-te}),_.set(s,Y);const K={messages:_,...V?{pendingUserMessageMetaBySession:Yc(l.pendingUserMessageMetaBySession,s)}:{}},U=jn(K.messageSessionIndex??l.messageSessionIndex,n,s);if(U!==(K.messageSessionIndex??l.messageSessionIndex)&&(K.messageSessionIndex=U),p){const Q=new Map(l.pendingAssistantParts);Q.delete(n),K.pendingAssistantParts=Q}return K}if(!j||j.role!=="assistant")return l;const M=p?.parts??[],C=l.pendingAssistantHeaderSessions.has(s),I={info:{...j,animationSettled:j?.animationSettled??!1,...C?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},E=new Map(l.messages),P=[...m,I];E.set(s,P);const D={messages:E,...C?{pendingAssistantHeaderSessions:(()=>{const L=new Set(l.pendingAssistantHeaderSessions);return L.delete(s),L})()}:{}},T=jn(D.messageSessionIndex??l.messageSessionIndex,n,s);if(T!==(D.messageSessionIndex??l.messageSessionIndex)&&(D.messageSessionIndex=T),p){const L=new Map(l.pendingAssistantParts);L.delete(n),D.pendingAssistantParts=L}return D}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=l.pendingUserMessageMetaBySession.get(s);M&&!j.mode&&M.mode&&(j.mode=M.mode);const C={...g,info:j},I=new Map(l.messages),E=[...m];if(E[f]=C,I.set(s,E),M){const P=new Map(l.pendingUserMessageMetaBySession);return P.delete(s),{messages:I,pendingUserMessageMetaBySession:P}}return{messages:I}}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,N={...g,info:v,parts:S},b=new Map(l.messages),k=[...m];k[f]=N,b.set(s,k);const A={messages:b};if(p){const j=new Map(l.pendingAssistantParts);j.delete(n),A.pendingAssistantParts=j}return A});const a=o?.finish,c=o?.role;typeof a=="string"&&c!=="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 c={};if(a&&(c.streamingMessageIds=cr(o.streamingMessageIds,s,null),c.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),c.messageStreamStates=d}Object.keys(c).length>0&&t(c),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}}),Xr([n]);let l=!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),l=!0,{sessionMemoryState:m}}),l){const d=vn.get(s);d&&(clearTimeout(d),vn.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}}),vn.delete(s)},2e3);vn.set(s,u)}},syncMessages:(s,n)=>{const o=ed(s),a=td(n,o),c=r().sessionMemoryState.get(s)?.trimmedHeadMaxId,l=c?a.filter(d=>{const u=d?.info?.id;return u?Ro(u,c):!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=l.map(b=>{const k={...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},A=(Array.isArray(b.parts)?b.parts:[]).map(C=>{if(C?.type==="text"){const I=C.text??C.content??"";if(pi(I))return{...C,synthetic:!0}}return C}),j=typeof k?.id=="string"?k.id:void 0,M=j?f.get(j):void 0;if(M&&M.info.role==="assistant"){const C=Array.isArray(M.parts)?M.parts:[],I=Dn(C),E=Dn(A);if(ka(M.info)&&I>E){const D=Na(C,A);return{...b,info:k,parts:D}}}return{...b,info:k,parts:A}}),h=Lo(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};Xr(w);const v=Yn(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=cr(y.streamingMessageIds??d.streamingMessageIds,s,null))}if(w.length>0){const b=Oo(y.messageSessionIndex??d.messageSessionIndex,w);b!==(y.messageSessionIndex??d.messageSessionIndex)&&(y.messageSessionIndex=b)}if(w.length>0){const b=new Map(d.pendingAssistantParts);let k=!1;w.forEach(A=>{b.delete(A)&&(k=!0)}),k&&(y.pendingAssistantParts=b)}const S=y.messageSessionIndex??d.messageSessionIndex;let N=S;return h.forEach(b=>{const k=b?.info?.id;typeof k=="string"&&k.length>0&&(N=jn(N,k,s))}),N!==S&&(y.messageSessionIndex=N),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 c=n+xb;return a.get(s)===c?o:(a.set(s,c),{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},c=new Map(o.sessionMemoryState);return c.set(s,{...a,viewportAnchor:n}),{sessionMemoryState:c}})},trimToViewportWindow:(s,n,o)=>{const a=n??ja().VIEWPORT_MESSAGES,c=r(),l=c.messages.get(s);if(!l||l.length<=a)return;const d=c.sessionMemoryState.get(s)||{viewportAnchor:l.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(d.isStreaming&&s===o)return;const u=d.viewportAnchor||l.length-1;let m=Math.max(0,u-Math.floor(a/2));const f=Math.min(l.length,m+a);f===l.length&&f-m<a&&(m=Math.max(0,f-a));const p=l.slice(m,f),h=l.slice(0,m),x=new Set(p.map(w=>w.info.id)),g=l.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:vb(h,d.trimmedHeadMaxId)};v.set(s,S);const N={messages:y,sessionMemoryState:v};Xr(g);const b=Yn(w.messageStreamStates,g);if(b!==w.messageStreamStates&&(N.messageStreamStates=b),g.length>0){const j=w.streamingMessageIds.get(s);j&&g.includes(j)&&(N.streamingMessageIds=cr(N.streamingMessageIds??w.streamingMessageIds,s,null))}if(g.length>0){const j=Oo(N.messageSessionIndex??w.messageSessionIndex,g);j!==(N.messageSessionIndex??w.messageSessionIndex)&&(N.messageSessionIndex=j)}const k=N.messageSessionIndex??w.messageSessionIndex;let A=k;return p.forEach(j=>{const M=j?.info?.id;typeof M=="string"&&M.length>0&&(A=jn(A,M,s))}),A!==k&&(N.messageSessionIndex=A),N})},evictLeastRecentlyUsed:s=>{const n=r();if(n.messages.size<=Sr.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 c=a.filter(([d,u])=>d!==s&&!u.isStreaming);if(c.length===0)return;c.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const l=c[0][0];t(d=>{const m=(d.messages.get(l)||[]).map(N=>N.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(l);const h={messages:f,sessionMemoryState:p},x=new Map(d.pendingAssistantParts);let g=!1;x.forEach((N,b)=>{N.sessionId===l&&(x.delete(b),g=!0)}),g&&(h.pendingAssistantParts=x);const w=new Map(d.sessionCompactionUntil);w.delete(l)&&(h.sessionCompactionUntil=w),Xr(m);const y=Yn(d.messageStreamStates,m);y!==d.messageStreamStates&&(h.messageStreamStates=y);const v=Oo(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const S=cr(d.streamingMessageIds,l,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(l)){const N=new Map(d.abortControllers);N.delete(l),h.abortControllers=N}return h})},loadMoreMessages:async(s,n="up")=>{const o=r(),a=o.messages.get(s),c=o.sessionMemoryState.get(s);if(!a||!c||c.totalAvailableMessages&&a.length>=c.totalAvailableMessages)return;const l=await wi(s,()=>Fe.getSessionMessages(s));if(n==="up"&&a.length>0){const d=Lo(l),u=a[0],m=d.findIndex(f=>f.info.id===u.info.id);if(m>0){const f=Math.min(Sr.VIEWPORT_MESSAGES,m),p=d.slice(m-f,m);t(h=>{const x=[...p,...a],g=Lo(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,{...c,viewportAnchor:c.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,{...c,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 c=o[a];if(c.info.role==="assistant"&&"providerID"in c.info&&"modelID"in c.info)return{providerID:c.info.providerID,modelID:c.info.modelID}}return null}}),{name:"message-store",storage:Hs(()=>hs()),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"})),kb=t=>typeof t=="object"&&t!==null,Nb=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},Cb=async(t,r)=>{try{const n=ft.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()},bo=ns()(cs(Ws((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 c=s.permission?.toLowerCase?.()??null;let l=n?.currentAgentContext?.get(o);if(l||(l=n?.sessionAgentSelections?.get(o)??void 0),!l&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(l=f.getState().currentAgentName??void 0)}const d=ia(l),u=n?.getSessionAgentEditMode?.(o,l)??d;if(u==="full"||u==="allow"&&mb(c)){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 Cb(s,()=>Fe.replyToPermission(n,o)),o==="reject"&&await Et.getState().abortCurrentOperation(s),t(a=>{const l=(a.permissions.get(s)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(s,l),{permissions:d}})}}),{name:"permission-store",storage:Hs(()=>hs()),partialize:t=>({permissions:Array.from(t.permissions.entries())}),merge:(t,r)=>{if(!kb(t))return r;const s=Nb(t.permissions);return{...r,permissions:new Map(s)}}}),{name:"permission-store"})),Mb=t=>typeof t=="object"&&t!==null,Db=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},sd=async(t,r)=>{try{const n=ft.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()},An=ns()(cs(Ws((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 c=a.questions.get(n)||[],l=new Map(a.questions);return l.set(n,[...c,s]),{questions:l}})},dismissQuestion:(s,n)=>{!s||!n||t(o=>{const c=(o.questions.get(s)||[]).filter(d=>d.id!==n),l=new Map(o.questions);return l.set(s,c),{questions:l}})},respondToQuestion:async(s,n,o)=>{await sd(s,()=>Fe.replyToQuestion(n,o)),r().dismissQuestion(s,n)},rejectQuestion:async(s,n)=>{await sd(s,()=>Fe.rejectQuestion(n)),r().dismissQuestion(s,n)}}),{name:"question-store",storage:Hs(()=>hs()),partialize:t=>({questions:Array.from(t.questions.entries())}),merge:(t,r)=>{if(!Mb(t))return r;const s=Db(t.questions);return{...r,questions:new Map(s)}}}),{name:"question-store"})),Wl=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
- `),co=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},rd=(t,r,s)=>{if(!r)return null;const n=s(r)?.path;if(typeof n=="string"&&n.trim().length>0)return co(n);const o=t.find(a=>a.id===r);return o?co(o.directory??null):null},fe=ns()(cs((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)=>ht.getState().getSessionAgentEditMode(s,n,o),toggleSessionAgentEditMode:(s,n,o)=>ht.getState().toggleSessionAgentEditMode(s,n,o),setSessionAgentEditMode:(s,n,o,a)=>ht.getState().setSessionAgentEditMode(s,n,o,a),loadSessions:()=>ft.getState().loadSessions(),openNewSessionDraft:s=>{let n=null;s?.directoryOverride!==void 0?n=s.directoryOverride:n=Vt.getState().getActiveProject()?.path??null,t({newSessionDraft:{open:!0,directoryOverride:n,parentID:s?.parentID??null,title:s?.title},currentSessionId:null,error:null});try{const o=at.getState(),a=o.getVisibleAgents();let c;if(o.settingsDefaultAgent){const l=a.find(d=>d.name===o.settingsDefaultAgent);l&&(c=l.name)}c||(c=a.find(l=>l.name==="build")?.name||a[0]?.name),c&&o.setAgent(c)}catch{}},closeNewSessionDraft:()=>{const s=ft.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 ft.getState().createSession(s,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async s=>{if(!s)return;const n=Et.getState(),{messages:o,lastUsedProvider:a}=n;let c,l;if(o.forEach((y,v)=>{const S=y.find(N=>N.info?.id===s);S&&!c&&(c=S,l=v)}),!c||c.info.role!=="assistant")return;const d=Wl(c.parts);if(!d.trim())return;const u=ft.getState(),m=rd(u.sessions,l??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:x}=at.getState(),g=p||a?.providerID,w=h||a?.modelID;!g||!w||await Fe.sendMessage({id:f.id,providerID:g,modelID:w,text:d,prefaceText:tf,agent:x??void 0})},deleteSession:(s,n)=>ft.getState().deleteSession(s,n),deleteSessions:(s,n)=>ft.getState().deleteSessions(s,n),updateSessionTitle:(s,n)=>ft.getState().updateSessionTitle(s,n),shareSession:s=>ft.getState().shareSession(s),unshareSession:s=>ft.getState().unshareSession(s),setCurrentSession:async s=>{s&&r().closeNewSessionDraft();const n=ft.getState().currentSessionId,o=rd(ft.getState().sessions,s,ft.getState().getWorktreeMetadata),a=Fe.getDirectory()??bt.getState().currentDirectory??null,c=o??a;try{Fe.setDirectory(c??void 0)}catch(l){console.warn("Failed to set OpenCode directory for session switch:",l)}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,ja().VIEWPORT_MESSAGES)}if(ft.getState().setCurrentSession(s),s){r().messages.get(s)||await r().loadMessages(s),r().trimToViewportWindow(s,nl());const d=r().messages.get(s);if(d&&d.length>0){const u=at.getState().agents;if(u.length>0)try{await ht.getState().analyzeAndSaveExternalSessionChoices(s,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:(s,n)=>Et.getState().loadMessages(s,n),sendMessage:async(s,n,o,a,c,l,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=v=>{t(S=>{const N=new Map(S.sessionActivityPhase??new Map);return N.set(v,"busy"),{sessionActivityPhase:N}})},h=v=>{t(S=>{const N=new Map(S.sessionActivityPhase??new Map);return N.set(v,"idle"),{sessionActivityPhase:N}})};if(m?.open){const v=await ft.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!v?.id)throw new Error("Failed to create session");const S=at.getState(),N=S.currentAgentName,b=f??N,k=S.currentProviderId,A=S.currentModelId;if(k&&A)try{ht.getState().saveSessionModelSelection(v.id,k,A)}catch{}if(b){try{ht.getState().saveSessionAgentSelection(v.id,b)}catch{}if(k&&A){try{ht.getState().saveAgentModelForSession(v.id,b,k,A)}catch{}if(u!==void 0)try{ht.getState().saveAgentModelVariantForSession(v.id,b,k,A,u)}catch{}}}try{ft.getState().initializeNewOpenChamberSession(v.id,S.agents)}catch{}r().closeNewSessionDraft(),p(v.id);try{return await Et.getState().sendMessage(s,n,o,b,v.id,c,l,d,u)}catch(j){throw h(v.id),j}}const x=ft.getState().currentSessionId,g=x?ht.getState().getSessionAgentSelection(x):null,w=at.getState().currentAgentName,y=f||g||w||void 0;if(x&&y){try{ht.getState().saveSessionAgentSelection(x,y)}catch{}if(u!==void 0)try{ht.getState().saveAgentModelVariantForSession(x,y,n,o,u)}catch{}}x&&p(x);try{return await Et.getState().sendMessage(s,n,o,y,x||void 0,c,l,d,u)}catch(v){throw x&&h(x),v}},abortCurrentOperation:()=>{const s=ft.getState().currentSessionId;return Et.getState().abortCurrentOperation(s||void 0)},armAbortPrompt:(s=3e3)=>{const n=ft.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&&Et.getState().acknowledgeSessionAbort(s)},addStreamingPart:(s,n,o,a)=>{const l=ft.getState().currentSessionId||s;return Et.getState().addStreamingPart(s,n,o,a,l)},completeStreamingMessage:(s,n)=>Et.getState().completeStreamingMessage(s,n),markMessageStreamSettled:s=>Et.getState().markMessageStreamSettled(s),updateMessageInfo:(s,n,o)=>Et.getState().updateMessageInfo(s,n,o),updateSessionCompaction:(s,n)=>Et.getState().updateSessionCompaction(s,n??null),addPermission:s=>{const n={currentAgentContext:ht.getState().currentAgentContext,sessionAgentSelections:ht.getState().sessionAgentSelections,getSessionAgentEditMode:ht.getState().getSessionAgentEditMode};return bo.getState().addPermission(s,n)},respondToPermission:(s,n,o)=>bo.getState().respondToPermission(s,n,o),addQuestion:s=>An.getState().addQuestion(s),dismissQuestion:(s,n)=>An.getState().dismissQuestion(s,n),respondToQuestion:(s,n,o)=>An.getState().respondToQuestion(s,n,o),rejectQuestion:(s,n)=>An.getState().rejectQuestion(s,n),clearError:()=>ft.getState().clearError(),getSessionsByDirectory:s=>ft.getState().getSessionsByDirectory(s),getDirectoryForSession:s=>ft.getState().getDirectoryForSession(s),getLastMessageModel:s=>Et.getState().getLastMessageModel(s),getCurrentAgent:s=>ht.getState().getCurrentAgent(s),syncMessages:(s,n)=>Et.getState().syncMessages(s,n),applySessionMetadata:(s,n)=>ft.getState().applySessionMetadata(s,n),addAttachedFile:s=>or.getState().addAttachedFile(s),addServerFile:(s,n,o)=>or.getState().addServerFile(s,n,o),removeAttachedFile:s=>or.getState().removeAttachedFile(s),clearAttachedFiles:()=>or.getState().clearAttachedFiles(),updateViewportAnchor:(s,n)=>Et.getState().updateViewportAnchor(s,n),trimToViewportWindow:(s,n)=>{const o=ft.getState().currentSessionId,a=r().sessionActivityPhase?.get(s);if(!(a==="busy"||a==="cooldown"))return Et.getState().trimToViewportWindow(s,n,o||void 0)},evictLeastRecentlyUsed:()=>{const s=ft.getState().currentSessionId;return Et.getState().evictLeastRecentlyUsed(s||void 0)},loadMoreMessages:(s,n)=>Et.getState().loadMoreMessages(s,n),saveSessionModelSelection:(s,n,o)=>ht.getState().saveSessionModelSelection(s,n,o),getSessionModelSelection:s=>ht.getState().getSessionModelSelection(s),saveSessionAgentSelection:(s,n)=>ht.getState().saveSessionAgentSelection(s,n),getSessionAgentSelection:s=>ht.getState().getSessionAgentSelection(s),saveAgentModelForSession:(s,n,o,a)=>ht.getState().saveAgentModelForSession(s,n,o,a),getAgentModelForSession:(s,n)=>ht.getState().getAgentModelForSession(s,n),saveAgentModelVariantForSession:(s,n,o,a,c)=>ht.getState().saveAgentModelVariantForSession(s,n,o,a,c),getAgentModelVariantForSession:(s,n,o,a)=>ht.getState().getAgentModelVariantForSession(s,n,o,a),analyzeAndSaveExternalSessionChoices:(s,n)=>{const o=Et.getState().messages;return ht.getState().analyzeAndSaveExternalSessionChoices(s,n,o)},isOpenChamberCreatedSession:s=>ft.getState().isOpenChamberCreatedSession(s),markSessionAsOpenChamberCreated:s=>ft.getState().markSessionAsOpenChamberCreated(s),initializeNewOpenChamberSession:(s,n)=>ft.getState().initializeNewOpenChamberSession(s,n),setWorktreeMetadata:(s,n)=>ft.getState().setWorktreeMetadata(s,n),setSessionDirectory:(s,n)=>ft.getState().setSessionDirectory(s,n),getWorktreeMetadata:s=>ft.getState().getWorktreeMetadata(s),getContextUsage:(s,n)=>{if(r().newSessionDraft?.open)return null;const o=ft.getState().currentSessionId;if(!o)return null;const a=Et.getState().messages;return ht.getState().getContextUsage(o,s,n,a)},updateSessionContextUsage:(s,n,o)=>{const a=Et.getState().messages;return ht.getState().updateSessionContextUsage(s,n,o,a)},initializeSessionContextUsage:(s,n,o)=>{const a=Et.getState().messages;return ht.getState().initializeSessionContextUsage(s,n,o,a)},debugSessionMessages:async s=>{const n=Et.getState().messages.get(s)||[],o=ft.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=Et.getState().messages;return ht.getState().pollForTokenUpdates(s,n,a,o)},updateSession:s=>ft.getState().updateSession(s),removeSessionFromStore:s=>ft.getState().removeSessionFromStore(s),revertToMessage:async(s,n)=>{const a=(Et.getState().messages.get(s)||[]).find(m=>m.info.id===n);let c="";a&&a.info.role==="user"&&(c=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
- `).trim());const l=await Fe.revertSession(s,n);ft.getState().updateSession(l);const d=Et.getState().messages.get(s)||[],u=l.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);Et.getState().syncMessages(s,f)}}c&&t({pendingInputText:c})},handleSlashUndo:async s=>{const o=(r().messages.get(s)||[]).filter(p=>p.info.role==="user"),c=r().sessions.find(p=>p.id===s);if(o.length===0)return;const l=c?.revert?.messageID;let d;if(l){const p=o.findIndex(h=>h.info.id===l);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(s,d.info.id);const{toast:f}=await bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);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 l=(r().messages.get(s)||[]).filter(m=>m.info.role==="user"),d=l.findIndex(m=>m.info.id===a),u=l[d-1];if(u){const m=u.parts.find(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 bs(async()=>{const{toast:h}=await import("./vendor-.bun-BrcdMJ39.js").then(x=>x.db);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Fe.unrevertSession(s);await ft.getState().updateSession(m),await r().loadMessages(s);const{toast:f}=await bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(s,n)=>{const a=r().sessions.find(c=>c.id===s);if(a)try{const c=await Fe.forkSession(s,n);if(!c||!c.id){const{toast:f}=await bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);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 bs(async()=>{const{toast:p}=await import("./vendor-.bun-BrcdMJ39.js").then(h=>h.db);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(c.id),u&&t({pendingInputText:u}),await r().loadMessages(c.id);const{toast:m}=await bs(async()=>{const{toast:f}=await import("./vendor-.bun-BrcdMJ39.js").then(p=>p.db);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(c){console.error("Failed to fork session:",c);const{toast:l}=await bs(async()=>{const{toast:d}=await import("./vendor-.bun-BrcdMJ39.js").then(u=>u.db);return{toast:d}},__vite__mapDeps([0,1]));l.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"}));ft.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})});Et.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 c=n[a];if(!c||!c.info)continue;const l=c.info;if(l.role==="user"){const d=l.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=l.time&&typeof l.time.created=="number"?l.time.created:null;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})});or.subscribe((t,r)=>{t.attachedFiles!==r.attachedFiles&&fe.setState({attachedFiles:t.attachedFiles})});ht.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})});bo.subscribe((t,r)=>{t.permissions!==r.permissions&&fe.setState({permissions:t.permissions})});An.subscribe((t,r)=>{t.questions!==r.questions&&fe.setState({questions:t.questions})});bt.subscribe((t,r)=>{const s=co(t.currentDirectory??null),n=co(r.currentDirectory??null);if(s===n)return;const o=fe.getState().newSessionDraft;if(!o?.open)return;const a=co(o.directoryOverride);a&&a!==n||fe.setState(c=>({newSessionDraft:{...c.newSessionDraft,directoryOverride:s,parentID:null}}))});const Ab=fe.getState().newSessionDraft?.open;fe.setState({sessions:ft.getState().sessions,currentSessionId:Ab?null:ft.getState().currentSessionId,lastLoadedDirectory:ft.getState().lastLoadedDirectory,isLoading:ft.getState().isLoading,error:ft.getState().error,webUICreatedSessions:ft.getState().webUICreatedSessions,worktreeMetadata:ft.getState().worktreeMetadata,availableWorktrees:ft.getState().availableWorktrees,availableWorktreesByProject:ft.getState().availableWorktreesByProject,messages:Et.getState().messages,sessionMemoryState:Et.getState().sessionMemoryState,messageStreamStates:Et.getState().messageStreamStates,sessionCompactionUntil:Et.getState().sessionCompactionUntil,sessionAbortFlags:Et.getState().sessionAbortFlags,streamingMessageIds:Et.getState().streamingMessageIds,abortControllers:Et.getState().abortControllers,lastUsedProvider:Et.getState().lastUsedProvider,isSyncing:Et.getState().isSyncing,permissions:bo.getState().permissions,questions:An.getState().questions,attachedFiles:or.getState().attachedFiles,sessionModelSelections:ht.getState().sessionModelSelections,sessionAgentSelections:ht.getState().sessionAgentSelections,sessionAgentModelSelections:ht.getState().sessionAgentModelSelections,currentAgentContext:ht.getState().currentAgentContext,sessionContextUsage:ht.getState().sessionContextUsage,sessionAgentEditModes:ht.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=fe);const Hl=({containerRef:t,minThumbSize:r=32,hideDelayMs:s=1e3,className:n,disableHorizontal:o=!1})=>{const[a,c]=i.useState(!1),[l,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:I,scrollTop:E,scrollWidth:P,clientWidth:D,scrollLeft:T}=M,L=8;if(C>I){const V=Math.max(I-L*2,0),q=I/C*V,_=Math.max(r,Math.min(V,q)),Y=Math.max(V-_,0),K=Math.max(C-I,1),U=E/K*Y;d({length:_,offset:U})}else d({length:0,offset:0});if(!o&&P>D){const V=Math.max(D-L*2,0),q=D/P*V,_=Math.max(r,Math.min(V,q)),Y=Math.max(V-_,0),K=Math.max(P-D,1),U=T/K*Y;m({length:_,offset:U})}else m({length:0,offset:0})},[t,r,o]),y=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>c(!1),s)},[s]),v=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{w(),c(!0),y()})},[y,w]);i.useEffect(()=>{const M=t.current;if(!M)return;w(),c(!0),y(),M.addEventListener("scroll",v,{passive:!0});const C=typeof ResizeObserver<"u"?new ResizeObserver(()=>w()):null;C?.observe(M);const I=typeof MutationObserver<"u"?new MutationObserver(()=>w()):null;return I?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),C?.disconnect(),I?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[t,v,y,w]);const S=(M,C)=>{const I=t.current;I&&(h.current=!0,x.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:I.scrollTop,scrollLeft:I.scrollLeft},g.current=C,c(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},N=M=>{if(!h.current)return;const C=t.current;if(!C)return;const I=g.current;if(I==="vertical"){const{pointerY:E,scrollTop:P}=x.current,D=M.clientY-E,T=C.clientHeight,L=Math.max(T-l.length,1),V=Math.max(C.scrollHeight-C.clientHeight,1),q=D/L*V;C.scrollTop=P+q}else if(I==="horizontal"){const{pointerX:E,scrollLeft:P}=x.current,D=M.clientX-E,T=C.clientWidth,L=Math.max(T-u.length,1),V=Math.max(C.scrollWidth-C.clientWidth,1),q=D/L*V;C.scrollLeft=P+q}},b=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),y())},k=l.length>0,A=u.length>0;if(!k&&!A)return null;const j=8;return e.jsxs("div",{className:F("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[k&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${l.length}px`,top:`${j+l.offset}px`,right:`${j/2}px`},onPointerDown:M=>S(M,"vertical"),onPointerMove:N,onPointerUp:b,onPointerCancel:b}),A&&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:N,onPointerUp:b,onPointerCancel:b})]})},gt=i.forwardRef(({className:t,outerClassName:r,children:s,style:n,minThumbSize:o,hideDelayMs:a,as:c="div",scrollbarClassName:l,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(c,{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(Hl,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:l,disableHorizontal:d})]})});gt.displayName="ScrollableOverlay";const nd="mobile-overlay-root",Eb=()=>{if(typeof document>"u")return null;let t=document.getElementById(nd);return t||(t=document.createElement("div"),t.id=nd,document.body.appendChild(t)),t},$s=({open:t,title:r,onClose:s,children:n,footer:o,className:a,contentMaxHeightClassName:c,renderHeader:l})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Eb()),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=c??"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(Zt,{className:"h-4 w-4"})});return l?l(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(gt,{outerClassName:u,className:"px-2 py-2 pwa-overlay-scroll",children:n}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return Ku.createPortal(m,d.current)},al=({totalTokens:t,percentage:r,contextLimit:s,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[c,l]=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(()=>{l(!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(zp,{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($s,{open:c,onClose:()=>l(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(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))})})]})},Zn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},rf=(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 vi(){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,c=typeof navigator<"u"?navigator.maxTouchPoints??0:0,l=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||c>0,u=t>Zn.md&&t<=Zn.lg,m=t<=Zn.md;let f=d&&m,p=d&&!f&&u,h=!d||t>Zn.lg,x="desktop";l?(f=!1,p=!1,h=!0,x="desktop"):f?x="mobile":p?x="tablet":(h=!0,x="desktop"),rf(l,x,d);let g="xs";for(const[w,y]of Object.entries(Zn))t>=y&&(g=w);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:x,screenWidth:t,breakpoint:g,hasTouchInput:d}}function Qt(){const[t,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:vi());return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(vi())};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(vi())},a=[],c=l=>{l&&(typeof l.addEventListener=="function"?(l.addEventListener("change",o),a.push(()=>l.removeEventListener("change",o))):typeof l.addListener=="function"&&(l.addListener(o),a.push(()=>l.removeListener(o))))};return c(s),c(n),()=>{a.forEach(l=>l())}},[]),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,c=o?.matches??!1,l=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=c||l||d>0;rf(s,t.deviceType,u)},[t.deviceType,t.hasTouchInput]),t}const _o=5e3,Ib=1e4,Pb=5e3,Tb=1e4,Fb=25,Rb=4,od=15e3,dr=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Lb=(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},Ob=(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!!Lb(t.diffStats,r.diffStats)},_b=(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])),c=new Map(o.map(f=>[f.path,f])),l=new Set([...a.keys(),...c.keys()]);for(const f of l){const p=a.get(f),h=c.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},as=ns()(cs((t,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:_o,setActiveDirectory:s=>{const{activeDirectory:n,directories:o}=r();if(n!==s)if(s&&!o.has(s)){const a=new Map(o);a.set(s,dr()),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:c}=r();let l=c.get(s);l||(l=dr()),a||t({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(s)){const f=new Map(c);return f.set(s,{...l,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),t({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(s);if(Ob(l.status,m)){d=!0;const f=new Map(r().directories),p=f.get(s)??dr(),h=_b(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)??dr();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),c=a.get(s)??dr();a.set(s,{...c,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(),c=a.get(s),l=o??c?.logMaxCount??25;t({isLoadingLog:!0});try{const d=await n.getGitLog(s,{maxCount:l}),u=new Map(r().directories),m=u.get(s)??dr();u.set(s,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:l}),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),c=a.get(s)??dr();a.set(s,{...c,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 c=a.get(s);if(!c){c=dr();const f=new Map(a);f.set(s,c),t({directories:f})}const{force:l=!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);(l||m>Tb||!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),c=a.get(s)??dr(),l=new Map(c.diffCache);l.set(n,{...o,fetchedAt:Date.now()}),a.set(s,{...c,diffCache:l}),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 l=o.status.files.filter(v=>!o.diffCache.has(v.path)).slice(0,Fb);if(l.length===0)return;let d=0;const u=[],m=()=>{const v=d;return d+=1,v<l.length?l[v]:null},f=async v=>{const S=n.getGitFileDiff(s,{path:v}),N=new Promise((k,A)=>{setTimeout(()=>A(new Error(`Timed out after ${od}ms`)),od)}),b=await Promise.race([S,N]);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(Rb,l.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)??dr();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:l}=r();if(!l){t({pollIntervalId:o()});return}if(await r().fetchStatus(l,s,{silent:!0}))await r().fetchLog(l,s),r().fetchAllDiffs(l,s),t({currentPollInterval:_o});else{const m=Math.min(a+Pb,Ib);t({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&t({pollIntervalId:o()})},a)};t({pollIntervalId:o(),currentPollInterval:_o})},stopPolling:()=>{const{pollIntervalId:s}=r();s&&(clearTimeout(s),t({pollIntervalId:null,currentPollInterval:_o}))},refresh:async(s,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,s,n)}}),{name:"git-store"})),nf=t=>as(r=>t?r.directories.get(t)?.status??null:null),of=t=>as(r=>t?r.directories.get(t)?.branches??null:null),$b=t=>as(r=>t?r.directories.get(t)?.log??null:null),Bb=t=>as(r=>t?r.directories.get(t)?.identity??null:null),Ul=t=>as(r=>t?r.directories.get(t)?.isGitRepo??null:null),zb=t=>as(r=>t?r.directories.get(t)?.status?.files?.length??0:0);function es({...t}){return e.jsx(Wp,{"data-slot":"dropdown-menu",...t})}function ts({...t}){return e.jsx(Hp,{"data-slot":"dropdown-menu-trigger",...t})}function ss({className:t,sideOffset:r=4,...s}){return e.jsx(Up,{children:e.jsx(Vp,{"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 Nt({className:t,inset:r,variant:s="default",...n}){return e.jsx(Xp,{"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 Ca({...t}){return e.jsx(qp,{"data-slot":"dropdown-menu-radio-group",...t})}function Ma({className:t,children:r,...s}){return e.jsxs(Kp,{"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(Qp,{children:e.jsx(Gt,{className:"size-3"})})}),r]})}function _r({className:t,inset:r,...s}){return e.jsx(Gp,{"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 Ds({className:t,...r}){return e.jsx(Yp,{"data-slot":"dropdown-menu-separator",className:F("bg-border -mx-1 my-0.5 h-px",t),...r})}const Wb=Jp("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 Me({className:t,variant:r,size:s,asChild:n=!1,...o}){const a=n?Qu:"button";return e.jsx(a,{"data-slot":"button",className:F(Wb({variant:r,size:s,className:t})),...o})}const ko=Zp,Ka=({className:t,...r})=>e.jsx(eh,{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}),No=({className:t,...r})=>e.jsx(th,{className:F("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",t),...r}),Hb={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 Vl(t){return Hb[t]||{displayName:t.charAt(0).toUpperCase()+t.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Ub(t,r,s){const n=Vl(t);if(n.outputLanguage==="auto"){if(s?.filePath||s?.file_path||s?.sourcePath){const o=s.filePath||s.file_path||s.sourcePath,a=Pr(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 Pr(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 Vb=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function wo(t){const r=t.split(".").pop()?.toLowerCase();return Vb.includes(r||"")}function il(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 Gb(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 c=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let l=a;return typeof a=="object"?l=JSON.stringify(a,null,2):typeof a=="boolean"&&(l=a?"Yes":"No"),`${c}: ${l}`}).join(`
12
- `):String(t)}const Gl=i.createContext(null),Tr=()=>{const t=i.useContext(Gl);if(!t)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return t},af=t=>{const r=Tr();return t(r)},qb=()=>af(t=>t.runtime.isDesktop),lf=()=>af(t=>t.runtime.isVSCode),cf=({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(Me,{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(sh,{className:"h-3 w-3"}):e.jsx(rh,{className:"h-3 w-3"})})},ql=Pe.createContext(void 0);function Yr(){const t=Pe.useContext(ql);if(!t)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return t}function Qa(){return Pe.useContext(ql)}const Kb="Flexoki",Qb="dark",Yb={"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"},Xb=[{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"}}],Jb={name:Kb,type:Qb,colors:Yb,tokenColors:Xb},Zb="Flexoki",ew="light",tw={"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"},sw=[{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"}}],rw={name:Zb,type:ew,colors:tw,tokenColors:sw},Kl="flexoki-dark",Ql="flexoki-light",nw=Jb,ow=rw;function df(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 uf(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 Yl=uf(nw,Kl,"dark"),Xl=uf(ow,Ql,"light");df(Yl,Kl);df(Xl,Ql);const Bn={dark:Kl,light:Ql},ad=[Xl,Yl];let id=!1;function mf(){id||(xc(Bn.dark,async()=>Yl),xc(Bn.light,async()=>Xl),id=!0)}const ji=({...t})=>{const{theme:r="system"}=nh();return e.jsx(oh,{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})},ld=async t=>{try{await navigator.clipboard.writeText(t)}catch(r){console.error("Failed to copy to clipboard:",r)}},G={...Qn,success:(t,r)=>Qn.success(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),info:(t,r)=>Qn.info(t,{...r,action:r?.action||{label:"OK",onClick:()=>{}}}),error:(t,r)=>Qn.error(t,{...r,action:r?.action||{label:"Copy",onClick:()=>ld(String(t))}}),warning:(t,r)=>Qn.warning(t,{...r,action:r?.action||{label:"Copy",onClick:()=>ld(String(t))}})},Rs=Pe.forwardRef(({className:t,...r},s)=>e.jsx(gt,{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 aw=`
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 iw(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 lw=(t,r,s)=>{const a=(s.side==="deletions"?t:r).split(`
75
- `),c=Math.max(1,s.start),l=Math.min(a.length,s.end);return c>l?"":a.slice(c-1,l).join(`
76
- `)},ll=({original:t,modified:r,language:s,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:c="fill"})=>{const{isMobile:l}=Qt(),{inputBarOffset:d,isKeyboardOpen:u}=Te(),f=Qa()?.currentTheme?.metadata?.variant==="dark",p=Te(K=>K.setActiveMainTab),[h,x]=Pe.useState(null),[g,w]=Pe.useState(""),y=Pe.useRef(null),v=Pe.useCallback(()=>{if(l)return"50%";const K=document.querySelector("main.flex-1");if(K){const U=K.getBoundingClientRect();return`${U.left+U.width/2}px`}return"50%"},[l]),[S,N]=Pe.useState(v),b=fe(K=>K.sendMessage),k=fe(K=>K.currentSessionId),{currentProviderId:A,currentModelId:j,currentAgentName:M,currentVariant:C}=at(),I=ht(K=>K.getSessionAgentSelection),E=ht(K=>K.getAgentModelForSession),P=ht(K=>K.getAgentModelVariantForSession);Pe.useEffect(()=>{if(l)return;const K=()=>{N(v())};return window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[l,v]);const D=Pe.useCallback(K=>{if(l&&K&&h&&K.start===K.end){const U=K.start,Q=h.start,z=h.end,re=Math.min(Q,z,U),te=Math.max(Q,z,U);if(U<Q||U>z){x({...K,start:re,end:te});return}}x(K),K||w("")},[l,h]);Pe.useEffect(()=>{if(!h)return;const K=Q=>{const z=Q.target;if(y.current?.contains(z)||z.closest("[data-sonner-toast]")||z.closest("[data-sonner-toaster]"))return;Q.composedPath().some(pe=>pe instanceof HTMLElement?pe.hasAttribute("data-line-number")||pe.closest?.("[data-line-number]"):!1)||(x(null),w(""))},U=setTimeout(()=>{document.addEventListener("click",K)},100);return()=>{clearTimeout(U),document.removeEventListener("click",K)}},[h]);const T=Pe.useCallback(async()=>{if(!h||!g.trim())return;if(!k){G.error("Select a session to send comment");return}const K=I(k)||M,U=K?E(k,K):null,Q=U?.providerId||A,z=U?.modelId||j;if(!Q||!z){G.error("Select a model to send comment");return}const re=K&&Q&&z?P(k,K,Q,z)??C:C,te=lw(t,r,h),pe=h.start,R=h.end,ee=h.side==="deletions"?"original":"modified",B=`Comment on \`${n}\` lines ${pe}-${R} (${ee}):
77
- \`\`\`${s}
78
- ${te}
79
- \`\`\`
80
-
81
- ${g}`;w(""),x(null),p("chat");try{await b(B,Q,z,K,void 0,void 0,void 0,re)}catch(W){console.error("Failed to send comment",W)}},[h,g,t,r,n,s,b,k,A,j,M,C,p,I,E,P]);mf();const L=Pe.useRef(null),V=Pe.useMemo(()=>{const K=iw(n,t,r);if(L.current?.key===K)return L.current.fileDiff;const U={name:n,contents:t,cacheKey:`old-${K}`},Q={name:n,contents:r,cacheKey:`new-${K}`},z=Gi(U,Q);return L.current={key:K,fileDiff:z},z},[n,t,r,s]),q=Pe.useMemo(()=>({theme:{dark:Bn.dark,light:Bn.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:D,unsafeCSS:aw}),[f,o,a,D]);if(typeof window>"u")return null;const Y=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:K=>{w(K.target.value);const U=K.target;U.style.height="auto";const z=20*5+8;U.style.height=`${Math.min(U.scrollHeight,z)}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:!l,rows:1,onKeyDown:K=>{K.key==="Enter"&&(K.metaKey||K.ctrlKey)&&(K.preventDefault(),T()),K.key==="Escape"&&(K.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:[!l&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Xt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:K=>{g.trim()&&(K.preventDefault(),T())},onClick:()=>{l||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(La,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return c==="fill"?e.jsxs("div",{className:F("flex flex-col relative","size-full"),style:{paddingBottom:l?"var(--oc-keyboard-inset, 0px)":void 0},children:[e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(gt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(yc,{fileDiff:V,options:q,selectedLines:h})})}),h&&e.jsx("div",{className:F("pointer-events-auto relative pb-2 transition-none z-50 flex justify-center",l&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:l&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:Y})]}):e.jsxs("div",{className:F("relative","w-full"),children:[e.jsx(gt,{outerClassName:"pierre-diff-wrapper w-full",disableHorizontal:!1,fillContainer:!1,children:e.jsx(yc,{fileDiff:V,options:q,selectedLines:h})}),h&&Ku.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:l?"var(--oc-keyboard-inset, 0px)":"0px",isolation:"isolate"},children:e.jsx("div",{className:F("pointer-events-auto relative pb-2 transition-none",l&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginLeft:S,transform:"translateX(-50%)",marginBottom:l&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",ref:y,children:Y})}),document.body)]})},cw=1100,ff=15e3,pf={"?":{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"}},dw=pf.M,la=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],uw=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"},hf=t=>{const r=uw(t);return pf[r]??dw},mw=t=>{const{index:r,working_dir:s}=t;return r==="A"||s==="A"||r==="?"||s==="?"},Da=(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]})},fw=i.memo(({changedFiles:t,selectedFile:r,selectedFileEntry:s,onSelectFile:n,isMobile:o,showModeSelector:a=!1,mode:c,onModeChange:l})=>{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(es,{children:[e.jsx(ts,{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)}),Da(s.insertions,s.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Ot,{className:"size-4 opacity-50"})]})}),e.jsxs(ss,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&c&&l?e.jsxs(e.Fragment,{children:[e.jsx(_r,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(Ca,{value:c,onValueChange:u=>l(u),children:la.map(u=>e.jsx(Ma,{value:u.value,className:"items-center",children:e.jsx("span",{className:"typography-meta text-foreground",children:u.label})},u.value))}),e.jsx(Ds,{})]}):null,e.jsx(Ca,{value:r??"",onValueChange:n,children:t.map(u=>e.jsx(Ma,{value:u.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(u.path)}),e.jsx("span",{className:"ml-auto",children:Da(u.insertions,u.deletions)})]})},u.path))})]})]})}),pw=i.memo(({mode:t,onModeChange:r})=>{const s=la.find(n=>n.value===t)??la[0];return e.jsxs(es,{children:[e.jsx(ts,{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(Ot,{className:"size-4 opacity-50"})]})}),e.jsx(ss,{className:"min-w-[220px]",children:e.jsx(Ca,{value:t,onValueChange:n=>r(n),children:la.map(n=>e.jsx(Ma,{value:n.value,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-meta text-foreground",children:n.label}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:n.description})]})},n.value))})})]})}),hw=i.memo(({changedFiles:t,selectedFile:r,onSelectFile:s})=>t.length===0?null:e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:t.map(n=>{const o=hf(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}),Da(n.insertions,n.deletions)]})},n.path)})})})),gw=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 c=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",l=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:c,children:[o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${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:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${t}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),xw=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",c=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: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:s?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),o&&e.jsxs("div",{className:c,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"}})]})]})})}),yw=i.memo(({filePath:t,diff:r,renderSideBySide:s,wrapLines:n})=>{const o=i.useMemo(()=>Pr(t)||"text",[t]);return wo(t)?e.jsx(xw,{filePath:t,diff:r,renderSideBySide:s}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(ll,{original:r.original,modified:r.modified,language:o,fileName:t,renderSideBySide:s,wrapLines:n,layout:"inline"})})}),bw=i.memo(({filePath:t,diff:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>Pr(t)||"text",[t]);return wo(t)?e.jsx(gw,{filePath:t,diff:r,isVisible:s,renderSideBySide:n}):s?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(ll,{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(ll,{original:r.original,modified:r.modified,language:a,fileName:t,renderSideBySide:n,wrapLines:o})})}),ww=i.memo(({directory:t,filePath:r,isVisible:s,renderSideBySide:n,wrapLines:o})=>{const a=as(i.useCallback(l=>l.directories.get(t)?.diffCache.get(r)??null,[t,r])),c=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return c?e.jsx(bw,{filePath:r,diff:c,isVisible:s,renderSideBySide:n,wrapLines:o}):null}),vw=i.memo(({directory:t,file:r,layout:s,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:c,registerSectionRef:l})=>{const{git:d}=Tr(),u=as(i.useCallback(D=>D.directories.get(t)?.diffCache.get(r.path)??null,[t,r.path])),m=as(D=>D.setDiff),f=Te(D=>D.setDiffFileLayout),[p,h]=i.useState(!0),[x,g]=i.useState(!1),[w,y]=i.useState(0),[v,S]=i.useState(null),[N,b]=i.useState(!1),k=i.useRef(null),A=i.useRef(null),j=i.useMemo(()=>hf(r),[r]),M=s==="side-by-side",C=i.useMemo(()=>u?{original:u.original,modified:u.modified}:null,[u]),I=i.useCallback(D=>{A.current=D,l(r.path,D)},[r.path,l]),E=i.useCallback(D=>{h(D),D&&g(!0)},[]),P=i.useCallback(()=>{c(r.path)},[r.path,c]);return i.useEffect(()=>{if(!p||x)return;const D=A.current;if(!D)return;if(!o.current||typeof IntersectionObserver>"u"){g(!0);return}const T=new IntersectionObserver(L=>{L.some(V=>V.isIntersecting)&&(g(!0),T.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return T.observe(D),()=>T.disconnect()},[x,p,o]),i.useEffect(()=>{if(!p||!x)return;if(!t||C){k.current=null,b(!1);return}const D=`${t}::${r.path}::${w}`;if(k.current===D)return;k.current=D,S(null),b(!0);let T=!1;return(async()=>{try{const L=d.getGitFileDiff(t,{path:r.path}),V=ff,q=new Promise((Y,K)=>{setTimeout(()=>K(new Error(`Timed out after ${V}ms`)),V)}),_=await Promise.race([L,q]);if(T)return;m(t,r.path,{original:_.original??"",modified:_.modified??""}),b(!1)}catch(L){if(T)return;const V=L instanceof Error?L.message:String(L);S(V),b(!1)}})(),()=>{T=!0,k.current===D&&(k.current=null)}},[t,C,w,r.path,d,x,p,m]),e.jsx("div",{ref:I,className:"scroll-mt-4",children:e.jsxs(ko,{open:p,onOpenChange:E,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(Ka,{onClick:P,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(Ot,{className:"size-4"}):e.jsx(Bs,{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:[Da(r.insertions,r.deletions),e.jsx(cf,{mode:M?"side-by-side":"unified",onModeChange:D=>{const T=D==="side-by-side"?"side-by-side":"inline";f(r.path,T)},className:"opacity-70"})]})]})}),e.jsx(No,{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(D=>D+1),children:"Retry"})]}):null,N&&!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(Jt,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,C?e.jsx(yw,{filePath:r.path,diff:C,renderSideBySide:M,wrapLines:n}):null]})})]})})}),jw=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=fe(),{currentDirectory:n}=bt(),o=t?s.get(t)??void 0:void 0,c=r.find(l=>l.id===t)?.directory;return o?.path??c??n??void 0},Sw=()=>{const{git:t}=Tr(),r=jw(),{screenWidth:s,isMobile:n}=Qt(),o=Ul(r??null),a=nf(r??null),c=as(H=>H.isLoadingStatus),{setActiveDirectory:l,fetchStatus:d,setDiff:u}=as(),[m,f]=i.useState(null),[p,h]=i.useState(0),[x,g]=i.useState(null),w=i.useRef(null),y=Te(H=>H.pendingDiffFile),v=Te(H=>H.setPendingDiffFile),S=Te(H=>H.diffLayoutPreference),N=Te(H=>H.diffFileLayout),b=Te(H=>H.setDiffFileLayout),k=Te(H=>H.diffWrapLines),A=Te(H=>H.setDiffWrapLines),j=Te(H=>H.diffViewMode),M=Te(H=>H.setDiffViewMode),C=n||k,I=j==="stacked",E=n||s<=768,P=!E&&s>=1024,D=i.useRef(null),T=i.useRef(new Map),L=i.useRef(null),V=i.useMemo(()=>{if(!a?.files)return[];const H=a.diffStats??{};return a.files.map(me=>({...me,insertions:H[me.path]?.insertions??0,deletions:H[me.path]?.deletions??0,isNew:mw(me)})).sort((me,we)=>me.path.localeCompare(we.path))},[a]),q=i.useMemo(()=>m?V.find(H=>H.path===m)??null:null,[V,m]),_=i.useCallback(H=>{const me=N[H.path];if(me)return me;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const we=s<cw;return H.isNew||we?"inline":"side-by-side"},[N,S,s]),Y=i.useMemo(()=>q?_(q):null,[_,q]);i.useEffect(()=>{r&&(l(r),as.getState().directories.get(r)?.status||d(r,t))},[r,l,d,t]),i.useEffect(()=>{y&&(f(y),v(null),I&&(L.current=y))},[I,y,v]),i.useEffect(()=>{!m&&!y&&V.length>0&&f(V[0].path)},[V,m,y]),i.useEffect(()=>{if(!I){L.current=null;return}const H=L.current;if(!H)return;const me=T.current.get(H);me&&(me.scrollIntoView({behavior:"smooth",block:"start"}),L.current=null)},[V,I]),i.useEffect(()=>{m&&V.length>0&&(V.some(me=>me.path===m)||f(V[0]?.path??null))},[V,m]);const K=i.useCallback((H,me)=>{const we=T.current;me?we.set(H,me):we.delete(H)},[]),U=i.useCallback((H,me="smooth")=>{const we=T.current.get(H);return we?(we.scrollIntoView({behavior:me,block:"start"}),!0):!1},[]),Q=i.useCallback(H=>{f(H)},[]),z=i.useCallback(H=>{f(H),I&&!U(H)&&(L.current=H)},[I,U]),re=i.useCallback(H=>{M(H),H==="stacked"&&m&&!U(m,"auto")&&(L.current=m)},[U,m,M]),te=i.useCallback(H=>{const me=H==="side-by-side"?"side-by-side":"inline";if(I){V.forEach(we=>{b(we.path,me)});return}q&&b(q.path,me)},[V,I,q,b]),pe=(Y??"side-by-side")==="side-by-side",R=!I||!P,ee=as(i.useCallback(H=>!r||!m?null:H.directories.get(r)?.diffCache.get(m)??null,[r,m])),B=!!ee,W=!I&&!!m&&!B;i.useEffect(()=>{if(I)return;if(g(null),!r||!m){w.current=null;return}if(ee){w.current=null;return}const H=`${r}::${m}::${p}`;if(w.current===H)return;w.current=H;let me=!1;return(async()=>{try{const we=t.getGitFileDiff(r,{path:m}),he=ff,_e=new Promise((J,ne)=>{setTimeout(()=>ne(new Error(`Timed out after ${he}ms`)),he)}),se=await Promise.race([we,_e]);if(me)return;u(r,m,{original:se.original??"",modified:se.modified??""})}catch(we){if(me)return;const he=we instanceof Error?we.message:String(we);g(he)}})(),()=>{me=!0,w.current===H&&(w.current=null)}},[r,I,m,ee,t,u,p]);const X=()=>!r||V.length===0?null:V.map(H=>e.jsx(ww,{directory:r,filePath:H.path,isVisible:H.path===m,renderSideBySide:pe,wrapLines:C},H.path)),ie=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 gap-3 px-3 pb-3 pt-2",children:[P&&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:V.length})]}),e.jsx(hw,{changedFiles:V,selectedFile:m,onSelectFile:z})]}),e.jsx(gt,{ref:D,outerClassName:"flex-1 min-h-0",className:"pr-2",children:e.jsx("div",{className:"flex flex-col gap-3",children:V.map(H=>e.jsx(vw,{directory:r,file:H,layout:_(H),wrapLines:C,scrollRootRef:D,isSelected:H.path===m,onSelect:Q,registerSectionRef:K},H.path))})})]}):null,be=()=>r?c&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jt,{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."}):V.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"}):I?ie():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[X(),W&&!B&&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(H=>H+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(Jt,{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(kl,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:c&&!a?"Loading changes…":`${V.length} ${V.length===1?"file":"files"} changed`})]}),!E&&e.jsx(pw,{mode:j,onModeChange:re}),R&&e.jsx(fw,{changedFiles:V,selectedFile:m,selectedFileEntry:q,onSelectFile:z,isMobile:E,showModeSelector:E,mode:j,onModeChange:re}),e.jsx("div",{className:"flex-1"}),q&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>A(!k),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(Yu,{className:"size-4"})}),q&&Y&&e.jsx(cf,{mode:Y==="side-by-side"?"side-by-side":"unified",onModeChange:te})]}),be()]})},kw=()=>{const{git:t}=Tr(),{currentSessionId:r,sessions:s,worktreeMetadata:n}=fe(),{currentDirectory:o}=bt(),a=r?n.get(r)??void 0:void 0,l=s.find(p=>p.id===r)?.directory,d=a?.path??l??o??void 0,{setActiveDirectory:u,fetchStatus:m}=as(),f=zb(d??null);return i.useEffect(()=>{d&&(u(d),as.getState().directories.get(d)?.status||m(d,t))},[d,u,m,t]),f},uo=Pe.forwardRef(({className:t,...r},s)=>e.jsx(Xu,{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(ah,{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"}})}));uo.displayName=Xu.displayName;const Nw={},ca=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},cd=t=>ca(t)??"__global__",Cw=t=>{const r=Object.entries(t??{}),s=r.filter(([,c])=>c?.status==="connected").length,n=r.length,o=r.some(([,c])=>c?.status==="failed"),a=r.some(([,c])=>c?.status==="needs_auth"||c?.status==="needs_client_registration");return{connected:s,total:n,hasFailed:o,hasAuthRequired:a}},ro=ns()(cs((t,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:s=>{const n=cd(s??bt.getState().currentDirectory);return r().byDirectory[n]??Nw},refresh:async s=>{const n=ca(s?.directory??bt.getState().currentDirectory),o=cd(n);s?.silent||t(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const l=(await Fe.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};t(d=>({byDirectory:{...d.byDirectory,[o]:l},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const c=a instanceof Error?a.message:"Failed to load MCP status";t(l=>({loadingKeys:{...l.loadingKeys,[o]:!1},lastErrorKeys:{...l.lastErrorKeys,[o]:c}}))}},connect:async(s,n)=>{const o=ca(n??bt.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=ca(n??bt.getState().currentDirectory);await Fe.getApiClient().mcp.disconnect({name:s,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function Mw(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 Dw=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}},Aw=t=>{switch(t?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},cl=({headerIconButtonClass:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:c}=Qt(),d=bt(j=>j.currentDirectory)??null,u=ro(j=>j.getStatusForDirectory(d)),m=ro(j=>j.refresh),f=ro(j=>j.connect),p=ro(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(()=>Cw(u),[u]),N=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]),k=()=>e.jsxs(e.Fragment,{children:[N.map(j=>{const M=u[j],C=Aw(M),I=M?.status==="connected",E=y===j,P=Dw(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:[c?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":P}):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":P})}),e.jsx(it,{side:"left",children:e.jsx("p",{children:P})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:j})]})}),e.jsx(uo,{checked:I,disabled:E,className:"data-[state=checked]:bg-status-info",onCheckedChange:async D=>{v(j);try{D?await f(j,d):await p(j,d)}finally{v(null)}}})]},j)}),N.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."})]}),A=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:F(t,"relative"),onClick:c?()=>s(!0):void 0,children:[e.jsx(Mw,{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 c?e.jsxs(e.Fragment,{children:[A,e.jsxs($s,{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(zr,{className:F("h-4 w-4",g&&"animate-spin")})}),j]})]}),children:[e.jsx("div",{className:"py-1",children:k()}),d&&e.jsx("div",{className:"px-2 py-1 border-t border-border/40 mt-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]}):e.jsxs(es,{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(ts,{asChild:!0,children:A})}),e.jsx(it,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(ss,{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(zr,{className:F("h-4 w-4",g&&"animate-spin")})})]}),e.jsx(Ds,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:k()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),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})})]})]})]})},dd=()=>{const t=Te(_=>_.setSessionSwitcherOpen),r=Te(_=>_.toggleSidebar),s=Te(_=>_.setSettingsDialogOpen),n=Te(_=>_.toggleCommandPalette),o=Te(_=>_.toggleHelpDialog),a=Te(_=>_.activeMainTab),c=Te(_=>_.setActiveMainTab),{getCurrentModel:l}=at(),d=fe(_=>_.getContextUsage),{isMobile:u}=Qt(),m=kw(),f=Wa(_=>_.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||""),[]);Pe.useEffect(()=>{if(typeof window>"u")return;const _=typeof window.opencodeDesktop<"u";x(_)},[]);const w=l(),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,N=d(v,S),b=Te(_=>_.isSessionSwitcherOpen),k=i.useCallback(()=>{if(typeof document>"u")return;const _=document.activeElement;if(!_)return;const Y=_.tagName;(Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||_.isContentEditable)&&_.blur()},[]),A=i.useCallback(()=>{if(u){k(),t(!b);return}r()},[k,u,b,t,r]),j=i.useCallback(()=>{u&&k(),t(!1),s(!0)},[k,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]),I=i.useCallback(()=>{if(typeof document>"u")return;const _=p.current?.getBoundingClientRect().height;_&&document.documentElement.style.setProperty("--oc-header-height",`${_}px`)},[]);Pe.useEffect(()=>{if(typeof window>"u")return;I();const _=p.current;if(!_||typeof ResizeObserver>"u")return()=>{};const Y=new ResizeObserver(()=>{I()});return Y.observe(_),window.addEventListener("resize",I),window.addEventListener("orientationchange",I),()=>{Y.disconnect(),window.removeEventListener("resize",I),window.removeEventListener("orientationchange",I)}},[I]),Pe.useEffect(()=>{I()},[I,u]);const E=i.useCallback(async _=>{if(!_.target.closest("button, a, input, select, textarea")&&_.button===0&&h)try{const{getCurrentWindow:Y}=await bs(async()=>{const{getCurrentWindow:U}=await import("./vendor-.bun-BrcdMJ39.js").then(Q=>Q.dd);return{getCurrentWindow:U}},__vite__mapDeps([0,1]));await Y().startDragging()}catch(Y){console.error("Failed to start window dragging:",Y)}},[h]),P=i.useCallback(async _=>{if(_.button===0&&h)try{const{getCurrentWindow:Y}=await bs(async()=>{const{getCurrentWindow:U}=await import("./vendor-.bun-BrcdMJ39.js").then(Q=>Q.dd);return{getCurrentWindow:U}},__vite__mapDeps([0,1]));await Y().startDragging()}catch(Y){console.error("Failed to start window dragging:",Y)}},[h]),D=i.useMemo(()=>[{id:"chat",label:"Chat",icon:ih},{id:"diff",label:"Diff",icon:Ks,badge:!u&&m>0?m:void 0},{id:"files",label:"Files",icon:tr},{id:"terminal",label:"Terminal",icon:Ur},{id:"git",label:"Git",icon:Ht,showDot:u&&m>0}],[m,u]);Pe.useEffect(()=>{const _=Y=>{if(Ts(Y)&&!Y.shiftKey&&!Y.altKey){const K=parseInt(Y.key,10);K>=1&&K<=D.length&&(Y.preventDefault(),c(D[K-1].id))}};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[D,c]);const T=_=>{const Y=a===_.id,K=_.icon,U=_.id==="chat";return e.jsxs("button",{type:"button",onClick:()=>c(_.id),onMouseDown:Y?P:void 0,className:F("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",Y?"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",U&&!u&&"min-w-[100px] justify-center"),"aria-label":_.label,"aria-selected":Y,role:"tab",children:[u?e.jsx(K,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(K,{size:16}),e.jsx("span",{className:"header-tab-label",children:_.label})]}),U&&!u&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(al,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.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)},L=()=>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:A,"aria-label":"Open sessions",className:`${M} mr-2`,children:e.jsx(Cl,{className:"h-5 w-5"})}),e.jsx("div",{className:"flex items-center gap-1 p-1 bg-background/50 rounded-lg",children:D.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(hn,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Command Palette (",Xt(),"+K)"]})})]}),e.jsx(cl,{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(un,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Xt(),"+.)"]})})]})]})]}),V=()=>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(Nl,{className:"h-5 w-5"})}):e.jsx("button",{onClick:A,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(lh,{className:"h-5 w-5"})}),!b&&N&&N.totalTokens>0&&a==="chat"&&e.jsx(al,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.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:D.map(_=>{const Y=a===_.id,K=_.icon;return e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{u&&k(),c(_.id)},"aria-label":_.label,"aria-selected":Y,role:"tab",className:F(M,"relative",Y&&"text-foreground bg-secondary"),children:[e.jsx(K,{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(cl,{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(dn,{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"})})]})]})]}),q=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:q,style:{"--padding-scale":"1"},children:u?V():L()})};function Jl({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 gf({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 xf({className:t,...r}){return e.jsx("div",{"data-slot":"card-title",className:F("leading-none font-semibold",t),...r})}function yf({className:t,...r}){return e.jsx("div",{"data-slot":"card-content",className:F("px-6",t),...r})}class fs 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(Jl,{className:"w-full max-w-md",children:[e.jsx(gf,{className:"text-center",children:e.jsxs(xf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(qi,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(yf,{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(Me,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let $o=0;function xs({...t}){return e.jsx(ch,{"data-slot":"dialog",...t})}function Ew({...t}){return e.jsx(mh,{"data-slot":"dialog-portal",...t})}const bf=Pe.forwardRef(({className:t,...r},s)=>(Pe.useEffect(()=>($o+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{$o=Math.max(0,$o-1),$o===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Ju,{ref:s,"data-slot":"dialog-overlay",className:F("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",t),...r})));bf.displayName=Ju.displayName;function ys({className:t,children:r,showCloseButton:s=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Ew,{"data-slot":"dialog-portal",children:[e.jsx(bf,{className:"rounded-none"}),e.jsxs(dh,{"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(uh,{"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(Zt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function vs({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 zs({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 js({className:t,...r}){return e.jsx(fh,{"data-slot":"dialog-title",className:F("typography-markdown leading-none font-semibold text-foreground",t),...r})}function Ns({className:t,...r}){return e.jsx(ph,{"data-slot":"dialog-description",className:F("text-muted-foreground typography-ui-label",t),...r})}const ud="https://github.com/btriapitsyn/openchamber/releases";async function Iw(){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 Pw(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 dl=({open:t,onOpenChange:r,info:s,downloading:n,downloaded:o,progress:a,error:c,onDownload:l,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Pe.useState(!1),[p,h]=Pe.useState("idle"),[x,g]=Pe.useState(null),w=s?.version?`${ud}/tag/v${s.version}`:ud,y=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",S=s?.updateCommand||"openchamber update";Pe.useEffect(()=>{t||(h("idle"),g(null))},[t]);const N=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},b=Pe.useCallback(async()=>{h("updating"),g(null);const A=await Iw();if(!A.success){h("error"),g(A.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await Pw()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),k=p!=="idle"&&p!=="error";return e.jsx(xs,{open:t,onOpenChange:k?void 0:r,children:e.jsxs(ys,{className:"max-w-md",children:[e.jsx(vs,{children:e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(hh,{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&&k&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Jo,{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&&!k&&e.jsx(gt,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:s.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((A,j)=>/^\d+\.\d+\.\d+$/.test(A.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",A.trim(),`
82
- `]},j):A.replace(/^- /gm,"• ").trim()+`
83
-
84
- `)})}),v&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(gh,{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:N,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(Gt,{className:"h-4 w-4"}):e.jsx(Zu,{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}%`}})})]}),(c||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:c||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(ha,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:l,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(Wr,{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(Jo,{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(Is,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!k&&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(Wr,{className:"h-4 w-4"}),"Update Now"]}),v&&k&&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(Jo,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},md=264,fd=200,pd=500,hd="openchamber:check-for-updates",Tw=({isOpen:t,isMobile:r,children:s})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:c}=Te(),[l,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||md),[f,p]=i.useState(!1),h=Wa(),x=i.useRef(!1),g=h.checkForUpdates,{available:w,downloaded:y,checking:v}=h,[S,N]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");if(i.useEffect(()=>{if(typeof window>"u")return;const A=typeof window.opencodeDesktop<"u";N(A)},[]),i.useEffect(()=>{if(typeof window>"u")return;const A=()=>{typeof window.opencodeDesktop<"u"&&(x.current=!0,g())};return window.addEventListener(hd,A),()=>{window.removeEventListener(hd,A)}},[g]),i.useEffect(()=>{x.current&&(v||(w||y?p(!0):G.success("No updates available",{description:"You are running the latest version."}),x.current=!1))},[w,y,v]),i.useEffect(()=>{if(r||!l)return;const A=M=>{const C=M.clientX-u.current,I=Math.min(pd,Math.max(fd,m.current+C));o(I)},j=()=>{d(!1)};return window.addEventListener("pointermove",A),window.addEventListener("pointerup",j,{once:!0}),()=>{window.removeEventListener("pointermove",A),window.removeEventListener("pointerup",j)}},[r,l,o]),i.useEffect(()=>{r&&l&&d(!1)},[r,l]),r)return null;const b=t?Math.min(pd,Math.max(fd,n||md)):0,k=A=>{t&&(d(!0),u.current=A.clientX,m.current=b,A.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",l?"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",l&&"bg-primary"),onPointerDown:k,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(fs,{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(dn,{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(Wr,{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:()=>c(!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(ps,{className:"h-4 w-4"})})}),e.jsx(it,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(dl,{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 Zl({className:t,...r}){return e.jsx(gn,{"data-slot":"command",className:F("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",t),...r})}function Fw({title:t="Command Palette",description:r="Search for a command to run...",children:s,className:n,showCloseButton:o=!0,...a}){return e.jsxs(xs,{...a,children:[e.jsxs(vs,{className:"sr-only",children:[e.jsx(js,{children:t}),e.jsx(Ns,{children:r})]}),e.jsx(ys,{className:F("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Zl,{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 ec({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(ir,{className:"size-4 shrink-0 opacity-50"}),e.jsx(gn.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 tc({className:t,children:r,scrollbarClassName:s,disableHorizontal:n,...o}){return e.jsx(gt,{as:gn.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 sc({...t}){return e.jsx(gn.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...t})}function an({className:t,...r}){return e.jsx(gn.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 Aa({className:t,...r}){return e.jsx(gn.Separator,{"data-slot":"command-separator",className:F("bg-border -mx-1 h-px",t),...r})}function gs({className:t,...r}){return e.jsx(gn.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 jr({className:t,...r}){const s=a=>{const c=a.trim().toLowerCase();return c==="ctrl"||c==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):c==="cmd"||c==="⌘"||c==="command"||c==="meta"?e.jsx(hn,{className:"size-3.5"}):c==="shift"||c==="⇧"?e.jsx(jo,{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,c)=>e.jsxs(Pe.Fragment,{children:[c>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),s(a)]},`${a}-${c}`)):r.children})}const gd=["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"],xd=["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 Rw(){const t=gd[Math.floor(Math.random()*gd.length)],r=xd[Math.floor(Math.random()*xd.length)];return`${t}-${r}`}function yd(t){const r=Rw();return t&&t.trim()?`${t.trim().replace(/\/+$/,"")}/${r}`:r}async function Lw(t,r,s=10){let n;try{const o=await Ga(t);n=new Set(o?.all??[])}catch{return yd(r)}for(let o=0;o<s;o++){const a=yd(r);if(!n.has(a))return a}return null}const wf=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Tn=!1;async function Ya(){if(Tn)return null;const t=Vt.getState().getActiveProject();if(!t?.path)return G.error("No active project",{description:"Please select a project first."}),null;const r=t.path;let s=!1;try{s=await Qr(r)}catch{}if(!s)return G.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Tn=!0,qs("Creating new worktree session...");try{const n=t.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,c=await Lw(r,o);if(!c)return G.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const l=wf(c),u=await $l({projectDirectory:r,worktreeSlug:l,branch:c,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await qa(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=fe.getState(),h=await p.createSession(void 0,u.path);if(!h)return await Qm({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),G.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const x=at.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 N=v.find(b=>b.name===x.settingsDefaultAgent);N&&(S=N.name)}if(S||(S=v.find(N=>N.name==="build")?.name||v[0]?.name),S){x.setAgent(S),ht.getState().saveSessionAgentSelection(h.id,S);const N=x.settingsDefaultModel;if(N){const b=N.split("/");if(b.length===2){const[k,A]=b;if(x.getModelMetadata(k,A)){ht.getState().saveSessionModelSelection(h.id,k,A),ht.getState().saveAgentModelForSession(h.id,S,k,A);const M=x.settingsDefaultVariant;if(M){const E=x.providers.find(P=>P.id===k)?.models.find(P=>P.id===A)?.variants;E&&Object.prototype.hasOwnProperty.call(E,M)&&(x.setCurrentVariant(M),ht.getState().saveAgentModelVariantForSession(h.id,S,k,A,M))}}}}}}catch{}bt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const y=(await Kn(r)).filter(v=>v.trim().length>0);return y.length>0?(G.success("Worktree created",{description:`Branch: ${c}. Running ${y.length} setup command${y.length===1?"":"s"}...`}),Bl(u.path,r,y).then(v=>{if(v.success)G.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),N=v.results.filter(b=>b.success);G.error("Setup commands failed",{description:`${S.length} of ${v.results.length} command${v.results.length===1?"":"s"} failed.`+(N.length>0?` ${N.length} succeeded.`:"")})}}).catch(()=>{G.error("Setup commands failed",{description:"Could not execute setup commands."})})):G.success("Worktree created",{description:`Branch: ${c}`}),h}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return G.error("Failed to create worktree",{description:o}),null}finally{Fs(),Tn=!1}}async function Ow(t,r){if(Tn)return null;let s=!1;try{s=await Qr(t)}catch{}if(!s)return G.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Tn=!0,qs("Creating worktree session...");try{const n=wf(r),o=await $l({projectDirectory:t,worktreeSlug:n,branch:r,createBranch:!1}),a=await qa(o.path).catch(()=>{}),c=a?{...o,status:a}:o,l=fe.getState(),d=await l.createSession(void 0,o.path);if(!d)return await Qm({projectDirectory:t,path:o.path,force:!0}).catch(()=>{}),G.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const u=at.getState(),m=u.agents;l.initializeNewOpenChamberSession(d.id,m),l.setSessionDirectory(d.id,o.path),l.setWorktreeMetadata(d.id,c);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),ht.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)){ht.getState().saveSessionModelSelection(d.id,y,v),ht.getState().saveAgentModelForSession(d.id,x,y,v);const N=u.settingsDefaultVariant;if(N){const A=u.providers.find(j=>j.id===y)?.models.find(j=>j.id===v)?.variants;A&&Object.prototype.hasOwnProperty.call(A,N)&&(u.setCurrentVariant(N),ht.getState().saveAgentModelVariantForSession(d.id,x,y,v,N))}}}}}}catch{}bt.getState().setDirectory(o.path,{showOverlay:!1});try{await l.loadSessions()}catch{}const p=(await Kn(t)).filter(h=>h.trim().length>0);return p.length>0?(G.success("Worktree created",{description:`Branch: ${r}. Running ${p.length} setup command${p.length===1?"":"s"}...`}),Bl(o.path,t,p).then(h=>{if(h.success)G.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);G.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(()=>{G.error("Setup commands failed",{description:"Could not execute setup commands."})})):G.success("Worktree created",{description:`Branch: ${r}`}),d}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return G.error("Failed to create worktree",{description:o}),null}finally{Fs(),Tn=!1}}const _w=()=>{const{isCommandPaletteOpen:t,setCommandPaletteOpen:r,setHelpDialogOpen:s,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:c,toggleSidebar:l}=Te(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=fe(),f=at(T=>T.settingsAutoCreateWorktree),{currentDirectory:p}=bt(),{themeMode:h,setThemeMode:x}=Yr(),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()},N=()=>{g(),Ya()},{isMobile:b}=Qt(),k=()=>{if(b){const{isSessionSwitcherOpen:T}=Te.getState();a(!T)}else l();g()},A=()=>{n("diff"),g()},j=()=>{n("git"),g()},M=()=>{n("terminal"),g()},C=()=>{o(!0),g()},I=()=>{io(),g()},E=()=>{c(!0),g()},P=m(p??""),D=i.useMemo(()=>P.slice(0,5),[P]);return e.jsxs(Fw,{open:t,onOpenChange:r,children:[e.jsx(ec,{placeholder:"Type a command or search..."}),e.jsxs(tc,{children:[e.jsx(sc,{children:"No results found."}),e.jsxs(an,{heading:"Actions",children:[e.jsxs(gs,{onSelect:k,children:[e.jsx(Cl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(jr,{children:[Xt()," + L"]})]}),e.jsxs(gs,{onSelect:w,children:[e.jsx(is,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(jr,{children:f?`Shift + ${Xt()} + N`:`${Xt()} + N`})]}),e.jsxs(gs,{onSelect:N,children:[e.jsx(Ht,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(jr,{children:f?`${Xt()} + N`:`Shift + ${Xt()} + N`})]}),e.jsxs(gs,{onSelect:S,children:[e.jsx(un,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(jr,{children:[Xt()," + ."]})]}),e.jsxs(gs,{onSelect:A,children:[e.jsx(Ks,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(jr,{children:[Xt()," + 2"]})]}),e.jsxs(gs,{onSelect:M,children:[e.jsx(Ur,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(jr,{children:[Xt()," + 3"]})]}),e.jsxs(gs,{onSelect:j,children:[e.jsx(Ht,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(jr,{children:[Xt()," + 4"]})]}),e.jsxs(gs,{onSelect:E,children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(jr,{children:[Xt()," + T"]})]}),e.jsxs(gs,{onSelect:C,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(jr,{children:[Xt()," + ,"]})]}),e.jsxs(gs,{onSelect:I,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Aa,{}),e.jsxs(an,{heading:"Theme",children:[e.jsxs(gs,{onSelect:()=>v("light"),children:[e.jsx(xh,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Gt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(gs,{onSelect:()=>v("dark"),children:[e.jsx(yh,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Gt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(gs,{onSelect:()=>v("system"),children:[e.jsx(em,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Gt,{className:"ml-auto h-4 w-4"})]})]}),D.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Aa,{}),e.jsx(an,{heading:"Recent Sessions",children:D.map(T=>e.jsxs(gs,{onSelect:()=>y(T.id),children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:T.title||"Untitled Session"})]},T.id))})]})]})]})},$w=(t,r)=>{const s=t.trim().toLowerCase();return s==="ctrl"||s==="control"?e.jsx(Oa,{className:"h-3.5 w-3.5"},`ctrl-${r}`):s==="⌘"||s==="cmd"||s==="command"||s==="meta"?e.jsx(hn,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:t.trim()},`key-${r}`)},Bw=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:"+"}),$w(s,n)]},`${s}-${n}`))},zw=()=>{const{isHelpDialogOpen:t,setHelpDialogOpen:r}=Te(),s=at(a=>a.settingsAutoCreateWorktree),n=Xt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:hn},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:un},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:Cl},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:mn},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:tm},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:br}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:s?"Create New Session in Worktree":"Create New Session",icon:s?Ht:is},{keys:[`Shift + ${n} + N`],description:s?"Create New Session":"Create New Session in Worktree",icon:s?is:Ht},{keys:[`${n} + I`],description:"Focus Chat Input",icon:sm},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Rn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:bh},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:Ks},{keys:[`${n} + 3`],description:"Open Files",icon:tr},{keys:[`${n} + 4`],description:"Open Terminal",icon:Ur},{keys:[`${n} + 5`],description:"Open Git Panel",icon:Ht},{keys:[`${n} + T`],description:"Open Timeline",icon:yr},{keys:[`${n} + ,`],description:"Open Settings",icon:dn}]}];return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(vs,{children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ns,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((c,l)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c.icon&&e.jsx(c.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:c.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(c.keys)?c.keys:c.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:Bw(d)})]},`${d}-${u}`))})]},l))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(un,{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"})]})]})]})})]})]})})},Ww={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"}},vf=({className:t,size:r="md"})=>{const s=Ww[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))})},Si=new Set,ki=new Set,Ni=new Set,zn={onDeleteRequest(t){return Si.add(t),()=>{Si.delete(t)}},requestDelete(t){!t.sessions.length&&t.mode!=="worktree"||Si.forEach(r=>r(t))},onCreateRequest(t){return ki.add(t),()=>{ki.delete(t)}},requestCreate(t){const r=t??{};ki.forEach(s=>s(r))},onDirectoryRequest(t){return Ni.add(t),()=>{Ni.delete(t)}},requestDirectoryDialog(){Ni.forEach(t=>t())}};function jf(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 jt({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 Hw({open:t,onOpenChange:r,projects:s,activeProjectId:n}){const[o,a]=i.useState(""),[c,l]=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=>{l(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([Ga(y.path),Bm(y.path)]);l(N=>{const b=new Map(N);return b.set(y.id,{branches:v,worktrees:S,loading:!1,error:null}),b})}catch(v){l(S=>{const N=new Map(S);return N.set(y.id,{branches:null,worktrees:[],loading:!1,error:v instanceof Error?v.message:"Failed to load"}),N})}})},[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 Ow(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=c.get(w.id);return y&&!y.error&&(y.loading||y.branches)});return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl max-h-[70vh] flex flex-col overflow-hidden gap-3",children:[e.jsxs(vs,{className:"flex-shrink-0",children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(Ht,{className:"h-5 w-5"}),"Branches & Worktrees"]}),e.jsx(Ns,{children:"Start a new worktree session from any local branch"})]}),e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(ir,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{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=c.get(w.id),v=d.has(w.id),S=y?.branches,N=y?.worktrees||[],b=new Set(N.map(M=>M.branch).filter(Boolean)),k=S?.all||[],j=x(k,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(Bs,{className:F("h-4 w-4 text-muted-foreground transition-transform",v&&"rotate-90")}),e.jsx(lr,{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(Jt,{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],I=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(Ht,{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",I&&"font-medium text-primary"),children:M}),I&&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(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(is,{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 bd="oc.sessions.projectCollapse",wd="oc.sessions.expandedParents",vd=t=>{const r=new Date(t),s=new Date,n=(c,l)=>c.getFullYear()===l.getFullYear()&&c.getMonth()===l.getMonth()&&c.getDate()===l.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(",","")},ur=t=>{if(!t)return null;const r=t.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},jd=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),Uw=({id:t,projectLabel:r,projectDescription:s,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:c,isDesktopRuntime:l,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onNewWorktreeSession:x,onOpenBranchPicker:g,onOpenMultiRunLauncher:w,onClose:y,sentinelRef:v,children:S,settingsAutoCreateWorktree:N})=>{const{attributes:b,listeners:k,setNodeRef:A,isDragging:j}=Ih({id:t}),[M,C]=i.useState(!1);return e.jsxs("div",{ref:A,className:F("relative",j&&"opacity-40"),children:[l&&e.jsx("div",{ref:v,"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",!l&&"bg-sidebar"),style:{backgroundColor:l?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:c?"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(),C(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...b,children:[e.jsxs(lt,{delayDuration:1500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...k,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(es,{open:M,onOpenChange:C,children:[e.jsx(ts,{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(Vr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"min-w-[180px]",children:[a&&!u&&N&&h&&e.jsxs(Nt,{onClick:h,children:[e.jsx(is,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),a&&!u&&!N&&x&&e.jsxs(Nt,{onClick:x,children:[e.jsx(Ht,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),a&&!u&&g&&e.jsxs(Nt,{onClick:g,children:[e.jsx(rm,{className:"mr-1.5 h-4 w-4"}),"Browse Branches"]}),a&&!u&&e.jsxs(Nt,{onClick:w,children:[e.jsx(jf,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(Nt,{onClick:y,className:"text-destructive focus:text-destructive",children:[e.jsx(Zt,{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(Ht,{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(is,{className:"h-4 w-4"})})}),e.jsx(it,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})}),S]})},Vw=({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})})}),Ea=({mobileVariant:t=!1,onSessionSelected:r,allowReselect:s=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,c]=i.useState(null),[l,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(()=>hs(),[]),[v,S]=i.useState(new Set),[N,b]=i.useState(new Map),[k,A]=i.useState(new Set),[j,M]=i.useState(null),[C,I]=i.useState(!1),[E,P]=i.useState(null),[D,T]=i.useState(new Set),[L,V]=i.useState(null),q=i.useRef(new Map),_=i.useRef(0),Y=bt($=>$.homeDirectory),K=bt($=>$.currentDirectory),U=bt($=>$.setDirectory),Q=Vt($=>$.projects),z=Vt($=>$.activeProjectId),re=Vt($=>$.addProject),te=Vt($=>$.removeProject),pe=Vt($=>$.setActiveProject),R=Vt($=>$.setActiveProjectIdOnly),ee=Vt($=>$.reorderProjects),B=Te($=>$.setActiveMainTab),W=Te($=>$.setSessionSwitcherOpen),X=Te($=>$.openMultiRunLauncher),ie=at($=>$.settingsAutoCreateWorktree),be=fe($=>$.sessions),H=fe($=>$.sessionsByDirectory),me=fe($=>$.currentSessionId),we=fe($=>$.setCurrentSession),he=fe($=>$.updateSessionTitle),_e=fe($=>$.shareSession),se=fe($=>$.unshareSession),J=fe($=>$.sessionMemoryState),ne=fe($=>$.sessionActivityPhase),ke=fe($=>$.permissions),Z=fe($=>$.worktreeMetadata),xe=fe($=>$.availableWorktreesByProject),de=fe($=>$.getSessionsByDirectory),je=fe($=>$.openNewSessionDraft),[ae,Xe]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),mt=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{try{const $=y.getItem(wd);if($){const ve=JSON.parse($);Array.isArray(ve)&&h(new Set(ve.filter(Be=>typeof Be=="string")))}const ue=y.getItem(bd);if(ue){const ve=JSON.parse(ue);Array.isArray(ve)&&S(new Set(ve.filter(Be=>typeof Be=="string")))}}catch{}},[y]),i.useEffect(()=>{typeof window>"u"||Xe(typeof window.opencodeDesktop<"u")},[]);const De=i.useMemo(()=>[...be].sort(($,ue)=>(ue.time?.updated||0)-($.time?.updated||0)),[be]);i.useEffect(()=>{let $=!1;const ue=Q.map(ve=>({id:ve.id,path:ur(ve.path)})).filter(ve=>!!ve.path);return b(new Map),ue.length===0?()=>{$=!0}:(ue.forEach(ve=>{Qr(ve.path).then(Be=>{$||b(ze=>{const tt=new Map(ze);return tt.set(ve.id,Be),tt})}).catch(()=>{$||b(Be=>{const ze=new Map(Be);return ze.set(ve.id,null),ze})})}),()=>{$=!0})},[Q]);const oe=i.useMemo(()=>{const $=new Map;return De.forEach(ue=>{const ve=ue.parentID;ve&&$.set(ue.id,ve)}),$},[De]),Ue=i.useMemo(()=>{const $=new Map;return De.forEach(ue=>{const ve=ue.parentID;if(!ve)return;const Be=$.get(ve)??[];Be.push(ue),$.set(ve,Be)}),$.forEach(ue=>ue.sort((ve,Be)=>(Be.time?.updated||0)-(ve.time?.updated||0))),$},[De]);i.useEffect(()=>{me&&h($=>{const ue=new Set($);let ve=oe.get(me)||null,Be=!1;for(;ve;)ue.has(ve)||(ue.add(ve),Be=!0),ve=oe.get(ve)||null;return Be?ue:$})},[me,oe]),i.useEffect(()=>{const $=new Set;De.forEach(ue=>{const ve=ur(ue.directory??null);ve&&$.add(ve)}),Q.forEach(ue=>{const ve=ur(ue.path);ve&&$.add(ve)}),$.forEach(ue=>{const ve=x.get(ue);ve&&ve!=="unknown"||w.current.has(ue)||(w.current.add(ue),Fe.listLocalDirectory(ue).then(()=>{g(Be=>{const ze=new Map(Be);return ze.get(ue)==="exists"?Be:(ze.set(ue,"exists"),ze)})}).catch(()=>{g(Be=>{const ze=new Map(Be);return ze.get(ue)==="missing"?Be:(ze.set(ue,"missing"),ze)})}).finally(()=>{w.current.delete(ue)}))})},[De,Q,x]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const Se=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."})]}),Ne=i.useCallback(($,ue,ve,Be)=>{if(!ve){if(Be&&Be!==z&&R(Be),ue&&ue!==K&&U(ue,{showOverlay:!1}),t&&(B("chat"),W(!1)),!s&&$===me){r?.($);return}we($),r?.($)}},[z,s,K,me,t,r,B,R,we,U,W]),Ge=i.useCallback(async()=>{a&&l.trim()&&(await he(a,l.trim()),c(null),d(""))},[a,l,he]),rt=i.useCallback(()=>{c(null),d("")},[]),Ke=i.useCallback(async $=>{const ue=await _e($.id);ue&&ue.share?.url?G.success("Session shared",{description:"You can copy the link from the menu."}):G.error("Unable to share session")},[_e]),Le=i.useCallback(($,ue)=>{navigator.clipboard.writeText($).then(()=>{m(ue),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{G.error("Failed to copy URL")})},[]),Ye=i.useCallback(async $=>{await se($)?G.success("Session unshared"):G.error("Unable to unshare session")},[se]),xt=i.useCallback($=>{const ue=[],ve=Be=>{(Ue.get(Be)??[]).forEach(tt=>{ue.push(tt),ve(tt.id)})};return ve($),ue},[Ue]),nt=fe($=>$.deleteSession),It=fe($=>$.deleteSessions),Pt=i.useCallback(async $=>{const ue=xt($.id),ve=Z.get($.id);if(ve){const Be=ve.path,ze=[],tt=new Set;be.forEach(Ce=>{const qe=Z.get(Ce.id);qe&&qe.path===Be&&!tt.has(Ce.id)&&(ze.push(Ce),tt.add(Ce.id),xt(Ce.id).forEach(ot=>{tt.has(ot.id)||(ze.push(ot),tt.add(ot.id))}))}),zn.requestDelete({sessions:ze,mode:"worktree",worktree:ve});return}if(ue.length===0)await nt($.id)?G.success("Session deleted",{action:{label:"OK",onClick:()=>{}}}):G.error("Failed to delete session");else{const Be=[$.id,...ue.map(Ce=>Ce.id)],{deletedIds:ze,failedIds:tt}=await It(Be);ze.length>0&&G.success(`Deleted ${ze.length} session${ze.length===1?"":"s"}`,{action:{label:"OK",onClick:()=>{}}}),tt.length>0&&G.error(`Failed to delete ${tt.length} session${tt.length===1?"":"s"}`)}},[xt,nt,It,Z,be]),zt=i.useCallback(()=>{ae&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then($=>{$.success&&$.path?re($.path,{id:$.projectId})||G.error("Failed to add project",{description:"Please select a valid directory."}):$.error&&$.error!=="Directory selection cancelled"&&G.error("Failed to select directory",{description:$.error})}).catch($=>{console.error("Desktop: Error selecting directory:",$),G.error("Failed to select directory")}):zn.requestDirectoryDialog()},[re,ae]),We=i.useCallback($=>{h(ue=>{const ve=new Set(ue);ve.has($)?ve.delete($):ve.add($);try{y.setItem(wd,JSON.stringify(Array.from(ve)))}catch{}return ve})},[y]),ut=i.useCallback($=>{const ue=Ue.get($.id)??[];return{session:$,children:ue.map(ve=>ut(ve)),worktree:Z.get($.id)??null}},[Ue,Z]),vt=i.useCallback(($,ue,ve)=>{const Be=ur(ue??null),ze=[...$].sort((wt,ge)=>(ge.time?.updated||0)-(wt.time?.updated||0)),tt=new Map(ze.map(wt=>[wt.id,wt])),Ce=new Map;ze.forEach(wt=>{const ge=wt.parentID;if(!ge)return;const Ee=Ce.get(ge)??[];Ee.push(wt),Ce.set(ge,Ee)}),Ce.forEach(wt=>wt.sort((ge,Ee)=>(Ee.time?.updated||0)-(ge.time?.updated||0)));const qe=new Map;ve.forEach(wt=>{if(wt.path){const ge=ur(wt.path)??wt.path;qe.set(ge,wt)}});const et=wt=>{const ge=ur(wt.directory??null),Ee=Z.get(wt.id)??null;if(Ee)return Ee;if(ge){const st=qe.get(ge)??null;if(st&&ge!==Be)return st}return null},ot=wt=>{const ge=Ce.get(wt.id)??[];return{session:wt,children:ge.map(Ee=>ot(Ee)),worktree:et(wt)}},$t=ze.filter(wt=>{const ge=wt.parentID;return ge?!tt.has(ge):!0}).map(wt=>ot(wt));return[{id:"all",label:"All sessions",description:Be?nn(Be,Y):null,isMain:!0,worktree:null,directory:Be,sessions:$t}]},[Y,Z]),dt=i.useCallback($=>{A(ue=>{const ve=new Set(ue);return ve.has($)?ve.delete($):ve.add($),ve})},[]),Tt=i.useCallback($=>{_.current=Date.now()+150,S(ue=>{const ve=new Set(ue);ve.has($)?ve.delete($):ve.add($);try{y.setItem(bd,JSON.stringify(Array.from(ve)))}catch{}return ve})},[y]),Ct=i.useMemo(()=>Q.map($=>({...$,normalizedPath:ur($.path)})).filter($=>!!$.normalizedPath),[Q]),os=i.useCallback($=>{const ue=mt?[]:xe.get($.normalizedPath)??[],ve=[$.normalizedPath,...ue.map(tt=>ur(tt.path)??tt.path).filter(tt=>!!tt)],Be=new Set,ze=[];return ve.forEach(tt=>{(H.get(tt)??de(tt)).forEach(qe=>{Be.has(qe.id)||(Be.add(qe.id),ze.push(qe))})}),ze},[xe,de,H,mt]),St=i.useMemo(()=>Ct.map($=>{const ue=os($),ve=xe.get($.normalizedPath)??[],Be=vt(ue,$.normalizedPath,ve);return{project:$,groups:Be}}),[Ct,os,vt,xe]);i.useEffect(()=>{if(!ae)return;const $=new IntersectionObserver(ue=>{ue.forEach(ve=>{const Be=ve.target.dataset.projectId;Be&&T(ze=>{const tt=new Set(ze);return ve.isIntersecting?tt.delete(Be):tt.add(Be),tt})})},{threshold:0});return q.current.forEach(ue=>{ue&&$.observe(ue)}),()=>$.disconnect()},[ae,St]);const Lt=i.useCallback(($,ue=0,ve,Be)=>{const ze=$.session,tt=ur(ze.directory??null)??ur(ve??null),qe=(tt?x.get(tt):null)==="missing",et=J.get(ze.id),ot=me===ze.id,_t=ze.title||"Untitled Session",$t=$.children.length>0,wt=p.has(ze.id),ge=ze.summary?.additions,Ee=ze.summary?.deletions,st=typeof ge=="number"||typeof Ee=="number";if(a===ze.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",ue>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:pt=>{pt.preventDefault(),Ge()},children:[e.jsx("input",{value:l,onChange:pt=>d(pt.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:pt=>{pt.key==="Escape"&&rt()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Gt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:rt,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Zt,{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:[$t?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:wt?e.jsx(Ot,{className:"h-3 w-3"}):e.jsx(Bs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:vd(ze.time?.created||Date.now())}),ze.share?e.jsx(oi,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,st&&((ge??0)!==0||(Ee??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,ge??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ee??0)]})]}):null,$t?e.jsxs("span",{className:"truncate",children:[$.children.length," ",$.children.length===1?"task":"tasks"]}):null]})]})},ze.id);const $e=ne?.get(ze.id)??"idle",kt=$e==="busy"||$e==="cooldown",Mt=ke.get(ze.id)?.length??0,Kt=et&&et.isZombie?e.jsx(qi,{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",ot?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",qe?"opacity-75":"",ue>0&&"pl-[20px]"),onContextMenu:pt=>{pt.preventDefault(),V(ze.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:qe,onClick:()=>Ne(ze.id,tt,qe,Be),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:[kt?e.jsx(vf,{size:"xs",className:"text-primary flex-shrink-0"}):null,e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:_t}),Mt>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(wh,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:Mt})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[$t?e.jsx("span",{role:"button",tabIndex:0,onClick:pt=>{pt.stopPropagation(),We(ze.id)},onKeyDown:pt=>{(pt.key==="Enter"||pt.key===" ")&&(pt.preventDefault(),pt.stopPropagation(),We(ze.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":wt?"Collapse subsessions":"Expand subsessions",children:wt?e.jsx(Ot,{className:"h-3 w-3"}):e.jsx(Bs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:vd(ze.time?.created||Date.now())}),ze.share?e.jsx(oi,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,$.worktree?e.jsxs(lt,{delayDuration:700,children:[e.jsx(ct,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Ht,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(it,{side:"top",className:"text-xs",children:$.worktree.branch||$.worktree.label||"Worktree"})]}):null,st&&((ge??0)!==0||(Ee??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,ge??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ee??0)]})]}):null,$t?e.jsxs("span",{className:"truncate",children:[$.children.length," ",$.children.length===1?"task":"tasks"]}):null,qe?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(qi,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Kt,e.jsxs(es,{open:L===ze.id,onOpenChange:pt=>V(pt?ze.id:null),children:[e.jsx(ts,{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:pt=>pt.stopPropagation(),onKeyDown:pt=>pt.stopPropagation(),children:e.jsx(Vr,{className:t?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"min-w-[180px]",children:[e.jsxs(Nt,{onClick:()=>{c(ze.id),d(_t)},className:"[&>svg]:mr-1",children:[e.jsx(kr,{className:"mr-1 h-4 w-4"}),"Rename"]}),ze.share?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{onClick:()=>{ze.share?.url&&Le(ze.share.url,ze.id)},className:"[&>svg]:mr-1",children:u===ze.id?e.jsxs(e.Fragment,{children:[e.jsx(Gt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(Nt,{onClick:()=>Ye(ze.id),className:"[&>svg]:mr-1",children:[e.jsx(vh,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(Nt,{onClick:()=>Ke(ze),className:"[&>svg]:mr-1",children:[e.jsx(oi,{className:"mr-1 h-4 w-4"}),"Share"]}),$.worktree?e.jsxs(Nt,{onClick:()=>{Be&&Be!==z&&pe(Be),B("chat"),t&&W(!1),je({directoryOverride:$.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(Ht,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(Nt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Pt(ze),children:[e.jsx(Us,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),$t&&wt?$.children.map(pt=>Lt(pt,ue+1,tt??ve,Be)):null]},ze.id)},[x,J,ne,ke,me,p,a,l,Ge,rt,We,Ne,Ke,Le,Ye,Pt,u,t,z,pe,B,W,je,L]),Ft=i.useCallback(($,ue,ve)=>{const Be=k.has(ue),ze=n?10:5,tt=$.sessions.length,Ce=Be?$.sessions:$.sessions.slice(0,ze),qe=tt-Ce.length;return e.jsxs(e.Fragment,{children:[Ce.map(et=>Lt(et,0,$.directory,ve)),tt===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,qe>0&&!Be?e.jsxs("button",{type:"button",onClick:()=>dt(ue),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 ",qe," more ",qe===1?"session":"sessions"]}):null,Be&&tt>ze?e.jsx("button",{type:"button",onClick:()=>dt(ue),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})},[k,n,Lt,dt]),Ut=jh(bc(Eh,{activationConstraint:{distance:8}}),bc(Ah,{coordinateGetter:Dh})),Rt=i.useCallback($=>{P($.active.id)},[]),qt=i.useCallback($=>{const{active:ue,over:ve}=$;if(P(null),!ve||ue.id===ve.id)return;const Be=Ct.findIndex(tt=>tt.id===ue.id),ze=Ct.findIndex(tt=>tt.id===ve.id);Be!==-1&&ze!==-1&&ee(Be,ze)},[Ct,ee]),ye=i.useCallback(()=>{P(null)},[]),Ae=i.useMemo(()=>{if(!E)return null;const $=St.find(ve=>ve.project.id===E);if(!$)return null;const ue=$.project;return{id:ue.id,label:jd(ue.label?.trim()||kc(ue.normalizedPath,Y)||ue.normalizedPath),isActive:ue.id===z}},[E,St,Y,z]);return e.jsxs("div",{className:F("flex h-full flex-col text-foreground overflow-x-hidden",t?"":ae?"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:Q.length})]}),e.jsx("button",{type:"button",onClick:zt,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",!ae&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Ki,{className:"h-4.5 w-4.5"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:F("space-y-1 pb-1 pl-2.5 pr-1",""),children:St.length===0?Se:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const $=St.find(Be=>Be.project.id===z)??St[0];if(!$)return Se;const ue=$.groups.find(Be=>Be.isMain&&Be.sessions.length>0)??$.groups.find(Be=>Be.sessions.length>0)??$.groups.find(Be=>Be.isMain)??$.groups[0];if(!ue)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const ve=`${$.project.id}:${ue.id}`;return Ft(ue,ve,$.project.id)})()}):e.jsxs(Sh,{sensors:Ut,collisionDetection:kh,onDragStart:Rt,onDragEnd:qt,onDragCancel:ye,children:[e.jsx(Nh,{items:Ct.map($=>$.id),strategy:Ch,children:St.map($=>{const ue=$.project,ve=ue.id,Be=jd(ue.label?.trim()||kc(ue.normalizedPath,Y)||ue.normalizedPath),ze=nn(ue.normalizedPath,Y),tt=v.has(ve),Ce=ve===z,qe=N.get(ve),et=j===ve;return e.jsx(Uw,{id:ve,projectLabel:Be,projectDescription:ze,isCollapsed:tt,isActiveProject:Ce,isRepo:!!qe,isHovered:et,isDesktopRuntime:ae,isStuck:D.has(ve),hideDirectoryControls:n,mobileVariant:t,onToggle:()=>Tt(ve),onHoverChange:ot=>M(ot?ve:null),onNewSession:()=>{ve!==z&&pe(ve),B("chat"),t&&W(!1),je({directoryOverride:ue.normalizedPath})},onNewWorktreeSession:()=>{ve!==z&&pe(ve),B("chat"),t&&W(!1),Ya()},onOpenBranchPicker:()=>I(!0),onOpenMultiRunLauncher:()=>{ve!==z&&pe(ve),X()},onClose:()=>te(ve),sentinelRef:ot=>{q.current.set(ve,ot)},settingsAutoCreateWorktree:ie,children:tt?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:$.groups[0]?Ft($.groups[0],`${ve}:all`,ve):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},ve)})}),e.jsx(Mh,{children:Ae?e.jsx(Vw,{projectLabel:Ae.label,isActiveProject:Ae.isActive}):null})]})}),e.jsx(Hw,{open:C,onOpenChange:I,projects:Ct,activeProjectId:z})]})},Xa=()=>{const[t,r]=Pe.useState(!1);Pe.useEffect(()=>{r(ls())},[]);const s=Pe.useCallback(async a=>t?await jx(a):{success:!0,path:a},[t]),n=Pe.useCallback(async a=>t?await Sx(a):{success:!0},[t]),o=Pe.useCallback(async a=>t?await kx(a):{success:!0},[t]);return{isDesktop:t,requestAccess:s,startAccessing:n,stopAccessing:o}},Sd=({currentPath:t,onSelectPath:r,triggerClassName:s,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:c,showHidden:l=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=i.useMemo(()=>ls(),[]),{isMobile:p}=Qt(),[h,x]=i.useState([]),[g,w]=i.useState(new Set),[y,v]=i.useState(!0),[S,N]=i.useState(!1),[b,k]=i.useState(""),[A,j]=i.useState(new Set),[M,C]=i.useState(null),[I,E]=i.useState(""),[P,D]=i.useState(!0),T=i.useRef(null),{requestAccess:L,startAccessing:V,isDesktop:q}=Xa(),_=i.useRef(l),Y=i.useCallback(se=>{if(!se)return se;if(se==="/"||se.length===0)return"/";let J=se;for(;J.length>1&&J.endsWith("/");)J=J.slice(0,-1);return J.length===0?"/":J},[]),K=i.useMemo(()=>{if(!b)return null;const se=b.replace(/\\/g,"/");return Y(se)},[b,Y]),U=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const se=d.replace(/\\/g,"/"),J=Y(se);if(J&&J!=="/")return J}return K&&K!=="/"?K:null},[d,K,Y]),Q=i.useMemo(()=>typeof u=="boolean"?!!(u&&U):!!U,[u,U]);i.useEffect(()=>{Q||(v(!0),x([]))},[Q]);const z=i.useCallback(se=>{if(!se||!Q||!U)return!1;const J=se.replace(/\\/g,"/"),ne=Y(J)??J;if(ne===U)return!0;const ke=`${U}/`;return ne.startsWith(ke)},[Q,U,Y]),re=async se=>{if(Q){if(a==="deferred"){r(se);return}if(q){const J=await L(se);J.success&&J.path?(await V(J.path),r(J.path)):(console.error("Failed to get directory access:",J.error),r(se))}else r(se)}};i.useEffect(()=>{let se=!1;const J=Z=>{if(!Z)return!1;const xe=Y(Z.replace(/\\/g,"/"));return!xe||xe==="/"?!1:(k(typeof xe=="string"?xe:Z.replace(/\\/g,"/")),!0)};return d&&J(d)||(async()=>{try{const Z=await Fe.getFilesystemHome();if(!se&&J(Z))return}catch(Z){console.warn("Failed to resolve filesystem home directory:",Z)}try{const Z=await Fe.getSystemInfo();if(!se&&J(Z?.homeDirectory))return}catch(Z){console.warn("Failed to resolve home directory from system info:",Z)}})(),()=>{se=!0}},[d,Y]),i.useEffect(()=>{let se=!1;const J=xe=>{if(se)return;const de=xe.filter(je=>typeof je=="string"&&je.length>0).map(je=>{const ae=je.replace(/\\/g,"/");return Y(ae)??ae});j(new Set(de))},ne=()=>{try{const xe=localStorage.getItem("pinnedDirectories");if(!xe)return;const de=JSON.parse(xe);Array.isArray(de)&&J(de)}catch(xe){console.warn("Failed to load pinned directories from local storage:",xe)}},ke=async()=>{try{let xe=[];if(f){const de=await Ir();xe=Array.isArray(de?.pinnedDirectories)?de.pinnedDirectories:[]}else{const de=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(de.ok){const je=await de.json();xe=Array.isArray(je?.pinnedDirectories)?je.pinnedDirectories:[]}}if(se)return;J(xe)}catch(xe){console.warn("Failed to load pinned directories:",xe)}};ne();const Z=xe=>{const de=xe.detail;de&&Array.isArray(de.pinnedDirectories)&&J(de.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",Z),ke(),()=>{se=!0,window.removeEventListener("openchamber:settings-synced",Z)}},[f,Y]);const te=i.useRef(!0);i.useEffect(()=>{if(te.current){te.current=!1;return}const se={pinnedDirectories:Array.from(A)};us(se)},[A]),i.useEffect(()=>{U&&j(se=>{const J=Array.from(se).map(ne=>Y(ne.replace(/\\/g,"/"))??ne).filter(ne=>z(ne));return new Set(J)})},[U,z,Y]),i.useEffect(()=>{_.current!==l&&(_.current=l)},[l]);const pe=se=>{j(J=>{if(!z(se))return J;const ne=Y(se.replace(/\\/g,"/"))??se.replace(/\\/g,"/"),ke=new Set(J);return ke.has(ne)?ke.delete(ne):ke.add(ne),ke})},R=i.useMemo(()=>Array.from(A).map(se=>Y(se.replace(/\\/g,"/"))??se).filter(se=>z(se)).map(se=>({path:se,name:se.split("/").pop()||se})).sort((se,J)=>se.name.localeCompare(J.name)),[A,z,Y]),ee=i.useCallback(async se=>{const J=de=>l||!de.startsWith("."),ne=U;if(!Q||!ne)return[];const ke=se&&se.length>0?se:ne,Z=ke?ke.replace(/\\/g,"/"):null,xe=Z?Y(Z)??Z:null;if(xe){const de=`${ne}/`;if(!(xe===ne||xe.startsWith(de)))return[]}try{return(await Fe.listLocalDirectory(se)).filter(je=>{if(!je.isDirectory||!J(je.name))return!1;const ae=je.path.replace(/\\/g,"/"),Xe=Y(ae)??ae,mt=Xe===ne?ne:`${ne}/`;return Xe===ne||Xe.startsWith(mt)}).map(je=>({name:je.name,path:je.path.replace(/\\/g,"/"),isDirectory:!0})).sort((je,ae)=>je.name.localeCompare(ae.name))}catch{try{const je=await Fe.getApiClient().file.list({path:".",directory:se});return je.data?je.data.filter(ae=>{if(ae.type!=="directory"||!ae.name||!J(ae.name))return!1;const Xe=String(ae.absolute||ae.path||ae.name).replace(/\\/g,"/"),mt=Y(Xe)??Xe,De=mt===ne?ne:`${ne}/`;return mt===ne||mt.startsWith(De)}).map(ae=>({name:ae.name||"",path:String(ae.absolute||ae.path||ae.name).replace(/\\/g,"/"),isDirectory:!0})).filter(ae=>ae.name!=="").sort((ae,Xe)=>ae.name.localeCompare(Xe.name)):[]}catch{return[]}}},[l,U,Y,Q]),B=i.useRef(!1),W=i.useCallback(async()=>{if(!Q||!U){v(!0),x([]);return}B.current||v(!0);try{const se=await ee(U);x(se),B.current=!0}catch{}finally{v(!1)}},[Q,U,ee]);i.useEffect(()=>{Q&&(n==="inline"||S)&&W()},[n,S,Q,W]);const X=async se=>{if(!Q)return;const J=g.has(se.path),ne=new Set(g);if(J){ne.delete(se.path),w(ne);return}ne.add(se.path),w(ne);const ke=await ee(se.path),Z=xe=>xe.map(de=>de.path===se.path?{...de,children:ke}:de.children?{...de,children:Z(de.children)}:de);x(xe=>Z(xe))};i.useEffect(()=>{M&&T.current&&(T.current.focus(),T.current.select())},[M]);const ie=(se,J=[])=>{const ne="new_directory",ke=J.map(je=>je.name);if(!ke.includes(ne))return ne;let Z=1;const xe=new RegExp(`^${ne}(\\d+)$`);for(const je of ke){const ae=je.match(xe);if(ae){const Xe=parseInt(ae[1],10);Xe>Z&&(Z=Xe)}}let de=2;for(;ke.includes(`${ne}${de}`);)de++;return`${ne}${Math.max(de,Z+1)}`},be=async se=>{if(Q){if(g.has(se.path)){const J=ie(se.path,se.children);E(J)}else{const J=new Set(g);if(J.add(se.path),w(J),se.children){const ne=ie(se.path,se.children);E(ne)}else{const ne=await ee(se.path),ke=xe=>xe.map(de=>de.path===se.path?{...de,children:ne}:de.children?{...de,children:ke(de.children)}:de);x(xe=>ke(xe));const Z=ie(se.path,ne);E(Z)}}C(se.path)}},H=async()=>{if(!M||!Q)return;const se=I.trim()||"new_directory",J=`${M}/${se}`;try{await Fe.createDirectory(J);const ne=await ee(M),ke=Z=>Z.map(xe=>xe.path===M?{...xe,children:ne}:xe.children?{...xe,children:ke(xe.children)}:xe);x(Z=>ke(Z)),C(null),E("")}catch(ne){console.error("Failed to create directory:",ne)}},me=()=>{C(null),E("")},we=(se,J=0)=>{const ne=g.has(se.path),ke=se.isDirectory,Z=A.has(se.path),xe=t===se.path,de=n==="inline",je=e.jsxs(e.Fragment,{children:[ke&&e.jsx("button",{onClick:ae=>{ae.stopPropagation(),X(se)},className:F("hover:bg-accent rounded","p-0.5"),children:ne?e.jsx(Ot,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Bs,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!ke&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:ae=>{ae.stopPropagation(),re(se.path),n==="dropdown"&&a==="immediate"&&N(!1)},onDoubleClick:ae=>{ae.stopPropagation(),c&&c(se.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",de&&xe?"text-primary":"text-foreground"),children:[e.jsx(tr,{className:F("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",de&&xe&&"text-primary")}),e.jsx("span",{className:F("font-medium truncate","typography-ui-label",de&&xe?"text-primary":"text-foreground"),children:se.name})]}),e.jsx("button",{onClick:ae=>{ae.stopPropagation(),be(se)},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(is,{className:F("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:ae=>{ae.stopPropagation(),pe(se.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:Z?"Unpin directory":"Pin directory",children:Z?e.jsx(ai,{className:F("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Ph,{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:`${J*(p?12:14)+(p?4:6)}px`},children:je}),ne&&e.jsxs(e.Fragment,{children:[M===se.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(J+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:T,value:I,onChange:ae=>E(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"?(ae.preventDefault(),ae.stopPropagation(),H()):ae.key==="Escape"&&(ae.preventDefault(),ae.stopPropagation(),me())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Gt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),me()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Zt,{className:"h-3 w-3 text-muted-foreground"})})]}),se.children&&se.children.map(ae=>we(ae,J+1))]})]},se.path):e.jsxs("div",{children:[e.jsxs(Nt,{className:F("flex items-center gap-1 cursor-pointer group",t===se.path&&"bg-accent"),style:{paddingLeft:`${J*12+8}px`},onSelect:ae=>{ae.preventDefault()},children:[ke&&e.jsx("button",{onClick:ae=>{ae.stopPropagation(),X(se)},className:"p-0.5 hover:bg-accent rounded",children:ne?e.jsx(Ot,{className:"h-3 w-3"}):e.jsx(Bs,{className:"h-3 w-3"})}),!ke&&e.jsx("div",{className:"w-4"}),je]}),ne&&e.jsxs("div",{children:[M===se.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(J+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:T,value:I,onChange:ae=>E(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"?(ae.preventDefault(),ae.stopPropagation(),H()):ae.key==="Escape"&&(ae.preventDefault(),ae.stopPropagation(),me())},onBlur:H,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),H()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Gt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),me()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Zt,{className:"h-3 w-3 text-muted-foreground"})})]}),se.children&&se.children.map(ae=>we(ae,J+1))]})]},se.path)},he=(se,J)=>{if(n==="inline"){const ne=t===J;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",ne?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>re(J),onDoubleClick:ke=>{ke.stopPropagation(),c&&c(J)},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",ne?"text-primary":"text-foreground"),children:[e.jsx(tr,{className:F("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",ne?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:F("typography-ui-label font-medium truncate flex-shrink-0",ne?"text-primary":"text-foreground"),children:se}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:nn(J,b)})]}),e.jsx("button",{onClick:()=>pe(J),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(ai,{className:F("text-primary","h-3.5 w-3.5")})})]},J)}return e.jsxs(Nt,{onSelect:ne=>{ne.preventDefault(),re(J),a==="immediate"&&N(!1)},className:F("flex items-start gap-2 cursor-pointer group py-2",t===J&&"bg-accent"),children:[e.jsx(tr,{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:se}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:nn(J,b)})]}),e.jsx("button",{onClick:ne=>{ne.stopPropagation(),ne.preventDefault(),pe(J)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(ai,{className:"h-3 w-3 text-primary"})})]},J)},_e=e.jsx(e.Fragment,{children:Q?e.jsxs(e.Fragment,{children:[R.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>D(se=>!se),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:[P?e.jsx(Ot,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Bs,{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:R.length})]}),P&&R.map(({name:se,path:J})=>he(se,J)),n==="dropdown"&&e.jsx(Ds,{}),n==="inline"&&P&&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(se=>we(se)),!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(gt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:_e})}):e.jsxs(es,{open:S,onOpenChange:N,children:[e.jsx(ts,{asChild:!0,children:e.jsxs(Me,{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(tr,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:t,children:nn(t,b)})]}),e.jsx(Ot,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(ss,{align:"start",className:"w-[350px]",children:e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:_e})})]})},Ja=(t,r=200)=>{const[s,n]=Pe.useState(t);return Pe.useEffect(()=>{const o=window.setTimeout(()=>{n(t)},r);return()=>{window.clearTimeout(o)}},[t,r]),s},Sf=i.forwardRef(({inputValue:t,homeDirectory:r,onSelectSuggestion:s,visible:n,onClose:o,showHidden:a},c)=>{const[l,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(0),h=i.useRef(null),x=i.useRef([]),g=i.useCallback((b,k)=>{const A=b.trim().toLowerCase();if(!A)return 0;const j=k.toLowerCase();let M=0,C=-1,I=0;for(let E=0;E<A.length;E+=1){const P=A[E];if(!P||P===" ")continue;const D=j.indexOf(P,C+1);if(D===-1)return null;const T=D-C-1;if(T===0?I+=1:I=0,M+=10,M+=Math.max(0,18-D),M-=Math.max(0,T),D===0)M+=12;else{const L=j[D-1];(L==="/"||L==="_"||L==="-"||L==="."||L===" ")&&(M+=10)}M+=I>0?12:0,C=D}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 k=w(b);if(k.endsWith("/"))return k;const A=k.lastIndexOf("/");return A===-1?"":A===0?"/":k.substring(0,A+1)},[w]),v=i.useCallback(b=>{const k=w(b);if(k.endsWith("/"))return"";const A=k.lastIndexOf("/");return A===-1?k:k.substring(A+1)},[w]),S=Ja(t,150);i.useEffect(()=>{if(!n||!S){d([]);return}const b=y(S),k=v(S).toLowerCase();if(!b){d([]);return}let A=!1;return m(!0),Fe.listLocalDirectory(b).then(j=>{if(A)return;const M=j.filter(I=>!(!I.isDirectory||!a&&I.name.startsWith("."))),C=k?M.map(I=>{const E=g(k,I.name);return E!==null?{entry:I,score:E}:null}).filter(I=>I!==null).sort((I,E)=>E.score-I.score||I.entry.name.localeCompare(E.entry.name)).map(I=>I.entry):M.sort((I,E)=>I.name.localeCompare(E.name));d(C.slice(0,10)),p(0)}).catch(()=>{A||d([])}).finally(()=>{A||m(!1)}),()=>{A=!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=k=>{const A=k.target;!A||!h.current||h.current.contains(A)||o()};return document.addEventListener("pointerdown",b,!0),()=>{document.removeEventListener("pointerdown",b,!0)}},[n,o]);const N=i.useCallback(b=>{const k=b.path.endsWith("/")?b.path:b.path+"/";s(k)},[s]);return i.useImperativeHandle(c,()=>({handleKeyDown:b=>{if(!n||l.length===0)return!1;const k=l.length;if(b.key==="Tab"){if(b.preventDefault(),b.shiftKey)p(A=>(A-1+k)%k);else if(k===1){const A=l[0];A&&N(A)}else p(A=>(A+1)%k);return!0}if(b.key==="ArrowDown")return b.preventDefault(),p(A=>(A+1)%k),!0;if(b.key==="ArrowUp")return b.preventDefault(),p(A=>(A-1+k)%k),!0;if(b.key==="Enter"){b.preventDefault();const A=(f%k+k)%k,j=l[A];return j&&N(j),o(),!0}return b.key==="Escape"?(b.preventDefault(),o(),!0):!1}}),[n,l,f,N,o]),!n||l.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(zr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:l.map((b,k)=>{const A=f===k;return e.jsxs("div",{ref:j=>{x.current[k]=j},className:F("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",A&&"bg-muted"),onClick:()=>{N(b),o()},onMouseEnter:()=>p(k),children:[e.jsx(lr,{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"})]})});Sf.displayName="DirectoryAutocomplete";const kf="directoryTreeShowHidden",ul="directory-show-hidden-change",kd=()=>{if(typeof window>"u")return!1;try{return hs().getItem(kf)==="true"}catch{return!1}},Gw=()=>{typeof window>"u"||window.dispatchEvent(new Event(ul))},Nf=t=>{if(!(typeof window>"u"))try{hs().setItem(kf,t?"true":"false"),Gw()}catch{}},Co=()=>{const[t,r]=i.useState(kd);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(kd())};return window.addEventListener("storage",s),window.addEventListener(ul,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(ul,s)}},[]),t},qw=({open:t,onOpenChange:r})=>{const{currentDirectory:s,homeDirectory:n,isHomeReady:o}=bt(),{addProject:a,getActiveProject:c}=Vt(),[l,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,x]=i.useState(!1),g=Co(),{isDesktop:w,requestAccess:y,startAccessing:v}=Xa(),{isMobile:S}=Qt(),[N,b]=i.useState(!1),k=i.useRef(null),A=i.useCallback(re=>re?nn(re,n):"",[n]);i.useEffect(()=>{if(t){p(!1),x(!1),b(!1);const te=c()?.path||s||n||"";d(te),m(A(te))}},[t,s,n,A,c]),i.useEffect(()=>{!t||f||l||n&&o&&(d(n),p(!0),m("~"))},[t,f,l,n,o]);const j=i.useCallback(()=>{r(!1)},[r]),M=i.useCallback(async re=>{if(!(!re||h)){x(!0);try{let te=re,pe;if(w){const ee=await y(re);if(!ee.success){G.error("Unable to access directory",{description:ee.error||"Desktop denied directory access."});return}te=ee.path??re,pe=ee.projectId;const B=await v(te);if(!B.success){G.error("Failed to open directory",{description:B.error||"Desktop could not grant file access."});return}}if(!a(te,{id:pe})){G.error("Failed to add project",{description:"Please select a valid directory path."});return}j()}catch(te){G.error("Failed to select directory",{description:te instanceof Error?te.message:"Unknown error occurred."})}finally{x(!1)}}},[a,j,w,y,v,h]),C=i.useCallback(async()=>{const re=u.trim()||l;re&&await M(re)},[M,u,l]),I=i.useCallback(re=>{d(re),p(!0),m(A(re))},[A]),E=i.useCallback(async re=>{d(re),p(!0),m(A(re)),await M(re)},[M,A]),P=i.useCallback(re=>{const te=re.target.value;if(m(te),p(!0),b(te.startsWith("/")||te.startsWith("~")),te.startsWith("/")||te.startsWith("~")){const pe=te.startsWith("~")&&n?te.replace(/^~/,n):te;d(pe)}},[n]),D=i.useCallback(re=>{k.current?.handleKeyDown(re)||re.key==="Enter"&&(re.preventDefault(),C())},[C]),T=i.useCallback(re=>{d(re),p(!0),m(A(re))},[A]),L=i.useCallback(()=>{b(!1)},[]),V=i.useCallback(()=>{Nf(!g)},[g]),q=e.jsxs("button",{type:"button",onClick:V,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(Dl,{className:"h-4 w-4 text-primary"}):e.jsx(Al,{className:"h-4 w-4"}),"Show hidden"]}),_=e.jsxs(vs,{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(js,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(Ns,{className:"flex-1",children:"Choose a folder to add as a project."}),q]})]}),Y=e.jsxs("div",{className:"relative",children:[e.jsx(jt,{value:u,onChange:P,onKeyDown:D,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(Sf,{ref:k,inputValue:u,homeDirectory:n,onSelectSuggestion:T,visible:N,onClose:L,showHidden:g})]}),K=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(Sd,{variant:"inline",currentPath:l??s,onSelectPath:I,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})}),U=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:Y}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children: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(Sd,{variant:"inline",currentPath:l??s,onSelectPath:I,onDoubleClickPath:E,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),Q=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[Y,K]}),z=()=>e.jsxs(e.Fragment,{children:[e.jsx(Me,{variant:"ghost",onClick:j,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Me,{onClick:C,disabled:h||!f||!l&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:h?"Adding...":"Add Project"})]});return S?e.jsx($s,{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:z()}),children:U}):e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{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:re=>{re.preventDefault()},children:[_,Q,e.jsx(zs,{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:z()})]})})},Bo=t=>t?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:t}):void 0,Kw=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Qw=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=i.useRef(new Set),[a,c]=i.useState(null),[l,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}=bt(),{projects:N,addProject:b,activeProjectId:k}=Vt(),{requestAccess:A,startAccessing:j}=Xa(),{isMobile:M,isTablet:C,hasTouchInput:I}=Qt(),E=M||C||I,P=i.useMemo(()=>{const W=(k?N.find(X=>X.id===k)??null:null)?.path??y;return Kw(W)},[k,y,N]),D=i.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||l.some(B=>B.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,l]),T=i.useMemo(()=>{const B=a?.worktree;return B&&typeof B.branch=="string"&&B.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:W})=>typeof W.branch=="string"&&W.branch.trim().length>0)},[a?.worktree,l]),L=a?.mode==="worktree",V=L,q=f||!L||!T;i.useEffect(()=>{P&&(o.current.has(P)||By(P).then(()=>o.current.add(P)).catch(B=>{console.warn("Failed to ensure .openchamber directory is ignored:",B),o.current.delete(P)}))},[P]),i.useEffect(()=>{g()},[g,y]);const _=i.useMemo(()=>N.map(B=>`${B.id}:${B.path}`).join("|"),[N]),Y=i.useRef(_);i.useEffect(()=>{_!==Y.current&&(Y.current=_,g())},[g,_]),i.useEffect(()=>{if(!(s||!S||N.length>0)){if(n(!0),ls()){A("").then(async B=>{if(!B.success||!B.path){B.error&&B.error!=="Directory selection cancelled"&&G.error("Failed to select directory",{description:B.error});return}const W=await j(B.path);if(!W.success){G.error("Failed to open directory",{description:W.error||"Desktop could not grant file access."});return}b(B.path,{id:B.projectId})||G.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(B=>{console.error("Desktop: Error selecting directory:",B),G.error("Failed to select directory")});return}r(!0)}},[b,s,S,N.length,A,j]);const K=i.useCallback(B=>{c({sessions:B.sessions,dateLabel:B.dateLabel,mode:B.mode??"session",worktree:B.worktree??null})},[]),U=i.useCallback(()=>{c(null),d([]),m(!1),p(!1)},[]);i.useEffect(()=>zn.onDeleteRequest(B=>{K(B)}),[K]),i.useEffect(()=>zn.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1);return}const B=a.sessions.map(X=>{const ie=w(X.id);return ie?{session:X,metadata:ie}:null}).filter(X=>!!X);if(d(B),m(!1),B.length===0)return;let W=!1;return(async()=>{const X=await Promise.all(B.map(async({metadata:ie})=>{if(ie.status&&typeof ie.status.isDirty=="boolean")return ie.status;try{return await qa(ie.path)}catch{return ie.status}})).catch(ie=>(console.warn("Failed to inspect worktree status before deletion:",ie),B.map(({metadata:be})=>be.status)));W||!Array.isArray(X)||d(ie=>ie.map((be,H)=>({session:be.session,metadata:{...be.metadata,status:X[H]??be.metadata.status}})))})(),()=>{W=!0}},[a,w]),i.useEffect(()=>{T||m(!1)},[T]);const Q=i.useCallback(async()=>{if(a){p(!0);try{const B=V,W=B&&u;if(a.sessions.length===0&&L&&a.worktree){const X=u&&T;await Ym({projectDirectory:P,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:X});const ie=X?"Worktree and remote branch removed.":"Worktree removed.";G.success("Worktree removed",{description:Bo(ie)}),U(),g();return}if(a.sessions.length===1){const X=a.sessions[0];if(!await h(X.id,{archiveWorktree:B,deleteRemoteBranch:W})){G.error("Failed to delete session"),p(!1);return}const be=B?W?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;G.success("Session deleted",{description:Bo(be),action:{label:"OK",onClick:()=>{}}})}else{const X=a.sessions.map(H=>H.id),{deletedIds:ie,failedIds:be}=await x(X,{archiveWorktree:B,deleteRemoteBranch:W});if(ie.length>0){const H=B?W?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,we=[be.length>0?`${be.length} session${be.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,H].filter(Boolean).join(" ");G.success(`Deleted ${ie.length} session${ie.length===1?"":"s"}`,{description:Bo(we||void 0),action:{label:"OK",onClick:()=>{}}})}if(be.length>0&&(G.error(`Failed to delete ${be.length} session${be.length===1?"":"s"}`,{description:Bo("Please try again in a moment.")}),ie.length===0)){p(!1);return}}U()}finally{p(!1)}}},[a,u,h,x,U,V,L,T,P,g]),z=a?.worktree??l[0]?.metadata??null,re=a?a.mode==="worktree"?a.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${a.sessions.length===1?"1 linked session":`${a.sessions.length} linked sessions`}.`:`This action permanently removes ${a.sessions.length===1?"1 session":`${a.sessions.length} sessions`}${a.dateLabel?` from ${a.dateLabel}`:""}.`:"",te=a?e.jsxs("div",{className:F(L?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&e.jsxs("div",{className:F(L?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[L&&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(L?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(B=>e.jsxs("li",{className:F(L?"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(!L&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:B.title||"Untitled Session"})]},B.id)),a.sessions.length>5&&e.jsxs("li",{className:F(L?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",a.sessions.length-5," more"]})]})]}),L?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(Ht,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),z?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:z.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:z?nn(z.path,v):"Worktree path unavailable."}),D&&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,pe=L?T?e.jsxs("button",{type:"button",onClick:()=>{q||m(B=>!B)},disabled:q,className:F("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",q?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?e.jsx(Dl,{className:"size-4 text-primary"}):e.jsx(Al,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,R=L?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[pe,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{variant:"ghost",onClick:U,disabled:f,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:Q,disabled:f,children:f?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(Me,{variant:"ghost",onClick:U,disabled:f,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:Q,disabled:f,children:f?"Deleting…":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),ee=L?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[E?e.jsx($s,{open:!!a,onClose:()=>{f||U()},title:ee,footer:e.jsx("div",{className:"flex justify-end gap-2",children:R}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[re&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:re}),te]})}):e.jsx(xs,{open:!!a,onOpenChange:B=>{if(!B){if(f)return;U()}},children:e.jsxs(ys,{className:F(L?"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(vs,{children:[e.jsxs(js,{className:F(L&&"flex items-center gap-2"),children:[L&&e.jsx(Us,{className:"h-5 w-5"}),ee]}),re&&e.jsx(Ns,{children:re})]}),e.jsx("div",{className:F(L&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:te}),e.jsx(zs,{className:"mt-2 gap-2 pt-1 pb-1",children:R})]})}),e.jsx(qw,{open:t,onOpenChange:r})]})};function Yw(){return new Worker(Th,{type:"module"})}const Xw=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];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}`}function Nd(t){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>t(void 0),0);return()=>window.clearTimeout(r)}const Zw=({children:t})=>{const r=Rh(),s=as(l=>l.activeDirectory),n=as(l=>s?l.directories.get(s)?.lastStatusChange??0:0),o=as(l=>s?l.directories.get(s)?.diffCache.size??0:0),a=Pe.useRef(!1),c=Pe.useRef(new Map);return Pe.useEffect(()=>{if(!r||a.current)return;a.current=!0;const l={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Gi(l,{...l,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Pe.useEffect(()=>{if(!r||!s||!n||o===0)return;const l=as.getState().directories.get(s);if(!l||l.diffCache.size===0||(c.current.get(s)??0)>=l.lastStatusChange)return;c.current.set(s,l.lastStatusChange);let u=!1,m=null;const f=Array.from(l.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,Pr(w);const v=Jw(w,y.original,y.modified),S={name:w,contents:y.original,cacheKey:`old-${v}`},N={name:w,contents:y.modified,cacheKey:`new-${v}`},b=Gi(S,N),k={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(k,b)}p<f.length&&(m=Nd(h))};return h(void 0),p<f.length&&(m=Nd(h)),()=>{u=!0,m?.()}},[r,s,n,o]),e.jsx(e.Fragment,{children:t})},ev=({children:t})=>{const s=Qa()?.currentTheme?.metadata?.variant==="dark";mf();const n=Pe.useMemo(()=>({theme:{dark:Bn.dark,light:Bn.light},themeType:s?"dark":"light",langs:Xw}),[s]);return e.jsx(Fh,{poolOptions:{workerFactory:Yw,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Zw,{children:t})})},ml=t=>t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),tv=(t,r)=>{const s=ml(t),n=ml(r);return`${s}-${n}`.substring(0,60)},Cd=(t,r)=>`${t}/${r}`,sv=t=>t.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),rv=()=>{const t=Vt.getState(),r=t.activeProjectId,s=r?t.projects.find(l=>l.id===r)?.path:void 0;if(typeof s=="string"&&s.trim().length>0)return s;const n=bt.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,c=o.indexOf("/.openchamber/");return c>0?o.slice(0,c):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},mo=ns()(cs(t=>({isLoading:!1,error:null,createMultiRun:async r=>{const s=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:c,setupCommands:l}=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=rv();if(!d)return t({error:"No directory selected",isLoading:!1}),null;if(!await Qr(d))return t({error:"Not in a git repository",isLoading:!1}),null;const m=ml(s),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,h=[],x=l?.filter(b=>b.trim().length>0)??[],g=new Map;for(const b of o){const k=`${b.providerID}:${b.modelID}`;g.set(k,(g.get(k)||0)+1)}const w=new Map;for(const b of o){const k=`${b.providerID}:${b.modelID}`,A=g.get(k)||1,j=(w.get(k)||0)+1;w.set(k,j);const M=tv(b.providerID,b.modelID),C=A>1?Cd(m,`${M}/${j}`):Cd(m,M);if(!C)return t({error:"Branch name is required for worktree creation",isLoading:!1}),null;const I=sv(C);if(!I)return t({error:`Invalid branch name: ${C}`,isLoading:!1}),null;try{const E=await $l({projectDirectory:d,worktreeSlug:I,branch:C,createBranch:!0,startPoint:p}),P=A>1?`${m}/${b.providerID}/${b.modelID}/${j}`:`${m}/${b.providerID}/${b.modelID}`,D=await Fe.withDirectory(E.path,()=>Fe.createSession({title:P}));ft.getState().setWorktreeMetadata(D.id,E),h.push({sessionId:D.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=l?.filter(b=>b.trim().length>0)??[];y.length>0&&Gm(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 N=c?.map(b=>({type:"file",mime:b.mime,filename:b.filename,url:b.url}));try{await ft.getState().loadSessions()}catch{}if(x.length>0)for(const b of h)Bl(b.worktreePath,d,x).then(k=>{if(!k.success){const A=k.results.filter(j=>!j.success);console.warn(`[MultiRun] Setup commands failed for ${b.worktreePath}:`,A)}}).catch(k=>{console.warn(`[MultiRun] Setup commands error for ${b.worktreePath}:`,k)});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:N}))}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}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 Ls({...t}){return e.jsx(Lh,{"data-slot":"select",...t})}function ln({...t}){return e.jsx(Hh,{"data-slot":"select-group",...t})}function fn({...t}){return e.jsx($h,{"data-slot":"select-value",...t})}function Os({className:t,size:r="default",children:s,...n}){return e.jsxs(Oh,{"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(_h,{asChild:!0,children:e.jsx(Ot,{className:"size-4 opacity-50"})})]})}function _s({className:t,children:r,position:s="popper",fitContent:n=!1,...o}){return e.jsx(Bh,{children:e.jsx(zh,{"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(gt,{as:Wh,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 Fn({className:t,...r}){return e.jsx(Uh,{"data-slot":"select-label",className:F("text-muted-foreground px-2 py-1.5 typography-meta",t),...r})}function rs({className:t,children:r,...s}){return e.jsxs(Vh,{"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(Gh,{children:e.jsx(Gt,{className:"size-4"})})}),e.jsx(qh,{children:r})]})}function Ia({className:t,...r}){return e.jsx(Kh,{"data-slot":"select-separator",className:F("bg-border pointer-events-none -mx-1 my-1 h-px",t),...r})}const nv="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",ov=Object.assign({"../assets/provider-logos/gocode.svg":nv}),fl=new Map;for(const[t,r]of Object.entries(ov)){const s=t.match(/provider-logos\/([^/]+)\.svg$/i);s?.[1]&&r&&fl.set(s[1].toLowerCase(),r)}function Cf(t){const r=t?.toLowerCase()??null,s=r?fl.has(r):!1,n=r?fl.get(r)??null:null,[o,a]=Pe.useState(s?"local":"remote");Pe.useEffect(()=>{a(s?"local":"remote")},[s,r]);const c=Pe.useCallback(()=>{a(l=>l==="local"&&s?"remote":"none")},[s]);return r?o==="local"&&n?{src:n,onError:c,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:c,hasLogo:!0}:{src:null,onError:c,hasLogo:!1}:{src:null,onError:c,hasLogo:!1}}const ws=({providerId:t,alt:r,className:s,onError:n})=>{const{src:o,onError:a,hasLogo:c}=Cf(t),l=i.useCallback(()=>{a(),n?.()},[a,n]);return!c||!o?null:e.jsx("img",{src:o,alt:r||`${t} logo`,className:F("dark:invert",s),onError:l})},rc=t=>t.nativeEvent.isComposing||t.nativeEvent.keyCode===229,nc=()=>{const{providers:t}=at(),{favoriteModels:r,recentModels:s}=Te(),n=i.useMemo(()=>r.map(({providerID:a,modelID:c})=>{const l=t.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===c);return u?{provider:l,model:u,providerID:a,modelID:c}:null}).filter(a=>a!==null),[r,t]),o=i.useMemo(()=>s.map(({providerID:a,modelID:c})=>{const l=t.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===c);return u?{provider:l,model:u,providerID:a,modelID:c}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:c})=>!r.some(l=>l.providerID===a&&l.modelID===c)),[s,t,r]);return{favoriteModelsList:n,recentModelsList:o}},Mf="h-7",Pa=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,av=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),iv=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=av.format(t);return r.endsWith(".0")?r.slice(0,-2):r},lv=({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",Mf),children:[e.jsx(ws,{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(Zt,{className:"h-3.5 w-3.5"})})]})},Df=({selectedModels:t,onAdd:r,onRemove:s,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:c=!0,maxModels:l})=>{const{providers:d,modelsMetadata:u}=at(),{favoriteModelsList:m,recentModelsList:f}=nc(),[p,h]=i.useState(!1),[x,g]=i.useState(""),[w,y]=i.useState(0),[v,S]=i.useState(null),N=i.useRef(null),b=i.useRef(null),k=i.useRef(null),A=i.useRef([]),j=i.useMemo(()=>{const q=new Map;for(const _ of t){const Y=`${_.providerID}:${_.modelID}`;q.set(Y,(q.get(Y)||0)+1)}return q},[t]),M=i.useCallback(q=>t.filter(Y=>Y.providerID===q.providerID&&Y.modelID===q.modelID).findIndex(Y=>Y.instanceId===q.instanceId)+1,[t]),C=(q,_)=>{const Y=`${q}/${_}`;return u.get(Y)},I=q=>{const _=q?.name||q?.id||"",Y=String(_);return Y.length>40?Y.substring(0,37)+"...":Y},E=i.useCallback((q,_)=>{if(!x.trim())return!0;const Y=x.toLowerCase();return q.toLowerCase().includes(Y)||_.toLowerCase().includes(Y)},[x]),P=i.useMemo(()=>m.filter(({model:q,providerID:_})=>{const K=d.find(Q=>Q.id===_)?.name||_,U=I(q);return E(U,K)}),[m,d,E]),D=i.useMemo(()=>f.filter(({model:q,providerID:_})=>{const K=d.find(Q=>Q.id===_)?.name||_,U=I(q);return E(U,K)}),[f,d,E]),T=i.useMemo(()=>d.map(q=>{const Y=(Array.isArray(q.models)?q.models:[]).filter(K=>{const U=I(K);return E(U,q.name||q.id||"")});return{...q,models:Y}}).filter(q=>q.models.length>0),[d,E]),L=P.length>0||D.length>0||T.length>0;i.useEffect(()=>{if(p&&k.current){const _=k.current.getBoundingClientRect().top-100;S(Math.max(150,Math.min(400,_)))}},[p]),i.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const q=_=>{b.current&&!b.current.contains(_.target)&&(h(!1),g(""),y(0))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[p]),i.useEffect(()=>{y(0)},[x]);const V=(q,_,Y,K,U,Q)=>{const z=`${_}:${Y}`,re=j.get(z)||0,te=C(_,Y),pe=iv(te?.limit?.context);return e.jsxs("button",{ref:R=>{A.current[U]=R},type:"button",onClick:()=>{r({providerID:_,modelID:Y,displayName:q.name||Y,instanceId:Pa()})},onMouseEnter:()=>y(U),className:F("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",Q?"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:I(q)}),pe&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:pe})]}),re>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",re]})]},`${K}-${z}`)};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(Me,{ref:k,type:"button",variant:"outline",size:"sm",className:Mf,onClick:()=>h(!p),children:[e.jsx(is,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const q=[];P.forEach(({model:U,providerID:Q,modelID:z})=>{q.push({model:U,providerID:Q,modelID:z,section:"fav"})}),D.forEach(({model:U,providerID:Q,modelID:z})=>{q.push({model:U,providerID:Q,modelID:z,section:"recent"})}),T.forEach(U=>{U.models.forEach(Q=>{q.push({model:Q,providerID:U.id,modelID:Q.id,section:"provider"})})});const _=q.length,Y=U=>{if(!rc(U))if(U.key==="ArrowDown"){U.preventDefault(),U.stopPropagation();const Q=(w+1)%Math.max(1,_);y(Q),setTimeout(()=>{A.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(U.key==="ArrowUp"){U.preventDefault(),U.stopPropagation();const Q=(w-1+Math.max(1,_))%Math.max(1,_);y(Q),setTimeout(()=>{A.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(U.key==="Enter"){U.preventDefault(),U.stopPropagation();const Q=q[w];Q&&r({providerID:Q.providerID,modelID:Q.modelID,displayName:Q.model.name||Q.modelID,instanceId:Pa()})}else U.key==="Escape"&&(U.preventDefault(),U.stopPropagation(),h(!1),g(""),y(0))};let K=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(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:N,type:"text",placeholder:"Search models",value:x,onChange:U=>g(U.target.value),onKeyDown:Y,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(gt,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!L&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),P.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(Nr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),P.map(({model:U,providerID:Q,modelID:z})=>{const re=K++;return V(U,Q,z,"fav",re,w===re)})]}),D.length>0&&e.jsxs(e.Fragment,{children:[P.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(yr,{className:"h-4 w-4"}),"Recent"]}),D.map(({model:U,providerID:Q,modelID:z})=>{const re=K++;return V(U,Q,z,"recent",re,w===re)})]}),(P.length>0||D.length>0)&&T.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),T.map((U,Q)=>e.jsxs(i.Fragment,{children:[Q>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(ws,{providerId:U.id,className:"h-4 w-4 flex-shrink-0"}),U.name]}),U.models.map(z=>{const re=K++;return V(z,U.id,z.id,"provider",re,w===re)})]},U.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"})]})})()]}),c&&t.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:t.map((q,_)=>{const Y=`${q.providerID}:${q.modelID}`,K=j.get(Y)||1,U=M(q),z=d.find(ee=>ee.id===q.providerID)?.models.find(ee=>ee.id===q.modelID),re=z?.variants?Object.keys(z.variants):[],te=re.length>0,pe="__default__",R=q.variant??pe;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(lv,{model:q,instanceIndex:U,totalSameModel:K,onRemove:()=>s(_)}),te&&e.jsxs(Ls,{value:R,onValueChange:ee=>{if(!n)return;n(_,{...q,variant:ee===pe?void 0:ee})},children:[e.jsxs(Os,{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(br,{className:F("h-3.5 w-3.5 flex-shrink-0",R===pe?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(fn,{placeholder:"Thinking"})]}),e.jsxs(_s,{fitContent:!0,children:[e.jsx(rs,{value:pe,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),re.map(ee=>e.jsx(rs,{value:ee,className:"pr-2 [&>span:first-child]:hidden",children:ee},ee))]})]})]},q.instanceId)})})]}),o!==void 0&&t.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",l!==void 0?`to ${l} models`:"","."]})]})};function oc(t){const[r,s]=i.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=i.useState(!1),[a,c]=i.useState(null);return i.useEffect(()=>{let l=!1;if(!t){c(null),o(!1),s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),c(null),(async()=>{try{const d=await Qr(t);if(l)return;if(c(d),!d){s([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await Ga(t).catch(()=>null);if(l)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(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{l||o(!1)}})(),()=>{l=!0}},[t]),{branches:r,isLoading:n,isGitRepository:a}}const Af=({directory:t,value:r,onChange:s,className:n,disabled:o,id:a})=>{const{branches:c,isLoading:l,isGitRepository:d}=oc(t),u=i.useMemo(()=>c.find(f=>f.value===r)?.label??null,[c,r]);i.useEffect(()=>{!c.some(p=>p.value===r)&&c.length>0&&s("HEAD")},[c,r,s]);const m=o||!d||l;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Ls,{value:r,onValueChange:s,disabled:m,children:[e.jsx(Os,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(fn,{children:u}):e.jsx(fn,{placeholder:l?"Loading branches…":"Select a branch"})}),e.jsxs(_s,{fitContent:!0,children:[e.jsxs(ln,{children:[e.jsx(Fn,{children:"Default"}),c.filter(f=>f.group==="special").map(f=>e.jsx(rs,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),c.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{}),e.jsxs(ln,{children:[e.jsx(Fn,{children:"Local branches"}),c.filter(f=>f.group==="local").map(f=>e.jsx(rs,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,c.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{}),e.jsxs(ln,{children:[e.jsx(Fn,{children:"Remote branches"}),c.filter(f=>f.group==="remote").map(f=>e.jsx(rs,{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."})]})},Ef=({value:t,onChange:r,className:s,disabled:n,id:o})=>{const a=at(f=>f.getVisibleAgents),c=at(f=>f.loadAgents),l=at(f=>f.currentAgentName),d=a(),u=i.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(n)return;const f=t.trim();if(f.length>0&&u.some(x=>x.name===f))return;const p=typeof l=="string"&&l.trim().length>0?l.trim():null;if(p&&u.some(x=>x.name===p)){r(p);return}const h=u[0]?.name;h&&r(h)},[l,n,r,u,t]);const m=t.trim().length>0?t:void 0;return e.jsxs(Ls,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Os,{id:o,size:"lg",className:s??"max-w-full typography-meta text-foreground",children:e.jsx(fn,{placeholder:"Select an agent"})}),e.jsx(_s,{fitContent:!0,children:u.length>0&&e.jsx(ln,{children:u.map(f=>e.jsx(rs,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},cv=10*1024*1024,Md=5,Dd=({initialPrompt:t,onCreated:r,onCancel:s})=>{const[n,o]=i.useState(""),[a,c]=i.useState(()=>t??""),[l,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,N]=i.useState(!1),b=i.useRef(null),k=bt(B=>B.currentDirectory??null),A=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},[]),j=Vt(B=>B.activeProjectId),M=Vt(B=>B.projects),C=i.useMemo(()=>{if(j){const be=M.find(H=>H.id===j);if(be?.path)return be.path}const B=k??A;if(!B)return null;const W=B.replace(/\\/g,"/").replace(/\/+$/,"")||B,ie=W.indexOf("/.openchamber/");return ie>0?W.slice(0,ie):W.endsWith("/.openchamber")?W.slice(0,W.length-13):W},[j,M,k,A]),I=Te(B=>B.isSidebarOpen),[E,P]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),D=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const B=typeof window.opencodeDesktop<"u";P(B)},[]);const T=i.useMemo(()=>E&&D?I?"pl-0":"pl-[8.0rem]":"pl-3",[E,D,I]),[L,V]=i.useState("HEAD"),{isLoading:q,isGitRepository:_}=oc(k),Y=mo(B=>B.createMultiRun),K=mo(B=>B.error),U=mo(B=>B.clearError);i.useEffect(()=>{typeof t=="string"&&t.trim().length>0&&c(B=>B.trim().length>0?B:t)},[t]),i.useEffect(()=>{if(!C)return;let B=!1;return N(!0),(async()=>{try{const W=await Kn(C);B||w(W)}catch{}finally{B||N(!1)}})(),()=>{B=!0}},[C]);const Q=B=>{l.length>=Md||(d(W=>[...W,B]),U())},z=B=>{d(W=>W.filter((X,ie)=>ie!==B)),U()},re=i.useCallback((B,W)=>{d(X=>X.map((ie,be)=>be===B?W:ie))},[]),te=async B=>{const W=B.target.files;if(!W)return;let X=0;for(let ie=0;ie<W.length;ie++){const be=W[ie];if(be.size>cv){G.error(`File "${be.name}" is too large (max 10MB)`);continue}try{const H=await new Promise((we,he)=>{const _e=new FileReader;_e.onload=()=>we(_e.result),_e.onerror=he,_e.readAsDataURL(be)}),me={id:Pa(),filename:be.name,mimeType:be.type||"application/octet-stream",size:be.size,dataUrl:H};p(we=>[...we,me]),X++}catch(H){console.error("File attach failed",H),G.error(`Failed to attach "${be.name}"`)}}X>0&&G.success(`Attached ${X} file${X>1?"s":""}`),b.current&&(b.current.value="")},pe=B=>{p(W=>W.filter(X=>X.id!==B))},R=async B=>{if(B.preventDefault(),!!a.trim()&&!(l.length<2)){x(!0),U();try{const W=l.map(({instanceId:me,...we})=>we),X=f.map(me=>({mime:me.mimeType,filename:me.filename,url:me.dataUrl})),ie=g.filter(me=>me.trim().length>0),be={name:n.trim(),prompt:a.trim(),models:W,agent:u||void 0,worktreeBaseBranch:L,files:X.length>0?X:void 0,setupCommands:ie.length>0?ie:void 0},H=await Y(be);H&&(H.firstSessionId&&fe.getState().setCurrentSession(H.firstSessionId),r?.())}finally{x(!1)}}},ee=!!(n.trim()&&a.trim()&&l.length>=2&&_&&!q);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className: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&&D&&I&&"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(Zt,{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:R,className:"space-y-6","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:["Group name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(jt,{id:"group-name",value:n,onChange:B=>o(B.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(Af,{directory:k,value:L,onChange:V,id:"multirun-worktree-base-branch"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:L||"HEAD"}),"."]})]}),e.jsxs(ko,{open:y,onOpenChange:v,children:[e.jsxs(Ka,{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(B=>B.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",g.filter(B=>B.trim()).length," configured)"]})]}),e.jsx(Ot,{className:F("h-4 w-4 text-muted-foreground transition-transform duration-200",y&&"rotate-180")})]}),e.jsx(No,{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((B,W)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:B,onChange:X=>{const ie=[...g];ie[W]=X.target.value,w(ie)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const X=g.filter((ie,be)=>be!==W);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(Zt,{className:"h-4 w-4"})})]},W)),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(is,{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(Ef,{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:B=>c(B.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:te,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(Me,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>b.current?.click(),children:[e.jsx(ga,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.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(wr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(pr,{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.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",B.size<1024?`${B.size}B`:B.size<1024*1024?`${(B.size/1024).toFixed(1)}KB`:`${(B.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>pe(B.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Zt,{className:"h-3.5 w-3.5"})})]},B.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(Df,{selectedModels:l,onAdd:Q,onRemove:z,onUpdate:re,minModels:2,maxModels:Md})]}),K&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:K}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(Me,{type:"button",variant:"outline",onClick:s,children:"Cancel"}),e.jsx(Me,{type:"submit",disabled:!ee||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(Qh,{className:"h-4 w-4 mr-2"}),"Start (",l.length," models)"]})})]})]})})})]})},dv=(t={})=>{const{edgeThreshold:r=30,minSwipeDistance:s=50,maxSwipeTime:n=300,enabled:o=!0}=t,{isMobile:a,setSessionSwitcherOpen:c,isSessionSwitcherOpen:l}=Te(),d=Pe.useRef(null),u=Pe.useRef(null);return Pe.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:N,time:b}=u.current,k=S-w,A=N-y,j=b-v,M=Math.abs(A)<Math.abs(k),C=j<=n,I=Math.abs(A)<s;k>=s&&M&&C&&I&&!l&&c(!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,c,l]),null},no=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;Pe.memo(()=>{const t=Pe.useRef(null),{addAttachedFile:r}=fe(),{isMobile:s}=Te(),n=lf(),o=s?"h-9 w-9":"h-7 w-7",a=s?"h-5 w-5":"h-[18px] w-[18px]",c=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),G.error(x instanceof Error?x.message:"Failed to attach file")}}m>0&&G.success(`Attached ${m} file${m>1?"s":""}`)},l=async u=>{const m=u.target.files;m&&(await c(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(`
85
- `);G.error(`Some files were skipped:
86
- ${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 N=new Blob([S],{type:y});return new File([N],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 c(h)}catch(u){console.error("VS Code file pick failed",u),G.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:l,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(ga,{className:F(a,"text-current")})})]})});const uv=Pe.memo(({file:t,onRemove:r})=>{const s=()=>t.mimeType.startsWith("image/")?e.jsx(wr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("text")||t.mimeType.includes("code")?e.jsx(pr,{className:"h-3.5 w-3.5"}):t.mimeType.includes("json")||t.mimeType.includes("xml")?e.jsx(_a,{className:"h-3.5 w-3.5"}):e.jsx(pr,{className:"h-3.5 w-3.5"}),n=c=>c<1024?c+" B":c<1048576?(c/1024).toFixed(1)+" KB":(c/1048576).toFixed(1)+" MB",a=(c=>{const d=c.replace(/\\/g,"/").split("/");return d[d.length-1]||c})(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(Yh,{className:"h-3 w-3 text-primary"}):e.jsx(em,{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(Zt,{className:"h-3 w-3"})})]})}),mv=Pe.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(uv,{file:s,onRemove:()=>r(s.id)},s.id))]})})}),If=Pe.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(wr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(pr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(_a,{className:"h-3.5 w-3.5"}):e.jsx(pr,{className:"h-3.5 w-3.5"}):e.jsx(pr,{className:"h-3.5 w-3.5"}),a=s.filter(d=>d.mime?.startsWith("image/")&&d.url),c=s.filter(d=>!d.mime?.startsWith("image/")),l=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:[c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:c.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:()=>l(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(wr,{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}`)})})})]})}),Pf=Pe.memo(({message:t,sessionId:r,onEdit:s})=>{const n=fr(c=>c.removeFromQueue),o=i.useMemo(()=>{const c=t.content.split(`
87
- `),l=c[0]||"",d=50;return l.length>d?l.substring(0,d)+"...":l+(c.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(Xh,{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(Zt,{className:"h-3 w-3"})})]})});Pf.displayName="QueuedMessageChip";const Ad=[],Tf=Pe.memo(({onEditMessage:t})=>{const r=fe(a=>a.currentSessionId),s=fr(i.useCallback(a=>r?a.queuedMessages[r]??Ad:Ad,[r])),n=fr(a=>a.popToInput),o=i.useCallback(a=>{if(!r)return;const c=n(r,a.id);if(c){if(c.attachments&&c.attachments.length>0){const l=or.getState().attachedFiles;or.setState({attachedFiles:[...l,...c.attachments]})}t(c.content,c.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(Pf,{message:a,sessionId:r,onEdit:o},a.id))]})})});Tf.displayName="QueuedMessageChips";const Ff="filesViewShowGitignored",pl="files-view-show-gitignored-change",Ed=()=>{if(typeof window>"u")return!1;try{return hs().getItem(Ff)==="true"}catch{return!1}},fv=()=>{typeof window>"u"||window.dispatchEvent(new Event(pl))},pv=t=>{if(!(typeof window>"u"))try{hs().setItem(Ff,t?"true":"false"),fv()}catch{}},Za=()=>{const[t,r]=i.useState(Ed);return i.useEffect(()=>{if(typeof window>"u")return;const s=()=>{r(Ed())};return window.addEventListener("storage",s),window.addEventListener(pl,s),()=>{window.removeEventListener("storage",s),window.removeEventListener(pl,s)}},[]),t},hv=i.forwardRef(({searchQuery:t,onFileSelect:r,onClose:s},n)=>{const{currentDirectory:o}=bt(),{addServerFile:a}=fe(),c=Ua(P=>P.searchFiles),l=Ja(t,180),d=Co(),u=Za(),[m,f]=i.useState([]),[p,h]=i.useState(!1),[x,g]=i.useState(0),[w,y]=i.useState(360),[v,S]=i.useState({}),[N,b]=i.useState({}),k=i.useRef([]),A=i.useRef([]),j=i.useRef([]),M=i.useRef(null),C=i.useCallback((P,D)=>{const T=P.trim().toLowerCase();if(!T)return 0;const L=D.toLowerCase();let V=0,q=-1,_=0;for(let Y=0;Y<T.length;Y+=1){const K=T[Y];if(!K||K===" ")continue;const U=L.indexOf(K,q+1);if(U===-1)return null;const Q=U-q-1;if(Q===0?_+=1:_=0,V+=10,V+=Math.max(0,18-U),V-=Math.max(0,Q),U===0)V+=12;else{const z=L[U-1];(z==="/"||z==="_"||z==="-"||z==="."||z===" ")&&(V+=10)}V+=_>0?12:0,q=U}return V+=Math.max(0,24-Math.round(L.length/3)),V},[]);i.useEffect(()=>{const P=D=>{const T=D.target;!T||!M.current||M.current.contains(T)||s()};return document.addEventListener("pointerdown",P,!0),()=>{document.removeEventListener("pointerdown",P,!0)}},[s]),i.useEffect(()=>{if(!o){f([]);return}const D=(l??"").trim().replace(/^\.\//,"").replace(/^\/+/,"").toLowerCase();let T=!1;return h(!0),c(o,D,80,{includeHidden:d,respectGitignore:!u}).then(L=>{if(T)return;const V=D?L.map(q=>{const _=q.relativePath||q.name||q.path,Y=C(D,_);return Y===null?null:{file:q,score:Y,labelLength:_.length}}).filter(Boolean):L.map(q=>({file:q,score:0,labelLength:(q.relativePath||q.name||q.path).length}));V.sort((q,_)=>_.score-q.score||q.labelLength-_.labelLength||q.file.path.localeCompare(_.file.path)),f(V.slice(0,15).map(q=>q.file))}).catch(()=>{T||f([])}).finally(()=>{T||h(!1)}),()=>{T=!0}},[o,l,C,c,d,u]),i.useEffect(()=>{g(0),S({}),b({})},[m]),i.useEffect(()=>{k.current[x]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[x]),i.useEffect(()=>{let P=null;const D=()=>{P!==null&&cancelAnimationFrame(P),P=requestAnimationFrame(()=>{const T={},L={};A.current.forEach((V,q)=>{if(!V)return;const Y=j.current[q]?.offsetWidth??V.scrollWidth,K=Math.max(0,Y-V.clientWidth),U=K>8;if(T[q]=U,U){const Q=Math.max(.6,K/110);L[q]=Q}}),S(T),b(L)})};return D(),window.addEventListener("resize",D),()=>{P!==null&&cancelAnimationFrame(P),window.removeEventListener("resize",D)}},[m]),i.useEffect(()=>{const P=A.current[x];if(!P)return;const D=()=>{const L=P.clientWidth;L>0&&y(L)};if(D(),typeof ResizeObserver>"u")return;const T=new ResizeObserver(D);return T.observe(P),()=>{T.disconnect()}},[x]);const I=i.useCallback(async P=>{await a(P.path,P.name),r(P)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:P=>{if(P==="Escape"){s();return}const D=m.length;if(D!==0){if(P==="ArrowDown"){g(T=>(T+1)%D);return}if(P==="ArrowUp"){g(T=>(T-1+D)%D);return}if(P==="Enter"||P==="Tab"){const T=(x%D+D)%D,L=m[T];L&&I(L)}}}}),[m,x,s,I]);const E=P=>{switch(P.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(Ks,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Ks,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(pr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(wr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(_a,{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(gt,{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(zr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[m.map((P,D)=>{const T=P.relativePath||P.name,L=Nm(T,{maxLength:45}),V=x===D,q=v[D]??!1,_=N[D]??2.6,Y=e.jsxs("div",{ref:K=>{k.current[D]=K},className:F("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",V&&"bg-muted"),onClick:()=>I(P),onMouseEnter:()=>g(D),children:[E(P),e.jsxs("span",{ref:K=>{A.current[D]=K},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:V?{"--file-mention-marquee-width":`${w}px`,"--file-mention-marquee-duration":`${_}s`}:void 0,"aria-label":T,children:[e.jsx("span",{ref:K=>{j.current[D]=K},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:T}),q&&V?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:T}):e.jsx("span",{className:"block truncate",children:L})]})]});return e.jsx(i.Fragment,{children:Y},P.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"})]})}),Rf=i.forwardRef(({searchQuery:t,onCommandSelect:r,onClose:s},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=fe(El(v=>{const S=v.currentSessionId;return{hasMessagesInCurrentSession:(S?v.messages.get(S)?.length??0:0)>0,currentSessionId:S}})),c=!!a,[l,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=qr(),[h,x]=i.useState(0),g=i.useRef([]),w=i.useRef(null);i.useEffect(()=>{const v=S=>{const N=S.target;!N||!w.current||w.current.contains(N)||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})),N=[...c&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...c?[{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;N.forEach(M=>b.set(M.name,M)),S.forEach(M=>b.set(M.name,M));const k=Array.from(b.values()),A=!o,j=(t?k.filter(M=>Gs(M.name,t)||M.description&&Gs(M.description,t)):k).filter(M=>A||M.name!=="init");j.sort((M,C)=>{const I=M.name.toLowerCase().startsWith(t.toLowerCase()),E=C.name.toLowerCase().startsWith(t.toLowerCase());return I&&!E?-1:!I&&E?1:M.name.localeCompare(C.name)}),d(j)}catch{const S=!o,N=[...c&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...c?[{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?N.filter(k=>Gs(k.name,t)||k.description&&Gs(k.description,t)):N).filter(k=>S||k.name!=="init");d(b)}finally{m(!1)}})()},[t,o,c,f]),i.useEffect(()=>{x(0)},[l]),i.useEffect(()=>{g.current[h]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[h]),i.useImperativeHandle(n,()=>({handleKeyDown:v=>{const S=l.length;if(v==="Escape"){s();return}if(S!==0){if(v==="ArrowDown"){x(N=>(N+1)%S);return}if(v==="ArrowUp"){x(N=>(N-1+S)%S);return}if(v==="Enter"||v==="Tab"){const N=(h%S+S)%S,b=l[N];b&&r(b)}}}}),[l,h,s,r]);const y=v=>{switch(v.name){case"init":return e.jsx(pr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Ln,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(eg,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(yr,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(Zh,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Ur,{className:"h-3.5 w-3.5 text-cyan-500"});default:return v.isBuiltIn?e.jsx(Jh,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(hn,{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(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:u?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(zr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[l.map((v,S)=>{const N=v.isBuiltIn,b=v.scope==="project";return e.jsxs("div",{ref:k=>{g.current[S]=k},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]}),N?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):v.scope?e.jsx("span",{className: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)}),l.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Rf.displayName="CommandAutocomplete";const gv=t=>t?t!=="primary":!1,Lf=i.forwardRef(({searchQuery:t,onAgentSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,c]=i.useState(0),[l,d]=i.useState([]),u=i.useRef([]),{getVisibleAgents:m}=at(),{agents:f,loadAgents:p}=Kr();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const g=m().filter(v=>gv(v.mode)).map(v=>{const S=f.find(N=>N.name===v.name);return{name:v.name,description:v.description,mode:v.mode??void 0,scope:S?.scope,isBuiltIn:S?tn(S):!1}}),w=t.trim(),y=w.length?g.filter(v=>Gs(v.name,w)):g;y.sort((v,S)=>v.name.localeCompare(S.name)),d(y),c(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(l.length){if(x==="ArrowDown"){c(g=>(g+1)%l.length);return}if(x==="ArrowUp"){c(g=>(g-1+l.length)%l.length);return}if(x==="Enter"||x==="Tab"){const g=l[(a+l.length)%l.length];g&&r(g.name)}}}}),[l,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:()=>c(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(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.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"})]})});Lf.displayName="AgentMentionAutocomplete";const Of=i.forwardRef(({searchQuery:t,onSkillSelect:r,onClose:s},n)=>{const o=i.useRef(null),[a,c]=i.useState(0),[l,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=nr();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=t.trim(),g=[...h.length?m.filter(w=>Gs(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),c(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(l.length){if(h==="ArrowDown"){c(x=>(x+1)%l.length);return}if(h==="ArrowUp"){c(x=>(x-1+l.length)%l.length);return}if(h==="Enter"||h==="Tab"){const x=l[a];x&&r(x.name)}}}}),[l,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:()=>c(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(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.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"})]})});Of.displayName="SkillAutocomplete";function xv({className:t,children:r,...s}){return e.jsxs(tg,{"data-slot":"scroll-area",className:F("relative",t),...s,children:[e.jsx(sg,{"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(yv,{}),e.jsx(rg,{})]})}function yv({className:t,orientation:r="vertical",...s}){return e.jsx(ng,{"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(og,{"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:c}=Qt(),l=c,{currentDirectory:d}=bt(),u=Ua(Z=>Z.searchFiles),m=Co(),f=Za(),[p,h]=i.useState(!1),[x,g]=i.useState(0),[w,y]=i.useState(!1),[v,S]=i.useState(""),N=Ja(v,200),[b,k]=i.useState(new Set),[A,j]=i.useState(new Set),[M,C]=i.useState({}),I=i.useRef(new Set),E=i.useRef(new Set),[P,D]=i.useState([]),[T,L]=i.useState(!1),[V,q]=i.useState(!1),[_,Y]=i.useState(!1),[K,U]=i.useState(null),Q=n??p,z=o??h,re=i.useCallback(Z=>Z.slice().sort((xe,de)=>xe.type!==de.type?xe.type==="directory"?-1:1:xe.name.localeCompare(de.name)),[]),te=i.useCallback((Z,xe)=>re(xe.filter(de=>m||!de.name.startsWith(".")).map(de=>{const je=de.name,ae=!de.isDirectory&&je.includes(".")?je.split(".").pop()?.toLowerCase():void 0;return{name:je,path:de.path||`${Z}/${je}`,type:de.isDirectory?"directory":"file",size:0,extension:ae}})),[re,m]),pe=i.useCallback(async Z=>{q(!0),U(null);try{const xe=await Fe.listLocalDirectory(Z,{respectGitignore:!f}),de=te(Z,xe.map(je=>({name:je.name,path:je.path,isDirectory:je.isDirectory})));I.current=new Set([Z]),E.current=new Set,C({[Z]:de}),j(new Set)}catch{U("Failed to load directory contents"),I.current=new Set([Z]),E.current=new Set,C({[Z]:[]}),j(new Set)}finally{q(!1)}},[te,f]),R=i.useCallback(async Z=>{const xe=Z.trim();if(!xe)return;const de=`${xe}::${x}`;if(!I.current.has(de)&&!E.current.has(de)){E.current=new Set(E.current),E.current.add(de);try{const je=await Fe.listLocalDirectory(xe,{respectGitignore:!f}),ae=te(xe,je.map(Xe=>({name:Xe.name,path:Xe.path,isDirectory:Xe.isDirectory})));I.current=new Set(I.current),I.current.add(de),C(Xe=>({...Xe,[xe]:ae}))}catch{C(je=>je[xe]?je:{...je,[xe]:[]})}finally{E.current=new Set(E.current),E.current.delete(de)}}},[te,f,x]);i.useEffect(()=>{(Q||w)&&d&&pe(d)},[Q,w,d,pe]),i.useEffect(()=>{g(Z=>Z+1)},[m,f]),i.useEffect(()=>{if(!(Q||w)||!d){D([]),L(!1);return}const Z=N.trim().replace(/^\.\//,"").replace(/^\/+/,"");if(!Z){D([]),L(!1);return}const xe=Z.toLowerCase();let de=!1;return L(!0),u(d,xe,150,{includeHidden:m,respectGitignore:!f}).then(je=>{if(de)return;const ae=je.map(Xe=>({name:Xe.name,path:Xe.path,type:"file",extension:Xe.extension,relativePath:Xe.relativePath,size:0}));D(ae)}).catch(()=>{de||D([])}).finally(()=>{de||L(!1)}),()=>{de=!0}},[Q,w,d,N,u,m,f]),i.useEffect(()=>{!Q&&!w&&(k(new Set),S(""),D([]),L(!1),I.current=new Set,E.current=new Set,C({}),j(new Set))},[Q,w]);const ee=Z=>{if(Z.type==="directory")return A.has(Z.path)?e.jsx(tr,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(tr,{className:"h-3.5 w-3.5 text-primary/60"});switch(Z.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(Ks,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Ks,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(po,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(wr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(po,{className:"h-3.5 w-3.5 text-muted-foreground"})}},B=async Z=>{A.has(Z)?j(de=>{const je=new Set(de);return je.delete(Z),je}):(j(de=>{const je=new Set(de);return je.add(Z),je}),await R(Z))},W=Z=>{k(r?xe=>{const de=new Set(xe);return de.has(Z)?de.delete(Z):de.add(Z),de}:new Set([Z]))},X=async()=>{const Z=new Map;Object.values(M).forEach(je=>{je.forEach(ae=>{ae.type==="file"&&Z.set(ae.path,ae)})});const xe=new Map(P.map(je=>[je.path,je])),de=Array.from(b).map(je=>Z.get(je)??xe.get(je)).filter(je=>!!je);Y(!0);try{await t(de),k(new Set),z(!1),y(!1)}finally{Y(!1)}},ie=i.useMemo(()=>d?M[d]??[]:[],[M,d]),be=v.trim().length>0,H=Z=>M[Z]??[],me=Z=>{if(d&&Z.startsWith(d)){const xe=Z.substring(d.length);return xe.startsWith("/")?xe.substring(1):xe}return Z.split("/").pop()||Z},we=(Z,xe)=>{const de=be?Z.relativePath||me(Z.path):Z.name,je=be&&de.includes("/")&&de.length>45,ae=je?Nm(de,{maxLength:l?42:48}):de,Xe=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",Z.type==="file"&&b.has(Z.path)&&"bg-primary/10"),style:{paddingLeft:`${xe*12}px`},onClick:mt=>{mt.preventDefault(),mt.stopPropagation(),Z.type==="file"&&W(Z.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ee(Z)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":de,children:ae})]}),Z.type==="file"&&b.has(Z.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:Xe}),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:de})})]},Z.path):i.cloneElement(Xe,{key:Z.path})},he=(Z,xe)=>{const de=Z.type==="directory",je=de?H(Z.path):[],ae=A.has(Z.path),Xe=de&&ae&&E.current.has(Z.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",!de&&b.has(Z.path)&&"bg-primary/10"),style:{paddingLeft:`${xe*12}px`},onClick:mt=>{mt.preventDefault(),mt.stopPropagation(),de?B(Z.path):W(Z.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ee(Z)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:Z.name}),!de&&b.has(Z.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),de&&ae&&je.length>0&&e.jsx("div",{children:je.map(mt=>he(mt,xe+1))}),de&&ae&&Xe&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(xe+1)*12}px`},children:"Loading…"})]},Z.path)},_e=b.size>0?`${b.size} file${b.size!==1?"s":""} selected`:"No files selected",se=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(Me,{size:"sm",onClick:X,disabled:b.size===0||_,className:"h-6 typography-meta",children:_?"Attaching...":"Attach Files"})]}),J=l?"flex-1 min-h-[240px]":"h-[300px]",ne=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(ir,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{value:v,onChange:Z=>S(Z.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:Z=>Z.stopPropagation()}),v&&e.jsx("button",{onClick:Z=>{Z.stopPropagation(),S("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Zt,{className:"h-3 w-3"})})]})}),e.jsxs(xv,{className:J,children:[V&&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..."})}),K&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:K})}),!V&&!K&&e.jsxs("div",{className:"py-1 px-2",children:[be?T?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):P.map(Z=>we(Z,0)):ie.map(Z=>he(Z,0)),!be&&ie.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),be&&!T&&P.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),ke=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),y(!0)},children:s});return a==="modal"?e.jsxs(e.Fragment,{children:[s?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:Z=>{Z.preventDefault(),Z.stopPropagation(),z(!0)},children:s}):null,e.jsx($s,{open:Q,onClose:()=>z(!1),title:"Select Project Files",footer:se,children:e.jsx("div",{className:"flex flex-col gap-0",children:ne})})]}):l?e.jsxs(e.Fragment,{children:[ke,e.jsx($s,{open:w,onClose:()=>y(!1),title:"Select Project Files",footer:se,children:e.jsx("div",{className:"flex flex-col gap-0",children:ne})})]}):e.jsxs(es,{open:Q,onOpenChange:z,children:[e.jsx(ts,{asChild:!0,children:s}),e.jsxs(ss,{className:F("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[ne,e.jsx(Ds,{}),se]})]})},zo=[{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 Lr(t){if(!t||t==="build")return zo[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)%(zo.length-1);return zo[s]}const wv=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),_f=t=>wv(t),vv=t=>t?typeof t=="string"?t==="ask":_f(t)?Object.values(t).some(r=>r==="ask"):!1:!1,jv=t=>t?typeof t=="string"?t==="deny":_f(t)?Object.values(t).some(r=>r==="deny"):!1:!1,$f=({agentDefaultEditMode:t,webfetchPermission:r,bashPermission:s})=>{const n=vv(s),o=jv(s),a=!n&&!o,c=r==="allow",l=r!=="deny",d=t==="allow"||t==="full",u=t==="ask";let m=t;d&&c&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:t!=="deny"&&l&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:c,webfetchNotDeny:l}},Wo=t=>t==="primary"||t==="all"||t===void 0||t===null,Ta=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},Ho=(t,r)=>{const s=Ta(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}}},Sv=(t,r)=>{const s=Ta(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},kv=[{key:"tool_call",icon:$a,label:"Tool calling",isActive:t=>t?.tool_call===!0},{key:"reasoning",icon:br,label:"Reasoning",isActive:t=>t?.reasoning===!0}],Nv={text:{icon:sm,label:"Text"},image:{icon:wr,label:"Image"},video:{icon:ig,label:"Video"},audio:{icon:ag,label:"Audio"},pdf:{icon:_a,label:"PDF"}},Cv=t=>t.trim().toLowerCase(),eo=(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=>Cv(o)))).map(o=>{const a=Nv[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Mv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Dv=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Js=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},Uo=t=>typeof t!="number"||!Number.isFinite(t)?"—":Dv.format(t),Ci=t=>kv.filter(r=>r.isActive(t)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Id=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},Pd=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)},Td=({className:t})=>{const{providers:r,currentProviderId:s,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:c,setProvider:l,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:h,getCurrentAgent:x,getVisibleAgents:g}=at(),w=g(),{currentSessionId:y,messages:v,saveSessionAgentSelection:S,getSessionAgentSelection:N,saveAgentModelForSession:b,getAgentModelForSession:k,saveAgentModelVariantForSession:A,getAgentModelVariantForSession:j,analyzeAndSaveExternalSessionChoices:M,getSessionAgentEditMode:C,setSessionAgentEditMode:I}=fe(),E=ht(O=>O.hasHydrated),{toggleFavoriteModel:P,isFavoriteModel:D,addRecentModel:T,isModelSelectorOpen:L,setModelSelectorOpen:V}=Te(),{favoriteModelsList:q,recentModelsList:_}=nc(),{isMobile:Y}=Qt(),K=qb(),U=lf(),Q=Y,[z,re]=i.useState(null),[te,pe]=i.useState(null),[R,ee]=i.useState(""),B=i.useCallback(()=>re(null),[]),W=i.useCallback(()=>pe(null),[]),X=i.useRef(void 0),[ie,be]=i.useState(()=>{const O=new Set;return s&&O.add(s),O}),[H,me]=i.useState(!1),we=L,he=V,[_e,se]=i.useState(!1),J=i.useId(),[ne,ke]=i.useState(""),[Z,xe]=i.useState(0),de=i.useRef([]);i.useEffect(()=>{z==="model"&&be(()=>{const O=new Set;return s&&O.add(s),O})},[z,s]),i.useEffect(()=>{z!=="agent"&&me(!1),z!=="model"&&ee("")},[z]);const je=i.useRef(we);i.useEffect(()=>{const O=je.current;je.current=we,we||(se(!1),ke(""),xe(0),O&&!Q&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[we,Q]),i.useEffect(()=>{xe(0)},[ne]);const ae=x?.(),Xe=i.useMemo(()=>ae?Ho(ae.permission,"edit")??"ask":"deny",[ae]),mt=i.useMemo(()=>{if(ae)return Ho(ae.permission,"webfetch")},[ae]),De=i.useMemo(()=>{if(!ae)return;const O=Sv(ae.permission,"bash");return O||void 0},[ae]),oe=i.useMemo(()=>$f({agentDefaultEditMode:Xe,webfetchPermission:mt,bashPermission:De}),[Xe,mt,De]),{cascadeDefaultMode:Ue,modeAvailability:Se,autoApproveAvailable:Ne}=oe,Ge=!!(y&&a),rt=Ge&&y&&a?C(y,a,Ue):Ue,Ke={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Le=i.useCallback(O=>!Se[O],[Se]),Ye=i.useMemo(()=>!Ge||Le(rt)&&rt!==Ue?Ue:rt,[Ue,Le,Ge,rt]),xt=[{mode:"ask",label:Ke.ask,disabled:Le("ask")},{mode:"allow",label:Ke.allow,disabled:Le("allow")},{mode:"full",label:Ke.full,disabled:Le("full")}],nt=i.useMemo(()=>no(Ye),[Ye]),It=!Ge||!Ne;i.useEffect(()=>{It&&(me(!1),se(!1))},[It]);const Pt=Y?"mobile":U?"vscode":"default",zt=Pt==="mobile"?"h-9":Pt==="vscode"?"h-6":"h-8",We=Pt==="mobile"?"h-5 w-5":"h-4 w-4",ut=Pt==="mobile"?"h-5 w-5":"h-4 w-4",vt=Q?"typography-micro":"typography-meta",dt=Pt==="mobile"||Pt==="vscode"?"gap-x-1":"gap-x-3",Tt=Ke[Ye],Ct=i.useCallback((O,ce=We)=>{const le=F(ce,"flex-shrink-0"),Re=no(O),Qe={color:Re?Re.text:"var(--foreground)"};return O==="full"?e.jsx(kr,{className:le,style:Qe}):O==="allow"?e.jsx(Zo,{className:le,style:Qe}):O==="deny"?e.jsx(Rn,{className:le,style:Qe}):e.jsx(un,{className:le,style:Qe})},[We]),os=i.useCallback(O=>{It||!y||!a||Le(O)||(I(y,a,O,Ue),he(!1),me(!1),se(!1))},[Ue,It,y,a,I,he,se,Le]),St=p(),Lt=Array.isArray(St?.models)?St.models:[],Ft=s&&n?h(s,n):void 0,Ut=Ci(Ft),Rt=eo(Ft,"input"),qt=eo(Ft,"output"),ye=i.useMemo(()=>`${s}/${n}`?m():[],[m,s,n]),Ae=ye.length>0,$=[{label:"Input",value:Uo(Ft?.cost?.input)},{label:"Output",value:Uo(Ft?.cost?.output)},{label:"Cache read",value:Uo(Ft?.cost?.cache_read)},{label:"Cache write",value:Uo(Ft?.cost?.cache_write)}],ue=[{label:"Context",value:Js(Ft?.limit?.context)},{label:"Output",value:Js(Ft?.limit?.output)}],ve=i.useRef(void 0),Be=y?v.get(y)?.length??-1:-1,ze=i.useRef(null),tt=i.useCallback((O,ce,le)=>{if(!O||!ce)return"model-missing";const Re=r.find(Ie=>Ie.id===O);return Re?(Array.isArray(Re.models)?Re.models:[]).find(Ie=>Ie.id===ce)?(l(O),d(ce),y&&le&&b(y,le,O,ce),"applied"):"model-missing":"provider-missing"},[r,l,d,y,b]);i.useEffect(()=>{if(!y){ze.current=null;return}if(!E||r.length===0||w.length===0)return;(!ze.current||ze.current.sessionId!==y)&&(ze.current={sessionId:y,resolved:!1,inFlight:!1});const O=ze.current;if(!O||O.resolved||O.inFlight)return;let ce=!1;const le=()=>{if(ce)return;const Ie=ze.current;Ie&&Ie.sessionId===y&&(Ie.resolved=!0,Ie.inFlight=!1)},Re=()=>{const Ie=N(y);if(Ie){a!==Ie&&f(Ie);const Ve=k(y,Ie);if(Ve){const Oe=tt(Ve.providerId,Ve.modelId,Ie);if(Oe==="applied")return"resolved";if(Oe==="provider-missing")return"waiting"}else return"resolved"}for(const Ve of w){const Oe=k(y,Ve.name);if(!Oe)continue;a!==Ve.name&&f(Ve.name),S(y,Ve.name);const Je=tt(Oe.providerId,Oe.modelId,Ve.name);if(Je==="applied")return"resolved";if(Je==="provider-missing")return"waiting"}return"continue"},He=()=>{if(w.length===0)return;const Ie=w.filter(Oe=>Wo(Oe.mode)),Ve=w.find(Oe=>Oe.name==="build")||Ie[0]||w[0];Ve&&(S(y,Ve.name),a!==Ve.name&&f(Ve.name),Ve.model?.providerID&&Ve.model?.modelID&&tt(Ve.model.providerID,Ve.model.modelID,Ve.name))};return(async()=>{try{const Ie=Re();if(Ie==="resolved"){le();return}if(Ie==="waiting"||Be===-1)return;if(Be>0){O.inFlight=!0;try{const Ve=await M(y,w);if(ce)return;if(Ve.size>0){let Oe=null,Je=-1/0;for(const[yt,Dt]of Ve)Dt.timestamp>Je&&(Je=Dt.timestamp,Oe=yt);if(Oe){S(y,Oe),a!==Oe&&f(Oe);const yt=Ve.get(Oe);if(yt){const Dt=tt(yt.providerId,yt.modelId,Oe);if(Dt==="applied"){le();return}if(Dt==="provider-missing")return}else{le();return}}}}catch(Ve){ce||console.error("[ModelControls] Error resolving session from messages:",Ve)}finally{const Ve=ze.current;!ce&&Ve&&Ve.sessionId===y&&(Ve.inFlight=!1)}}He(),le()}catch(Ie){ce||console.error("[ModelControls] Error in session switch:",Ie)}})(),()=>{ce=!0}},[y,Be,w,a,N,k,f,tt,M,S,E,r]),i.useEffect(()=>{if(!E||!y||r.length===0||w.length===0)return;const ce=N(y)||a;if(!ce)return;const le=k(y,ce);if(!le)return;const Re=r.find(Ve=>Ve.id===le.providerId);if(!Re||!(Array.isArray(Re.models)?Re.models.some(Ve=>Ve.id===le.modelId):!1))return;const Qe=s===le.providerId,Ie=n===le.modelId;Qe&&Ie||(ce!==a&&f(ce),tt(le.providerId,le.modelId,ce))},[E,y,a,s,n,r,w,N,k,tt,f]),i.useEffect(()=>{if(!E)return;(async()=>{try{if(a!==ve.current&&(ve.current=a,a&&y)){await new Promise(Re=>setTimeout(Re,50));const ce=k(y,a);if(ce){const Re=tt(ce.providerId,ce.modelId,a);if(Re==="applied"||Re==="provider-missing")return}const le=w.find(Re=>Re.name===a);if(le?.model?.providerID&&le?.model?.modelID&&tt(le.model.providerID,le.model.modelID,a)==="provider-missing")return}}catch(ce){console.error("[ModelControls] Agent change error:",ce)}})()},[a,y,k,tt,w,E]),i.useEffect(()=>{if(!E||!a){u(void 0);return}if(!s||!n){u(void 0);return}if(ye.length===0){u(void 0);return}if(o&&!ye.includes(o)){u(void 0);return}if(!y){if(!o){const le=c&&ye.includes(c)?c:void 0;u(le)}return}const O=j(y,a,s,n),ce=O&&ye.includes(O)?O:void 0;u(ce)},[ye,E,y,a,s,n,o,j,u,c]);const Ce=i.useCallback(O=>{u(O),y&&a&&s&&n&&A(y,a,s,n,O)},[a,n,s,y,A,u]),qe=O=>{try{f(O),he(!1),y&&S(y,O),Q&&B()}catch(ce){console.error("[ModelControls] Handle agent change error:",ce)}},et=(O,ce)=>{try{const le=tt(O,ce,a||void 0);if(le!=="applied"){le==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",O):le==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:O,modelId:ce});return}T(O,ce),he(!1),Q&&B(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(le){console.error("[ModelControls] Handle model change error:",le)}},ot=O=>{const ce=typeof O?.name=="string"?O.name:typeof O?.id=="string"?O.id:"";return ce.length>40?ce.substring(0,37)+"...":ce},_t=()=>r.find(ce=>ce.id===s)?.name||s,$t=()=>{if(!s||!n||Lt.length===0)return"Not selected";const O=Lt.find(ce=>ce.id===n);return ot(O)},wt=()=>{if(!a){const ce=w.filter(He=>Wo(He.mode)),Re=ce.find(He=>He.name==="build")||ce[0];return Re?ge(Re.name):"Select Agent"}const O=w.find(ce=>ce.name===a);return ge(O?O.name:a)},ge=O=>O.charAt(0).toUpperCase()+O.slice(1),Ee=(O,ce,le)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:ce,"aria-label":ce,role:"img",children:e.jsx(O,{className:"h-3.5 w-3.5"})},le),st=i.useCallback(O=>{be(ce=>{const le=new Set(ce);return le.has(O)?le.delete(O):le.add(O),le})},[]),$e=i.useCallback(O=>{X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{pe(O)},500)},[]),kt=i.useCallback(()=>{X.current&&clearTimeout(X.current)},[]);i.useEffect(()=>()=>{X.current&&clearTimeout(X.current)},[]);const Mt=()=>!Q||te!=="model"?null:e.jsx($s,{open:!0,onClose:W,title:Ft?.name||$t(),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:_t()})]}),Ut.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:Ut.map(({key:O,icon:ce,label:le})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ee(ce,le,`cap-${O}`),e.jsx("span",{className:"typography-meta text-foreground",children:le})]},O))})]}),(Rt.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:[Rt.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:Rt.map(({key:O,icon:ce,label:le})=>Ee(ce,`${le} input`,`input-${O}`))})]}),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:O,icon:ce,label:le})=>Ee(ce,`${le} output`,`output-${O}`))})]})]})]}),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:Js(Ft?.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:Js(Ft?.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:Id(Ft?.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:Pd(Ft?.release_date)})]})]})]})]})}),Kt=()=>{if(!Q||te!=="agent"||!ae)return null;const O=!!(ae.prompt&&ae.prompt.trim().length>0),ce=ae.model?.providerID&&ae.model?.modelID,le=ae.temperature!==void 0||ae.topP!==void 0,Re=Ve=>{const Oe=Ta(ae.permission)??[],Je=Oe.some(Dt=>Dt.permission===Ve&&Dt.pattern!=="*"),yt=Ho(Oe,Ve)??"ask";return Je?{mode:"ask",label:"Custom"}:yt==="allow"?{mode:"allow",label:"Allow"}:yt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},He=Re("edit"),Qe=Re("bash"),Ie=Re("webfetch");return e.jsx($s,{open:!0,onClose:W,title:ge(ae.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ae.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:ae.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:ae.mode==="primary"?"Primary":ae.mode==="subagent"?"Subagent":ae.mode==="all"?"All":"—"})]}),(ce||le)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),ce&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ae.model.providerID," / ",ae.model.modelID]}),le&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[ae.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:ae.temperature})]}),ae.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:ae.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:[Ct(He.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:He.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:[Ct(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:[Ct(Ie.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ie.label})]})]})]})]}),O&&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(Zo,{className:"h-4 w-4 text-foreground"})]})})]})})},pt=()=>{if(!Q)return null;const O=R.trim(),ce=r.map(le=>{const Re=Array.isArray(le.models)?le.models:[],He=O.length===0?!0:Gs(le.name,O)||Gs(le.id,O),Qe=O.length===0?Re:Re.filter(Ie=>{const Ve=ot(Ie),Oe=typeof Ie.id=="string"?Ie.id:"";return Gs(Ve,O)||Gs(Oe,O)});return{provider:le,providerModels:Qe,matchesProvider:He}}).filter(({matchesProvider:le,providerModels:Re})=>le||Re.length>0);return e.jsx($s,{open:z==="model",onClose:B,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(ir,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{value:R,onChange:le=>ee(le.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),R&&e.jsx("button",{type:"button",onClick:()=>ee(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Rn,{className:"h-4 w-4"})})]})}),ce.length===0&&e.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),!R&&q.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(Nr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:q.map(({model:le,providerID:Re,modelID:He})=>{const Qe=Re===s&&He===n,Ie=h(Re,He);return e.jsxs("button",{type:"button",onClick:()=>et(Re,He),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(ws,{providerId:Re,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ot(le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Ie?.limit?.context||Ie?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Ie?.limit?.context?`${Js(Ie?.limit?.context)} ctx`:"",Ie?.limit?.context&&Ie?.limit?.output?" • ":"",Ie?.limit?.output?`${Js(Ie?.limit?.output)} out`:""]})})]},`fav-mobile-${Re}-${He}`)})})]}),!R&&_.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(yr,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:_.map(({model:le,providerID:Re,modelID:He})=>{const Qe=Re===s&&He===n,Ie=h(Re,He);return e.jsxs("button",{type:"button",onClick:()=>et(Re,He),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(ws,{providerId:Re,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ot(le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Ie?.limit?.context||Ie?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Ie?.limit?.context?`${Js(Ie?.limit?.context)} ctx`:"",Ie?.limit?.context&&Ie?.limit?.output?" • ":"",Ie?.limit?.output?`${Js(Ie?.limit?.output)} out`:""]})})]},`recent-mobile-${Re}-${He}`)})})]}),ce.map(({provider:le,providerModels:Re})=>{if(Re.length===0&&!O.length)return null;const He=le.id===s,Qe=ie.has(le.id)||O.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:()=>st(le.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(ws,{providerId:le.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:le.name}),He&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Qe?e.jsx(Ot,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Bs,{className:"h-3 w-3 text-muted-foreground"})]}),Qe&&Re.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Re.map(Ie=>{const Ve=He&&Ie.id===n,Oe=h(le.id,Ie.id),Je=Ci(Oe).slice(0,3),yt=eo(Oe,"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",!Ve&&"hover:bg-muted",Ve?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>et(le.id,Ie.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:ot(Ie)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Oe?.limit?.context||Oe?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Oe?.limit?.context?e.jsxs("span",{children:[Js(Oe?.limit?.context)," ctx"]}):null,Oe?.limit?.context&&Oe?.limit?.output?e.jsx("span",{children:"•"}):null,Oe?.limit?.output?e.jsxs("span",{children:[Js(Oe?.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:Dt,icon:ks,label:Cs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Cs,"aria-label":Cs,children:e.jsx(ks,{className:"h-3 w-3"})},`meta-${le.id}-${Ie.id}-${Dt}`))})]})]}),e.jsx("button",{type:"button",onClick:Dt=>{Dt.preventDefault(),Dt.stopPropagation(),P(le.id,Ie.id)},className:F("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",D(le.id,Ie.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":D(le.id,Ie.id)?"Unfavorite":"Favorite",title:D(le.id,Ie.id)?"Remove from favorites":"Add to favorites",children:D(le.id,Ie.id)?e.jsx(Nr,{className:"h-4 w-4"}):e.jsx(En,{className:"h-4 w-4"})})]},Ie.id)})})]},le.id)})]})})},Ss=()=>{if(!Q||!Ae)return null;const O=!o,ce=le=>{Ce(le),B(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx($s,{open:z==="variant",onClose:B,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",O?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ce(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),O&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),ye.map(le=>{const Re=o===le,He=le.charAt(0).toUpperCase()+le.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",Re?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ce(le),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:He}),Re&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},le)})]})})},ms=()=>{if(!Q)return null;const O=w.filter(ce=>Wo(ce.mode));return e.jsx($s,{open:z==="agent",onClose:B,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[O.map(ce=>{const le=ce.name===a,Re=Lr(ce.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",Re.class,le?"active":"border-border/40"),onClick:()=>qe(ce.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:F("h-2 w-2 rounded-full",Re.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:le?{color:`var(${Re.var})`}:void 0,children:ge(ce.name)})]}),ce.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:ce.description})]},ce.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:It,onClick:()=>{It||me(ce=>!ce)},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",It?"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:Tt})}),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:Ct(Ye,We)}),e.jsx(Ot,{className:F("h-4 w-4 text-muted-foreground transition-transform",H?"rotate-180":"")})]})]}),H&&!It&&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(ce=>{const le=ce.mode===Ye,Re=no(ce.mode);return e.jsxs("button",{type:"button",disabled:ce.disabled,onClick:()=>os(ce.mode),className:F("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",ce.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",le?"bg-primary/10":void 0),style:le&&Re?{backgroundColor:Re.background??void 0}:void 0,children:[Ct(ce.mode,We),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:Re?Re.text:"var(--foreground)"},children:ce.label})})]},ce.mode)})})})]})]})})},Yt=()=>e.jsx(it,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ft?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:Ft.name||$t()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:_t()})]}),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:Ut.length>0?Ut.map(({key:O,icon:ce,label:le})=>Ee(ce,le,`cap-${O}`)):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:Rt.length>0?Rt.map(({key:O,icon:ce,label:le})=>Ee(ce,`${le} input`,`input-${O}`)):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:O,icon:ce,label:le})=>Ee(ce,`${le} output`,`output-${O}`)):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)"}),$.map(O=>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:O.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:O.value})]},O.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"}),ue.map(O=>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:O.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:O.value})]},O.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:Id(Ft.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:Pd(Ft.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Vs=(O,ce,le,Re,He,Qe)=>{const Ie=h(ce,le),Ve=Ci(Ie).map(Es=>({...Es,id:`cap-${Es.key}`})),Oe=[...eo(Ie,"input"),...eo(Ie,"output")],Je=Array.from(new Map(Oe.map(Es=>[Es.key,Es])).values()).map(Es=>({...Es,id:`mod-${Es.key}`})),yt=[...Ve,...Je],Dt=Js(Ie?.limit?.context),ks=s===ce&&n===le,Cs=D(ce,le);return e.jsxs("div",{ref:Es=>{de.current[He]=Es},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:()=>et(ce,le),onMouseEnter:()=>xe(He),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:ot(O)}),Ie?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Dt}):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:Es,icon:Ep,label:gc})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":gc,role:"img",title:gc,children:e.jsx(Ep,{className:"h-2.5 w-2.5"})},Es))}),ks&&e.jsx(Gt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Es=>{Es.preventDefault(),Es.stopPropagation(),P(ce,le)},className:F("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Cs?"text-yellow-500":"text-muted-foreground"),"aria-label":Cs?"Unfavorite":"Favorite",title:Cs?"Remove from favorites":"Add to favorites",children:Cs?e.jsx(Nr,{className:"h-3.5 w-3.5"}):e.jsx(En,{className:"h-3.5 w-3.5"})})]})]},`${Re}-${ce}-${le}`)},xn=(O,ce,le)=>le.trim()?Gs(O,le)||Gs(ce,le):!0,ti=()=>{const O=q.filter(({model:Oe,providerID:Je})=>{const Dt=r.find(Cs=>Cs.id===Je)?.name||Je,ks=ot(Oe);return xn(ks,Dt,ne)}),ce=_.filter(({model:Oe,providerID:Je})=>{const Dt=r.find(Cs=>Cs.id===Je)?.name||Je,ks=ot(Oe);return xn(ks,Dt,ne)}),le=r.map(Oe=>{const yt=(Array.isArray(Oe.models)?Oe.models:[]).filter(Dt=>{const ks=ot(Dt);return xn(ks,Oe.name||Oe.id||"",ne)});return{...Oe,models:yt}}).filter(Oe=>Oe.models.length>0),Re=O.length>0||ce.length>0||le.length>0,He=[];O.forEach(({model:Oe,providerID:Je,modelID:yt})=>{He.push({model:Oe,providerID:Je,modelID:yt,section:"fav"})}),ce.forEach(({model:Oe,providerID:Je,modelID:yt})=>{He.push({model:Oe,providerID:Je,modelID:yt,section:"recent"})}),le.forEach(Oe=>{Oe.models.forEach(Je=>{He.push({model:Je,providerID:Oe.id,modelID:Je.id,section:"provider"})})});const Qe=He.length,Ie=Oe=>{if(Oe.key==="ArrowDown")Oe.preventDefault(),Oe.stopPropagation(),xe(Je=>(Je+1)%Math.max(1,Qe)),setTimeout(()=>{const Je=(Z+1)%Math.max(1,Qe);de.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Oe.key==="ArrowUp")Oe.preventDefault(),Oe.stopPropagation(),xe(Je=>(Je-1+Math.max(1,Qe))%Math.max(1,Qe)),setTimeout(()=>{const Je=(Z-1+Math.max(1,Qe))%Math.max(1,Qe);de.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Oe.key==="Enter"){Oe.preventDefault(),Oe.stopPropagation();const Je=He[Z];Je&&et(Je.providerID,Je.modelID)}else Oe.key==="Escape"&&(Oe.preventDefault(),Oe.stopPropagation(),he(!1))};let Ve=0;return e.jsxs(lt,{delayDuration:1e3,children:[Q?e.jsxs("button",{type:"button",onClick:()=>re("model"),onTouchStart:()=>$e("model"),onTouchEnd:kt,onTouchCancel:kt,className:F("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",zt),children:[s?e.jsx(ws,{providerId:s,className:F(ut,"flex-shrink-0")}):e.jsx(kr,{className:F(ut,"text-muted-foreground")}),e.jsx("span",{className:F("model-controls__model-label typography-micro font-medium overflow-hidden min-w-0",Y?"max-w-[120px]":"max-w-[220px]"),children:e.jsx("span",{className:"marquee-text",children:$t()})})]}):e.jsxs(es,{open:we,onOpenChange:he,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{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",zt),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(ws,{providerId:s,className:F(ut,"flex-shrink-0")}),e.jsx(kr,{className:F(ut,"text-primary/60 hidden")})]}):e.jsx(kr,{className:F(ut,"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:$t()})},`${s}-${n}`)]})})}),e.jsxs(ss,{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(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{type:"text",placeholder:"Search models",value:ne,onChange:Oe=>ke(Oe.target.value),onKeyDown:Ie,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Re&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),O.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(_r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Nr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),O.map(({model:Oe,providerID:Je,modelID:yt})=>{const Dt=Ve++;return Vs(Oe,Je,yt,"fav",Dt,Z===Dt)})]}),ce.length>0&&e.jsxs(e.Fragment,{children:[O.length>0&&e.jsx(Ds,{}),e.jsxs(_r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(yr,{className:"h-4 w-4"}),"Recent"]}),ce.map(({model:Oe,providerID:Je,modelID:yt})=>{const Dt=Ve++;return Vs(Oe,Je,yt,"recent",Dt,Z===Dt)})]}),(O.length>0||ce.length>0)&&le.length>0&&e.jsx(Ds,{}),le.map((Oe,Je)=>e.jsxs(i.Fragment,{children:[Je>0&&e.jsx(Ds,{}),e.jsxs(_r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ws,{providerId:Oe.id,className:"h-4 w-4 flex-shrink-0"}),Oe.name]}),Oe.models.map(yt=>{const Dt=Ve++;return Vs(yt,Oe.id,yt.id,"provider",Dt,Z===Dt)})]},Oe.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})]}),Yt()]})},si=()=>{if(!ae)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 O=!!(ae.prompt&&ae.prompt.trim().length>0),ce=ae.model?.providerID&&ae.model?.modelID,le=ae.temperature!==void 0||ae.topP!==void 0,Re=Ve=>{const Oe=Ta(ae.permission)??[],Je=Oe.some(Dt=>Dt.permission===Ve&&Dt.pattern!=="*"),yt=Ho(Oe,Ve)??"ask";return Je?{mode:"ask",label:"Custom"}:yt==="allow"?{mode:"allow",label:"Allow"}:yt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},He=Re("edit"),Qe=Re("bash"),Ie=Re("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:ge(ae.name)}),ae.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:ae.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:ae.mode==="primary"?"Primary":ae.mode==="subagent"?"Subagent":ae.mode==="all"?"All":"—"})]}),(ce||le)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),ce?e.jsxs("span",{className:"typography-meta text-foreground",children:[ae.model.providerID," / ",ae.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),le&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[ae.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:ae.temperature})]}),ae.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:ae.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:[Ct(He.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:He.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:[Ct(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:[Ct(Ie.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ie.label})]})]})]}),O&&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(Zo,{className:"h-4 w-4 text-foreground"})]})]})})},Mo=()=>{if(!Ae)return null;const O=o??"Default",ce=!o,le=ce?"text-muted-foreground":"text-[color:var(--status-info)]";return Q?e.jsxs("button",{type:"button",onClick:()=>re("variant"),className:F("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",zt,"cursor-pointer hover:opacity-70"),children:[e.jsx(br,{className:F(ut,"flex-shrink-0",le)}),e.jsx("span",{className:F("model-controls__variant-label",vt,"font-medium truncate min-w-0",Y&&"max-w-[60px]",le),children:O})]}):e.jsxs(lt,{delayDuration:800,children:[e.jsxs(es,{children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{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",zt),children:[e.jsx(br,{className:F(ut,"flex-shrink-0",le)}),e.jsx("span",{className:F("model-controls__variant-label",vt,"font-medium min-w-0 truncate",K?"max-w-[180px]":void 0,le),children:O})]})})}),e.jsxs(ss,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(_r,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(Nt,{className:"typography-meta",onSelect:()=>Ce(void 0),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:"Default"}),ce&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),ye.length>0&&e.jsx(Ds,{}),ye.map(Re=>{const He=o===Re,Qe=Re.charAt(0).toUpperCase()+Re.slice(1);return e.jsx(Nt,{className:"typography-meta",onSelect:()=>Ce(Re),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}),He&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},Re)})]})]}),e.jsx(it,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",O]})})]})},ri=()=>Q?e.jsxs("button",{type:"button",onClick:()=>re("agent"),onTouchStart:()=>$e("agent"),onTouchEnd:kt,onTouchCancel:kt,className:F("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",zt,"cursor-pointer hover:opacity-70"),children:[e.jsx(mn,{className:F(ut,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Lr(a).var})`}:void 0}),e.jsx("span",{className:F("model-controls__agent-label",vt,"font-medium truncate min-w-0",Y&&"max-w-[60px]"),style:a?{color:`var(${Lr(a).var})`}:void 0,children:wt()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(lt,{delayDuration:1e3,children:[e.jsxs(es,{children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs("div",{className:F("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",zt),children:[e.jsx(mn,{className:F(ut,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Lr(a).var})`}:void 0}),e.jsx("span",{className:F("model-controls__agent-label",vt,"font-medium min-w-0 truncate",K?"max-w-[220px]":void 0),style:a?{color:`var(${Lr(a).var})`}:void 0,children:wt()})]})})}),e.jsxs(ss,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[w.filter(O=>Wo(O.mode)).map(O=>e.jsx(Nt,{className:"typography-meta",onSelect:()=>qe(O.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",Lr(O.name).class)}),e.jsx("span",{className:"font-medium",children:ge(O.name)})]}),O.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:O.description})]})},O.name)),e.jsx(Ds,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:It,onClick:()=>{It||se(O=>!O)},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",It?"cursor-not-allowed opacity-60":void 0),"aria-expanded":_e,"aria-controls":J,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:nt?nt.text:"var(--foreground)"},children:Tt})}),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:Ct(Ye)}),e.jsx(Ot,{className:F("h-3.5 w-3.5 transition-transform text-muted-foreground",_e?"rotate-180":"")})]})]}),_e&&!It&&e.jsx("div",{id:J,className:"flex flex-col gap-1 rounded-xl border border-border/40 px-2 py-2 bg-transparent",role:"group","aria-label":"Edit permission options",children:xt.map(O=>{const ce=O.mode===Ye,le=no(O.mode);return e.jsxs("button",{type:"button",disabled:O.disabled,onClick:()=>os(O.mode),className:F("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",O.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",ce?"bg-primary/10":void 0),style:ce&&le?{backgroundColor:le.background??void 0}:void 0,children:[Ct(O.mode,We),e.jsx("span",{className:"typography-meta font-medium",style:{color:le?le.text:"var(--foreground)"},children:O.label})]},O.mode)})})]})]})]}),si()]})}),ni=F("@container/model-controls flex items-center min-w-0",Y&&"w-full",t);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:ni,children:e.jsxs("div",{className:F("flex items-center min-w-0 flex-1 justify-end",dt,Y&&"overflow-hidden"),children:[Mo(),ti(),ri()]})}),pt(),Ss(),ms(),Mt(),Kt()]})},Av=t=>t?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(t):!0,Fd=(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 c;for(;(c=a.exec(t))!==null;){const l=c.index,d=l+c[0].length,u=l>0?t[l-1]:null;if(!Av(u))continue;const m={name:o.name,source:{value:c[0],start:l,end:d}};n||(n=m)}}return n?{sanitizedText:t,mention:n}:{sanitizedText:t,mention:null}},Bf=t=>({id:t.id,content:t.content,status:t.status||"pending",priority:t.priority||"medium"}),hl=ns()(cs((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(Bf);t(c=>{const l=new Map(c.sessionTodos);return l.set(s,a),{sessionTodos:l,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"})),Ev=(t,r)=>{const s=r.map(Bf);hl.getState().updateTodos(t,s)},Rd=[{variant:"shine",component:({children:t,className:r,...s})=>e.jsx(kn.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)=>Pe.createElement(kn.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(c=>c===" "?" ":c);return e.jsxs(kn.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((c,l)=>e.jsx(kn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:c},String(l)))}),e.jsx("div",{className:F("absolute inset-0"),children:a.map((c,l)=>e.jsx(kn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:c},String(l)))})]})}},{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 Mi({variant:t="shine",className:r,...s}){const a=Rd.find(c=>c.variant===t)?.component||Rd[0].component;return e.jsx(Qu,{children:e.jsx(a,{...s,className:r})})}const Ld=1500,Iv=2e3;function Pv({statusText:t,isGenericStatus:r,isWaitingForPermission:s,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:c}){const[l,d]=Pe.useState("idle"),[u,m]=Pe.useState(null),[f,p]=Pe.useState(!1),h=Pe.useRef(0),x=Pe.useRef(null),g=Pe.useRef(null),w=Pe.useRef(null),y=Pe.useRef(null),v=Pe.useRef(!1),S=Pe.useRef(!1),N=Pe.useRef(!1),b=Pe.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),w.current&&(clearTimeout(w.current),w.current=null)},[]),k=Pe.useCallback((P,D)=>{b(),x.current=null,m(P),p(D),d("showing"),h.current=Date.now(),v.current=!0},[b]),A=Pe.useCallback(()=>{if(g.current)return;const P=Date.now()-h.current,D=Math.max(0,Ld-P);g.current=setTimeout(()=>{g.current=null;const T=x.current;T&&k(T.text,T.permission)},D)},[k]),j=Pe.useCallback(P=>{if(b(),x.current=null,!v.current){d("idle"),m(null),c?.(!1);return}if(P==="done"&&o&&y.current===o){d("idle"),m(null),v.current=!1,c?.(!1);return}P==="done"&&o&&(y.current=o),d(P),m(null),c?.(!0),w.current=setTimeout(()=>{w.current=null,d("idle"),v.current=!1,c?.(!1)},Iv)},[b,o,c]);if(Pe.useEffect(()=>{if(n&&!N.current){N.current=!0,j("aborted");return}if(N.current=!!n,a&&!S.current){S.current=!0,j("done");return}if(!a&&S.current&&(S.current=!1),!(l==="done"||l==="aborted")&&t){const D=Date.now()-h.current;if(l==="idle"||!u)k(t,!!s);else if(t!==u||!!s!==f){if(r)return;D>=Ld?k(t,!!s):(x.current={text:t,permission:!!s},A())}}},[t,s,n,a,l,u,f,k,j,A,r]),Pe.useEffect(()=>()=>b(),[b]),Pe.useEffect(()=>{const P=()=>{typeof document>"u"||document.visibilityState==="visible"&&(l==="done"||l==="aborted")&&(b(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[l,b]),l==="idle"&&!u)return null;let M,C=!0;l==="done"?(M="Done",C=!1):l==="aborted"?(M="Aborted",C=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const I=C?`${M}...`:M,E=l!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${E?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:l==="done"?e.jsx(Mi,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):l==="aborted"?e.jsx(Mi,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(Mi,{variant:"shine",className:"typography-ui-header",children:I})})})}const Od={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Tv=({todo:t})=>{const r=Od[t.status]||Od.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})})},_d=[],Fv=({isWorking:t,statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:c,isComplete:l,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=i.useState(!1),h=fe(D=>D.currentSessionId),x=hl(D=>h?D.sessionTodos.get(h)??_d:_d),g=hl(D=>D.loadTodos),{isMobile:w}=Te(),y=w||Wt();i.useEffect(()=>{h&&g(h)},[h,g]);const v=i.useMemo(()=>{const D={in_progress:0,pending:1,completed:2,cancelled:3};return[...x].filter(T=>T.status!=="cancelled").sort((T,L)=>D[T.status]-D[L.status])},[x]),S=i.useMemo(()=>v.find(D=>D.status==="in_progress")||v.find(D=>D.status==="pending")||null,[v]),N=i.useMemo(()=>{const D=x.filter(L=>L.status!=="cancelled").length;return{completed:x.filter(L=>L.status==="completed").length,total:D}},[x]),b=v.some(D=>D.status==="in_progress"||D.status==="pending"),k=!m&&(o||!a),[A,j]=i.useState(!1),M=t||l||o||A||b||m,C=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const D=T=>{C.current&&!C.current.contains(T.target)&&p(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[f]),!M)return null;const I=()=>p(D=>!D),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(Rn,{size:18,"aria-hidden":"true"})}):null,P=b?e.jsxs("button",{type:"button",onClick:I,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:[N.completed,"/",N.total]}),f?e.jsx(Oa,{className:"h-3.5 w-3.5"}):e.jsx(Ot,{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(Rn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(Pv,{statusText:r,isGenericStatus:s,isWaitingForPermission:n,wasAborted:o,completionId:c??null,isComplete:l,onResultVisibilityChange:j},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:C,children:[E,P,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:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:v.map(D=>e.jsx(Tv,{todo:D},D.id))})]})]})]})})},da=t=>!t||typeof t!="object"?!1:!!t.synthetic,$d=t=>!Array.isArray(t)||t.length===0?!1:t.every(r=>da(r)),Rv=t=>!Array.isArray(t)||t.length===0?[]:t.some(s=>!da(s))&&t.some(n=>da(n))?t.filter(n=>!da(n)):t,Lv={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Ov(t){const r=fe(s=>!t||!s.sessionActivityPhase?"idle":s.sessionActivityPhase.get(t)??"idle");return i.useMemo(()=>{if(r==="idle")return Lv;const s=r==="busy",n=r==="cooldown";return{phase:r,isWorking:s||n,isBusy:s,isCooldown:n}},[r])}function ac(){const t=fe(r=>r.currentSessionId);return Ov(t)}const _v={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},Bd=t=>t.role==="assistant",$v=t=>t.type==="reasoning",zf=t=>t.type==="text",zd=t=>{if(zf(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},Wd=t=>(zf(t)||$v(t),t.time),Bv=t=>{if(t.tool)return t.tool;const r=t;return typeof r.name=="string"?r.name:"tool"};function Wf(){const{currentSessionId:t,messages:r,permissions:s,sessionAbortFlags:n}=fe(El(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:c}=ac(),l=i.useMemo(()=>t?r.get(t)??[]:[],[t,r]),d=i.useMemo(()=>{if(l.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=l.filter(M=>Bd(M.info)&&!$d(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const x=[...h].sort((M,C)=>{const I=typeof M.info.time?.created=="number"?M.info.time.created:null,E=typeof C.info.time?.created=="number"?C.info.time.created:null;return I!==null&&E!==null&&I!==E?I-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 I=C.time??Wd(C);(!I||typeof I.end>"u")&&!w&&(w="reasoning");break}case"tool":{const I=C.state?.status;if((I==="running"||I==="pending")&&!w){const E=Bv(C);v.has(E)?w="editing":(w="tool",y=E)}break}case"text":{const I=zd(C)??"";if(typeof I=="string"&&I.trim().length>0){const E=Wd(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"},N=["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}`,k=()=>N[Math.floor(Math.random()*N.length)],A=w===void 0,j=w==="editing"?"editing file":w==="tool"&&y?b(y):w==="reasoning"?"thinking":w==="text"?"composing":k();return{activePartType:w,activeToolName:y,statusText:j,isGenericStatus:A}},[l]),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{..._v,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=c;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,c,d,u]),f=i.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||l.length===0)return{isActive:h,characterCount:0};const x=l.filter(y=>Bd(y.info)&&!$d(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=zd(y)??"";typeof v=="string"&&v.trim().length>0&&(w+=v.length)}),{isActive:h,characterCount:w}},[l,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 zv=8,Hd=[],Wv=t=>t==="primary"||t==="all"||t===void 0||t===null,Hf=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},Ud=(t,r)=>{const s=Hf(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}}},Hv=(t,r)=>{const s=Hf(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},Vo=({onOpenSettings:t,scrollToBottom:r})=>{const[s,n]=i.useState(""),[o,a]=i.useState(!1),[c,l]=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),[N,b]=i.useState(""),[k,A]=i.useState(null),j=i.useRef(null),M=i.useRef(null),C=i.useRef(null),I=i.useRef(null),E=i.useRef(null),P=i.useRef(null),D=fe(O=>O.sendMessage),T=fe(O=>O.currentSessionId),L=fe(O=>O.newSessionDraft?.open),V=fe(O=>O.abortCurrentOperation),q=fe(O=>O.acknowledgeSessionAbort),_=fe(O=>O.abortPromptSessionId),Y=fe(O=>O.abortPromptExpiresAt),K=fe(O=>O.clearAbortPrompt),U=fe(O=>O.sessionAbortFlags),Q=fe(O=>O.attachedFiles),z=fe(O=>O.addAttachedFile),re=fe(O=>O.addServerFile),te=fe(O=>O.clearAttachedFiles),pe=fe(O=>O.saveSessionAgentSelection),R=fe(O=>O.consumePendingInputText),ee=fe(O=>O.pendingInputText),{currentProviderId:B,currentModelId:W,currentVariant:X,currentAgentName:ie,setAgent:be,getVisibleAgents:H}=at(),me=H(),{isMobile:we,inputBarOffset:he,isKeyboardOpen:_e,setTimelineDialogOpen:se,cornerRadius:J}=Te(),{working:ne}=Wf(),[ke,Z]=i.useState(!1),xe=i.useRef(null),de=i.useRef(!1),je=i.useRef(!1),ae=fr(O=>O.queueModeEnabled),Xe=fr(i.useCallback(O=>T?O.queuedMessages[T]??Hd:Hd,[T])),mt=fr(O=>O.addToQueue),De=fr(O=>O.clearQueue),{phase:oe}=ac(),Ue=i.useRef(oe),Se=i.useRef(!1),Ne=i.useCallback(O=>{if(!we||O.pointerType!=="touch")return;const ce=j.current;if(!ce||document.activeElement===ce)return;O.preventDefault(),O.stopPropagation();const le=document.scrollingElement;le&&le.scrollTop!==0&&(le.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{ce.focus({preventScroll:!0})}catch{ce.focus()}const Re=ce.value.length;try{ce.setSelectionRange(Re,Re)}catch{}},[we]);i.useEffect(()=>{if(ee!==null){const O=R();O&&(n(O),setTimeout(()=>{j.current?.focus()},0))}},[ee,R]);const Ge=i.useMemo(()=>{if(ie)return me.find(O=>O.name===ie)},[me,ie]),rt=i.useMemo(()=>Ge?Ud(Ge.permission,"edit")??"ask":"deny",[Ge]),Ke=fe(i.useCallback(O=>!T||!ie?void 0:O.sessionAgentEditModes.get(T)?.get(ie),[T,ie])),Le=i.useMemo(()=>{if(Ge)return Ud(Ge.permission,"webfetch")},[Ge]),Ye=i.useMemo(()=>{if(!Ge)return;const O=Hv(Ge.permission,"bash");return O||void 0},[Ge]),xt=i.useMemo(()=>$f({agentDefaultEditMode:rt,webfetchPermission:Le,bashPermission:Ye}),[rt,Le,Ye]),nt=!!(T&&ie),It=i.useMemo(()=>nt&&Ke&&xt.modeAvailability[Ke]?Ke:xt.cascadeDefaultMode,[xt,nt,Ke]),Pt=i.useMemo(()=>no(It),[It]),zt=i.useCallback(O=>Wt()?`color-mix(in srgb, ${O} 55%, transparent)`:O,[]),We=i.useMemo(()=>{const O=Wt()?1:2,ce={borderRadius:J};if(!Pt)return{...ce,borderWidth:O};const le=Pt.border??Pt.text;return{...ce,borderColor:zt(le),borderWidth:O}},[Pt,zt,J]),ut=s.trim()||Q.length>0,vt=Xe.length>0,dt=ut||vt,Tt=ne.isWorking,Ct=i.useMemo(()=>T?_===T&&!!Y:!1,[_,Y,T]),os=i.useCallback(()=>{if(!ut||!T)return;const O=s.replace(/^\n+|\n+$/g,""),ce=Q.map(le=>({...le}));mt(T,{content:O,attachments:ce.length>0?ce:void 0}),n(""),ce.length>0&&te(),we||j.current?.focus()},[ut,T,s,Q,mt,te,we]),St=async O=>{if(O?.preventDefault(),!dt||!T&&!L)return;if(r?.({instant:!0,force:!0}),!B||!W){console.warn("Cannot send message: provider or model not selected");return}let ce="",le=[],Re;const He=[];for(let Ve=0;Ve<Xe.length;Ve++){const Oe=Xe[Ve],{sanitizedText:Je,mention:yt}=Fd(Oe.content,me);!Re&&yt?.name&&(Re=yt.name),Ve===0?(ce=Je,le=Oe.attachments??[]):He.push({text:Je,attachments:Oe.attachments})}if(ut){const Ve=s.replace(/^\n+|\n+$/g,""),{sanitizedText:Oe,mention:Je}=Fd(Ve,me),yt=Q.map(Dt=>({...Dt}));!Re&&Je?.name&&(Re=Je.name),Xe.length===0?(ce=Oe,le=yt):He.push({text:Oe,attachments:yt.length>0?yt:void 0})}if(!ce&&He.length===0)return;T&&vt&&De(T),n(""),Q.length>0&&te(),we&&j.current?.blur();const Qe=ce.trimStart();if(Qe.startsWith("/")){const Ve=Qe.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Ve==="undo"&&T){await fe.getState().handleSlashUndo(T),r?.({instant:!0,force:!0});return}else if(Ve==="redo"&&T){await fe.getState().handleSlashRedo(T),r?.({instant:!0,force:!0});return}else if(Ve==="timeline"&&T){se(!0),n("");return}else if(Ve==="compact"&&T){try{const{opencodeClient:Oe}=await bs(async()=>{const{opencodeClient:Dt}=await Promise.resolve().then(()=>_x);return{opencodeClient:Dt}},void 0),Je=Oe.getDirectory();if((await Oe.getApiClient().session.summarize({sessionID:T,directory:Je||void 0,providerID:B,modelID:W})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Oe){console.error("Failed to compact session:",Oe),G.error("Failed to compact session")}n("");return}}const Ie=[...le,...He.flatMap(Ve=>Ve.attachments??[])];await D(ce,B,W,ie,le,Re,He.length>0?He:void 0,X).catch(Ve=>{const Oe=Ve instanceof Error?Ve.message:typeof Ve=="string"?Ve:String(Ve??""),Je=Oe.toLowerCase();console.error("Message send failed:",Oe||Ve);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")){G.error("Attachments are too large to send. Please try reducing the number or size of images."),Ie.length>0&&or.setState({attachedFiles:Ie});return}yt||(Ie.length>0&&or.setState({attachedFiles:Ie}),G.error(Oe||"Message failed to send. Attachments restored."))}),we||j.current?.focus()},Lt=i.useRef(St);Lt.current=St,i.useEffect(()=>{const O=Ue.current==="busy"||Ue.current==="cooldown",ce=oe==="idle",le=T&&U.has(T)&&(()=>{const Re=U.get(T);return Re?Date.now()-Re.timestamp<2e3:!1})();O&&ce&&Xe.length>0&&!Se.current&&!le&&(Se.current=!0,setTimeout(()=>{T&&B&&W&&Lt.current(),Se.current=!1},100)),Ue.current=oe},[oe,Xe.length,T,B,W,U]);const Ft=O=>{if(!rc(O)){if(m&&I.current&&(O.key==="Enter"||O.key==="ArrowUp"||O.key==="ArrowDown"||O.key==="Escape"||O.key==="Tab")){O.preventDefault(),I.current.handleKeyDown(O.key);return}if(x&&E.current&&(O.key==="Enter"||O.key==="ArrowUp"||O.key==="ArrowDown"||O.key==="Escape"||O.key==="Tab")){O.preventDefault(),E.current.handleKeyDown(O.key);return}if(v&&P.current&&(O.key==="Enter"||O.key==="ArrowUp"||O.key==="ArrowDown"||O.key==="Escape"||O.key==="Tab")){O.preventDefault(),P.current.handleKeyDown(O.key);return}if(c&&C.current&&(O.key==="Enter"||O.key==="ArrowUp"||O.key==="ArrowDown"||O.key==="Escape"||O.key==="Tab")){O.preventDefault(),C.current.handleKeyDown(O.key);return}if(O.key==="Tab"&&!m&&!x&&!c){O.preventDefault(),qt();return}if(O.key==="Enter"&&!O.shiftKey&&!we){O.preventDefault();const ce=O.ctrlKey||O.metaKey,le=ut&&T&&oe!=="idle";ae?ce||!le?St():os():ce&&le?os():St()}}},Ut=i.useCallback(()=>{xe.current&&(clearTimeout(xe.current),xe.current=null),Z(!0),xe.current=setTimeout(()=>{Z(!1),xe.current=null},1800)},[]),Rt=i.useCallback(()=>{K(),Ut(),V()},[V,K,Ut]),qt=()=>{const O=me.filter(He=>Wv(He.mode));if(O.length<=1)return;const le=(O.findIndex(He=>He.name===ie)+1)%O.length,Re=O[le];be(Re.name),T&&pe(T,Re.name)},ye=i.useCallback(()=>{const O=j.current;if(!O)return;O.style.height="auto";const ce=O.ownerDocument?.defaultView,le=ce?ce.getComputedStyle(O):null,Re=le?parseFloat(le.lineHeight):NaN,He=le?parseFloat(le.paddingTop):NaN,Qe=le?parseFloat(le.paddingBottom):NaN,Ie=22,Oe=Number.isNaN(He)||Number.isNaN(Qe)?16:He+Qe,yt=(Number.isNaN(Re)?Ie:Re)*zv+Oe,Dt=O.scrollHeight||O.offsetHeight,ks=Math.min(Dt,yt);O.style.height=`${ks}px`,O.style.maxHeight=`${yt}px`,A(Cs=>Cs&&Cs.height===ks&&Cs.maxHeight===yt?Cs:{height:ks,maxHeight:yt})},[]);i.useLayoutEffect(()=>{ye()},[ye,s,we]);const Ae=i.useCallback((O,ce)=>{if(O.startsWith("/")){const Ie=O.indexOf(" "),Ve=O.indexOf(`
88
- `),Oe=Math.min(Ie===-1?O.length:Ie,Ve===-1?O.length:Ve);if(ce<=Oe&&Ie===-1){const Je=O.substring(1,Oe);h(Je),f(!0),l(!1),g(!1),S(!1);return}}f(!1);const le=O.substring(0,ce),Re=le.lastIndexOf("#");if(Re!==-1){const Ie=Re>0?le[Re-1]:null,Ve=le.substring(Re+1),Oe=Ve.includes(" ")||Ve.includes(`
89
- `);if((!Ie||/\s/.test(Ie))&&!Oe){y(Ve),g(!0),l(!1);return}}g(!1),y("");const He=le.lastIndexOf("/");if(He!==-1){const Ie=He>0?le[He-1]:null,Ve=le.substring(He+1),Oe=Ve.includes(" ")||Ve.includes(`
90
- `);if((!Ie||/\s/.test(Ie))&&!Oe){b(Ve),S(!0),l(!1),g(!1);return}}S(!1),b("");const Qe=le.lastIndexOf("@");if(Qe!==-1){const Ie=le.substring(Qe+1);!Ie.includes(" ")&&!Ie.includes(`
91
- `)?(u(Ie),l(!0)):l(!1)}else l(!1)},[y,h,u,g,f,l,S,b]),$=i.useCallback(O=>{if(!O)return;const ce=j.current;if(!ce){const Ie=s+O;n(Ie),Ae(Ie,Ie.length),requestAnimationFrame(()=>ye());return}const le=ce.selectionStart??s.length,Re=ce.selectionEnd??s.length,He=`${s.substring(0,le)}${O}${s.substring(Re)}`;n(He);const Qe=le+O.length;requestAnimationFrame(()=>{const Ie=j.current;Ie&&(Ie.selectionStart=Qe,Ie.selectionEnd=Qe),ye()}),Ae(He,Qe)},[ye,s,Ae]),ue=O=>{const ce=O.target.value,le=O.target.selectionStart??ce.length;n(ce),ye(),Ae(ce,le)},ve=i.useCallback(async O=>{const ce=new Map;Array.from(O.clipboardData.files||[]).forEach(Qe=>{Qe.type.startsWith("image/")&&ce.set(`${Qe.name}-${Qe.size}`,Qe)}),Array.from(O.clipboardData.items||[]).forEach(Qe=>{if(Qe.kind==="file"&&Qe.type.startsWith("image/")){const Ie=Qe.getAsFile();Ie&&ce.set(`${Ie.name}-${Ie.size}`,Ie)}});const le=Array.from(ce.values());if(le.length===0||!T&&!L)return;O.preventDefault();const Re=O.clipboardData.getData("text");Re&&$(Re);let He=0;for(const Qe of le){const Ie=fe.getState().attachedFiles.length;try{await z(Qe),fe.getState().attachedFiles.length>Ie&&(He+=1)}catch(Ve){console.error("Clipboard image attach failed",Ve),G.error(Ve instanceof Error?Ve.message:"Failed to attach image from clipboard")}}He>0&&G.success(`Attached ${He} image${He>1?"s":""} from clipboard`)},[z,T,L,$]),Be=O=>{const ce=j.current?.selectionStart||0,Re=s.substring(0,ce).lastIndexOf("@");if(Re!==-1){const He=s.substring(0,Re)+O.name+s.substring(ce);n(He)}l(!1),u(""),j.current?.focus()},ze=O=>{const le=j.current?.selectionStart??s.length,He=s.substring(0,le).lastIndexOf("#");if(He!==-1){const Qe=s.substring(0,He)+`#${O} `+s.substring(le);n(Qe);const Ie=He+O.length+2;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Ie,j.current.selectionEnd=Ie),ye(),Ae(Qe,Ie)})}g(!1),y(""),j.current?.focus()},tt=O=>{const le=j.current?.selectionStart??s.length,He=s.substring(0,le).lastIndexOf("/");if(He!==-1){const Qe=s.substring(0,He)+`${O} `+s.substring(le);n(Qe);const Ie=He+O.length+1;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Ie,j.current.selectionEnd=Ie),ye(),Ae(Qe,Ie)})}S(!1),b(""),j.current?.focus()},Ce=O=>{n(`/${O.name} `);const ce=j.current;ce&&(ce._commandMetadata=O),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&&!we&&j.current.focus()},[T,we]),i.useEffect(()=>{_&&_!==T&&K()},[_,T,K]);const qe=O=>{O.preventDefault(),O.stopPropagation(),(T||L)&&!o&&a(!0)},et=O=>{O.preventDefault(),O.stopPropagation(),O.currentTarget===O.target&&a(!1)},ot=async O=>{if(O.preventDefault(),O.stopPropagation(),a(!1),!T&&!L)return;const ce=Array.from(O.dataTransfer.files);let le=0;for(const Re of ce){const He=fe.getState().attachedFiles.length;try{await z(Re),fe.getState().attachedFiles.length>He&&(le+=1)}catch(Qe){console.error("File attach failed",Qe),G.error(Qe instanceof Error?Qe.message:"Failed to attach file")}}le>0&&G.success(`Attached ${le} file${le>1?"s":""}`)},_t=i.useCallback(async O=>{let ce=0;for(const le of O){const Re=fe.getState().attachedFiles.length;try{await re(le.path,le.name),fe.getState().attachedFiles.length>Re&&(ce+=1)}catch(He){console.error("Server file attach failed",He),G.error(He instanceof Error?He.message:"Failed to attach file")}}ce>0&&G.success(`Attached ${ce} file${ce>1?"s":""}`)},[re]),$t=i.useRef(null),[wt,ge]=i.useState(!1),Ee=i.useCallback(async O=>{let ce=0;const le=Array.isArray(O)?O:Array.from(O);for(const Re of le){const He=fe.getState().attachedFiles.length;try{await z(Re),fe.getState().attachedFiles.length>He&&(ce+=1)}catch(Qe){console.error("File attach failed",Qe),G.error(Qe instanceof Error?Qe.message:"Failed to attach file")}}ce>0&&G.success(`Attached ${ce} file${ce>1?"s":""}`)},[z]),st=i.useCallback(async()=>{try{const ce=await(await fetch("/api/vscode/pick-files")).json(),le=Array.isArray(ce?.files)?ce.files:[],Re=Array.isArray(ce?.skipped)?ce.skipped:[];if(Re.length>0){const Qe=Re.map(Ie=>`${Ie?.name||"file"}: ${Ie?.reason||"skipped"}`).join(`
92
- `);G.error(`Some files were skipped:
93
- ${Qe}`)}const He=le.map(Qe=>{if(!Qe?.dataUrl)return null;try{const[Ie,Ve]=Qe.dataUrl.split(","),Oe=Qe.mimeType||Ie?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Ve)return null;const Je=atob(Ve),yt=new Uint8Array(Je.length);for(let ks=0;ks<Je.length;ks++)yt[ks]=Je.charCodeAt(ks);const Dt=new Blob([yt],{type:Oe});return new File([Dt],Qe.name||"file",{type:Oe})}catch(Ie){return console.error("Failed to decode VS Code picked file",Ie),null}}).filter(Boolean);He.length>0&&await Ee(He)}catch(O){console.error("VS Code file pick failed",O),G.error(O instanceof Error?O.message:"Failed to pick files in VS Code")}},[Ee]),$e=i.useCallback(()=>{if(Wt()){st();return}$t.current?.click()},[st]),kt=i.useCallback(async O=>{const ce=O.target.files;ce&&(await Ee(ce),O.target.value="")},[Ee]),Mt="gap-x-1.5 gap-y-0",Kt=Wt(),pt=we?"px-1.5 py-1.5":Kt?"px-1.5 py-1":"px-2.5 py-1.5",Ss=we?"h-9 w-9":Kt?"h-[22px] w-[22px]":"h-7 w-7",ms=we?"h-5 w-5":Kt?"h-4 w-4":"h-[18px] w-[18px]",Yt=F(Ss,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),xn=!we&&Ct&&Tt?e.jsx("button",{type:"button",onClick:Rt,className:F(Yt,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Rn,{className:F(ms)})}):e.jsx("button",{type:we?"button":"submit",disabled:!dt||!T&&!L,onPointerDownCapture:O=>{!we||O.pointerType!=="touch"||!dt||!T&&!L||(je.current=!0,O.preventDefault(),O.stopPropagation(),St())},onClick:O=>{if(we){if(je.current){je.current=!1;return}O.preventDefault(),St()}},className:F(Yt,dt&&(T||L)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(La,{className:F(ms)})}),ti=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:$t,type:"file",multiple:!0,className:"hidden",onChange:kt,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(bv,{onFilesSelected:_t,multiSelect:!0,presentation:we?"modal":"dropdown",open:wt,onOpenChange:ge,children:we?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx("button",{type:"button",className:Yt,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(nm,{className:F(ms,"text-current")})})}),e.jsxs(ss,{align:"start",children:[e.jsxs(Nt,{onSelect:()=>{requestAnimationFrame(()=>$e())},children:[e.jsx(ga,{}),"Attach files"]}),e.jsxs(Nt,{onSelect:()=>{requestAnimationFrame(()=>{ge(!0)})},children:[e.jsx(lg,{}),"Attach from project"]})]})]})]})]}),si=t?e.jsx("button",{type:"button",onClick:t,className:Yt,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(mn,{className:F(ms,"text-current")})}):null,Mo=e.jsxs(e.Fragment,{children:[ti,si]}),ri=ne.statusText;i.useEffect(()=>{const O=!!ne.wasAborted;!de.current&&O&&!ke&&(Ut(),T&&q(T)),de.current=O},[q,T,ke,Ut,ne.wasAborted]),i.useEffect(()=>()=>{xe.current&&(clearTimeout(xe.current),xe.current=null)},[]);const ni=we&&Tt;return e.jsxs("form",{onSubmit:St,className:F("relative pt-0 pb-2 md:pb-4",we&&_e?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:we&&he>0&&!_e?{marginBottom:`${he}px`}:void 0,children:[e.jsx("div",{className:"absolute bottom-full left-0 right-0",children:e.jsx(Fv,{isWorking:ne.isWorking,statusText:ri,isGenericStatus:ne.isGenericStatus,isWaitingForPermission:ne.isWaitingForPermission,wasAborted:ne.wasAborted,abortActive:ne.abortActive,completionId:ne.lastCompletionId,isComplete:ne.isComplete,showAbort:ni,onAbort:Rt,showAbortStatus:ke})}),e.jsxs("div",{ref:M,className:F("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:qe,onDragLeave:et,onDrop:ot,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:Yt,onClick:()=>$e(),title:"Attach files","aria-label":"Attach files",children:e.jsx(ga,{className:F(ms,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(mv,{}),e.jsx(Tf,{onEditMessage:O=>{n(O),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:We,children:[m&&e.jsx(Rf,{ref:I,searchQuery:p,onCommandSelect:Ce,onClose:()=>f(!1)}),x&&e.jsx(Lf,{ref:E,searchQuery:w,onAgentSelect:ze,onClose:()=>g(!1)}),v&&e.jsx(Of,{ref:P,searchQuery:N,onSkillSelect:tt,onClose:()=>S(!1)}),c&&e.jsx(hv,{ref:C,searchQuery:d,onFileSelect:Be,onClose:()=>l(!1)}),e.jsx(Rs,{ref:j,"data-chat-input":"true",value:s,onChange:ue,onKeyDown:Ft,onPaste:ve,onPointerDownCapture:Ne,placeholder:T||L?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!T&&!L,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",we?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:k?`${k.height}px`:void 0,maxHeight:k?`${k.maxHeight}px`:void 0,borderTopLeftRadius:J,borderTopRightRadius:J},rows:1}),e.jsx("div",{className:F("bg-transparent",pt,we?"flex items-center gap-x-1.5":F("flex items-center justify-between",Mt)),style:{borderBottomLeftRadius:J,borderBottomRightRadius:J},"data-chat-input-footer":"true",children:we?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:Mo}),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(Td,{className:F("w-full flex items-center justify-end min-w-0")})}),xn]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("flex items-center flex-shrink-0",Mt),children:Mo}),e.jsxs("div",{className:F("flex items-center flex-1 justify-end",Mt,"md:gap-x-3"),children:[e.jsx(Td,{className:F("flex-1 min-w-0 justify-end")}),xn]})]})})]})]})]})};function Di({className:t,...r}){return e.jsx("div",{"data-slot":"skeleton",className:F("bg-accent animate-pulse rounded-xl",t),...r})}const Vd=(t,r,s,n,o=4)=>{const a=[];for(let c=0;c<o;c++)for(let l=0;l<o;l++){const d=l/o,u=(l+1)/o,m=c/o,f=(c+1)/o,p=(v,S,N)=>v+(S-v)*N,h=(v,S,N,b,k,A)=>{const j=p(v,S,k),M=p(b,N,k);return p(j,M,A)},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:c,col:l})}return a},ic=({className:t="",width:r=70,height:s=70,isAnimated:n=!1})=>{const o=Qa();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const c=a?"white":"black",l=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,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},N={x:50,y:h+m},k=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(x.y+g.y+y.y+w.y)/4})`,A=Vd(g,y,N,v),j=Vd(y,w,S,N),M=Pe.useMemo(()=>{const C=[];for(let I=0;I<32;I++)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${N.x} ${N.y} Z`,fill:l,stroke:c,strokeWidth:"2",strokeLinejoin:"round"}),A.map((C,I)=>e.jsx("path",{d:C.path,fill:u,opacity:M[I]},`left-${I}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${w.x} ${w.y} L${S.x} ${S.y} L${N.x} ${N.y} Z`,fill:l,stroke:c,strokeWidth:"2",strokeLinejoin:"round"}),j.map((C,I)=>e.jsx("path",{d:C.path,fill:u,opacity:M[I+16]},`right-${I}`)),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:c,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${k} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function Uv({children:t,className:r,interval:s=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:c=!0,mode:l="popLayout"}){const[d,u]=Pe.useState(0),m=Pe.Children.toArray(t);Pe.useEffect(()=>{if(!c)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,c]);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(cg,{mode:l,initial:!1,children:e.jsx(kn.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Vv=["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"],Gv=()=>{const t=Qa();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(ic,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Uv,{className:"text-body-md",interval:4,transition:{duration:.5},children:Vv.map(n=>e.jsxs("span",{style:{color:s},children:['"',n,'…"']},n))})]})},Ai=i.memo(Gv),qv={'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"}},Kv={'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 $r{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return $r.instance||($r.instance=new $r),$r.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 lc(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 ar=({children:t,className:r,skipAnimation:s})=>{const[n,o]=i.useState(s??!1);return i.useEffect(()=>{if(s)return;let a=null;const c=()=>o(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?a=window.requestAnimationFrame(c):c(),()=>{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})},Qv=({isUser:t,providerID:r,agentName:s,modelName:n,variant:o,isDarkTheme:a})=>{const{src:c,onError:l,hasLogo:d}=Cf(r);return e.jsx(ar,{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(Qs,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&c?e.jsx("img",{src:c,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:l}):e.jsx(br,{className:"h-4 w-4",style:{color:`var(${Lr(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)]",Lr(s).class),children:[e.jsx(mn,{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(br,{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})]})]})]})})})})},Yv=i.memo(Qv),Xv=t=>`https://opencode.ai/docs/agents/#${encodeURIComponent(t)}`,Jv=({part:t,messageId:r,agentMention:s})=>{const n=t,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[c,l]=i.useState(!1),[d,u]=i.useState(!1),m=i.useRef(null);i.useEffect(()=>{const h=m.current;if(!h||c)return;const x=()=>{u(h.scrollHeight>h.clientHeight)};x();const g=new ResizeObserver(x);return g.observe(h),()=>g.disconnect()},[a,c]);const f=i.useCallback(()=>{(d||c)&&l(h=>!h)},[d,c]);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:Xv(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",!c&&"line-clamp-3",(d||c)&&"cursor-pointer"),ref:m,onClick:f,children:p()},t.id||`${r}-user-text`)},Zv=i.memo(Jv),Gd=(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},qd=()=>{if(!Wt()||typeof window>"u")return ad;const t=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(t?.light&&t?.dark){const r=Gd({...t.light},`vscode-shiki-light:${String(t.light?.name??"theme")}`),s=Gd({...t.dark},`vscode-shiki-dark:${String(t.dark?.name??"theme")}`);return[r,s]}return ad},ej=()=>{const[t,r]=i.useState(qd);return i.useEffect(()=>{if(!Wt()||typeof window>"u")return;const s=n=>{r(qd())};return window.addEventListener("openchamber:vscode-shiki-themes",s),()=>window.removeEventListener("openchamber:vscode-shiki-themes",s)},[]),t},Uf=t=>{const r=[],s=[],n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach(c=>r.push(c.innerText.trim()));const o=t.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(c=>{const l=c.querySelectorAll("td"),d=[];l.forEach(u=>d.push(u.innerText.trim())),s.push(d)}),{headers:r,rows:s}},Vf=({headers:t,rows:r})=>{const s=o=>o.includes(",")||o.includes('"')||o.includes(`
94
- `)?`"${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(`
95
- `)},tj=({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(`
96
- `)},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((c,l)=>s(o[l]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
97
- `)},rj=(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)},nj=({tableRef:t})=>{const[r,s]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>{const l=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[]);const c=async l=>{const d=t.current?.querySelector("table");if(d)try{const u=Uf(d),m=l==="csv"?Vf(u):tj(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(Gt,{className:"size-3.5"}):e.jsx(Ys,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>c("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:()=>c("tsv"),children:"TSV"})]})]})},oj=({tableRef:t})=>{const[r,s]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=c=>{n.current&&!n.current.contains(c.target)&&s(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const c=t.current?.querySelector("table");if(c)try{const l=Uf(c),d=a==="csv"?Vf(l):sj(l);rj(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),s(!1)}catch(l){console.error("Failed to download table:",l)}};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(Wr,{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"})]})]})},aj=({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(nj,{tableRef:s}),e.jsx(oj,{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})})]})},ij=({children:t,className:r,style:s,...n})=>{const[o,a]=i.useState(!1),c=i.useRef(null),l=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 N=v.slice(0,S).trim(),b=v.slice(S+1).trim();!N.startsWith("--")||b.length===0||(y[N]=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=()=>c.current&&c.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:c,children:[e.jsx("pre",{...n,className:F(r),style:l,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(Gt,{className:"size-3.5"}):e.jsx(Ys,{className:"size-3.5"})})})]})},lj={pre:ij,table:aj},cn=({content:t,className:r,variant:s="assistant"})=>{const n=ej(),o=s==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:F("break-words",r),children:e.jsx(dg,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:lj,children:t})})},cj=t=>{let r=t.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},dj=t=>t?t.includes("<file_diagnostics>")||t.includes("This file has errors")||t.includes("please fix"):!1,uj=t=>t?t.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Kd=(t,r)=>!t||typeof t!="object"?String(t):Gb(t,r||""),Ei=(t,r,s)=>{let n=cj(t);if((r==="edit"||r==="multiedit")&&dj(n)&&(n=uj(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&s?.diff){const o=s.diff;return typeof o=="string"?o:String(o)}return n},mj=(t,r)=>{try{const s=t.trim().split(`
98
- `).filter(Boolean);if(s.length===0)return null;const n=[];return s.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,c,l]=a,d=Math.floor(c.length/2),u=!l.endsWith("/");n.push({name:l.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:Cr.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(`
99
- `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const c=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(c){const[,l,d,u]=c,m=u!==void 0?d:"",f=u!==void 0?u:d;o[l]||(o[l]=[]),o[l].push({lineNum:m,content:f})}}),e.jsxs("div",{className:F("space-y-2 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Cr.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,c])=>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:c.map((l,d)=>!l.lineNum&&!l.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:[l.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",l.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:l.content||" "})]})]},d))})]},a))]})}catch{return null}},pj=(t,r,s)=>{try{const n=t.trim().split(`
100
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(c=>{const l=c.lastIndexOf("/"),d=l>0?c.substring(0,l):"/",u=l>=0?c.substring(l+1):c;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:Cr.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(c=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:F("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[c,"/"]}),e.jsx("div",{className:F("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[c].sort().map(l=>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:l})]},l))})]},c))]})}catch{return null}},hj=(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 c="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:c,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:c,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:c,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:c,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:Cr.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,c)=>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||c))})]}),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,c)=>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||c))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gt,{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,c)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Gt,{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||c))})]}),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,c)=>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||c))})]})]})}catch{return null}},gj=(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:Cr.tool.popup,children:e.jsx(cn,{content:t,variant:"tool"})})}catch{return null}},Gf=t=>{const r=t.split(`
101
- `);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 c=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),l=c?parseInt(c[1]):0,d=c?parseInt(c[2]):0,u=[];let m=l,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:l,newStart:d,lines:u}),o=p;continue}o++}return n},gl=(t,r,s)=>Ub(r,t,s),qf=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(ug,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(om,{className:r}):s==="read"||s==="view"||s==="file_read"||s==="cat"?e.jsx(po,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"?e.jsx(Ur,{className:r}):s==="list"||s==="ls"||s==="dir"||s==="list_files"?e.jsx(tr,{className:r}):s==="search"||s==="grep"||s==="find"||s==="ripgrep"?e.jsx(mg,{className:r}):s==="glob"?e.jsx(fg,{className:r}):s==="fetch"||s==="curl"||s==="wget"||s==="webfetch"?e.jsx(Qi,{className:r}):s==="web-search"||s==="websearch"||s==="search_web"||s==="codesearch"||s==="google"||s==="bing"||s==="duckduckgo"||s==="perplexity"?e.jsx(Qi,{className:r}):s==="todowrite"||s==="todoread"?e.jsx(am,{className:r}):s==="skill"?e.jsx(im,{className:r}):s==="question"?e.jsx(pg,{className:r}):s.startsWith("git")?e.jsx(Ht,{className:r}):e.jsx($a,{className:r})},xj=(t,r,s=Date.now())=>{const o=(r?r-t:s-t)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},yj=({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:xj(t,r,n)})},bj=t=>{if(!t?.diff||typeof t.diff!="string")return null;const r=t.diff.split(`
102
- `);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}},ua=(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},wj=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},vj=(t,r,s,n)=>{const o=r,a=o.metadata,c=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"?ua(m,n,s):"Patch"}if(t.tool==="question"&&c?.questions&&Array.isArray(c.questions)){const d=c.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((t.tool==="edit"||t.tool==="multiedit")&&c){const d=c?.filePath||c?.file_path||c?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return ua(d,n,s)}if((t.tool==="read"||t.tool==="write")&&c){const d=c?.filePath||c?.file_path||c?.path;if(typeof d=="string")return ua(d,n,s)}if(t.tool==="bash"&&c?.command&&typeof c.command=="string"){const d=c.command.split(`
103
- `)[0];return s?d.substring(0,50):d.substring(0,100)}if(t.tool==="task"&&c?.description&&typeof c.description=="string")return s?c.description.substring(0,40):c.description.substring(0,80);if(t.tool==="skill"&&c?.name&&typeof c.name=="string")return c.name;const l=c?.description||a?.description||"title"in r&&r.title||"";return typeof l=="string"?l:""},xl=({children:t,maxHeightClass:r="max-h-[60vh]",className:s,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(gt,{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})}),jj=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"},Sj=t=>t.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),kj=({entries:t,isExpanded:r,hasPrevTool:s,hasNextTool:n,output:o,sessionId:a})=>{const c=fe(g=>g.setCurrentSession),l=i.useMemo(()=>t.filter(g=>g.state?.status==="completed"),[t]),d=typeof o=="string"?Sj(o):"",u=d.length>0,[m,f]=i.useState(!1),p=g=>{g.stopPropagation(),a&&c(a)};if(l.length===0&&!u&&!a)return null;const h=r?l:l.slice(-6),x=Math.max(0,l.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:[l.length>0?e.jsx(xl,{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=jj(g),S=Vl(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:qf(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(ha,{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",(l.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:g=>g.stopPropagation(),onClick:g=>{g.stopPropagation(),f(w=>!w)},children:[m?e.jsx(Ot,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Bs,{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(xl,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(cn,{content:d,variant:"tool"})})}):null]}):null]})},Nj=({diff:t,syntaxTheme:r,input:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Gf(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,c)=>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(Mr,{style:r,language:Pr(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})})]},c))})]},o))}),Cj=({content:t,syntaxTheme:r,filePath:s,displayPath:n})=>{const o=t.split(`
104
- `),a=Pr(s??"")||gl(t,"write",s?{filePath:s}:void 0),c=Math.max(o.length,1),l=c===1?"line 1":`lines 1-${c}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${l})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Mr,{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))})]})},Mj=({content:t,filePath:r,displayPath:s})=>{const n=il(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"}})})]})},Dj=({part:t,state:r,syntaxTheme:s,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:c})=>{const l=r,d=l.metadata,u=l.input,m=l.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?wo(x):!1,v=w?x?ua(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"?Kd(u,t.tool):typeof u.content=="string"?u.content??"":Kd(u,t.tool),[u,t.tool]),N=t.tool!=="apply_patch"&&S.trim().length>0,b=(A,j)=>e.jsx(xl,{maxHeightClass:j?.maxHeightClass,className:j?.className,disableHorizontal:j?.disableHorizontal,outerClassName:j?.outerClassName,children:A}),k=()=>{if(t.tool==="question"){if(r.status==="completed"&&f){const A=wj(p);if(A&&A.length>0)return b(e.jsx("div",{className:"space-y-2",children:A.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 A=hj(p,{unstyled:!0});return b(A??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(t.tool==="list"&&f){const A=mj(p,{unstyled:!0});return b(A??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 A=fj(p,n,{unstyled:!0});return b(A??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 A=pj(p,n,{unstyled:!0});return b(A??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(cn,{content:p,variant:"tool"})}));if((t.tool==="web-search"||t.tool==="websearch"||t.tool==="search_web")&&f){const A=gj(p,s,{unstyled:!0});return b(A??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(cn,{content:p,variant:"tool"})}));if(t.tool==="skill"&&f)return b(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(cn,{content:p,variant:"tool"})}));if((t.tool==="edit"||t.tool==="multiedit"||t.tool==="apply_patch")&&h)return b(e.jsx(Nj,{diff:h,syntaxTheme:s,input:u}),{className:"p-1"});if(f&&p.trim()){if(t.tool==="read"){const A=Ei(p,t.tool,d),j=A.split(`
105
- `),M=typeof u?.offset=="number"?u.offset:0,C=typeof u?.limit=="number"?u.limit:void 0,I=E=>E.trim().startsWith("(");return b(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:j.map((E,P)=>{const D=I(E),T=M+P+1,L=!D&&(C===void 0||P<C);return e.jsxs("div",{className:F("typography-code font-mono flex w-full min-w-0",D&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:L?T:""}),e.jsx("div",{className:"flex-1 min-w-0",children:D?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(Mr,{style:s,language:gl(A,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})})]},P)})}),{className:"p-1"})}return b(e.jsx(Mr,{style:s,language:gl(Ei(p,t.tool,d),t.tool,u),PreTag:"div",customStyle:{...ea.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Ei(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]",c?"before:bottom-[-0.6rem]":"before:bottom-0"),children:t.tool==="todowrite"||t.tool==="todoread"||t.tool==="question"?k():e.jsxs(e.Fragment,{children:[w&&y?e.jsx("div",{className:"my-1",children:b(e.jsx(Mj,{content:g,filePath:x,displayPath:v??"New file"}))}):w?e.jsx("div",{className:"my-1",children:b(e.jsx(Cj,{content:g,syntaxTheme:s,filePath:x,displayPath:v??"New file"}))}):N?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:"}),k()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})},yl=({part:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:c=!1,hasNextTool:l=!1})=>{const d=t.state,u=bt(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({}),N=i.useRef(t.id);if(N.current!==t.id&&(N.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,k=m?S.current.end??v?.end:v?.end,A=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(L=>typeof L=="object"&&L!==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,I=vj(t,d,o,u),E=Vl(t.tool).displayName,P=i.useContext(Gl),D=T=>{if(m||!P?.editor){s(t.id);return}let L;if((t.tool==="edit"||t.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(t.tool))&&(L=y?.filePath||y?.file_path||y?.path||w?.filePath||w?.file_path||w?.path),typeof L=="string"){T.stopPropagation();let V=L;L.startsWith("/")||(V=u.endsWith("/")?u+L:u+"/"+L),P.editor.openFile(V)}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:D,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:qf(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(Ot,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{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:[I&&e.jsx("span",{className:F("truncate",o&&"max-w-[120px]"),children:I}),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(yj,{start:b,end:typeof k=="number"?k:void 0,active:!!(m&&p&&typeof k!="number")})})]})]}),m&&(j.length>0||p||f||A)?e.jsx(kj,{entries:j,isExpanded:r,hasPrevTool:c,hasNextTool:l,output:typeof g.output=="string"?g.output:void 0,sessionId:A}):null,!m&&r?e.jsx(Dj,{part:t,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:c,hasNextTool:l}):null]})},Aj={thinking:{label:"Thinking",Icon:br},justification:{label:"Justification",Icon:Ml}},Ej=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
106
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
107
- `).trim(),Ij=t=>{if(!t)return"";const r=t.trim(),s=r.indexOf(`
108
- `),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},Kf=({text:t,variant:r,onContentChange:s,blockId:n})=>{const[o,a]=i.useState(!1),c=i.useMemo(()=>Ij(t),[t]),{label:l,Icon:d}=Aj[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(Ot,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:l})]}),c&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:c})})]}),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(gt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:t})})]})},Pj=({part:t,onContentChange:r,messageId:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>Ej(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Kf,{text:a,variant:"thinking",onContentChange:r,blockId:t.id||`${s}-reasoning`}):null},Tj=t=>typeof t!="string"||t.trim().length===0?"":t.split(`
109
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
110
- `).trim(),Fj=({part:t,messageId:r,onContentChange:s})=>{const n=t,o=n.text||n.content||"",a=i.useMemo(()=>Tj(o),[o]);return("time"in t?t.time:null)?.end?e.jsx(Kf,{text:a,variant:"justification",onContentChange:s,blockId:t.id||`${r}-justification`}):null},Rj=i.memo(Fj),Qd=6,Lj=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}),Yd=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},Oj=({parts:t,isExpanded:r,onToggle:s,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:c,onContentChange:l,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 A=u.current===!1;if(u.current=r,l?.("structural"),r&&A){h(M=>M+1),f(!0);const j=setTimeout(()=>f(!1),50);return()=>clearTimeout(j)}else f(!1)},[r,l]);const x=i.useMemo(()=>Lj(t),[t]),g=Yd(x),w=i.useMemo(()=>x.slice(-Qd),[x]),y=i.useMemo(()=>{const A=new Set;return w.forEach(j=>{j.part.id&&A.add(j.part.id)}),A},[w]),v=i.useMemo(()=>Yd(w),[w]),S=Math.max(0,x.length-Qd);if(x.length===0)return null;const N=r?x:w,b=r?g:v,k=S>0;return e.jsx(ar,{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",k&&"cursor-pointer"),onClick:k?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:k?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(On,{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(Ot,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})]}):e.jsx(On,{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..."]}),N.map((A,j)=>{const M=A.part.id||`group-part-${j}`,C=b[M],I=`${M}-exp${p}`,E=A.part.id?y.has(A.part.id):!1,P=m&&E;switch(A.kind){case"tool":return e.jsx(ar,{skipAnimation:P,children:e.jsx(yl,{part:A.part,isExpanded:a.has(M),onToggle:c,syntaxTheme:n,isMobile:o,onContentChange:l,hasPrevTool:C?.hasPrev??!1,hasNextTool:C?.hasNext??!1})},I);case"reasoning":return e.jsx(ar,{skipAnimation:P,children:e.jsx(Pj,{part:A.part,messageId:A.messageId,onContentChange:l})},I);case"justification":return e.jsx(ar,{skipAnimation:P,children:e.jsx(Rj,{part:A.part,messageId:A.messageId,onContentChange:l})},I);default:return null}})]})]})})},_j=i.memo(Oj),Qf=t=>{const r=t,s=r.text;return typeof s=="string"?s:r.content||r.value||""},Yf=t=>{if(t.type!=="text")return!1;const r=Qf(t);return!r||r.trim().length===0},$j=(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"))},Bj=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`},zj=new Set(["task"]),Go=t=>typeof t=="string"&&zj.has(t.toLowerCase()),Wj=({messageId:t,parts:r,isMobile:s,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:c,onShowPopup:l,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:!Yf(j)),[r]),g=d?.token;let w=!1;const y=!!a,v=!!c,S=!!(n??s),N=!!o,b=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),k=i.useCallback(()=>{!S||!y||!N||typeof window>"u"||(b(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[y,b,N,S]);i.useEffect(()=>{N||(p(!1),b())},[b,N]);const A=i.useCallback(j=>{!a||!N||(j.stopPropagation(),j.preventDefault(),a(),S&&k())},[N,S,a,k]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&y&&N?k: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&&Qf(j).includes(g)&&(C=d,w=!0),e.jsx(ar,{children:e.jsx(Zv,{part:j,messageId:t,isMobile:s,agentMention:C})},`user-text-${M}`)})}),e.jsx(If,{files:r,onShowPopup:l}),y&&N||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(Me,{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(Ln,{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(Me,{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(Ht,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Fork from here"})]}),y&&N&&e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(Me,{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:A,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(Gt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(it,{sideOffset:6,children:"Copy message"})]})]}):null]})},Hj=({messageId:t,parts:r,isMessageCompleted:s,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:c,hasTouchInput:l,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:N})=>{const[b,k]=i.useState(!1),A=i.useRef(null),j=!!g,M=!!w,C=!!(l??c),I=!s,E=i.useMemo(()=>r.filter(We=>!Yf(We)).filter(We=>We.type!=="compaction"),[r]),P=i.useMemo(()=>E.filter(We=>We.type==="tool"),[E]),D=i.useMemo(()=>E.filter(We=>We.type==="text"),[E]),T=fe(We=>We.createSessionFromAssistantMessage),L=Te(We=>We.openMultiRunLauncherWithPrompt),V=S?.isLastAssistantInTurn??!1,q=n==="stop",_=P.length>0,Y=i.useMemo(()=>P.some(We=>{const vt=(We.state??{})?.status;return vt==="pending"||vt==="running"||vt==="started"}),[P]),K=i.useCallback(We=>{const ut=We.state??{},vt=ut?.status;if(vt==="pending"||vt==="running"||vt==="started")return!1;const dt=ut?.time??{},Tt=typeof dt?.end=="number"?dt.end:void 0,Ct=typeof dt?.start=="number"?dt.start:void 0;return!(typeof Tt!="number"||typeof Ct=="number"&&Tt<Ct)},[]),U=i.useMemo(()=>P.length===0?!0:Y?!1:P.every(We=>K(We)),[P,Y,K]),Q=i.useMemo(()=>E.filter(We=>We.type==="reasoning"),[E]),z=i.useMemo(()=>Q.length===0?!0:Q.every(We=>typeof We.time?.end=="number"),[Q]),re=typeof n!="string",te=Q.length>0&&_&&(Y||re||!U),pe=I||_&&(Y||re||!U),R=I||te,ee=_||Q.length>0,B=D.length===0,W=ee&&B&&!pe&&!R&&U&&z,X=i.useRef(!1),ie=i.useRef(!1);i.useEffect(()=>{ie.current=!1},[t]),i.useEffect(()=>{if(!W){X.current=!1;return}X.current||(X.current=!0,y?.())},[W,y]),i.useEffect(()=>{if(I){ie.current=!1;return}if(_){ie.current=!1;return}Q.length!==0&&(R||!z||ie.current||(ie.current=!0,h?.("structural")))},[I,_,h,z,Q.length,R]);const be=!!x&&!I,H=i.useCallback(()=>{A.current!==null&&typeof window<"u"&&(window.clearTimeout(A.current),A.current=null)},[]),me=i.useCallback(()=>{!C||!j||!be||typeof window>"u"||(H(),k(!0),A.current=window.setTimeout(()=>{k(!1),A.current=null},1800))},[j,H,be,C]);i.useEffect(()=>{be||(k(!1),H())},[H,be]);const we=i.useCallback(We=>{!g||!be||(We.stopPropagation(),We.preventDefault(),g(),C&&me())},[be,C,g,me]),he=i.useCallback(We=>{We.stopPropagation(),We.preventDefault(),T&&T(t)},[T,t]),_e=i.useCallback(We=>{We.stopPropagation(),We.preventDefault();const ut=Wl(D);if(!ut.trim())return;const vt=`${ab}
111
-
112
- ${ut}`;L(vt)},[D,L]);i.useEffect(()=>()=>{H()},[H]);const se=i.useMemo(()=>{const We={},ut=P.filter(vt=>Go(vt.tool)||pe?!1:K(vt));return ut.forEach((vt,dt)=>{We[vt.id]={hasPrev:dt>0,hasNext:dt<ut.length-1}}),We},[P,pe,K]),J=i.useMemo(()=>S?.activityParts??[],[S]),ne=i.useMemo(()=>S?J.filter(We=>We.messageId===t):[],[J,t,S]),ke=i.useMemo(()=>S?S.activityGroupSegments.filter(We=>We.anchorMessageId===t):[],[t,S]),Z=i.useMemo(()=>{const We=new Map;return ne.forEach(ut=>{We.set(ut.part,ut)}),We},[ne]),xe=i.useMemo(()=>S?(v?J:J.filter(ut=>ut.kind==="tool")).filter(ut=>{if(ut.kind!=="tool")return!0;const vt=ut.part.tool;return!Go(vt)}):[],[J,v,S]),[de,je]=i.useState(!1);i.useEffect(()=>{if(!S)return;const We=S.activityGroupSegments.some(ut=>ut.afterToolPartId!==null);(xe.length>1||We&&xe.length>0)&&je(!0)},[S,xe.length]);const ae=!!(S&&de),Xe=!!(S&&ae&&xe.length>0&&ke.length>0),mt=i.useMemo(()=>P.filter(We=>Go(We.tool)),[P]),De=i.useMemo(()=>{const We=[],ut=dt=>{!S||!Xe||ke.filter(Tt=>(Tt.afterToolPartId??null)===dt).forEach(Tt=>{const Ct=v?Tt.parts:Tt.parts.filter(os=>os.kind==="tool");Ct.length!==0&&We.push(e.jsx(_j,{parts:Ct,isExpanded:S.isGroupExpanded,onToggle:S.toggleGroup,syntaxTheme:a,isMobile:c,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,diffStats:S.diffStats},`progressive-group-${Tt.id}`))})};ut(null),mt.forEach(dt=>{We.push(e.jsx(ar,{children:e.jsx(yl,{part:dt,isExpanded:d.has(dt.id),onToggle:u,syntaxTheme:a,isMobile:c,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${dt.id}`)),ut(dt.id)});const vt=[];return E.forEach((dt,Tt)=>{const Ct=Z.get(dt);if(!Ct||!S)return;let os=null,St=null;if(!ae){if(Ct.kind==="tool"){const Lt=dt;if(Go(Lt.tool))return;const Ut=Lt.state?.time,Rt=K(Lt);if(!(!pe&&Rt))return;const ye=se[Lt.id];St=e.jsx(ar,{children:e.jsx(yl,{part:Lt,isExpanded:d.has(Lt.id),onToggle:u,syntaxTheme:a,isMobile:c,onContentChange:h,hasPrevTool:ye?.hasPrev??!1,hasNextTool:ye?.hasNext??!1})},`tool-${Lt.id}`),os=Rt&&typeof Ut?.end=="number"?Ut.end:null}St&&vt.push({part:dt,index:Tt,endTime:os,element:St})}}),vt.sort((dt,Tt)=>dt.endTime===null&&Tt.endTime===null?dt.index-Tt.index:dt.endTime===null?1:Tt.endTime===null?-1:dt.endTime-Tt.endTime),vt.forEach(({element:dt})=>{We.push(dt)}),We},[Z,ke,d,c,K,h,m,u,pe,ae,v,a,se,S,E,mt,Xe]),oe=S?.turnId,Ue=fe(We=>We.currentSessionId),Se=Et(We=>{if(!oe||!Ue)return;const ut=We.messages.get(Ue);if(!ut)return;const vt=ut.find(Ct=>Ct.info?.id===oe);if(!vt)return;const Tt=vt.info.summary?.body;return typeof Tt=="string"&&Tt.trim().length>0?Tt:void 0}),Ne=typeof S?.summaryBody=="string"&&S.summaryBody.trim().length>0?S.summaryBody:Se,Ge=i.useRef(void 0);Ne&&Ne.trim().length>0&&(Ge.current=Ne);const rt=i.useRef(oe);rt.current!==oe&&(rt.current=oe,Ge.current=void 0);const Ke=Ge.current,Le=S?.isLastAssistantInTurn&&Ke&&Ke.trim().length>0,Ye=!!N,xt=V&&x&&(q||!!N),[nt,It]=i.useState(!1),Pt=i.useMemo(()=>{if(!V||!q)return;const We=S?.userMessageCreatedAt;if(!(typeof We!="number"||typeof o!="number")&&!(o<=We))return Bj(o-We)},[V,q,S?.userMessageCreatedAt,o]),zt=e.jsxs(e.Fragment,{children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(Me,{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:We=>We.stopPropagation(),onClick:he,children:e.jsx(hg,{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(Me,{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:We=>We.stopPropagation(),onClick:_e,children:e.jsx(jf,{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(Me,{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",!be&&"opacity-50"),disabled:!be,"aria-label":"Copy message text","aria-hidden":!be,onPointerDown:We=>We.stopPropagation(),onClick:we,onFocus:()=>{be&&k(!0)},onBlur:()=>{M||k(!1)},children:M?e.jsx(Gt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{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&&be?me: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:[De,Ye&&e.jsx(ar,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(cn,{content:N??""})})},"assistant-error"),Le&&e.jsx(ar,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>It(!0),onMouseLeave:()=>It(!1),children:[e.jsx(cn,{content:Ke}),xt&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Pt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(wc,{className:"h-3.5 w-3.5"}),Pt]}):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:zt})]})]})},"summary-body")]}),e.jsx(If,{files:r,onShowPopup:m}),!Le&&xt&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[Pt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(wc,{className:"h-3.5 w-3.5"}),Pt]}):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:zt})]})]})})},Uj=({isUser:t,...r})=>t?e.jsx(Wj,{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(Hj,{...r}),Xd=i.memo(Uj),Ii=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}},Vj=i.lazy(()=>bs(()=>import("./ToolOutputDialog-PTbkCnSK.js"),__vite__mapDeps([2,0,1,3,4]))),Gj=new Set(["task","edit","multiedit","write","bash"]),Jd=t=>typeof t=="string"&&Gj.has(t.toLowerCase());function Pi(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 mr=(t,r)=>{if(typeof t=="object"&&t!==null)return t[r]},qj=({message:t,previousMessage:r,nextMessage:s,onContentChange:n,animationHandlers:o,turnGroupingContext:a})=>{const{isMobile:c,hasTouchInput:l}=Qt(),{currentTheme:d}=Yr(),u=i.useRef(null),m=fe(El(Ce=>({lifecyclePhase:Ce.messageStreamStates.get(t.info.id)?.phase??null,isStreamingMessage:(()=>{const qe=t.info.sessionID??Ce.currentSessionId??null;return qe?(Ce.streamingMessageIds.get(qe)??null)===t.info.id:!1})(),currentSessionId:Ce.currentSessionId,getCurrentAgent:Ce.getCurrentAgent,getSessionAgentSelection:Ce.getSessionAgentSelection,getAgentModelForSession:Ce.getAgentModelForSession,getSessionModelSelection:Ce.getSessionModelSelection}))),{lifecyclePhase:f,isStreamingMessage:p,currentSessionId:h,getCurrentAgent:x,getSessionAgentSelection:g,getAgentModelForSession:w,getSessionModelSelection:y}=m,v=at(Ce=>Ce.providers),S=Te(Ce=>Ce.showReasoningTraces),N=Te(Ce=>Ce.toolCallExpansion);i.useEffect(()=>{h&&$r.getInstance().recordSessionStart(h)},[h]);const[b,k]=i.useState(null),[A,j]=i.useState(!1),[M,C]=i.useState(new Set),[I,E]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{C(new Set)},[t.info.id,N]);const D=i.useMemo(()=>Ii(t.info),[t.info]).isUser,T=i.useMemo(()=>D?t.parts.map(Ce=>Ce.type==="compaction"?{type:"text",text:"/compact"}:Ce):t.parts,[D,t.parts]),L=i.useMemo(()=>{if(D||!r)return null;const Ce=mr(r.info,"clientRole"),qe=mr(r.info,"role");if((typeof Ce=="string"?Ce:typeof qe=="string"?qe:void 0)!=="user")return null;const ot=mr(r.info,"mode"),_t=mr(r.info,"providerID"),$t=mr(r.info,"modelID"),wt=mr(r.info,"variant"),ge=typeof ot=="string"&&ot.trim().length>0?ot:void 0,Ee=typeof _t=="string"&&_t.trim().length>0?_t:void 0,st=typeof $t=="string"&&$t.trim().length>0?$t:void 0,$e=typeof wt=="string"&&wt.trim().length>0?wt:void 0;return!ge&&!Ee&&!st&&!$e?null:{agentName:ge,providerId:Ee,modelId:st,variant:$e}},[D,r]),V=i.useMemo(()=>{if(D)return;const Ce=mr(t.info,"mode");if(typeof Ce=="string"&&Ce.trim().length>0)return Ce;if(L?.agentName)return L.agentName;const qe=t.info.sessionID;if(!qe)return;const et=x(qe);return et||(g(qe)??void 0)},[D,t.info,L,x,g]),q=t.info.sessionID,_=D?null:mr(t.info,"providerID"),Y=D?null:mr(t.info,"modelID"),K=i.useMemo(()=>{if(D||!q)return null;if(L?.providerId&&L?.modelId)return{providerId:L.providerId,modelId:L.modelId};if(V){const qe=w(q,V);if(qe?.providerId&&qe?.modelId)return qe}const Ce=y(q);return Ce?.providerId&&Ce?.modelId?Ce:null},[D,q,V,L,w,y]),U=i.useMemo(()=>D?null:typeof _=="string"&&_.trim().length>0?_:K?.providerId??null,[D,_,K]),Q=i.useMemo(()=>D?null:typeof Y=="string"&&Y.trim().length>0?Y:K?.modelId??null,[D,Y,K]),z=i.useMemo(()=>{if(!D&&U&&Q&&v.length>0){const Ce=v.find(qe=>qe.id===U);if(Ce?.models&&Array.isArray(Ce.models)){const ot=Ce.models.find(_t=>_t.id===Q)?.name;return typeof ot=="string"?ot:void 0}}},[D,U,Q,v]),re=i.useMemo(()=>{if(D||!U||!Q)return!1;const Ce=v.find(ot=>ot.id===U);if(!Ce?.models||!Array.isArray(Ce.models))return!1;const et=Ce.models.find(ot=>ot.id===Q)?.variants;return!!(et&&Object.keys(et).length>0)},[D,Q,U,v]),te=Pi(V),pe=Pi(U??void 0),R=Pi(z),ee=te??void 0,B=pe??null,W=R??void 0,X=i.useMemo(()=>{const Ce=t.info.time;return typeof Ce?.completed=="number"?Ce.completed:null},[t.info.time]),ie=i.useMemo(()=>D?!0:!!(X&&X>0),[D,X]),be=i.useMemo(()=>{const Ce=t.info.finish;return typeof Ce=="string"?Ce:void 0},[t.info]),H=i.useMemo(()=>$j(T,{includeReasoning:S}),[T,S]),me=i.useMemo(()=>D||ie?H:[],[D,ie,H]),we=i.useMemo(()=>D?[]:H.filter(Ce=>Ce.type==="text"),[D,H]),he=i.useMemo(()=>D?[]:H.filter(qe=>qe.type==="tool"),[D,H]),_e=i.useMemo(()=>{if(N==="collapsed"||N==="activity")return M;const Ce=new Set;for(const et of he){const ot=et.tool;et.id&&Jd(ot)&&Ce.add(et.id)}if(a?.isFirstAssistantInTurn)for(const et of a.activityParts){if(et.kind!=="tool")continue;const ot=et.part;ot.id&&Jd(ot.tool)&&Ce.add(ot.id)}const qe=new Set(Ce);for(const et of M)qe.has(et)?qe.delete(et):qe.add(et);return qe},[M,N,he,a]),se=i.useMemo(()=>{if(!D)return;const Ce=t.parts.find(_t=>_t.type==="agent");if(!Ce)return;const qe=Ce,et=typeof qe.name=="string"?qe.name:void 0;if(!et)return;const ot=qe.source&&typeof qe.source.value=="string"&&qe.source.value.trim().length>0?qe.source.value:`#${et}`;return{name:et,token:ot}},[D,t.parts]),J=typeof be!="string",ne=i.useMemo(()=>D?!1:we.length===0||he.length===0?J:!0,[we.length,he.length,J,D]),ke=d?.metadata.variant,Z=i.useMemo(()=>ke?ke==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ke]),xe=i.useMemo(()=>d?lc(d):Z?qv:Kv,[d,Z]),de=i.useMemo(()=>D?!1:$r.getInstance().shouldAnimateMessage(t.info,h||t.info.sessionID),[t.info,h,D]),je=i.useRef(!1),ae=i.useMemo(()=>r?Ii(r.info):null,[r]),Xe=i.useMemo(()=>s?Ii(s.info):null,[s]),mt=i.useMemo(()=>D||!Xe?!1:!Xe.isUser&&Xe.role==="assistant",[D,Xe]),De=i.useMemo(()=>ie?"completed":f||(p?"streaming":"completed"),[ie,f,p]),oe=i.useMemo(()=>{if(D)return!0;const Ce=a?.headerMessageId;if(Ce){if(t.info.id===Ce){if(De==="completed")return!0;const et=De==="streaming"||De==="cooldown",ot=je.current;return et&&!ot&&(je.current=!0),ot||et}return!1}return ae?ae.isUser:!0},[D,ae,a,De,t.info]),Ue=i.useCallback(Ce=>{navigator.clipboard.writeText(Ce),k(Ce),setTimeout(()=>k(null),2e3)},[]),Se=a?.turnId,Ne=Et(Ce=>{if(!Se)return;const qe=t.info.sessionID;if(!qe)return;const et=Ce.messages.get(qe);if(!et)return;const ot=et.find(wt=>wt.info?.id===Se);if(!ot)return;const $t=ot.info.summary?.body;return typeof $t=="string"&&$t.trim().length>0?$t:void 0}),Ge=Et(Ce=>{if(!Se)return;const qe=t.info.sessionID;if(!qe)return;const et=Ce.messages.get(qe);if(!et)return;const ot=et.find($t=>$t.info?.id===Se);if(!ot)return;const _t=ot.info.variant;return typeof _t=="string"&&_t.trim().length>0?_t:void 0}),rt=D?void 0:Ge??L?.variant,Ke=!D&&re?rt??"Default":void 0,Le=typeof a?.summaryBody=="string"&&a.summaryBody.trim().length>0?a.summaryBody:Ne,Ye=i.useRef(void 0);Le&&Le.trim().length>0&&(Ye.current=Le);const xt=i.useRef(Se);xt.current!==Se&&(xt.current=Se,Ye.current=void 0);const nt=Ye.current,It=i.useMemo(()=>{if(D)return;const Ce=t.info?.error;if(!Ce)return;const qe=typeof Ce.data?.message=="string"?Ce.data.message:void 0,et=typeof Ce.message=="string"?Ce.message:void 0,ot=typeof Ce.name=="string"?Ce.name:void 0,_t=qe||et||ot;if(_t)return`Opencode failed to send message with error:
113
- \`${_t}\``},[D,t.info]),Pt=i.useMemo(()=>D?me.filter(et=>et.type==="text").map(et=>(et.text||et.content||"").trim()).filter(et=>et.length>0).join(`
114
- `).replace(/\n\s*\n+/g,`
115
- `):It&&It.trim().length>0?It:nt&&nt.trim().length>0?nt:Wl(me),[It,nt,me,D]),zt=Pt.length>0,We=i.useCallback(async Ce=>{if(!Ce)return!1;if(typeof navigator<"u"&&navigator.clipboard&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(Ce),!0}catch{}if(typeof document>"u")return!1;const qe=document.createElement("textarea");qe.value=Ce,qe.setAttribute("readonly",""),qe.style.position="fixed",qe.style.top="-1000px",qe.style.left="-1000px",document.body.appendChild(qe),qe.select(),qe.setSelectionRange(0,qe.value.length);const et=document.execCommand("copy");return document.body.removeChild(qe),et},[]),ut=i.useCallback(async()=>{await We(Pt)&&(j(!0),setTimeout(()=>j(!1),2e3))},[We,Pt]),vt=fe(Ce=>Ce.revertToMessage),dt=fe(Ce=>Ce.forkFromMessage),Tt=i.useCallback(()=>{!q||!t.info.id||vt(q,t.info.id)},[q,t.info.id,vt]),Ct=i.useCallback(()=>{!q||!t.info.id||dt(q,t.info.id)},[q,t.info.id,dt]),os=i.useCallback(Ce=>{C(qe=>{const et=new Set(qe);return et.has(Ce)?et.delete(Ce):et.add(Ce),et})},[]),St=o??null,Lt=i.useRef(!1),Ft=i.useRef(!1),Ut=i.useRef(!1),Rt=i.useRef(!1),qt=i.useRef(!1);i.useEffect(()=>{Ft.current=!1,Ut.current=!1,Rt.current=!1,qt.current=!1,Lt.current=!1},[t.info.id]);const ye=i.useCallback(()=>{D||Lt.current||(Lt.current=!0,n?.("structural"))},[D,n]),Ae=i.useCallback(Ce=>{Ce.image&&E(Ce)},[]),$=i.useCallback(Ce=>{E(qe=>({...qe,open:Ce}))},[]),ue=!!mr(t.info,"animationSettled"),ve=De==="streaming",Be=i.useMemo(()=>D?!1:H.some(Ce=>Ce.type==="reasoning"),[D,H]),ze=de&&!ue&&!ve,tt=!D&&de&&we.length>0&&!ne;return i.useEffect(()=>{if(St?.onStreamingCandidate){if(!tt){Ut.current&&(Be&&St?.onReasoningBlock?St.onReasoningBlock():St?.onReservationCancelled&&St.onReservationCancelled(),Ut.current=!1);return}qt.current||(qt.current=!0,St.onStreamingCandidate(),Ut.current=!0)}},[St,tt,Be]),i.useEffect(()=>{St?.onAnimationStart&&ze&&(Rt.current||(St.onAnimationStart(),Rt.current=!0))},[St,ze]),i.useEffect(()=>{if(D)return;const Ce=St?.onAnimatedHeightChange;if(!Ce||!(ze||tt))return;const et=u.current;if(!et)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Ce(et.getBoundingClientRect().height);return}let ot=null;const _t=wt=>{if(typeof window>"u"){Ce(wt);return}ot!==null&&window.cancelAnimationFrame(ot),ot=window.requestAnimationFrame(()=>{Ce(wt)})},$t=new ResizeObserver(wt=>{const ge=wt[0];ge&&_t(ge.contentRect.height)});return $t.observe(et),_t(et.getBoundingClientRect().height),()=>{ot!==null&&(window.cancelAnimationFrame(ot),ot=null),$t.disconnect()}},[ze,D,St,tt]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:F("group w-full",oe?"pt-6":"pt-0",D?"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:D?e.jsx(ar,{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(Xd,{messageId:t.info.id,parts:H,isUser:D,isMessageCompleted:ie,messageFinish:be,syntaxTheme:xe,isMobile:c,hasTouchInput:l,copiedCode:b,onCopyCode:Ue,expandedTools:M,onToggleTool:os,onShowPopup:Ae,streamPhase:De,allowAnimation:ze,onContentChange:n,shouldShowHeader:!1,hasTextContent:zt,onCopyMessage:ut,copiedMessage:A,showReasoningTraces:S,onAuxiliaryContentComplete:ye,agentMention:se,onRevert:Tt,onFork:D?Ct:void 0,errorMessage:It})})})}):e.jsxs("div",{className:"relative pl-4 ml-1",children:[oe&&e.jsx(Yv,{isUser:D,providerID:B,agentName:ee,modelName:W,variant:Ke,isDarkTheme:Z}),e.jsx(Xd,{messageId:t.info.id,parts:H,isUser:D,isMessageCompleted:ie,messageFinish:be,messageCompletedAt:X??void 0,syntaxTheme:xe,isMobile:c,hasTouchInput:l,copiedCode:b,onCopyCode:Ue,expandedTools:_e,onToggleTool:os,onShowPopup:Ae,streamPhase:De,allowAnimation:ze,onContentChange:n,shouldShowHeader:oe,hasTextContent:zt,onCopyMessage:ut,copiedMessage:A,onAuxiliaryContentComplete:ye,showReasoningTraces:S,agentMention:se,turnGroupingContext:a,errorMessage:It})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(Vj,{popup:I,onOpenChange:$,syntaxTheme:xe,isMobile:c})})]})},Kj=i.memo(qj),Qj=({diff:t,syntaxTheme:r,filePath:s})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Gf(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,c)=>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(Mr,{style:r,language:Pr(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})})]},c))})]},o))}),Yj=({content:t,syntaxTheme:r,filePath:s})=>{const n=t.split(`
116
- `),o=Pr(s??"")||"text",a=s?.split("/").pop()||"New file",c=Math.max(n.length,1),l=c===1?"line 1":`lines 1-${c}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${l})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Mr,{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))})]})},Xj=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(kr,{className:r}):s==="write"||s==="create"||s==="file_write"?e.jsx(om,{className:r}):s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?e.jsx(Ur,{className:r}):s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?e.jsx(Qi,{className:r}):e.jsx($a,{className:r})},Jj=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},Zj=({permission:t,onResponse:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:c}=fe(),{currentTheme:l}=Yr(),d=i.useMemo(()=>lc(l),[l]),u=async y=>{n(!0);try{await c(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=Jj(m),w=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),N=p("description"),b=p("cwd")||p("working_directory")||p("directory")||p("path"),k=h("timeout");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),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})]}),k&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",k,"ms"]}),S&&e.jsx("div",{children:e.jsx(Mr,{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"),N=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"})}),N&&e.jsx(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Qj,{diff:N,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Yj,{content:N,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",b=t.metadata.headers&&typeof t.metadata.headers=="object"?t.metadata.headers:void 0,k=p("body")||p("data")||p("payload"),A=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:N}),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(gt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Mr,{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)})})]}),k&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Mr,{language:typeof k=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof k=="object"?JSON.stringify(k,null,2):String(k)})})]}),(A||j)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[A&&e.jsxs("span",{children:["Timeout: ",A,"ms"]}),A&&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(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(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(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(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(un,{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:[Xj(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(Gt,{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(yr,{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(yr,{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(Zt,{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"})})]})]})})})},Ti="summary",e0=({question:t})=>{const{respondToQuestion:r,rejectQuestion:s}=fe(),[n,o]=i.useState("0"),[a,c]=i.useState(!1),[l,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===Ti,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 D=g.map((T,L)=>({value:String(L),label:T.header?.trim()||`Q${L+1}`}));return g.length>1&&D.push({value:Ti,label:"Summary"}),D},[g]),N=i.useCallback(D=>{if(!!f[D])return(h[D]??"").trim()||"(no answer)";const L=u[D]??[];return L.length>0?L.join(", "):"(no answer)"},[f,h,u]),b=!!v?.multiple,k=u[y]??[],A=!!f[y],j=i.useMemo(()=>{if(g.length===0)return!1;for(let D=0;D<g.length;D+=1){if(!!f[D]){if(!(h[D]??"").trim())return!1;continue}if((u[D]??[]).length===0)return!1}return!0},[f,h,g.length,u]),M=i.useCallback(()=>{const D=[];for(let T=0;T<g.length;T+=1){if(!!f[T]){const V=(h[T]??"").trim();D.push(V?[V]:[]);continue}D.push(u[T]??[])}return D},[f,h,g.length,u]),C=i.useCallback(D=>{v&&(p(T=>({...T,[y]:!1})),m(T=>{const L=T[y]??[];if(b){const q=L.includes(D)?L.filter(_=>_!==D):[...L,D];return{...T,[y]:q}}return{...T,[y]:[D]}}))},[y,v,b]),I=i.useCallback(()=>{p(D=>({...D,[y]:!0})),m(D=>({...D,[y]:[]}))},[y]),E=i.useCallback(async()=>{if(j){c(!0);try{const D=M();await r(t.sessionID,t.id,D),d(!0)}catch{}finally{c(!1)}}},[M,t.id,t.sessionID,j,r]),P=i.useCallback(async()=>{c(!0);try{await s(t.sessionID,t.id),d(!0)}catch{}finally{c(!1)}},[t.id,t.sessionID,s]);return l||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(un,{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(D=>{const T=n===D.value,L=D.value===Ti;return e.jsxs("button",{type:"button",onClick:()=>o(D.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:[L?e.jsx(am,{className:"h-3 w-3"}):null,D.label]},D.value)})}):null,w?e.jsx("div",{className:"space-y-2",children:g.map((D,T)=>{const L=N(T),V=L!=="(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:D.header||`Question ${T+1}`}),e.jsx("div",{className:F("typography-meta",V?"text-foreground":"text-muted-foreground/50 italic"),children:L})]},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((D,T)=>{const L=k.includes(D.label),V=/\(recommended\)/i.test(D.label);return e.jsx("button",{type:"button",onClick:()=>C(D.label),disabled:a,className:F("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",L?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5 shrink-0",children:L?e.jsx(gg,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(Yi,{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",L?"text-foreground font-medium":"text-foreground/80"),children:D.label}),V?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),D.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:D.description}):null]})]})},`${T}:${D.label}`)}),e.jsx("button",{type:"button",onClick:I,disabled:a,className:F("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",A?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vn,{className:F("h-3.5 w-3.5",A?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:F("typography-meta",A?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),A?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:D=>{if(D){D.style.height="auto";const T=20,L=T*2,V=T*4;D.style.height=`${Math.min(Math.max(D.scrollHeight,L),V)}px`}},value:h[y]??"",onChange:D=>{const T=D.target;T.style.height="auto";const L=20,V=L*2,q=L*4;T.style.height=`${Math.min(Math.max(T.scrollHeight,V),q)}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(Gt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:P,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(Zt,{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]})]})})})},t0=new Set(["task"]),Zd=t=>typeof t=="string"&&t0.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},r0=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}}},n0=t=>{const r=r0(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(N=>{if(!N)return;const b=typeof N.additions=="number"?N.additions:0,k=typeof N.deletions=="number"?N.deletions:0;(b!==0||k!==0)&&(S+=1),y+=b,v+=k}),S>0&&(s={additions:y,deletions:v,files:S})}let a=!1,c=!1;t.assistantMessages.forEach(y=>{y.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(c=!0)})});const l=[];let d=0;t.assistantMessages.forEach(y=>{const v=y.info.id;y.info.finish,y.parts.forEach(S=>{const N=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-activity-${d++}`;if(S.type==="tool"){const k=S.state?.time,A=typeof k?.end=="number"?k.end:void 0;l.push({id:N,turnId:t.turnId,messageId:v,kind:"tool",part:S,endedAt:A});return}if(S.type==="reasoning"){const b=S.text??S.content;if(typeof b!="string"||b.trim().length===0)return;const k=S.time,A=typeof k?.end=="number"?k.end:void 0;l.push({id:N,turnId:t.turnId,messageId:v,kind:"reasoning",part:S,endedAt:A});return}})});const u=[],m=new WeakMap;l.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 k=S.tool;if(Zd(k)){const A=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-task-${p.length+1}`;f.has(A)||(f.set(A,v),p.push(A)),x=A;return}}const N=m.get(S);if(!N)return;if(N.kind==="tool"){const k=N.part.tool;if(Zd(k))return}const b=h.get(x)??[];b.push(N),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,N=0;for(const b of t.assistantMessages){const k=v.get(b.info.id)??0;if(k>0&&!S&&(S=b.info.id),N+=k,N>=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:l,activityGroupSegments:u,hasTools:a,hasReasoning:c,summaryBody:r,diffStats:s}},o0=t=>{const{isWorking:r}=ac(),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,n0(g))}),x},[s]),[c,l]=i.useState(()=>new Map),d=Te(x=>x.toolCallExpansion),u=d==="activity"||d==="detailed";i.useEffect(()=>{l(new Map)},[d]);const m=i.useCallback(x=>{const g=c.get(x);return g||{isExpanded:u}},[c,u]),f=i.useCallback(x=>{l(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(V=>V.info.id===x))return;const y=a.get(g.turnId),v=y?.activityParts??[],S=y?.activityGroupSegments??[],N=!!y?.hasTools,b=!!y?.hasReasoning,k=y?.summaryBody,A=y?.diffStats,j=g.assistantMessages[0]?.info.id,M=x===j,C=g.assistantMessages[g.assistantMessages.length-1]?.info.id,I=x===C,E=j,P=m(g.turnId),D=r&&n===g.turnId,T=g.userMessage.info.time,L=typeof T?.created=="number"?T.created:void 0;return{turnId:g.turnId,isFirstAssistantInTurn:M,isLastAssistantInTurn:I,summaryBody:k,activityParts:v,activityGroupSegments:S,headerMessageId:E,hasTools:N,hasReasoning:b,diffStats:A,userMessageCreatedAt:L,isWorking:D,isGroupExpanded:P.isExpanded,toggleGroup:()=>f(g.turnId)}},[m,n,o,r,f,a]);return{turns:s,getTurnForMessage:p,getContextForMessage:h}},a0=({messages:t,permissions:r,questions:s,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:c,onLoadOlder:l,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=Rv(p.parts);return h===p.parts?p:{...p,parts:h}})},[t]),{getContextForMessage:m}=o0(u);return e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:c?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:l,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((f,p)=>e.jsx(Kj,{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(e0,{question:f},f.id)),r.map(f=>e.jsx(Zj,{permission:f},f.id))]}),e.jsx("div",{className:"flex-shrink-0",style:{height:"10vh"},"aria-hidden":"true"})]})},i0=i.memo(a0);function l0(...t){return r=>{t.forEach(s=>{typeof s=="function"?s(r):s&&typeof s=="object"&&(s.current=r)})}}const Xf=i.forwardRef(({orientation:t="vertical",offset:r=72,size:s=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:c,className:l,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={...c};return v["--scroll-shadow-size"]=`${s}px`,v},[s,c]),g=i.useCallback((v,S,N,b,k)=>{const A=`${b}${k.charAt(0).toUpperCase()}${k.slice(1)}Scroll`;S&&N?(v.dataset[A]="true",v.removeAttribute(`data-${b}-scroll`),v.removeAttribute(`data-${k}-scroll`)):(v.dataset[`${b}Scroll`]=String(S),v.dataset[`${k}Scroll`]=String(N),v.removeAttribute(`data-${b}-${k}-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 N=t==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&t==="vertical"&&(N=!1),g(v,S,N,t==="vertical"?"top":"left",t==="vertical"?"bottom":"right");const b=S&&N?"both":S?t==="vertical"?"top":"left":N?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(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null,b=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return y(),v.addEventListener("scroll",S,{passive:!0}),N?.observe(v),b?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",S),N?.disconnect(),b?.disconnect()}},[y]),e.jsx("div",{...u,ref:l0(f,m),className:l,"data-orientation":t,"data-scroll-shadow":h??!0,style:x,children:d})});Xf.displayName="ScrollShadow";const c0=160,d0=({containerRef:t})=>{const[r,s]=i.useState(!0),n=i.useRef(!0),o=i.useRef(!1),a=i.useRef(null),c=i.useRef(null),l=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,c.current=null,u.current=!1},[]),f=i.useCallback(N=>{const b=t.current;if(!b){m();return}c.current===null&&(c.current=N),u.current&&(d.current=b.scrollHeight-b.clientHeight);const k=Math.min(1,(N-c.current)/c0),A=1-Math.pow(1-k,3),j=l.current,M=d.current,C=j+(M-j)*A;if(b.scrollTop=C,k<1){a.current=window.requestAnimationFrame(f);return}b.scrollTop=M,m(),n.current&&(n.current=!1,s(!1))},[m,t,s]),p=i.useCallback((N,b)=>{const k=t.current;if(!k)return;const A=Math.max(0,N),j=b?.instant??!1,M=b?.followBottom??!1;if(o.current=!1,typeof window>"u"||j){m(),k.scrollTop=A;const I=A<=1;n.current!==I&&(n.current=I,s(I));return}if(M&&u.current&&a.current!==null)return;if(m(),Math.abs(A-k.scrollTop)<=.5){k.scrollTop=A;const I=A<=1;n.current!==I&&(n.current=I,s(I));return}l.current=k.scrollTop,d.current=A,c.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 N=t.current;if(!N)return;o.current&&a.current!==null&&m();const b=N.scrollTop<=1;n.current!==b&&(n.current=b,s(b))},[m,t]);return i.useEffect(()=>{const N=t.current;if(N)return N.addEventListener("wheel",x,{passive:!0}),N.addEventListener("touchstart",x,{passive:!0}),()=>{N.removeEventListener("wheel",x),N.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])},u0=typeof window<"u"?i.useLayoutEffect:i.useEffect,m0=200,f0=250,p0=.1,h0=({currentSessionId:t,sessionMessages:r,updateViewportAnchor:s,isSyncing:n,isMobile:o})=>{const a=i.useRef(null),c=d0({containerRef:a}),l=i.useCallback(()=>{const P=a.current;if(!P||P.clientHeight<=0)return 0;const D=P.clientHeight*p0;return Math.max(24,Math.min(200,D))},[]),[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()+m0},[]),S=i.useCallback(()=>{const P=a.current;return P?P.scrollHeight-P.scrollTop-P.clientHeight:0},[]),N=i.useCallback(P=>{w.current!==P&&(w.current=P,f(P))},[]),b=i.useCallback(P=>{const D=a.current;if(!D)return;const T=D.scrollHeight-D.clientHeight;v(),c.scrollToPosition(Math.max(0,T),P)},[v,c]),k=i.useCallback(()=>{const P=a.current;if(!P){u(!1);return}if(!(P.scrollHeight>P.clientHeight)){u(!1);return}const T=S();u(T>l())},[S,l]),A=i.useCallback((P,D)=>{a.current&&(v(),c.scrollToPosition(Math.max(0,P),D))},[v,c]),j=i.useCallback(P=>{a.current&&(N(!0),b(P),u(!1))},[b,N]),M=i.useCallback(P=>{const D=a.current;if(!D||!t)return;const T=Date.now(),L=T<x.current,V=T-g.current<=f0;c.handleScroll(),k();const q=D.scrollTop;P?.isTrusted&&!L&&V&&q<y.current&&w.current&&N(!1),w.current||S()<=l()&&N(!0),y.current=q;const{scrollTop:_,scrollHeight:Y,clientHeight:K}=D,U=(_+K/2)/Math.max(Y,1),Q=Math.floor(U*r.length);s(t,Q)},[t,S,l,c,r.length,N,k,s]);i.useEffect(()=>{const P=a.current;if(!P)return;const D=()=>{g.current=Date.now()};return P.addEventListener("scroll",M,{passive:!0}),P.addEventListener("wheel",D,{passive:!0}),P.addEventListener("touchmove",D,{passive:!0}),()=>{P.removeEventListener("scroll",M),P.removeEventListener("wheel",D),P.removeEventListener("touchmove",D)}},[M]),u0(()=>{if(!t||t===p.current)return;p.current=t,$r.getInstance().recordSessionStart(t),N(!0),u(!1),a.current&&(v(),b({instant:!0}))},[t,v,b,N]),i.useEffect(()=>{if(!w.current||n||!a.current)return;S()>l()&&(v(),b({instant:!0}))},[S,l,n,v,b,r]),i.useEffect(()=>{const P=a.current;if(!P||typeof ResizeObserver>"u")return;const D=new ResizeObserver(()=>{k(),w.current&&S()>l()&&b({instant:!0})});D.observe(P);const T=new MutationObserver(()=>{w.current&&S()>l()&&b({instant:!0})});return T.observe(P,{childList:!0,subtree:!0}),()=>{D.disconnect(),T.disconnect()}},[S,l,b,k]),i.useEffect(()=>{if(typeof window>"u"){k();return}const P=window.requestAnimationFrame(()=>{k()});return()=>{window.cancelAnimationFrame(P)}},[t,r.length,k]);const C=i.useRef(new Map),I=i.useCallback(()=>{k(),w.current&&S()>l()&&b({instant:!0})},[S,l,b,k]),E=i.useCallback(P=>{const D=C.current.get(P);if(D)return D;const T={onChunk:()=>{k(),w.current&&S()>l()&&b({instant:!0})},onComplete:()=>{k()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{k(),w.current&&S()>l()&&b({instant:!0})},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return C.current.set(P,T),T},[S,l,b,k]);return{scrollRef:a,handleMessageContentChange:I,getAnimationHandlers:E,showScrollButton:d,scrollToBottom:j,scrollToPosition:A,isPinned:m}};function g0(t){const s=Date.now()-t,n=Math.floor(s/1e3),o=Math.floor(n/60),a=Math.floor(o/60),c=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:c<7?`${c}d ago`:new Date(t).toLocaleDateString()}const x0=({open:t,onOpenChange:r,onScrollToMessage:s})=>{const n=fe(g=>g.currentSessionId),o=Et(g=>n?g.messages.get(n)||[]:[]),a=fe(g=>g.revertToMessage),c=fe(g=>g.forkFromMessage),l=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=>eu(w.parts).toLowerCase().includes(g))},[p,m]),x=async g=>{if(n){u(g);try{await c(n,g),await l(),r(!1)}finally{u(null)}}};return n?e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(vs,{children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ns,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(ir,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{placeholder:"Search messages...",value:m,onChange: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=eu(g.parts),y=g.info.time.created,v=g0(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 N=>{N.stopPropagation(),await a(n,g.info.id),r(!1)},children:e.jsx(Ln,{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:N=>{N.stopPropagation(),x(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ht,{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(Ln,{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(Ht,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function eu(t){const r=t.find(s=>s.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Jf=()=>{const{currentSessionId:t,messages:r,permissions:s,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:c,loadMoreMessages:l,updateViewportAnchor:d,sessionMemoryState:u,openNewSessionDraft:m,isSyncing:f,messageStreamStates:p,trimToViewportWindow:h,sessionActivityPhase:x,newSessionDraft:g}=fe(),{isTimelineDialogOpen:w,setTimelineDialogOpen:y}=Te(),v=i.useMemo(()=>t?o.get(t)??null:null,[t,o]),{isMobile:S}=Qt(),N=!!g?.open;i.useEffect(()=>{!t&&!N&&m()},[t,N,m]);const b=i.useMemo(()=>t?r.get(t)||[]:[],[t,r]),k=i.useMemo(()=>t?s.get(t)||[]:[],[t,s]),A=i.useMemo(()=>t?n.get(t)||[]:[],[t,n]);i.useMemo(()=>[...k,...A],[k,A]);const{scrollRef:j,handleMessageContentChange:M,getAnimationHandlers:C,showScrollButton:I,scrollToBottom:E,scrollToPosition:P,isPinned:D}=h0({currentSessionId:t,sessionMessages:b,updateViewportAnchor:d,isSyncing:f,isMobile:S}),L=!!i.useMemo(()=>t?u.get(t)??null:null,[t,u])?.hasMoreAbove,[V,q]=i.useState(!1);i.useEffect(()=>{q(!1)},[t]);const _=i.useCallback(async()=>{if(!t||V)return;const K=j.current,U=K?.scrollHeight??null,Q=K?.scrollTop??null;q(!0);try{if(await l(t,"up"),K&&U!==null&&Q!==null){const z=K.scrollHeight-U;P(Q+z,{instant:!0})}}finally{q(!1)}},[t,V,l,j,P]),Y=i.useCallback(K=>{const U=j.current;if(!U)return;const Q=U.querySelector(`[data-message-id="${K}"]`);if(Q){const z=U.getBoundingClientRect(),pe=Q.getBoundingClientRect().top-z.top+U.scrollTop-50;U.scrollTo({top:pe,behavior:"smooth"})}},[j]);return i.useEffect(()=>{if(!t||(r.has(t)?r.get(t)??[]:[]).length>0)return;(async()=>{try{await c(t)}finally{const z=x?.get(t)??"idle";(z==="busy"||z==="cooldown")&&D||(typeof window>"u"?E():window.requestAnimationFrame(()=>{E()}))}})()},[t,D,c,r,E,x]),!t&&!N?e.jsx("div",{className:"flex flex-col h-full bg-background",style:S?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(Ai,{})}):!t&&N?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(Ai,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Vo,{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(U=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Di,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Di,{className:"h-4 w-24"}),e.jsx(Di,{className:"h-20 w-full"})]})]},U))})}),e.jsx(Vo,{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(Ai,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Vo,{scrollToBottom:E})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style: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(Xf,{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(i0,{messages:b,permissions:k,questions:A,onMessageContentChange:M,getAnimationHandlers:C,hasMoreAbove:L,isLoadingOlder:V,onLoadOlder:_,scrollToBottom:E})})}),e.jsx(Hl,{containerRef:j})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[I&&b.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Me,{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(Gn,{className:"h-4 w-4"})})}),e.jsx(Vo,{scrollToBottom:E})]}),e.jsx(x0,{open:w,onOpenChange:y,onScrollToMessage:Y})]}):null};class Zf 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(Jl,{className:"w-full max-w-md",children:[e.jsx(gf,{className:"text-center",children:e.jsxs(xf,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(xg,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(yf,{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(Me,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Is,{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 fo=()=>{const t=fe(r=>r.currentSessionId);return e.jsx(Zf,{sessionId:t||void 0,children:e.jsx(Jf,{})})},tu=12,y0=[{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=y0,onComplete:a})=>{const c=Pe.useRef(!1);Pe.useEffect(()=>{!t&&c.current&&a?.(),t&&(c.current=!0)},[t,a]);const l=Pe.useMemo(()=>Array.from({length:tu},(d,u)=>{const m=Math.PI*2*u/tu;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:l.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},w0=({durationMs:t=3400}={})=>{const[r,s]=Pe.useState({isActive:!1,cycle:0}),n=Pe.useRef(null),o=Pe.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Pe.useCallback(()=>{o(),s(l=>l.isActive?{...l,isActive:!1}:l)},[o]),c=Pe.useCallback(()=>{o(),s(l=>({isActive:!0,cycle:l.cycle+1})),n.current=window.setTimeout(()=>{s(l=>l.isActive?{...l,isActive:!1}:l),n.current=null},t)},[o,t]);return Pe.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:c,dismissFireworks:a}},ep=i.createContext(void 0),su=({children:t})=>{const{isActive:r,burstKey:s,triggerFireworks:n,dismissFireworks:o}=w0(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(ep.Provider,{value:a,children:[t,e.jsx(b0,{isActive:r,burstKey:s})]})},v0=()=>{const t=i.useContext(ep);if(!t)throw new Error("useFireworksCelebration must be used within FireworksProvider");return t},Wn=ns()(cs(Ws((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 zy();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 Gy();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 Vy();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(ls()){const o=await Ir();n=s(o?.defaultGitIdentityId)}else{const o=As()?.settings;if(o)try{const c=(await o.load())?.settings||{};n=s(c.defaultGitIdentityId)}catch{}if(n===null)try{const a=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(a.ok){const c=await a.json().catch(()=>null);n=s(c?.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 us({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 Wy(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(c=>c.id===s);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Hy(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 Uy(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:Hs(()=>hs()),partialize:t=>({selectedProfileId:t.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Wn);const j0=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),S0=({currentBranch:t,localBranches:r,remoteBranches:s,branchInfo:n,onCheckout:o,onCreate:a,disabled:c=!1})=>{const[l,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(()=>j0(h),[h]),S=i.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(C=>C.toLowerCase().includes(M)):r},[u,r]),N=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("")},k=()=>{p(!0),setTimeout(()=>y.current?.focus(),50)},A=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(()=>{l||(m(""),p(!1),x(""))},[l]),e.jsxs(es,{open:l,onOpenChange:d,children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:c,children:[e.jsx(Ht,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:t||"Detached HEAD"}),e.jsx(Ot,{className:"size-4 opacity-60"})]})})}),e.jsxs(it,{sideOffset:8,children:["Switch branch (",r.length," local · ",s.length," remote)"]})]}),e.jsx(ss,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Zl,{className:"h-full min-h-0",children:[e.jsx(ec,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(tc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(sc,{children:"No branches found."}),e.jsx(an,{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(),A()):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:A,disabled:!v||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(is,{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(Zt,{className:"size-4"})})]}):e.jsxs(gs,{onSelect:k,children:[e.jsx(is,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Aa,{}),e.jsxs(an,{heading:"Local branches",children:[S.map(M=>e.jsxs(gs,{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(gs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Aa,{}),e.jsxs(an,{heading:"Remote branches",children:[N.map(M=>e.jsx(gs,{onSelect:()=>b(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),N.length===0&&e.jsx(gs,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},k0=t=>t.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),N0=({currentBranch:t,onRename:r})=>{const[s,n]=i.useState(!1),[o,a]=i.useState(t||""),[c,l]=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=k0(o);if(h===t){n(!1);return}l(!0);try{await r(t,h),n(!1),a("")}finally{l(!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(Ht,{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:c,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(Gt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:c,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Zt,{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(Ht,{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(Me,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(Vn,{className:"size-4"})})]})},C0=({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(Me,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[t==="fetch"?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(zr,{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(Me,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[t==="pull"?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(Gn,{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(Me,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[t==="push"?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(jo,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(it,{sideOffset:8,children:"Push changes"})]})]})},M0={branch:Ht,briefcase:Tl,house:Pl,graduation:Il,code:Ks,heart:lm,user:Qs},D0={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 tp(t){return t&&D0[t]||"var(--primary)"}const ru=({icon:t,className:r,colorToken:s})=>{const n=M0[t??"branch"]??Qs;return e.jsx(n,{className:r,style:{color:tp(s)}})},A0=({activeProfile:t,identities:r,onSelect:s,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(es,{children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ts,{asChild:!0,children:e.jsxs(Me,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:tp(t?.color)},disabled:o,children:[n?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(ru,{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(Ot,{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(ss,{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(Nt,{onSelect:()=>s(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ru,{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))})]})},E0=({status:t,localBranches:r,remoteBranches:s,branchInfo:n,syncAction:o,onFetch:a,onPull:c,onPush:l,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(N0,{currentBranch:t.current,onRename:m}):e.jsx(S0,{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(jo,{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(Gn,{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(C0,{syncAction:o,onFetch:a,onPull:c,onPush:l,disabled:!t}),e.jsx("div",{className:"flex-1"}),e.jsx(A0,{activeProfile:f,identities:p,onSelect:h,isApplying:x})]}):null,I0=({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(kl,{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(Me,{variant:"outline",onClick:r,disabled:s,children:[s?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(Gn,{className:"size-4"}),"Pull ",t," commit",t===1?"":"s"]})]}),sp={"?":{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"}},P0=sp.M;function T0(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 F0(t){const r=T0(t);return sp[r]??P0}const R0=i.memo(function({file:r,checked:s,onToggle:n,onViewDiff:o,onRevert:a,isReverting:c,stats:l}){const d=Pe.useMemo(()=>F0(r),[r]),u=d.description,m=l?.insertions??0,f=l?.deletions??0,p=Pe.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=Pe.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),x=Pe.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(Dl,{className:"size-4 text-primary"}):e.jsx(Al,{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:c,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:c?e.jsx(Jt,{className:"size-3.5 animate-spin"}):e.jsx(Ln,{className:"size-3.5"})})}),e.jsx(it,{sideOffset:8,children:"Revert changes"})]})]})})}),L0=({changeEntries:t,selectedPaths:r,diffStats:s,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:c,onViewDiff:l,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(Me,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Me,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:c,disabled:u===0,children:"None"})]})]})]}),e.jsx(gt,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:t.map(f=>e.jsx(R0,{file:f,checked:r.has(f.path),stats:s?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>l(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function pn({className:t,variant:r,...s}){return e.jsx(Me,{variant:r,size:"sm",className:F("h-7 px-2 py-0",t),...s})}const Fi=38,nu=200,O0=({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=`${Fi}px`;const c=Math.min(Math.max(a.scrollHeight,Fi),nu);a.style.height=`${c}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:Fi,maxHeight:nu}})},_0=({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(Me,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(Gn,{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))})]})},$0=({selectedCount:t,commitMessage:r,onCommitMessageChange:s,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:c,isGeneratingMessage:l,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(ko,{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(No,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(_0,{highlights:n,onInsert:o,onClear:a}),e.jsx(O0,{value:r,onChange:s,placeholder:"Commit message",disabled:m!==null}),p&&e.jsxs(Me,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[e.jsx(yg,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:c,disabled:l||m!==null||t===0||f,"aria-label":"Generate commit message",children:l?e.jsx(Jt,{className:"size-4 animate-spin"}):e.jsx(tm,{className:"size-4 text-primary"})})}),e.jsx(it,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(pn,{variant:"outline",onClick:d,disabled:!g||l,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kl,{className:"size-4"}),"Commit"]})}),e.jsx(pn,{variant:"default",onClick:u,disabled:!g||l,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(jo,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function ou(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 B0(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 z0=({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:ou(t.date),children:ou(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(Me,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:c=>{c.stopPropagation(),a(t.hash)},children:e.jsx(Ys,{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(Jt,{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(c=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:F("font-semibold w-3 text-center",B0(c.changeType)),children:c.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:c.path,children:c.path}),!c.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",c.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",c.deletions]})]}),c.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},c.path))})})]}),W0=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],H0=({log:t,isLogLoading:r,logMaxCount:s,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:c,loadingCommitHashes:l,onCopyHash:d})=>{const[u,m]=i.useState(!0);return t?e.jsxs(ko,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Ka,{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(Ls,{value:String(s),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Os,{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(fn,{placeholder:"Commits"})}),e.jsx(_s,{children:W0.map(f=>e.jsx(rs,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Oa,{className:"size-4 text-muted-foreground"}):e.jsx(Ot,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(No,{children:e.jsx(gt,{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(z0,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:c.get(f.hash)??[],isLoadingFiles:l.has(f.hash),onCopyHash:d},f.hash))})})})]}):null},rp="gitmojiCache",U0=1e3*60*60*24*7,np="1",V0="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",au={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:"},op=t=>{if(!t||typeof t!="object")return!1;const r=t;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},G0=()=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(rp);if(!t)return null;const r=JSON.parse(t);return!r||r.version!==np||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(op),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},q0=t=>{if(!(typeof window>"u"))try{const r={gitmojis:t,fetchedAt:Date.now(),version:np};localStorage.setItem(rp,JSON.stringify(r))}catch{return}},K0=t=>Date.now()-t.fetchedAt<U0,Q0=(t,r)=>{const s=t.toLowerCase(),n=/^([a-z]+)(?:\(.*\))?!?:/,o=s.match(n);if(o){const l=o[1],d=au[l];if(d)return r.find(u=>u.code===d)||null}const a=s.split(" ")[0],c=au[a];return c&&r.find(l=>l.code===c)||null};let to=null;const Y0=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=fe(),{currentDirectory:n}=bt(),o=t?s.get(t)??void 0:void 0,c=r.find(l=>l.id===t)?.directory;return o?.path??c??n??void 0},X0=()=>{const{git:t}=Tr(),r=Y0(),{currentSessionId:s,worktreeMetadata:n}=fe(),o=s?n.get(s)??void 0:void 0,{profiles:a,globalIdentity:c,defaultGitIdentityId:l,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=Wn(),f=Ul(r??null),p=nf(r??null),h=of(r??null),x=$b(r??null),g=Bb(r??null),w=as(ye=>ye.isLoadingStatus),y=as(ye=>ye.isLoadingLog),{setActiveDirectory:v,fetchAll:S,fetchStatus:N,fetchBranches:b,fetchLog:k,fetchIdentity:A,setLogMaxCount:j}=as(),M=i.useMemo(()=>!to||to.directory!==r?null:to,[r]),C=at(ye=>ye.settingsGitmojiEnabled),[I,E]=i.useState(M?.commitMessage??""),[P,D]=i.useState(!1),[T,L]=i.useState(null),[V,q]=i.useState(null),[_,Y]=i.useState(25),[K,U]=i.useState(!1),{triggerFireworks:Q}=v0(),z=i.useRef(new Map),re=i.useRef(0),te=i.useCallback(()=>{re.current+=1,U(!0)},[]),pe=i.useCallback(()=>{re.current=Math.max(0,re.current-1),re.current===0&&U(!1)},[]),[R,ee]=i.useState(()=>new Set(M?.selectedPaths??[])),[B,W]=i.useState(!1),[X,ie]=i.useState(new Set),[be,H]=i.useState(!1),[me,we]=i.useState([]),he=i.useCallback(()=>{we([])},[]),[_e,se]=i.useState(new Set),[J,ne]=i.useState(new Map),[ke,Z]=i.useState(new Set),[xe,de]=i.useState(null),[je,ae]=i.useState([]),[Xe,mt]=i.useState(""),De=i.useCallback(ye=>{navigator.clipboard.writeText(ye).then(()=>{G.success("Commit hash copied")}).catch(()=>{G.error("Failed to copy")})},[]),oe=i.useCallback(ye=>{se(Ae=>{const $=new Set(Ae);return $.has(ye)?$.delete(ye):$.add(ye),$})},[]);i.useEffect(()=>{if(!r||!t)return;const ye=Array.from(_e).filter(Ae=>!J.has(Ae)&&!ke.has(Ae));if(ye.length!==0){Z(Ae=>{const $=new Set(Ae);for(const ue of ye)$.add(ue);return $});for(const Ae of ye)t.getCommitFiles(r,Ae).then($=>{ne(ue=>new Map(ue).set(Ae,$.files))}).catch($=>{console.error("Failed to fetch commit files:",$),ne(ue=>new Map(ue).set(Ae,[]))}).finally(()=>{Z($=>{const ue=new Set($);return ue.delete(Ae),ue})})}},[_e,r,t,J,ke]),i.useEffect(()=>()=>{if(!r){to=null;return}to={directory:r,selectedPaths:Array.from(R),commitMessage:I}},[I,r,R]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!t?.getRemoteUrl){de(null);return}t.getRemoteUrl(r).then(de).catch(()=>de(null))},[r,t]),i.useEffect(()=>{if(!C){ae([]);return}let ye=!1;const Ae=G0();return Ae&&(ae(Ae.gitmojis),K0(Ae))?()=>{ye=!0}:((async()=>{try{const ue=await fetch(V0);if(!ue.ok)throw new Error(`Failed to load gitmojis: ${ue.statusText}`);const ve=await ue.json(),Be=Array.isArray(ve.gitmojis)?ve.gitmojis.filter(op):[];ye||(ae(Be),q0(Be))}catch(ue){ye||console.warn("Failed to load gitmoji list:",ue)}})(),()=>{ye=!0})},[C]),i.useEffect(()=>{r&&(v(r),as.getState().directories.get(r)?.status||S(r,t,{force:!0}))},[r,v,S,t]);const Ue=i.useCallback(async(ye=!0)=>{if(r)try{await Promise.all([N(r,t),b(r,t)])}catch(Ae){if(ye){const $=Ae instanceof Error?Ae.message:"Failed to refresh repository state";G.error($)}}},[r,t,N,b]),Se=i.useCallback(async()=>{r&&await k(r,t,_)},[r,t,k,_]),Ne=i.useCallback(async()=>{r&&await A(r,t)},[r,t,A]);i.useEffect(()=>{if(!r||!t?.hasLocalIdentity||f!==!0)return;const ye=typeof l=="string"?l.trim():"";if(!ye||ye==="global"||z.current.get(r)===ye)return;let $=!1;return(async()=>{try{const ve=await t.hasLocalIdentity?.(r);if($||ve===!0)return;te(),await t.setGitIdentity(r,ye),z.current.set(r,ye),await Ne()}catch(ve){console.warn("Failed to auto-apply default git identity:",ve)}finally{$||pe()}})(),()=>{$=!0}},[te,r,l,pe,t,f,Ne]);const Ge=i.useMemo(()=>{if(!p)return[];const ye=p.files??[],Ae=new Map;for(const $ of ye)Ae.set($.path,$);return Array.from(Ae.values()).sort(($,ue)=>$.path.localeCompare(ue.path))},[p]);i.useEffect(()=>{if(!p||Ge.length===0){ee(new Set),W(!1);return}ee(ye=>{const Ae=new Set,$=ye??new Set;for(const ue of Ge)$.has(ue.path)?Ae.add(ue.path):B||Ae.add(ue.path);return Ae})},[p,Ge,B]);const rt=async ye=>{if(r){L(ye);try{if(ye==="fetch")await t.gitFetch(r),G.success("Fetched latest updates");else if(ye==="pull"){const Ae=await t.gitPull(r);G.success(`Pulled ${Ae.files.length} file${Ae.files.length===1?"":"s"}`)}else ye==="push"&&(await t.gitPush(r),G.success("Pushed to remote"));await Ue(!1),await Se()}catch(Ae){const $=Ae instanceof Error?Ae.message:`Failed to ${ye==="pull"?"pull":ye}`;G.error($)}finally{L(null)}}},Ke=async(ye={})=>{if(!r)return;if(!I.trim()){G.error("Please enter a commit message");return}const Ae=Array.from(R).sort();if(Ae.length===0){G.error("Select at least one file to commit");return}const $=ye.pushAfter?"commitAndPush":"commit";q($);try{await t.createGitCommit(r,I.trim(),{files:Ae}),G.success("Commit created successfully"),E(""),ee(new Set),W(!1),he(),await Ue(),ye.pushAfter?(await t.gitPush(r),G.success("Pushed to remote"),Q(),await Ue(!1)):await Ue(!1),await Se()}catch(ue){const ve=ue instanceof Error?ue.message:"Failed to create commit";G.error(ve)}finally{q(null)}},Le=i.useCallback(async()=>{if(r){if(R.size===0){G.error("Select at least one file to describe");return}H(!0);try{const{message:ye}=await t.generateCommitMessage(r,Array.from(R)),Ae=ye.subject?.trim()??"",$=Array.isArray(ye.highlights)?ye.highlights:[];if(Ae){let ue=Ae;if(C&&je.length>0){const ve=Q0(Ae,je);if(ve){const{code:Be,emoji:ze}=ve;!Ae.startsWith(Be)&&!Ae.startsWith(ze)&&(ue=`${Be} ${Ae}`)}}E(ue)}we($),G.success("Commit message generated")}catch(ye){const Ae=ye instanceof Error?ye.message:"Failed to generate commit message";G.error(Ae)}finally{H(!1)}}},[r,R,t,C,je]),Ye=async ye=>{if(!r||!p)return;const Ae=p.current??null;try{await t.createBranch(r,ye,Ae??"HEAD"),G.success(`Created branch ${ye}`);let $=!1;try{await t.checkoutBranch(r,ye),await t.gitPush(r,{remote:"origin",branch:ye,options:["--set-upstream"]}),$=!0}catch(ue){const ve=ue instanceof Error?ue.message:"Unable to push new branch to origin.";G.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",ve]})})}finally{if(Ae)try{await t.checkoutBranch(r,Ae)}catch(ue){console.warn("Failed to restore original branch after creation:",ue)}}await Ue(),await Se(),$&&G.success(`Upstream set for ${ye}`)}catch($){const ue=$ instanceof Error?$.message:"Failed to create branch";throw G.error(ue),$}},xt=async(ye,Ae)=>{if(r)try{await t.renameBranch(r,ye,Ae),G.success(`Renamed branch ${ye} to ${Ae}`),await Ue(),await Se()}catch($){const ue=$ instanceof Error?$.message:`Failed to rename branch ${ye} to ${Ae}`;G.error(ue)}},nt=async ye=>{if(!r)return;const Ae=ye.replace(/^remotes\//,"");if(p?.current!==Ae)try{await t.checkoutBranch(r,Ae),G.success(`Checked out ${Ae}`),await Ue(),await Se()}catch($){const ue=$ instanceof Error?$.message:`Failed to checkout ${Ae}`;G.error(ue)}},It=async ye=>{if(r){te();try{await t.setGitIdentity(r,ye.id),G.success(`Applied "${ye.name}" to repository`),await Ne()}catch(Ae){const $=Ae instanceof Error?Ae.message:"Failed to apply git identity";G.error($)}finally{pe()}}},Pt=i.useMemo(()=>h?.all?h.all.filter(ye=>!ye.startsWith("remotes/")).sort():[],[h]),zt=i.useMemo(()=>h?.all?h.all.filter(ye=>ye.startsWith("remotes/")).map(ye=>ye.replace(/^remotes\//,"")).sort():[],[h]),We=i.useMemo(()=>{const ye=new Map;c&&ye.set(c.id,c);let Ae=null;if(xe)try{let $=xe.trim();$.startsWith("git@")&&($=`https://${$.slice(4).replace(":","/")}`),$.endsWith(".git")&&($=$.slice(0,-4));const ue=new URL($);Ae=ue.hostname+ue.pathname}catch{}for(const $ of a){if($.authType!=="token"){ye.set($.id,$);continue}const ue=$.host;if(!ue){ye.set($.id,$);continue}if(!ue.includes("/")){ye.set($.id,$);continue}Ae&&Ae===ue&&ye.set($.id,$)}return Array.from(ye.values())},[a,c,xe]),ut=i.useMemo(()=>{if(g?.userName&&g?.userEmail){const ye=a.find(Ae=>Ae.userName===g.userName&&Ae.userEmail===g.userEmail);return ye||(c&&c.userName===g.userName&&c.userEmail===g.userEmail?c:{id:"local-config",name:g.userName,userName:g.userName,userEmail:g.userEmail,sshKey:g.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return c??null},[g,a,c]),vt=Ge.length,dt=R.size,Tt=w||T!==null||V!==null,Ct=vt>0,os=ye=>{ee(Ae=>{const $=new Set(Ae);return $.has(ye)?$.delete(ye):$.add(ye),$}),W(!0)},St=()=>{const ye=new Set(Ge.map(Ae=>Ae.path));ee(ye),W(!0)},Lt=()=>{ee(new Set),W(!0)},Ft=i.useCallback(async ye=>{if(r){ie(Ae=>{const $=new Set(Ae);return $.add(ye),$});try{await t.revertGitFile(r,ye),G.success(`Reverted ${ye}`),await Ue(!1)}catch(Ae){const $=Ae instanceof Error?Ae.message:"Failed to revert changes";G.error($)}finally{ie(Ae=>{const $=new Set(Ae);return $.delete(ye),$})}}},[r,Ue,t]),Ut=i.useCallback(()=>{if(me.length===0)return;const ye=me.map(Ae=>Ae.trim()).filter(Boolean);if(ye.length===0){he();return}E(Ae=>{const $=Ae.trim(),ue=$.length>0?`
117
-
118
- `:"";return`${$}${ue}${ye.join(`
119
- `)}`.trim()})},[me,he]),Rt=i.useCallback((ye,Ae)=>{const $=Ae||ye;E(ue=>{const ve=ue.trimStart();return ve.startsWith(ye)||Ae&&ve.startsWith(Ae)?ue:`${$.endsWith(" ")?$:`${$} `}${ue}`.trimStart()}),mt(""),D(!1)},[]),qt=i.useCallback(ye=>{Y(ye),r&&(j(r,ye),k(r,t,ye))},[r,j,k,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(Jt,{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(Ht,{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(E0,{status:p,localBranches:Pt,remoteBranches:zt,branchInfo:h?.branches,syncAction:T,onFetch:()=>rt("fetch"),onPull:()=>rt("pull"),onPush:()=>rt("push"),onCheckoutBranch:nt,onCreateBranch:Ye,onRenameBranch:xt,activeIdentityProfile:ut,availableIdentities:We,onSelectIdentity:It,isApplyingIdentity:K,isWorktreeMode:!!o}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[Ct?e.jsx(L0,{changeEntries:Ge,selectedPaths:R,diffStats:p?.diffStats,revertingPaths:X,onToggleFile:os,onSelectAll:St,onClearSelection:Lt,onViewDiff:ye=>Te.getState().navigateToDiff(ye),onRevertFile:Ft}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(I0,{behind:p?.behind??0,onPull:()=>rt("pull"),isPulling:T==="pull"})}),Ge.length>0&&e.jsx($0,{selectedCount:dt,commitMessage:I,onCommitMessageChange:E,generatedHighlights:me,onInsertHighlights:Ut,onClearHighlights:he,onGenerateMessage:Le,isGeneratingMessage:be,onCommit:()=>Ke({pushAfter:!1}),onCommitAndPush:()=>Ke({pushAfter:!0}),commitAction:V,isBusy:Tt,gitmojiEnabled:C,onOpenGitmojiPicker:()=>D(!0)})]}),e.jsx(H0,{log:x,isLogLoading:y,logMaxCount:_,onLogMaxCountChange:qt,expandedCommitHashes:_e,onToggleCommit:oe,commitFilesMap:J,loadingCommitHashes:ke,onCopyHash:De})]})}),e.jsx(xs,{open:P,onOpenChange:D,children:e.jsxs(ys,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(vs,{className:"px-4 pt-4",children:e.jsx(js,{children:"Pick a gitmoji"})}),e.jsxs(Zl,{className:"h-[420px]",children:[e.jsx(ec,{placeholder:"Search gitmojis...",value:Xe,onValueChange:mt}),e.jsxs(tc,{children:[e.jsx(sc,{children:"No gitmojis found."}),e.jsx(an,{children:(je.length===0?[]:je.filter(ye=>{const Ae=Xe.trim().toLowerCase();return Ae?ye.emoji.includes(Ae)||ye.code.toLowerCase().includes(Ae)||ye.description.toLowerCase().includes(Ae):!0})).map(ye=>e.jsxs(gs,{onSelect:()=>Rt(ye.emoji,ye.code),children:[e.jsx("span",{className:"text-lg",children:ye.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:ye.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:ye.description})]},ye.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."})})},J0=1e6;function Zr(t){let r=t.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const qo=t=>({directory:t,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),iu=ns((t,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:s=>{const n=Zr(s);return r().sessions.get(n)},setTerminalSession:(s,n)=>{const o=Zr(s);t(a=>{const c=new Map(a.sessions),l=c.get(o),u=!l||l.terminalSessionId!==n.sessionId?qo(o):l??qo(o);return c.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:c}})},setConnecting:(s,n)=>{const o=Zr(s);t(a=>{const c=new Map(a.sessions),l=c.get(o)??qo(o);return c.set(o,{...l,isConnecting:n,updatedAt:Date.now()}),{sessions:c}})},appendToBuffer:(s,n)=>{if(!n)return;const o=Zr(s);t(a=>{const c=new Map(a.sessions),l=c.get(o)??qo(o),d=a.nextChunkId,u={id:d,data:n},m=[...l.bufferChunks,u];let f=l.bufferLength+n.length;for(;f>J0&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return c.set(o,{...l,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:c,nextChunkId:d+1}})},clearTerminalSession:s=>{const n=Zr(s);t(o=>{const a=new Map(o.sessions),c=a.get(n);return c&&a.set(n,{...c,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:s=>{const n=Zr(s);t(o=>{const a=new Map(o.sessions),c=a.get(n);return c?(a.set(n,{...c,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:s=>{const n=Zr(s);t(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{t({sessions:new Map,nextChunkId:1})}})),ap=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Z0=[{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'}],eS=[{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'}],ip=t=>Object.fromEntries(t.map(r=>[r.id,r])),lu=ip(Z0),en=ip(eS),tS="ibm-plex-sans",ma="ibm-plex-mono";function sS(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 rS(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 Ri=null;function nS(){return Ri||(Ri=vg.load()),Ri}function oS(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 bl=i.forwardRef(({sessionKey:t,chunks:r,onInput:s,onResize:n,theme:o,fontFamily:a,fontSize:c,className:l,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),N=i.useRef(null),b=i.useRef(null),k=i.useRef(null),A=i.useRef(0),j=i.useRef(null),[,M]=i.useReducer(_=>_+1,0),[C,I]=i.useReducer(_=>_+1,0);x.current=s,g.current=n;const E=i.useCallback((_,Y)=>{const K=j.current,U=m.current;if(!K||!U)return;const Q=U.getBoundingClientRect(),z=Q.left+Q.width/2,re=Q.top+Q.height-12,te=typeof _=="number"?_:z,pe=typeof Y=="number"?Y:re,R=8,ee=Math.max(R,Math.min(Q.width-R,te-Q.left)),B=Math.max(R,Math.min(Q.height-R,pe-Q.top));K.style.left=`${ee}px`,K.style.top=`${B}px`,K.style.bottom="";try{K.focus({preventScroll:!0})}catch{try{K.focus()}catch{}}},[]),P=i.useCallback(()=>{y.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,S.current=!1,N.current=null},[]),D=i.useCallback(()=>{const _=h.current,Y=p.current,K=m.current;if(!_||!Y||!K)return;const U=K.getBoundingClientRect();if(!(U.width<24||U.height<24))try{_.fit();const Q={cols:Y.cols,rows:Y.rows},z=w.current;(!z||z.cols!==Q.cols||z.rows!==Q.rows)&&(w.current=Q,g.current(Q.cols,Q.rows))}catch{}},[]),T=i.useCallback(()=>{if(S.current)return;const _=p.current;if(!_){P();return}if(!y.current)return;const Y=y.current;y.current="",S.current=!0,_.write(Y,()=>{S.current=!1,y.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,T()}):T())})},[P]),L=i.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,T()}):T())},[T]),V=i.useCallback(_=>{_&&(y.current+=_,L())},[L]),q=i.useCallback(()=>{if(b.current?.(),b.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),!d){A.current=0;return}const _=m.current;if(!_)return;const Y=p.current;if(!Y)return;A.current=0;const K=2.2,U=2.8,Q=25,z=.25,re=8,te=.05,pe=.015,R={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},ee=()=>typeof performance<"u"?performance.now():Date.now(),B=Math.max(12,Math.round(c*1.35));let W=0;const X=J=>{if(!J)return!1;const ne=Y.getViewportY(),ke=W+J,Z=Math.trunc(ke/B);return W=ke-Z*B,Z!==0&&Y.scrollLines(Z),Y.getViewportY()!==ne},ie=()=>{R.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(R.rafId),R.rafId=null},be={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const J=Object.assign(R,{pointerId:null,startX:null,startY:null,moved:!1}),ne=6,ke=je=>{if(je.pointerType==="touch"){ie(),J.pointerId=je.pointerId,J.startX=je.clientX,J.startY=je.clientY,J.moved=!1,J.lastY=je.clientY,J.lastTime=ee(),J.velocity=0;try{_.setPointerCapture(je.pointerId)}catch{}}},Z=je=>{if(je.pointerType!=="touch"||J.pointerId!==je.pointerId)return;if(J.startX!==null&&J.startY!==null&&!J.moved){const Ge=je.clientX-J.startX,rt=je.clientY-J.startY;Math.hypot(Ge,rt)>=ne&&(J.moved=!0)}if(J.lastY===null){J.lastY=je.clientY,J.lastTime=ee();return}const ae=J.lastY,Xe=J.lastTime??ee(),mt=ee();J.lastY=je.clientY,J.lastTime=mt;const De=ae-je.clientY;if(Math.abs(De)<1)return;const oe=Math.max(mt-Xe,8),Ue=K+Math.min(U,Math.abs(De)/Q),Se=De*Ue,Ne=Se/oe;J.velocity=J.velocity*(1-z)+Ne*z,J.velocity>re?J.velocity=re:J.velocity<-re&&(J.velocity=-re),J.moved&&(je.cancelable&&je.preventDefault(),je.stopPropagation()),X(Se)},xe=je=>{if(je.pointerType!=="touch"||J.pointerId!==je.pointerId)return;const ae=!J.moved;J.pointerId=null,J.startX=null,J.startY=null,J.moved=!1,J.lastY=null,J.lastTime=null;try{_.releasePointerCapture(je.pointerId)}catch{}if(ae){E(je.clientX,je.clientY);return}if(typeof window>"u")return;if(Math.abs(J.velocity)<te){J.velocity=0;return}let Xe=ee();const mt=()=>{const De=ee(),oe=Math.max(De-Xe,8);Xe=De;const Ue=X(J.velocity*oe)??!1,Se=Math.sign(J.velocity),Ne=Math.max(0,Math.abs(J.velocity)-pe*oe);if(J.velocity=Ne*Se,!Ue||Ne<=te){ie(),J.velocity=0;return}J.rafId=window.requestAnimationFrame(mt)};J.rafId=window.requestAnimationFrame(mt)};_.addEventListener("pointerdown",ke,be),_.addEventListener("pointermove",Z,be),_.addEventListener("pointerup",xe,be),_.addEventListener("pointercancel",xe,be);const de=_.style.touchAction;_.style.touchAction="manipulation",b.current=()=>{ie(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),A.current=0,_.removeEventListener("pointerdown",ke,be),_.removeEventListener("pointermove",Z,be),_.removeEventListener("pointerup",xe,be),_.removeEventListener("pointercancel",xe,be),_.style.touchAction=de};return}const me=6,we=J=>{J.touches.length===1&&(ie(),R.lastY=J.touches[0].clientY,R.lastTime=ee(),R.velocity=0,R.startX=J.touches[0].clientX,R.startY=J.touches[0].clientY,R.didMove=!1)},he=J=>{if(J.touches.length!==1){R.lastY=null,R.lastTime=null,R.velocity=0,R.startX=null,R.startY=null,R.didMove=!1,ie();return}const ne=J.touches[0].clientX,ke=J.touches[0].clientY;if(R.startX!==null&&R.startY!==null&&!R.didMove){const oe=ne-R.startX,Ue=ke-R.startY;Math.hypot(oe,Ue)>=me&&(R.didMove=!0)}if(R.lastY===null){R.lastY=ke,R.lastTime=ee();return}const Z=R.lastY,xe=R.lastTime??ee(),de=ee();R.lastY=ke,R.lastTime=de;const je=Z-ke;if(Math.abs(je)<1)return;const ae=Math.max(de-xe,8),Xe=K+Math.min(U,Math.abs(je)/Q),mt=je*Xe,De=mt/ae;R.velocity=R.velocity*(1-z)+De*z,R.velocity>re?R.velocity=re:R.velocity<-re&&(R.velocity=-re),R.didMove&&(J.preventDefault(),J.stopPropagation()),X(mt)},_e=J=>{const ne=!R.didMove;R.lastY=null,R.lastTime=null;const ke=R.velocity;if(R.startX=null,R.startY=null,R.didMove=!1,ne){const de=J.changedTouches?.[0];E(de?.clientX,de?.clientY);return}if(typeof window>"u")return;if(Math.abs(ke)<te){R.velocity=0;return}let Z=ee();const xe=()=>{const de=ee(),je=Math.max(de-Z,8);Z=de;const ae=X(R.velocity*je)??!1,Xe=Math.sign(R.velocity),mt=Math.max(0,Math.abs(R.velocity)-pe*je);if(R.velocity=mt*Xe,!ae||mt<=te){ie(),R.velocity=0;return}R.rafId=window.requestAnimationFrame(xe)};R.rafId=window.requestAnimationFrame(xe)};_.addEventListener("touchstart",we,be),_.addEventListener("touchmove",he,be),_.addEventListener("touchend",_e,be),_.addEventListener("touchcancel",_e,be);const se=_.style.touchAction;_.style.touchAction="manipulation",b.current=()=>{ie(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),A.current=0,_.removeEventListener("touchstart",we,be),_.removeEventListener("touchmove",he,be),_.removeEventListener("touchend",_e,be),_.removeEventListener("touchcancel",_e,be),_.style.touchAction=se}},[d,E,c]);return i.useEffect(()=>{let _=!1,Y=null,K=null,U=[];const Q=m.current;return Q?(Q.tabIndex=0,(async()=>{try{const re=await nS();if(_)return;const te=rS(a,c,o,re),pe=new bg(te),R=new wg;Y=pe,p.current=pe,h.current=R,pe.loadAddon(R),pe.open(Q),I();const ee=oS(Q);ee?(ee.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=ee,M()):f.current=null,D(),q(),pe.focus(),U=[pe.onData(B=>{x.current(B)})],K=new ResizeObserver(()=>{D()}),K.observe(Q),typeof window<"u"&&window.setTimeout(()=>{D()},0)}catch{}})(),()=>{_=!0,b.current?.(),b.current=null,U.forEach(re=>re.dispose()),K?.disconnect(),Y?.dispose(),p.current=null,h.current=null,f.current=null,w.current=null,P()}):void 0},[D,a,c,q,o,P]),i.useEffect(()=>{const _=p.current;_&&(_.reset(),P(),w.current=null,D(),_.focus())},[t,C,D,P]),i.useEffect(()=>(q(),()=>{b.current?.(),b.current=null}),[q,t]),i.useEffect(()=>{const _=p.current;if(!_)return;if(r.length===0){N.current!==null&&(_.reset(),P(),D());return}const Y=N.current;let K;if(Y===null)K=r;else{const U=r.findIndex(Q=>Q.id===Y);K=U>=0?r.slice(U+1):r}K.length>0&&V(K.map(U=>U.data).join("")),N.current=r[r.length-1].id},[r,C,V,D,P]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){E();return}p.current?.focus()},clear:()=>{const _=p.current;_&&(_.reset(),P(),D())},fit:()=>{D()}}),[d,E,D,P]),e.jsxs("div",{ref:m,className:F("relative h-full w-full terminal-viewport-container",l),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 Y=String(_.currentTarget.value||"");if(!Y)return;const K=Y.replace(/\r\n|\r|\n/g,"\r");x.current(K),_.currentTarget.value=""},onKeyDown:_=>{_.key==="Backspace"&&(_.currentTarget.value||x.current(""))}}):null,f.current&&!d?e.jsx(Hl,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});bl.displayName="TerminalViewport";const cu=13,aS={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Ko={ctrl:"5",cmd:"3"},iS={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},lS=(t,r)=>{if(r)switch(t){case"arrow-up":return`\x1B[1;${Ko[r]}A`;case"arrow-down":return`\x1B[1;${Ko[r]}B`;case"arrow-right":return`\x1B[1;${Ko[r]}C`;case"arrow-left":return`\x1B[1;${Ko[r]}D`}return aS[t]??null},cS=()=>{const{terminal:t}=Tr(),{currentTheme:r}=Yr(),{monoFont:s}=ap(),{isMobile:n,hasTouchInput:o}=Qt(),{currentSessionId:a,sessions:c,worktreeMetadata:l}=fe(),d=a?l.get(a)??void 0:void 0,u=i.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const ne=c.find(Z=>Z.id===a),ke=typeof ne?.directory=="string"?ne.directory:null;return ke&&ke.length>0?ke:null},[a,c,d]),{currentDirectory:m,homeDirectory:f}=bt(),p=u||m||null,h=i.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),x=iu(),g=x.sessions,w=x.setTerminalSession,y=x.setConnecting,v=x.appendToBuffer,S=x.clearTerminalSession,N=x.removeTerminalSession,b=x.clearBuffer,k=i.useMemo(()=>{if(p)return g.get(p)},[g,p]),A=k?.terminalSessionId??null,j=k?.bufferChunks??[],M=k?.bufferLength??0,C=k?.isConnecting??!1,I=A,[E,P]=i.useState(null),[D,T]=i.useState(!1),[L,V]=i.useState(null),[q,_]=i.useState(!1),Y=i.useRef(null),K=i.useRef(null),U=i.useRef(I),Q=i.useRef(p),z=i.useRef(null),te=Te(ne=>ne.activeMainTab)==="terminal";i.useEffect(()=>{U.current=I},[I]),i.useEffect(()=>{Q.current=p},[p]),i.useEffect(()=>{!n&&L!==null&&V(null)},[n,L,V]),i.useEffect(()=>{!I&&L!==null&&V(null)},[I,L,V]);const pe=i.useCallback(()=>{Y.current?.(),Y.current=null,K.current=null},[]);i.useEffect(()=>()=>{pe(),U.current=null},[pe]);const R=i.useCallback(ne=>{if(K.current===ne)return;pe();const ke=t.connect(ne,{onEvent:Z=>{const xe=Q.current;if(xe)switch(Z.type){case"connected":{(Z.runtime||Z.ptyBackend)&&console.log(`[Terminal] connected runtime=${Z.runtime??"unknown"} pty=${Z.ptyBackend??"unknown"}`),y(xe,!1),P(null),T(!1),z.current?.focus();break}case"reconnecting":{const de=Z.attempt??0,je=Z.maxAttempts??3;P(`Reconnecting (${de}/${je})...`),T(!1);break}case"data":{Z.data&&v(xe,Z.data);break}case"exit":{const de=typeof Z.exitCode=="number"?Z.exitCode:null,je=typeof Z.signal=="number"?Z.signal:null;v(xe,`\r
120
- [Process exited${de!==null?` with code ${de}`:""}${je!==null?` (signal ${je})`:""}]\r
121
- `),S(xe),y(xe,!1),P("Terminal session ended"),T(!1),pe();break}}},onError:(Z,xe)=>{const de=Q.current;if(!de)return;const je=xe?`Connection failed: ${Z.message}`:Z.message||"Terminal stream connection error";P(je),T(!!xe),xe&&(y(de,!1),pe(),N(de))}},iS);Y.current=()=>{ke.close(),K.current=null},K.current=ne},[v,S,pe,N,y,t,P]);i.useEffect(()=>{let ne=!1;if(!p){P(a?"No working directory available for terminal.":"Select a session to open the terminal."),pe();return}return(async()=>{const Z=p;if(!Q.current||Q.current!==Z)return;let de=iu.getState().getTerminalSession(Z)?.terminalSessionId??null;if(!de){P(null),T(!1),y(Z,!0);try{const je=await t.createSession({cwd:Z});if(ne){try{await t.close(je.sessionId)}catch{}return}w(Z,je),de=je.sessionId}catch(je){ne||(P(je instanceof Error?je.message:"Failed to start terminal session"),T(!0),y(Z,!1));return}}!de||ne||(U.current=de,R(de))})(),()=>{ne=!0,U.current=null,pe()}},[a,p,I,N,y,w,R,pe,t]);const ee=i.useCallback(async()=>{if(!p||q)return;_(!0),P(null),T(!1),pe();const ne=U.current;try{if(t.restartSession&&ne){const ke=await t.restartSession(ne,{cwd:p});w(p,ke),U.current=ke.sessionId,R(ke.sessionId)}else{if(ne)try{await t.close(ne)}catch{}N(p)}}catch(ke){P(ke instanceof Error?ke.message:"Failed to restart terminal"),T(!0)}finally{_(!1)}},[p,q,pe,t,w,R,N]),B=i.useCallback(async()=>{if(p&&!q){_(!0),P(null),T(!1),pe();try{t.forceKill&&await t.forceKill({cwd:p})}catch{}N(p),b(p),z.current?.clear(),await new Promise(ne=>setTimeout(ne,100));try{y(p,!0);const ne=await t.createSession({cwd:p});w(p,ne),U.current=ne.sessionId,R(ne.sessionId)}catch(ne){P(ne instanceof Error?ne.message:"Failed to create terminal"),T(!0),y(p,!1)}finally{_(!1)}}},[p,q,pe,t,N,b,y,w,R]),W=i.useCallback(()=>{if(!p)return;b(p),z.current?.clear(),z.current?.focus();const ne=U.current;ne&&t.sendInput(ne,"\f").catch(ke=>{P(ke instanceof Error?ke.message:"Failed to refresh prompt")})},[b,p,P,t]),X=i.useCallback(ne=>{if(!ne)return;let ke=ne,Z=!1;if(L&&ne.length>0){const de=ne[0];if(de.length===1&&/[a-zA-Z]/.test(de)){const je=de.toUpperCase();(L==="ctrl"||L==="cmd")&&(ke=String.fromCharCode(je.charCodeAt(0)&31),Z=!0)}Z||(Z=!0)}const xe=U.current;xe&&(t.sendInput(xe,ke).catch(de=>{P(de instanceof Error?de.message:"Failed to send input")}),Z&&(V(null),z.current?.focus()))},[L,V,t]),ie=i.useCallback((ne,ke)=>{const Z=U.current;Z&&t.resize({sessionId:Z,cols:ne,rows:ke}).catch(()=>{})},[t]),be=i.useCallback(ne=>{V(ke=>ke===ne?null:ne),z.current?.focus()},[V]),H=i.useCallback(ne=>{const ke=lS(ne,L);ke&&(X(ke),V(null),z.current?.focus())},[L,X,V]);i.useEffect(()=>{if(!n||!L||!I)return;const ne=ke=>{if(ke.repeat)return;const Z=ke.key;if(!Z||Z==="Control"||Z==="Meta"||Z==="Alt"||Z==="Shift")return;const xe=Z.length===1?Z.toLowerCase():Z,de=ke.code??"",je=de.startsWith("Key")&&de.length===4?de.slice(3).toUpperCase():null,ae=Z.length===1&&/[a-zA-Z]/.test(Z)?Z.toUpperCase():je,Xe={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 Xe){ke.preventDefault(),ke.stopPropagation(),H(Xe[xe]);return}if(L==="ctrl"&&ae&&ae.length===1&&ae>="A"&&ae<="Z"){const mt=String.fromCharCode(ae.charCodeAt(0)&31);ke.preventDefault(),ke.stopPropagation(),X(mt),V(null),z.current?.focus()}};return window.addEventListener("keydown",ne),()=>{window.removeEventListener("keydown",ne)}},[L,H,X,n,V,I]);const me=i.useMemo(()=>{const ne=en[ma].stack;if(typeof window>"u")return(en[s]??en[ma]).stack;const Z=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Z&&Z.trim().length>0?Z.trim():(en[s]??en[ma]).stack??ne},[s]),we=i.useMemo(()=>sS(r),[r]),he=i.useMemo(()=>`${p??"no-dir"}::${I??"pending"}`,[p,I]);i.useEffect(()=>{if(!te)return;const ne=z.current;if(!ne)return;const ke=()=>{ne.fit()};if(typeof window<"u"){const Z=window.requestAnimationFrame(()=>{ke(),ne.focus()}),xe=[220,400].map(de=>window.setTimeout(ke,de));return()=>{window.cancelAnimationFrame(Z),xe.forEach(de=>window.clearTimeout(de))}}ke()},[te,he,I]);const _e=E?.includes("Reconnecting"),se=E?_e?e.jsx(jg,{size:20,className:"text-amber-400"}):e.jsx(Zt,{size:20,className:"text-destructive"}):I&&!C&&!q?e.jsx(Zo,{size:20,className:"text-emerald-400"}):C||q?e.jsx(Yi,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Yi,{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:ee,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const J=!I||C||q;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[se,e.jsxs(Me,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:W,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(Us,{size:16}),"Clear"]}),e.jsxs(Me,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:ee,disabled:q,title:"Restart terminal session",type:"button",children:[e.jsx(Is,{size:16,className:F((C||q)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>H("esc"),disabled:J,children:"Esc"}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("tab"),disabled:J,children:[e.jsx(vc,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:L==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>be("ctrl"),disabled:J,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:L==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>be("cmd"),disabled:J,children:[e.jsx(hn,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-up"),disabled:J,children:[e.jsx(jo,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-left"),disabled:J,children:[e.jsx(cm,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-down"),disabled:J,children:[e.jsx(Gn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("arrow-right"),disabled:J,children:[e.jsx(vc,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Me,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>H("enter"),disabled:J,children:[e.jsx(Ln,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:we.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:te?n?e.jsx(bl,{ref:ne=>{z.current=ne},sessionKey:he,chunks:j,onInput:X,onResize:ie,theme:we,fontFamily:me,fontSize:cu,enableTouchScroll:o},he):e.jsx(gt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(bl,{ref:ne=>{z.current=ne},sessionKey:he,chunks:j,onInput:X,onResize:ie,theme:we,fontFamily:me,fontSize:cu,enableTouchScroll:o},he)}):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}),D&&e.jsx(Me,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:B,disabled:q,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},du=new Ba,uu=new Ba,mu=new Ba,fu=new Ba,pu=t=>{if(!t)return[];const r=Math.max(1,t.start),s=Math.max(r,t.end);return Ig.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 Pg;for(let a=r;a<=s&&a<=n.state.doc.lines;a+=1){const c=n.state.doc.line(a);o.add(c.from,c.from,Tg.line({class:"oc-cm-selected-line"}))}return o.finish()}},{decorations:n=>n.decorations})};function dS({value:t,onChange:r,extensions:s,className:n,readOnly:o,lineNumbersConfig:a,highlightLines:c}){const l=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(!l.current)return;const f=Sg.create({doc:u.current,extensions:[kg({fixed:!0}),du.of(jc(a)),Ng(),Cg.of(" "),Mg.of([Dg,...Ag,...Eg]),Nn.updateListener.of(p=>{if(!p.docChanged)return;const h=p.state.doc.toString();u.current=h,m.current(h)}),uu.of(Nn.editable.of(!o)),mu.of(s??[]),fu.of(pu(c))]});return d.current=new Nn({state:f,parent:l.current}),()=>{d.current?.destroy(),d.current=null}},[]),i.useEffect(()=>{const f=d.current;f&&f.dispatch({effects:[du.reconfigure(jc(a)),uu.reconfigure(Nn.editable.of(!o)),mu.reconfigure(s??[]),fu.reconfigure(pu(c))]})},[s,c,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:l,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 wl=qn.define(Fg),lp=qn.define(Rg),uS=qn.define(Lg),mS=qn.define(Og),fS=qn.define(_g),pS=qn.define($g);function hS(t){const r=t.trim().toLowerCase();switch(r){case"bash":case"sh":case"zsh":case"shell":case"shellsession":case"console":return wl;case"toml":return lp;case"diff":case"patch":return uS;case"json":case"jsonc":case"json5":return xm().language;case"js":case"javascript":return Cn().language;case"jsx":return Cn({jsx:!0}).language;case"ts":case"typescript":return Cn({typescript:!0}).language;case"tsx":return Cn({typescript:!0,jsx:!0}).language;case"yaml":case"yml":return pm().language;case"html":return hm().language;case"css":return gm().language;case"xml":case"svg":return um().language;case"py":case"python":return fm().language;case"sql":return mm().language;case"rs":case"rust":return dm().language;default:return zg.matchLanguageName(Wg,r,!0)}}const gS=t=>t.split("/").pop()?.toLowerCase()??"";function xS(t){const r=t.toLowerCase();switch(gS(r)){case"dockerfile":return mS;case"makefile":case"gnumakefile":return wl}const n=r.lastIndexOf("."),o=n>=0?r.slice(n+1):"";switch(o){case"ts":case"tsx":case"mts":case"cts":return Cn({typescript:!0,jsx:o==="tsx"});case"js":case"jsx":case"mjs":case"cjs":return Cn({typescript:!1,jsx:o==="jsx"});case"json":case"jsonc":case"json5":case"jsonl":case"ndjson":case"geojson":return xm();case"css":case"scss":case"sass":case"less":return gm();case"html":case"htm":return hm();case"md":case"mdx":case"markdown":case"mdown":case"mkd":return Bg({codeLanguages:hS});case"yml":case"yaml":return pm();case"toml":return lp;case"ini":case"cfg":case"conf":case"config":case"properties":return pS;case"sh":case"bash":case"zsh":case"fish":case"env":return wl;case"py":case"pyw":case"pyi":return fm();case"sql":case"psql":case"plsql":return mm();case"xml":case"xsl":case"xslt":case"xsd":case"dtd":case"plist":case"svg":return um();case"rs":return dm();case"rb":case"erb":case"rake":case"gemspec":return fS;default:return null}}function hu(t){const r=t.metadata.variant==="dark",s=t.config?.fonts?.mono||"monospace",n=t.colors.syntax.highlights||{},o=t.colors.syntax.tokens||{},a=Nn.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}),c=Hg.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,Ug(c)]}const yS=t=>t.slice().sort((r,s)=>r.type!==s.type?r.type==="directory"?-1:1:r.name.localeCompare(s.name)),Zs=t=>t.replace(/\\/g,"/"),bS=new Set(["node_modules"]),wS=t=>bS.has(t),vS=t=>{const r=Zs(t);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},jS=()=>{const{currentSessionId:t,sessions:r,worktreeMetadata:s}=fe(),{currentDirectory:n}=bt(),o=t?s.get(t)??void 0:void 0,c=r.find(l=>l.id===t)?.directory;return o?.path??c??n??""},so=2e5,SS=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"]),kS=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"]),NS=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),CS=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),gu=t=>{const r=t?.toLowerCase();return r&&SS.has(r)?e.jsx(Ks,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&kS.has(r)?e.jsx(Ks,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&NS.has(r)?e.jsx(wr,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&CS.has(r)?e.jsx(po,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(po,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},MS=()=>{const{files:t,runtime:r}=Tr(),{currentTheme:s}=Yr();i.useMemo(()=>lc(s),[s]);const{isMobile:n,screenWidth:o}=Qt(),a=Co(),c=Za(),l=jS(),d=Zs(l),u=Ua(ge=>ge.searchFiles),[m,f]=i.useState(""),p=Ja(m,200),h=i.useRef(null),[x,g]=i.useState(!1),[w,y]=i.useState(n),[v,S]=i.useState(new Set),[N,b]=i.useState({}),k=i.useRef(new Set),A=i.useRef(new Set),[j,M]=i.useState([]),[C,I]=i.useState(!1),[E,P]=i.useState(null),[D,T]=i.useState(""),[L,V]=i.useState(!1),[q,_]=i.useState(null),[Y,K]=i.useState(""),[U,Q]=i.useState(""),[z,re]=i.useState(!1),[te,pe]=i.useState(!1),R=i.useRef(null),ee=i.useRef(null),B=i.useRef(!1),[W,X]=i.useState(null),[ie,be]=i.useState(null),[H,me]=i.useState(""),[we,he]=i.useState(!1),[_e,se]=i.useState(null),J=!!t.writeFile,ne=!!t.createDirectory,ke=!!t.rename,Z=!!t.delete,xe=i.useCallback((ge,Ee)=>{X(ge),be(Ee),me(ge==="rename"&&Ee.name||""),he(!1)},[]),[de,je]=i.useState(null),[ae,Xe]=i.useState(""),mt=i.useRef(!1),De=i.useRef(null),oe=fe(ge=>ge.sendMessage),Ue=fe(ge=>ge.currentSessionId),{currentProviderId:Se,currentModelId:Ne,currentAgentName:Ge,currentVariant:rt}=at(),Ke=ht(ge=>ge.getSessionAgentSelection),Le=ht(ge=>ge.getAgentModelForSession),Ye=ht(ge=>ge.getAgentModelVariantForSession),xt=Te(ge=>ge.setActiveMainTab),nt=Te(ge=>ge.setMainTabGuard),{inputBarOffset:It,isKeyboardOpen:Pt}=Te();i.useEffect(()=>{const ge=()=>{mt.current=!1,De.current=null};return document.addEventListener("mouseup",ge),()=>document.removeEventListener("mouseup",ge)},[]),i.useEffect(()=>{je(null),Xe(""),nt(null),Q(""),re(!1)},[E?.path,nt]),i.useEffect(()=>{if(!de)return;const ge=st=>{const $e=st.target;document.querySelector("[data-comment-ui]")?.contains($e)||$e.closest(".cm-gutterElement")||$e.closest("[data-sonner-toast]")||$e.closest("[data-sonner-toaster]")||(je(null),Xe(""))},Ee=setTimeout(()=>{document.addEventListener("click",ge)},100);return()=>{clearTimeout(Ee),document.removeEventListener("click",ge)}},[de]);const zt=i.useCallback((ge,Ee)=>{const st=ge.split(`
122
- `),$e=Math.max(1,Ee.start),kt=Math.min(st.length,Ee.end);return $e>kt?"":st.slice($e-1,kt).join(`
123
- `)},[]),We=i.useCallback(async()=>{if(!de||!ae.trim()||!E)return;if(!Ue){G.error("Select a session to send comment");return}const ge=Ke(Ue)||Ge,Ee=ge?Le(Ue,ge):null,st=Ee?.providerId||Se,$e=Ee?.modelId||Ne;if(!st||!$e){G.error("Select a model to send comment");return}const kt=ge&&st&&$e?Ye(Ue,ge,st,$e)??rt:rt,Mt=zt(D,de),Kt=Pr(E.path)||"text",pt=E.name,Ss=de.start,ms=de.end,Yt=`Comment on \`${pt}\` lines ${Ss}-${ms}:
124
- \`\`\`${Kt}
125
- ${Mt}
126
- \`\`\`
127
-
128
- ${ae}`;Xe(""),je(null),xt("chat");try{await oe(Yt,st,$e,ge,void 0,void 0,void 0,kt)}catch(Vs){console.error("Failed to send comment",Vs)}},[de,ae,E,D,Ue,Se,Ne,Ge,rt,zt,oe,xt,Ke,Le,Ye]),ut=i.useCallback((ge,Ee)=>{const st=Ee.filter($e=>$e&&typeof $e.name=="string"&&$e.name.length>0).filter($e=>a||!$e.name.startsWith(".")).filter($e=>c||!wS($e.name)).map($e=>{const kt=$e.name,Mt=Zs($e.path||`${ge}/${kt}`),Kt=$e.isDirectory?"directory":"file",pt=Kt==="file"&&kt.includes(".")?kt.split(".").pop()?.toLowerCase():void 0;return{name:kt,path:Mt,type:Kt,extension:pt}});return yS(st)},[c,a]),vt=i.useCallback(async ge=>{const Ee=Zs(ge.trim());if(Ee&&!(k.current.has(Ee)||A.current.has(Ee))){A.current=new Set(A.current),A.current.add(Ee);try{const st=!c;let $e;r.isDesktop?$e=(await t.listDirectory(Ee,{respectGitignore:st})).entries.map(Kt=>({name:Kt.name,path:Kt.path,isDirectory:Kt.isDirectory})):$e=(await Fe.listLocalDirectory(Ee,{respectGitignore:st})).map(Kt=>({name:Kt.name,path:Kt.path,isDirectory:Kt.isDirectory}));const kt=ut(Ee,$e);k.current=new Set(k.current),k.current.add(Ee),b(Mt=>({...Mt,[Ee]:kt}))}catch{b(st=>({...st,[Ee]:st[Ee]??[]}))}finally{A.current=new Set(A.current),A.current.delete(Ee)}}},[t,ut,r.isDesktop,c]),dt=i.useCallback(async()=>{const ge=Zs(l.trim());ge&&(k.current=new Set,A.current=new Set,S(new Set),b({}),await vt(ge))},[l,vt]);i.useEffect(()=>{l&&(dt(),P(null),T(""),_(null),K(""),g(!1))},[l,dt]),i.useEffect(()=>{l&&dt()},[l,dt,c]);const Tt=i.useCallback(async ge=>{if(ge?.preventDefault(),!(!ie||!W)){he(!0);try{if(W==="createFile"){if(!H.trim())throw new Error("Filename is required");const Ee=ie.path,st=Ee?`${Ee}/`:"",$e=Zs(`${st}${H.trim()}`);if(!t.writeFile)throw new Error("Write not supported");(await t.writeFile($e,"")).success&&(G.success("File created"),await dt())}else if(W==="createFolder"){if(!H.trim())throw new Error("Folder name is required");const Ee=ie.path,st=Ee?`${Ee}/`:"",$e=Zs(`${st}${H.trim()}`);(await t.createDirectory($e)).success&&(G.success("Folder created"),await dt())}else if(W==="rename"){if(!H.trim())throw new Error("Name is required");const Ee=ie.path,st=Ee.split("/").slice(0,-1).join("/"),$e=st?`${st}/`:"",kt=Zs(`${$e}${H.trim()}`);t.rename?(await t.rename(Ee,kt)).success&&(G.success("Renamed successfully"),await dt(),E?.path===Ee&&P(null)):G.error("Rename not supported")}else W==="delete"&&(t.delete?(await t.delete(ie.path)).success&&(G.success("Deleted successfully"),await dt(),(E?.path===ie.path||E?.path.startsWith(ie.path+"/"))&&(P(null),T(""))):G.error("Delete not supported"));X(null)}catch(Ee){G.error(Ee instanceof Error?Ee.message:"Operation failed")}finally{he(!1)}}},[W,ie,H,t,dt,E]),Ct=i.useCallback((ge,Ee)=>{const st=ge.trim().toLowerCase();if(!st)return 0;const $e=Ee.toLowerCase();let kt=0,Mt=-1,Kt=0;for(let pt=0;pt<st.length;pt+=1){const Ss=st[pt];if(!Ss||Ss===" ")continue;const ms=$e.indexOf(Ss,Mt+1);if(ms===-1)return null;const Yt=ms-Mt-1;if(Yt===0?Kt+=1:Kt=0,kt+=10,kt+=Math.max(0,18-ms),kt-=Math.max(0,Yt),ms===0)kt+=12;else{const Vs=$e[ms-1];(Vs==="/"||Vs==="_"||Vs==="-"||Vs==="."||Vs===" ")&&(kt+=10)}kt+=Kt>0?12:0,Mt=ms}return kt+=Math.max(0,24-Math.round($e.length/3)),kt},[]);i.useEffect(()=>{l&&dt()},[l,dt,c]),i.useEffect(()=>{if(!l){M([]),I(!1);return}const ge=p.trim();if(!ge){M([]),I(!1);return}const Ee=ge.toLowerCase();let st=!1;return I(!0),u(l,ge,150,{includeHidden:a,respectGitignore:!c}).then($e=>{if(st)return;const Mt=$e.filter(pt=>c||!vS(pt.path)).map(pt=>{const Ss=pt.relativePath||pt.name||pt.path,ms=Ct(Ee,Ss);return ms===null?null:{hit:pt,score:ms,labelLength:Ss.length}}).filter(Boolean);Mt.sort((pt,Ss)=>Ss.score-pt.score||pt.labelLength-Ss.labelLength||pt.hit.path.localeCompare(Ss.hit.path));const Kt=Mt.map(({hit:pt})=>({name:pt.name,path:Zs(pt.path),type:"file",extension:pt.extension,relativePath:pt.relativePath}));M(Kt)}).catch(()=>{st||M([])}).finally(()=>{st||I(!1)}),()=>{st=!0}},[l,p,Ct,u,a,c]);const os=i.useCallback(async ge=>{if(t.readFile)return(await t.readFile(ge)).content??"";const Ee=await fetch(`/api/fs/read?path=${encodeURIComponent(ge)}`);if(!Ee.ok){const st=await Ee.json().catch(()=>({error:Ee.statusText}));throw new Error(st.error||"Failed to read file")}return Ee.text()},[t]),St=i.useMemo(()=>D.length>so?`${D.slice(0,so)}
129
-
130
- … truncated …`:D,[D]),Lt=i.useMemo(()=>U!==St,[U,St]),Ft=i.useCallback(async()=>{if(!E||!t.writeFile){G.error("Saving not supported");return}if(Lt){re(!0);try{if(!(await t.writeFile(E.path,U))?.success)throw new Error("Failed to write file");T(U)}catch(ge){G.error(ge instanceof Error?ge.message:"Save failed")}finally{re(!1)}}},[U,t,Lt,E]);i.useEffect(()=>{if(!Lt){nt(null);return}const ge=Ee=>B.current?(B.current=!1,!0):(pe(!0),ee.current=Ee,!1);return nt(ge),()=>{Te.getState().mainTabGuard===ge&&nt(null)}},[Lt,nt]),i.useEffect(()=>{const ge=Ee=>{Ts(Ee)&&Ee.key.toLowerCase()==="s"&&(Ee.preventDefault(),z||Ft())};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[z,Ft]);const Ut=i.useCallback(async ge=>{if(B.current)B.current=!1;else if(Lt){pe(!0),R.current=ge;return}P(ge),_(null),K("");const Ee=wo(ge.path);n&&g(!0);const st=ge.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&Ee&&!st){T(""),V(!0);return}if(!r.isDesktop&&Ee&&!st){T(""),V(!1);return}V(!0);try{const $e=await os(ge.path);T($e),Q($e.length>so?`${$e.slice(0,so)}
131
-
132
- … truncated …`:$e)}catch($e){T(""),Q(""),_($e instanceof Error?$e.message:"Failed to read file")}finally{V(!1)}},[Lt,n,os,r.isDesktop]),Rt=i.useCallback(()=>{const ge=R.current,Ee=ee.current;if(R.current=null,ee.current=null,B.current=!0,pe(!1),Q(St),ge){Ut(ge);return}Ee&&(nt(null),Te.getState().setActiveMainTab(Ee))},[St,Ut,nt]),qt=i.useCallback(async()=>{const ge=R.current,Ee=ee.current;if(R.current=null,ee.current=null,B.current=!0,pe(!1),await Ft(),ge){await Ut(ge);return}Ee&&(nt(null),Te.getState().setActiveMainTab(Ee))},[Ut,Ft,nt]),ye=i.useCallback(async ge=>{const Ee=Zs(ge);S(st=>{const $e=new Set(st);return $e.has(Ee)?$e.delete(Ee):$e.add(Ee),$e}),k.current.has(Ee)||await vt(Ee)},[vt]),Ae=i.useCallback((ge,Ee)=>{const st=N[ge]??[];return st.map(($e,kt)=>{const Mt=$e.type==="directory",Kt=Mt&&v.has($e.path),pt=E?.path===$e.path,Ss=Mt&&A.current.has($e.path),ms=kt===st.length-1;return e.jsxs("li",{className:"relative",children:[Ee>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"absolute top-3.5 left-[-12px] w-3 h-px bg-border/40"}),ms&&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:Yt=>{!ke&&!J&&!ne&&!Z||(Yt.preventDefault(),se($e.path))},children:[e.jsxs("button",{type:"button",onClick:()=>{Mt?ye($e.path):Ut($e)},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",pt?"bg-accent/70":"hover:bg-accent/40"),children:[Mt?Ss?e.jsx(Jt,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):Kt?e.jsx(Vg,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(Gg,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):gu($e.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:$e.path,children:$e.name})]}),(ke||J||ne||Z)&&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(es,{open:_e===$e.path,onOpenChange:Yt=>se(Yt?$e.path:null),children:[e.jsx(ts,{asChild:!0,children:e.jsx(Me,{variant:"ghost",size:"icon",className:"h-6 w-6",children:e.jsx(qg,{className:"h-4 w-4"})})}),e.jsxs(ss,{align:"end",onCloseAutoFocus:()=>se(null),children:[ke&&e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),xe("rename",$e)},children:[e.jsx(Vn,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),navigator.clipboard.writeText($e.path),G.success("Path copied")},children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"})," Copy Path"]}),Mt&&(J||ne)&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),J&&e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),xe("createFile",$e)},children:[e.jsx(Sc,{className:"mr-2 h-4 w-4"})," New File"]}),ne&&e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),xe("createFolder",$e)},children:[e.jsx(Ki,{className:"mr-2 h-4 w-4"})," New Folder"]})]}),Z&&e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsxs(Nt,{onClick:Yt=>{Yt.stopPropagation(),xe("delete",$e)},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]})})]}),Mt&&Kt&&e.jsx("ul",{className:"flex flex-col gap-1 ml-3 pl-3 border-l border-border/40 relative",children:Ae($e.path,Ee+1)})]},$e.path)})},[N,v,Ut,E?.path,ye,xe,J,ne,ke,Z,_e,se]),$=!!(E?.path&&wo(E.path)),ue=!!(E?.path&&E.path.toLowerCase().endsWith(".svg")),ve=i.useMemo(()=>{if(!E?.path)return"";const ge=Zs(E.path);if(d&&ge.startsWith(d)){const Ee=ge.slice(d.length);return Ee.startsWith("/")?Ee.slice(1):Ee}return ge},[E?.path,d]),Be=!!(E&&(!$||ue)&&D.length>0),ze=!!(E&&ve.length>0),tt=!!(E&&!$&&t.writeFile&&D.length<=so),Ce=i.useMemo(()=>{if(!E?.path)return[hu(s)];const ge=[hu(s)],Ee=xS(E.path);return Ee&&ge.push(Ee),w&&ge.push(Nn.lineWrapping),ge},[s,E?.path,w]),qe=E?.path&&$?r.isDesktop?ue?`data:${il(E.path)};utf8,${encodeURIComponent(D)}`:Y:ue?`data:${il(E.path)};utf8,${encodeURIComponent(D)}`:`/api/fs/raw?path=${encodeURIComponent(E.path)}`:"";i.useEffect(()=>{let ge=!1;return(async()=>{if(!r.isDesktop||!E?.path||!$||ue){K("");return}_(null);try{if(t.readFileBinary){const Mt=await t.readFileBinary(E.path);ge||K(Mt.dataUrl);return}const $e=(await bs(()=>import("./vendor-.bun-BrcdMJ39.js").then(Mt=>Mt.dc),__vite__mapDeps([0,1]))).convertFileSrc;if(!$e)return;const kt=$e(E.path,"asset");ge||K(kt)}catch(st){ge||(K(""),_(st instanceof Error?st.message:"Failed to read file"))}finally{ge||V(!1)}})(),()=>{ge=!0}},[t,$,ue,r.isDesktop,E?.path]);const et=()=>e.jsx(xs,{open:!!W,onOpenChange:ge=>!ge&&X(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsxs(js,{children:[W==="createFile"&&"Create File",W==="createFolder"&&"Create Folder",W==="rename"&&"Rename",W==="delete"&&"Delete"]}),e.jsxs(Ns,{children:[W==="createFile"&&`Create a new file in ${ie?.path??"root"}`,W==="createFolder"&&`Create a new folder in ${ie?.path??"root"}`,W==="rename"&&`Rename ${ie?.name}`,W==="delete"&&`Are you sure you want to delete ${ie?.name}? This action cannot be undone.`]})]}),W!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(jt,{value:H,onChange:ge=>me(ge.target.value),placeholder:W==="rename"?"New name":"Name",onKeyDown:ge=>{ge.key==="Enter"&&Tt()},autoFocus:!0})}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"outline",onClick:()=>X(null),disabled:we,children:"Cancel"}),e.jsx(Me,{variant:W==="delete"?"destructive":"default",onClick:()=>{Tt()},disabled:we||W!=="delete"&&!H.trim(),children:we?e.jsx(Jt,{className:"animate-spin"}):W==="delete"?"Delete":"Confirm"})]})]})}),ot=()=>!de||!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:ae,onChange:ge=>{Xe(ge.target.value);const Ee=ge.target;Ee.style.height="auto";const $e=20*5+8;Ee.style.height=`${Math.min(Ee.scrollHeight,$e)}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:ge=>{ge.key==="Enter"&&(ge.metaKey||ge.ctrlKey)&&(ge.preventDefault(),We()),ge.key==="Escape"&&(ge.preventDefault(),je(null),Xe(""))}}),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,":",de.start,"-",de.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!n&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Xt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:ge=>{ae.trim()&&(ge.preventDefault(),We())},onClick:()=>{n||We()},disabled:!ae.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",ae.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(La,{className:"h-[18px] w-[18px]"})})]})]})]})}),_t=e.jsxs("div",{className:"relative flex h-full min-h-0 min-w-0 w-full flex-col overflow-hidden",children:[e.jsx(xs,{open:te,onOpenChange:ge=>{ge||pe(!0)},children:e.jsxs(ys,{showCloseButton:!1,className:"max-w-md",children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Unsaved changes"}),e.jsx(Ns,{children:"Save your edits before continuing?"})]}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"outline",onClick:()=>{qt()},disabled:z,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(Me,{variant:"destructive",onClick:Rt,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(Nl,{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:ve,children:ve})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[tt&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{Ft()},disabled:!Lt||z,className:"h-5 w-5 p-0 text-[color:var(--status-success)] opacity-70 hover:opacity-100",title:`Save (${Xt()}+S)`,"aria-label":`Save (${Xt()}+S)`,children:z?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Kg,{className:"h-4 w-4"})}),tt&&E&&!$&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),E&&!$&&e.jsx(Me,{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(Yu,{className:"size-4"})}),(Be||ze)&&(tt||E&&!$)&&e.jsx("span",{"aria-hidden":"true",className:"mx-1 h-4 w-px bg-border/60"}),Be&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(D),G.success("Copied")}catch{G.error("Copy failed")}},className:"h-5 w-5 p-0",title:"Copy file contents","aria-label":"Copy file contents",children:e.jsx(Zu,{className:"h-4 w-4"})}),ze&&e.jsx(Me,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(ve),G.success("Copied")}catch{G.error("Copy failed")}},className:"h-5 w-5 p-0",title:`Copy file path (${ve})`,"aria-label":`Copy file path (${ve})`,children:e.jsx(Qg,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 relative",children:e.jsx(gt,{outerClassName:"h-full min-w-0",className:"h-full min-w-0",children:E?L?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):q?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:q}):$?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:qe,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(dS,{value:U,onChange:Q,extensions:Ce,className:"h-full",highlightLines:de?{start:Math.min(de.start,de.end),end:Math.max(de.start,de.end)}:void 0,lineNumbersConfig:{domEventHandlers:{mousedown:(ge,Ee,st)=>{if(!(st instanceof MouseEvent)||st.button!==0)return!1;st.preventDefault();const $e=ge.state.doc.lineAt(Ee.from).number;if(n&&de&&!st.shiftKey){const kt=Math.min(de.start,de.end,$e),Mt=Math.max(de.start,de.end,$e);return je({start:kt,end:Mt}),mt.current=!1,De.current=null,!0}if(mt.current=!0,De.current=$e,de&&st.shiftKey){const kt=Math.min(de.start,$e),Mt=Math.max(de.end,$e);je({start:kt,end:Mt})}else je({start:$e,end:$e});return!0},mouseover:(ge,Ee,st)=>{if(!(st instanceof MouseEvent)||st.buttons!==1||!mt.current||De.current===null)return!1;const $e=ge.state.doc.lineAt(Ee.from).number,kt=Math.min(De.current,$e),Mt=Math.max(De.current,$e);return je({start:kt,end:Mt}),!1},mouseup:()=>(mt.current=!1,De.current=null,!1)}}})}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),de&&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&&Pt?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:n&&!Pt&&It>0?`${It}px`:"16px"},"data-keyboard-avoid":"true",children:ot()})})]}),$t=!!(d&&N[d]),wt=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(ir,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{ref:h,value:m,onChange:ge=>f(ge.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(Zt,{className:"h-4 w-4"})})]}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>xe("createFile",{path:l,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New File",children:e.jsx(Sc,{className:"h-4 w-4"})}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>xe("createFolder",{path:l,type:"directory"}),className:"h-8 w-8 p-0 flex-shrink-0",title:"New Folder",children:e.jsx(Ki,{className:"h-4 w-4"})}),e.jsx(Me,{variant:"ghost",size:"sm",onClick:()=>{dt()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(zr,{className:"h-4 w-4"})})]})}),e.jsx(gt,{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(Jt,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):j.length>0?j.map(ge=>{const Ee=E?.path===ge.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{Ut(ge)},className:F("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Ee?"bg-accent/70":"hover:bg-accent/40"),children:[gu(ge.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:ge.path,children:ge.relativePath??ge.path})]})},ge.path)}):$t?Ae(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:[et(),n?x?_t:wt: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:wt}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:_t})]})]})},cp=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Ml},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:br},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:hn},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:im},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:On},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ht},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:dn}],DS={},AS={},ES={};cp.forEach(t=>{DS[t.id]=t.label,AS[t.id]=t.description,ES[t.id]=t});const IS=t=>t==="doom_loop"||t==="external_directory"?"ask":"allow",PS=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},xu=t=>{const r=PS(t);if(r.length===0)return;const s={};for(const c of r)c.permission&&((s[c.permission]||={})[c.pattern]=c.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 c of o){const l=s[c],d=Object.keys(l);if(d.length===1&&d[0]==="*"&&c!=="*"){const u=l["*"],m=IS(c);if(n){if(u===n)continue}else if(u===m)continue;a[c]=u}else c==="*"&&d.length===1&&d[0]==="*"?a[c]=l["*"]:a[c]=l}return Object.keys(a).length>0?a:void 0},TS=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedAgentName:a,agents:c,setSelectedAgent:l,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=Kr(),{setSidebarOpen:p}=Te(),{isMobile:h}=Qt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=i.useMemo(()=>Wt(),[]);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 P=E,D=1;for(;c.some(T=>T.name===P);)P=`${E}-${D}`,D++;d({name:P,scope:"user"}),l(P),t?.(),h&&p(!1)},S=async E=>{if(tn(E)){G.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${E.name}"?`)&&(await m(E.name)?G.success(`Agent "${E.name}" deleted successfully`):G.error("Failed to delete agent"))},N=async E=>{tn(E)&&window.confirm(`Are you sure you want to reset agent "${E.name}" to its default configuration?`)&&(await m(E.name)?G.success(`Agent "${E.name}" reset to default`):G.error("Failed to reset agent"))},b=E=>{const P=E.name;let D=1,T=`${P}-copy`;for(;c.some(_=>_.name===T);)D++,T=`${P}-copy-${D}`;const L=E,V=E.model?.providerID&&E.model?.modelID?`${E.model.providerID}/${E.model.modelID}`:null,q=E;d({name:T,scope:L.scope||"user",description:E.description,model:V,temperature:E.temperature,top_p:E.topP,prompt:E.prompt,mode:E.mode,permission:xu(E.permission),disable:q.disable}),l(T),h&&p(!1)},k=E=>{o(E.name),s(E)},A=async()=>{if(!r)return;const E=n.trim().replace(/\s+/g,"-");if(!E){G.error("Agent name is required");return}if(E===r.name){s(null);return}if(c.some(L=>L.name===E)){G.error("An agent with this name already exists");return}const P=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,D=r;await u({name:E,description:r.description,model:P,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:xu(r.permission),disable:D.disable,scope:D.scope})?await m(r.name)?(G.success(`Agent renamed to "${E}"`),l(E)):G.error("Failed to remove old agent after rename"):G.error("Failed to rename agent"),s(null)},j=E=>{switch(E){case"primary":return e.jsx(mn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(bm,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(ym,{className:"h-3 w-3 text-primary"});default:return null}},M=c.filter(E=>!Om(E)),C=M.filter(tn),I=M.filter(E=>!tn(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(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:M.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(ho,{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(yu,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),t?.(),h&&p(!1)},onReset:()=>N(E),onDuplicate:()=>b(E),getAgentModeIcon:j},E.name))]}),I.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"}),I.map(E=>e.jsx(yu,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),t?.(),h&&p(!1)},onRename:()=>k(E),onDelete:()=>S(E),onDuplicate:()=>b(E),getAgentModeIcon:j},E.name))]})]})}),e.jsx(xs,{open:r!==null,onOpenChange:E=>!E&&s(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Rename Agent"}),e.jsxs(Ns,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:E=>o(E.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:E=>{E.key==="Enter"&&A()}}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(pn,{onClick:A,children:"Rename"})]})]})})]})},yu=({agent:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:c,getAgentModeIcon:l})=>{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}),l(t.mode),(d.scope||tn(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:tn(t)?"system":d.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx(Me,{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(Vr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(Vn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),c()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Is,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Nt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Ms({className:t,variant:r,...s}){return e.jsx(Me,{variant:r,size:"sm",className:F("h-6 px-2 text-xs",t),...s})}const FS=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),RS=t=>{if(typeof t!="number"||Number.isNaN(t))return"";if(t===0)return"0";const r=FS.format(t);return r.endsWith(".0")?r.slice(0,-2):r},cc=({providerId:t,modelId:r,onChange:s,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:c}=at(),l=Te(z=>z.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=Te(),{favoriteModelsList:f,recentModelsList:p}=nc(),{isMobile:h}=Qt(),x=l||h,[g,w]=i.useState(!1),[y,v]=i.useState(new Set),[S,N]=i.useState(!1),[b,k]=i.useState(""),[A,j]=i.useState(0),M=i.useRef([]),C=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),I=i.useMemo(()=>C?a.filter(z=>C.has(String(z.id))):a,[a,C]),E=()=>w(!1),P=z=>{v(re=>{const te=new Set(re);return te.has(z)?te.delete(z):te.add(z),te})};i.useEffect(()=>{S||(k(""),j(0))},[S]),i.useEffect(()=>{j(0)},[b]);const D=z=>{const re=z?.name||z?.id||"",te=String(re);return te.length>40?te.substring(0,37)+"...":te},T=(z,re)=>{const te=`${z}/${re}`;return c.get(te)},L=(z,re)=>{s(z,re),z&&re&&m(z,re),N(!1)},V=(z,re)=>{if(!b.trim())return!0;const te=b.toLowerCase();return z.toLowerCase().includes(te)||re.toLowerCase().includes(te)},q=(z,re,te,pe,R,ee)=>{const B=T(re,te),W=RS(B?.limit?.context),X=t===re&&r===te,ie=u(re,te);return e.jsxs("div",{ref:be=>{M.current[R]=be},className:F("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",ee?"bg-accent":"hover:bg-accent/50"),onClick:()=>L(re,te),onMouseEnter:()=>j(R),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:D(z)}),W?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:W}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[X&&e.jsx(Gt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:be=>{be.preventDefault(),be.stopPropagation(),d(re,te)},className:F("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",ie?"text-yellow-500":"text-muted-foreground"),"aria-label":ie?"Unfavorite":"Favorite",title:ie?"Remove from favorites":"Add to favorites",children:ie?e.jsx(Nr,{className:"h-3.5 w-3.5"}):e.jsx(En,{className:"h-3.5 w-3.5"})})]})]},`${pe}-${re}-${te}`)},_=f.filter(({model:z,providerID:re})=>{if(C&&!C.has(re))return!1;const pe=a.find(ee=>ee.id===re)?.name||re,R=D(z);return V(R,pe)}),Y=p.filter(({model:z,providerID:re})=>{if(C&&!C.has(re))return!1;const pe=a.find(ee=>ee.id===re)?.name||re,R=D(z);return V(R,pe)}),K=I.map(z=>{const te=(Array.isArray(z.models)?z.models:[]).filter(pe=>{const R=D(pe);return V(R,z.name||z.id||"")});return{...z,models:te}}).filter(z=>z.models.length>0),U=_.length>0||Y.length>0||K.length>0,Q=()=>x?e.jsx($s,{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:z,providerID:re,modelID:te})=>{const pe=re===t&&te===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",pe?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{L(re,te),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:re,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:D(z)})]})}),e.jsx("button",{onClick:R=>{R.preventDefault(),R.stopPropagation(),d(re,te)},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(Nr,{className:"h-4 w-4"})})]},`fav-mobile-${re}-${te}`)})})]}),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:z,providerID:re,modelID:te})=>{const pe=re===t&&te===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",pe?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{L(re,te),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:re,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:D(z)})]})}),e.jsx("button",{onClick:R=>{R.preventDefault(),R.stopPropagation(),d(re,te)},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(En,{className:"h-4 w-4"})})]},`recent-mobile-${re}-${te}`)})})]}),I.map(z=>{const re=Array.isArray(z.models)?z.models:[];if(re.length===0)return null;const te=z.id===t,pe=y.has(z.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:()=>P(z.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:z.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:z.name}),te&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),pe?e.jsx(Ot,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Bs,{className:"h-3 w-3 text-muted-foreground"})]}),pe&&e.jsx("div",{className:"border-t border-border/20",children:re.map(R=>{const ee=z.id===t&&R.id===r;return e.jsxs("div",{className:F("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ee?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{L(z.id,R.id),E()},children:e.jsx("span",{className:"font-medium truncate",children:D(R)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:B=>{B.preventDefault(),B.stopPropagation(),d(z.id,R.id)},className:F("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(z.id,R.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(z.id,R.id)?"Unfavorite":"Favorite",children:u(z.id,R.id)?e.jsx(Nr,{className:"h-4 w-4"}):e.jsx(En,{className:"h-4 w-4"})}),ee&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},R.id)})})]},z.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{L("",""),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(ws,{providerId:t,className:"h-3.5 w-3.5"}):e.jsx(kr,{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(Ot,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(es,{open:S,onOpenChange:N,children:[e.jsx(ts,{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(ws,{providerId:t,className:"h-3 w-3 flex-shrink-0"}),e.jsx(kr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(kr,{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(Ot,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(ss,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const z=[];_.forEach(({model:R,providerID:ee,modelID:B})=>{z.push({model:R,providerID:ee,modelID:B,section:"fav"})}),Y.forEach(({model:R,providerID:ee,modelID:B})=>{z.push({model:R,providerID:ee,modelID:B,section:"recent"})}),K.forEach(R=>{R.models.forEach(ee=>{z.push({model:ee,providerID:R.id,modelID:ee.id,section:"provider"})})});const re=z.length,te=R=>{if(R.key==="ArrowDown"){R.preventDefault(),R.stopPropagation();const ee=(A+1)%Math.max(1,re);j(ee),setTimeout(()=>{M.current[ee]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(R.key==="ArrowUp"){R.preventDefault(),R.stopPropagation();const ee=(A-1+Math.max(1,re))%Math.max(1,re);j(ee),setTimeout(()=>{M.current[ee]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(R.key==="Enter"){R.preventDefault(),R.stopPropagation();const ee=z[A];ee&&L(ee.providerID,ee.modelID)}else R.key==="Escape"&&(R.preventDefault(),R.stopPropagation(),N(!1))};let pe=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(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{type:"text",placeholder:"Search models",value:b,onChange:R=>k(R.target.value),onKeyDown:te,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:F("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>L("",""),children:[e.jsx(Zt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!t&&!r&&e.jsx(Gt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ds,{}),!U&&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(_r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Nr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),_.map(({model:R,providerID:ee,modelID:B})=>{const W=pe++;return q(R,ee,B,"fav",W,A===W)})]}),Y.length>0&&e.jsxs(e.Fragment,{children:[_.length>0&&e.jsx(Ds,{}),e.jsxs(_r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(yr,{className:"h-4 w-4"}),"Recent"]}),Y.map(({model:R,providerID:ee,modelID:B})=>{const W=pe++;return q(R,ee,B,"recent",W,A===W)})]}),(_.length>0||Y.length>0)&&K.length>0&&e.jsx(Ds,{}),K.map((R,ee)=>e.jsxs(i.Fragment,{children:[ee>0&&e.jsx(Ds,{}),e.jsxs(_r,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ws,{providerId:R.id,className:"h-4 w-4 flex-shrink-0"}),R.name]}),R.models.map(B=>{const W=pe++;return q(B,R.id,B.id,"provider",W,A===W)})]},R.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()})]}),Q()]})},LS=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],Ar=t=>t==="allow"||t==="ask"||t==="deny",OS=t=>{if(Ar(t))return t;if(t&&typeof t=="object"&&!Array.isArray(t)){const r=t["*"];if(Ar(r))return r}},_S=t=>{if(Ar(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=OS(n);o!==void 0&&(r[s]=o)}return{entries:r}},$S=t=>{const r={...t},s=r["*"];return Ar(s)?(delete r["*"],{defaultOverride:s,overrides:r}):{defaultOverride:"default",overrides:r}},ei=t=>t==="doom_loop"||t==="external_directory"?"ask":"allow",fa=(t,r)=>r==="default"?ei(t):r,bu=(t,r)=>{const s={...t};for(const[n,o]of Object.entries(t)){if(n==="*")continue;const a=fa(n,r),c=ei(n);if(!(Ar(o)&&o!==c)){if(Ar(o)&&o===a){delete s[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const l=o,d=Object.keys(l),u=l["*"];if(u!==void 0&&u!==c)continue;d.length===1&&d[0]==="*"&&u===a&&delete s[n]}}}return s},dp=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},BS=t=>{const r=dp(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,c]of Object.entries(s)){if(a==="*"){o[a]=c;continue}const l=ei(a);if(n){if(c===n)continue}else if(c===l)continue;o[a]=c}return{entries:o}},zS=()=>{const{selectedAgentName:t,getAgentByName:r,createAgent:s,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:c}=Kr();at();const l=t?r(t):null,d=!!(a&&a.name===t&&!l),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,x]=i.useState(""),[g,w]=i.useState("subagent"),[y,v]=i.useState(""),[S,N]=i.useState(void 0),[b,k]=i.useState(void 0),[A,j]=i.useState(""),[M,C]=i.useState("default"),[I,E]=i.useState({}),[P,D]=i.useState(""),[T,L]=i.useState(!1),V=bt(W=>W.currentDirectory??null),[q,_]=i.useState([]),Y=bo(W=>W.permissions);i.useEffect(()=>{let W=!1;return(async()=>{const ie=await Fe.listToolIds({directory:V});if(W)return;const be=new Set(["write","patch","multiedit"]),H=ie.map(me=>typeof me=="string"?me.trim():"").filter(Boolean).filter(me=>me!=="*").filter(me=>me!=="invalid").filter(me=>!be.has(me));_(Array.from(new Set(H)).sort((me,we)=>me.localeCompare(we)))})(),()=>{W=!0}},[V]);const K=i.useMemo(()=>{const W=new Set;for(const X of o){const ie=dp(X.permission);if(ie)for(const be of ie)be.permission&&be.permission!=="*"&&be.permission!=="invalid"&&W.add(be.permission)}for(const X of Y.values())for(const ie of X){const be=ie.permission?.trim();be&&be!=="invalid"&&W.add(be)}for(const X of q)W.add(X);return Array.from(W).sort((X,ie)=>X.localeCompare(ie))},[o,Y,q]),U=i.useCallback(W=>{const X=I[W];if(Ar(X))return X;if(X&&typeof X=="object"&&!Array.isArray(X)){const ie=X["*"];if(Ar(ie))return ie}},[I]),Q=i.useCallback(W=>{const X=I[W];return!X||typeof X!="object"||Array.isArray(X)?0:Object.keys(X).filter(be=>be!=="*").length},[I]),z=i.useCallback((W,X)=>{W!=="*"&&E(ie=>{const be={...ie},H=be[W],me=fa(W,M),we=ei(W),he=X===me&&X===we;if(H&&typeof H=="object"&&!Array.isArray(H)){const _e={...H};_e["*"]=X;const se=Object.keys(_e).filter(J=>J!=="*");return he&&se.length===0?(delete be[W],be):(be[W]=_e,be)}return he?(delete be[W],be):(be[W]=X,be)})},[M]),re=i.useCallback(W=>{E(X=>{if(!(W in X))return X;const ie={...X};return delete ie[W],ie})},[]),te=i.useMemo(()=>{const W=Object.entries(I).filter(([X])=>X!=="*");return W.sort(([X],[ie])=>X.localeCompare(ie)),W},[I]),pe=i.useMemo(()=>{const W=new Set;for(const X of LS)W.add(X);for(const X of K)W.add(X);for(const X of Object.keys(I))W.delete(X);return Array.from(W).sort((X,ie)=>X.localeCompare(ie))},[K,I]),R=i.useCallback(W=>{const X=P.trim();if(!X)return;const ie=fa(X,M);if(W===ie){const be=M==="default"?"OpenCode defaults":`Default Permissions ("${M}")`;G.message(`"${X}" already matches ${be} (${ie}).`),D("");return}z(X,W),D("")},[P,z,M]),ee=i.useCallback(W=>W==="webfetch"?"WebFetch":W==="websearch"?"WebSearch":W==="codesearch"?"CodeSearch":W==="doom_loop"?"Doom Loop":W==="external_directory"?"External Directory":W==="todowrite"?"TodoWrite":W==="todoread"?"TodoRead":W.split(/[_-]+/g).filter(Boolean).map(X=>X.charAt(0).toUpperCase()+X.slice(1)).join(" "),[]);i.useEffect(()=>{D("");const W=X=>{const ie=$S(X);C(ie.defaultOverride),E(bu(ie.overrides,ie.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),x(a.description||""),w(a.mode||"subagent"),v(a.model||""),N(a.temperature),k(a.top_p),j(a.prompt||"");const X=_S(a.permission);W(X.entries);return}if(l&&t===l.name){x(l.description||""),w(l.mode||"subagent"),l.model?.providerID&&l.model?.modelID?v(`${l.model.providerID}/${l.model.modelID}`):v(""),N(l.temperature),k(l.topP),j(l.prompt||"");const X=BS(l.permission);W(X.entries)}},[a,d,l,t]);const B=async()=>{const W=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!W){G.error("Agent name is required");return}if(d&&o.some(X=>X.name===W)){G.error("An agent with this name already exists");return}L(!0);try{const X=y.trim(),ie={name:W,description:h.trim()||void 0,mode:g,model:X===""?null:X,temperature:S,top_p:b,prompt:A.trim()||void 0,permission:(()=>{const H=bu(I,M),me=M==="default"?H:{"*":M,...H},we=["doom_loop","external_directory"];for(const _e of we)if(!(_e in me)){const se=I[_e];Ar(se)?me[_e]=se:me[_e]=fa(_e,M)}return Object.keys(me).length===0?d?void 0:null:me})(),scope:d?f:void 0};let be;d?(be=await s(ie),be&&c(null)):be=await n(W,ie),be?G.success(d?"Agent created successfully":"Agent updated successfully"):G.error(d?"Failed to create agent":"Failed to update agent")}catch(X){console.error("Error saving agent:",X);const ie=X instanceof Error&&X.message?X.message:"An error occurred while saving";G.error(ie)}finally{L(!1)}};return t?e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Agent":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(jt,{value:u,onChange:W=>m(W.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Ls,{value:f,onValueChange:W=>p(W),children:[e.jsxs(Os,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Qs,{className:"h-4 w-4"}):e.jsx(lr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(_s,{align:"end",children:[e.jsx(rs,{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(Qs,{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(rs,{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(lr,{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:W=>x(W.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(Ms,{variant:g==="primary"?"default":"outline",onClick:()=>w("primary"),className:F("gap-2",g==="primary"?void 0:"text-foreground"),children:[e.jsx(mn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Ms,{variant:g==="subagent"?"default":"outline",onClick:()=>w("subagent"),className:F("gap-2",g==="subagent"?void 0:"text-foreground"),children:[e.jsx(ym,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Ms,{variant:g==="all"?"default":"outline",onClick:()=>w("all"),className:F("gap-2",g==="all"?void 0:"text-foreground"),children:[e.jsx(bm,{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(cc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(W,X)=>{v(W&&X?`${W}/${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(ps,{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);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(ii,{className:"h-3.5 w-3.5"})}),e.jsx(jt,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:W=>{const X=W.target.value;if(X===""){N(void 0);return}const ie=parseFloat(X);!isNaN(ie)&&ie>=0&&ie<=2&&N(ie)},onBlur:W=>{const X=W.target.value;if(X!==""){const ie=parseFloat(X);if(!isNaN(ie)){const be=Math.max(0,Math.min(2,ie));N(parseFloat(be.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);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(is,{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(ps,{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);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(ii,{className:"h-3.5 w-3.5"})}),e.jsx(jt,{type:"text",inputMode:"decimal",value:b!==void 0?b:"",onChange:W=>{const X=W.target.value;if(X===""){k(void 0);return}const ie=parseFloat(X);!isNaN(ie)&&ie>=0&&ie<=1&&k(ie)},onBlur:W=>{const X=W.target.value;if(X!==""){const ie=parseFloat(X);if(!isNaN(ie)){const be=Math.max(0,Math.min(1,ie));k(parseFloat(be.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);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(is,{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:A,onChange:W=>j(W.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(Me,{size:"sm",variant:M==="default"?"default":"outline",onClick:()=>C("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(Me,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>C("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Me,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>C("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Me,{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(ps,{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(Ls,{value:P,onValueChange:D,children:[e.jsx(Os,{className:"h-8 w-full sm:w-72",children:P?e.jsx("span",{className:"truncate",children:ee(P)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(_s,{children:pe.map(W=>e.jsx(rs,{value:W,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:ee(W)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:W})]})},W))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Me,{size:"sm",variant:"outline",disabled:!P,onClick:()=>R("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Me,{size:"sm",variant:"outline",disabled:!P,onClick:()=>R("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Me,{size:"sm",variant:"outline",disabled:!P,onClick:()=>R("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),te.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:te.map(([W])=>{const X=U(W),ie=Q(W),be=ee(W);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:[e.jsx("span",{children:be}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:W}),e.jsxs(lt,{delayDuration:1e3,children:[e.jsx(ct,{asChild:!0,children:e.jsx(ps,{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']}),ie>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",ie," pattern rules preserved"]}):null]})})]})]}),e.jsxs(Me,{size:"sm",variant:"outline",onClick:()=>re(W),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(ii,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Me,{size:"sm",variant:X==="allow"?"default":"outline",onClick:()=>z(W,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Me,{size:"sm",variant:X==="ask"?"default":"outline",onClick:()=>z(W,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Me,{size:"sm",variant:X==="deny"?"default":"outline",onClick:()=>z(W,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},W)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Me,{size:"sm",variant:"default",onClick:B,disabled:T,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(za,{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(ho,{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"})]})})},WS=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedCommandName:a,commands:c,setSelectedCommand:l,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=qr(),{setSidebarOpen:p}=Te(),{isMobile:h}=Qt(),[x,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=i.useMemo(()=>Wt(),[]);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 I=C,E=1;for(;c.some(P=>P.name===I);)I=`${C}-${E}`,E++;d({name:I,scope:"user"}),l(I),t?.(),h&&p(!1)},S=async C=>{if(Mn(C)){G.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${C.name}"?`)&&(await m(C.name)?G.success(`Command "${C.name}" deleted successfully`):G.error("Failed to delete command"))},N=async C=>{Mn(C)&&window.confirm(`Are you sure you want to reset command "${C.name}" to its default configuration?`)&&(await m(C.name)?G.success(`Command "${C.name}" reset to default`):G.error("Failed to reset command"))},b=C=>{const I=C.name;let E=1,P=`${I}-copy`;for(;c.some(D=>D.name===P);)E++,P=`${I}-copy-${E}`;d({name:P,scope:C.scope||"user",description:C.description,template:C.template,agent:C.agent,model:C.model,subtask:C.subtask}),l(P),h&&p(!1)},k=C=>{o(C.name),s(C)},A=async()=>{if(!r)return;const C=n.trim().replace(/\s+/g,"-");if(!C){G.error("Command name is required");return}if(C===r.name){s(null);return}if(c.some(E=>E.name===C)){G.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)?(G.success(`Command renamed to "${C}"`),l(C)):G.error("Failed to remove old command after rename"):G.error("Failed to rename command"),s(null)},j=c.filter(Mn),M=c.filter(C=>!Mn(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 ",c.length]}),e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:c.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ur,{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,I)=>C.name.localeCompare(I.name)).map(C=>e.jsx(wu,{command:C,isSelected:a===C.name,onSelect:()=>{l(C.name),t?.(),h&&p(!1)},onReset:()=>N(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,I)=>C.name.localeCompare(I.name)).map(C=>e.jsx(wu,{command:C,isSelected:a===C.name,onSelect:()=>{l(C.name),t?.(),h&&p(!1)},onRename:()=>k(C),onDelete:()=>S(C),onDuplicate:()=>b(C)},C.name))]})]})}),e.jsx(xs,{open:r!==null,onOpenChange:C=>!C&&s(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Rename Command"}),e.jsxs(Ns,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:C=>o(C.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:C=>{C.key==="Enter"&&A()}}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(pn,{onClick:A,children:"Rename"})]})]})})]})},wu=({command:t,isSelected:r,onSelect:s,onDelete:n,onReset:o,onRename:a,onDuplicate:c})=>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||Mn(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:Mn(t)?"system":t.scope})]}),t.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:t.description})]}),e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx(Me,{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(Vr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Vn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),c()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(Is,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Nt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),up=({agentName:t,onChange:r,className:s})=>{const{loadAgents:n,getVisibleAgents:o}=Kr(),a=o(),c=Te(x=>x.isMobile),{isMobile:l}=Qt(),d=c||l,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=x=>{r(x)},h=()=>d?e.jsx($s,{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(ho,{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(Ot,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(es,{children:[e.jsx(ts,{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(ho,{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(Ot,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(ss,{className:"max-w-[300px]",children:[a.map(x=>e.jsx(Nt,{className:"typography-meta",onSelect:()=>p(x.name),children:e.jsx("span",{className:"font-medium",children:x.name})},x.name)),e.jsx(Nt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},HS=()=>{const{selectedCommandName:t,getCommandByName:r,createCommand:s,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:c}=qr(),l=t?r(t):null,d=!!(a&&a.name===t&&!l),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,x]=i.useState(""),[g,w]=i.useState(""),[y,v]=i.useState(""),[S,N]=i.useState(""),[b,k]=i.useState(!1),[A,j]=i.useState(!1);i.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),x(a.description||""),w(a.agent||""),v(a.model||""),N(a.template||""),k(a.subtask||!1)):l&&(x(l.description||""),w(l.agent||""),v(l.model||""),N(l.template||""),k(l.subtask||!1))},[l,d,t,o,a]);const M=async()=>{const C=d?u.trim().replace(/\s+/g,"-"):t?.trim();if(!C){G.error("Command name is required");return}if(!S.trim()){G.error("Command template is required");return}if(d&&o.some(I=>I.name===C)){G.error("A command with this name already exists");return}j(!0);try{const I=g.trim(),E=y.trim(),P=S.trim(),D={name:C,description:h.trim()||void 0,agent:I===""?null:I,model:E===""?null:E,template:P,subtask:b,scope:d?f:void 0};let T;d?(T=await s(D),T&&c(null)):T=await n(C,D),T?G.success(d?"Command created successfully":"Command updated successfully"):G.error(d?"Failed to create command":"Failed to update command")}catch(I){console.error("Error saving command:",I),G.error("An error occurred while saving")}finally{j(!1)}};return t?e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Command":`/${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(jt,{value:u,onChange:C=>m(C.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Ls,{value:f,onValueChange:C=>p(C),children:[e.jsxs(Os,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Qs,{className:"h-4 w-4"}):e.jsx(lr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(_s,{align:"end",children:[e.jsx(rs,{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(Qs,{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(rs,{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(lr,{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(up,{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(cc,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(C,I)=>{v(C&&I?`${C}/${I}`:"")}}),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=>k(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(Gt,{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(ps,{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=>N(C.target.value),placeholder:`Your command template here...
133
-
134
- Use $ARGUMENTS to reference user input.
135
- Use !\`shell command\` to inject shell output.
136
- 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(ps,{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(ps,{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(ps,{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(Me,{size:"sm",variant:"default",onClick:M,disabled:A,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(za,{className:"h-3 w-3"}),A?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ur,{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"})]})})},US=({onItemSelect:t})=>{const[r,s]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:c,setSelectedSkill:l,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=nr(),{setSidebarOpen:h}=Te(),{isMobile:x}=Qt(),[g,w]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Wt(),[]);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 I=C,E=1;for(;c.some(P=>P.name===I);)I=`${C}-${E}`,E++;d({name:I,scope:"user",description:""}),l(I),t?.(),x&&h(!1)},N=async C=>{window.confirm(`Are you sure you want to delete skill "${C.name}"?`)&&(await m(C.name)?G.success(`Skill "${C.name}" deleted successfully`):G.error("Failed to delete skill"))},b=async C=>{const I=C.name;let E=1,P=`${I}-copy`;for(;c.some(T=>T.name===P);)E++,P=`${I}-copy-${E}`;const D=await p(C.name);if(!D){G.error("Failed to load skill details for duplication");return}d({name:P,scope:C.scope||"user",description:(D.sources.md.fields.includes("description"),""),instructions:""}),l(P),x&&h(!1)},k=C=>{o(C.name),s(C)},A=async()=>{if(!r)return;const C=n.trim().replace(/\s+/g,"-").toLowerCase();if(!C){G.error("Skill name is required");return}if(C===r.name){s(null);return}if(c.some(P=>P.name===C)){G.error("A skill with this name already exists");return}if(!await p(r.name)){G.error("Failed to load skill details"),s(null);return}await u({name:C,description:"Renamed skill",scope:r.scope})?await m(r.name)?(G.success(`Skill renamed to "${C}"`),l(C)):G.error("Failed to remove old skill after rename"):G.error("Failed to rename skill"),s(null)},j=c.filter(C=>C.scope==="project"),M=c.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 ",c.length]}),e.jsx(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:c.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(wm,{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(vu,{skill:C,isSelected:a===C.name,onSelect:()=>{l(C.name),t?.(),x&&h(!1)},onRename:()=>k(C),onDelete:()=>N(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(vu,{skill:C,isSelected:a===C.name,onSelect:()=>{l(C.name),t?.(),x&&h(!1)},onRename:()=>k(C),onDelete:()=>N(C),onDuplicate:()=>b(C)},C.name))]})]})}),e.jsx(xs,{open:r!==null,onOpenChange:C=>!C&&s(null),children:e.jsxs(ys,{children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Rename Skill"}),e.jsxs(Ns,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:C=>o(C.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:C=>{C.key==="Enter"&&A()}}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>s(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(pn,{onClick:A,children:"Rename"})]})]})})]})},vu=({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(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx(Me,{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(Vr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(Vn,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Nt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function mp({tabs:t,value:r,onValueChange:s,className:n,isInteractive:o=!0,animate:a=!0}){const c=i.useRef(null),l=i.useRef(null),d=i.useCallback(()=>{const u=c.current,m=l.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=c.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:c,"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?l: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 VS=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,GS=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},qS=async()=>{try{if(ls())return await Ir();const t=As()?.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}},KS=({open:t,onOpenChange:r})=>{const{scanRepo:s,loadCatalog:n,isScanning:o}=So(),a=Wn(C=>C.defaultGitIdentityId),c=Wn(C=>C.loadDefaultGitIdentityId),[l,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,N]=i.useState([]),[b,k]=i.useState(null);i.useEffect(()=>{t&&(d(""),m(""),p(""),w(null),v(!1),N([]),k(null),c(),(async()=>{const C=await qS(),I=Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[];x(I||[])})())},[t,c]);const A=i.useMemo(()=>{const C=u.trim(),I=f.trim();return h.some(E=>{const P=(E.source||"").trim(),D=(E.subpath||"").trim();return P===C&&D===I})},[h,u,f]),j=async()=>{const C=u.trim();if(!C){G.error("Repository source is required");return}l.trim()||d(GS(C)),v(!1),w(null);const I=await s({source:C,subpath:f.trim()||void 0,gitIdentityId:b||void 0});if(!I.ok){if(I.error?.kind==="authRequired"){if(Wt()){G.error("Private repositories are not supported in VS Code yet");return}const P=I.error.identities||[];if(N(P),!b&&P.length>0){const D=a&&a!=="global"&&P.some(T=>T.id===a)?a:P[0].id;k(D)}G.error("Authentication required. Select a Git identity and scan again.");return}G.error(I.error?.message||"Failed to scan repository");return}const E=I.items?.length||0;if(w(E),E===0){G.error("No skills found in this repository"),v(!1);return}N([]),v(!0),G.success(`Found ${E} skill(s)`)},M=async()=>{const C=l.trim(),I=u.trim(),E=f.trim();if(!C){G.error("Catalog name is required");return}if(!I){G.error("Repository source is required");return}if(!y){G.error("Scan the repository before adding this catalog");return}if(A){G.error("This catalog already exists");return}const P={id:VS(),label:C,source:I,...E?{subpath:E}:{},...b?{gitIdentityId:b}:{}},D=[...h,P];try{await us({skillCatalogs:D}),x(D),G.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(T){G.error(T instanceof Error?T.message:"Failed to save catalog")}};return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Add skills catalog"}),e.jsxs(Ns,{children:["Add a Git repository as a new catalog source. OpenChamber will scan it for folders containing ",e.jsx("code",{className:"font-mono",children:"SKILL.md"}),"."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Catalog name"}),e.jsx(jt,{value:l,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(jt,{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(jt,{value:f,onChange:C=>{p(C.target.value),v(!1),w(null)},placeholder:"e.g. skills"})]}),S.length>0&&!Wt()?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Authentication required"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:"Select a Git identity (SSH key) that can access this repository."}),e.jsx("div",{className:"mt-2",children:e.jsxs(Ls,{value:b||"",onValueChange:C=>k(C),children:[e.jsx(Os,{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(rs,{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,A?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(Me,{variant:"outline",onClick:()=>{j()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(rm,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Me,{variant:"default",onClick:()=>{M()},disabled:!y||A||!l.trim()||!u.trim(),children:"Add catalog"})]})]})})},QS=({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 c=d=>{const u={};for(const m of s)u[m.skillName]=d;a(u)},l=s.length>0&&s.every(d=>o[d.skillName]);return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-2xl",children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Skills already exist"}),e.jsx(Ns,{children:"Some selected skills are already installed in this scope. Choose whether to skip or overwrite them."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[s.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{variant:"outline",size:"sm",onClick:()=>c("skip"),children:"Skip all"}),e.jsx(Me,{variant:"outline",size:"sm",onClick:()=>c("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(Ls,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Os,{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(rs,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(rs,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(pn,{onClick:()=>n(o),disabled:!l,children:"Continue"})]})]})})},YS=({open:t,onOpenChange:r,item:s})=>{const{installSkills:n,isInstalling:o}=So(),[a,c]=i.useState("user"),[l,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{t&&(c("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){G.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"){G.error(w.error.message||"Authentication required");return}G.error(w.error?.message||"Failed to install skill")};return s?e.jsxs(e.Fragment,{children:[e.jsx(xs,{open:t,onOpenChange:r,children:e.jsxs(ys,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Install skill"}),e.jsxs(Ns,{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(zs,{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(Ls,{value:a,onValueChange:x=>c(x),children:[e.jsx(Os,{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(Qs,{className:"h-4 w-4"}):e.jsx(lr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(_s,{align:"start",children:[e.jsx(rs,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Qs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(rs,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lr,{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(Me,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Me,{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(QS,{open:l,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},XS=async()=>{try{if(ls())return await Ir();const t=As()?.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}},JS=({mode:t,onModeChange:r})=>{const{sources:s,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:c,isLoadingCatalog:l,lastCatalogError:d}=So(),[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(()=>{c()},[c]);const S=i.useMemo(()=>o?n[o]||[]:[],[n,o]),N=i.useMemo(()=>{const j=u.trim().toLowerCase();return j?S.filter(M=>{const C=M.skillName.toLowerCase(),I=(M.description||"").toLowerCase(),E=(M.frontmatterName||"").toLowerCase();return C.includes(j)||I.includes(j)||E.includes(j)}):S},[S,u]),b=i.useMemo(()=>s.find(j=>j.id===o)||null,[s,o]),k=!!(o&&o.startsWith("custom:")),A=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){v(!0);try{const j=await XS(),C=(Array.isArray(j?.skillCatalogs)?j?.skillCatalogs:[]).filter(I=>I.id!==o);await us({skillCatalogs:C}),await c({refresh:!0})}finally{v(!1)}}};return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(mp,{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(Ls,{value:o||"",onValueChange:j=>a(j),children:[e.jsx(Os,{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(rs,{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(Me,{type:"button",variant:"outline",onClick:()=>{c({refresh:!0})},disabled:l,className:"gap-2",children:[e.jsx(zr,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(Me,{type:"button",variant:"outline",onClick:()=>{A()},disabled:y,className:"gap-2",children:[e.jsx(Us,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Me,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(is,{className:"h-4 w-4"}),"Add catalog"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(jt,{value:u,onChange:j=>m(j.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:l?"Loading…":`${N.length} skill(s)`})]}),d?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.length===0?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):N.map(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(Wr,{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(En,{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(Me,{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(KS,{open:f,onOpenChange:p}),e.jsx(YS,{open:h,onOpenChange:x,item:g})]})})},ZS=()=>{const{selectedSkillName:t,getSkillByName:r,getSkillDetail:s,createSkill:n,updateSkill:o,skills:a,skillDraft:c,setSkillDraft:l,setSelectedSkill:d}=nr(),u=t?r(t):null,m=!!(c&&c.name===t&&!u),f=!!(t&&!u&&!c),[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(mp,{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,N]=i.useState(""),[b,k]=i.useState(""),[A,j]=i.useState([]),[M,C]=i.useState([]),[I,E]=i.useState(!1),[P,D]=i.useState(!1),[T,L]=i.useState(""),[V,q]=i.useState(""),[_,Y]=i.useState(!1),[K,U]=i.useState(""),[Q,z]=i.useState(""),[re,te]=i.useState(null),[pe,R]=i.useState(!1),[ee,B]=i.useState(""),W=m?g.trim()!==""||S.trim()!==""||b.trim()!==""||M.length>0:S!==T||b!==V,X=re?Q!==ee:K.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&c)w(c.name||""),v(c.scope||"user"),N(c.description||""),k(c.instructions||""),L(""),q(""),j([]),C(c.pendingFiles||[]);else if(t&&u){D(!0);try{const _e=await s(t);if(_e){const se=_e.sources.md;N(se.description||""),k(se.instructions||""),L(se.description||""),q(se.instructions||""),j(se.supportingFiles||[])}}catch(_e){console.error("Failed to load skill details:",_e)}finally{D(!1)}}})()},[u,m,t,a,c,s,p]);const ie=async()=>{const he=m?g.trim().replace(/\s+/g,"-").toLowerCase():t?.trim();if(!he){G.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(he)||he.length>64){G.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){G.error("Description is required");return}if(m&&a.some(_e=>_e.name===he)){G.error("A skill with this name already exists");return}E(!0);try{const _e={name:he,description:S.trim(),instructions:b.trim()||void 0,scope:m?y:void 0,supportingFiles:m&&M.length>0?M:void 0};let se;m?(se=await n(_e),se&&(l(null),C([]),d(he))):(se=await o(he,_e),se&&(L(S.trim()),q(b.trim()))),se?G.success(m?"Skill created successfully":"Skill updated successfully"):G.error(m?"Failed to create skill":"Failed to update skill")}catch(_e){console.error("Error saving skill:",_e),G.error("An error occurred while saving")}finally{E(!1)}},be=()=>{te(null),U(""),z(""),B(""),Y(!0)},H=async he=>{if(te(he),U(he),m){const se=M.find(J=>J.path===he)?.content||"";z(se),B(se),Y(!0);return}if(t){R(!0),Y(!0);try{const{readSupportingFile:_e}=nr.getState(),se=await _e(t,he);z(se||""),B(se||"")}catch{G.error("Failed to load file content"),z(""),B("")}finally{R(!1)}}},me=async()=>{if(!K.trim()){G.error("File name is required");return}const he=K.trim(),_e=re!==null;if(m){if(_e)C(ne=>ne.map(ke=>ke.path===re?{path:he,content:Q}:ke)),G.success(`File "${he}" updated`);else{if(M.some(ne=>ne.path===he)){G.error("A file with this name already exists");return}C(ne=>[...ne,{path:he,content:Q}]),G.success(`File "${he}" added`)}Y(!1),te(null);return}if(!t){G.error("No skill selected");return}const{writeSupportingFile:se}=nr.getState();if(await se(t,he,Q)){G.success(_e?`File "${he}" updated`:`File "${he}" created`),Y(!1),te(null);const ne=await s(t);ne&&j(ne.sources.md.supportingFiles||[])}else G.error(_e?"Failed to update file":"Failed to create file")},we=async he=>{if(m){C(_e=>_e.filter(se=>se.path!==he)),G.success(`File "${he}" removed`);return}if(t&&window.confirm(`Are you sure you want to delete "${he}"?`)){const{deleteSupportingFile:_e}=nr.getState();if(await _e(t,he)){G.success(`File "${he}" deleted`);const J=await s(t);J&&j(J.sources.md.supportingFiles||[])}else G.error("Failed to delete file")}};return m&&p==="external"?e.jsx(JS,{mode:p,onModeChange:h}):!t&&!c||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(wm,{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"})]})}):P?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skill details..."})})}):e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[m?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(jt,{value:g,onChange:he=>w(he.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(Ls,{value:y,onValueChange:he=>v(he),children:[e.jsxs(Os,{className:"!h-9 w-auto gap-1.5",children:[y==="user"?e.jsx(Qs,{className:"h-4 w-4"}):e.jsx(lr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:y})]}),e.jsxs(_s,{align:"end",children:[e.jsx(rs,{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(Qs,{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(rs,{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(lr,{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:he=>N(he.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:he=>k(he.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(Me,{variant:"outline",size:"sm",onClick:be,className:"gap-1.5",children:[e.jsx(is,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const he=m?M:A;return he.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:he.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:()=>H(_e.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(pr,{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(Me,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:se=>{se.stopPropagation(),we(_e.path)},children:e.jsx(Us,{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(Me,{size:"sm",variant:"default",onClick:ie,disabled:I||!W,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(za,{className:"h-3 w-3"}),I?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(xs,{open:_,onOpenChange:he=>{Y(he),he||te(null)},children:e.jsxs(ys,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(vs,{className:"flex-shrink-0",children:[e.jsx(js,{children:re?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ns,{children:re?"Modify the file content":"Create a new file in the skill directory"})]}),pe?e.jsx("div",{className:"flex-1 flex items-center justify-center py-8",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading file content..."})}):e.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"File Path"}),e.jsx(jt,{value:K,onChange:he=>U(he.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:re!==null}),!re&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Relative path within the skill directory. Subdirectories will be created automatically."})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-h-0 flex flex-col",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:"Content"}),e.jsx(Rs,{value:Q,onChange:he=>z(he.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"ghost",onClick:()=>{Y(!1),te(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(pn,{onClick:me,disabled:pe||!X,children:re?"Save Changes":"Create File"})]})]})})]})})},ek="__add_provider__",tk=({onItemSelect:t})=>{const r=at(u=>u.providers),s=at(u=>u.selectedProviderId),n=at(u=>u.setSelectedProvider),{isMobile:o}=Qt(),[a,c]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||c(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":l?"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(Me,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(ek),t?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(is,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:r.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(On,{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(ws,{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)})})]})},sk=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),ju=t=>{if(typeof t!="number"||Number.isNaN(t))return null;if(t===0)return"0";const r=sk.format(t);return r.endsWith(".0")?r.slice(0,-2):r},Sn="__add_provider__",Hn=t=>typeof t=="object"&&t!==null,Su=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()},rk=t=>{if(!Hn(t))return{};const r={};for(const[s,n]of Object.entries(t))Array.isArray(n)&&(r[s]=n.filter(o=>Hn(o)));return r},nk=t=>{if(typeof t=="string")return{id:t};if(!Hn(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}},ok=t=>{let r=[];Array.isArray(t)?r=t:Hn(t)&&(Array.isArray(t.all)?r=t.all:Array.isArray(t.providers)&&(r=t.providers));const s=r.map(o=>nk(o)).filter(o=>!!o),n=new Set;return s.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},ak=()=>{const t=at(H=>H.providers),r=at(H=>H.selectedProviderId),s=at(H=>H.setSelectedProvider),n=at(H=>H.getModelMetadata),[o,a]=i.useState({}),[c,l]=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({}),[N,b]=i.useState([]),[k,A]=i.useState(!1),[j,M]=i.useState(null),[C,I]=i.useState(""),[E,P]=i.useState(""),[D,T]=i.useState(!1),[L,V]=i.useState({}),[q,_]=i.useState(!1);i.useEffect(()=>{!r&&t.length>0&&s(t[0].id)},[t,r,s]),i.useEffect(()=>{let H=!0;return(async()=>{l(!0);try{const we=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!we.ok)throw new Error(`Auth methods request failed (${we.status})`);const he=await we.json().catch(()=>({}));if(!H)return;a(rk(he))}catch(we){if(!H)return;console.error("Failed to load provider auth methods:",we),G.error("Failed to load provider authentication methods")}finally{H&&l(!1)}})(),()=>{H=!1}},[]),i.useEffect(()=>{let H=!0;return(async()=>{A(!0),M(null);try{const we=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!we.ok)throw new Error(`Provider list request failed (${we.status})`);const he=await we.json().catch(()=>({}));if(!H)return;b(ok(he))}catch(we){if(!H)return;console.error("Failed to load available providers:",we),M("Unable to load provider list")}finally{H&&A(!1)}})(),()=>{H=!1}},[]);const Y=i.useMemo(()=>new Set(t.map(H=>H.id)),[t]),K=i.useMemo(()=>N.filter(H=>!Y.has(H.id)),[N,Y]);i.useEffect(()=>{if(r===Sn){if(!C&&K.length>0){I(K[0].id);return}C&&!K.some(H=>H.id===C)&&I(K[0]?.id??"")}},[r,C,K]),i.useEffect(()=>{if(r===Sn){_(!0);return}_(!1)},[r]),i.useEffect(()=>{if(!r||r===Sn)return;let H=!1;return(async()=>{try{const we=await fetch(`/api/provider/${encodeURIComponent(r)}/source`,{method:"GET",headers:{Accept:"application/json"}}),he=await we.json().catch(()=>null);if(!we.ok)throw new Error(he?.error||"Failed to load provider sources");const _e=he?.sources??he?.data?.sources;!H&&_e&&V(se=>({...se,[r]:_e}))}catch(we){H||console.error("Failed to load provider sources:",we)}})(),()=>{H=!0}},[r]);const U=t.find(H=>H.id===r),Q=r?L[r]:void 0,z=async H=>{const me=d[H]?.trim()??"";if(!me){G.error("API key is required");return}const we=`api:${H}`;f(we);try{const he=await fetch(`/api/auth/${encodeURIComponent(H)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:me})}),_e=await he.json().catch(()=>null);if(!he.ok){const se=_e?.error||"Failed to save API key";throw new Error(se)}G.success("API key saved"),u(se=>({...se,[H]:""})),await io({scopes:["providers"],mode:"active"}),s(H)}catch(he){console.error("Failed to save API key:",he),G.error("Failed to save API key")}finally{f(null)}},re=async(H,me)=>{const we=`oauth:${H}:${me}`;f(we);try{const he=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:me})}),_e=await he.json().catch(()=>null);if(!he.ok){const de=_e?.error||"Failed to start OAuth flow";throw new Error(de)}const se=Hn(_e)?_e:{},J=Hn(se.data)?se.data:se,ne=typeof J.url=="string"&&J.url||typeof J.verification_uri_complete=="string"&&J.verification_uri_complete||typeof J.verification_uri=="string"&&J.verification_uri||void 0,ke=typeof J.instructions=="string"&&J.instructions||typeof J.message=="string"&&J.message||void 0,Z=typeof J.user_code=="string"&&J.user_code||typeof J.code=="string"&&J.code||typeof J.userCode=="string"&&J.userCode||void 0;if(!ne&&!ke&&!Z)throw new Error("No OAuth details returned");const xe=`${H}:${me}`;S(de=>({...de,[xe]:{url:ne,instructions:ke,userCode:Z}})),ne&&window.open(ne,"_blank","noopener,noreferrer"),g({providerId:H,methodIndex:me}),G.message("Complete the OAuth flow in your browser")}catch(he){console.error("Failed to start OAuth flow:",he),G.error("Failed to start OAuth flow")}finally{f(null)}},te=async(H,me)=>{const we=`${H}:${me}`,he=w[we]?.trim(),_e=`oauth-complete:${H}:${me}`;f(_e);try{const se={method:me};he&&(se.code=he);const J=await fetch(`/api/provider/${encodeURIComponent(H)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(se)}),ne=await J.json().catch(()=>null);if(!J.ok){const ke=ne?.error||"Failed to complete OAuth flow";throw new Error(ke)}G.success("OAuth connection completed"),y(ke=>({...ke,[we]:""})),g(null),await io({scopes:["providers"],mode:"active"}),s(H)}catch(se){console.error("Failed to complete OAuth flow:",se),G.error("Failed to complete OAuth flow")}finally{f(null)}},pe=async H=>{try{await navigator.clipboard.writeText(H),G.success("OAuth link copied")}catch(me){console.error("Failed to copy OAuth link:",me),G.error("Failed to copy OAuth link")}},R=async H=>{try{await navigator.clipboard.writeText(H),G.success("Device code copied")}catch(me){console.error("Failed to copy device code:",me),G.error("Failed to copy device code")}},ee=async H=>{const me=`disconnect:${H}`;f(me);try{const we=await fetch(`/api/provider/${encodeURIComponent(H)}/auth?scope=all`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),he=await we.json().catch(()=>null);if(!we.ok){const _e=he?.error||"Failed to disconnect provider";throw new Error(_e)}G.success("Provider disconnected"),await io({scopes:["providers"],mode:"active"})}catch(we){console.error("Failed to disconnect provider:",we),G.error("Failed to disconnect provider")}finally{f(null)}},B=r===Sn;if(!B&&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(On,{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(B)return e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Connect provider"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:"Choose a provider to connect and set up its authentication."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Provider"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select a provider that is not connected yet."})]}),k?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:j}):K.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(es,{open:D,onOpenChange:H=>{T(H),H||P("")},children:[e.jsx(ts,{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?K.find(H=>H.id===C)?.name||C:"Select provider"}),e.jsx(Ot,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(ss,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:H=>H.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:H=>H.stopPropagation(),children:[e.jsx(ir,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:H=>P(H.target.value),onKeyDown:H=>H.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(gt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const H=K.filter(me=>{const we=E.toLowerCase();return(me.name||me.id).toLowerCase().includes(we)||me.id.toLowerCase().includes(we)});return H.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):H.map(me=>e.jsxs(Nt,{onSelect:()=>{I(me.id),T(!1),P("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:me.name||me.id}),C===me.id&&e.jsx(Gt,{className:"h-4 w-4 text-primary"})]},me.id))})()})]})]})]}),C&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{type:"password",value:d[C]??"",onChange:H=>u(me=>({...me,[C]:H.target.value})),placeholder:"sk-..."}),e.jsx(Me,{size:"sm",onClick:()=>z(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 me=(o[C]??[]).filter(we=>Su(we)==="oauth");return me.length===0?null:e.jsx("div",{className:"space-y-3",children:me.map((we,he)=>{const _e=we.label||we.name||`OAuth method ${he+1}`,se=`${C}:${he}`,J=x?.providerId===C&&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:_e}),(we.description||we.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(we.description||we.help)})]}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>re(C,he),disabled:m===`oauth:${C}:${he}`,className:"h-8",children:"Connect"})]}),v[se]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[se]?.instructions}),v[se]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[se]?.userCode,readOnly:!0}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>R(v[se]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[se]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[se]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Me,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[se]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>pe(v[se]?.url??""),className:"h-8",children:"Copy link"})]})]}),J&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:w[se]??"",onChange:ne=>y(ke=>({...ke,[se]:ne.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Me,{size:"sm",onClick:()=>te(C,he),disabled:m===`oauth-complete:${C}:${he}`,className:"h-8",children:m===`oauth-complete:${C}:${he}`?"Saving…":"Complete"})]})]},`${C}-${_e}`)})})})()]})]})]})});if(!U)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(On,{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 W=Array.isArray(U.models)?U.models:[],ie=(o[U.id]??[]).filter(H=>Su(H)==="oauth"),be=W.filter(H=>{const me=typeof H?.name=="string"?H.name:"",we=typeof H?.id=="string"?H.id:"",he=p.trim().toLowerCase();return he?me.toLowerCase().includes(he)||we.toLowerCase().includes(he):!0});return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ws,{providerId:U.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:U.name||U.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",U.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!==Sn&&e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>_(H=>!H),className:"h-8",children:q?"Hide":"Reconnect"})]}),!q&&r!==Sn?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Connected. Use Reconnect to update credentials."}):c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{type:"password",value:d[U.id]??"",onChange:H=>u(me=>({...me,[U.id]:H.target.value})),placeholder:"sk-..."}),e.jsx(Me,{size:"sm",onClick:()=>z(U.id),disabled:m===`api:${U.id}`,className:"h-8",children:m===`api:${U.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."})]}),ie.length>0&&e.jsx("div",{className:"space-y-3",children:ie.map((H,me)=>{const we=H.label||H.name||`OAuth method ${me+1}`,he=`${U.id}:${me}`,_e=x?.providerId===U.id&&x?.methodIndex===me;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:we}),(H.description||H.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(H.description||H.help)})]}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>re(U.id,me),disabled:m===`oauth:${U.id}:${me}`,className:"h-8",children:"Connect"})]}),v[he]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[he]?.instructions}),v[he]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[he]?.userCode,readOnly:!0}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>R(v[he]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[he]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[he]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Me,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[he]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>pe(v[he]?.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(jt,{value:w[he]??"",onChange:se=>y(J=>({...J,[he]:se.target.value})),placeholder:"Paste authorization code"}),e.jsx(Me,{size:"sm",onClick:()=>te(U.id,me),disabled:m===`oauth-complete:${U.id}:${me}`,className:"h-8",children:m===`oauth-complete:${U.id}:${me}`?"Saving…":"Complete"})]})]},`${U.id}-${we}`)})})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Connection"}),Q&&(Q.auth.exists||Q.user.exists||Q.project.exists||Q.custom?.exists)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Configured in: ",[Q.auth.exists?"auth credentials":null,Q.user.exists?"user config":null,Q.project.exists?"project config":null,Q.custom?.exists?"custom config":null].filter(Boolean).join(", ")]}),e.jsx(Me,{size:"sm",variant:"outline",onClick:()=>ee(U.id),disabled:m===`disconnect:${U.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${U.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(jt,{value:p,onChange:H=>h(H.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:be.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):be.map(H=>{const me=typeof H?.id=="string"?H.id:"",we=typeof H?.name=="string"?H.name:me,he=me?n(U.id,me):void 0,_e=ju(he?.limit?.context),se=ju(he?.limit?.output),J=[];return he?.tool_call&&J.push({key:"tools",icon:$a,label:"Tool calling"}),he?.reasoning&&J.push({key:"reasoning",icon:br,label:"Reasoning"}),he?.attachment&&J.push({key:"image",icon:wr,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:we}),(_e||se)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[_e?`${_e} ctx`:"",_e&&se?" · ":"",se?`${se} out`:""]}),J.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:J.map(({key:ne,icon:ke,label:Z})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Z,"aria-label":Z,children:e.jsx(ke,{className:"h-3 w-3"})},ne))})]},me)})})]})]})})},ik={branch:Ht,briefcase:Tl,house:Pl,graduation:Il,code:Ks,heart:lm},lk={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},ck=({onItemSelect:t})=>{const{selectedProfileId:r,defaultGitIdentityId:s,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:c,loadProfiles:l,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=Wn(),{setSidebarOpen:h}=Te(),{isMobile:x}=Qt(),[g,w]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||w(typeof window.opencodeDesktop<"u")},[]);const v=p();i.useEffect(()=>{l(),d(),u(),m()},[l,d,u,m]);const S=j=>{a(`import:${j.host}:${j.username}`),t?.(),x&&h(!1)},N=g?"bg-transparent":y?"bg-background":"bg-sidebar",b=()=>{a("new"),t?.(),x&&h(!1)},k=async j=>{window.confirm(`Are you sure you want to delete profile "${j.name}"?`)&&(await c(j.id)?G.success(`Profile "${j.name}" deleted successfully`):G.error("Failed to delete profile"))},A=async j=>{const M=s===j?null:j;if(!await f(M)){G.error("Failed to update default identity");return}G.success(M?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:F("flex h-full flex-col",N),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(Me,{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(is,{className:"size-4"})})]})}),e.jsxs(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"System Default"}),e.jsx(ku,{profile:o,isSelected:r==="global",isDefault:s==="global",onSelect:()=>{a("global"),t?.(),x&&h(!1)},onToggleDefault:()=>A("global"),onDelete:void 0,isReadOnly:!0})]}),n.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),n.length===0&&!o&&v.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ht,{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(ku,{profile:j,isSelected:r===j.id,isDefault:s===j.id,onSelect:()=>{a(j.id),t?.(),x&&h(!1)},onToggleDefault:()=>A(j.id),onDelete:()=>k(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(uk,{credential:j,onImport:()=>S(j)},`${j.host}-${j.username}`))]})]})]})},ku=({profile:t,isSelected:r,isDefault:s=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:c=!1})=>{const l=ik[t.icon||"branch"]||Ht,d=lk[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(l,{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||!c&&a)&&e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx(Me,{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(Vr,{className:"h-3.5 w-3.5"})})}),e.jsxs(ss,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(Nt,{onClick:m=>{m.stopPropagation(),o()},children:s?"Unset default":"Set as default"}),!c&&a&&e.jsxs(Nt,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},dk=t=>{const r=t.split("/");return r.length>=3?r[r.length-1]:t},uk=({credential:t,onImport:r})=>{const s=dk(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(Me,{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(Wr,{className:"h-3 w-3"}),"Import"]})]})})},Nu=[{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)"}],mk=[{key:"branch",Icon:Ht,label:"Branch"},{key:"briefcase",Icon:Tl,label:"Work"},{key:"house",Icon:Pl,label:"Personal"},{key:"graduation",Icon:Il,label:"School"},{key:"code",Icon:Ks,label:"Code"}],fk=()=>{const{selectedProfileId:t,getProfileById:r,createProfile:s,updateProfile:n,deleteProfile:o}=Wn(),a=i.useMemo(()=>{if(t?.startsWith("import:")){const[,D,T]=t.split(":");return{host:D,username:T}}return null},[t]),c=i.useMemo(()=>t&&t!=="new"&&!a?r(t):null,[t,r,a]),l=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,N]=i.useState(""),[b,k]=i.useState("keyword"),[A,j]=i.useState("branch"),[M,C]=i.useState(!1);i.useEffect(()=>{if(a){const D=a.host.split("/"),T=D.length>=3?D[D.length-1]:a.host;m(T),p(a.username),x(""),w("token"),v(""),N(a.host),k("string"),j("code")}else l?(m(""),p(""),x(""),w("ssh"),v(""),N(""),k("keyword"),j("branch")):c&&(m(c.name),p(c.userName),x(c.userEmail),w(c.authType||"ssh"),v(c.sshKey||""),N(c.host||""),k(c.color||"keyword"),j(c.icon||"branch"))},[c,l,t,a]);const I=async()=>{if(!f.trim()||!h.trim()){G.error("User name and email are required");return}if(g==="token"&&!S.trim()){G.error("Host is required for token-based authentication");return}C(!0);try{const D={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:A};let T;if(l)T=await s(D);else if(t)T=await n(t,D);else return;T?G.success(l?"Profile created successfully":"Profile updated successfully"):G.error(l?"Failed to create profile":"Failed to update profile")}catch(D){console.error("Error saving profile:",D),G.error("An error occurred while saving")}finally{C(!1)}},E=async()=>{if(!(!t||l)&&confirm("Are you sure you want to delete this profile?"))try{await o(t)?G.success("Profile deleted successfully"):G.error("Failed to delete profile")}catch(D){console.error("Error deleting profile:",D),G.error("An error occurred while deleting")}},P=i.useMemo(()=>Nu.find(T=>T.key===b)?.cssVar||"var(--syntax-keyword)",[b]);return t?e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:a?"Import Credential":l?"New Git Profile":d?"Global Identity":u||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:a?`Import token credential for ${a.host} - please fill in your email address`:l?"Create a new Git identity profile for your repositories":d?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!d&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(jt,{value:u,onChange:D=>m(D.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:Nu.map(D=>e.jsx("button",{onClick:()=>k(D.key),className:F("w-8 h-8 rounded-lg border-2 transition-all",b===D.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:D.cssVar},title:D.label},D.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:mk.map(D=>{const T=D.Icon;return e.jsx("button",{onClick:()=>j(D.key),className:F("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",A===D.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:D.label,children:e.jsx(T,{className:"w-4 h-4",style:{color:P}})},D.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(ps,{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(jt,{value:f,onChange:D=>p(D.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(ps,{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(jt,{type:"email",value:h,onChange:D=>x(D.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(ps,{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(Yg,{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(Xg,{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(ps,{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(jt,{value:y,onChange:D=>v(D.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(ps,{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(jt,{value:S,onChange:D=>N(D.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!l&&e.jsxs(Me,{size:"sm",variant:"destructive",onClick:E,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Us,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:F("flex gap-2",l&&"ml-auto"),children:e.jsxs(Me,{size:"sm",variant:"default",onClick:I,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(za,{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(Qs,{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 Li(t,r,s){return Math.min(s,Math.max(r,t))}const rn=Pe.forwardRef(({value:t,onValueChange:r,min:s=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:c,onBlur:l,onKeyDown:d,disabled:u,...m},f)=>{const p=Pe.useRef(null);Pe.useImperativeHandle(f,()=>p.current);const[h,x]=Pe.useState(()=>String(t));Pe.useEffect(()=>{document.activeElement!==p.current&&x(String(t))},[t]);const g=Pe.useCallback(()=>{p.current?.focus()},[]),w=Pe.useCallback(C=>{const I=Li(C,s,n);r(I),x(String(I))},[n,s,r]),y=Pe.useCallback(()=>{const C=Number(h);return Number.isFinite(C)?C:t},[h,t]),v=Pe.useCallback(()=>{w(y()+o),g()},[w,y,g,o]),S=Pe.useCallback(()=>{w(y()-o),g()},[w,y,g,o]),N=C=>{const I=C.target.value;x(I);const E=Number(I);Number.isFinite(E)&&r(Li(E,s,n))},b=C=>{const I=Number(h);if(!Number.isFinite(I))x(String(t));else{const E=Li(I,s,n);E!==I&&r(E),x(String(E))}l?.(C)},k=C=>{if(C.key==="ArrowUp"){C.preventDefault(),v();return}if(C.key==="ArrowDown"){C.preventDefault(),S();return}d?.(C)},A=y(),j=u||A<=s,M=u||A>=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",c),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:N,onBlur:b,onKeyDown:k,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(Oa,{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(Ot,{className:"h-3.5 w-3.5"})})]})]})});rn.displayName="NumberInput";const pk=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Cu=[{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"}],Mu=[{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."}],Du=[{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."}],dc=({visibleSettings:t})=>{const{isMobile:r}=Qt(),s=Co(),n=Te(j=>j.showReasoningTraces),o=Te(j=>j.setShowReasoningTraces),a=Te(j=>j.toolCallExpansion),c=Te(j=>j.setToolCallExpansion),l=Te(j=>j.fontSize),d=Te(j=>j.setFontSize),u=Te(j=>j.padding),m=Te(j=>j.setPadding),f=Te(j=>j.cornerRadius),p=Te(j=>j.setCornerRadius),h=Te(j=>j.inputBarOffset),x=Te(j=>j.setInputBarOffset),g=Te(j=>j.diffLayoutPreference),w=Te(j=>j.setDiffLayoutPreference),y=Te(j=>j.diffViewMode),v=Te(j=>j.setDiffViewMode),S=fr(j=>j.queueModeEnabled),N=fr(j=>j.setQueueMode),{themeMode:b,setThemeMode:k}=Yr(),A=j=>t?t.includes(j):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[A("theme")&&!Wt()&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Theme Mode"})}),e.jsx("div",{className:"flex gap-1 w-fit",children:pk.map(j=>e.jsx(Ms,{variant:b===j.value?"default":"outline",className:F(b===j.value?void 0:"text-foreground"),onClick:()=>k(j.value),children:j.label},j.value))})]}),A("fontSize")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Font Size"})}),e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:l,onChange: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(rn,{value:l,onValueChange:d,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ms,{type:"button",variant:"ghost",onClick:()=>d(100),disabled:l===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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(Ms,{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(Is,{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(rn,{value:u,onValueChange:m,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ms,{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(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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(Ms,{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(Is,{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(rn,{value:f,onValueChange:p,min:0,max:32,step:1,"aria-label":"Corner radius in pixels"}),e.jsx(Ms,{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(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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(Ms,{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(Is,{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(rn,{value:h,onValueChange:x,min:0,max:100,step:5,"aria-label":"Input bar offset in pixels"}),e.jsx(Ms,{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(Is,{className:"h-3.5 w-3.5"})})]})]}),A("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:Cu.find(j=>j.value===a)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Cu.map(j=>e.jsx(Ms,{variant:a===j.value?"default":"outline",className:F(a===j.value?void 0:"text-foreground"),onClick:()=>c(j.value),children:j.label},j.value))})]}),A("diffLayout")&&!r&&!Wt()&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:Mu.map(j=>e.jsx(Ms,{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:Mu.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:Du.map(j=>e.jsx(Ms,{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:Du.find(j=>j.id===y)?.description})]})]}),A("dotfiles")&&!Wt()&&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(Ms,{variant:s===j.value?"default":"outline",className:F(s===j.value?void 0:"text-foreground"),onClick:()=>Nf(j.value),children:j.label},j.id))})})]}),A("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"})]}),A("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=>N(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, ${Xt()}+Enter sends immediately.`:`Enter sends immediately, ${Xt()}+Enter queues messages.`})]})]})},Au="https://github.com/btriapitsyn/openchamber",hk=800,fp=()=>{const[t,r]=i.useState(!1),[s,n]=i.useState(!1),o=Wa(),{isMobile:a}=Qt(),c=o.info?.currentVersion||"unknown",l=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),l.current=!0;else if(s){const u=setTimeout(()=>{n(!1),l.current&&!o.available&&!o.error&&(G.success("You are on the latest version"),l.current=!1)},hk);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:()=>io(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Is,{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",c]}),!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(Wr,{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:Au,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Xi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(vm,{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(Ji,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(dl,{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:c})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Jo,{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(Wr,{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:Au,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(Xi,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:F("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ji,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(dl,{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})]})},gk=1440*60*1e3,pp=5,Eu=1440*60*1e3,Oi=t=>t.time?.updated??t.time?.created??0,Iu=({sessions:t,currentSessionId:r,cutoffDays:s,keepRecent:n=pp,now:o=Date.now()})=>{if(!Array.isArray(t)||s<=0)return[];const a=o-s*gk,c=[...t].sort((d,u)=>Oi(u)-Oi(d)),l=new Set(c.slice(0,n).map(d=>d.id));return c.filter(d=>{if(!d?.id||l.has(d.id)||d.id===r||d.share)return!1;const u=Oi(d);return u?u<a:!1}).map(d=>d.id)},hp=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),c=Te(g=>g.autoDeleteEnabled),l=Te(g=>g.autoDeleteAfterDays),d=Te(g=>g.autoDeleteLastRunAt),u=Te(g=>g.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>l<=0?[]:Iu({sessions:s,currentSessionId:n,cutoffDays:l}),[l,n,s]),x=i.useCallback(async({force:g=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!c||l<=0)&&!g)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const w=Date.now();if(!g&&d&&w-d<Eu)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(s.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const y=Iu({sessions:s,currentSessionId:n,cutoffDays:l,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())}},[l,c,d,n,a,o,s,u]);return i.useEffect(()=>{if(!r||!c||l<=0||o||s.length===0)return;const g=Date.now();d&&g-d<Eu||x()},[l,c,d,r,o,s.length,x]),{candidates:h,isRunning:m,runCleanup:x,keepRecentCount:pp}},_i=1,$i=365,gp=()=>{const{isMobile:t}=Qt(),r=Te(p=>p.autoDeleteEnabled),s=Te(p=>p.autoDeleteAfterDays),n=Te(p=>p.setAutoDeleteEnabled),o=Te(p=>p.setAutoDeleteAfterDays),[a,c]=i.useState(String(s));i.useEffect(()=>{c(String(s))},[s]);const{candidates:l,isRunning:d,runCleanup:u}=hp({autoRun:!1}),m=l.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){G.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&G.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&G.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(ps,{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(c(h),h.trim()==="")return;const x=Number(h);if(!Number.isFinite(x))return;const g=Math.min($i,Math.max(_i,Math.round(x)));o(g)},onBlur:()=>{if(a.trim()===""){c(String(s));return}const p=Number(a);if(!Number.isFinite(p)){c(String(s));return}const h=Math.min($i,Math.max(_i,Math.round(p)));o(h),c(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(rn,{value:s,onValueChange:o,min:_i,max:$i,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(Ms,{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]})]})},xk=10,yk=500,bk=20,wk=500,vk=30,jk=1e3,Sk=()=>{const{isMobile:t}=Qt(),r=Te(h=>h.memoryLimitHistorical),s=Te(h=>h.memoryLimitViewport),n=Te(h=>h.memoryLimitActiveSession),o=Te(h=>h.setMemoryLimitHistorical),a=Te(h=>h.setMemoryLimitViewport),c=Te(h=>h.setMemoryLimitActiveSession),[l,d]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let x=null;if(ls())x=await Ir();else{const g=As()?.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"&&c(x.memoryLimitActiveSession))}catch(x){console.warn("Failed to load memory limits settings:",x)}finally{d(!1)}})()},[o,a,c]);const u=i.useCallback(async(h,x)=>{try{if(await us({[h]:x}),!ls()){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=>{c(h),u("memoryLimitActiveSession",h)},[c,u]);return l?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(ps,{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(Bi,{label:"Initial load limit",description:"Messages loaded when opening a session",value:r,defaultValue:sn.HISTORICAL_MESSAGES,min:xk,max:yk,onChange:m,isMobile:t}),e.jsx(Bi,{label:"Background trim limit",description:"Max messages kept when switching away",value:s,defaultValue:sn.VIEWPORT_MESSAGES,min:bk,max:wk,onChange:f,isMobile:t}),e.jsx(Bi,{label:"Active session limit",description:"Max messages for active session",value:n,defaultValue:rl,min:vk,max:jk,onChange:p,isMobile:t})]})]})},Bi=({label:t,description:r,value:s,defaultValue:n,min:o,max:a,onChange:c,isMobile:l})=>{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)));c(w)},[o,a,c]),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)));c(x),u(String(x))},[d,s,o,a,c]),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,")"]}),l?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(rn,{value:s,onValueChange:c,min:o,max:a,step:10,"aria-label":t})]})]})})},Pu="opencode",Tu="big-pickle",kk=(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===Pu)?.models.some(o=>o.id===Tu))return{providerId:Pu,modelId:Tu};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},xp=()=>{const t=at(I=>I.setProvider),r=at(I=>I.setModel),s=at(I=>I.setAgent),n=at(I=>I.setCurrentVariant),o=at(I=>I.setSettingsDefaultModel),a=at(I=>I.setSettingsDefaultVariant),c=at(I=>I.setSettingsDefaultAgent),l=at(I=>I.settingsAutoCreateWorktree),d=at(I=>I.setSettingsAutoCreateWorktree),u=at(I=>I.providers),[m,f]=i.useState(),[p,h]=i.useState(),[x,g]=i.useState(),[w,y]=i.useState(!0),v=i.useMemo(()=>kk(m,u),[m,u]),S=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{(async()=>{try{let E=null;if(ls())E=await Ir();else{const P=As()?.settings;if(P)try{const T=(await P.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 D=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});D.ok&&(E=await D.json())}}if(E){const P=typeof E.defaultModel=="string"&&E.defaultModel.trim().length>0?E.defaultModel.trim():void 0,D=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;P!==void 0&&f(P),D!==void 0&&h(D),T!==void 0&&g(T)}}catch(E){console.warn("Failed to load defaults settings:",E)}finally{y(!1)}})()},[]);const N=i.useCallback(async(I,E)=>{const P=I&&E?`${I}/${E}`:void 0;f(P),h(void 0),a(void 0),n(void 0),o(P),I&&E&&u.find(T=>T.id===I)&&(t(I),r(E));try{if(await us({defaultModel:P??"",defaultVariant:""}),!ls()){const D=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:P})});D.ok||console.warn("Failed to save default model to server:",D.status,D.statusText)}}catch(D){console.warn("Failed to save default model:",D)}},[u,n,t,r,o,a]),b="__default__",k=i.useCallback(async I=>{const E=I===b?void 0:I||void 0;h(E),a(E),n(E);try{await us({defaultVariant:E??""})}catch(P){console.warn("Failed to save default variant:",P)}},[n,a]),A=i.useCallback(async I=>{const E=I||void 0;g(E),c(E),I&&s(I);try{await us({defaultAgent:E??""})}catch(P){console.warn("Failed to save default agent:",P)}},[s,c]),j=i.useMemo(()=>{if(!v.providerId||!v.modelId)return[];const P=u.find(D=>D.id===v.providerId)?.models.find(D=>D.id===v.modelId)?.variants;return P?Object.keys(P):[]},[v.modelId,v.providerId,u]),M=j.length>0;i.useEffect(()=>{!M&&p&&(h(void 0),a(void 0),n(void 0),us({defaultVariant:""}).catch(()=>{}))},[p,n,a,M]);const C=i.useCallback(async I=>{const E=I.target.checked;d(E);try{await us({autoCreateWorktree:E})}catch(P){console.warn("Failed to save auto create worktree setting:",P)}},[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(ps,{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(cc,{providerId:v.providerId,modelId:v.modelId,onChange:N})]}),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(Ls,{value:p??b,onValueChange:k,children:[e.jsx(Os,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(fn,{placeholder:"Thinking"})}),e.jsxs(_s,{children:[e.jsx(rs,{value:b,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),j.map(I=>e.jsx(rs,{value:I,className:"pr-2 [&>span:first-child]:hidden",children:I},I))]})]})]}),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(up,{agentName:x||"",onChange:A})]})]}),(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:l,onChange:C}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Always create worktree for new sessions"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5 mt-1",children:l?`New session (Worktree): ${Xt()} + N • New session (Standard): Shift + ${Xt()} + N`:`New session (Standard): ${Xt()} + N • New session (Worktree): Shift + ${Xt()} + N`})]})]})},Nk=()=>{const t=at(c=>c.settingsGitmojiEnabled),r=at(c=>c.setSettingsGitmojiEnabled),s=Za(),[n,o]=i.useState(!0);i.useEffect(()=>{(async()=>{try{let l=null;if(ls())l=await Ir();else{const d=As()?.settings;if(d)try{const m=(await d.load())?.settings;m&&(l={gitmojiEnabled:typeof m.gitmojiEnabled=="boolean"?m.gitmojiEnabled:void 0})}catch{}if(!l){const u=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});u.ok&&(l=await u.json())}}l&&typeof l.gitmojiEnabled=="boolean"&&r(l.gitmojiEnabled)}catch(l){console.warn("Failed to load git settings:",l)}finally{o(!1)}})()},[r]);const a=i.useCallback(async c=>{const l=c.target.checked;r(l);try{await us({gitmojiEnabled:l})}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(ps,{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:c=>pv(c.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."})]})})]})},Ck=()=>{const t=Vt(R=>R.getActiveProject()),r=Vt(R=>R.updateWorktreeDefaults),s=t?.path??null,n=t?.worktreeDefaults,o=Ul(s),a=of(s),{sessions:c,getWorktreeMetadata:l}=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),[N,b]=i.useState(null),[k,A]=i.useState([]),[j,M]=i.useState(!1),C=".openchamber",I=i.useCallback((R,ee)=>{const B=R.replace(/\\/g,"/").replace(/\/+$/,""),W=!B||B==="/"?`/${C}`:`${B}/${C}`;return ee?`${W}/${ee}`:W},[]),E=i.useCallback(async()=>{if(!(!s||v===!1))try{const ee=(await _n(s)).map(ie=>$n(s,ie)),W=`${I(s,"")}/`,X=ee.filter(ie=>ie.path.startsWith(W));A(X)}catch{}},[s,v,I]);i.useEffect(()=>{if(!s)return;let R=!1;return y(!0),M(!0),S(null),b(null),A([]),(async()=>{try{const ee=await Qr(s);if(R)return;if(S(ee),ee){const[B,W]=await Promise.all([Ga(s),_n(s).catch(()=>[])]);if(!R){B&&b({all:B.all,current:B.current});const X=W.map(me=>$n(s,me)),be=`${`${s.replace(/\\/g,"/").replace(/\/+$/,"")}/${C}`}/`,H=X.filter(me=>me.path.startsWith(be));A(H)}}}catch{}finally{R||(y(!1),M(!1))}})(),()=>{R=!0}},[s]),i.useEffect(()=>{if(!s)return;let R=!1;return g(!0),(async()=>{try{const ee=await Kn(s);R||h(ee.length>0?ee:[""])}catch{R||h([""])}finally{R||g(!1)}})(),()=>{R=!0}},[s]),i.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const P=N??a,D=v??o,T=i.useMemo(()=>{const R=[],ee=P?.current?`Current (HEAD: ${P.current})`:"Current (HEAD)";return R.push({value:"HEAD",label:ee,group:"special"}),P&&(P.all.filter(X=>!X.startsWith("remotes/")).sort((X,ie)=>X.localeCompare(ie)).forEach(X=>{R.push({value:X,label:X,group:"local"})}),P.all.filter(X=>X.startsWith("remotes/")).map(X=>X.replace(/^remotes\//,"")).sort((X,ie)=>X.localeCompare(ie)).forEach(X=>{R.push({value:X,label:X,group:"remote"})})),R},[P]),L=i.useRef(null),V=i.useCallback(R=>{u(R),L.current=R},[]),q=i.useCallback(R=>{t?.id&&(r(t.id,{branchPrefix:R}),L.current=null)},[t?.id,r]),_=i.useCallback(()=>{q(d)},[d,q]);i.useEffect(()=>()=>{L.current!==null&&t?.id&&r(t.id,{branchPrefix:L.current})},[t?.id,r]);const Y=i.useCallback(R=>{f(R),t?.id&&r(t.id,{baseBranch:R})},[t?.id,r]),K=i.useCallback((R,ee)=>{h(B=>{const W=[...B];return W[R]=ee,W})},[]),U=i.useCallback(()=>{h(R=>[...R,""])},[]),Q=i.useCallback(R=>{h(ee=>ee.filter((B,W)=>W!==R))},[]),z=i.useCallback(async()=>{if(!s)return;const R=p.filter(ee=>ee.trim().length>0);await Gm(s,R)},[s,p]),re=i.useCallback(()=>{z()},[z]),te=i.useCallback(R=>{const ee=R.path.replace(/\\/g,"/").replace(/\/+$/,""),B=c.filter(me=>{if(l(me.id)?.path===R.path)return!0;const he=me.directory;return!!(he&&he.replace(/\\/g,"/").replace(/\/+$/,"")===ee)}),W=new Set(B.map(me=>me.id)),X=me=>{const we=c.filter(_e=>{const se=_e.parentID;return se&&me.has(se)});if(we.length===0)return[];const he=new Set(we.map(_e=>_e.id));return[...we,...X(he)]},ie=X(W),be=new Set,H=[...B,...ie].filter(me=>be.has(me.id)?!1:(be.add(me.id),!0));zn.requestDelete({sessions:H,mode:"worktree",worktree:R})},[c,l]),pe=i.useMemo(()=>c.map(R=>R.id).join(","),[c]);return i.useEffect(()=>{v&&s&&E()},[pe,v,s,E]),s?w?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):D===!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(ps,{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(jt,{value:d,onChange:R=>V(R.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(ps,{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(Ls,{value:m,onValueChange:Y,children:[e.jsx(Os,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(fn,{placeholder:"Select a branch"})}),e.jsxs(_s,{children:[e.jsxs(ln,{children:[e.jsx(Fn,{children:"Default"}),T.filter(R=>R.group==="special").map(R=>e.jsx(rs,{value:R.value,children:R.label},R.value))]}),T.some(R=>R.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(Ia,{}),e.jsxs(ln,{children:[e.jsx(Fn,{children:"Local branches"}),T.filter(R=>R.group==="local").map(R=>e.jsx(rs,{value:R.value,children:R.label},R.value))]})]}),T.some(R=>R.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(Ia,{}),e.jsxs(ln,{children:[e.jsx(Fn,{children:"Remote branches"}),T.filter(R=>R.group==="remote").map(R=>e.jsx(rs,{value:R.value,children:R.label},R.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((R,ee)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:R,onChange:B=>K(ee,B.target.value),onBlur:re,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{Q(ee),setTimeout(z,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(Zt,{className:"h-4 w-4"})})]},ee)),e.jsxs("button",{type:"button",onClick:U,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(is,{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(ps,{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..."}):k.length===0?e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["No worktrees found under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})]}):e.jsx("div",{className:"space-y-1",children:k.map(R=>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:R.label||R.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:R.relativePath||R.path})]}),e.jsx("button",{type:"button",onClick:()=>te(R),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 ${R.branch||R.label}`,children:e.jsx(Us,{className:"h-4 w-4"})})]},R.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},Mk=()=>{const t=Te(k=>k.nativeNotificationsEnabled),r=Te(k=>k.setNativeNotificationsEnabled),s=Te(k=>k.notificationMode),n=Te(k=>k.setNotificationMode),[o,a]=i.useState("default"),[c,l]=i.useState(!1),[d,u]=i.useState(!1),[m,f]=i.useState(!1);i.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission);const k=typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window;l(k),(async()=>{if(!k){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 k=>{if(k&&typeof Notification<"u"&&Notification.permission==="default")try{const A=await Notification.requestPermission();a(A),A==="granted"?r(!0):G.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(A){console.error("Failed to request notification permission:",A),G.error("Failed to request notification permission")}else r(!!(k&&o==="granted"))},h=typeof Notification<"u"&&Notification.permission==="granted",x=k=>{const A="=".repeat((4-k.length%4)%4),j=(k+A).replace(/-/g,"+").replace(/_/g,"/"),M=atob(j),C=new Uint8Array(M.length);for(let I=0;I<M.length;I+=1)C[I]=M.charCodeAt(I);return C},g=async(k,A,j)=>{let M=null;const C=new Promise((I,E)=>{M=setTimeout(()=>{E(new Error(j))},A)});try{return await Promise.race([k,C])}finally{M&&clearTimeout(M)}},w=async k=>{if(k.active)return;const A=k.installing||k.waiting;A&&A.state!=="activated"&&await g(new Promise(j=>{const M=()=>{A.state==="activated"&&(A.removeEventListener("statechange",M),j())};A.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 k=[{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 A=null;for(const j of k)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){A=M}throw A instanceof Error?A:new Error("Service worker registration failed")},v=async()=>{if(!("serviceWorker"in navigator))throw new Error("Service worker not supported");const k=await navigator.serviceWorker.getRegistration();if(k)return k;const A=await y();try{await A.update()}catch{}return await w(A),A},S=k=>{const A=k,j=[`type=${typeof k}`,`toString=${String(k)}`,`name=${String(A?.name??"")}`,`message=${String(A?.message??"")}`];let M="";try{M=JSON.stringify(k)}catch{}return{summary:j.filter(Boolean).join(" | "),json:M,stack:typeof A?.stack=="string"?A.stack:""}},N=async()=>{if(!c){G.error("Push notifications not supported");return}const k=As();if(!k?.push){G.error("Push API not available");return}f(!0);try{if(typeof Notification<"u"&&Notification.permission==="default"){const D=await Notification.requestPermission();if(a(D),D!=="granted"){G.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}}if(typeof Notification<"u"&&Notification.permission!=="granted"){G.error("Notification permission denied",{description:"Enable notifications in your browser settings."});return}const A=await k.push.getVapidPublicKey();if(!A?.publicKey){G.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 I=(M??await g(j.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x(A.publicKey)}),15e3,"Push subscription timed out")).toJSON(),E=I.keys;if(!I.endpoint||!E?.p256dh||!E.auth)throw new Error("Push subscription missing keys");if(!(await g(k.push.subscribe({endpoint:I.endpoint,keys:{p256dh:E.p256dh,auth:E.auth},origin:typeof window<"u"?window.location.origin:void 0}),15e3,"Push subscribe request timed out"))?.ok){G.error("Failed to enable background notifications");return}u(!0),G.success("Background notifications enabled")}catch(A){console.error("[Push] Enable failed:",A);const j=S(A);G.error("Failed to enable background notifications",{description:j.summary})}finally{f(!1)}},b=async()=>{if(!c){u(!1);return}const k=As();if(!k?.push){G.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 k.push.unsubscribe({endpoint:M}),u(!1),G.success("Background notifications disabled")}finally{f(!1)}};return hr()?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(uo,{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(uo,{checked:s==="always",onCheckedChange:k=>n(k?"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."})]}),c?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."}),c&&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(vf,{size:"sm"})}),e.jsx(uo,{checked:d,disabled:m,onCheckedChange:k=>{k?N():b()},className:"data-[state=checked]:bg-status-info"})]})]})]}):null},Dk=({section:t})=>{const{isMobile:r}=Qt(),s=r&&hr();if(!t)return e.jsxs(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-3 p-3 sm:space-y-6 sm:p-6",children:[e.jsx(dc,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(xp,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gp,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(fp,{})})]});const n=()=>{switch(t){case"visual":return e.jsx(Ak,{});case"chat":return e.jsx(Ek,{});case"sessions":return e.jsx(Ik,{});case"git":return e.jsx(Pk,{});case"notifications":return e.jsx(Tk,{});default:return null}};return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},Ak=()=>e.jsx(dc,{visibleSettings:["theme","fontSize","spacing","cornerRadius","inputBarOffset"]}),Ek=()=>e.jsx(dc,{visibleSettings:["toolOutput","diffLayout","dotfiles","reasoning","queueMode"]}),Ik=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(xp,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gp,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Sk,{})})]}),Pk=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Nk,{}),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(Ck,{})]})]}),Tk=()=>e.jsx(Mk,{}),Fk=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"git",label:"Git",items:["Commit Messages","Worktree"],hideInVSCode:!0},{id:"notifications",label:"Notifications",items:["Native"],webOnly:!0}],Rk=({selectedSection:t,onSelectSection:r})=>{const{isMobile:s}=Qt(),n=s&&hr(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>Wt(),[]),l=i.useMemo(()=>hr(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>Fk.filter(m=>!(m.webOnly&&!l||m.hideInVSCode&&c)),[l,c]),u=o?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:F("flex h-full flex-col",u),children:[e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:d.map(m=>{const f=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(fp,{})})]})},Lk=t=>{let r=cp.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},zi=200,Wi=500,Ok=264,_k=940,vl=({onClose:t,forceMobile:r})=>{const s=Qt(),n=r??s.isMobile,[o,a]=i.useState("settings"),[c,l]=i.useState("visual"),[d,u]=i.useState(!1),[m,f]=i.useState(()=>typeof window<"u"?Math.min(Wi,Math.max(zi,Math.floor(window.innerWidth*.2))):Ok),[p,h]=i.useState(!1),[x,g]=i.useState(!1),[w,y]=i.useState(0),v=i.useRef(null),S=i.useRef(0),N=i.useRef(m),[b,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),A=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),j=i.useMemo(()=>Wt(),[]),M=i.useMemo(()=>Lk(j),[j]);i.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const R=v.current;if(!R)return;const ee=new ResizeObserver(B=>{for(const W of B)y(W.contentRect.width)});return ee.observe(R),y(R.clientWidth),()=>ee.disconnect()},[]);const C=Vt(R=>R.projects),I=Vt(R=>R.activeProjectId),E=Vt(R=>R.setActiveProject),P=i.useMemo(()=>[...C].sort((R,ee)=>(R.label||R.path).localeCompare(ee.label||ee.path)),[C]),D=i.useMemo(()=>P.length===0?null:P.find(R=>R.id===I)??P[0],[I,P]),T=i.useCallback(R=>R.replace(/[-_]/g," ").replace(/\b\w/g,ee=>ee.toUpperCase()),[]),L=i.useMemo(()=>{if(!D)return"Project";const R=D.label&&D.label.trim().length>0?D.label:D.path.split("/").filter(Boolean).pop()||D.path;return T(R)},[D,T]),V=P.length>0&&!j,q=w===0||w>=_k;i.useEffect(()=>{if(o==="agents"){setTimeout(()=>{Kr.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{qr.getState().loadCommands()},0);return}o==="skills"&&(nr.getState().loadSkills(),So.getState().loadCatalog())},[I,o]),i.useEffect(()=>{if(typeof window>"u")return;const R=()=>{if(!p){const ee=Math.min(Wi,Math.max(zi,Math.floor(window.innerWidth*.2)));f(ee)}};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[p]),i.useEffect(()=>{if(!x)return;const R=B=>{const W=B.clientX-S.current,X=Math.min(Wi,Math.max(zi,N.current+W));f(X),h(!0)},ee=()=>g(!1);return window.addEventListener("pointermove",R),window.addEventListener("pointerup",ee,{once:!0}),()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",ee)}},[x]);const _=R=>{g(!0),S.current=R.clientX,N.current=m,R.preventDefault()},Y=i.useCallback(async R=>{if(!R.target.closest("button, a, input, select, textarea")&&R.button===0&&b)try{const{getCurrentWindow:ee}=await bs(async()=>{const{getCurrentWindow:W}=await import("./vendor-.bun-BrcdMJ39.js").then(X=>X.dd);return{getCurrentWindow:W}},__vite__mapDeps([0,1]));await ee().startDragging()}catch(ee){console.error("Failed to start window dragging:",ee)}},[b]),K=i.useCallback(async R=>{if(R.button===0&&b)try{const{getCurrentWindow:ee}=await bs(async()=>{const{getCurrentWindow:W}=await import("./vendor-.bun-BrcdMJ39.js").then(X=>X.dd);return{getCurrentWindow:W}},__vite__mapDeps([0,1]));await ee().startDragging()}catch(ee){console.error("Failed to start window dragging:",ee)}},[b]),U=i.useCallback(R=>{a(R),u(!1)},[]),Q=i.useCallback(()=>{n&&u(!0)},[n]),z=()=>{switch(o){case"settings":return e.jsx(Rk,{selectedSection:c,onSelectSection:R=>{l(R),Q()}});case"agents":return e.jsx(TS,{onItemSelect:Q});case"commands":return e.jsx(WS,{onItemSelect:Q});case"skills":return e.jsx(US,{onItemSelect:Q});case"providers":return e.jsx(tk,{onItemSelect:Q});case"git-identities":return e.jsx(ck,{onItemSelect:Q});default:return null}},re=()=>{switch(o){case"agents":return e.jsx(zS,{});case"commands":return e.jsx(HS,{});case"skills":return e.jsx(ZS,{});case"providers":return e.jsx(ak,{});case"git-identities":return e.jsx(fk,{});case"settings":return e.jsx(Dk,{section:c});default:return null}},te=Xt(),pe=i.useMemo(()=>b&&A?"pl-[5.75rem]":"",[b,A]);return e.jsxs("div",{ref:v,className:F("flex h-full flex-col overflow-hidden",b?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:Y,className:F("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&pe,b?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[n&&d&&e.jsx("button",{type:"button",onClick:()=>u(!1),"aria-label":"Back",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(Nl,{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:M.map(({id:R,label:ee,icon:B})=>{const W=o===R,X=B;return n?e.jsxs(lt,{delayDuration:500,children:[e.jsx(ct,{asChild:!0,children:e.jsx("button",{onClick:()=>U(R),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",W?"bg-secondary text-foreground shadow-sm":"text-muted-foreground"),"aria-pressed":W,"aria-label":ee,children:e.jsx(X,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(it,{children:e.jsx("p",{children:ee})})]},R):e.jsxs("button",{onClick:()=>U(R),onMouseDown:W?K:void 0,className:F("relative flex h-8 items-center gap-2 px-3 rounded-md typography-ui-label font-medium transition-colors",W?"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":W,"aria-label":ee,children:[e.jsx(X,{className:"h-4 w-4",weight:"regular"}),q&&e.jsx("span",{children:ee})]},R)})})}),(t||V)&&e.jsxs("div",{className:F("flex items-center gap-2",n?"":"pr-3"),children:[V&&e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:L,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(lr,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:L,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:L}),e.jsx(Ot,{className:"size-4 opacity-50"})]})}),e.jsx(ss,{align:"end",className:"w-auto",children:e.jsx(Ca,{value:D?.id??"",onValueChange:R=>{R&&E(R)},children:P.map(R=>{const ee=R.label?.trim()?R.label.trim():R.path.split("/").filter(Boolean).pop()||R.path,B=T(ee);return e.jsx(Ma,{value:R.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:B})},R.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(Zt,{className:"h-5 w-5"})})}),e.jsx(it,{children:e.jsxs("p",{children:["Close Settings (",te,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:n?d?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(fs,{children:re()})}):e.jsx("div",{className:F("flex-1 overflow-hidden",j?"bg-background":"bg-sidebar"),children:e.jsx(fs,{children:z()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:F("relative overflow-hidden border-r",b?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":j?"bg-background":"bg-sidebar",x?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}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",x?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:_,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(fs,{children:z()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(fs,{children:re()})})]})})]})},$k=()=>{const{isSidebarOpen:t,activeMainTab:r,setIsMobile:s,isSessionSwitcherOpen:n,isSettingsDialogOpen:o,setSettingsDialogOpen:a,isMultiRunLauncherOpen:c,setMultiRunLauncherOpen:l,multiRunLauncherPrefillPrompt:d}=Te(),{isMobile:u}=Qt(),[m,f]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");i.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),dv({enabled:!0});const p=Wa(w=>w.checkForUpdates);i.useEffect(()=>{const w=setTimeout(()=>{p()},3e3);return()=>clearTimeout(w)},[p]),i.useEffect(()=>{Te.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(()=>{Te.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,N=null;const b=Te.getState().setKeyboardOpen,k=()=>{N&&(N.style.setProperty("--oc-keyboard-avoid-offset","0px"),N.removeAttribute("data-keyboard-avoid-active"),N=null)},A=P=>{if(!P)return null;const D=P.closest("[data-keyboard-avoid]");if(D)return D;if(P.classList.contains("overlay-scrollbar-container")){const T=P.parentElement;if(T instanceof HTMLElement)return T}return P},j=()=>{y=0,v=!0,w.style.setProperty("--oc-keyboard-inset","0px"),b(!1)},M=()=>{const P=window.visualViewport,D=P?Math.round(P.height):window.innerHeight,T=P?Math.max(0,Math.round(P.offsetTop)):0;w.style.setProperty("--oc-visual-viewport-offset-top",`${T}px`);const L=document.activeElement,V=L?.tagName,_=V==="INPUT"||V==="TEXTAREA"||V==="SELECT"||!!L?.isContentEditable,Y=Math.round(w.clientHeight||window.innerHeight),K=D+T,U=Math.max(0,Y-K),z=U>=(_?120:180)?U:0;if(v)z===0&&(v=!1),y=0;else if(y===0)z>0&&_&&(y=z);else{const R=!_&&D>S+6;z===0?(y=0,b(!1)):R?j():(z>0&&_||z>y)&&(y=z,b(!0))}w.style.setProperty("--oc-keyboard-inset",`${y}px`),S=D;const te=/iPad|iPhone|iPod/.test(navigator.userAgent)&&y>0?34:0;w.style.setProperty("--oc-keyboard-home-indicator",`${te}px`);const pe=_?A(L):null;if(!u||!pe||!L)k();else{pe!==N&&(k(),N=pe);const R=T+D,B=L.getBoundingClientRect().bottom-R,W=8,X=Math.max(y,z),ie=B>W&&X>0?Math.min(B,X):0,be=N;be&&(be.style.setProperty("--oc-keyboard-avoid-offset",`${ie}px`),be.setAttribute("data-keyboard-avoid-active","true"))}if(u&&_){const R=document.scrollingElement;R&&R.scrollTop!==0&&(R.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 I=P=>{const D=P.target;if(!D)return;const T=D.tagName;(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||D.isContentEditable)&&(v=!1),M()};document.addEventListener("focusin",I,!0);const E=P=>{const D=P.target;if(!D)return;const T=D.tagName;if(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||D.isContentEditable){const V=P.relatedTarget,q=V?.tagName;if(q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||V?.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",I,!0),document.removeEventListener("focusout",E,!0),k()}},[u]);const h=i.useMemo(()=>{switch(r){case"git":return e.jsx(X0,{});case"diff":return e.jsx(Sw,{});case"terminal":return e.jsx(cS,{});case"files":return e.jsx(MS,{});default:return null}},[r]),x=r==="chat",g=o&&!u;return e.jsx(ev,{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(_w,{}),e.jsx(zw,{}),e.jsx(Qw,{}),u?e.jsxs(e.Fragment,{children:[!(o||c)&&e.jsx(dd,{}),e.jsx("div",{className:F("flex flex-1 overflow-hidden",(o||c)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:n?e.jsx("div",{className:"flex-1 overflow-hidden bg-sidebar",children:e.jsx(fs,{children:e.jsx(Ea,{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(fs,{children:e.jsx(fo,{})})}),h&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(fs,{children:h})})]})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(fs,{children:e.jsx(Dd,{initialPrompt:d,onCreated:()=>l(!1),onCancel:()=>l(!1)})})}),o&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(fs,{children:e.jsx(vl,{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||c)&&"invisible"),children:[e.jsx(dd,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsx(Tw,{isOpen:t,isMobile:u,children:e.jsx(Ea,{})}),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(fs,{children:e.jsx(fo,{})})}),h&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(fs,{children:h})})]})]})]}),c&&e.jsx("div",{className:F("absolute inset-0 z-10",m?"bg-transparent":"bg-background"),children:e.jsx(fs,{children:e.jsx(Dd,{initialPrompt:d,onCreated:()=>l(!1),onCancel:()=>l(!1)})})})]}),g&&e.jsx("div",{className:F("absolute inset-0 z-10",m?"bg-transparent":"bg-background"),children:e.jsx(fs,{children:e.jsx(vl,{onClose:()=>a(!1)})})})]})]})})},Bk=550,zk=1400,Wk=280,Hk=()=>{const t=Tr(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),s=i.useMemo(()=>{const P=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof P=="string"&&P.trim().length>0?P.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[c,l]=i.useState(0),d=i.useRef(null),u=fe(P=>P.currentSessionId),m=fe(P=>P.sessions),f=i.useMemo(()=>u?m.find(P=>P.id===u)?.title||"Session":null,[u,m]),p=fe(P=>!!P.newSessionDraft?.open),h=fe(P=>P.openNewSessionDraft),[x,g]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),w=at(P=>P.isInitialized),y=at(P=>P.initializeApp),v=fe(P=>P.loadSessions),S=fe(P=>P.loadMessages),N=fe(P=>P.messages),[b,k]=i.useState(()=>w),[A,j]=i.useState(!1),M=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const P=t.vscode;P&&P.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 P=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(P==="connected"||P==="connecting"||P==="error"||P==="disconnected")&&g(P);const D=T=>{const V=T.detail?.status;(V==="connected"||V==="connecting"||V==="error"||V==="disconnected")&&g(V)};return window.addEventListener("openchamber:connection-status",D),()=>window.removeEventListener("openchamber:connection-status",D)},[]),i.useEffect(()=>{const P=D=>{const L=D.detail?.view;L==="settings"?a("settings"):L==="chat"?a("chat"):L==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",P),()=>window.removeEventListener("openchamber:navigate",P)},[]),i.useEffect(()=>{(async()=>{if(A||b||x!=="connected")return;const D=Date.now();if(!(D-M.current<750)){M.current=D,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 L=at.getState();if(!L.isInitialized||!L.isConnected||L.providers.length===0||L.agents.length===0)return;await v();const V=fe.getState().error;if(T&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:L.providers.length,agents:L.agents.length,sessions:fe.getState().sessions.length,sessionsError:V}),typeof V=="string"&&V.length>0)return;k(!0)}catch{}finally{j(!1)}}})()},[x,w,b,y,A,v]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!b||x!=="connected")){if(!s){n.current=!0,h();return}m.some(P=>P.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(!(N.has(u)&&(N.get(u)?.length||0)>0))try{await S(u)}catch{}})()},[x,u,o,b,S,N,p]),i.useEffect(()=>{const P=d.current;if(!P)return;const D=new ResizeObserver(T=>{for(const L of T)l(L.contentRect.width)});return D.observe(P),l(P.clientWidth),()=>D.disconnect()},[]);const I=c>0&&c<Bk,E=c>=zk;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(Qo,{title:m.find(P=>P.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fs,{children:e.jsx(fo,{})})})]}):o==="settings"?e.jsx(vl,{onClose:()=>a(E?"chat":"sessions"),forceMobile:I}):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:Wk},children:e.jsx(Ea,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(Qo,{title:p&&!u?"New session":m.find(P=>P.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fs,{children:e.jsx(fo,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Qo,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ea,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Qo,{title:p&&!u?"New session":m.find(P=>P.id===u)?.title||"Chat",showBack:!0,onBack:C,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(fs,{children:e.jsx(fo,{})})})]})})},Qo=({title:t,showBack:r,onBack:s,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:c,showContextUsage:l})=>{const{getCurrentModel:d}=at(),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(cm,{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(is,{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(ho,{className:"h-5 w-5"})}),c&&e.jsx(cl,{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(dn,{className:"h-5 w-5"})}),l&&x&&x.totalTokens>0&&e.jsx(al,{totalTokens:x.totalTokens,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit??0,size:"compact"})]})},jl=".openchamber",Yo=t=>{const r=Vt.getState(),s=r.activeProjectId,n=s?r.projects.find(l=>l.id===s)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof t=="string"?Bt(t):"",a=`/${jl}/`,c=o.indexOf(a);return c>0?o.slice(0,c):t?Bt(t):null},Bt=t=>{if(!t)return"";const r=t.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Fu=t=>{const r=Bt(t);return!r||r==="/"?`/${jl}`:`${r}/${jl}`},Uk=(t,r)=>{const s=Bt(t);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const c=Bt(o);if(c)return c}const a=typeof n.name=="string"?n.name.trim():"";return!a||!s?null:`${s}/${a}`}).filter(n=>!!n)},Vk=async t=>{const r=Bt(t);if(!r)return[];try{const n=(await Fe.listLocalDirectory(r)).filter(o=>o.isDirectory);return Uk(r,n)}catch{return[]}},Or=(t,r)=>{const s=Bt(t),n=Bt(r);if(!s||!n)return!1;if(s===n)return!0;const o=n==="/"?"/":`${n}/`;return s.startsWith(o)},yp=async(t,r)=>{const s=Bt(r);if(!s)return s;try{const n=await t.path.get({directory:s});return Bt(n.data?.directory??"")||s}catch{return s}},bp=async(t,r)=>{const s=Bt(r);if(!s)return[];const n=await yp(t,s),o=c=>c.filter(l=>{const d=Bt(l.directory??"");return d?Or(d,s)||n!==s&&Or(d,n):!1}),a=async c=>{const l=await t.session.list({directory:c});return Array.isArray(l.data)?l.data:[]};try{const c=o(await a(s));if(c.length>0)return c}catch{}if(n&&n!==s)try{const c=o(await a(n));if(c.length>0)return c}catch{}try{const c=await t.session.list(void 0),l=Array.isArray(c.data)?c.data:[];return o(l)}catch{return[]}},Gk=async(t,r)=>{const s=new Map;t.sessions.forEach(o=>{o.worktreeMetadata&&s.set(Bt(o.path),o.worktreeMetadata)});const n=Array.from(new Set(t.sessions.map(o=>Bt(o.path)))).filter(Boolean).filter(o=>!s.has(o));if(n.length===0)return s;try{const o=await _n(r),a=new Map(o.map(c=>[Bt(c.worktree),c]));n.forEach(c=>{const l=a.get(c);l&&s.set(c,$n(r,l))})}catch{}return s},Hi=async t=>{const{apiClient:r,group:s,projectDirectory:n,worktreePaths:o}=t,a=await Gk(s,n),c=fe.getState(),l=Array.from(new Set(o.map(p=>Bt(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<l.length;){const p=l[u];u+=1;const h=s.sessions.filter(v=>Bt(v.path)===p).map(v=>v.id),x=c.getSessionsByDirectory(p),g=Array.isArray(x)?x.map(v=>v.id):[];let w=[];if(g.length===0)try{w=(await bp(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,l.length)},f)),m};function qk(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),c=r.length>=4&&!isNaN(a)&&String(a)===o,l=c?r.slice(2,-1):r.slice(2);if(l.length===0)return null;const d=l.join("/");return{groupSlug:s,provider:n,model:d,index:c?a:1}}const Br=ns()(cs((t,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const s=bt.getState().currentDirectory,n=Yo(s);if(!n){t({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Bt(n),a=Fu(o),c=r().groups;t({isLoading:!0,error:null});try{const l=Fe.getApiClient(),d=await yp(l,o),u=Fu(d);let m=new Map,f=[];try{f=await _n(o),m=new Map(f.map(S=>[Bt(S.worktree),S]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const N=await l.session.list({directory:o}),b=Array.isArray(N.data)?N.data:[];if(b.some(k=>{const A=Bt(k.directory??"");return Or(A,a)||Or(A,u)}))return b}catch{}const S=await l.session.list(void 0);return Array.isArray(S.data)?S.data:[]},h=async S=>{const N=new Map,b=5;let k=0;const A=async()=>{for(;k<S.length;){const j=S[k];k+=1;const M=Bt(j);if(M)try{(await bp(l,M)).forEach(I=>N.set(I.id,I))}catch(C){console.debug("Failed to fetch sessions from worktree:",M,C)}}};return await Promise.all(Array.from({length:Math.min(b,S.length)},A)),Array.from(N.values())};let g=(await p()).filter(S=>{const N=Bt(S.directory??"");return N?Or(N,a)||Or(N,u):!1});if(g.length===0){const S=new Set;f.map(b=>Bt(b.worktree)).filter(b=>Or(b,a)||Or(b,u)).forEach(b=>S.add(b));const N=Array.from(new Set([a,u].map(b=>Bt(b)).filter(Boolean)));await Promise.all(N.map(async b=>{(await Vk(b)).forEach(A=>S.add(A))})),S.size>0&&(g=await h(Array.from(S)))}const w=new Map;for(const S of g){const N=S.time?.updated??0;w.set(S.id,typeof N=="number"?N:0)}const y=new Map;for(const S of g){const N=qk(S.title);if(!N)continue;const b=Bt(S.directory),k=m.get(b),A={id:S.id,path:b,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:k?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:k?$n(o,k):void 0},j=y.get(N.groupSlug);j?j.push(A):y.set(N.groupSlug,[A])}const v=Array.from(y.entries()).map(([S,N])=>{const b=N.reduce((k,A)=>{const j=w.get(A.id)??0;return Math.max(k,j)},0);return{name:S,sessions:N.sort((k,A)=>{const j=k.providerId.localeCompare(A.providerId);if(j!==0)return j;const M=k.modelId.localeCompare(A.modelId);return M!==0?M:k.instanceNumber-A.instanceNumber}),lastActive:b||Date.now(),sessionCount:N.length}});v.sort((S,N)=>S.name.localeCompare(N.name)),t({groups:v,isLoading:!1,error:null})}catch(l){console.error("Failed to load agent groups:",l),t({groups:c.length>0?c:[],isLoading:!1,error:l instanceof Error?l.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(c=>c.name===s);if(!n)return!1;const o=bt.getState().currentDirectory,a=Yo(o);if(!a)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const c=Fe.getApiClient(),l=await Hi({apiClient:c,group:n,projectDirectory:Bt(a),worktreePaths:n.sessions.map(f=>f.path)}),d=fe.getState(),u=new Set;l.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(c){return t({error:c instanceof Error?c.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=Bt(n);if(!a)return!1;const c=bt.getState().currentDirectory,l=Yo(c);if(!l)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const d=Fe.getApiClient(),u=await Hi({apiClient:d,group:o,projectDirectory:Bt(l),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=Bt(n);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(m=>Bt(m.path)).filter(Boolean))).filter(m=>m!==a);if(l.length===0)return!0;const d=bt.getState().currentDirectory,u=Yo(d);if(!u)return t({error:"No project directory selected"}),!1;t({isLoading:!0,error:null});try{const m=Fe.getApiClient(),f=await Hi({apiClient:m,group:o,projectDirectory:Bt(u),worktreePaths:l}),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=>Bt(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"})),Kk=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`},Qk=({group:t,isSelected:r,onSelect:s})=>{const[n,o]=i.useState(!1),[a,c]=i.useState(!1),[l,d]=i.useState(!1),u=Br(f=>f.deleteGroup),m=i.useCallback(async()=>{if(l)return;if(d(!0),G.info(`Deleting "${t.name}"...`),await u(t.name))G.success(`Deleted "${t.name}"`);else{const p=Br.getState().error;G.error(p||`Failed to delete "${t.name}"`)}d(!1),c(!1)},[u,t.name,l]);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(Ht,{className:"h-3 w-3"}),t.sessionCount," model",t.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:Kk(t.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(es,{open:n,onOpenChange:o,children:[e.jsx(ts,{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(Vr,{className:"h-3.5 w-3.5"})})}),e.jsx(ss,{align:"end",className:"min-w-[140px]",children:e.jsx(Nt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),c(!0)},children:"Delete"})})]})})]})}),e.jsx(xs,{open:a,onOpenChange:c,children:e.jsxs(ys,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{children:"Delete agent group"}),e.jsxs(Ns,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"outline",onClick:()=>c(!1),disabled:l,children:"Cancel"}),e.jsx(Me,{variant:"destructive",onClick:()=>{m()},disabled:l,children:l?"Deleting…":"Delete"})]})]})})]})},Yk=({className:t,selectedGroupName:r,onGroupSelect:s,onNewAgent:n})=>{const[o,a]=i.useState(""),[c,l]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Br(),f=bt(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=c?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(ir,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{value:o,onChange: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(Me,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(is,{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(Ot,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),u&&e.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."})]}),e.jsxs(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[x.map(w=>e.jsx(Qk,{group:w,isSelected:r===w.name,onSelect:()=>s?.(w.name)},w.name)),!c&&g>0&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",g,")"]}),c&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>l(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&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"})]})]})]})},Xk=10*1024*1024,Jk=5,Zk=({className:t,onCreateGroup:r,isCreating:s=!1})=>{const[n,o]=i.useState(""),[a,c]=i.useState(""),[l,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,N]=i.useState(!1),[b,k]=i.useState(!1),A=i.useRef(null),j=i.useRef(null),M=bt(te=>te.currentDirectory??null),{isGitRepository:C,isLoading:I}=oc(M),E=i.useMemo(()=>{if(typeof window>"u")return null;const te=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof te=="string"&&te.trim().length>0?te.trim():null},[]),P=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),D=Vt(te=>te.activeProjectId),T=Vt(te=>te.projects),L=i.useMemo(()=>{if(P&&E)return E;if(D){const B=T.find(W=>W.id===D);if(B?.path)return B.path}const te=M??E;if(!te)return null;const pe=te.replace(/\\/g,"/").replace(/\/+$/,"")||te,ee=pe.indexOf("/.openchamber/");return ee>0?pe.slice(0,ee):pe.endsWith("/.openchamber")?pe.slice(0,pe.length-13):pe},[D,T,M,E,P]);i.useEffect(()=>{if(!L)return;let te=!1;return k(!0),(async()=>{try{const pe=await Kn(L);te||v(pe)}catch{}finally{te||k(!1)}})(),()=>{te=!0}},[L]);const V=i.useCallback(te=>{l.length>=Jk||d(pe=>[...pe,te])},[l.length]),q=i.useCallback(te=>{d(pe=>pe.filter((R,ee)=>ee!==te))},[]),_=i.useCallback((te,pe)=>{d(R=>R.map((ee,B)=>B===te?pe:ee))},[]),Y=async te=>{const pe=te.target.files;if(!pe)return;let R=0;for(let ee=0;ee<pe.length;ee++){const B=pe[ee];if(B.size>Xk){G.error(`File "${B.name}" is too large (max 10MB)`);continue}try{const W=await new Promise((ie,be)=>{const H=new FileReader;H.onload=()=>ie(H.result),H.onerror=be,H.readAsDataURL(B)}),X={id:Pa(),filename:B.name,mimeType:B.type||"application/octet-stream",size:B.size,dataUrl:W};x(ie=>[...ie,X]),R++}catch(W){console.error("File attach failed",W),G.error(`Failed to attach "${B.name}"`)}}R>0&&G.success(`Attached ${R} file${R>1?"s":""}`),A.current&&(A.current.value="")},K=te=>{x(pe=>pe.filter(R=>R.id!==te))},U=g||s,Q=!!(n.trim()&&a.trim()&&l.length>=1&&C&&!I),z=async te=>{if(te.preventDefault(),!(!Q||U)){w(!0);try{const pe=l.map(({providerID:B,modelID:W,displayName:X,variant:ie})=>({providerID:B,modelID:W,displayName:X,variant:ie})),R=h.length>0?h.map(B=>({mime:B.mimeType,filename:B.filename,url:B.dataUrl})):void 0,ee=y.filter(B=>B.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:pe,agent:u||void 0,worktreeBaseBranch:f,files:R,setupCommands:ee.length>0?ee:void 0}),o(""),c(""),d([]),m(""),x([]),p("HEAD")}catch(pe){console.error("Failed to create agent group:",pe),G.error("Failed to create agent group")}finally{w(!1)}}},re=te=>{rc(te)||te.key==="Enter"&&!te.shiftKey&&(te.preventDefault(),Q&&!U&&z(te))};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:z,className:"w-full max-w-2xl space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:"Group Name"}),e.jsx(jt,{id:"group-name",value:n,onChange:te=>o(te.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(Ht,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Af,{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(ko,{open:S,onOpenChange:N,children:[e.jsxs(Ka,{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(te=>te.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(te=>te.trim()).length," configured)"]})]}),e.jsx(Ot,{className:F("h-4 w-4 text-muted-foreground transition-transform duration-200",S&&"rotate-180")})]}),e.jsx(No,{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((te,pe)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:te,onChange:R=>{const ee=[...y];ee[pe]=R.target.value,v(ee)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const R=y.filter((ee,B)=>B!==pe);v(R)},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(Zt,{className:"h-4 w-4"})})]},pe)),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(is,{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(Ef,{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(Df,{selectedModels:l,onAdd:V,onRemove:q,onUpdate:_,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-input/10 dark:bg-input/30 overflow-hidden",children:[e.jsx(Rs,{ref:j,id:"prompt",value:a,onChange:te=>c(te.target.value),onKeyDown:re,placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),h.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:h.map(te=>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:[te.mimeType.startsWith("image/")?e.jsx(wr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(pr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:te.filename,children:te.filename}),e.jsx("button",{type:"button",onClick:()=>K(te.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Zt,{className:"h-3.5 w-3.5"})})]},te.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:A,type:"file",multiple:!0,className:"hidden",onChange:Y,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>A.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(nm,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length," model",l.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!Q||U,className:F("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",Q?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:U?e.jsx(Jg,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(La,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},eN=({group:t,className:r})=>{const{selectedSessionId:s,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Br(),{setCurrentSession:c,currentSessionId:l}=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),c(S.id)},[n,c]);i.useEffect(()=>{if(t.sessions.length>0){const S=s?t.sessions.find(N=>N.id===s)??t.sessions[0]:t.sessions[0];S&&(S.id!==l&&c(S.id),s||n(S.id))}},[t.name,t.sessions,s,l,n,c]);const x=p?.id===l,g=i.useCallback(()=>{if(!p?.path){G.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{G.success("Worktree path copied")}).catch(()=>{G.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(G.info("Removing worktree..."),await o(t.name,d.path))G.success("Worktree removed");else{const N=Br.getState().error;G.error(N||"Failed to remove worktree");return}else if(G.info("Removing other worktrees..."),await a(t.name,d.path))G.success("Removed other worktrees");else{const N=Br.getState().error;G.error(N||"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(Ht,{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(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsxs(Me,{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(ws,{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(Ot,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(ss,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:t.sessions.map(S=>e.jsxs(Nt,{onClick:()=>h(S),className:"flex items-center gap-2 py-2",children:[e.jsx(ws,{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(Ht,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:S.worktreeMetadata?.label||S.branch})]})]}),p?.id===S.id&&e.jsx(Gt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},S.id))})]})}),e.jsxs(es,{children:[e.jsx(ts,{asChild:!0,children:e.jsx(Me,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Vr,{className:"h-4 w-4"})})}),e.jsxs(ss,{align:"end",className:"min-w-[220px]",children:[e.jsx(Nt,{onSelect:S=>{S.preventDefault(),w()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Nt,{onSelect:S=>{S.preventDefault(),y()},children:"Leave this one, remove others"}),e.jsxs(Nt,{onClick:S=>{S.stopPropagation(),g()},disabled:!p?.path,children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(xs,{open:!!d,onOpenChange:S=>{S||u(null)},children:e.jsxs(ys,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(vs,{children:[e.jsx(js,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Ns,{children:d?.kind==="remove"?e.jsxs(e.Fragment,{children:["Remove ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):e.jsxs(e.Fragment,{children:["Keep ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label})," and remove the other worktrees in ",e.jsx("span",{className:"text-foreground font-medium",children:t.name}),"."]})})]}),e.jsxs(zs,{children:[e.jsx(Me,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Me,{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(Zf,{sessionId:p.id,children:e.jsx(Jf,{})}):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(ws,{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"})})})]})},tN=({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=at(S=>S.isInitialized),a=at(S=>S.initializeApp),c=fe(S=>S.loadSessions),l=bt(S=>S.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Br(),{createMultiRun:h,isLoading:x}=mo();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 N=b=>{const A=b.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&n(A)};return window.addEventListener("openchamber:connection-status",N),()=>window.removeEventListener("openchamber:connection-status",N)},[r]),i.useEffect(()=>{if(!r||s!=="connected")return;const S=Date.now();if(S-d.current<750)return;d.current=S;const N=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof N=="string"&&N.trim().length>0)try{l(N,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const k=at.getState();if(!k.isInitialized||!k.isConnected||k.providers.length===0||k.agents.length===0)return;await c(),ds()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:k.providers.length,agents:k.agents.length,sessions:fe.getState().sessions.length})}catch{}})()},[s,o,a,r,c,l]);const g=i.useCallback(S=>{m(S)},[m]),w=i.useCallback(()=>{m(null)},[m]),y=i.useCallback(async S=>{G.info(`Creating agent group "${S.name}" with ${S.models.length} model(s)...`);const N=await h(S);if(N){G.success(`Agent group "${S.name}" created with ${N.sessionIds.length} session(s)`);const b=N.groupSlug,k=async(A=6)=>{for(let j=0;j<A;j+=1){if(await p(),Br.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 k(),m(b)}else{const b=mo.getState().error;G.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(Yk,{selectedGroupName:u,onGroupSelect:g,onNewAgent:w})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(eN,{group:v}):e.jsx(Zk,{onCreateGroup:y,isCreating:x})})]})},sN=(t=5e3)=>{const[r,s]=Pe.useState(null);return Pe.useEffect(()=>{if(!ls())return;let n=!1,o=null;const a=async()=>{const c=await bx();n||(s(c),o=setTimeout(a,t))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[t]),r},rN=({onClose:t})=>{const{sessions:r,messages:s,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:c}=fe(),l=sN(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(Jl,{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(Zg,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),t&&e.jsx(Me,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:t,children:e.jsx(Zt,{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," / ",Sr.MAX_SESSIONS]})]})]}),l&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:l.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[l.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:l.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[Sr.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:[Sr.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:[Sr.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]})]}),e.jsxs("div",{className:"border-t pt-2",children:[e.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e.jsx(gt,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(f=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${f.isCurrent?"bg-primary/10":"bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"truncate",children:f.title}),f.isStreaming&&e.jsx(ex,{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>Sr.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(Me,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Us,{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(Me,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{c()},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(Me,{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"})]})]})]})]})},nN="openchamber-message-cursors",Un="cursors",oN=1,wp="openchamber.messageCursors",uc=()=>typeof window<"u",mc=()=>uc()&&typeof indexedDB<"u",vp=()=>mc()?new Promise((t,r)=>{const s=indexedDB.open(nN,oN);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(Un)||n.createObjectStore(Un)},s.onerror=()=>{r(s.error??new Error("Failed to open IndexedDB"))},s.onsuccess=()=>{t(s.result)}}):Promise.reject(new Error("IndexedDB not supported")),jp=()=>{if(!uc())return{};try{const t=window.localStorage.getItem(wp);if(!t)return{};const r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},aN=t=>{if(uc())try{window.localStorage.setItem(wp,JSON.stringify(t))}catch{}},iN=async(t,r,s)=>{if(!t||!r)return;if(mc())try{const o=await vp();await new Promise((a,c)=>{const l=o.transaction(Un,"readwrite");l.objectStore(Un).put({messageId:r,completedAt:s},t),l.oncomplete=()=>a(),l.onerror=()=>c(l.error??new Error("Cursor write failed")),l.onabort=()=>c(l.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=jp();n[t]={messageId:r,completedAt:s},aN(n)},lN=async t=>{if(!t)return null;if(mc())try{const s=await vp(),n=await new Promise((o,a)=>{const c=s.transaction(Un,"readonly"),d=c.objectStore(Un).get(t);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),c.onerror=()=>a(c.error??new Error("Cursor read failed")),c.onabort=()=>a(c.error??new Error("Cursor read aborted"))});return s.close(),n}catch{}return jp()[t]??null},cN=50,dN=750,Ru=new WeakMap,Lu=t=>{if(!t||!Array.isArray(t))return 0;const r=Ru.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 Ru.set(t,s),s},uN=10,Ou=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<uN?null:n},_u=(t,r)=>{const s=Ou(t),n=Ou(r);return!s||!n||s.length!==n.length?!0:s>n},Sl=new Map,$u=(t,r)=>{const s=`${t}:${r}`,n=Sl.get(s);if(n&&n.sessionId===t)return n.message;const c=(fe.getState().messages.get(t)||[]).find(l=>l.info.id===r)||null;return Sl.set(s,{sessionId:t,message:c}),c},mN=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(" ")},fN=()=>{const{addStreamingPart:t,completeStreamingMessage:r,updateMessageInfo:s,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:c,currentSessionId:l,applySessionMetadata:d,getWorktreeMetadata:u,loadMessages:m,loadSessions:f,updateSession:p,removeSessionFromStore:h}=fe(),{checkConnection:x}=at(),g=Te(De=>De.nativeNotificationsEnabled),w=Te(De=>De.notificationMode),y=bt(De=>De.currentDirectory),v=i.useMemo(()=>{if(!l)return;try{const Ue=u?.(l);if(Ue?.path)return Ue.path}catch(Ue){console.warn("Failed to inspect worktree metadata for session directory:",Ue)}const oe=fe.getState().sessions.find(Ue=>Ue.id===l);if(oe&&typeof oe.directory=="string"&&oe.directory.trim().length>0)return oe.directory.trim()},[l,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 De=!1;const oe=async()=>{try{const Se=await Fe.listPendingPermissions();if(De||Se.length===0)return;for(const Ne of Se)o(Ne)}catch{}},Ue=async()=>{try{const Ne=Vt.getState().projects.map(Ye=>Ye.path),rt=fe.getState().sessions.map(Ye=>Ye.directory),Ke=[S,...Ne,...rt],Le=await Fe.listPendingQuestions({directories:Ke});if(De||Le.length===0)return;for(const Ye of Le)a(Ye)}catch{}};return oe(),Ue(),()=>{De=!0}},[o,a,S]);const N=i.useCallback(De=>{if(typeof De!="string")return null;const oe=De.trim();if(!oe)return null;const Ue=oe.replace(/\\/g,"/");return Ue.length>1?Ue.replace(/\/+$/,""):Ue},[]),b=i.useCallback(De=>{if(!De)return null;try{const Se=u?.(De),Ne=N(Se?.path??null);if(Ne)return Ne}catch{}const Ue=fe.getState().sessions.find(Se=>Se.id===De);return N(Ue?.directory??null)},[u,N]),k=Te(De=>De.setEventStreamStatus),A=i.useRef(null),j=i.useCallback((De,oe)=>{const Ue=oe??null,Se=A.current;if(!(Se&&Se.status===De&&Se.hint===Ue)){if(A.current={status:De,hint:Ue},ds()){const Ge={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[De]??"[INFO]",rt=Ue?`${Ge} SSE ${De}: ${Ue}`:`${Ge} SSE ${De}`;console.info(rt)}k(De,Ue)}},[k]),M=i.useCallback((De,oe,Ue)=>{if(!De)return Promise.resolve();const Se=Date.now();if(_.current)return _.current;if(Se-Y.current<dN)return Promise.resolve();const Ne=m(De,Ue).catch(Ge=>{console.warn(`[useEventStream] Failed to resync messages (${oe}):`,Ge)}).finally(()=>{_.current=null,Y.current=Date.now()});return _.current=Ne,Ne},[m]),C=i.useCallback(async De=>{ds()&&console.info("[useEventStream] Bootstrapping state:",De);try{await Promise.all([f(),l?M(l,De,1/0):Promise.resolve()])}catch(oe){console.warn("[useEventStream] Bootstrap failed:",De,oe)}},[l,f,M]),I=i.useCallback((De,oe,Ue)=>{ds()&&console.debug(`[MessageTracker] ${De}: ${oe}`,Ue)},[]),E=i.useCallback(De=>{ds()&&console.debug(`[MessageTracker] ${De}: reported`)},[]),P=i.useRef(null),D=i.useRef(null),T=i.useRef(0);i.useRef(new Set);const L=i.useRef(new Map),V=i.useRef(null),q=i.useRef(!1),_=i.useRef(null),Y=i.useRef(0),K=i.useRef(new Set),U=i.useRef(new Set),Q=i.useRef(new Set),z=i.useRef(new Set),re=i.useCallback(()=>{if(typeof document>"u")return"visible";const De=document.visibilityState;return De==="hidden"&&document.hasFocus()?"visible":De},[]),te=i.useRef(re()),pe=i.useRef(typeof navigator>"u"?!0:navigator.onLine),R=i.useRef(!1),ee=i.useRef(null),B=i.useRef(null),W=i.useRef(Date.now()),X=i.useRef(!1),ie=i.useCallback(De=>{const oe=Date.now();oe-W.current>25e3&&(C(De),W.current=oe)},[C]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(X.current=!0)},[]);const be=i.useRef(new Map),H=i.useRef(new Map),me=i.useRef(0),we=i.useRef(null),he=i.useRef(l),_e=i.useRef(null),se=i.useRef(null);i.useEffect(()=>{he.current=l},[l]);const J=i.useCallback((De,oe)=>{if(!De)return;const Ue=Date.now(),Se=L.current,Ne=Se.get(De);if(Ne&&Ue-Ne<3e3)return;Se.set(De,Ue);const Ge=rt=>{if(typeof oe=="string"&&oe.trim().length>0)return oe.trim();try{const Ye=u?.(rt);if(Ye?.path)return Ye.path}catch{}const Le=fe.getState().sessions.find(Ye=>Ye.id===rt);return Le&&typeof Le.directory=="string"&&Le.directory.trim().length>0?Le.directory.trim():null};setTimeout(async()=>{try{const rt=Ge(De),Ke=rt?await Fe.withDirectory(rt,()=>Fe.getSession(De)):await Fe.getSession(De);if(Ke){const Le={};typeof Ke.title=="string"&&Ke.title.length>0&&(Le.title=Ke.title),Ke.summary!==void 0&&(Le.summary=Ke.summary),Object.keys(Le).length>0&&d(De,Le)}}catch(rt){console.warn("Failed to refresh session metadata:",rt)}},100)},[d,u]),ne=i.useCallback((De,oe)=>{if(fe.getState().sessionActivityPhase?.get(De)===oe){H.current=new Map(fe.getState().sessionActivityPhase??new Map);return}const Se=be.current.get(De);Se&&(clearTimeout(Se),be.current.delete(De));const Ne=new Map(fe.getState().sessionActivityPhase??new Map);if(Ne.set(De,oe),H.current=Ne,fe.setState({sessionActivityPhase:Ne}),oe==="cooldown"){const Ge=setTimeout(()=>{if(be.current.delete(De),fe.getState().sessionActivityPhase?.get(De)==="cooldown"){const Ke=new Map(fe.getState().sessionActivityPhase??new Map);Ke.set(De,"idle"),H.current=Ke,fe.setState({sessionActivityPhase:Ke})}},2e3);be.current.set(De,Ge)}},[]),ke=i.useCallback(async()=>{const De=Date.now();if(we.current)return we.current;if(De-me.current<1500)return;me.current=De;const oe=Se=>{const Ne=new Set,Ge=fe.getState().sessions,rt=new Set(Ge.map(Le=>Le.id));for(const[Le,Ye]of Object.entries(Se)){if(!Le||!Ye)continue;Ne.add(Le);const xt=Ye.type==="busy"||Ye.type==="retry"?"busy":"idle";ne(Le,xt)}const Ke=fe.getState().sessionActivityPhase;if(Ke)for(const[Le,Ye]of Ke.entries())rt.has(Le)&&(Ye==="busy"||Ye==="cooldown")&&!Ne.has(Le)&&ne(Le,"idle")},Ue=(async()=>{try{const Se=await Fe.getGlobalSessionStatus();if(Se&&Object.keys(Se).length>0){oe(Se);return}const Ne=new Set,Ge=fe.getState().sessions;for(const xt of Ge){const nt=b(xt.id);nt&&Ne.add(nt)}const rt=N(S??null);rt&&Ne.add(rt);const Ke=Array.from(Ne);if(Ke.length===0){const xt=await Fe.getSessionStatus();xt&&oe(xt);return}const Le=await Promise.allSettled(Ke.map(xt=>Fe.getSessionStatusForDirectory(xt))),Ye={};for(const xt of Le)xt.status!=="fulfilled"||!xt.value||Object.assign(Ye,xt.value);if(Object.keys(Ye).length===0&&Array.from(fe.getState().sessionActivityPhase?.values?.()??[]).some(nt=>nt==="busy"||nt==="cooldown")&&!await Fe.checkHealth().catch(()=>!1))return;oe(Ye)}catch{}})().finally(()=>{we.current=null});return we.current=Ue,Ue},[S,N,b,ne]);i.useEffect(()=>{const De=l??null,oe=_e.current,Ue=b(De),Se=se.current;oe&&De&&oe!==De&&Se&&Ue&&Se!==Ue&&ke(),_e.current=De,se.current=Ue},[l,ke,b]);const Z=i.useCallback(De=>{if(W.current=Date.now(),ds()&&console.debug("[useEventStream] Received event:",De.type,De.properties),!De.properties)return;const oe=De.properties;if(!new Set(["session.abort","session.error"]).has(De.type)){const Se=(typeof oe.session=="object"&&oe.session!==null?oe.session:null)||(typeof oe.sessionInfo=="object"&&oe.sessionInfo!==null?oe.sessionInfo:null);if(Se){const Ne=Se,Ge=typeof Ne.id=="string"&&Ne.id.length>0?Ne.id:typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof oe.sessionID=="string"&&oe.sessionID.length>0?oe.sessionID:typeof oe.id=="string"&&oe.id.length>0?oe.id:void 0;if(Ge){const rt=typeof Ne.title=="string"?Ne.title:typeof oe.title=="string"?oe.title:void 0,Ke=typeof Ne.summary=="object"&&Ne.summary!==null?Ne.summary:typeof oe.summary=="object"&&oe.summary!==null?oe.summary:void 0;if(rt!==void 0||Ke!==void 0){const Le={};rt!==void 0&&(Le.title=rt),Ke!==void 0&&(Le.summary=Ke),d(Ge,Le)}}}}switch(De.type){case"server.connected":x();break;case"global.disposed":case"server.instance.disposed":{C("server_disposed_event");break}case"openchamber:session-activity":{const Se=typeof oe.sessionId=="string"?oe.sessionId:null,Ne=typeof oe.phase=="string"?oe.phase:null;Se&&(Ne==="idle"||Ne==="busy"||Ne==="cooldown")&&(ne(Se,Ne),J(Se,typeof oe.directory=="string"?oe.directory:null));break}case"mcp.tools.changed":{const Se=typeof oe.directory=="string"?oe.directory:S;ro.getState().refresh({directory:Se??null,silent:!0});break}case"session.status":if(X.current)break;{const Se=typeof oe.sessionID=="string"?oe.sessionID:null,Ne=typeof oe.status=="object"&&oe.status!==null?oe.status:null,Ge=typeof Ne?.type=="string"?Ne.type:null;Se&&Ge&&(ne(Se,Ge==="busy"||Ge==="retry"?"busy":"idle"),J(Se,typeof oe.directory=="string"?oe.directory:null))}break;case"message.part.updated":{const Se=typeof oe.part=="object"&&oe.part!==null?oe.part:null;if(!Se)break;const Ne=Se,Ge=typeof oe.info=="object"&&oe.info!==null?oe.info:oe,rt=typeof Ge.sessionID=="string"?Ge.sessionID:null,Ke=typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof rt=="string"&&rt.length>0?rt:typeof oe.sessionID=="string"&&oe.sessionID.length>0?oe.sessionID:null,Le=typeof Ge.id=="string"?Ge.id:null,Ye=typeof Ne.messageID=="string"&&Ne.messageID.length>0?Ne.messageID:typeof Le=="string"&&Le.length>0?Le:typeof oe.messageID=="string"&&oe.messageID.length>0?oe.messageID:null;if(!Ke||!Ye){ds()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:Ne.sessionID??rt??oe.sessionID,messageID:Ne.messageID??Le??oe.messageID});break}const xt=Ke,nt=Ye,It=fe.getState().sessionMemoryState.get(xt)?.trimmedHeadMaxId;if(It&&!_u(nt,It)){ds()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:xt,messageId:nt,trimmedHeadMaxId:It});break}let Pt="assistant";if(Ge&&typeof Ge.role=="string")Pt=Ge.role;else{const We=$u(xt,nt);if(We){const ut=We.info.role;typeof ut=="string"&&(Pt=ut)}}if(I(nt,"part_received",{role:Pt}),Pt==="user"&&Ne.synthetic===!0){I(nt,"skipped_synthetic_user_part");break}const zt={...Se,type:Se.type||"text"};I(nt,"addStreamingPart_called"),t(xt,nt,zt,Pt);break}case"message.updated":{const Se=typeof oe.info=="object"&&oe.info!==null?oe.info:oe,Ne=Se,Ge=typeof Ne.sessionID=="string"&&Ne.sessionID.length>0?Ne.sessionID:typeof oe.sessionID=="string"&&oe.sessionID.length>0?oe.sessionID:null,rt=typeof Ne.id=="string"&&Ne.id.length>0?Ne.id:typeof oe.messageID=="string"&&oe.messageID.length>0?oe.messageID:null;if(!Ge||!rt){ds()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:Ne.sessionID??oe.sessionID,messageID:Ne.id??oe.messageID});break}const Ke=Ge,Le=rt,Ye=fe.getState().sessionMemoryState.get(Ke)?.trimmedHeadMaxId;if(Ye&&!_u(Le,Ye)){ds()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Ke,messageId:Le,trimmedHeadMaxId:Ye});break}if(X.current&&ds())try{const Rt=oe.parts||Ne.parts||[],ye=(Array.isArray(Rt)?Rt.filter(Ae=>Ae?.type==="text"):[]).map(Ae=>{const $=Ae;return typeof $?.text=="string"?$.text:typeof $?.content=="string"?$.content:""}).join(`
137
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Le,role:Ne.role,status:Ne.status,textLen:ye.length,textPreview:ye.slice(0,120),partsCount:Array.isArray(Rt)?Rt.length:0})}catch{}if(I(Le,"message_updated",{role:Ne.role}),Ne.role==="user"){const Rt=oe.parts||Ne.parts,qt=Array.isArray(Rt)?Rt:[],ye={...Se,userMessageMarker:!0,clientRole:"user"};if(s(Ke,Le,ye),qt.length>0)for(let Ae=0;Ae<qt.length;Ae++){const $=qt[Ae];if($.synthetic===!0)continue;const ue={...$,type:$?.type||"text",sessionID:$?.sessionID||Ke,messageID:$?.messageID||Le};t(Ke,Le,ue,"user")}I(Le,"user_message_created_from_event",{partsCount:qt.length});break}const xt=$u(Ke,Le),nt=Lu(xt?.parts||[]),It=xt?.info?.finish==="stop",Pt=oe.parts||Ne.parts,zt=Array.isArray(Pt)?Pt:[],We=zt.length>0,vt=typeof(Ne.time||{})?.completed=="number";if(!We&&!vt)break;const dt=Se.finish,Tt=typeof dt=="string"?dt:null,Ct=Tt==="stop";if(Ne.role==="assistant"&&We){const Rt=Lu(zt);if(nt>0&&Rt+cN<nt&&!Ct){I(Le,"skipped_shrinking_update",{incomingLen:Rt,existingLen:nt});break}if(X.current){const ye=nt>0&&Rt<nt,Ae=zt.some(ue=>{if(!ue||ue.type!=="text")return!1;const ve=ue;return typeof ve.text=="string"&&ve.text.length>0});if(ye&&!(Ct&&Ae)){I(Le,"desktop_shrinking_update_suppressed",{incomingLen:Rt,existingLen:nt});break}}}if(s(Ke,Le,Se),We&&Ne.role!=="user"){const ye=(fe.getState().messages.get(Ke)||[]).find(ue=>ue.info.id===Le),Ae=!ye||ye.parts.length===0;I(Le,Ae?"server_parts_injected":"server_parts_refreshed",{count:zt.length});const $=X.current&&Ne.role==="assistant"?zt.filter(ue=>ue?.type!=="text"):zt;for(let ue=0;ue<$.length;ue++){const ve=$[ue],Be={...ve,type:ve?.type||"text",sessionID:ve?.sessionID||Ke,messageID:ve?.messageID||Le};t(Ke,Le,Be,Ne.role),I(Le,`server_part_${ue}`)}}const os=Se.time,St=os?.completed,Lt=typeof St=="number"&&Number.isFinite(St),Ft=Tt==="stop"||It;if(Se.role==="assistant"&&(Lt||Ft)&&Se.role==="assistant"){const qt=fe.getState().messages.get(Ke)||[];let ye=null,Ae="";for(let tt=0;tt<qt.length;tt++){const Ce=qt[tt];Ce.info.role==="assistant"&&Ce.info.id>Ae&&(Ae=Ce.info.id,ye=Ce.info.id)}if(l===Ke&&Le!==ye)break;if(!Ft&&X.current){I(Le,"desktop_completion_without_stop");break}const ue=Lt?St:Date.now();if(Lt||s(Ke,Le,{...Se,time:{...os??{},completed:ue}}),I(Le,"completed",{timeCompleted:ue}),E(Le),iN(Ke,Le,ue),r(Ke,Le),Tt==="stop"&&hr()&&g&&(w==="always"||te.current==="hidden")){const Ce=Q.current;if(!Ce.has(Le)){Ce.add(Le);const qe=As();if(qe?.notifications){const et=Ne.mode||"agent",ot=Ne.modelID||"assistant",_t=`${et.charAt(0).toUpperCase()+et.slice(1)} agent is ready`,$t=`${mN(ot)} completed the task`;qe.notifications.notifyAgentCompletion({title:_t,body:$t,tag:Le})}}}X.current||Tt==="stop"&&fe.getState().sessionActivityPhase?.get(Ke)==="busy"&&ne(Ke,"cooldown");const ve=Se.sessionID,Be=typeof ve=="string"&&ve.length>0?ve:Ke;J(Be,typeof oe.directory=="string"?oe.directory:null),Se.summary&&typeof Be=="string"&&n(Be,null)}break}case"session.created":case"session.updated":{const Se=typeof oe.info=="object"&&oe.info!==null?oe.info:typeof oe.sessionInfo=="object"&&oe.sessionInfo!==null?oe.sessionInfo:typeof oe.session=="object"&&oe.session!==null?oe.session:oe,Ne=typeof Se.id=="string"&&Se.id.length>0?Se.id:typeof Se.sessionID=="string"&&Se.sessionID.length>0?Se.sessionID:typeof oe.sessionID=="string"&&oe.sessionID.length>0?oe.sessionID:typeof oe.id=="string"&&oe.id.length>0?oe.id:void 0;if(Ne){const Ge=typeof Se.time=="object"&&Se.time!==null?Se.time:typeof oe.time=="object"&&oe.time!==null?oe.time:null,rt=Ge&&typeof Ge.compacting=="number"?Ge.compacting:null;n(Ne,rt);const Ke=typeof Se.directory=="string"?Se.directory:typeof oe.directory=="string"?oe.directory:null,Le={...Se,id:Ne,...Ke?{directory:Ke}:{}};p(Le)}break}case"session.deleted":{const Se=typeof oe.sessionID=="string"?oe.sessionID:typeof oe.id=="string"?oe.id:null;Se&&h(Se);break}case"session.abort":{const Se=typeof oe.sessionID=="string"&&oe.sessionID.length>0?oe.sessionID:null,Ne=typeof oe.messageID=="string"&&oe.messageID.length>0?oe.messageID:null;Se&&Ne&&r(Se,Ne);break}case"permission.asked":{if(!("sessionID"in oe)||typeof oe.sessionID!="string")break;const Se=oe;o(Se);const Ne=`${Se.sessionID}:${Se.id}`;K.current.has(Ne)||setTimeout(()=>{if(he.current===Se.sessionID||!fe.getState().permissions.get(Se.sessionID)?.some(Le=>Le.id===Se.id))return;K.current.add(Ne);const Ke=fe.getState().sessions.find(Le=>Le.id===Se.sessionID)?.title||"Session";if(bs(async()=>{const{toast:Le}=await import("./vendor-.bun-BrcdMJ39.js").then(Ye=>Ye.db);return{toast:Le}},__vite__mapDeps([0,1])).then(({toast:Le})=>{Le.warning("Permission required",{description:Ke,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),fe.getState().setCurrentSession(Se.sessionID)}}})}),hr()&&g&&(w==="always"||te.current==="hidden")){const Ye=As();Ye?.notifications&&Ye.notifications.notifyAgentCompletion({title:"Permission required",body:Ke,tag:`permission-${Ne}`})}},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in oe)||typeof oe.sessionID!="string")break;const Se=oe;a(Se);const Ne=`${Se.sessionID}:${Se.id}`;if(hr()&&g&&(w==="always"||te.current==="hidden")){const rt=z.current;if(!rt.has(Ne)){rt.add(Ne);const Ke=As();Ke?.notifications&&Ke.notifications.notifyAgentCompletion({title:"Input needed",body:"Agent is waiting for your response",tag:Ne})}}U.current.has(Ne)||setTimeout(()=>{if(he.current===Se.sessionID||!fe.getState().questions.get(Se.sessionID)?.some(Le=>Le.id===Se.id))return;U.current.add(Ne);const Ke=fe.getState().sessions.find(Le=>Le.id===Se.sessionID)?.title||"Session";bs(async()=>{const{toast:Le}=await import("./vendor-.bun-BrcdMJ39.js").then(Ye=>Ye.db);return{toast:Le}},__vite__mapDeps([0,1])).then(({toast:Le})=>{Le.info("Input needed",{description:Ke,action:{label:"Open",onClick:()=>{Te.getState().setActiveMainTab("chat"),fe.getState().setCurrentSession(Se.sessionID)}}})})},0);break}case"question.replied":{const Se=typeof oe.sessionID=="string"?oe.sessionID:null,Ne=typeof oe.requestID=="string"?oe.requestID:null;Se&&Ne&&c(Se,Ne);break}case"todo.updated":{const Se=typeof oe.sessionID=="string"?oe.sessionID:null,Ne=Array.isArray(oe.todos)?oe.todos:null;Se&&Ne&&Ev(Se,Ne);break}}},[l,g,w,t,r,s,o,a,c,x,J,n,d,I,E,ne,p,h,C,S]),xe=i.useCallback(()=>{const De=re();return te.current=De,De==="visible"&&pe.current},[re]),de=i.useCallback(()=>{ds()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:X.current,hasUnsubscribe:!!P.current,currentSessionId:he.current,effectiveDirectory:S,onlineStatus:pe.current,visibilityState:te.current,lastEventTimestamp:W.current,reconnectAttempts:T.current})},[S]),je=i.useCallback(async()=>!0,[]),ae=i.useCallback(()=>{if(q.current){ds()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(q.current=!0,D.current&&(clearTimeout(D.current),D.current=null),P.current){const De=P.current;P.current=null;try{De()}catch(oe){console.warn("[useEventStream] Error during unsubscribe:",oe)}}q.current=!1},[]),Xe=i.useCallback(async De=>{if(de(),!xe()){R.current=!0,pe.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")),De?.resetAttempts&&(T.current=0),ae(),W.current=Date.now(),j("connecting",null),ds()&&console.info("[useEventStream] Starting event stream...");const oe=Se=>{console.warn("Event stream error:",Se)},Ue=()=>{const Se=R.current;if(T.current=0,R.current=!1,W.current=Date.now(),j("connected",null),x(),ke(),Se)C("sse_reconnected");else{const Ne=he.current;Ne&&setTimeout(()=>{M(Ne,"sse_reconnected",1/0).then(()=>J(Ne)).catch(Ge=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Ge)})},0)}};if(ds()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:S,isCleaningUp:q.current}),q.current){ds()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Se=Fe.subscribeToGlobalEvents(Ge=>{const rt=Ge.payload,Ke=Ge.payload,Le=typeof Ke.properties=="object"&&Ke.properties!==null?Ke.properties:{},Ye=Ge.directory&&Ge.directory!=="global"?{...Le,directory:Ge.directory}:Le;Z({type:typeof rt.type=="string"?rt.type:"",properties:Ye})},oe,Ue),Ne=()=>{try{Se()}catch(Ge){console.warn("[useEventStream] Error during unsubscribe:",Ge)}};q.current?Ne():P.current=Ne}catch(Se){console.error("[useEventStream] Error during subscription:",Se),oe(Se)}},[xe,ae,j,x,M,J,Z,S,ke,je,de,C]),mt=i.useCallback(De=>{if(!xe()){R.current=!0,ae(),pe.current?j("paused","Paused while hidden"):j("offline","Waiting for network");return}const oe=T.current+1;T.current=oe;const Ue=De??`Retrying (${oe})`;j("reconnecting",Ue);const Se=oe<=3?Math.min(1e3*Math.pow(2,oe-1),8e3):Math.min(2e3*Math.pow(2,oe-3),32e3),Ne=Math.floor(Math.random()*250),Ge=Se+Ne;D.current&&clearTimeout(D.current),D.current=setTimeout(()=>{Xe({resetAttempts:!1})},Ge)},[xe,ae,j,Xe]);i.useEffect(()=>{const De=be.current;typeof window<"u"&&(window.__messageTracker=I);let oe=null;X.current&&typeof window<"u"&&(oe=Ye=>{const xt=typeof Ye.detail?.sessionId=="string"?Ye.detail.sessionId:null,nt=typeof Ye.detail?.phase=="string"?Ye.detail.phase:null;xt&&(nt==="idle"||nt==="busy"||nt==="cooldown")&&(ne(xt,nt),J(xt))},window.addEventListener("openchamber:session-activity",oe));const Ue=()=>{ee.current&&(clearTimeout(ee.current),ee.current=null)},Se=()=>{ee.current||(ee.current=setTimeout(()=>{const Ye=re();te.current=Ye,Ye!=="visible"?(ae(),R.current=!0,j("paused","Paused while hidden")):Ue()},5e3))},Ne=()=>{if(te.current=re(),te.current==="visible"){if(Ue(),ie("visibility_restore"),R.current||!P.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ye=he.current;Ye&&(M(Ye,"visibility_restore",nl()).catch(()=>{}),J(Ye)),ke(),j("connecting","Resuming stream"),Xe({resetAttempts:!0})}}else j("paused","Paused while hidden"),Se()},Ge=()=>{if(te.current=re(),te.current==="visible"&&(Ue(),ie("window_focus"),R.current||!P.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ye=he.current;Ye&&(J(Ye),M(Ye,"window_focus",nl()).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(xt=>console.warn("[useEventStream] Failed to refresh messages:",xt))),ke(),j("connecting","Resuming stream"),Xe({resetAttempts:!0})}},rt=()=>{pe.current=!0,ie("network_restored"),(R.current||!P.current)&&(j("connecting","Network restored"),Xe({resetAttempts:!0}))},Ke=()=>{pe.current=!1,R.current=!0,j("offline","Waiting for network"),ae()};typeof document<"u"&&document.addEventListener("visibilitychange",Ne),typeof window<"u"&&(window.addEventListener("online",rt),window.addEventListener("offline",Ke),window.addEventListener("focus",Ge));const Le=setTimeout(()=>{Xe({resetAttempts:!0})},100);return B.current&&clearInterval(B.current),B.current=setInterval(()=>{if(!xe())return;const Ye=Date.now();Array.from(fe.getState().sessionActivityPhase?.values?.()??[]).some(nt=>nt==="busy"||nt==="cooldown")&&ke(),Ye-W.current>45e3&&Promise.resolve().then(async()=>{try{await Fe.checkHealth()?W.current=Date.now():mt("Refreshing stalled stream")}catch(nt){console.warn("Health check after stale stream failed:",nt),mt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Le),oe&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",oe),typeof document<"u"&&document.removeEventListener("visibilitychange",Ne),typeof window<"u"&&(window.removeEventListener("online",rt),window.removeEventListener("offline",Ke),window.removeEventListener("focus",Ge)),Ue(),B.current&&(clearInterval(B.current),B.current=null),De.forEach(Ye=>clearTimeout(Ye)),De.clear(),Sl.clear(),Q.current.clear(),z.current.clear(),R.current=!1,te.current=re(),pe.current=typeof navigator>"u"?!0:navigator.onLine,ae(),V.current&&(clearTimeout(V.current),V.current=null),j("idle",null)}},[S,I,re,ae,j,Xe,mt,m,J,ne,ke,xe,f,ie,M])},pN=()=>{const{openNewSessionDraft:t,abortCurrentOperation:r,armAbortPrompt:s,clearAbortPrompt:n,currentSessionId:o}=fe(),{toggleCommandPalette:a,toggleHelpDialog:c,toggleSidebar:l,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=Te(),{themeMode:p,setThemeMode:h}=Yr(),{working:x}=Wf(),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=N=>{if(Ts(N)&&N.key==="k"&&(N.preventDefault(),a()),Ts(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const k=As()?.diagnostics;if(!k||(N.preventDefault(),y.current))return;y.current=!0,k.downloadLogs().then(({fileName:A,content:j})=>{const M=A||"openchamber.log",C=new Blob([j],{type:"text/plain;charset=utf-8"}),I=URL.createObjectURL(C),E=document.createElement("a");E.href=I,E.download=M,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(I)}).finally(()=>{y.current=!1});return}if(Ts(N)&&N.key==="."&&(N.preventDefault(),c()),Ts(N)&&N.key.toLowerCase()==="n"){N.preventDefault();const b=Wt(),k=at.getState().settingsAutoCreateWorktree;if(b?!1:k?!N.shiftKey:N.shiftKey){u("chat"),d(!1),Ya();return}u("chat"),d(!1),t()}if(Ts(N)&&N.key==="/"){N.preventDefault();const b=["light","dark","system"],A=(b.indexOf(p)+1)%b.length;h(b[A])}if(Ts(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:b,setTimelineDialogOpen:k}=Te.getState();k(!b);return}if(Ts(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:b}=Te.getState();m(!b);return}if(Ts(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:b,isSessionSwitcherOpen:k}=Te.getState();b?d(!k):l();return}if(Ts(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Ts(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:b,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C,isModelSelectorOpen:I}=Te.getState();if(b||k||A||j||M||!(C==="chat"))return;N.preventDefault(),f(!I);return}if(Ts(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:b,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C}=Te.getState();if(b||k||A||j||M||!(C==="chat"))return;const P=at.getState();if(P.getCurrentModelVariants().length===0)return;N.preventDefault(),P.cycleCurrentVariant();const T=at.getState().currentVariant,L=fe.getState(),V=L.currentSessionId,q=at.getState().currentAgentName,_=at.getState().currentProviderId,Y=at.getState().currentModelId;V&&q&&_&&Y&&L.saveAgentModelVariantForSession(V,q,_,Y,T);return}if(N.key==="Escape"){const{isSettingsDialogOpen:b,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:j,isAboutDialogOpen:M,activeMainTab:C}=Te.getState();if(b){N.preventDefault(),m(!1),v();return}if(k||A||j||M||!(C==="chat")){v();return}const P=o;if(!(x.canAbort&&!!P)){v();return}const T=Date.now(),L=g.current;if(L&&T<L){N.preventDefault(),v(),r();return}N.preventDefault();const V=s(3e3)??T+3e3;g.current=V,w.current&&clearTimeout(w.current);const q=Math.max(V-T,0);w.current=setTimeout(()=>{g.current&&Date.now()>=g.current&&v()},q||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[t,r,a,c,l,d,u,m,f,h,p,x,s,v,o]),i.useEffect(()=>()=>{v()},[v])},Bu="openchamber:menu-action",hN=t=>{const{openNewSessionDraft:r}=fe(),{toggleCommandPalette:s,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:c,setSettingsDialogOpen:l,setAboutDialogOpen:d}=Te(),{addProject:u}=Vt(),{requestAccess:m,startAccessing:f}=Xa(),{setThemeMode:p}=Yr(),h=i.useRef(!1),x=i.useCallback(()=>{ls()?m("").then(async g=>{if(!g.success||!g.path){g.error&&g.error!=="Directory selection cancelled"&&G.error("Failed to select directory",{description:g.error});return}const w=await f(g.path);if(!w.success){G.error("Failed to open directory",{description:w.error||"Desktop could not grant file access."});return}u(g.path,{id:g.projectId})||G.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(g=>{console.error("Desktop: Error selecting directory:",g),G.error("Failed to select directory")}):zn.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const g=w=>{switch(w.detail){case"about":d(!0);break;case"settings":l(!0);break;case"command-palette":s();break;case"new-session":c("chat"),a(!1),r();break;case"new-worktree-session":c("chat"),a(!1),Ya();break;case"change-workspace":x();break;case"open-git-tab":{const{activeMainTab:v}=Te.getState();c(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=Te.getState();c(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=Te.getState();c(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=As()?.diagnostics;if(!S||h.current)break;h.current=!0,S.downloadLogs().then(({fileName:N,content:b})=>{const k=N||"openchamber.log",A=new Blob([b],{type:"text/plain;charset=utf-8"}),j=URL.createObjectURL(A),M=document.createElement("a");M.href=j,M.download=k,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(j),G.success("Logs saved",{description:`Downloaded to ~/Downloads/${k}`})}).catch(()=>{G.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(Bu,g),()=>window.removeEventListener(Bu,g)},[r,s,n,o,a,c,l,d,p,t,x])},gN=t=>t.role==="assistant",zu=t=>{const r=t.info;if(!gN(r))return;const s=r.time?.completed;return typeof s=="number"?s:void 0},pa=t=>{if(!t)return!1;if(t.role==="user")return!0;const r=t;return r.clientRole==="user"?!0:!!r.userMessageMarker},Wu=t=>(Array.isArray(t?.parts)?t.parts:[]).map(n=>lo(n)).join(" ").replace(/\s+/g," ").trim(),xN=(t,r)=>{if(!t||!pa(t.info))return-1;const s=Wu(t),n=typeof t.info?.time?.created=="number"?t.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((c,l)=>{if(!pa(c.info))return;const d=Wu(c),u=!!(s&&d&&d===s),m=typeof c.info?.time?.created=="number"?c.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=l,a=p);return}!s&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=l,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(c=>{if(!pa(c.info))return!1;const l=typeof c.info?.time?.created=="number"?c.info.time.created:void 0;return typeof l!="number"?!1:Math.abs(l-n)<1e3}):-1},yN=()=>{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),c=i.useCallback(async()=>{if(!t||n)return;const l=Date.now();if(!(l-a.current<2e3)){a.current=l;try{const d=r.get(t)||[],u=fe.getState().sessionMemoryState.get(t),m=ja(),f=u?.isStreaming?m.VIEWPORT_MESSAGES:m.HISTORICAL_MESSAGES,p=f+m.FETCH_BUFFER,h=await Fe.getSessionMessages(t,p),x=await lN(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?xN(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 N=[...d,...S],{syncMessages:b}=fe.getState();b(t,N)}else{const S=h[v],N=d[d.length-1],b=zu(S),k=zu(N);if(b&&!k){console.log("[SYNC] Last message completed on server");const A=[...d.slice(0,-1),S],{syncMessages:j}=fe.getState();j(t,A)}}else if(pa(g.info)){const S=h.slice(-f);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:N}=fe.getState();N(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 l=()=>{console.log("[FOCUS] Window focused - checking for updates"),c()};return window.addEventListener("focus",l),()=>window.removeEventListener("focus",l)},[c]),i.useEffect(()=>{if(!t||n)return;const l=()=>{document.visibilityState==="visible"&&c(),o.current=setTimeout(l,3e4)};return o.current=setTimeout(l,3e4),()=>{o.current&&clearTimeout(o.current)}},[t,n,c]),i.useEffect(()=>{const l=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),c())};return document.addEventListener("visibilitychange",l),()=>document.removeEventListener("visibilitychange",l)},[c])},bN=()=>{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 c=a,l=c.type==="busy"||c.type==="retry"?"busy":"idle";n.set(o,l)}),n.size>0&&fe.setState({sessionActivityPhase:n})}catch{}})(),()=>{t=!0}},[])},wN=()=>{const t=fe(r=>r.setCurrentSession);i.useEffect(()=>{if(typeof window>"u")return;let r=null;try{r=new URLSearchParams(window.location.search).get("session")}catch{return}if(!r||r.trim().length===0)return;(async()=>{try{Te.getState().setActiveMainTab("chat"),await t(r)}finally{try{const n=new URL(window.location.href);n.searchParams.delete("session"),window.history.replaceState({},"",n.toString())}catch{}}})()},[t])},vN=1e4,Hu=t=>{if(!hr())return;const r=As();r?.push?.setVisibility&&r.push.setVisibility({visible:t})},jN=()=>{i.useEffect(()=>{if(!hr()||typeof document>"u")return;const t=()=>{Hu(document.visibilityState==="visible")},r=()=>{document.visibilityState==="visible"&&Hu(!0)};t();const s=window.setInterval(r,vN);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 SN(){const{git:t}=Tr(),r=bt(m=>m.currentDirectory),{currentSessionId:s,sessions:n,worktreeMetadata:o}=fe(),{setActiveDirectory:a,startPolling:c,stopPolling:l,fetchAll:d}=as(),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){l();return}return a(u),d(u,t),c(t),()=>{l()}},[u,t,a,c,l,d])}function kN({children:t}){return SN(),e.jsx(e.Fragment,{children:t})}const NN=()=>{const[{isUpdating:t,message:r},s]=i.useState(()=>Bx());return i.useEffect(()=>$x(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(ic,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Sp={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}),c=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),l=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!c&&!l&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:c,hasTools:l,hasStepMarkers:d,onlyStepMarkers:d&&!c&&!l}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!c&&!l&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(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=bt.getState(),r=fe.getState(),s=Vt.getState(),n=t.currentDirectory||null,o=Fe.getDirectory()??null,a=r.sessions||[],c=new Set,l={};a.forEach(j=>{const M=j.directory;typeof M=="string"&&M.trim().length>0?(c.add(M),l[M]=(l[M]??0)+1):l["(none)"]=(l["(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 N=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";w=await x(N),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 Qr(n)}catch(j){b={isGitRepo:null,error:j instanceof Error?j.message:String(j)}}const k=s.projects.map(j=>({id:j.id,path:j.path,label:j.label})),A={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:k},sessions:{total:a.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:c.size,directorySamples:Array.from(c).slice(0,5),directoryCounts:l},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:",A),A},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||[],c=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),l=a.some(d=>d.type==="tool");return a.length===0||!c&&!l});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
138
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
139
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
140
- `),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)
141
- `),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 c=o.messages.get(a)||[],l=r?c:c.filter(p=>p.info.role==="assistant"),d={totalMessages:c.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const h=p.filter(x=>typeof x=="number");return h.length>0?Math.max(...h):null},f=l.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"),N=g.filter(E=>E.type==="reasoning"),b=m(S.map(E=>u(E.state?.time?.end??E.state?.time?.start))),k=m(N.map(E=>u(E.time?.end??E.time?.start))),A=m([b,k].filter(E=>E!==null)),j=S.some(E=>["pending","running","started"].includes(E.state?.status)),M=N.some(E=>typeof E.time?.end!="number");S.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const C=!!(v&&typeof b=="number"&&y<b);C&&(d.completedBeforeTool+=1);const I=!!(v&&typeof k=="number"&&y<k);return I&&(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:k,latestPartTimestamp:A,completed_missing:!v,completed_before_tool:C,completed_before_reasoning:I,running_tools_when_completed:!!(v&&j),reasoning_open_when_completed:!!(v&&M),has_tools:S.length>0,has_reasoning:N.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"),c=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&c),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:",c),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:c,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Sp,ds()&&(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 CN=({open:t,onOpenChange:r})=>{const[s,n]=i.useState(null),[o,a]=i.useState(!1),[c,l]=i.useState(!1),d=i.useCallback(async()=>{if(!o){a(!0),l(!1);try{(await Sp.copyDiagnosticsReport()).ok?(l(!0),G.success("Diagnostics copied")):G.error("Copy failed")}catch(m){G.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 bs(async()=>{const{getVersion:x}=await import("./vendor-.bun-BrcdMJ39.js").then(g=>g.de);return{getVersion:x}},__vite__mapDeps([0,1])),h=await p();n(h)}catch{n("1.5.4")}})():n("1.5.4")},[t]);const u=s;return e.jsx(xs,{open:t,onOpenChange:r,children:e.jsx(ys,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(ic,{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:c?"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(Xi,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(vm,{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(Ji,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:"Made with love to comunity"})]})})})};function Ui({apis:t,children:r}){return e.jsx(Gl.Provider,{value:t,children:r})}const MN="curl -fsSL https://opencode.ai/install | bash",DN=3e3;function AN({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(Ys,{className:"h-4 w-4"})})]})}const EN=3e4;function IN({onCliAvailable:t}){const[r,s]=i.useState(!1),[n,o]=i.useState(!1),[a,c]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),EN);return()=>clearTimeout(m)},[]),i.useEffect(()=>{c(typeof window.opencodeDesktop<"u")},[]);const l=i.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await bs(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-BrcdMJ39.js").then(x=>x.dd);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(MN),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,DN);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:l,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(ha,{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(Gt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(AN,{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(ha,{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 PN=()=>{const{isAboutDialogOpen:t,setAboutDialogOpen:r}=Te();return e.jsx(CN,{open:t,onOpenChange:r})};function TN({apis:t}){const{initializeApp:r,isInitialized:s,isConnected:n}=at(),{error:o,clearError:a,loadSessions:c}=fe(),l=bt(b=>b.currentDirectory),d=bt(b=>b.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=ap(),[h,x]=i.useState(()=>t.runtime.isDesktop),[g,w]=i.useState(()=>t.runtime.isVSCode),[y,v]=i.useState(()=>t.runtime.isDesktop?wx():!0);i.useEffect(()=>{x(t.runtime.isDesktop),w(t.runtime.isVSCode)},[t.runtime.isDesktop,t.runtime.isVSCode]),i.useEffect(()=>(Ac(t),()=>Ac(null)),[t]),i.useEffect(()=>{if(typeof document>"u")return;const b=document.documentElement,k=lu[f]?.stack??lu[tS].stack,A=en[p]?.stack??en[ma].stack;b.style.setProperty("--font-sans",k),b.style.setProperty("--font-heading",k),b.style.setProperty("--font-family-sans",k),b.style.setProperty("--font-mono",A),b.style.setProperty("--font-family-mono",A),b.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[f,p]),i.useEffect(()=>{if(s){const k=setTimeout(()=>{const A=document.getElementById("initial-loading");A&&(A.classList.add("fade-out"),setTimeout(()=>{A.remove()},300))},150);return()=>clearTimeout(k)}},[s]),i.useEffect(()=>{const b=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!s&&(k.classList.add("fade-out"),setTimeout(()=>{k.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(l),await c()))()},[l,d,c,n,g]),fN(),jN(),wN(),pN();const S=i.useCallback(()=>{m(b=>!b)},[]);hN(S),yN(),bN(),hp(),i.useEffect(()=>{const b=k=>{Ts(k)&&k.shiftKey&&k.key==="D"&&(k.preventDefault(),m(A=>!A))};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=i.useCallback(()=>{v(!0),window.location.reload()},[]);return h&&!y?e.jsx(fs,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(IN,{onCliAvailable:N})})}):g?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(fs,{children:e.jsx(Ui,{apis:t,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(tN,{}),e.jsx(ji,{})]})})}):e.jsx(fs,{children:e.jsx(Ui,{apis:t,children:e.jsx(su,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Hk,{}),e.jsx(ji,{})]})})})}):e.jsx(fs,{children:e.jsx(Ui,{apis:t,children:e.jsx(kN,{children:e.jsx(su,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx($k,{}),e.jsx(ji,{}),e.jsx(NN,{}),e.jsx(PN,{}),u&&e.jsx(rN,{onClose:()=>m(!1)})]})})})})})}const kp=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=bt.getState();t&&s.homeDirectory!==t&&s.synchronizeHomeDirectory(t),r&&!Wt()&&s.setDirectory(r,{showOverlay:!1})},Np="/auth/session",FN=async()=>fetch(Np,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Uu=async t=>fetch(Np,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:t})}),fc=({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})]}),RN=({message:t="Preparing workspace…"})=>e.jsx(fc,{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})})}),LN=({onRetry:t})=>e.jsx(fc,{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(Me,{type:"button",onClick:t,className:"w-full max-w-xs",children:"Retry"})]})}),ON=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},_N=()=>{try{const t=new URL(window.location.href);t.searchParams.delete("token"),window.history.replaceState({},"",t.toString())}catch{}},$N=({children:t})=>{const r=i.useMemo(()=>ls(),[]),s=i.useMemo(()=>Wt(),[]),n=r||s,[o,a]=i.useState(()=>n?"authenticated":"pending"),[c,l]=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 FN();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=ON();y&&(x.current=!0,_N(),u(!0),f(""),Uu(y).then(v=>{if(v.ok){l(""),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 Am(),await Em(),await kp()))())},[n,o]);const w=async y=>{if(y.preventDefault(),!(!c||d)){u(!0),f("");try{const v=await Uu(c);if(v.ok){l(""),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(RN,{}):o==="error"?e.jsx(LN,{onRetry:()=>{g()}}):o==="locked"?e.jsx(fc,{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(tx,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(jt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:c,onChange:y=>{l(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(Me,{type:"submit",size:"icon",disabled:!c||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(sx,{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})},Vi=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(l=>l+l).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,c=n&255;return`${o} ${a} ${c}`};class BN{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(`
142
- `)}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=Vi(r.colors.surface.muted),o=Vi(r.colors.surface.subtle),a=Vi(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 c=r.metadata.variant==="dark",l=c?.8:.95,d=c?.7:.9;if(n)s.push(` --sidebar-overlay-strong: rgb(${n} / ${l}) !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,l)} !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 {
143
- ${s}
144
- }
145
-
146
- .dark {
147
- ${s}
148
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
149
- ${s}
150
- }
151
-
152
- :root:not(.dark) {
153
- ${s}
154
- }`,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=Wt()?Ex:Fl;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),c=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${c}, ${s})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),c=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${c}, ${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,c=(n>>8&255)-o,l=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(c<255?c<0?0:c:255)*256+(l<255?l<0?0:l: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,c=(n>>8&255)+o,l=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(c<255?c<0?0:c:255)*256+(l<255?l<0?0:l: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 pc={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"}}},hc={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"}}},vo=[pc,hc];function Fa(t){return vo.find(r=>r.metadata.id===t)}const Cp=pc.metadata.id,Mp=hc.metadata.id,zN=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Dp=t=>t==="dark"?hc:pc,WN=t=>(vo.find(s=>s.metadata.variant===t)??Dp(t)).metadata.id,Xo=(t,r)=>{const s=Fa(t);return s&&s.metadata.variant===r?s:vo.find(o=>o.metadata.variant===r)??Dp(r)},HN=typeof window<"u"?i.useLayoutEffect:i.useEffect,Ra=(t,r)=>{if(!t)return r==="light"?Cp:Mp;const s=Fa(t);return s&&s.metadata.variant===r?s.metadata.id:WN(r)},UN=t=>{let r=Cp,s=Mp,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),c=localStorage.getItem("darkThemeId"),l=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(l!==null){if(l==="true")n="system";else if(d){const f=Fa(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=Ra(a,"light"),s=Ra(c,"dark")}if(t){const o=Fa(t);o&&(o.metadata.variant==="light"?r=o.metadata.id:s=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:s}};function VN({children:t,defaultThemeId:r}){const s=Pe.useMemo(()=>new BN,[]),[n,o]=Pe.useState(()=>UN(r)),[a,c]=Pe.useState(()=>zN()),[l,d]=Pe.useState(()=>typeof window>"u"||!Wt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Pe.useMemo(()=>Wt(),[]),m=Pe.useMemo(()=>u&&l?l:n.themeMode==="light"?Xo(n.lightThemeId,"light"):n.themeMode==="dark"||a?Xo(n.darkThemeId,"dark"):Xo(n.lightThemeId,"light"),[u,n,a,l]),f=Pe.useMemo(()=>u&&l?[l,...vo]:vo,[u,l]);Pe.useEffect(()=>{if(!u)return;const N=A=>{d(A);const j=A.metadata.variant==="dark"?"dark":"light",M=Te.getState();M.theme!==j&&M.setTheme(j)},b=A=>{const j=A.detail;j?.theme&&N(j.theme)},k=window.__OPENCHAMBER_VSCODE_THEME__;return k&&N(k),window.addEventListener("openchamber:vscode-theme",b),()=>window.removeEventListener("openchamber:vscode-theme",b)},[u]);const p=Pe.useCallback(N=>{if(typeof document>"u")return;const b=N.colors.surface.background;ls()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=b;let k=document.querySelector('meta[name="theme-color"]');k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),document.head.appendChild(k)),k.setAttribute("content",b);const A=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let j=document.querySelector(`meta[name="theme-color"][media="${A}"]`);j||(j=document.createElement("meta"),j.setAttribute("name","theme-color"),j.setAttribute("media",A),document.head.appendChild(j)),j.setAttribute("content",b)},[]),h=Pe.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);HN(()=>{if(typeof window>"u")return;s.apply(m),h(u),p(m);const N=document.documentElement;N.classList.remove("light","dark"),N.classList.add(m.metadata.variant)},[h,s,m,u,p]),Pe.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),b=k=>{c(k.matches)};return c(N.matches),N.addEventListener("change",b),()=>N.removeEventListener("change",b)},[n.themeMode]),Pe.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]),Pe.useEffect(()=>{us({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]),Pe.useEffect(()=>{if(typeof window>"u")return;const N=b=>{const k=b.detail;k&&o(A=>{let j=A.themeMode;k.useSystemTheme===!0?j="system":k.useSystemTheme===!1&&(k.themeVariant==="dark"||k.themeVariant==="light")&&(j=k.themeVariant);let M=A.lightThemeId;typeof k.lightThemeId=="string"&&k.lightThemeId.length>0&&(M=Ra(k.lightThemeId,"light"));let C=A.darkThemeId;return typeof k.darkThemeId=="string"&&k.darkThemeId.length>0&&(C=Ra(k.darkThemeId,"dark")),j===A.themeMode&&M===A.lightThemeId&&C===A.darkThemeId?A:{themeMode:j,lightThemeId:M,darkThemeId:C}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const x=Pe.useCallback(N=>{const b=f.find(k=>k.metadata.id===N);b&&o(k=>b.metadata.variant==="dark"?k.darkThemeId===b.metadata.id&&k.themeMode==="dark"?k:{...k,darkThemeId:b.metadata.id,themeMode:"dark"}:k.lightThemeId===b.metadata.id&&k.themeMode==="light"?k:{...k,lightThemeId:b.metadata.id,themeMode:"light"})},[f]),g=Pe.useCallback(N=>{o(b=>b.themeMode===N?b:{...b,themeMode:N})},[]),w=Pe.useCallback(N=>{if(N){o(k=>k.themeMode==="system"?k:{...k,themeMode:"system"});return}const b=m.metadata.variant==="dark"?"dark":"light";o(k=>k.themeMode===b?k:{...k,themeMode:b})},[m.metadata.variant]),y=Pe.useCallback(N=>{const b=f.find(k=>k.metadata.id===N&&k.metadata.variant==="light");b&&o(k=>k.lightThemeId===b.metadata.id?k:{...k,lightThemeId:b.metadata.id})},[f]),v=Pe.useCallback(N=>{const b=f.find(k=>k.metadata.id===N&&k.metadata.variant==="dark");b&&o(k=>k.darkThemeId===b.metadata.id?k:{...k,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(ql.Provider,{value:S,children:t})}const GN=({children:t})=>{const{theme:r,applyTheme:s,fontSize:n,applyTypography:o,padding:a,applyPadding:c}=Te();return i.useLayoutEffect(()=>{s(),o(),c()},[r,s,n,o,a,c]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&s()};return l.addEventListener("change",d),()=>{l.removeEventListener("change",d)}},[r,s]),e.jsx(e.Fragment,{children:t})};let Vu=!1;const qN=()=>{if(Vu||typeof window>"u")return;Vu=!0;let t={showReasoningTraces:Te.getState().showReasoningTraces,autoDeleteEnabled:Te.getState().autoDeleteEnabled,autoDeleteAfterDays:Te.getState().autoDeleteAfterDays},r=null,s=null;const n=()=>{const a=r;r=null,s=null,a&&Object.keys(a).length>0&&us(a)},o=a=>{r={...r??{},...a},!s&&(s=setTimeout(n,150))};Te.subscribe(a=>{const c={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},l={};c.showReasoningTraces!==t.showReasoningTraces&&(l.showReasoningTraces=c.showReasoningTraces),c.autoDeleteEnabled!==t.autoDeleteEnabled&&(l.autoDeleteEnabled=c.autoDeleteEnabled),c.autoDeleteAfterDays!==t.autoDeleteAfterDays&&(l.autoDeleteAfterDays=c.autoDeleteAfterDays),t=c,Object.keys(l).length>0&&o(l)})};let Gu=!1;const qu="openchamber-typography-base",KN=()=>{if(typeof document>"u")return;const r=`:root {
155
- ${Object.entries(Fl).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
156
- `)}
157
- }
158
- `,s=document.getElementById(qu);if(s){s.textContent=r;return}const n=document.createElement("style");n.id=qu,n.textContent=r,document.head.appendChild(n)},QN=()=>{Gu||typeof window>"u"||(Gu=!0,KN())},YN=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Am();await Em();qN();QN();await kp();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 c=o[o.length-1].info.tokens;c&&typeof c=="object"&&console.debug("Token breakdown:",{base:(c.input||0)+(c.output||0)+(c.reasoning||0),cache:c.cache?(c.cache.read||0)+(c.cache.write||0):0}),r.sessionContextUsage.get(s);const l=window.__zustand_config_store__;if(l){const d=l.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Ap=document.getElementById("root");if(!Ap)throw new Error("Root element not found");rx.createRoot(Ap).render(e.jsx(Pe.StrictMode,{children:e.jsx(VN,{children:e.jsx(GN,{children:e.jsx($N,{children:e.jsx(TN,{apis:YN})})})})}));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 ZN=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{xs as D,cn as S,ys as a,cf as b,F as c,mj as d,fj as e,Kd as f,Pr as g,pj as h,gj as i,ZN as m,Gf as p,hj as r,ea as t};