@openchamber/web 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,156 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-w0O-Y8Mh.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-DTPUcxdH.js","assets/index-BaEcQUOW.js","assets/index-lcIVG0lU.css"])))=>i.map(i=>d[i]);
2
+ import{t as ep,c as tp,F as sp,j as e,R as rp,T as np,P as op,C as ap,A as ip,a as lp,b as Kt,d as ss,p as Ps,e as Ts,f as cp,_ as ls,g as i,r as Nu,i as Gt,I as dp,k as up,l as mp,m as fp,n as pp,L as hp,o as gp,q as xp,s as yp,u as Bt,S as bp,v as vp,w as Cu,x as wp,y as jp,z as Sp,B as kp,D as Np,E as Cp,G as Ae,H as tc,J as Z,K as Oi,M as sc,N as Ma,O as Ft,Q as Is,U as ts,V as cl,W as Mu,X as Du,Y as Mp,Z as Rr,$ as Dp,a0 as $s,a1 as Gs,a2 as $r,a3 as _t,a4 as Da,a5 as Ap,a6 as nn,a7 as un,a8 as on,a9 as _i,aa as Os,ab as Au,ac as Ep,ad as Ip,ae as Pp,af as Tp,ag as Fp,ah as Rp,ai as Op,aj as Ho,ak as _p,al as Eu,am as oa,an as Or,ao as cs,ap as mn,aq as Xs,ar as po,as as Zt,at as fr,au as $p,av as Lp,aw as Iu,ax as dl,ay as an,az as Pu,aA as pr,aB as Tu,aC as An,aD as Bp,aE as Aa,aF as Js,aG as Qa,aH as zp,aI as Lr,aJ as br,aK as er,aL as Wp,aM as Bs,aN as Hp,aO as rc,aP as Up,aQ as Vp,aR as Gp,aS as qp,aT as Kp,aU as Qp,aV as Yp,aW as Xp,aX as Jp,aY as Zp,aZ as Fu,a_ as Ya,a$ as eh,b0 as ul,b1 as ml,b2 as th,b3 as sh,b4 as rh,b5 as nh,b6 as oh,b7 as ah,b8 as ih,b9 as lh,ba as ch,bb as dh,bc as uh,bd as mh,be as fh,bf as ph,bg as hh,bh as gh,bi as vr,bj as aa,bk as hr,bl as cr,bm as xh,bn as yh,bo as Ea,bp as bh,bq as fl,br as vh,bs as wh,bt as jh,bu as En,bv as Sh,bw as kh,bx as Nh,by as Ch,bz as Mh,bA as no,bB as Uo,bC as Ia,bD as Dh,bE as Ah,bF as kn,bG as vn,bH as Ru,bI as Eh,bJ as Ih,bK as Ls,bL as Ou,bM as Ph,bN as _u,bO as Th,bP as Fh,bQ as $i,bR as $u,bS as Lu,bT as Rh,bU as dr,bV as oo,bW as Oh,bX as nc,bY as _h,bZ as Li,b_ as ho,b$ as $n,c0 as $h,c1 as Bu,c2 as pl,c3 as hl,c4 as gl,c5 as Lh,c6 as Bh,c7 as zh,c8 as Wh,c9 as oc,ca as zu,cb as Hh,cc as Uh,cd as Vh,ce as Gh,cf as Wu,cg as ao,ch as Hu,ci as Uu,cj as Xa,ck as Pa,cl as Vu,cm as qh,cn as Kh,co as Bi,cp as Gu,cq as zi,cr as Qh,cs as Yh,ct as Xh,cu as Jh,cv as Zh,cw as eg,cx as tg,cy as sg}from"./vendor-.bun-w0O-Y8Mh.js";import{c as rg,l as ng,g as og,r as ag,d as ig,a as lg,b as cg,e as dg,u as ug,f as mg,h as fg,i as pg,j as hg,k as gg,m as xg}from"./index-BaEcQUOW.js";const os=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",zt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,ln=()=>typeof window>"u"?!1:!os()&&!zt(),Br=()=>os()?window.opencodeDesktop??null:null,qu=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const s=window.opencodeDesktop;return s?.getSettings&&s?.updateSettings?{getSettings:s.getSettings.bind(s),updateSettings:s.updateSettings.bind(s)}:null},Ku=async()=>{const s=Br();if(typeof window<"u"){const r=window.__OPENCHAMBER_HOME__;if(r&&r.length>0)return r}if(!s)return null;if(typeof s.homeDirectory=="string"&&s.homeDirectory.length>0)return s.homeDirectory;try{if(!s.getHomeDirectory)return null;const r=await s.getHomeDirectory();if(r?.success&&typeof r.path=="string"&&r.path.length>0)return r.path}catch(r){console.warn("Failed to obtain desktop home directory:",r)}return null},yg=async()=>{const s=Br();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},bg=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,zr=async()=>{const s=qu();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},vg=async s=>{const r=qu();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},wg=async s=>{const r=Br();if(!r||!r.requestDirectoryAccess)return{success:!0,path:s};try{return await r.requestDirectoryAccess(s)}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},jg=async s=>{const r=Br();if(!r||!r.startAccessingDirectory)return{success:!0};try{return await r.startAccessingDirectory(s)}catch(t){return console.warn("Failed to start accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},Sg=async s=>{const r=Br();if(!r||!r.stopAccessingDirectory)return{success:!0};try{return await r.stopAccessingDirectory(s)}catch(t){return console.warn("Failed to stop accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},kg=async()=>{const s=Br();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},Ng=async s=>{const r=Br();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},Cg=async()=>{const s=Br();if(!s||!s.restartToUpdate)return!1;try{return await s.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function R(...s){return ep(tp(s))}const Qu=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Es=s=>Qu()&&os()?s.metaKey:s.ctrlKey,es=()=>Qu()&&os()?"⌘":"Ctrl",Yu=(s,r)=>{const t=s??"",n=Math.max(16,r?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const l=Math.max(0,n-(a.length+2));if(l<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>l)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,l):""}return c?`${c}…/${a}`:`…/${a}`},ia=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Zr(s,r){if(!s)return"";const t=ia(s);if(t==="/")return"/";const n=r?ia(r):void 0;if(n&&n!=="/"){if(t===n)return"~";if(t.startsWith(`${n}/`)){const o=t.slice(n.length+1);return o?`~/${o}`:"~"}}return t}function ac(s,r){if(!s)return"/";const t=ia(s);if(!t||t==="/")return"/";const n=r?ia(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Rs(s,r){return r?s?s.toLowerCase().includes(r.toLowerCase())?!0:new sp([s],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function Mg({delayDuration:s=0,...r}){return e.jsx(lp,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function dt({delayDuration:s=0,...r}){return e.jsx(Mg,{delayDuration:s,children:e.jsx(rp,{"data-slot":"tooltip",...r})})}function ut({...s}){return e.jsx(np,{"data-slot":"tooltip-trigger",...s})}function ct({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(op,{children:e.jsxs(ap,{"data-slot":"tooltip-content",sideOffset:r,className:R("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",s),...n,children:[t,e.jsx(ip,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Ja=null;const ic=()=>{const s=new Map;return{getItem:r=>s.get(r)??null,setItem:(r,t)=>{s.set(r,t)},removeItem:r=>{s.delete(r)},clear:()=>{s.clear()},key:r=>Array.from(s.keys())[r]??null,get length(){return s.size}}},Dg=()=>{if(typeof window>"u"||!window.localStorage)return ic();const s=window.localStorage,r=ic();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const m=s.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(t)try{s.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(t)try{s.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(t)try{s.clear()}catch{n()}r.clear()},key:u=>{if(t)try{return s.key(u)}catch{n()}return r.key(u)},get length(){if(t)try{return s.length+r.length}catch{n()}return r.length}}},ps=()=>(Ja||(Ja=Dg()),Ja),xl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Ag={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function lc(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const wr={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)"}}},Vo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...wr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Vo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...wr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Vo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...wr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Vo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...wr.tool.inline})},_e=Kt()(ss(Ps((s,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,toolCallExpansion:"collapsed",fontSize:100,padding:100,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,diffViewMode:"single",isTimelineDialogOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",setTheme:t=>{s({theme:t}),r().applyTheme()},toggleSidebar:()=>{s(t=>{const n=!t.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:t=>{s(()=>{if(t&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:t,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:t}})},setSidebarWidth:t=>{s({sidebarWidth:t,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:t=>{s({isSessionSwitcherOpen:t})},setActiveMainTab:t=>{s({activeMainTab:t})},setPendingDiffFile:t=>{s({pendingDiffFile:t})},navigateToDiff:t=>{s({pendingDiffFile:t,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:t}=r();return t&&s({pendingDiffFile:null}),t},setIsMobile:t=>{s({isMobile:t})},toggleCommandPalette:()=>{s(t=>({isCommandPaletteOpen:!t.isCommandPaletteOpen}))},setCommandPaletteOpen:t=>{s({isCommandPaletteOpen:t})},toggleHelpDialog:()=>{s(t=>({isHelpDialogOpen:!t.isHelpDialogOpen}))},setHelpDialogOpen:t=>{s({isHelpDialogOpen:t})},setAboutDialogOpen:t=>{s({isAboutDialogOpen:t})},setSessionCreateDialogOpen:t=>{s({isSessionCreateDialogOpen:t})},setSettingsDialogOpen:t=>{s({isSettingsDialogOpen:t})},setModelSelectorOpen:t=>{s({isModelSelectorOpen:t})},setSidebarSection:t=>{s({sidebarSection:t})},setEventStreamStatus:(t,n)=>{s({eventStreamStatus:t,eventStreamHint:n??null})},setShowReasoningTraces:t=>{s({showReasoningTraces:t})},setAutoDeleteEnabled:t=>{s({autoDeleteEnabled:t})},setAutoDeleteAfterDays:t=>{const n=Math.max(1,Math.min(365,t));s({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:t=>{s({autoDeleteLastRunAt:t})},setToolCallExpansion:t=>{s({toolCallExpansion:t})},setFontSize:t=>{const n=Math.max(50,Math.min(200,t));s({fontSize:n}),r().applyTypography()},setPadding:t=>{const n=Math.max(50,Math.min(200,t));s({padding:n}),r().applyPadding()},applyTypography:()=>{const{fontSize:t}=r(),n=document.documentElement,o=t/100,a=Object.entries(xl);if(o===1){for(const[l]of a)n.style.removeProperty(lc(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(lc(l),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=r(),n=document.documentElement,o=t/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const l=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*l).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*l).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*l).toFixed(3)),n.style.setProperty("--line-height-loose",(2*l).toFixed(3))},setDiffLayoutPreference:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setDiffViewMode:t=>{s({diffViewMode:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(l=>l.providerID===t&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===t&&l.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{s(o=>{const a=o.recentModels.filter(l=>!(l.providerID===t&&l.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||s(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)},setMultiRunLauncherOpen:t=>{s(n=>({isMultiRunLauncherOpen:t,multiRunLauncherPrefillPrompt:t?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:t=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:t,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:t=>{s({isTimelineDialogOpen:t})},setNativeNotificationsEnabled:t=>{s({nativeNotificationsEnabled:t})},setNotificationMode:t=>{s({notificationMode:t})}}),{name:"ui-store",storage:Ts(()=>ps()),partialize:s=>({theme:s.theme,isSidebarOpen:s.isSidebarOpen,sidebarWidth:s.sidebarWidth,isSessionSwitcherOpen:s.isSessionSwitcherOpen,activeMainTab:s.activeMainTab,sidebarSection:s.sidebarSection,isSessionCreateDialogOpen:s.isSessionCreateDialogOpen,isSettingsDialogOpen:s.isSettingsDialogOpen,showReasoningTraces:s.showReasoningTraces,autoDeleteEnabled:s.autoDeleteEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,autoDeleteLastRunAt:s.autoDeleteLastRunAt,toolCallExpansion:s.toolCallExpansion,fontSize:s.fontSize,padding:s.padding,favoriteModels:s.favoriteModels,recentModels:s.recentModels,diffLayoutPreference:s.diffLayoutPreference,diffWrapLines:s.diffWrapLines,diffViewMode:s.diffViewMode,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode})}),{name:"ui-store"}));async function Eg(){try{const s=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`Server responded with ${s.status}`);const r=await s.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(s){return console.warn("Failed to check for web updates:",s),null}}function Ig(){return os()?"desktop":ln()?"web":null}const cc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Ta=Kt()((s,r)=>({...cc,checkForUpdates:async()=>{const t=Ig();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await kg():t==="web"&&(n=await Eg()),s({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){s({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:t,runtimeType:n}=r();if(!(n!=="desktop"||!t)){s({downloading:!0,error:null,progress:null});try{await Ng(o=>{s({progress:o})}),s({downloading:!1,downloaded:!0})}catch(o){s({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:t,runtimeType:n}=r();if(!(n!=="desktop"||!t))try{await Cg()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(cc)}})),Pg="/api",Tg=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Fg=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(Tg.test(r)||typeof window>"u")return r;const t=window.location?.href||window.location?.origin;if(!t)return r;try{return new URL(r,t).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},Rg=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!s||!r)return null;const t=typeof s.origin=="string"&&s.origin.length>0?s.origin:null;return t?`${t}/api`:null},vo=s=>s.replace(/\\/g,"/"),Za=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class Og{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=Pg){const n=Rg()||r;this.baseUrl=Fg(n),this.client=cp({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const t=r.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const t=r.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],c=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,t){if(r==null)return t();const n=this.currentDirectory;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&r.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const t=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(r){const t=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,t){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:t});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r,t){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},...typeof t=="number"?{limit:t}:{}})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const t=r.toLowerCase();return t.startsWith("text/")&&t!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async compressImage(r,t,n=.8,o=2048){return typeof document>"u"?r:new Promise(a=>{const l=new Image;l.onload=()=>{let c=l.width,d=l.height;(c>o||d>o)&&(c>d?(d=Math.round(d*(o/c)),c=o):(c=Math.round(c*(o/d)),d=o));const u=document.createElement("canvas");u.width=c,u.height=d;const m=u.getContext("2d");if(!m){a(r);return}m.drawImage(l,0,0,c,d);let f=t;t==="image/png"&&r.length>2.5*1024*1024&&(f="image/jpeg");try{a(u.toDataURL(f,n))}catch{a(r)}},l.onerror=()=>a(r),l.src=r})}async convertHeicToJpeg(r){try{const t=(await ls(async()=>{const{default:f}=await import("./vendor-.bun-w0O-Y8Mh.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),l=new Uint8Array(a.length);for(let f=0;f<a.length;f++)l[f]=a.charCodeAt(f);const c=new Blob([l],{type:r.mime}),d=await t({blob:c,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const 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(t){return console.warn("Failed to convert HEIC to JPEG:",t),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(r.mime.startsWith("image/")&&(r.mime==="image/jpeg"||r.mime==="image/png"||r.mime==="image/webp")&&r.url.length>1.33*1024*1024){const n=await this.compressImage(r.url,r.mime),o=n.startsWith("data:image/jpeg")?"image/jpeg":r.mime;return{...r,mime:o,url:n}}if(!this.shouldNormalizeToTextPlain(r.mime))return r;let t=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),a=r.url.substring(n);t=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:t}}async sendMessage(r){const t=Date.now(),n=r.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const l=await this.normalizeFilePart(a),c={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(c)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text}),a.files&&a.files.length>0)for(const l of a.files){const c=await this.normalizeFilePart(l),d={type:"file",mime:c.mime,filename:c.filename,url:c.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,t,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const t=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Failed to unrevert session");return t.data}async forkSession(r,t){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const l=await a.json().catch(()=>null);return!l||typeof l!="object"?{}:l}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async listToolIds(r){try{const t=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,t,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:t,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(r,t){const n=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];return(await this.client.question.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:n})).data||!1}async rejectQuestion(r){return(await this.client.question.reject({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(r){const t=[],n=async d=>{try{const u=typeof d=="string"?d.trim():"";return(await this.client.question.list(u?{directory:u}:void 0)).data||[]}catch{return[]}};t.push(n(null));const o=new Set;for(const d of r?.directories??[]){const u=this.normalizeCandidatePath(d??null);u&&o.add(u)}for(const d of o)t.push(n(d));const a=await Promise.all(t),l=[],c=new Set;for(const d of a)for(const u of d){if(!u||typeof u!="object")continue;const m=u.id;typeof m!="string"||m.length===0||c.has(m)||(c.add(m),l.push(u))}return l}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(r){const t=await this.getConfig(),n=r(t);return await this.updateConfig(n)}async getProviders(){const r=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!r.data)throw new Error("Failed to get providers");return r.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(r){if(!r)return null;const t=r.split(`
3
+ `),n=[];let o;for(const l of t)if(l.startsWith("data:"))n.push(l.slice(5).replace(/^\s/,""));else if(l.startsWith("id:")){const c=l.slice(3).trim();c&&(o=c)}if(n.length===0)return null;const a=n.join(`
4
+ `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const t=r,n=typeof t.directory=="string"?t.directory:typeof t.properties=="object"&&t.properties!==null?t.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof t.type=="string")return{directory:o&&o.length>0?o:"global",payload:t};const a=t.payload;if(a&&typeof a=="object"){const l=a;if(typeof l.type=="string")return{directory:o&&o.length>0?o:"global",payload:l}}return null}emitGlobalSseEvent(r){for(const t of this.globalSseListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(t){console.warn("[OpencodeClient] Global SSE open handler error:",t)}}notifyGlobalSseError(r){for(const t of this.globalSseErrorListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const r=new AbortController;this.globalSseAbortController=r,this.globalSseTask=this.runGlobalSseLoop(r).catch(t=>{t?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",t)}).finally(()=>{this.globalSseAbortController===r&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null)}async runGlobalSseLoop(r){const t=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!r.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const l=await fetch(t,{method:"GET",headers:a,signal:r.signal});if(!l.ok||!l.body)throw new Error(`Global SSE connect failed with status ${l.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const c=l.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await c.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
5
+ `);const h=u.split(`
6
+
7
+ `);u=h.pop()??"";for(const y of h){const g=this.parseSseBlock(y);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,t,n,o){const a=this.normalizeCandidatePath(o?.directory??null),l=c=>{a&&c.directory!==a||r(c)};return this.globalSseListeners.add(l),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(c){console.warn("[OpencodeClient] Global SSE open handler error:",c)}},0)),t&&this.globalSseErrorListeners.add(t),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(l),n&&this.globalSseOpenListeners.delete(n),t&&this.globalSseErrorListeners.delete(t),this.maybeStopGlobalSse()}}subscribeToEvents(r,t,n,o,a){const l=a?.key??"default",c=a?.scope??"directory",d=this.sseAbortControllers.get(l);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(l,u);let m;if(c==="global"){let p=null;const h=g=>{if(g.directory==="global")return g.payload;const w=g.payload,b=typeof w.properties=="object"&&w.properties!==null?w.properties:{};return b.directory===g.directory?g.payload:{...w,properties:{...b,directory:g.directory}}},y=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)};return u.signal.addEventListener("abort",y,{once:!0}),p=this.subscribeToGlobalEvents(g=>{u.signal.aborted||r(h(g))},t?g=>{u.signal.aborted||t(g)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{y(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const h=p;if(typeof h.type=="string")return h;const y=h.payload;if(y&&typeof y=="object"){const g=y;if(typeof g.type=="string"){if(typeof h.directory=="string"&&h.directory.length>0){const b={...(typeof g.properties=="object"&&g.properties!==null?g.properties:null)??{},directory:h.directory};return{...g,properties:b}}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 y=>{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),t&&!u.signal.aborted&&t(v))},onSseEvent:v=>{if(u.signal.aborted)return;v.id&&typeof v.id=="string"&&(m=v.id);const j=v.data,k=f(j);k&&r(k)}};m&&(w.headers={...w.headers||{},"Last-Event-ID":m});const b=await this.client.event.subscribe(g,w);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const v of b.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(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),t&&t(g);const w=Math.min(3e3*Math.pow(2,y),3e4);await new Promise(b=>setTimeout(b,w)),u.signal.aborted||await h(y+1);return}if(!u.signal.aborted){const g=Math.min(3e3*Math.pow(2,y),3e4);await new Promise(w=>setTimeout(w,g)),await h(y+1)}};try{await h(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)}})(),()=>{this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l),u.abort()}}async readFile(r){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${r}
8
+ // This would be loaded from the server`}}async listFiles(r){try{const t=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model,template:t.template,subtask:t.subtask}))}catch{return[]}}async getCommandDetails(r){try{const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(t.data){const n=t.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;t==="/api"?r="/health":t.endsWith("/api")?r=`${t.slice(0,-4)}/health`:r=`${t}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const t=Za();if(t?.createDirectory)try{return await t.createDirectory(r)}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(l||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r,t){const n=Za();if(n)try{const o=await n.listDirectory(r||"");return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:vo(a.path),isDirectory:!!a.isDirectory,isFile:!a.isDirectory,isSymbolicLink:!1}))}catch(o){throw console.error("Failed to list directory contents:",o),o}try{const o=new URLSearchParams;r&&r.trim().length>0&&o.set("path",r),t?.respectGitignore&&o.set("respectGitignore","true");const a=o.toString(),l=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!l.ok){const d=await l.json().catch(()=>({})),u=typeof d.error=="string"?d.error:"Failed to list directory";throw new Error(u)}const c=await l.json();return!c||!Array.isArray(c.entries)?[]:c.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(r,t){const n=Za(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?vo(o):null;if(n)try{const m=await n.search({directory:o||"",query:r,maxResults:t?.limit});return Array.isArray(m)?m.map(f=>{const p=vo(f.path),h=p.split("/").filter(Boolean).pop()||p,y=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?vo(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:y,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const l=new URLSearchParams;o&&o.length>0&&l.set("directory",o),typeof r=="string"&&l.set("q",r),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&l.set("limit",String(t.limit));const c=`${this.baseUrl}/fs/search${l.toString()?`?${l.toString()}`:""}`,d=await fetch(c,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await Ku();if(r)return r;try{const t=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok){const o=await t.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await t.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(t){return console.warn("Failed to resolve filesystem home directory:",t),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const t=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",t,"with path:",r);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},l=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(l)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const Ee=new Og,_g=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Ee},Symbol.toStringTag,{value:"Module"})),Wi=new Set;function Fa(s){return Wi.add(s),()=>{Wi.delete(s)}}function ur(s,r){const t=Array.isArray(s)?s:[s],n=Array.from(new Set(t));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const a of Wi)try{const l=a(o);l instanceof Promise&&l.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(l){console.error("[ConfigSync] Listener threw:",l)}}function io(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const yl="Updating OpenCode configuration...";let mr=0,_r=yl;const Hi=new Set;function la(){const s={isUpdating:mr>0,message:_r};Hi.forEach(r=>r(s))}function _s(s){mr+=1,mr===1?(_r=s||yl,la()):s&&(_r=s,la())}function ks(){mr!==0&&(mr-=1,mr===0&&(_r=yl,la()))}function jr(s){_r===s&&mr>0||(_r=s,mr>0&&la())}function $g(s){return Hi.add(s),s({isUpdating:mr>0,message:_r}),()=>{Hi.delete(s)}}function Lg(){return{isUpdating:mr>0,message:_r}}const lr=Kt()(ss(Ps((s,r)=>({queuedMessages:{},queueModeEnabled:!1,addToQueue:(t,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};s(l=>{const c=l.queuedMessages[t]??[];return{queuedMessages:{...l.queuedMessages,[t]:[...c,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const l=(o.queuedMessages[t]??[]).filter(c=>c.id!==n);if(l.length===0){const{[t]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:l}}})},popToInput:(t,n)=>{const l=(r().queuedMessages[t]??[]).find(c=>c.id===n);return l?(s(c=>{const u=(c.queuedMessages[t]??[]).filter(m=>m.id!==n);if(u.length===0){const{[t]:m,...f}=c.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...c.queuedMessages,[t]:u}}}),l):null},clearQueue:t=>{s(n=>{const{[t]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{s({queuedMessages:{}})},setQueueMode:t=>{s({queueModeEnabled:t}),ns({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:Ts(()=>ps()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),dc=s=>{if(!s||typeof s!="object")return null;const r={};return typeof s.showReasoningTraces=="boolean"&&(r.showReasoningTraces=s.showReasoningTraces),Object.keys(r).length>0?r:null},Bg=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},zg=s=>{const r=_e.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},Wg=async()=>{if(typeof window>"u")return null;if(os()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return dc(typeof t=="object"&&t!==null?t:null)}catch(t){return console.warn("Failed to load appearance preferences from desktop storage:",t),null}}const s=localStorage.getItem("appearance-preferences");if(!s)return null;try{const r=JSON.parse(s),t=Bg(r);return dc(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Xu=null;const uc=s=>{Xu=s},Zs=()=>Xu,Go=s=>{typeof window>"u"||(s.themeId&&localStorage.setItem("selectedThemeId",s.themeId),s.themeVariant&&localStorage.setItem("selectedThemeVariant",s.themeVariant),s.lightThemeId&&localStorage.setItem("lightThemeId",s.lightThemeId),s.darkThemeId&&localStorage.setItem("darkThemeId",s.darkThemeId),typeof s.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(s.useSystemTheme)),s.lastDirectory&&localStorage.setItem("lastDirectory",s.lastDirectory),s.homeDirectory&&(localStorage.setItem("homeDirectory",s.homeDirectory),window.__OPENCHAMBER_HOME__=s.homeDirectory),Array.isArray(s.projects)&&s.projects.length>0?localStorage.setItem("projects",JSON.stringify(s.projects)):localStorage.removeItem("projects"),s.activeProjectId?localStorage.setItem("activeProjectId",s.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(s.pinnedDirectories)&&s.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(s.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"),s.commitMessageModel?localStorage.setItem("commitMessageModel",s.commitMessageModel):localStorage.removeItem("commitMessageModel"),typeof s.gitmojiEnabled=="boolean"?localStorage.setItem("gitmojiEnabled",String(s.gitmojiEnabled)):localStorage.removeItem("gitmojiEnabled"))},Hg=s=>{if(!Array.isArray(s))return;const r=[],t=new Set;for(const n of s){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",l=typeof o.label=="string"?o.label.trim():"",c=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!l||!c||t.has(a)||(t.add(a),r.push({id:a,label:l,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},Ug=s=>{if(!Array.isArray(s))return;const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=c==="/"?c:c.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||t.has(l)||n.has(d))continue;t.add(l),n.add(d);const u={id:l,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&m.branchPrefix.trim()&&(f.branchPrefix=m.branchPrefix.trim()),typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},Ju=()=>{const s=_e.persist;if(s&&typeof s=="object")return s},Zu=()=>Zs()?.settings??null,qo=s=>{const r=_e.getState(),t=lr.getState();if(typeof s.showReasoningTraces=="boolean"&&s.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(s.showReasoningTraces),typeof s.autoDeleteEnabled=="boolean"&&s.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(s.autoDeleteEnabled),typeof s.autoDeleteAfterDays=="number"&&Number.isFinite(s.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,s.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof s.queueModeEnabled=="boolean"&&s.queueModeEnabled!==t.queueModeEnabled&&t.setQueueMode(s.queueModeEnabled)},mc=s=>{if(!s||typeof s!="object")return null;const r=s,t={};typeof r.themeId=="string"&&r.themeId.length>0&&(t.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(t.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(t.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(t.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(t.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(t.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(t.homeDirectory=r.homeDirectory);const n=Ug(r.projects);n&&(t.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(t.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(t.approvedDirectories=r.approvedDirectories.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.securityScopedBookmarks)&&(t.securityScopedBookmarks=r.securityScopedBookmarks.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(a=>typeof a=="string"&&a.length>0)))),typeof r.showReasoningTraces=="boolean"&&(t.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(t.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(t.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(t.defaultModel=r.defaultModel),typeof r.defaultVariant=="string"&&r.defaultVariant.length>0&&(t.defaultVariant=r.defaultVariant),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(t.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(t.autoCreateWorktree=r.autoCreateWorktree),typeof r.commitMessageModel=="string"&&r.commitMessageModel.length>0&&(t.commitMessageModel=r.commitMessageModel),typeof r.gitmojiEnabled=="boolean"&&(t.gitmojiEnabled=r.gitmojiEnabled),typeof r.queueModeEnabled=="boolean"&&(t.queueModeEnabled=r.queueModeEnabled);const o=Hg(r.skillCatalogs);return o&&(t.skillCatalogs=o),t},Vg=async()=>{const s=Zu();if(s)try{const r=await s.load();return mc(r.settings)}catch(r){console.warn("Failed to load shared settings from runtime settings API:",r)}try{const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const t=await r.json().catch(()=>null);return mc(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},em=async()=>{if(typeof window>"u")return;const s=Ju(),r=t=>{Go(t);const n=()=>qo(t);if(s?.hasHydrated?.())n();else if(n(),s?.onFinishHydration){const o=s.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))};try{const t=os()?await zr():await Vg();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},ns=async s=>{if(typeof window>"u")return;if(os()){try{const t=await vg(s);t&&(Go(t),qo(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=Zu();if(r)try{const t=await r.save(s);t&&(Go(t),qo(t));return}catch(t){console.warn("Failed to update settings via runtime settings API:",t)}try{const t=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)});if(!t.ok){console.warn("Failed to update shared settings via API:",t.status,t.statusText);return}const n=await t.json().catch(()=>null);n&&(Go(n),qo(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},tm=async()=>{if(typeof window>"u")return;const s=Ju();try{const r=await Wg();if(!r)return;const t=()=>zg(r);if(s?.hasHydrated?.()){t();return}if(t(),s?.onFinishHydration){const n=s.onFinishHydration(()=>{n?.(),t()})}}catch(r){console.warn("Failed to load appearance preferences:",r)}},Gg=3e4,qg=40,Kg=60,Qg=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},Ra=Kt()(ss((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=Kg){if(!t||t.trim().length===0)return[];const a=t.trim(),l=typeof n=="string"?n.trim():"",c=Qg(a,l,o),d=Date.now(),u=r().cache[c];if(u&&d-u.timestamp<Gg)return u.files;const m=r().inFlight[c];if(m)return m;const f=Ee.searchFiles(l,{directory:a,limit:o}).then(p=>(s(h=>{const y={...h.cache,[c]:{files:p,timestamp:Date.now()}},g=h.cacheKeys.filter(w=>w!==c);for(g.push(c);g.length>qg;){const w=g.shift();w&&delete y[w]}return{cache:y,cacheKeys:g}}),p)).finally(()=>{s(p=>{const h={...p.inFlight};return delete h[c],{inFlight:h}})});return s(p=>({inFlight:{...p.inFlight,[c]:f}})),f},invalidateDirectory(t){if(!t||t.trim().length===0){s({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;s(a=>{const l={...a.cache},c=a.cacheKeys.filter(m=>m.startsWith(o)?(delete l[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:l,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"})),rs=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var Yg={};let Ks=null;const qs=ps(),fc=qs.getItem("lastDirectory"),Xg=typeof fc=="string"&&fc.length>0,wo=s=>{try{Ra.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},sm=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},Jg=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},Ko=(s,r)=>{const t=Jg(s,r);return sm(t)},ca=()=>{if(typeof window<"u"){const r=qs.getItem("homeDirectory")||Ks||null,t=qs.getItem("lastDirectory");if(t&&!zt())return Ko(t,r);if(Ks)return Ks;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 Ks=n,qs.setItem("homeDirectory",n),n;if(r&&!zt())return Ks=r,r}const s=typeof process<"u"&&Yg?.HOME;return s||process?.cwd?.()||"/"},Zg=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");if(t.length>1){const n=t.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return t==="/"||t.length===0?null:t},ex=s=>(Ks=s,typeof window<"u"&&qs.setItem("homeDirectory",s),ns({homeDirectory:s}),s),rm=async()=>{const s=n=>{const o=Zg(n);return o?ex(o):null};try{const n=await Ee.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Ee.getSystemInfo(),o=s(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await Ku(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=ca(),t=s(r);return t||r},tx=()=>{if(!zt())return null;const s=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof s!="string"||s.trim().length===0)return null;const r=sm(s);return r.length>0?r:null},en=tx()||ca();en&&Ee.setDirectory(en);const sx=!!(en&&en!=="/"),yt=Kt()(ss((s,r)=>({currentDirectory:en,directoryHistory:[en],historyIndex:0,homeDirectory:en,hasPersistedDirectory:Xg,isHomeReady:sx,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=Ks||r().homeDirectory||qs.getItem("homeDirectory"),a=Ko(t,o);rs()&&console.log("[DirectoryStore] setDirectory called with path:",a),Ee.setDirectory(a),wo(),s(l=>{const c=[...l.directoryHistory.slice(0,l.historyIndex+1),a];return qs.setItem("lastDirectory",a),ns({lastDirectory:a}),{currentDirectory:a,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const t=r();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];Ee.setDirectory(o),wo(),qs.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const t=r();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];Ee.setDirectory(o),wo(),qs.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=Ks||r().homeDirectory||ca();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,l=a.lastIndexOf("/");if(l===-1){const c=Ks||ca();n(c)}else n(l===0?"/":a.substring(0,l))},goHome:async()=>{const t=Ks||r().homeDirectory||await rm();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;Ks=o;const a=n.homeDirectory!==o,l=qs.getItem("lastDirectory"),c=typeof l=="string"&&l.length>0,d=!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||s({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?Ko(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>Ko(g,o)),p=f.some((g,w)=>g!==n.directoryHistory[w]),h=!!(m&&m!==n.currentDirectory),y={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d?(y.currentDirectory=o,y.directoryHistory=[o],y.historyIndex=0,y.isSwitchingDirectory=!1):(h||p)&&(y.currentDirectory=m,y.directoryHistory=f,y.historyIndex=Math.min(n.historyIndex,f.length-1),y.isSwitchingDirectory=!1),s(()=>y),(d||h)&&u){const g=d?o:m;Ee.setDirectory(g),wo(),qs.setItem("lastDirectory",g),ns({lastDirectory:g})}ns({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&rm().then(s=>{yt.getState().synchronizeHomeDirectory(s)});const Nn=ps(),nm="projects",Ui="activeProjectId",rx=(s,r)=>{const t=s.trim();return!t.startsWith("~")||!r?t:t==="~"?r:t.startsWith("~/")||t.startsWith("~\\")?`${r}${t.slice(1)}`:t},Oa=s=>{const r=s.trim();if(!r)return"";const t=Nn.getItem("homeDirectory")||yt.getState().homeDirectory||"",o=rx(r,t).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},om=s=>{const r=Oa(s);if(!r||r==="/")return"Root";const t=r.split("/").filter(Boolean);return t[t.length-1]||r},nx=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,am=s=>{if(!Array.isArray(s))return[];const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=Oa(c);if(!d||t.has(l)||n.has(d))continue;t.add(l),n.add(d);const u={id:l,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&(f.branchPrefix=m.branchPrefix),typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},ox=()=>{try{const s=Nn.getItem(nm);return s?am(JSON.parse(s)):[]}catch{return[]}},ax=()=>{try{const s=Nn.getItem(Ui);if(typeof s=="string"&&s.trim().length>0)return s.trim()}catch{return null}return null},bl=(s,r)=>{try{Nn.setItem(nm,JSON.stringify(s))}catch{}try{r?Nn.setItem(Ui,r):Nn.removeItem(Ui)}catch{}},pn=(s,r)=>{bl(s,r),ns({projects:s,activeProjectId:r??void 0})},ix=ox(),lx=()=>{if(typeof window>"u"||!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode)return null;const r=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof r!="string"||r.trim().length===0)return null;const t=Oa(r);if(!t)return null;const n=`vscode:${t}`,o={id:n,path:t,label:om(t),addedAt:Date.now(),lastOpenedAt:Date.now()};return rs()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},Vs=lx(),vl=Vs?.projects??ix,im=Vs?.activeProjectId??ax()??vl[0]?.id??null;Vs&&bl(vl,im);const Lt=Kt()(ss((s,r)=>({projects:vl,activeProjectId:im,validateProjectPath:t=>{if(typeof t!="string"||t.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=Oa(t);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(t,n)=>{if(Vs)return null;const{validateProjectPath:o}=r(),a=o(t);if(!a.ok||!a.normalizedPath)return null;const l=a.normalizedPath,c=r().projects.find(y=>y.path===l);if(c)return r().setActiveProject(c.id),c;const d=Date.now(),u=n?.label?.trim()||om(l),m=n?.id?.trim(),p={id:m&&!r().projects.some(y=>y.id===m)?m:nx(),path:l,label:u,addedAt:d,lastOpenedAt:d},h=[...r().projects,p];return s({projects:h}),rs()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:t=>{if(Vs)return;const n=r(),o=n.projects.filter(l=>l.id!==t);let a=n.activeProjectId;if(n.activeProjectId===t&&(a=o[0]?.id??null),s({projects:o,activeProjectId:a}),pn(o,a),a){const l=o.find(c=>c.id===a);l&&(Ee.setDirectory(l.path),yt.getState().setDirectory(l.path,{showOverlay:!1}))}else yt.getState().goHome()},setActiveProject:t=>{if(Vs)return;const{projects:n,activeProjectId:o}=r();if(o===t)return;const a=n.find(d=>d.id===t);if(!a)return;const l=Date.now(),c=n.map(d=>d.id===t?{...d,lastOpenedAt:l}:d);s({projects:c,activeProjectId:t}),pn(c,t),Ee.setDirectory(a.path),yt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:t=>{if(Vs)return;const{projects:n,activeProjectId:o}=r();if(o===t||!n.find(d=>d.id===t))return;const l=Date.now(),c=n.map(d=>d.id===t?{...d,lastOpenedAt:l}:d);s({projects:c,activeProjectId:t}),pn(c,t)},renameProject:(t,n)=>{if(Vs)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:l}=r(),c=a.map(d=>d.id===t?{...d,label:o}:d);s({projects:c}),pn(c,l)},reorderProjects:(t,n)=>{if(Vs)return;const{projects:o,activeProjectId:a}=r();if(t<0||t>=o.length||n<0||n>=o.length||t===n)return;const l=[...o],[c]=l.splice(t,1);l.splice(n,0,c),s({projects:l}),pn(l,a)},synchronizeFromSettings:t=>{if(Vs)return;const n=am(t.projects??[]),o=typeof t.activeProjectId=="string"&&t.activeProjectId.trim()?t.activeProjectId.trim():null,a=r(),l=JSON.stringify(a.projects)!==JSON.stringify(n),c=a.activeProjectId!==o;if(!(!l&&!c)&&(s({projects:n,activeProjectId:o}),bl(n,o),o)){const d=n.find(u=>u.id===o);d&&(Ee.setDirectory(d.path),yt.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:t,activeProjectId:n}=r();return n?t.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(t,n)=>{if(Vs)return;const{projects:o,activeProjectId:a}=r(),l=o.find(u=>u.id===t);if(!l)return;const c={...l.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?c.branchPrefix=n.branchPrefix.trim():delete c.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?c.baseBranch=n.baseBranch.trim():delete c.baseBranch),n.autoCreateWorktree!==void 0&&(c.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===t?{...u,worktreeDefaults:Object.keys(c).length>0?c:void 0}:u);s({projects:d}),pn(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",s=>{const r=s.detail;r&&typeof r=="object"&&Lt.getState().synchronizeFromSettings(r)});const cx=new Set(["init","review"]),wn=s=>cx.has(s.name),Yn="useCommandsStore",Vi=s=>new Promise(r=>setTimeout(r,s)),jo=()=>{try{const r=Lt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=Ee.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[CommandsStore] Error resolving config directory:",s)}return null},dx=2e4,pc=300,hc=4,ux=800,mx=200,fx=2e3,Wr=Kt()(ss(Ps((s,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:t=>{s({selectedCommandName:t})},setCommandDraft:t=>{s({commandDraft:t})},loadCommands:async()=>{s({isLoading:!0});const t=r().commands;let n=null;for(let o=0;o<3;o++)try{const a=jo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await Ee.withDirectory(a,()=>Ee.listCommandsWithDetails()),d=await Promise.all(c.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${l}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const 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(t)!==JSON.stringify(d)?s({commands:d,isLoading:!1}):s({isLoading:!1}),!0}catch(a){n=a;const l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{_s("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),t.scope&&(o.scope=t.scope),console.log("[CommandsStore] Command config to save:",o);const a=jo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await ei({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&ur("commands",{source:Yn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||ks()}},updateCommand:async(t,n)=>{_s("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const l=jo(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await ei({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&ur("commands",{source:Yn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||ks()}},deleteCommand:async t=>{_s("Deleting command configuration…");let n=!1;try{const o=jo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),c?.requiresReload??!0)return n=!0,await ei({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&ur("commands",{source:Yn}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||ks()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:Ts(()=>ps()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Wr);async function px(s){const r=typeof s=="number"&&s>0?Math.min(s,pc):0;r>0&&await Vi(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<dx;){n+=1,jr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ee.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,l=n<=hc&&a<1200?pc:Math.min(ux+Math.max(0,n-hc)*mx,fx);await Vi(l)}throw o||new Error("OpenCode did not become ready in time")}async function ei(s={}){const{message:r,delayMs:t}=s;try{jr(r||"Refreshing commands…")}catch{}try{await px(t),jr("Refreshing commands…"),await Wr.getState().loadCommands(),ur("commands",{source:Yn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),jr("OpenCode refresh failed. Please retry refreshing configuration manually."),await Vi(1500)}finally{ks()}}let gc=null;gc||(gc=Fa(s=>{if(s.source!==Yn&&io(s,"commands")){const{loadCommands:r}=Wr.getState();r()}}));const Mr=()=>{const s=Ee.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Qo="useSkillsStore",Qs=Kt()(ss(Ps((s,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:t=>{s({selectedSkillName:t})},setSkillDraft:t=>{s({skillDraft:t})},loadSkills:async()=>{s({isLoading:!0});const t=r().skills;let n=null;for(let o=0;o<3;o++)try{const a=Mr(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills${l}`);if(!c.ok)throw new Error(`Failed to list skills: ${c.status}`);const m=((await c.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return s({skills:m,isLoading:!1}),!0}catch(a){n=a;const l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=Mr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async t=>{_s("Creating skill...");try{const n={name:t.name,description:t.description};t.instructions&&(n.instructions=t.instructions),t.scope&&(n.scope=t.scope),t.supportingFiles&&(n.supportingFiles=t.supportingFiles);const o=Mr(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),c=await l.json().catch(()=>null);if(!l.ok){const u=c?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&ur("skills",{source:Qo}),d}catch{return!1}finally{ks()}},updateSkill:async(t,n)=>{_s("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=Mr(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&ur("skills",{source:Qo}),u}catch{return!1}finally{ks()}},deleteSkill:async t=>{_s("Deleting skill...");try{const n=Mr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`,{method:"DELETE"}),l=await a.json().catch(()=>null);if(!a.ok){const d=l?.error||"Failed to delete skill";throw new Error(d)}const c=await r().loadSkills();return c&&ur("skills",{source:Qo}),r().selectedSkillName===t&&s({selectedSkillName:null}),c}catch{return!1}finally{ks()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=Mr(),a=o?`&directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return l.ok?(await l.json()).content??null:null}catch{return null}},writeSupportingFile:async(t,n,o)=>{try{const a=Mr(),l=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${l}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(t,n)=>{try{const o=Mr(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Ts(()=>ps()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=Qs);let xc=null;xc||(xc=Fa(s=>{if(s.source!==Qo&&io(s,"skills")){const{loadSkills:r}=Qs.getState();r()}}));const ti=()=>{const s=Ee.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},go=Kt()(ss((s,r)=>({sources:[],itemsBySource:{},selectedSourceId:null,isLoadingCatalog:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:t=>s({selectedSourceId:t}),loadCatalog:async t=>{s({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource};let o=null;try{for(let a=0;a<3;a++)try{const l=ti(),c=t?.refresh?"&refresh=true":"",d=l?`?directory=${encodeURIComponent(l)}${c}`:c?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const g=200*(a+1);await new Promise(w=>setTimeout(w,g));continue}const f=m.sources||[],p=m.itemsBySource||{},h=r().selectedSourceId,y=h&&f.some(g=>g.id===h)?h:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:y}),!0}catch(l){o={kind:"unknown",message:l instanceof Error?l.message:String(l)};const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}return s({sources:n.sources,itemsBySource:n.itemsBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{s({isLoadingCatalog:!1})}},scanRepo:async t=>{s({isScanning:!0,lastScanError:null,scanResults:null});try{const n=ti(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),l=await a.json().catch(()=>null);if(!a.ok||!l){const c=l?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:c}),{ok:!1,error:c}}return l.ok?(s({scanResults:l.items||[]}),l):(s({lastScanError:l.error||{kind:"unknown",message:"Failed to scan repository"}}),l)}finally{s({isScanning:!1})}},installSkills:async t=>{s({isInstalling:!0,lastInstallError:null});try{const n=ti(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/install${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),l=await a.json().catch(()=>null);if(!l){const c={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}if(!a.ok||!l.ok){const c=l.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}return Qs.getState().loadSkills(),l}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return s({lastInstallError:o}),{ok:!1,error:o}}finally{s({isInstalling:!1})}}}),{name:"skills-catalog-store"})),hx=()=>{const s=Ee.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},So=()=>{try{const r=Lt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=Ee.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[AgentsStore] Error resolving config directory:",s)}return null},Jr=s=>{const r=s;return r.native===!0||r.builtIn===!0},lm=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},cm=s=>s.filter(r=>!lm(r)),Yo="useAgentsStore",da=s=>new Promise(r=>setTimeout(r,s)),gx=2e4,yc=300,bc=4,xx=800,yx=200,bx=2e3,Hr=Kt()(ss(Ps((s,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:t=>{s({selectedAgentName:t})},setAgentDraft:t=>{s({agentDraft:t})},loadAgents:async()=>{s({isLoading:!0});const t=r().agents;for(let n=0;n<3;n++)try{const o=So(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await Ee.withDirectory(o,()=>Ee.listAgents()),c=await Promise.all(l.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(t)!==JSON.stringify(c)?s({agents:c,isLoading:!1}):s({isLoading:!1}),!0}catch{}return s({isLoading:!1}),!1},createAgent:async t=>{_s("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),t.scope&&(o.scope=t.scope),console.log("[AgentsStore] Agent config to save:",o);const a=So(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Xn({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&ur("agents",{source:Yo}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||ks()}},updateAgent:async(t,n)=>{_s("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const l=So(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await Xn({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&ur("agents",{source:Yo}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||ks()}},deleteAgent:async t=>{_s("Deleting agent configuration…");let n=!1;try{const o=So(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete agent";throw new Error(m)}if(c?.requiresReload??!0)return n=!0,await Xn({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&ur("agents",{source:Yo}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||ks()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return cm(t)}}),{name:"agents-store",storage:Ts(()=>ps()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Hr);async function vx(s){const r=typeof s=="number"&&s>0?Math.min(s,yc):0;r>0&&await da(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<gx;){n+=1,jr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ee.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,l=n<=bc&&a<1200?yc:Math.min(xx+Math.max(0,n-bc)*yx,bx);await da(l)}throw o||new Error("OpenCode did not become ready in time")}const wx=s=>{if(!s||s.length===0)return["all"];const r=Array.from(new Set(s));return r.includes("all")?["all"]:r};async function jx(s={}){const{message:r,delayMs:t}=s,n=wx(s.scopes),o=s.mode??(n.includes("all")?"projects":"active");try{jr(r||"Refreshing configuration…")}catch{}try{await vx(t);const a=nt.getState(),l=Hr.getState(),c=Wr.getState(),d=Qs.getState(),u=go.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"),y=n.includes("all")||n.includes("skills"),g=hx(),w=o==="projects"?Lt.getState().projects:[],b=Array.from(new Set([...g?[g]:[],...w.map(k=>k.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&nt.setState({directoryScoped:{}});const v=[];for(const k of b)m&&v.push(a.loadProviders({directory:k}).then(()=>{})),f&&v.push(a.loadAgents({directory:k}).then(()=>{}));const j=[];p&&j.push(l.loadAgents().then(()=>{})),h&&j.push(c.loadCommands().then(()=>{})),y&&(j.push(d.loadSkills().then(()=>{})),j.push(u.loadCatalog().then(()=>{}))),jr("Refreshing configuration…"),await Promise.all([...v,...j])}catch{jr("OpenCode refresh failed. Please retry."),await da(1500)}finally{ks()}}async function Xn(s){await jx(s)}async function Jn(s){_s(s?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await r.json().catch(()=>null);if(!r.ok){const o=t?.error||"Failed to reload configuration";throw new Error(o)}const n={...s,scopes:s?.scopes??["all"],mode:s?.mode??"projects"};t?.requiresReload?await Xn({...n,message:t.message,delayMs:t.reloadDelayMs}):await Xn(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),jr("Failed to reload configuration. Please try again."),await da(2e3),ks(),r}}let vc=null;vc||(vc=Fa(s=>{if(s.source!==Yo&&io(s,"agents")){const{loadAgents:r}=Hr.getState();r()}}));const Sx="https://models.dev/api.json",kx="/api/openchamber/models-metadata",wc="opencode",jc="big-pickle",Nx=async()=>{try{if(os()){const d=await zr();return{defaultModel:d?.defaultModel,defaultVariant:d?.defaultVariant,defaultAgent:d?.defaultAgent,autoCreateWorktree:d?.autoCreateWorktree,commitMessageModel:d?.commitMessageModel,gitmojiEnabled:d?.gitmojiEnabled}}const s=Zs()?.settings;if(s)try{const u=(await s.load())?.settings;if(u){const m=typeof u?.defaultModel=="string"?u.defaultModel.trim():"",f=typeof u?.defaultVariant=="string"?u.defaultVariant.trim():"",p=typeof u?.defaultAgent=="string"?u.defaultAgent.trim():"",h=typeof u?.commitMessageModel=="string"?u.commitMessageModel.trim():"",y=typeof u?.gitmojiEnabled=="boolean"?u.gitmojiEnabled:void 0;return{defaultModel:m.length>0?m:void 0,defaultVariant:f.length>0?f:void 0,defaultAgent:p.length>0?p:void 0,autoCreateWorktree:typeof u?.autoCreateWorktree=="boolean"?u.autoCreateWorktree:void 0,commitMessageModel:h.length>0?h:void 0,gitmojiEnabled:y}}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const t=await r.json(),n=typeof t?.defaultModel=="string"?t.defaultModel.trim():"",o=typeof t?.defaultVariant=="string"?t.defaultVariant.trim():"",a=typeof t?.defaultAgent=="string"?t.defaultAgent.trim():"",l=typeof t?.commitMessageModel=="string"?t.commitMessageModel.trim():"",c=typeof t?.gitmojiEnabled=="boolean"?t.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 t?.autoCreateWorktree=="boolean"?t.autoCreateWorktree:void 0,commitMessageModel:l.length>0?l:void 0,gitmojiEnabled:c}}catch{return{}}},ko=s=>{if(!s||typeof s!="string")return null;const r=s.split("/");return r.length!==2||!r[0]||!r[1]?null:{providerId:r[0],modelId:r[1]}},Cx=s=>s?.toLowerCase?.()??"",Mx=s=>s==="primary"||s==="all"||s===void 0||s===null,lo=s=>typeof s=="object"&&s!==null,ua=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),Dx=s=>{if(!lo(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!ua(t)||n&&!ua(n))return!1}return!0},Ax=s=>{if(!lo(s))return!1;const r=s;return r.models===void 0||lo(r.models)},dm=(s,r)=>{const t=Cx(s);return!t||!r?"":`${t}/${r}`},Ex=s=>{const r=new Map;if(!lo(s))return r;for(const[t,n]of Object.entries(s)){if(!Ax(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!lo(a)))for(const[l,c]of Object.entries(a)){if(!Dx(c))continue;const d=typeof l=="string"&&l.length>0?l:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:ua(c.modalities.input)?c.modalities.input:void 0,output:ua(c.modalities.output)?c.modalities.output:void 0}:void 0,cost:c.cost,limit:c.limit,knowledge:typeof c.knowledge=="string"?c.knowledge:void 0,release_date:typeof c.release_date=="string"?c.release_date:void 0,last_updated:typeof c.last_updated=="string"?c.last_updated:void 0},m=dm(o,d);m&&r.set(m,u)}}return r},Ix=async()=>{if(typeof fetch!="function")return new Map;const s=[kx,Sx];for(const r of s){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const l=await fetch(r,a);if(!l.ok)throw new Error(`Metadata request to ${r} returned status ${l.status}`);const c=await l.json();return Ex(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let si=null;const Px=(s,r)=>{s().size>0||si||(si=Ix().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{si=null}))},Tx=s=>new Promise(r=>setTimeout(r,s)),wl="__global__",Cn=s=>{const r=typeof s=="string"?s.trim():"";return r.length>0?r:wl},hn=s=>s===wl?null:s,Fx=()=>{if(typeof window>"u")return wl;const s=Ee.getDirectory()??yt.getState().currentDirectory;return Cn(s)},nt=Kt()(ss(Ps((s,r)=>({activeDirectoryKey:Fx(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,settingsCommitMessageModel:void 0,settingsGitmojiEnabled:!1,activateDirectory:async t=>{const n=Cn(t);s(o=>{const a=o.directoryScoped[n];return a?{activeDirectoryKey:n,providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders}:{activeDirectoryKey:n,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),r().isConnected&&(await r().loadProviders({directory:hn(n)}),await r().loadAgents({directory:hn(n)}))},loadProviders:async t=>{const n=Cn(t?.directory??hn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),l=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let c=null;for(let d=0;d<3;d++)try{Px(()=>r().modelsMetadata,h=>s({modelsMetadata:h}));const u=await Ee.withDirectory(hn(n),()=>Ee.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(h=>{const y=h.models??{},g=Object.keys(y).map(w=>y[w]);return{...h,models:g}});s(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 b=ko(h.settingsDefaultModel);if(b){const v=p.find(j=>j.id===b.providerId);if(v?.models.some(j=>j.id===b.modelId)){const j=v.models.find(x=>x.id===b.modelId),k=h.settingsDefaultVariant&&j?.variants?.[h.settingsDefaultVariant]?h.settingsDefaultVariant:void 0;w.currentProviderId=b.providerId,w.currentModelId=b.modelId,w.currentVariant=k,w.selectedProviderId=b.providerId,g.currentProviderId=b.providerId,g.currentModelId=b.modelId,g.currentVariant=k,g.selectedProviderId=b.providerId}}}return w});return}catch(u){c=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",c),s(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:l},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=l,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=ko(d.settingsDefaultModel);if(p){const h=a.find(y=>y.id===p.providerId);if(h?.models.some(y=>y.id===p.modelId)){const y=h.models.find(w=>w.id===p.modelId),g=d.settingsDefaultVariant&&y?.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:t=>{const{providers:n}=r(),o=n.find(c=>c.id===t);if(!o)return;const l=o.models[0]?.id||"";s(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentVariant:c.currentVariant,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentProviderId:t,currentModelId:l,selectedProviderId:t};return{currentProviderId:t,currentModelId:l,selectedProviderId:t,directoryScoped:{...c.directoryScoped,[d]:m}}})},setModel:t=>{s(n=>{const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:t};return{currentModelId:t,directoryScoped:{...n.directoryScoped,[o]:l}}})},setCurrentVariant:t=>{s(n=>{if(n.currentVariant===t)return n;const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:t};return{currentVariant:t,directoryScoped:{...n.directoryScoped,[o]:l}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const t=r().getCurrentModelVariants();if(t.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(t[0]);return}const o=t.indexOf(n);if(o===-1||o===t.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(t[o+1])},setSelectedProvider:t=>{s(n=>{const o=n.activeDirectoryKey,l={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:t};return{selectedProviderId:t,directoryScoped:{...n.directoryScoped,[o]:l}}})},saveAgentModelSelection:(t,n,o)=>{s(a=>{const l=a.activeDirectoryKey,c={...a.agentModelSelections,[t]:{providerId:n,modelId:o}},u={...a.directoryScoped[l]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:c};return{agentModelSelections:c,directoryScoped:{...a.directoryScoped,[l]:u}}})},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async t=>{const n=Cn(t?.directory??hn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let l=null;for(let c=0;c<3;c++)try{const[d,u]=await Promise.all([Ee.withDirectory(hn(n),()=>Ee.listAgents()),Nx()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(s(x=>{const P={...x.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},C={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsCommitMessageModel:u.commitMessageModel,settingsGitmojiEnabled:u.gitmojiEnabled??!1,directoryScoped:{...x.directoryScoped,[n]:P}};return x.activeDirectoryKey===n&&(C.agents=m),C}),m.length===0)return s(x=>{const P={...x.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},C={directoryScoped:{...x.directoryScoped,[n]:P}};return x.activeDirectoryKey===n&&(C.currentAgentName=void 0),C}),!0;const p=(x,N)=>{const P=f.find(C=>C.id===x);return P?P.models.some(C=>C.id===N):!1},h=m.filter(x=>Mx(x.mode));let w=h.find(x=>x.name==="build")||h[0]||m[0];const b={};if(u.defaultAgent){const x=m.find(N=>N.name===u.defaultAgent);x?w=x:b.defaultAgent=""}let v,j,k;if(u.defaultModel){const x=ko(u.defaultModel);if(x&&p(x.providerId,x.modelId)){if(v=x.providerId,j=x.modelId,u.defaultVariant){const C=f.find(M=>M.id===x.providerId)?.models.find(M=>M.id===x.modelId)?.variants;C&&Object.prototype.hasOwnProperty.call(C,u.defaultVariant)?k=u.defaultVariant:b.defaultVariant=""}}else b.defaultModel=""}if(!v&&w?.model?.providerID&&w?.model?.modelID){const{providerID:x,modelID:N}=w.model;p(x,N)&&(v=x,j=N)}if(!v)if(p(wc,jc))v=wc,j=jc;else{const x=f[0],N=x?.models[0];x&&N&&(v=x.id,j=N.id)}return s(x=>{const N=x.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},P={...N,providers:f,agents:m,currentAgentName:w.name,currentProviderId:v??N.currentProviderId,currentModelId:j??N.currentModelId,currentVariant:k},C={directoryScoped:{...x.directoryScoped,[n]:P}};return x.activeDirectoryKey===n&&(C.currentAgentName=w.name,v&&j&&(C.currentProviderId=v,C.currentModelId=j,C.currentVariant=k)),C}),Object.keys(b).length>0&&(s({settingsDefaultModel:b.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:b.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:b.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),ns(b).catch(()=>{})),!0}catch(d){l=d;const u=200*(c+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",l),s(c=>{const d=c.activeDirectoryKey===n?c.providers:c.directoryScoped[n]?.providers??[],m={...c.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...c.directoryScoped,[n]:m}};return c.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:l}=r();if(s(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentAgentName:t};return{currentAgentName:t,directoryScoped:{...c.directoryScoped,[d]:m}}}),t&&typeof window<"u"){const c=window.__zustand_session_store__;if(c){const d=c.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&c.setState(h=>{const y=new Map(h.currentAgentContext);return y.set(u,t),{currentAgentContext:y}}),u&&m(u)&&(p(u,t)||f(u,n))}}if(t&&typeof window<"u"){const c=window.__zustand_session_store__;if(c?.getState){const{currentSessionId:m,getAgentModelForSession:f}=c.getState();if(m&&f(m,t))return}if(a){const m=ko(a);if(m&&o.find(p=>p.id===m.providerId)?.models.some(p=>p.id===m.modelId)){s(p=>{const h=p.activeDirectoryKey,y=p.directoryScoped[h]??{providers:p.providers,agents:p.agents,currentProviderId:p.currentProviderId,currentModelId:p.currentModelId,currentVariant:p.currentVariant,currentAgentName:p.currentAgentName,selectedProviderId:p.selectedProviderId,agentModelSelections:p.agentModelSelections,defaultProviders:p.defaultProviders};let g;if(l){const j=o.find(k=>k.id===m.providerId)?.models.find(k=>k.id===m.modelId)?.variants;j&&Object.prototype.hasOwnProperty.call(j,l)&&(g=l)}const w={...y,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===t)?.model;if(u?.providerID&&u?.modelID){const{providerID:m,modelID:f}=u;o.find(y=>y.id===m)?.models.find(y=>y.id===f)&&s(y=>{const g=y.activeDirectoryKey,b={...y.directoryScoped[g]??{providers:y.providers,agents:y.agents,currentProviderId:y.currentProviderId,currentModelId:y.currentModelId,currentAgentName:y.currentAgentName,selectedProviderId:y.selectedProviderId,agentModelSelections:y.agentModelSelections,defaultProviders:y.defaultProviders},currentProviderId:m,currentModelId:f,selectedProviderId:m};return{currentProviderId:m,currentModelId:f,selectedProviderId:m,directoryScoped:{...y.directoryScoped,[g]:b}}})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultVariant:t=>{s({settingsDefaultVariant:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},setSettingsAutoCreateWorktree:t=>{s({settingsAutoCreateWorktree:t})},setSettingsCommitMessageModel:t=>{s({settingsCommitMessageModel:t})},setSettingsGitmojiEnabled:t=>{s({settingsGitmojiEnabled:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Ee.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const l=400*n;await Tx(l)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{const t=rs();t&&console.log("Starting app initialization...");const n=await r().checkConnection();if(t&&console.log("Connection check result:",n),!n){t&&console.log("Server not connected"),s({isConnected:!1});return}t&&console.log("Initializing app..."),await Ee.initApp(),t&&console.log("Loading providers..."),await r().loadProviders(),t&&console.log("Loading agents..."),await r().loadAgents(),s({isInitialized:!0,isConnected:!0}),t&&console.log("App initialized successfully")}catch(t){console.error("Failed to initialize app:",t),s({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:t,currentProviderId:n}=r();return t.find(o=>o.id===n)},getCurrentModel:()=>{const t=r().getCurrentProvider(),{currentModelId:n}=r();if(t)return t.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:t,currentAgentName:n}=r();if(n)return t.find(o=>o.name===n)},getModelMetadata:(t,n)=>{const o=dm(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return cm(t)}}),{name:"config-store",storage:Ts(()=>ps()),partialize:s=>({activeDirectoryKey:s.activeDirectoryKey,directoryScoped:s.directoryScoped,currentProviderId:s.currentProviderId,currentModelId:s.currentModelId,currentVariant:s.currentVariant,currentAgentName:s.currentAgentName,selectedProviderId:s.selectedProviderId,agentModelSelections:s.agentModelSelections,defaultProviders:s.defaultProviders,settingsDefaultModel:s.settingsDefaultModel,settingsDefaultVariant:s.settingsDefaultVariant,settingsDefaultAgent:s.settingsDefaultAgent,settingsAutoCreateWorktree:s.settingsAutoCreateWorktree,settingsCommitMessageModel:s.settingsCommitMessageModel,settingsGitmojiEnabled:s.settingsGitmojiEnabled})})));typeof window<"u"&&(window.__zustand_config_store__=nt);let Sc=null;Sc||(Sc=Fa(async s=>{const r=[];if(io(s,"agents")){const{loadAgents:t}=nt.getState();r.push(t().then(()=>{}))}if(io(s,"providers")){const{loadProviders:t}=nt.getState();r.push(t())}r.length>0&&await Promise.all(r)}));let kc=null;typeof window<"u"&&!kc&&(kc=yt.subscribe((s,r)=>{const t=Cn(s.currentDirectory),n=Cn(r.currentDirectory);t!==n&&nt.getState().activateDirectory(s.currentDirectory)}));const fs={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,HISTORICAL_MESSAGES:90,FETCH_BUFFER:20,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Rx=180,bs=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Ur(s){const r=bs();return r?r.checkIsGitRepository(s):rg(s)}async function Ox(s){const r=bs();return r?r.getGitStatus(s):og(s)}async function _a(s){const r=bs();return r?r.getGitBranches(s):xg(s)}async function _x(s,r){const t=bs();return t?t.deleteGitBranch(s,r):ig(s,r)}async function $x(s,r){const t=bs();return t?t.deleteRemoteBranch(s,r):lg(s,r)}async function um(s){const r=bs();return r?r.listGitWorktrees(s):ng(s)}async function Lx(s,r){const t=bs();return t?t.addGitWorktree(s,r):cg(s,r)}async function mm(s,r){const t=bs();return t?t.removeGitWorktree(s,r):ag(s,r)}async function Bx(s){const r=bs();return r?r.ensureOpenChamberIgnored(s):gg(s)}async function zx(){const s=bs();return s?s.getGitIdentities():hg()}async function Wx(s){const r=bs();return r?r.createGitIdentity(s):mg(s)}async function Hx(s,r){const t=bs();return t?t.updateGitIdentity(s,r):ug(s,r)}async function Ux(s){const r=bs();return r?r.deleteGitIdentity(s):dg(s)}async function Vx(){const s=bs();return s?.discoverGitCredentials?s.discoverGitCredentials():fg()}async function Gx(){const s=bs();return s?.getGlobalGitIdentity?s.getGlobalGitIdentity():pg()}const qx="openchamber.json",fm=".openchamber";function pm(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const Kx=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Gi=(s,r)=>{const t=Kx(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},hm=s=>Gi(Gi(s,fm),qx);async function gm(s){const r=hm(s);try{const t=pm();if(t?.readFile)try{const l=await t.readFile(r);if(!l.content.trim())return null;const c=JSON.parse(l.content);return!c||typeof c!="object"?null:c}catch{return null}const n=await fetch(`${ym()}/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 Qx(s,r){const t=hm(s),n=Gi(s,fm);try{await Ee.createDirectory(n);const o=pm();if(o?.writeFile)try{return(await o.writeFile(t,JSON.stringify(r,null,2))).success}catch(l){return console.error("Failed to write openchamber config via runtime API:",l),!1}return(await fetch(`${ym()}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,content:JSON.stringify(r,null,2)})})).ok}catch(o){return console.error("Failed to write openchamber config:",o),!1}}async function Yx(s,r){const n={...await gm(s)||{},...r};return Qx(s,n)}async function Ln(s){return(await gm(s))?.["setup-worktree"]??[]}async function xm(s,r){const t=r.filter(n=>n.trim().length>0);return Yx(s,{"setup-worktree":t})}function Xx(s,r){return s.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function ym(){const s="/api";return s.startsWith("/"),s}const Jx=".openchamber",Nc="/api";function Zx(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const kr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Cc=(s,r)=>{const t=kr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},bm=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",ey=async s=>{try{await Ee.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function ty(s,r){const t=kr(s),n=Cc(t,Jx);return await ey(n),Cc(n,r)}async function jl(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,l=kr(r),c=await ty(l,t),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await Lx(l,d),{path:c,branch:n,label:bm(n),projectDirectory:l,relativePath:c.startsWith(`${l}/`)?c.slice(l.length+1):c}}async function vm(s){const{projectDirectory:r,path:t,force:n}=s,o=kr(r);await mm(o,{path:t,force:n})}async function wm(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:l}=s,c=kr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await mm(c,{path:t,force:o}),d&&(await _x(c,{branch:d,force:!0}),a))try{await $x(c,{branch:d,remote:l})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function In(s){const r=kr(s);return um(r)}async function $a(s){const r=kr(s),t=await Ox(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function Pn(s,r){const t=kr(s),n=kr(r.worktree);return{path:n,branch:r.branch??"",label:bm(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}async function Sl(s,r,t){const n=t??await Ln(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>Xx(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:s,projectDirectory:r,commands:o});try{const a=Zx();if(a?.execCommands){console.log("[worktreeService] Using runtime API for exec");try{const d=await a.execCommands(o,s);return console.log("[worktreeService] Runtime exec result:",d),d}catch(d){return console.error("[worktreeService] Runtime exec error:",d),{success:!1,results:o.map(u=>({command:u,success:!1,error:d instanceof Error?d.message:"Unknown error"}))}}}console.log("[worktreeService] Using web API for exec");const l=await fetch(`${Nc}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:s,background:!0})}),c=await l.json().catch(()=>null);if(l.status===202&&c&&typeof c.jobId=="string"){const d=c.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(g=>setTimeout(g,u));const p=await fetch(`${Nc}/fs/exec/${d}`,{method:"GET"}),h=await p.json().catch(()=>null);if(!p.ok)return{success:!1,results:o.map(g=>({command:g,success:!1,error:h&&h.error||"Failed to poll exec job"}))};if(h?.status==="done"){const g=Array.isArray(h?.results)?h.results:[];return{success:h?.success===!0,results:g}}}return{success:!1,results:o.map(p=>({command:p,success:!1,error:"Setup commands timed out"}))}}if(!l.ok){const d=c&&c.error||"Request failed";return console.error("[worktreeService] Web exec failed:",c),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",c),c}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(l=>({command:l,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const jm=ps(),Sm="oc.sessionSelectionByDirectory",ri=".openchamber",sy=()=>{try{const s=jm.getItem(Sm);if(!s)return{};const r=JSON.parse(s);return!r||typeof r!="object"?{}:Object.entries(r).reduce((t,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(t[n]=o),t),{})}catch{return{}}};let Xo=null;const kl=()=>(Xo||(Xo=sy()),Xo),km=s=>{Xo=s;try{jm.setItem(Sm,JSON.stringify(s))}catch{}},Nm=s=>{if(!s)return null;const t=kl()[s];return typeof t=="string"?t:null},xr=(s,r)=>{if(!s)return;const t={...kl()};r?t[s]=r:delete t[s],km(t)},ry=(s,r)=>{if(!s)return;const t=Nm(s);if(!t)return;if(!new Set(r).has(t)){const o={...kl()};delete o[s],km(o)}},Mc=async(s,r)=>{const t=s.status??await $a(s.path).catch(()=>{});await wm({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},At=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},Dc=()=>{if(typeof window>"u")return null;const s=window.__VSCODE_CONFIG__,r=typeof s?.workspaceFolder=="string"?s.workspaceFolder:null;return At(r)},ny=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,No=(...s)=>{rs()&&ny()&&console.log("[OpenChamber][VSCode][sessions]",...s)},Dr=s=>{const r=new Map;return s.forEach(t=>{if(!t||typeof t.id!="string"||t.id.length===0)return;const n=r.get(t.id);if(!n){r.set(t.id,t);return}const o=n.time?.updated??0;(t.time?.updated??0)>o&&r.set(t.id,t)}),Array.from(r.values())},Ws=s=>{const r=new Map;s.forEach(t=>{const n=At(t.directory??null);if(!n)return;const o=r.get(n);o?o.push(t):r.set(n,[t])});for(const[t,n]of r.entries())r.set(t,Dr(n));return r},gn=(s,r)=>{const t=s.find(n=>n.id===r);return t?At(t.directory??null):null},oy=async(s,r,t)=>{const n=At(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:At(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await In(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(t);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const l=new Map;a.forEach(u=>{const m=Pn(n,u),f=At(m.path)??m.path;f!==n&&l.set(f,m)});let c=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=l.get(m);if(!f){d.delete(u)&&(c=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),c=!0)}),c?d:null},pt=Kt()(ss(Ps((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,loadSessions:async()=>{s({isLoading:!0,error:null});try{const t=yt.getState(),n=Lt.getState(),o=Ee.getApiClient(),a=Dc(),l=!!a;No("loadSessions:start",{workspace:a,currentDirectory:t.currentDirectory,clientDirectory:Ee.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const c=new Map,d=async _=>{const V=At(_)??_,Y=V,H=c.get(Y);if(H)return H;try{const L=await o.path.get({directory:_}),Q=At(L.data?.directory??null)??V;return c.set(Y,Q),Q}catch{return c.set(Y,V),V}},u=(_,V,Y)=>{const H=At(V);if(!H)return _;const U=Y?.includeDescendants===!0?`${H}/`:null,Q=Y?.includeMissingDirectory===!0;return _.filter(J=>{const K=At(J.directory??null);return K?!!(K===H||U&&K.startsWith(U)):Q})},m=(_,V,Y)=>{const H=At(V);if(!H)return _;const L=At(Y??null);if(!L||L===H)return _.map(J=>At(J.directory??null)?J:{...J,directory:H});const U=L==="/"?"/":`${L}/`,Q=H==="/"?"/":`${H}/`;return _.map(J=>{const K=At(J.directory??null);if(!K)return{...J,directory:H};if(K===L)return{...J,directory:H};if(U!=="/"&&K.startsWith(U)){const ne=K.slice(U.length);return{...J,directory:`${Q}${ne}`}}return J})},f=async _=>{const V=At(_);if(!V)try{const K=await o.session.list(void 0);return Array.isArray(K.data)?K.data:[]}catch(K){throw console.debug("Failed to list sessions (global):",K),K}const Y=await d(V),H=async()=>{const K=await o.session.list({directory:V});return Array.isArray(K.data)?K.data:[]};let L=[],U=null,Q=!1;try{L=await H()}catch(K){console.debug("Failed to list sessions for directory:",V,K),U=K,L=[]}if(L.length===0){Q=!0;try{const K=await o.session.list(void 0),ne=Array.isArray(K.data)?K.data:[];L=u(ne,Y,{includeDescendants:l,includeMissingDirectory:!1})}catch(K){throw console.debug("Failed to list sessions (global fallback):",K),U||K}}const J=u(L,Y,{includeDescendants:l,includeMissingDirectory:!Q});return No("fetchSessionsForDirectory",{requestedDirectory:V,canonicalDirectory:Y,fetched:L.length,filtered:J.length}),m(J,V,Y)},p=At(t.currentDirectory??Ee.getDirectory()??null),h=n.projects.find(_=>_.id===n.activeProjectId)??null,y=At(h?.path??null),g=y??p??null,w=n.projects.length>0?n.projects:g?[{id:"legacy",path:g}]:[];if(w.length===0){s({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const b=await Promise.all(w.map(async _=>{const V=At(_.path);if(!V)return{projectId:_.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const Y=await Ur(V).catch(()=>!1),H=await f(V||null);No("projectSessions",{projectId:_.id,projectPath:V,isGitRepo:Y,parentSessions:H.length});const L=[];let U=[];const Q=new Set;if(Q.add(V),Y){const K=`${V}/${ri}`;try{const ne=new Set;(await Ee.listLocalDirectory(V)).some(z=>z.isDirectory&&z.name===ri)&&(await Ee.listLocalDirectory(K)).filter(T=>T.isDirectory).forEach(T=>{const W=/^([A-Za-z]:)?\//.test(T.path)?T.path:`${K}/${T.name}`,q=At(W)??W;ne.add(q)});const O=await In(V);Array.isArray(O)&&(U=O.map(z=>Pn(V,z)).filter(z=>z.path.includes(`/${ri}/`)),U.forEach(z=>ne.add(z.path))),ne.forEach(z=>{const T=At(z)??z;Q.add(T)}),ne.size>0&&(await Promise.allSettled(Array.from(ne).map(T=>f(T)))).forEach(T=>{T.status==="fulfilled"&&Array.isArray(T.value)&&L.push(...T.value)})}catch{U=[]}}const J=Dr([...H,...L]);return{projectId:_.id,projectPath:V,sessions:J,discoveredWorktrees:U,validPaths:Q}})),v=new Map;b.forEach(_=>{_.projectPath&&_.validPaths.forEach(V=>{const Y=At(V)??V,H=_.sessions.filter(L=>(At(L.directory??null)??Y)===Y);v.set(Y,Dr(H))})});const j=Dr(Array.from(v.values()).flat()),k=r();let x=k.worktreeMetadata;for(const _ of b)if(_.projectPath)try{const V=await oy(_.sessions,_.projectPath,x);V&&(x=V)}catch(V){console.debug("Failed to refresh worktree metadata during session load:",V)}const N=new Map;b.forEach(_=>{_.projectPath&&N.set(_.projectPath,_.discoveredWorktrees)});const P=new Set;b.forEach(_=>{_.validPaths.forEach(V=>{const Y=At(V)??V;Y&&P.add(Y)})});const C=p??y??null,M=C&&P.has(C)?C:y??C,S=M?v.get(M)??[]:j,A=new Set(j.map(_=>_.id));for(const[_,V]of v.entries())ry(_,V.map(Y=>Y.id));const D=(M??null)!==(k.lastLoadedDirectory??null);let F=k.currentSessionId;if((!F||!A.has(F)||D)&&(F=S[0]?.id??j[0]?.id??null),M){const _=Nm(M);_&&A.has(_)&&(F=_)}const E=(()=>{if(!F)return M??null;const _=x.get(F)?.path;if(_)return At(_)??_;const V=gn(j,F);return V||(M??null)})();try{Ee.setDirectory(E??void 0)}catch(_){console.warn("Failed to sync OpenCode directory after session load:",_)}const I=y?b.find(_=>_.projectPath===y)?.discoveredWorktrees??[]:[];s({sessions:j,sessionsByDirectory:v,currentSessionId:F,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:x,availableWorktrees:I,availableWorktreesByProject:N}),M&&xr(M,F),E&&E!==M&&xr(E,F)}catch(t){s({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,n,o)=>{s({error:null});const a=yt.getState(),l=At(a.currentDirectory),c=Dc(),d=c??At(n??Ee.getDirectory()??l);No("createSession:start",{title:t,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:c});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(g=>g.id)),p={id:u,title:t||"New session",parentID:o??void 0,directory:d??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(s(g=>{const w=[p,...g.sessions],b=new Map(g.sessionsByDirectory);if(d){const v=b.get(d)??[];b.set(d,Dr([p,...v]))}return{sessions:w,sessionsByDirectory:b,currentSessionId:u,webUICreatedSessions:new Set([...g.webUICreatedSessions,u]),isLoading:!1}}),d)try{Ee.setDirectory(d)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const h=g=>{const w=d??null,b=w?{...g,directory:w}:g;s(v=>{const j=v.sessions.map(x=>x.id===u?b:x),k=new Map(v.sessionsByDirectory);if(d){const N=(k.get(d)??[]).map(P=>P.id===u?b:P);k.set(d,Dr(N))}return{sessions:j,sessionsByDirectory:Ws(j),currentSessionId:b.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(x=>x!==u),b.id])}}),xr(d??null,b.id)},y=async()=>{const g=Ee.getApiClient(),w=20;for(let b=0;b<w;b+=1){try{const v=await g.session.list(d?{directory:d}:void 0),k=(Array.isArray(v.data)?v.data:[]).find(x=>!(f.has(x.id)||t&&x.title&&x.title!==t));if(k)return k}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,2e3))}return null};try{const g=()=>Ee.createSession({title:t,parentID:o??void 0});let w=null;try{w=d?await Ee.withDirectory(d,g):await g()}catch(b){console.warn("Direct session create failed or timed out, falling back to polling:",b)}return w||(w=await y()),w?(h(w),w):(s(b=>({sessions:b.sessions.filter(v=>v.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(v=>v!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return s(w=>({sessions:w.sessions.filter(b=>b.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(w.webUICreatedSessions).filter(b=>b!==u)),isLoading:!1,error:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{s({isLoading:!0,error:null});const o=r().worktreeMetadata.get(t),a=gn(r().sessions,t),l=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await Mc(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Ee.deleteSession(t);if(!(l?await Ee.withDirectory(l,d):await d()))return s(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const y=new Map(p.worktreeMetadata);y.delete(t),h.worktreeMetadata=y}return h}),!1;let m=null;s(p=>{const h=p.sessions.filter(b=>b.id!==t);m=p.currentSessionId===t?null:p.currentSessionId;const y=new Map(p.worktreeMetadata);y.delete(t);const g=n?.archiveWorktree&&o?p.availableWorktrees.filter(b=>At(b.path)!==At(o.path)):p.availableWorktrees,w=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const b=At(o.projectDirectory)??o.projectDirectory,v=w.get(b)??[];w.set(b,v.filter(j=>At(j.path)!==At(o.path)))}return{sessions:h,sessionsByDirectory:Ws(h),currentSessionId:m,isLoading:!1,worktreeMetadata:y,availableWorktrees:g,availableWorktreesByProject:w}});const f=l??Ee.getDirectory()??null;return xr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return s(c?m=>{const f=new Map(m.worktreeMetadata);return f.delete(t),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(w=>typeof w=="string"&&w.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||s({isLoading:!0,error:null});const l=[],c=[],d=new Set,u=[],m=new Set;for(const w of o)try{const b=r().worktreeMetadata.get(w),v=gn(r().sessions,w),j=b?.path??v;b&&n?.archiveWorktree&&!m.has(b.path)&&(await Mc(b,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(w),u.push({path:b.path,projectDirectory:b.projectDirectory}),m.add(b.path));const k=()=>Ee.deleteSession(w);(j?await Ee.withDirectory(j,k):await k())?(l.push(w),b?.path&&!u.some(N=>N.path===b.path)&&u.push({path:b.path,projectDirectory:b.projectDirectory})):c.push(w)}catch{c.push(w)}const f=yt.getState();u.forEach(({path:w,projectDirectory:b})=>{f.currentDirectory===w&&f.setDirectory(b,{showOverlay:!1})});const p=new Set(l),h=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let y=null;s(w=>{const b=w.sessions.filter(N=>!p.has(N.id));w.currentSessionId&&p.has(w.currentSessionId)?y=null:y=w.currentSessionId;const v=new Map(w.worktreeMetadata);for(const N of p)v.delete(N);for(const N of d)v.delete(N);const j=new Set(u.map(N=>At(N.path)).filter(N=>!!N)),k=j.size>0?w.availableWorktrees.filter(N=>!j.has(At(N.path)??N.path)):w.availableWorktrees,x=new Map(w.availableWorktreesByProject);return u.length>0&&u.reduce((P,C)=>{const M=At(C.projectDirectory)??C.projectDirectory,S=At(C.path)??C.path;return P.has(M)||P.set(M,new Set),P.get(M)?.add(S),P},new Map).forEach((P,C)=>{const S=(x.get(C)??[]).filter(A=>!P.has(At(A.path)??A.path));x.set(C,S)}),{sessions:b,sessionsByDirectory:Ws(b),currentSessionId:y,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:k,availableWorktreesByProject:x}});const g=Ee.getDirectory()??null;return xr(g,y),{deletedIds:l,failedIds:c}},updateSessionTitle:async(t,n)=>{try{const o=gn(r().sessions,t),a=r().worktreeMetadata.get(t),l=()=>Ee.updateSession(t,n),c=a?.path??o,d=c?await Ee.withDirectory(c,l):await l();s(u=>{const m=u.sessions.map(f=>f.id===t?d:f);return{sessions:m,sessionsByDirectory:Ws(m)}})}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=gn(r().sessions,t),o=Ee.getApiClient(),l=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ee.getDirectory();return o.session.share({sessionID:t,...u?{directory:u}:{}})},d=l?await Ee.withDirectory(l,c):await c();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:Ws(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=gn(r().sessions,t),o=Ee.getApiClient(),l=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ee.getDirectory();return o.session.unshare({sessionID:t,...u?{directory:u}:{}})},d=l?await Ee.withDirectory(l,c):await c();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:Ws(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{s({currentSessionId:t,error:null});const n=Ee.getDirectory()??null;xr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:t=>{const n=At(t)??t,{sessionsByDirectory:o,sessions:a}=r(),l=o.get(n);return l||a.filter(c=>(At(c.directory??null)??n)===n)},getDirectoryForSession:t=>{if(!t)return null;const n=r().worktreeMetadata.get(t);if(n?.path)return At(n.path)??n.path;const o=r().sessions.find(l=>l.id===t);return At(o?.directory??null)},applySessionMetadata:(t,n)=>{!t||!n||s(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const l=o.sessions[a],c=n.time?{...l.time,...n.time}:l.time,d=n.summary===void 0?l.summary:n.summary||void 0,u=n.share===void 0?l.share:n.share||void 0,m={...l,...n,time:c,summary:d,share:u},f=m.title!==l.title||m.parentID!==l.parentID||m.directory!==l.directory||m.version!==l.version||m.projectID!==l.projectID||JSON.stringify(m.time)!==JSON.stringify(l.time)||JSON.stringify(m.summary??null)!==JSON.stringify(l.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(l.share??null),p=[...o.sessions];return p[a]=f?m:l,{sessions:p,sessionsByDirectory:Ws(p)}})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=r();return n.has(t)},markSessionAsOpenChamberCreated:t=>{s(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=r();n(t)},setWorktreeMetadata:(t,n)=>{t&&s(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return r().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=r().sessions,a=o.findIndex(u=>u.id===t);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(s(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:Ws(m)}}),c&&xr(c,null),n&&xr(n,t))},updateSession:t=>{s(n=>{const a=n.sessions.findIndex(c=>c.id===t.id)===-1?[t,...n.sessions]:n.sessions.map(c=>c.id===t.id?t:c),l=Dr(a);return{sessions:l,sessionsByDirectory:Ws(l)}})},removeSessionFromStore:t=>{t&&s(n=>{const o=n.sessions.find(u=>u.id===t),a=At(o?.directory??null),l=n.sessions.filter(u=>u.id!==t);if(l.length===n.sessions.length)return n;const c=new Map(n.worktreeMetadata);c.delete(t);const d=n.currentSessionId===t?null:n.currentSessionId;return a&&xr(a,null),{sessions:l,sessionsByDirectory:Ws(l),currentSessionId:d,worktreeMetadata:c}})}}),{name:"session-store",storage:Ts(()=>ps()),partialize:s=>({currentSessionId:s.currentSessionId,sessions:s.sessions,lastLoadedDirectory:s.lastLoadedDirectory,webUICreatedSessions:Array.from(s.webUICreatedSessions),worktreeMetadata:Array.from(s.worktreeMetadata.entries()),availableWorktrees:s.availableWorktrees,availableWorktreesByProject:Array.from(s.availableWorktreesByProject.entries())}),merge:(s,r)=>{if(!(p=>typeof p=="object"&&p!==null)(s))return r;const n=Array.isArray(s.sessions)?s.sessions:r.sessions,o=typeof s.currentSessionId=="string"||s.currentSessionId===null?s.currentSessionId:r.currentSessionId,a=Array.isArray(s.webUICreatedSessions)?s.webUICreatedSessions:[],l=Array.isArray(s.worktreeMetadata)?s.worktreeMetadata:[],c=Array.isArray(s.availableWorktrees)?s.availableWorktrees:r.availableWorktrees,d=Array.isArray(s.availableWorktreesByProject)?s.availableWorktreesByProject:[],u=new Map(d),m=typeof s.lastLoadedDirectory=="string"?s.lastLoadedDirectory:r.lastLoadedDirectory??null,f=Dr(n);return{...r,...s,sessions:f,sessionsByDirectory:Ws(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(l),availableWorktrees:c,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),Cm="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.",ay="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: ",ni=s=>typeof s=="string"&&s.trim()===Cm.trim(),oi=(s,r)=>{const t=Date.now(),n=s.get(r),o=new Map(s);return o.set(r,{phase:"streaming",startedAt:n?.startedAt??t,lastUpdateAt:t}),o},Wn=(s,r)=>{const t=Array.from(r);if(!t.some(a=>s.has(a)))return s;const o=new Map(s);return t.forEach(a=>{o.delete(a)}),o},Ac=new Map,Mm=s=>{const r=Ac.get(s);r&&(clearTimeout(r),Ac.delete(s))},Kr=s=>{for(const r of s)Mm(r)},co=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>co(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>co(r)).join("")}return""},Zn=s=>{if(!s)return"";const r=s;if(typeof r.text=="string")return r.text;if(Array.isArray(r.text))return r.text.map(n=>typeof n=="string"?n:Zn(n)).join("");const t=co(r.delta);return t||(typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||co(o.delta)||""}return""}).join(""):"")},Hn=(s,r)=>{const t={...s};if(t.type=t.type||"text",t.type==="text"){const n=r&&typeof r.text=="string"?r.text:"",o=typeof t.text=="string"?t.text:"",a=co(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},Ec=50*1024*1024,iy=s=>{const r=(s||"").toLowerCase();switch(r.includes(".")&&r.split(".").pop()||""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"bmp":return"image/bmp";case"ico":return"image/x-icon";case"pdf":return"application/pdf";default:return"text/plain"}},ly=s=>{if(s.type&&s.type.trim().length>0)return s.type;const r=(s.name||"").toLowerCase(),t=r.includes(".")&&r.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(r))return"text/plain";switch(t){case"md":case"markdown":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"sh":case"bash":case"zsh":return"text/plain";default:return"application/octet-stream"}},cy=s=>{const r=s.replace(/\s+/g,"");if(!r)return 0;const t=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(r.length*3/4)-t},dy=s=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<s.length;n+=3){const o=s[n]??0,a=s[n+1],l=s[n+2],c=o<<16|(a??0)<<8|(l??0);t+=r[c>>18&63],t+=r[c>>12&63],t+=typeof a=="number"?r[c>>6&63]:"=",t+=typeof l=="number"?r[c&63]:"="}return t},Ys=Kt()(ss(Ps((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(y=>y.filename===t.name&&y.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=Ec;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 50MB.`);const l=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],c=ly(t);!l.some(y=>c.startsWith(y)||c===y||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,m=await new Promise((y,g)=>{u.onload=()=>y(u.result),u.onerror=g,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${c}`):m,p=y=>{const g=y.replace(/\\/g,"/").split("/");return g[g.length-1]||y},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:f,mimeType:c,filename:p(t.name),size:t.size,source:"local"};s(y=>({attachedFiles:[...y.attachedFiles,h]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=r();if(a.some(b=>b.serverPath===t&&b.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,u;if(!c)try{const b=Ee.getApiClient(),v=t.lastIndexOf("/"),j=v>0?t.substring(0,v):"/",k=v>0?t.substring(v+1):t,x=await b.file.read({path:k,directory:j});x.data&&"content"in x.data?(c=x.data.content,d=x.data.encoding??void 0,u=x.data.mimeType??void 0):c=""}catch(b){console.error("Failed to read server file:",b),c=`[File: ${n}]`}const m=u||iy(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return dy(v)})(),h=d==="base64"?cy(p):new TextEncoder().encode(c||"").length;if(h>Ec)throw new Error(`File "${n}" is too large. Maximum size is 50MB.`);const y=new File([],n,{type:f}),g=`data:${f};base64,${p}`,w={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:y,dataUrl:g,mimeType:f,filename:n,size:h,source:"server",serverPath:t};s(b=>({attachedFiles:[...b.attachedFiles,w]}))},removeAttachedFile:t=>{s(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{s({attachedFiles:[]})}}),{name:"file-store",storage:Ts(()=>ps()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),uy=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),my=s=>s?uy.has(s.toLowerCase()):!1,fy=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},py=s=>{if(s)try{const r=fy();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},hy=(s,r)=>{if(!s||s.length===0)return"ask";for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission===r&&n.pattern==="*")return n.action}for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},Jo=s=>{const r=py(s);return r?hy(r.permission,"edit"):"ask"},Ic=s=>{if(!s||typeof s!="object")return 0;const r=s.input??0,t=s.output??0,n=s.reasoning??0,o=s.cache&&typeof s.cache=="object"?s.cache.read??0:0,a=s.cache&&typeof s.cache=="object"?s.cache.write??0:0;return r+t+n+o+a},ai=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return Ic(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:Ic(t.tokens)},ii=(s,r,t)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,l=Math.min(o?a:32e3,32e3),c=Math.min(l,n),d=n>0?Math.max(n-c,1):0,u=d>0?s/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},Un=["ask","allow","full"],gt=Kt()(ss(Ps((s,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{s(a=>{const l=new Map(a.sessionModelSelections);return l.set(t,{providerId:n,modelId:o}),{sessionModelSelections:l}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=r();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{s(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=r();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{s(l=>{const c=new Map(l.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(t);return a&&a.get(n)||null},saveAgentModelVariantForSession:(t,n,o,a,l)=>{s(c=>{const d=new Map(c.sessionAgentModelVariantSelections);let u=d.get(t);u?u=new Map(u):u=new Map;let m=u.get(n);m?m=new Map(m):m=new Map;const f=`${o}/${a}`;return l===void 0?(m.delete(f),m.size===0?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,m),d.set(t,u))):(m.set(f,l),u.set(n,m),d.set(t,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(t,n,o,a)=>{const{sessionAgentModelVariantSelections:l}=r(),c=l.get(t);if(!c)return;const d=c.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:l}=r(),c=new Map,d=(y,g)=>{if("mode"in y&&y.mode&&typeof y.mode=="string"&&n.find(j=>j.name===y.mode))return y.mode;if(y.providerID&&y.modelID){const v=n.find(j=>j.model?.providerID===y.providerID&&j.model?.modelID===y.modelID);if(v)return v.name}const{currentAgentContext:w}=r(),b=w.get(t);if(b&&n.find(v=>v.name===b))return b;if(g>0&&y.providerID&&y.modelID){const j=(o.get(t)||[]).filter(k=>k.info.role==="assistant").sort((k,x)=>k.info.time.created-x.info.time.created);for(let k=g-1;k>=0;k--){const N=j[k].info;if(N.providerID===y.providerID&&N.modelID===y.modelID){if(N.mode&&typeof N.mode=="string"&&n.find(M=>M.name===N.mode))return N.mode;const P=n.find(C=>C.model?.providerID===N.providerID&&C.model?.modelID===N.modelID);if(P)return P.name}}}return y.providerID&&y.modelID&&n.find(j=>j.name==="build")?"build":null},u=o.get(t)||[],m=u.filter(y=>y.info.role==="assistant"||y.info.role==="user").sort((y,g)=>y.info.time.created-g.info.time.created),f=u.filter(y=>y.info.role==="assistant").sort((y,g)=>y.info.time.created-g.info.time.created);let p,h;for(let y=0;y<m.length;y++){const g=m[y],{info:w}=g,b=w;if(b.role==="user"){p=typeof b.variant=="string"&&b.variant.trim().length>0?b.variant:void 0,h=b.model?.providerID&&b.model?.modelID?{providerID:b.model.providerID,modelID:b.model.modelID}:void 0;continue}if(b.providerID&&b.modelID){const v=d(b,f.indexOf(g));if(v&&n.find(j=>j.name===v)){p&&h&&h.providerID===b.providerID&&h.modelID===b.modelID&&l(t,v,b.providerID,b.modelID,p);const j={providerId:b.providerID,modelId:b.modelID,timestamp:w.time.created},k=c.get(v);(!k||j.timestamp>k.timestamp)&&c.set(v,j)}}p=void 0,h=void 0}for(const[y,g]of c)a(t,y,g.providerId,g.modelId);return c},getContextUsage:(t,n,o,a)=>{if(!t)return null;const l=ii(0,n,o),c=l.contextLimit,d=l.normalizedOutput??0,u=l.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(t)||[]).filter(j=>j.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,y=j=>{const k=()=>{s(x=>{const N=x.sessionContextUsage.get(t);if(N&&N.totalTokens===j.totalTokens&&N.percentage===j.percentage&&N.contextLimit===j.contextLimit&&(N.outputLimit??0)===(j.outputLimit??0)&&(N.normalizedOutput??0)===(j.normalizedOutput??0)&&N.thresholdLimit===j.thresholdLimit&&N.lastMessageId===j.lastMessageId)return x;const P=new Map(x.sessionContextUsage);return P.set(t,j),{sessionContextUsage:P}})};typeof queueMicrotask=="function"?queueMicrotask(k):typeof window<"u"?window.setTimeout(k,0):setTimeout(k,0)},g=r().sessionContextUsage.get(t);if(g&&g.lastMessageId===h){const j=g.normalizedOutput??g.outputLimit??0,k=g.contextLimit!==c||j!==d||g.thresholdLimit!==u;if(k&&g.totalTokens>0){const x=g.totalTokens/u*100,N={totalTokens:g.totalTokens,percentage:Math.min(x,100),contextLimit:c,outputLimit:l.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return y(N),N}if(!k&&g.totalTokens>0)return g}const w=ai(p);if(w===0)return g||null;const b=ii(w,n,o),v={totalTokens:w,percentage:b.percentage,contextLimit:b.contextLimit,outputLimit:b.outputLimit,normalizedOutput:b.normalizedOutput,thresholdLimit:b.thresholdLimit,lastMessageId:h};return y(v),v},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=ai(d);if(u===0)return;const m=ii(u,n,o);s(f=>{const p=new Map(f.sessionContextUsage);return p.set(t,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(t,n,o,a)=>{const c=r().sessionContextUsage.get(t);(!c||c.totalTokens===0)&&r().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let l=0;const c=()=>{l++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&ai(u)>0){r().updateSessionContextUsage(t,0,0,o);return}l<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=Jo(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Jo(n))=>{if(!t||!n)return;const l=a??"ask";l==="deny"||o==="deny"||Un.includes(o)&&s(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===l?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Jo(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const l=r().getSessionAgentEditMode(t,n,a),c=Un.indexOf(l),d=Un.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%Un.length,f=Un[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:Ts(()=>ps()),partialize:s=>({sessionModelSelections:Array.from(s.sessionModelSelections.entries()),sessionAgentSelections:Array.from(s.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(s.sessionAgentModelSelections.entries()).map(([r,t])=>[r,Array.from(t.entries())]),sessionAgentModelVariantSelections:Array.from(s.sessionAgentModelVariantSelections.entries()).map(([r,t])=>[r,Array.from(t.entries()).map(([n,o])=>[n,Array.from(o.entries())])]),currentAgentContext:Array.from(s.currentAgentContext.entries()),sessionContextUsage:Array.from(s.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(s.sessionAgentEditModes.entries()).map(([r,t])=>[r,Array.from(t.entries())])}),merge:(s,r)=>{const t=new Map;s?.sessionAgentModelSelections&&s.sessionAgentModelSelections.forEach(([a,l])=>{t.set(a,new Map(l))});const n=new Map;s?.sessionAgentModelVariantSelections&&s.sessionAgentModelVariantSelections.forEach(([a,l])=>{const c=new Map;l.forEach(([d,u])=>{c.set(d,new Map(u))}),n.set(a,c)});const o=new Map;return s?.sessionAgentEditModes&&s.sessionAgentEditModes.forEach(([a,l])=>{o.set(a,new Map(l))}),{...r,...s,sessionModelSelections:new Map(s?.sessionModelSelections||[]),sessionAgentSelections:new Map(s?.sessionAgentSelections||[]),sessionAgentModelSelections:t,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(s?.currentAgentContext||[]),sessionContextUsage:new Map(s?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),Pc=(s,r)=>{const t=new Map(s);return t.delete(r),t};let li=[],ci=null;const gy=50,xy=3e4,Qr=new Map,Co=new Map,xn=new Map,yy=10,ma=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.indexOf("_"),n=t>=0?r.slice(t+1):r;return!n||n.length<yy?null:n},Mo=(s,r)=>{const t=ma(s),n=ma(r);return!t||!n||t.length!==n.length?!0:t>n},by=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},jn=s=>!Array.isArray(s)||s.length===0?0:s.reduce((r,t)=>{if(!t||t.type!=="text")return r;const n=t.text??t.content;return typeof n=="string"?r+n.length:r},0),fa=s=>s?.finish==="stop",Tc=s=>{if(s){if(typeof s.id=="string"&&s.id.length>0)return s.id;if(s.type){const r=s.reason,t=s.callID;return`${s.type}-${r??""}-${t??""}`}}},Fc=new Set,pa=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(Tc).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=Tc(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},vy=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=jn(t),a=jn(n),l=fa(s.info),c=fa(r.info);let d=n;return l&&o>=a?d=pa(t,n):c&&a>=o?d=pa(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},Do=s=>{const r=[],t=new Map;for(const n of s){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){r.push(n);continue}const a=t.get(o);if(a===void 0){t.set(o,r.length),r.push(n);continue}r[a]=vy(r[a],n)}return r},wy=(s,r)=>{let t=r,n=r?ma(r):null;for(const o of s){const a=o?.info?.id,l=ma(a);!a||!l||(!n||l>n)&&(n=l,t=a)}return t},nr=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return t?o.set(r,t):o.delete(r),o},yn=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},Ao=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},jy=(s,r)=>{const t=new Set,n=s.streamingMessageIds.get(r);return n&&t.add(n),s.messageStreamStates.forEach((o,a)=>{s.messageSessionIndex.get(a)===r&&t.add(a)}),t},Rc=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),Sy=async s=>{if(s)try{return pt.getState().getDirectoryForSession(s)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},Oc=s=>{if(!s)return null;try{return pt.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},_c=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},di=async(s,r)=>{const t=await Sy(s);return t?Ee.withDirectory(t,r):r()},Mt=Kt()(ss(Ps((s,r)=>({messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,pendingAssistantHeaderSessions:new Set,pendingUserMessageMetaBySession:new Map,loadMessages:async(t,n=fs.HISTORICAL_MESSAGES)=>{const o=r().sessionMemoryState.get(t)?.isStreaming,a=o?fs.VIEWPORT_MESSAGES:n,l=o?void 0:a+fs.FETCH_BUFFER,c=await di(t,()=>Ee.getSessionMessages(t,l)),d=Oc(t),u=_c(c,d),m=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,p=(m?u.filter(h=>{const y=h?.info?.id;return y?Mo(y,m):!0}):u).slice(-a);s(h=>{const y=new Map(h.messages),g=h.messages.get(t)||[],w=new Map(g.filter(D=>typeof D.info?.id=="string").map(D=>[D.info.id,D])),b=p.map(D=>{const F={...D.info,clientRole:D.info?.clientRole??D.info.role,userMessageMarker:D.info.role==="user"?!0:D.info?.userMessageMarker},E=(Array.isArray(D.parts)?D.parts:[]).map(_=>{if(_?.type==="text"){const V=_.text??_.content??"";if(ni(V))return{..._,synthetic:!0}}return _}),I=F?.id?w.get(F.id):void 0;if(I&&I.info.role==="assistant"){const _=Array.isArray(I.parts)?I.parts:[],V=jn(_),Y=jn(E);if(fa(I.info)&&V>Y){const L=pa(_,E);return{...D,info:F,parts:L}}}return{...D,info:F,parts:E}}),v=Do(b),j=new Set(g.map(D=>D.info.id)),k=new Set(v.map(D=>D.info.id)),x=[];j.forEach(D=>{k.has(D)||x.push(D)}),y.set(t,v);const N=new Map(h.sessionMemoryState),P=h.sessionMemoryState.get(t);N.set(t,{...P,viewportAnchor:v.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:c.length,hasMoreAbove:c.length>p.length,trimmedHeadMaxId:P?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const C={messages:y,sessionMemoryState:N};Kr(x);const M=Wn(h.messageStreamStates,x);if(M!==h.messageStreamStates&&(C.messageStreamStates=M),x.length>0){const D=h.streamingMessageIds.get(t);D&&x.includes(D)&&(C.streamingMessageIds=nr(C.streamingMessageIds??h.streamingMessageIds,t,null))}if(x.length>0){const D=Ao(C.messageSessionIndex??h.messageSessionIndex,x);D!==(C.messageSessionIndex??h.messageSessionIndex)&&(C.messageSessionIndex=D)}if(x.length>0){const D=new Map(h.pendingAssistantParts);let F=!1;x.forEach(E=>{D.delete(E)&&(F=!0)}),F&&(C.pendingAssistantParts=D)}const S=C.messageSessionIndex??h.messageSessionIndex;let A=S;return v.forEach(D=>{const F=D?.info?.id;typeof F=="string"&&F.length>0&&(A=yn(A,F,t))}),A!==S&&(C.messageSessionIndex=A),C})},sendMessage:async(t,n,o,a,l,c,d,u,m)=>{if(!l)throw new Error("No session selected");const f=l;r().sessionAbortFlags.has(f)&&s(p=>{const h=new Map(p.sessionAbortFlags);return h.delete(f),{sessionAbortFlags:h}}),await di(f,async()=>{try{let p=t;if(t.startsWith("/")){const y=t.indexOf(" "),g=y===-1?t.substring(1):t.substring(1,y),w=y===-1?"":t.substring(y+1).trim(),b=Ee.getApiClient(),v=Ee.getDirectory();if(g==="init"){const j=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await b.session.init({sessionID:f,...v?{directory:v}:{},messageID:j,providerID:n,modelID:o});return}if(g==="summarize"){await b.session.summarize({sessionID:f,...v?{directory:v}:{},providerID:n,modelID:o});return}try{const j=await Ee.getCommandDetails(g);j?.template?p=j.template.replace(/\$ARGUMENTS/g,w):p=t}catch(j){console.error("Command template resolution failed:",j),p=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(y=>{const g=y.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},w=xn.get(f);w&&(clearTimeout(w),xn.delete(f));const b=new Map(y.sessionMemoryState);return b.set(f,{...g,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:b}});try{const y=new AbortController;s(b=>{const v=new Map(b.abortControllers);return v.set(f,y),{abortControllers:v}});const g=(c??[]).map(b=>({type:"file",mime:b.mimeType,filename:b.filename,url:b.dataUrl}));s(b=>{const v=new Set(b.pendingAssistantHeaderSessions);v.add(f);const j=new Map(b.pendingUserMessageMetaBySession);return j.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:j}});const w=u?.map(b=>({text:b.text,files:b.attachments?.map(v=>({type:"file",mime:v.mimeType,filename:v.filename,url:v.dataUrl}))}));if(await Ee.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:g.length>0?g:void 0,additionalParts:w,agentMentions:d?[{name:d}]:void 0}),g.length>0)try{Ys.getState().clearAttachedFiles()}catch(b){console.error("Failed to clear attached files after send",b)}s(b=>{const v=new Map(b.abortControllers);return v.delete(f),{abortControllers:v}})}catch(y){let g="Network error while sending message. The message may still be processing.";if(y.name==="AbortError")g="Request timed out. The message may still be processing.";else if(y.message?.includes("504")||y.message?.includes("Gateway")){g="Gateway timeout - your message is being processed. Please wait for response.",s(w=>{const b=new Map(w.abortControllers);return b.delete(f),{abortControllers:b}});return}else y.message&&(g=y.message);throw s(w=>{const b=new Map(w.abortControllers);b.delete(f);const v=new Set(w.pendingAssistantHeaderSessions);v.delete(f);const j=new Map(w.pendingUserMessageMetaBySession);return j.delete(f),{abortControllers:b,pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:j}}),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),s(y=>{const g=new Map(y.abortControllers);g.delete(f);const w=new Set(y.pendingAssistantHeaderSessions);w.delete(f);const b=new Map(y.pendingUserMessageMetaBySession);return b.delete(f),{abortControllers:g,pendingAssistantHeaderSessions:w,pendingUserMessageMetaBySession:b}}),new Error(h)}})},abortCurrentOperation:async t=>{if(!t)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=jy(n,t);if(c.size===0){const u=t?a.get(t)??[]:[];let m=null;for(let f=u.length-1;f>=0;f-=1){const p=u[f];if(!p||p.info.role!=="assistant")continue;if(m||(m=p.info.id),(p.parts??[]).some(y=>y.type==="reasoning"||y.type==="tool"||y.type==="step-start")){c.add(p.info.id);break}}c.size===0&&m&&c.add(m)}for(const u of c){const m=Qr.get(u);m&&(clearTimeout(m),Qr.delete(u),Co.delete(u))}c.size>0&&Kr(c);const d=Date.now();s(u=>{const m=Wn(u.messageStreamStates,c),f=u.messages.get(t)??[];let p=!1,h=u.messages;if(f.length>0&&c.size>0){const b=f.map(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const j=(v.parts??[]).map(k=>{if(k.type==="reasoning"){const x=k,N={...x.time??{}};return typeof N.end!="number"&&(N.end=d),{...x,time:N}}if(k.type==="tool"){const x=k,N={...x.state??{}};return(N.status==="running"||N.status==="pending")&&(N.status="aborted"),{...x,state:N}}return k.type==="step-start"?{...k,type:"step-finish",aborted:!0}:k});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:j}});p&&(h=new Map(u.messages),h.set(t,b))}const y=u.sessionMemoryState.get(t);let g=u.sessionMemoryState;if(y){const b=new Map(u.sessionMemoryState);b.set(t,{...y,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),g=b}const w=new Map(u.sessionAbortFlags);return w.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:g,sessionAbortFlags:w,abortControllers:(()=>{const b=new Map(u.abortControllers);return b.delete(t),b})(),streamingMessageIds:nr(u.streamingMessageIds,t,null),...p?{messages:h}:{}}}),Ee.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,l)=>{const c=r();if(Fc.has(n))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!Mo(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.messages.get(t)||[],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(t);if(p?.streamStartTime&&Date.now()-p.streamStartTime>fs.ZOMBIE_TIMEOUT){p.isZombie||s(y=>{const g=new Map(y.sessionMemoryState);return g.set(t,{...p,isZombie:!0}),{sessionMemoryState:g}}),setTimeout(()=>{r().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}s(h=>{const g=[...h.messages.get(t)||[]],w={},b=yn(h.messageSessionIndex,n,t);b!==h.messageSessionIndex&&(w.messageSessionIndex=b);const v=M=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(t)))return M;const A=new Map(h.sessionAbortFlags);return A.delete(t),{...M,sessionAbortFlags:A}},j=M=>{const S=M||"",A=Co.get(n);if(S&&A===S){const E=r();if(Rc(E,t,n)){const I=Qr.get(n);I&&(clearTimeout(I),Qr.delete(n)),setTimeout(()=>{const _=r();typeof _.forceCompleteMessage=="function"&&_.forceCompleteMessage(t,n,"timeout"),_.completeStreamingMessage(t,n)},100)}}Co.set(n,S);const D=Qr.get(n);D&&clearTimeout(D);const F=setTimeout(()=>{const E=r();typeof E.forceCompleteMessage=="function"&&E.forceCompleteMessage(t,n,"timeout"),Rc(E,t,n)&&E.completeStreamingMessage(t,n),Qr.delete(n),Co.delete(n)},8e3);Qr.set(n,F)},k=t!==l,x=h.sessionMemoryState.get(t);if(k&&x?.isStreaming){g.length>=fs.BACKGROUND_STREAMING_BUFFER&&g.shift();const M=new Map(h.sessionMemoryState);M.set(t,{...x,backgroundMessageCount:(x.backgroundMessageCount||0)+1}),h.sessionMemoryState=M}if(f==="assistant"){const M=h.sessionMemoryState.get(t);if(M){const S=Date.now(),A=new Map(h.sessionMemoryState);A.set(t,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??S,lastAccessedAt:S,isZombie:!1}),h.sessionMemoryState=A}}const N=Zn(o);if(ni(N)&&(o.synthetic=!0),by()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:N.length,snapshotParts:u.length})}catch{}const P=w.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=nr(P,t,n);M!==P&&(w.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const C=g.findIndex(M=>M.info.id===n);if(C!==-1&&f==="user"){const M=g[C],S=M.parts.findIndex(I=>I.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const A=Hn(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`user_part_type:${A.type||"unknown"}`);const D={...M};S!==-1?D.parts=D.parts.map((I,_)=>_===S?A:I):D.parts=[...D.parts,A];const F=[...g];F[C]=D;const E=new Map(h.messages);return E.set(t,F),v({messages:E})}if(f==="assistant"&&C!==-1){const M=g[C],S=M.parts.findIndex(_=>_.id===o.id),A=Hn(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const D={...M};S!==-1?D.parts=D.parts.map((_,V)=>V===S?A:_):D.parts=[...D.parts,A];const F=[...g];F[C]=D;const E=new Map(h.messages);E.set(t,F),w.messageStreamStates=oi(h.messageStreamStates,n);const I=nr(w.streamingMessageIds??h.streamingMessageIds,t,n);return I!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=I,window.__messageTracker?.(n,"streamingId_set")),A.type==="text"?j(A.text||""):j(""),v({messages:E,...w})}if(C===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const X=Hn(o);window.__messageTracker?.(n,`new_user_part_type:${X.type||"unknown"}`);const ae=h.pendingUserMessageMetaBySession.get(t),O=gt.getState(),z=ae?.mode??O.getSessionAgentSelection(t)??O.getCurrentAgent(t),T=typeof z=="string"&&z.trim().length>0?z.trim():void 0,$=ae?.providerID??(h.lastUsedProvider?.providerID||void 0),W=ae?.modelID??(h.lastUsedProvider?.modelID||void 0);ae&&(w.pendingUserMessageMetaBySession=Pc(h.pendingUserMessageMetaBySession,t));const q={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...T?{mode:T}:{},...$?{providerID:$}:{},...W?{modelID:W}:{},time:{created:Date.now()}},parts:[X]},ue=[...g,q];ue.sort((de,je)=>{const Se=de.info?.time?.created||0,Le=je.info?.time?.created||0;return Se-Le});const oe=new Map(h.messages);return oe.set(t,ue),v({messages:oe})}if(o?.type==="text"){const X=Zn(o).trim();if(X.length>0){const ae=[...g].reverse().find(O=>O.info.role==="user");if(ae){const O=ae.parts.map(z=>Zn(z)).join("").trim();if(O.length>0&&O===X)return Fc.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=Hn(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?j(M.text||""):j("");const S=h.pendingAssistantParts.get(n),A=S?[...S.parts]:[],D=A.findIndex(X=>X.id===M.id);D!==-1?A[D]=M:A.push(M);const F=new Map(h.pendingAssistantParts);F.set(n,{sessionId:t,parts:A});const E=h.lastUsedProvider?.providerID||"",I=h.lastUsedProvider?.modelID||"",_=Date.now(),V=Ee.getDirectory()??"/",Y=gt.getState(),H=Y.getSessionAgentSelection(t)??Y.getCurrentAgent(t),L=typeof H=="string"&&H.trim().length>0?H.trim():void 0,U=h.pendingAssistantHeaderSessions.has(t);if(U){const X=new Set(h.pendingAssistantHeaderSessions);X.delete(t),w.pendingAssistantHeaderSessions=X}const J={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:_},agent:L||"default",model:{providerID:E,modelID:I},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:_},parentID:n,modelID:I,providerID:E,mode:L||"default",...U?{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:A},K=[...g,J],ne=new Map(h.messages);if(ne.set(t,K),f==="assistant"){w.messageStreamStates=oi(h.messageStreamStates,n);const X=nr(w.streamingMessageIds??h.streamingMessageIds,t,n);X!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=X,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:ne,pendingAssistantParts:F,...w})}else{const M=g[C],S=M.parts.findIndex(I=>I.id===o.id),A=Hn(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const D={...M};S!==-1?D.parts=D.parts.map((I,_)=>_===S?A:I):D.parts=[...D.parts,A];const F=[...g];F[C]=D;const E=new Map(h.messages);if(E.set(t,F),D.info.role==="assistant"){w.messageStreamStates=oi(h.messageStreamStates,n);const I=nr(w.streamingMessageIds??h.streamingMessageIds,t,n);I!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=I,window.__messageTracker?.(n,"streamingId_set"))}return A.type==="text"?j(A.text||""):j(""),v({messages:E,...w})}})},addStreamingPart:(t,n,o,a,l)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,l);return}li.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:l}),ci||(ci=setTimeout(()=>{const c=[...li];li=[],ci=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},gy))},forceCompleteMessage:(t,n,o="timeout")=>{const a=l=>{if(t)return t;for(const[c,d]of l.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};s(l=>{const c=a(l);if(!c)return l;const d=l.messages.get(c)??[],u=d.findIndex(x=>x.info.id===n);if(u===-1)return l;const m=d[u];if(!m)return l;const f=Date.now(),p=m.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let y=!1;const g={...p};h||(g.time={...p.time??{},completed:f},y=!0),g.status!=="completed"&&(g.status="completed",y=!0),g.streaming&&(g.streaming=!1,y=!0);let w=!1;const b=m.parts.map(x=>{if(!x)return x;if(x.type==="tool"){const N=x.state;if(!N)return x;const P=N.status,C=P==="running"||P==="pending"||P==="started",M=!N.time||typeof N.time?.end!="number";if(C||M){const S={...N};return C&&(S.status="completed"),M&&(S.time={...N.time??{},end:f}),w=!0,{...x,state:S}}return x}if(x.type==="reasoning"){const N=x.time;return!N||typeof N.end!="number"?(w=!0,{...x,time:{...N??{},end:f}}):x}if(x.type==="text"){const N=x.time;return N&&typeof N.end!="number"?(w=!0,{...x,time:{...N,end:f}}):x}return x});if(!y&&!w)return l;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:g,parts:w?b:m.parts},j=[...d];j[u]=v;const k=new Map(l.messages);return k.set(c,j),{messages:k}})},markMessageStreamSettled:t=>{s(n=>{Mm(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,l=!1;return n.messages.forEach((d,u)=>{if(l)return;const m=d.findIndex(g=>g.info.id===t);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 y=new Map(n.messages);y.set(u,h),a=y,l=!0}),{messageStreamStates:o,...l?{messages:a}:{}}}),Kr([t])},updateMessageInfo:(t,n,o)=>{s(c=>{const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!Mo(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(t)??[]],f=m.findIndex(C=>C.info.id===n),p=c.pendingAssistantParts.get(n),h=(C=[],M=[])=>{if(!M.length)return C;const S=[...C];return M.forEach(A=>{const D=S.findIndex(F=>F.id===A.id);D===-1?S.push(A):S[D]=A}),S},y=C=>{if(!C)return C;const M=C.clientRole??C.role,S=M==="user"?!0:C.userMessageMarker;return{...C,clientRole:M,...S?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:t,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const V=m[0]?.info,Y=typeof V?.time?.created=="number"?V.time.created:null,H=typeof V?.id=="string"?V.id:null,L=o,U=typeof L?.time?.created=="number"?L.time.created:null,Q=typeof L?.id=="string"?L.id:n;let J=!1;if(U!==null&&Y!==null&&(J=U<Y),!J&&Q&&H&&(J=Q.localeCompare(H)<0),J)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const C=y(o);if(C&&C.role==="user"){const _=p?.parts??[],V=c.pendingUserMessageMetaBySession.get(t),Y={info:{...C,userMessageMarker:!0,clientRole:"user",...V?.mode?{mode:V.mode}:{},...V?.providerID?{providerID:V.providerID}:{},...V?.modelID?{modelID:V.modelID}:{}},parts:_.length>0?[..._]:[]},H=new Map(c.messages),L=[...m,Y];L.sort((J,K)=>{const ne=J.info?.time?.created||0,X=K.info?.time?.created||0;return ne-X}),H.set(t,L);const U={messages:H,...V?{pendingUserMessageMetaBySession:Pc(c.pendingUserMessageMetaBySession,t)}:{}},Q=yn(U.messageSessionIndex??c.messageSessionIndex,n,t);if(Q!==(U.messageSessionIndex??c.messageSessionIndex)&&(U.messageSessionIndex=Q),p){const J=new Map(c.pendingAssistantParts);J.delete(n),U.pendingAssistantParts=J}return U}if(!C||C.role!=="assistant")return c;const M=p?.parts??[],S=c.pendingAssistantHeaderSessions.has(t),A={info:{...C,animationSettled:C?.animationSettled??!1,...S?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},D=new Map(c.messages),F=[...m,A];D.set(t,F);const E={messages:D,...S?{pendingAssistantHeaderSessions:(()=>{const _=new Set(c.pendingAssistantHeaderSessions);return _.delete(t),_})()}:{}},I=yn(E.messageSessionIndex??c.messageSessionIndex,n,t);if(I!==(E.messageSessionIndex??c.messageSessionIndex)&&(E.messageSessionIndex=I),p){const _=new Map(c.pendingAssistantParts);_.delete(n),E.pendingAssistantParts=_}return E}const g=m[f],w=g.info;if(w.userMessageMarker===!0||w.clientRole==="user"||w.role==="user"){const C={...g.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:w.providerID||void 0,modelID:w.modelID||void 0},M=c.pendingUserMessageMetaBySession.get(t);M&&!C.mode&&M.mode&&(C.mode=M.mode);const S={...g,info:C},A=new Map(c.messages),D=[...m];if(D[f]=S,A.set(t,D),M){const F=new Map(c.pendingUserMessageMetaBySession);return F.delete(t),{messages:A,pendingUserMessageMetaBySession:F}}return{messages:A}}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 j=p?.parts?h(g.parts,p.parts):g.parts,k={...g,info:v,parts:j},x=new Map(c.messages),N=[...m];N[f]=k,x.set(t,N);const P={messages:x};if(p){const C=new Map(c.pendingAssistantParts);C.delete(n),P.pendingAssistantParts=C}return P});const a=o?.finish,l=o?.role;typeof a=="string"&&l!=="user"&&setTimeout(()=>{r().completeStreamingMessage(t,n)},0)},completeStreamingMessage:(t,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const l={};if(a&&(l.streamingMessageIds=nr(o.streamingMessageIds,t,null),l.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),l.messageStreamStates=d}Object.keys(l).length>0&&s(l),o.pendingAssistantParts.has(n)&&s(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),Kr([n]);let c=!1;if(s(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const m=new Map(d.sessionMemoryState),f=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return m.set(t,p),c=!0,{sessionMemoryState:m}}),c){const d=xn.get(t);d&&(clearTimeout(d),xn.delete(t));const u=setTimeout(()=>{s(m=>{const f=m.sessionMemoryState.get(t);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:h,...y}=f;return p.set(t,y),{sessionMemoryState:p}}),xn.delete(t)},2e3);xn.set(t,u)}},syncMessages:(t,n)=>{const o=Oc(t),a=_c(n,o),l=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=l?a.filter(d=>{const u=d?.info?.id;return u?Mo(u,l):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(x=>typeof x.info?.id=="string").map(x=>[x.info.id,x])),p=c.map(x=>{const N={...x.info,clientRole:x.info?.clientRole??x.info.role,userMessageMarker:x.info.role==="user"?!0:x.info?.userMessageMarker,animationSettled:x.info.role==="assistant"?x.info?.animationSettled??!0:x.info?.animationSettled},P=(Array.isArray(x.parts)?x.parts:[]).map(S=>{if(S?.type==="text"){const A=S.text??S.content??"";if(ni(A))return{...S,synthetic:!0}}return S}),C=typeof N?.id=="string"?N.id:void 0,M=C?f.get(C):void 0;if(M&&M.info.role==="assistant"){const S=Array.isArray(M.parts)?M.parts:[],A=jn(S),D=jn(P);if(fa(M.info)&&A>D){const E=pa(S,P);return{...x,info:N,parts:E}}}return{...x,info:N,parts:P}}),h=Do(p),y=new Set(m.map(x=>x.info.id)),g=new Set(h.map(x=>x.info.id)),w=[];y.forEach(x=>{g.has(x)||w.push(x)}),u.set(t,h);const b={messages:u,isSyncing:!0};Kr(w);const v=Wn(d.messageStreamStates,w);if(v!==d.messageStreamStates&&(b.messageStreamStates=v),w.length>0){const x=d.streamingMessageIds.get(t);x&&w.includes(x)&&(b.streamingMessageIds=nr(b.streamingMessageIds??d.streamingMessageIds,t,null))}if(w.length>0){const x=Ao(b.messageSessionIndex??d.messageSessionIndex,w);x!==(b.messageSessionIndex??d.messageSessionIndex)&&(b.messageSessionIndex=x)}if(w.length>0){const x=new Map(d.pendingAssistantParts);let N=!1;w.forEach(P=>{x.delete(P)&&(N=!0)}),N&&(b.pendingAssistantParts=x)}const j=b.messageSessionIndex??d.messageSessionIndex;let k=j;return h.forEach(x=>{const N=x?.info?.id;typeof N=="string"&&N.length>0&&(k=yn(k,N,t))}),k!==j&&(b.messageSessionIndex=k),b}),setTimeout(()=>{s({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{s(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const l=n+xy;return a.get(t)===l?o:(a.set(t,l),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&s(n=>{const o=n.sessionAbortFlags.get(t);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,n)=>{s(o=>{const a=o.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(o.sessionMemoryState);return l.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:l}})},updateActiveTurnAnchor:(t,n,o)=>{s(a=>{const l=a.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},c=new Map(a.sessionMemoryState);return c.set(t,{...l,activeTurnAnchorId:n??void 0,activeTurnSpacerHeight:o}),{sessionMemoryState:c}})},getActiveTurnAnchor:t=>{const n=r().sessionMemoryState.get(t);return n?{anchorId:n.activeTurnAnchorId??null,spacerHeight:n.activeTurnSpacerHeight??0}:null},trimToViewportWindow:(t,n=fs.VIEWPORT_MESSAGES,o)=>{const a=r(),l=a.messages.get(t);if(!l||l.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:l.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.viewportAnchor||l.length-1;let u=Math.max(0,d-Math.floor(n/2));const m=Math.min(l.length,u+n);m===l.length&&m-u<n&&(u=Math.max(0,m-n));const f=l.slice(u,m),p=l.slice(0,u),h=new Set(f.map(g=>g.info.id)),y=l.filter(g=>!h.has(g.info.id)).map(g=>g.info.id);s(g=>{const w=new Map(g.messages);w.set(t,f);const b=new Map(g.sessionMemoryState),v={...c,viewportAnchor:d-u,trimmedHeadMaxId:wy(p,c.trimmedHeadMaxId)};b.set(t,v);const j={messages:w,sessionMemoryState:b};Kr(y);const k=Wn(g.messageStreamStates,y);if(k!==g.messageStreamStates&&(j.messageStreamStates=k),y.length>0){const P=g.streamingMessageIds.get(t);P&&y.includes(P)&&(j.streamingMessageIds=nr(j.streamingMessageIds??g.streamingMessageIds,t,null))}if(y.length>0){const P=Ao(j.messageSessionIndex??g.messageSessionIndex,y);P!==(j.messageSessionIndex??g.messageSessionIndex)&&(j.messageSessionIndex=P)}const x=j.messageSessionIndex??g.messageSessionIndex;let N=x;return f.forEach(P=>{const C=P?.info?.id;typeof C=="string"&&C.length>0&&(N=yn(N,C,t))}),N!==x&&(j.messageSessionIndex=N),j})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=fs.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const l=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(l.length===0)return;l.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=l[0][0];s(d=>{const m=(d.messages.get(c)||[]).map(k=>k.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c),p.delete(c);const h={messages:f,sessionMemoryState:p},y=new Map(d.pendingAssistantParts);let g=!1;y.forEach((k,x)=>{k.sessionId===c&&(y.delete(x),g=!0)}),g&&(h.pendingAssistantParts=y);const w=new Map(d.sessionCompactionUntil);w.delete(c)&&(h.sessionCompactionUntil=w),Kr(m);const b=Wn(d.messageStreamStates,m);b!==d.messageStreamStates&&(h.messageStreamStates=b);const v=Ao(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const j=nr(d.streamingMessageIds,c,null);if(j!==d.streamingMessageIds&&(h.streamingMessageIds=j),d.abortControllers.has(c)){const k=new Map(d.abortControllers);k.delete(c),h.abortControllers=k}return h})},loadMoreMessages:async(t,n="up")=>{const o=r(),a=o.messages.get(t),l=o.sessionMemoryState.get(t);if(!a||!l||l.totalAvailableMessages&&a.length>=l.totalAvailableMessages)return;const c=await di(t,()=>Ee.getSessionMessages(t));if(n==="up"&&a.length>0){const d=Do(c),u=a[0],m=d.findIndex(f=>f.info.id===u.info.id);if(m>0){const f=Math.min(fs.VIEWPORT_MESSAGES,m),p=d.slice(m-f,m);s(h=>{const y=[...p,...a],g=Do(y),w=Math.max(0,g.length-a.length),b=new Map(h.messages);b.set(t,g);const v=new Map(h.sessionMemoryState);return v.set(t,{...l,viewportAnchor:l.viewportAnchor+w,hasMoreAbove:m-f>0,totalAvailableMessages:d.length}),{messages:b,sessionMemoryState:v}})}else m===0&&s(f=>{const p=new Map(f.sessionMemoryState);return p.set(t,{...l,hasMoreAbove:!1,totalAvailableMessages:d.length}),{sessionMemoryState:p}})}},getLastMessageModel:t=>{const{messages:n}=r(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const l=o[a];if(l.info.role==="assistant"&&"providerID"in l.info&&"modelID"in l.info)return{providerID:l.info.providerID,modelID:l.info.modelID}}return null}}),{name:"message-store",storage:Ts(()=>ps()),partialize:s=>({lastUsedProvider:s.lastUsedProvider,sessionMemoryState:Array.from(s.sessionMemoryState.entries()).map(([r,t])=>[r,{viewportAnchor:t.viewportAnchor,isStreaming:t.isStreaming,lastAccessedAt:t.lastAccessedAt,backgroundMessageCount:t.backgroundMessageCount,totalAvailableMessages:t.totalAvailableMessages,hasMoreAbove:t.hasMoreAbove,trimmedHeadMaxId:t.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(s.sessionAbortFlags.entries()).map(([r,t])=>[r,{timestamp:t.timestamp,acknowledged:t.acknowledged}])}),merge:(s,r)=>{if(!s)return r;let t=r.sessionMemoryState;Array.isArray(s.sessionMemoryState)&&(t=new Map(s.sessionMemoryState.map(o=>o)));let n=r.sessionAbortFlags;return Array.isArray(s.sessionAbortFlags)&&(n=new Map(s.sessionAbortFlags)),{...r,lastUsedProvider:s.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:t,sessionAbortFlags:n}}}),{name:"message-store"})),ky=s=>typeof s=="object"&&s!==null,Ny=s=>{if(!Array.isArray(s))return[];const r=[];return s.forEach(t=>{if(!Array.isArray(t)||t.length!==2)return;const[n,o]=t;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},Cy=async(s,r)=>{try{const n=pt.getState().getDirectoryForSession(s);if(n)return Ee.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},uo=Kt()(ss(Ps((s,r)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===t.id))return;const l=t.permission?.toLowerCase?.()??null;let c=n?.currentAgentContext?.get(o);if(c||(c=n?.sessionAgentSelections?.get(o)??void 0),!c&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(c=f.getState().currentAgentName??void 0)}const d=Jo(c),u=n?.getSessionAgentEditMode?.(o,c)??d;if(u==="full"||u==="allow"&&my(l)){r().respondToPermission(o,t.id,"once").catch(()=>{});return}s(f=>{const p=f.permissions.get(o)||[],h=new Map(f.permissions);return h.set(o,[...p,t]),{permissions:h}})},respondToPermission:async(t,n,o)=>{await Cy(t,()=>Ee.replyToPermission(n,o)),o==="reject"&&await Mt.getState().abortCurrentOperation(t),s(a=>{const c=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:Ts(()=>ps()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!ky(s))return r;const t=Ny(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),My=s=>typeof s=="object"&&s!==null,Dy=s=>{if(!Array.isArray(s))return[];const r=[];return s.forEach(t=>{if(!Array.isArray(t)||t.length!==2)return;const[n,o]=t;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},$c=async(s,r)=>{try{const n=pt.getState().getDirectoryForSession(s);if(n)return Ee.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for question handling:",t)}return r()},Sn=Kt()(ss(Ps((s,r)=>({questions:new Map,addQuestion:t=>{const n=t.sessionID;!n||r().questions.get(n)?.some(a=>a.id===t.id)||s(a=>{const l=a.questions.get(n)||[],c=new Map(a.questions);return c.set(n,[...l,t]),{questions:c}})},dismissQuestion:(t,n)=>{!t||!n||s(o=>{const l=(o.questions.get(t)||[]).filter(d=>d.id!==n),c=new Map(o.questions);return c.set(t,l),{questions:c}})},respondToQuestion:async(t,n,o)=>{await $c(t,()=>Ee.replyToQuestion(n,o)),r().dismissQuestion(t,n)},rejectQuestion:async(t,n)=>{await $c(t,()=>Ee.rejectQuestion(n)),r().dismissQuestion(t,n)}}),{name:"question-store",storage:Ts(()=>ps()),partialize:s=>({questions:Array.from(s.questions.entries())}),merge:(s,r)=>{if(!My(s))return r;const t=Dy(s.questions);return{...r,questions:new Map(t)}}}),{name:"question-store"})),Nl=s=>s.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
9
+ `).replace(/\n\s*\n+/g,`
10
+ `),eo=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},Lc=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return eo(n);const o=s.find(a=>a.id===r);return o?eo(o.directory??null):null},he=Kt()(ss((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,questions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,pendingInputText:null,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},getSessionAgentEditMode:(t,n,o)=>gt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>gt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>gt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>pt.getState().loadSessions(),openNewSessionDraft:t=>{let n=null;t?.directoryOverride!==void 0?n=t.directoryOverride:n=Lt.getState().getActiveProject()?.path??null,s({newSessionDraft:{open:!0,directoryOverride:n,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const o=nt.getState(),a=o.getVisibleAgents();let l;if(o.settingsDefaultAgent){const c=a.find(d=>d.name===o.settingsDefaultAgent);c&&(l=c.name)}l||(l=a.find(c=>c.name==="build")?.name||a[0]?.name),l&&o.setAgent(l)}catch{}},closeNewSessionDraft:()=>{const t=pt.getState().currentSessionId;s({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:t})},createSession:async(t,n,o)=>{r().closeNewSessionDraft();const a=await pt.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=Mt.getState(),{messages:o,lastUsedProvider:a}=n;let l,c;if(o.forEach((b,v)=>{const j=b.find(k=>k.info?.id===t);j&&!l&&(l=j,c=v)}),!l||l.info.role!=="assistant")return;const d=Nl(l.parts);if(!d.trim())return;const u=pt.getState(),m=Lc(u.sessions,c??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:h,currentAgentName:y}=nt.getState(),g=p||a?.providerID,w=h||a?.modelID;!g||!w||await Ee.sendMessage({id:f.id,providerID:g,modelID:w,text:d,prefaceText:Cm,agent:y??void 0})},deleteSession:(t,n)=>pt.getState().deleteSession(t,n),deleteSessions:(t,n)=>pt.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>pt.getState().updateSessionTitle(t,n),shareSession:t=>pt.getState().shareSession(t),unshareSession:t=>pt.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=pt.getState().currentSessionId,o=Lc(pt.getState().sessions,t,pt.getState().getWorktreeMetadata),a=Ee.getDirectory()??yt.getState().currentDirectory??null,l=o??a;try{Ee.setDirectory(l??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}if(n&&n!==t&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,fs.VIEWPORT_MESSAGES)}if(pt.getState().setCurrentSession(t),t){r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,Rx);const d=r().messages.get(t);if(d&&d.length>0){const u=nt.getState().agents;if(u.length>0)try{await gt.getState().analyzeAndSaveExternalSessionChoices(t,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:t=>Mt.getState().loadMessages(t),sendMessage:async(t,n,o,a,l,c,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=v=>{s(j=>{const k=new Map(j.sessionActivityPhase??new Map);return k.set(v,"busy"),{sessionActivityPhase:k}})},h=v=>{s(j=>{const k=new Map(j.sessionActivityPhase??new Map);return k.set(v,"idle"),{sessionActivityPhase:k}})};if(m?.open){const v=await pt.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!v?.id)throw new Error("Failed to create session");const j=nt.getState(),k=j.currentAgentName,x=f??k,N=j.currentProviderId,P=j.currentModelId;if(N&&P)try{gt.getState().saveSessionModelSelection(v.id,N,P)}catch{}if(x){try{gt.getState().saveSessionAgentSelection(v.id,x)}catch{}if(N&&P){try{gt.getState().saveAgentModelForSession(v.id,x,N,P)}catch{}if(u!==void 0)try{gt.getState().saveAgentModelVariantForSession(v.id,x,N,P,u)}catch{}}}try{pt.getState().initializeNewOpenChamberSession(v.id,j.agents)}catch{}r().closeNewSessionDraft(),p(v.id);try{return await Mt.getState().sendMessage(t,n,o,x,v.id,l,c,d,u)}catch(C){throw h(v.id),C}}const y=pt.getState().currentSessionId,g=y?gt.getState().getSessionAgentSelection(y):null,w=nt.getState().currentAgentName,b=f||g||w||void 0;if(y&&b){try{gt.getState().saveSessionAgentSelection(y,b)}catch{}if(u!==void 0)try{gt.getState().saveAgentModelVariantForSession(y,b,n,o,u)}catch{}}y&&p(y);try{return await Mt.getState().sendMessage(t,n,o,b,y||void 0,l,c,d,u)}catch(v){throw y&&h(y),v}},abortCurrentOperation:()=>{const t=pt.getState().currentSessionId;return Mt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=pt.getState().currentSessionId;if(!n)return null;const o=Date.now()+t;return s({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{s({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&&Mt.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=pt.getState().currentSessionId||t;return Mt.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>Mt.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>Mt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>Mt.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>Mt.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:gt.getState().currentAgentContext,sessionAgentSelections:gt.getState().sessionAgentSelections,getSessionAgentEditMode:gt.getState().getSessionAgentEditMode};return uo.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>uo.getState().respondToPermission(t,n,o),addQuestion:t=>Sn.getState().addQuestion(t),dismissQuestion:(t,n)=>Sn.getState().dismissQuestion(t,n),respondToQuestion:(t,n,o)=>Sn.getState().respondToQuestion(t,n,o),rejectQuestion:(t,n)=>Sn.getState().rejectQuestion(t,n),clearError:()=>pt.getState().clearError(),getSessionsByDirectory:t=>pt.getState().getSessionsByDirectory(t),getDirectoryForSession:t=>pt.getState().getDirectoryForSession(t),getLastMessageModel:t=>Mt.getState().getLastMessageModel(t),getCurrentAgent:t=>gt.getState().getCurrentAgent(t),syncMessages:(t,n)=>Mt.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>pt.getState().applySessionMetadata(t,n),addAttachedFile:t=>Ys.getState().addAttachedFile(t),addServerFile:(t,n,o)=>Ys.getState().addServerFile(t,n,o),removeAttachedFile:t=>Ys.getState().removeAttachedFile(t),clearAttachedFiles:()=>Ys.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>Mt.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>Mt.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>Mt.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=pt.getState().currentSessionId;return Mt.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=pt.getState().currentSessionId;return Mt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>Mt.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>gt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>gt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>gt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>gt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>gt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>gt.getState().getAgentModelForSession(t,n),saveAgentModelVariantForSession:(t,n,o,a,l)=>gt.getState().saveAgentModelVariantForSession(t,n,o,a,l),getAgentModelVariantForSession:(t,n,o,a)=>gt.getState().getAgentModelVariantForSession(t,n,o,a),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=Mt.getState().messages;return gt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>pt.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>pt.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>pt.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>pt.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>pt.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>pt.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=pt.getState().currentSessionId;if(!o)return null;const a=Mt.getState().messages;return gt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=Mt.getState().messages;return gt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=Mt.getState().messages;return gt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=Mt.getState().messages.get(t)||[],o=pt.getState().sessions.find(a=>a.id===t);console.log(`Debug session ${t}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(t,n,o)=>{const a=Mt.getState().messages;return gt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>pt.getState().updateSession(t),removeSessionFromStore:t=>pt.getState().removeSessionFromStore(t),revertToMessage:async(t,n)=>{const a=(Mt.getState().messages.get(t)||[]).find(m=>m.info.id===n);let l="";a&&a.info.role==="user"&&(l=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
+ `).trim());const c=await Ee.revertSession(t,n);pt.getState().updateSession(c);const d=Mt.getState().messages.get(t)||[],u=c.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);Mt.getState().syncMessages(t,f)}}l&&s({pendingInputText:l})},handleSlashUndo:async t=>{const o=(r().messages.get(t)||[]).filter(p=>p.info.role==="user"),l=r().sessions.find(p=>p.id===t);if(o.length===0)return;const c=l?.revert?.messageID;let d;if(c){const p=o.findIndex(h=>h.info.id===c);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,d.info.id);const{toast:f}=await ls(async()=>{const{toast:p}=await import("./vendor-.bun-w0O-Y8Mh.js").then(h=>h.cz);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async t=>{const a=r().sessions.find(m=>m.id===t)?.revert?.messageID;if(!a)return;const c=(r().messages.get(t)||[]).filter(m=>m.info.role==="user"),d=c.findIndex(m=>m.info.id===a),u=c[d-1];if(u){const m=u.parts.find(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(t,u.info.id);const{toast:p}=await ls(async()=>{const{toast:h}=await import("./vendor-.bun-w0O-Y8Mh.js").then(y=>y.cz);return{toast:h}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Ee.unrevertSession(t);await pt.getState().updateSession(m),await r().loadMessages(t);const{toast:f}=await ls(async()=>{const{toast:p}=await import("./vendor-.bun-w0O-Y8Mh.js").then(h=>h.cz);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(t,n)=>{const a=r().sessions.find(l=>l.id===t);if(a)try{const l=await Ee.forkSession(t,n);if(!l||!l.id){const{toast:f}=await ls(async()=>{const{toast:p}=await import("./vendor-.bun-w0O-Y8Mh.js").then(h=>h.cz);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(r().messages.get(t)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await ls(async()=>{const{toast:p}=await import("./vendor-.bun-w0O-Y8Mh.js").then(h=>h.cz);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(l.id),u&&s({pendingInputText:u}),await r().loadMessages(l.id);const{toast:m}=await ls(async()=>{const{toast:f}=await import("./vendor-.bun-w0O-Y8Mh.js").then(p=>p.cz);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(l){console.error("Failed to fork session:",l);const{toast:c}=await ls(async()=>{const{toast:d}=await import("./vendor-.bun-w0O-Y8Mh.js").then(u=>u.cz);return{toast:d}},__vite__mapDeps([0,1]));c.error("Failed to fork session")}},setPendingInputText:t=>{s({pendingInputText:t})},consumePendingInputText:()=>{const t=r().pendingInputText;return t!==null&&s({pendingInputText:null}),t}}),{name:"composed-session-store"}));pt.subscribe((s,r)=>{if(s.sessions===r.sessions&&s.sessionsByDirectory===r.sessionsByDirectory&&s.currentSessionId===r.currentSessionId&&s.lastLoadedDirectory===r.lastLoadedDirectory&&s.isLoading===r.isLoading&&s.error===r.error&&s.webUICreatedSessions===r.webUICreatedSessions&&s.worktreeMetadata===r.worktreeMetadata&&s.availableWorktrees===r.availableWorktrees&&s.availableWorktreesByProject===r.availableWorktreesByProject)return;const t=he.getState().newSessionDraft?.open;he.setState({sessions:s.sessions,sessionsByDirectory:s.sessionsByDirectory,currentSessionId:t?null:s.currentSessionId,lastLoadedDirectory:s.lastLoadedDirectory,isLoading:s.isLoading,error:s.error,webUICreatedSessions:s.webUICreatedSessions,worktreeMetadata:s.worktreeMetadata,availableWorktrees:s.availableWorktrees,availableWorktreesByProject:s.availableWorktreesByProject})});Mt.subscribe((s,r)=>{if(s.messages===r.messages&&s.sessionMemoryState===r.sessionMemoryState&&s.messageStreamStates===r.messageStreamStates&&s.sessionCompactionUntil===r.sessionCompactionUntil&&s.sessionAbortFlags===r.sessionAbortFlags&&s.streamingMessageIds===r.streamingMessageIds&&s.abortControllers===r.abortControllers&&s.lastUsedProvider===r.lastUsedProvider&&s.isSyncing===r.isSyncing)return;const t=new Map;s.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const l=n[a];if(!l||!l.info)continue;const c=l.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:u,createdAt:m});break}}}}}),he.setState({messages:s.messages,sessionMemoryState:s.sessionMemoryState,messageStreamStates:s.messageStreamStates,sessionCompactionUntil:s.sessionCompactionUntil,sessionAbortFlags:s.sessionAbortFlags,streamingMessageIds:s.streamingMessageIds,abortControllers:s.abortControllers,lastUsedProvider:s.lastUsedProvider,isSyncing:s.isSyncing,userSummaryTitles:t})});Ys.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&he.setState({attachedFiles:s.attachedFiles})});gt.subscribe((s,r)=>{s.sessionModelSelections===r.sessionModelSelections&&s.sessionAgentSelections===r.sessionAgentSelections&&s.sessionAgentModelSelections===r.sessionAgentModelSelections&&s.currentAgentContext===r.currentAgentContext&&s.sessionContextUsage===r.sessionContextUsage&&s.sessionAgentEditModes===r.sessionAgentEditModes||he.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});uo.subscribe((s,r)=>{s.permissions!==r.permissions&&he.setState({permissions:s.permissions})});Sn.subscribe((s,r)=>{s.questions!==r.questions&&he.setState({questions:s.questions})});yt.subscribe((s,r)=>{const t=eo(s.currentDirectory??null),n=eo(r.currentDirectory??null);if(t===n)return;const o=he.getState().newSessionDraft;if(!o?.open)return;const a=eo(o.directoryOverride);a&&a!==n||he.setState(l=>({newSessionDraft:{...l.newSessionDraft,directoryOverride:t,parentID:null}}))});const Ay=he.getState().newSessionDraft?.open;he.setState({sessions:pt.getState().sessions,currentSessionId:Ay?null:pt.getState().currentSessionId,lastLoadedDirectory:pt.getState().lastLoadedDirectory,isLoading:pt.getState().isLoading,error:pt.getState().error,webUICreatedSessions:pt.getState().webUICreatedSessions,worktreeMetadata:pt.getState().worktreeMetadata,availableWorktrees:pt.getState().availableWorktrees,availableWorktreesByProject:pt.getState().availableWorktreesByProject,messages:Mt.getState().messages,sessionMemoryState:Mt.getState().sessionMemoryState,messageStreamStates:Mt.getState().messageStreamStates,sessionCompactionUntil:Mt.getState().sessionCompactionUntil,sessionAbortFlags:Mt.getState().sessionAbortFlags,streamingMessageIds:Mt.getState().streamingMessageIds,abortControllers:Mt.getState().abortControllers,lastUsedProvider:Mt.getState().lastUsedProvider,isSyncing:Mt.getState().isSyncing,permissions:uo.getState().permissions,questions:Sn.getState().questions,attachedFiles:Ys.getState().attachedFiles,sessionModelSelections:gt.getState().sessionModelSelections,sessionAgentSelections:gt.getState().sessionAgentSelections,sessionAgentModelSelections:gt.getState().sessionAgentModelSelections,currentAgentContext:gt.getState().currentAgentContext,sessionContextUsage:gt.getState().sessionContextUsage,sessionAgentEditModes:gt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=he);const Cl=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,l]=i.useState(!1),[c,d]=i.useState({length:0,offset:0}),[u,m]=i.useState({length:0,offset:0}),f=i.useRef(null),p=i.useRef(null),h=i.useRef(!1),y=i.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),g=i.useRef(null),w=i.useCallback(()=>{const M=s.current;if(!M)return;const{scrollHeight:S,clientHeight:A,scrollTop:D,scrollWidth:F,clientWidth:E,scrollLeft:I}=M,_=8;if(S>A){const V=Math.max(A-_*2,0),Y=A/S*V,H=Math.max(r,Math.min(V,Y)),L=Math.max(V-H,0),U=Math.max(S-A,1),Q=D/U*L;d({length:H,offset:Q})}else d({length:0,offset:0});if(!o&&F>E){const V=Math.max(E-_*2,0),Y=E/F*V,H=Math.max(r,Math.min(V,Y)),L=Math.max(V-H,0),U=Math.max(F-E,1),Q=I/U*L;m({length:H,offset:Q})}else m({length:0,offset:0})},[s,r,o]),b=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),t)},[t]),v=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{w(),l(!0),b()})},[b,w]);i.useEffect(()=>{const M=s.current;if(!M)return;w(),l(!0),b(),M.addEventListener("scroll",v,{passive:!0});const S=typeof ResizeObserver<"u"?new ResizeObserver(()=>w()):null;S?.observe(M);const A=typeof MutationObserver<"u"?new MutationObserver(()=>w()):null;return A?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),S?.disconnect(),A?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,v,b,w]);const j=(M,S)=>{const A=s.current;A&&(h.current=!0,y.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:A.scrollTop,scrollLeft:A.scrollLeft},g.current=S,l(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},k=M=>{if(!h.current)return;const S=s.current;if(!S)return;const A=g.current;if(A==="vertical"){const{pointerY:D,scrollTop:F}=y.current,E=M.clientY-D,I=S.clientHeight,_=Math.max(I-c.length,1),V=Math.max(S.scrollHeight-S.clientHeight,1),Y=E/_*V;S.scrollTop=F+Y}else if(A==="horizontal"){const{pointerX:D,scrollLeft:F}=y.current,E=M.clientX-D,I=S.clientWidth,_=Math.max(I-u.length,1),V=Math.max(S.scrollWidth-S.clientWidth,1),Y=E/_*V;S.scrollLeft=F+Y}},x=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),b())},N=c.length>0,P=u.length>0;if(!N&&!P)return null;const C=8;return e.jsxs("div",{className:R("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[N&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${C+c.offset}px`,right:`${C/2}px`},onPointerDown:M=>j(M,"vertical"),onPointerMove:k,onPointerUp:x,onPointerCancel:x}),P&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${C+u.offset}px`,bottom:`${C/2}px`},onPointerDown:M=>j(M,"horizontal"),onPointerMove:k,onPointerUp:x,onPointerCancel:x})]})},xt=i.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:l="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const h=i.useRef(null);return i.useImperativeHandle(p,()=>h.current,[]),e.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(l,{ref:h,className:R("overlay-scrollbar-target overlay-scrollbar-container overscroll-none",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",s),style:n,...f,children:t}),e.jsx(Cl,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});xt.displayName="ScrollableOverlay";const Bc="mobile-overlay-root",Ey=()=>{if(typeof document>"u")return null;let s=document.getElementById(Bc);return s||(s=document.createElement("div"),s.id=Bc,document.body.appendChild(s)),s},js=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:l,renderHeader:c})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Ey()),i.useEffect(()=>{if(!s)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[s,t]),!s||!d.current)return null;const u=l??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:R("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),"data-keyboard-avoid":"true",onClick:f=>f.stopPropagation(),children:[(()=>{const f=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(Gt,{className:"h-4 w-4"})});return c?c(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(xt,{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 Nu.createPortal(m,d.current)},qi=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[l,c]=i.useState(!1),d=i.useRef(void 0),u=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(s)}`,`Context limit: ${u(t)}`,`Output limit: ${u(f)}`],h=i.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c(!0)},500)},[]),y=i.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=e.jsxs("div",{className:R("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",onTouchStart:a?h:void 0,onTouchEnd:a?y:void 0,children:[e.jsx(dp,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:R(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[g,e.jsx(js,{open:l,onClose:()=>c(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(s)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:R("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:g}),e.jsx(ct,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(w=>e.jsx("p",{className:"typography-micro leading-tight",children:w},w))})})]})},Vn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Dm=(s,r,t)=>{if(typeof window>"u")return;const n=document.documentElement,o=r==="mobile",a=r==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(r==="mobile"?"device-mobile":r==="tablet"?"device-tablet":"device-desktop"),s?(n.classList.add("desktop-runtime"),n.style.setProperty("--is-mobile","0"),n.style.setProperty("--device-type","desktop"),n.style.setProperty("--font-scale","1"),n.style.setProperty("--has-coarse-pointer","0"),n.style.setProperty("--has-touch-input","0"),n.classList.remove("mobile-pointer")):(n.classList.remove("desktop-runtime"),n.style.setProperty("--is-mobile",o?"1":"0"),n.style.setProperty("--device-type",r),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",t?"1":"0"),n.style.setProperty("--has-touch-input",t?"1":"0"),t?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function ui(){const s=window.innerWidth,r=typeof window.matchMedia=="function",t=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,l=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||l>0,u=s>Vn.md&&s<=Vn.lg,m=s<=Vn.md;let f=d&&m,p=d&&!f&&u,h=!d||s>Vn.lg,y="desktop";c?(f=!1,p=!1,h=!0,y="desktop"):f?y="mobile":p?y="tablet":(h=!0,y="desktop"),Dm(c,y,d);let g="xs";for(const[w,b]of Object.entries(Vn))s>=b&&(g=w);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:y,screenWidth:s,breakpoint:g,hasTouchInput:d}}function Ht(){const[s,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:ui());return i.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(ui())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(ui())},a=[],l=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return l(t),l(n),()=>{a.forEach(c=>c())}},[]),i.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,l=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=l||c||d>0;Dm(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const Eo=5e3,Iy=1e4,Py=5e3,Ty=1e4,Fy=25,Ry=4,zc=15e3,or=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Oy=(s,r)=>{if(!s&&!r)return!1;if(!s||!r)return!0;const t=new Set([...Object.keys(s),...Object.keys(r)]);for(const n of t){const o=s[n],a=r[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},_y=(s,r)=>{if(!s&&!r)return!1;if(!s||!r)return!0;const t=s.files??[],n=r.files??[];if(t.length!==n.length||s.ahead!==r.ahead||s.behind!==r.behind||s.current!==r.current||s.tracking!==r.tracking||s.isClean!==r.isClean)return!0;const o=new Set(t.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of n)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!Oy(s.diffStats,r.diffStats)},$y=(s,r)=>{const t=new Set;if(!r)return t;const n=s?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),l=new Map(o.map(f=>[f.path,f])),c=new Set([...a.keys(),...l.keys()]);for(const f of c){const p=a.get(f),h=l.get(f);if(!p||!h){t.add(f);continue}if(p.index!==h.index||p.working_dir!==h.working_dir){t.add(f);continue}}const d=s?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],h=u[f];if(!p||!h){t.add(f);continue}(p.insertions!==h.insertions||p.deletions!==h.deletions)&&t.add(f)}return t},Qt=Kt()(ss((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:Eo,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,or()),s({activeDirectory:t,directories:a})}else s({activeDirectory:t})},getDirectoryState:t=>r().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:l}=r();let c=l.get(t);c||(c=or()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(l);return f.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),s({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(t);if(_y(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??or(),h=$y(p.status,m),y=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 y)g.has(v)||w.delete(v);for(const v of h)w.delete(v);const b=h.size>0;f.set(t,{...p,isGitRepo:!0,status:m,diffCache:w,lastStatusFetch:Date.now(),lastStatusChange:b?Date.now():p.lastStatusChange}),s({directories:f})}else{const f=new Map(r().directories),p=f.get(t)??or();f.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),s({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||s({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{s({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(r().directories),l=a.get(t)??or();a.set(t,{...l,branches:o}),s({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{s({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=r(),l=a.get(t),c=o??l?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),u=new Map(r().directories),m=u.get(t)??or();u.set(t,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:c}),s({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{s({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{s({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(r().directories),l=a.get(t)??or();a.set(t,{...l,identity:o}),s({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{s({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=r();let l=a.get(t);if(!l){l=or();const f=new Map(a);f.set(t,l),s({directories:f})}const{force:c=!1}=o,d=Date.now();await r().fetchStatus(t,n);const u=r().directories.get(t);if(!u?.isGitRepo)return;await r().fetchBranches(t,n);const m=d-(u.lastLogFetch||0);(c||m>Ty||!u.log)&&await r().fetchLog(t,n),await r().fetchIdentity(t,n),r().fetchAllDiffs(t,n)},getDiff:(t,n)=>r().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(r().directories),l=a.get(t)??or(),c=new Map(l.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...l,diffCache:c}),s({directories:a})},clearDiffCache:t=>{const n=new Map(r().directories),o=n.get(t);o&&(n.set(t,{...o,diffCache:new Map}),s({directories:n}))},fetchAllDiffs:async(t,n)=>{const o=r().directories.get(t);if(!o?.status?.files||o.status.files.length===0)return;const c=o.status.files.filter(v=>!o.diffCache.has(v.path)).slice(0,Fy);if(c.length===0)return;let d=0;const u=[],m=()=>{const v=d;return d+=1,v<c.length?c[v]:null},f=async v=>{const j=n.getGitFileDiff(t,{path:v}),k=new Promise((N,P)=>{setTimeout(()=>P(new Error(`Timed out after ${zc}ms`)),zc)}),x=await Promise.race([j,k]);return{path:v,diff:{original:x.original??"",modified:x.modified??""}}},p=async()=>{for(;;){const v=m();if(!v)return;try{u.push(await f(v.path))}catch{}}},h=Math.min(Ry,c.length);await Promise.allSettled(Array.from({length:h},()=>p()));const y=new Map(r().directories),g=y.get(t);if(!g)return;const w=new Map(g.diffCache),b=Date.now();u.forEach(v=>{w.set(v.path,{...v.diff,fetchedAt:b})}),y.set(t,{...g,diffCache:w}),s({directories:y})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??or();o.set(t,{...a,logMaxCount:n}),s({directories:o})},startPolling:t=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){s({pollIntervalId:o()});return}const{activeDirectory:c}=r();if(!c){s({pollIntervalId:o()});return}if(await r().fetchStatus(c,t,{silent:!0}))await r().fetchLog(c,t),r().fetchAllDiffs(c,t),s({currentPollInterval:Eo});else{const m=Math.min(a+Py,Iy);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:Eo})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:Eo}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),Am=s=>Qt(r=>s?r.directories.get(s)?.status??null:null),Em=s=>Qt(r=>s?r.directories.get(s)?.branches??null:null),Ly=s=>Qt(r=>s?r.directories.get(s)?.log??null:null),By=s=>Qt(r=>s?r.directories.get(s)?.identity??null:null),Ml=s=>Qt(r=>s?r.directories.get(s)?.isGitRepo??null:null),zy=s=>Qt(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function Yt({...s}){return e.jsx(up,{"data-slot":"dropdown-menu",...s})}function Xt({...s}){return e.jsx(mp,{"data-slot":"dropdown-menu-trigger",...s})}function Jt({className:s,sideOffset:r=4,...t}){return e.jsx(fp,{children:e.jsx(pp,{"data-slot":"dropdown-menu-content",sideOffset:r,className:R("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",s),...t})})}function It({className:s,inset:r,variant:t="default",...n}){return e.jsx(vp,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:R("hover:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s),...n})}function ha({...s}){return e.jsx(gp,{"data-slot":"dropdown-menu-radio-group",...s})}function ga({className:s,children:r,...t}){return e.jsxs(xp,{"data-slot":"dropdown-menu-radio-item",className:R("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s),...t,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(yp,{children:e.jsx(Bt,{className:"size-3"})})}),r]})}function Pr({className:s,inset:r,...t}){return e.jsx(hp,{"data-slot":"dropdown-menu-label","data-inset":r,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function Ss({className:s,...r}){return e.jsx(bp,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-0.5 h-px",s),...r})}const Wy=wp("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 De({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?Cu:"button";return e.jsx(a,{"data-slot":"button",className:R(Wy({variant:r,size:t,className:s})),...o})}const xo=jp,La=({className:s,...r})=>e.jsx(Sp,{className:R("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",s),...r}),yo=({className:s,...r})=>e.jsx(kp,{className:R("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r}),Hy={read:{displayName:"Read File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"offset",label:"Start Line",type:"text"},{key:"limit",label:"Lines to Read",type:"text"}]},write:{displayName:"Write File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit File",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace All",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},bash:{displayName:"Shell Command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include Pattern",type:"pattern"}]},glob:{displayName:"Find Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List Directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore Patterns",type:"pattern"}]},task:{displayName:"Agent Task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent Type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"numResults",label:"Results Count",type:"text"},{key:"type",label:"Search Type",type:"text"}]},codesearch:{displayName:"Code Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update Todo List",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo Items",type:"code",language:"json"}]},todoread:{displayName:"Read Todo List",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Load Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill Name",type:"text"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]}};function Dl(s){return Hy[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Uy(s,r,t){const n=Dl(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=gr(o);if(a)return a}if(s==="webfetch"){if(r.trim().startsWith("{")||r.trim().startsWith("["))try{return JSON.parse(r),"json"}catch{}if(r.trim().startsWith("<"))return"html";if(r.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function gr(s){const r=s.split(".").pop()?.toLowerCase(),t=s.split("/").pop()?.toLowerCase()||"",n={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return n[t]?n[t]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"elixir",heex:"elixir",leex:"elixir",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[r||""]||null}const Vy=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function mo(s){const r=s.split(".").pop()?.toLowerCase();return Vy.includes(r||"")}function Ki(s){const r=s.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[r||""]||"image/png"}function Gy(s,r){if(!s)return"";const t=n=>{const o=s[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=t("command");if(n)return n}if(r==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((r==="edit"||r==="multiedit")&&typeof s=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof s=="object"){const n=t("content");if(n)return n}return typeof s=="object"?Object.entries(s).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const l=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${l}: ${c}`}).join(`
12
+ `):String(s)}const Al=i.createContext(null),Nr=()=>{const s=i.useContext(Al);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},Im=s=>{const r=Nr();return s(r)},qy=()=>Im(s=>s.runtime.isDesktop),Pm=()=>Im(s=>s.runtime.isVSCode),Tm=({mode:s,onModeChange:r,className:t})=>{const n=i.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(De,{size:"sm",variant:"ghost",className:R("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:n,title:s==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:s==="side-by-side"?e.jsx(Np,{className:"h-3 w-3"}):e.jsx(Cp,{className:"h-3 w-3"})})},El=Ae.createContext(void 0);function Vr(){const s=Ae.useContext(El);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function Ba(){return Ae.useContext(El)}const Ky="Flexoki",Qy="dark",Yy={"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"},Xy=[{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"}}],Jy={name:Ky,type:Qy,colors:Yy,tokenColors:Xy},Zy="Flexoki",eb="light",tb={"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"},sb=[{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"}}],rb={name:Zy,type:eb,colors:tb,tokenColors:sb},Il="flexoki-dark",Pl="flexoki-light",nb=Jy,ob=rb;function Fm(s,r){return Object.defineProperty(s,"toString",{value:()=>r,enumerable:!1,configurable:!0}),Object.defineProperty(s,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0}),s}function Rm(s,r,t){const n=s.colors?.["editor.background"],o=s.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${r}" is missing editor.background/editor.foreground`);const a=s.tokenColors??[];return{...s,name:r,type:t,fg:o,bg:n,settings:a}}const Tl=Rm(nb,Il,"dark"),Fl=Rm(ob,Pl,"light");Fm(Tl,Il);Fm(Fl,Pl);const Tn={dark:Il,light:Pl},Wc=[Fl,Tl];let Hc=!1;function Om(){Hc||(tc(Tn.dark,async()=>Tl),tc(Tn.light,async()=>Fl),Hc=!0)}const Ns=Ae.forwardRef(({className:s,...r},t)=>e.jsx(xt,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:R("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",s),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r}));Ns.displayName="Textarea";const ab=`
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 ib(s,r,t){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${s}:${r.length}:${t.length}:${n.length}:${o.length}`}const lb=(s,r,t)=>{const a=(t.side==="deletions"?s:r).split(`
75
+ `),l=Math.max(1,t.start),c=Math.min(a.length,t.end);return l>c?"":a.slice(l-1,c).join(`
76
+ `)},Qi=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:l="fill"})=>{const{isMobile:c}=Ht(),{inputBarOffset:d,isKeyboardOpen:u}=_e(),f=Ba()?.currentTheme?.metadata?.variant==="dark",p=_e(L=>L.setActiveMainTab),[h,y]=Ae.useState(null),[g,w]=Ae.useState(""),b=Ae.useCallback(()=>{if(c)return"50%";const L=document.querySelector("main.flex-1");if(L){const U=L.getBoundingClientRect();return`${U.left+U.width/2}px`}return"50%"},[c]),[v,j]=Ae.useState(b),k=he(L=>L.sendMessage),x=he(L=>L.currentSessionId),{currentProviderId:N,currentModelId:P,currentAgentName:C,currentVariant:M}=nt(),S=gt(L=>L.getSessionAgentSelection),A=gt(L=>L.getAgentModelForSession),D=gt(L=>L.getAgentModelVariantForSession);Ae.useEffect(()=>{if(c)return;const L=()=>{j(b())};return window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[c,b]);const F=Ae.useCallback(L=>{if(c&&L&&h&&L.start===L.end){const U=L.start,Q=h.start,J=h.end,K=Math.min(Q,J,U),ne=Math.max(Q,J,U);if(U<Q||U>J){y({...L,start:K,end:ne});return}}y(L),L||w("")},[c,h]);Ae.useEffect(()=>{if(!h)return;const L=Q=>{const J=Q.target;if(document.querySelector("[data-comment-ui]")?.contains(J)||J.closest("[data-sonner-toast]")||J.closest("[data-sonner-toaster]"))return;Q.composedPath().some(ae=>ae instanceof HTMLElement?ae.hasAttribute("data-line-number")||ae.closest?.("[data-line-number]"):!1)||(y(null),w(""))},U=setTimeout(()=>{document.addEventListener("click",L)},100);return()=>{clearTimeout(U),document.removeEventListener("click",L)}},[h]);const E=Ae.useCallback(async()=>{if(!h||!g.trim())return;if(!x){Z.error("Select a session to send comment");return}const L=S(x)||C,U=L?A(x,L):null,Q=U?.providerId||N,J=U?.modelId||P;if(!Q||!J){Z.error("Select a model to send comment");return}const K=L&&Q&&J?D(x,L,Q,J)??M:M,ne=lb(s,r,h),X=h.start,ae=h.end,O=h.side==="deletions"?"original":"modified",z=`Comment on \`${n}\` lines ${X}-${ae} (${O}):
77
+ \`\`\`${t}
78
+ ${ne}
79
+ \`\`\`
80
+
81
+ ${g}`;w(""),y(null),p("chat");try{await k(z,Q,J,L,void 0,void 0,void 0,K)}catch(T){console.error("Failed to send comment",T)}},[h,g,s,r,n,t,k,x,N,P,C,M,p,S,A,D]);Om();const I=Ae.useRef(null),_=Ae.useMemo(()=>{const L=ib(n,s,r);if(I.current?.key===L)return I.current.fileDiff;const U={name:n,contents:s,cacheKey:`old-${L}`},Q={name:n,contents:r,cacheKey:`new-${L}`},J=Oi(U,Q);return I.current={key:L,fileDiff:J},J},[n,s,r,t]),V=Ae.useMemo(()=>({theme:{dark:Tn.dark,light:Tn.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:F,unsafeCSS:ab}),[f,o,a,F]);if(typeof window>"u")return null;const H=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(Ns,{value:g,onChange:L=>{w(L.target.value);const U=L.target;U.style.height="auto";const J=20*5+8;U.style.height=`${Math.min(U.scrollHeight,J)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!c,rows:1,onKeyDown:L=>{L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),E()),L.key==="Escape"&&(L.preventDefault(),y(null),w(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.split("/").pop(),":",h.start,"-",h.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!c&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[es(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:L=>{g.trim()&&(L.preventDefault(),E())},onClick:()=>{c||E()},disabled:!g.trim(),className:R("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(Ma,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return l==="fill"?e.jsxs("div",{className:R("flex flex-col relative","size-full"),style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":void 0},children:[e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(xt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(sc,{fileDiff:_,options:V,selectedLines:h})})}),h&&e.jsx("div",{className:R("pointer-events-auto relative pb-2 transition-none z-50 flex justify-center",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true",children:H})]}):e.jsxs("div",{className:R("relative","w-full"),children:[e.jsx(xt,{outerClassName:"pierre-diff-wrapper w-full",disableHorizontal:!1,fillContainer:!1,children:e.jsx(sc,{fileDiff:_,options:V,selectedLines:h})}),h&&Nu.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col justify-end items-start pointer-events-none transition-none transform-gpu",style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":"0px",isolation:"isolate"},children:e.jsx("div",{className:R("pointer-events-auto relative pb-2 transition-none",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginLeft:v,transform:"translateX(-50%)",marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",children:H})}),document.body)]})},cb=1100,_m=15e3,$m={"?":{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"}},db=$m.M,Zo=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],ub=s=>{const r=s.index?.trim(),t=s.working_dir?.trim();return r&&r!=="?"?r.charAt(0):t?t.charAt(0):r?.charAt(0)||t?.charAt(0)||"M"},Lm=s=>{const r=ub(s);return $m[r]??db},mb=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},xa=(s,r)=>{const t=s??0,n=r??0;return!t&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[t?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",t]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},fb=i.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o,showModeSelector:a=!1,mode:l,onModeChange:c})=>{const d=i.useCallback(u=>{if(!o)return u;const m=u.lastIndexOf("/");return m>=0?u.slice(m+1):u},[o]);return s.length===0?null:e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[t?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:d(t.path)}),xa(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Ft,{className:"size-4 opacity-50"})]})}),e.jsxs(Jt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&l&&c?e.jsxs(e.Fragment,{children:[e.jsx(Pr,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(ha,{value:l,onValueChange:u=>c(u),children:Zo.map(u=>e.jsx(ga,{value:u.value,className:"items-center",children:e.jsx("span",{className:"typography-meta text-foreground",children:u.label})},u.value))}),e.jsx(Ss,{})]}):null,e.jsx(ha,{value:r??"",onValueChange:n,children:s.map(u=>e.jsx(ga,{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:xa(u.insertions,u.deletions)})]})},u.path))})]})]})}),pb=i.memo(({mode:s,onModeChange:r})=>{const t=Zo.find(n=>n.value===s)??Zo[0];return e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsx("span",{className:"min-w-0 truncate typography-meta",children:t.label}),e.jsx(Ft,{className:"size-4 opacity-50"})]})}),e.jsx(Jt,{className:"min-w-[220px]",children:e.jsx(ha,{value:s,onValueChange:n=>r(n),children:Zo.map(n=>e.jsx(ga,{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))})})]})}),hb=i.memo(({changedFiles:s,selectedFile:r,onSelectFile:t})=>s.length===0?null:e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:s.map(n=>{const o=Lm(n),a=r===n.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>t(n.path),className:R("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}),xa(n.insertions,n.deletions)]})},n.path)})})})),gb=i.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const l=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:l,children:[o&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),xb=i.memo(({filePath:s,diff:r,renderSideBySide:t})=>{const n=r.original.length>0,o=r.modified.length>0,a=t?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",l=t?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:a,children:[n&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${s}`,className:t?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:n?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:t?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),yb=i.memo(({filePath:s,diff:r,renderSideBySide:t,wrapLines:n})=>{const o=i.useMemo(()=>gr(s)||"text",[s]);return mo(s)?e.jsx(xb,{filePath:s,diff:r,renderSideBySide:t}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(Qi,{original:r.original,modified:r.modified,language:o,fileName:s,renderSideBySide:t,wrapLines:n,layout:"inline"})})}),bb=i.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>gr(s)||"text",[s]);return mo(s)?e.jsx(gb,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(Qi,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(Qi,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),vb=i.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Qt(i.useCallback(c=>c.directories.get(s)?.diffCache.get(r)??null,[s,r])),l=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return l?e.jsx(bb,{filePath:r,diff:l,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),wb=i.memo(({directory:s,file:r,layout:t,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:l,registerSectionRef:c})=>{const{git:d}=Nr(),u=Qt(i.useCallback(E=>E.directories.get(s)?.diffCache.get(r.path)??null,[s,r.path])),m=Qt(E=>E.setDiff),f=_e(E=>E.setDiffFileLayout),[p,h]=i.useState(!0),[y,g]=i.useState(!1),[w,b]=i.useState(0),[v,j]=i.useState(null),[k,x]=i.useState(!1),N=i.useRef(null),P=i.useRef(null),C=i.useMemo(()=>Lm(r),[r]),M=t==="side-by-side",S=i.useMemo(()=>u?{original:u.original,modified:u.modified}:null,[u]),A=i.useCallback(E=>{P.current=E,c(r.path,E)},[r.path,c]),D=i.useCallback(E=>{h(E),E&&g(!0)},[]),F=i.useCallback(()=>{l(r.path)},[r.path,l]);return i.useEffect(()=>{if(!p||y)return;const E=P.current;if(!E)return;if(!o.current||typeof IntersectionObserver>"u"){g(!0);return}const I=new IntersectionObserver(_=>{_.some(V=>V.isIntersecting)&&(g(!0),I.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return I.observe(E),()=>I.disconnect()},[y,p,o]),i.useEffect(()=>{if(!p||!y)return;if(!s||S){N.current=null,x(!1);return}const E=`${s}::${r.path}::${w}`;if(N.current===E)return;N.current=E,j(null),x(!0);let I=!1;return(async()=>{try{const _=d.getGitFileDiff(s,{path:r.path}),V=_m,Y=new Promise((L,U)=>{setTimeout(()=>U(new Error(`Timed out after ${V}ms`)),V)}),H=await Promise.race([_,Y]);if(I)return;m(s,r.path,{original:H.original??"",modified:H.modified??""}),x(!1)}catch(_){if(I)return;const V=_ instanceof Error?_.message:String(_);j(V),x(!1)}})(),()=>{I=!0,N.current===E&&(N.current=null)}},[s,S,w,r.path,d,y,p,m]),e.jsx("div",{ref:A,className:"scroll-mt-4",children:e.jsxs(xo,{open:p,onOpenChange:D,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(La,{onClick:F,className:R("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:R("absolute inset-0 pointer-events-none transition-colors",a?"bg-primary/10":"group-hover:bg-accent/40")}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover:opacity-100 transition-opacity",children:p?e.jsx(Ft,{className:"size-4"}):e.jsx(Is,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:C.color},title:C.description,"aria-label":C.description,children:C.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path})]}),e.jsxs("div",{className:"relative flex items-center gap-2",children:[xa(r.insertions,r.deletions),e.jsx(Tm,{mode:M?"side-by-side":"unified",onModeChange:E=>{const I=E==="side-by-side"?"side-by-side":"inline";f(r.path,I)},className:"opacity-70"})]})]})}),e.jsx(yo,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[v?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:v}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>b(E=>E+1),children:"Retry"})]}):null,k&&!S&&!v?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(ts,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,S?e.jsx(yb,{filePath:r.path,diff:S,renderSideBySide:M,wrapLines:n}):null]})})]})})}),jb=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=yt(),o=s?t.get(s)??void 0:void 0,l=r.find(c=>c.id===s)?.directory;return o?.path??l??n??void 0},Sb=()=>{const{git:s}=Nr(),r=jb(),{screenWidth:t,isMobile:n}=Ht(),o=Ml(r??null),a=Am(r??null),l=Qt(oe=>oe.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=Qt(),[m,f]=i.useState(null),[p,h]=i.useState(0),[y,g]=i.useState(null),w=i.useRef(null),b=_e(oe=>oe.pendingDiffFile),v=_e(oe=>oe.setPendingDiffFile),j=_e(oe=>oe.diffLayoutPreference),k=_e(oe=>oe.diffFileLayout),x=_e(oe=>oe.setDiffFileLayout),N=_e(oe=>oe.diffWrapLines),P=_e(oe=>oe.setDiffWrapLines),C=_e(oe=>oe.diffViewMode),M=_e(oe=>oe.setDiffViewMode),S=n||N,A=C==="stacked",D=n||t<=768,F=!D&&t>=1024,E=i.useRef(null),I=i.useRef(new Map),_=i.useRef(null),V=i.useMemo(()=>{if(!a?.files)return[];const oe=a.diffStats??{};return a.files.map(de=>({...de,insertions:oe[de.path]?.insertions??0,deletions:oe[de.path]?.deletions??0,isNew:mb(de)})).sort((de,je)=>de.path.localeCompare(je.path))},[a]),Y=i.useMemo(()=>m?V.find(oe=>oe.path===m)??null:null,[V,m]),H=i.useCallback(oe=>{const de=k[oe.path];if(de)return de;if(j==="inline")return"inline";if(j==="side-by-side")return"side-by-side";const je=t<cb;return oe.isNew||je?"inline":"side-by-side"},[k,j,t]),L=i.useMemo(()=>Y?H(Y):null,[H,Y]);i.useEffect(()=>{r&&(c(r),Qt.getState().directories.get(r)?.status||d(r,s))},[r,c,d,s]),i.useEffect(()=>{b&&(f(b),v(null),A&&(_.current=b))},[A,b,v]),i.useEffect(()=>{!m&&!b&&V.length>0&&f(V[0].path)},[V,m,b]),i.useEffect(()=>{if(!A){_.current=null;return}const oe=_.current;if(!oe)return;const de=I.current.get(oe);de&&(de.scrollIntoView({behavior:"smooth",block:"start"}),_.current=null)},[V,A]),i.useEffect(()=>{m&&V.length>0&&(V.some(de=>de.path===m)||f(V[0]?.path??null))},[V,m]);const U=i.useCallback((oe,de)=>{const je=I.current;de?je.set(oe,de):je.delete(oe)},[]),Q=i.useCallback((oe,de="smooth")=>{const je=I.current.get(oe);return je?(je.scrollIntoView({behavior:de,block:"start"}),!0):!1},[]),J=i.useCallback(oe=>{f(oe)},[]),K=i.useCallback(oe=>{f(oe),A&&!Q(oe)&&(_.current=oe)},[A,Q]),ne=i.useCallback(oe=>{M(oe),oe==="stacked"&&m&&!Q(m,"auto")&&(_.current=m)},[Q,m,M]),X=i.useCallback(oe=>{const de=oe==="side-by-side"?"side-by-side":"inline";if(A){V.forEach(je=>{x(je.path,de)});return}Y&&x(Y.path,de)},[V,A,Y,x]),ae=(L??"side-by-side")==="side-by-side",O=!A||!F,z=Qt(i.useCallback(oe=>!r||!m?null:oe.directories.get(r)?.diffCache.get(m)??null,[r,m])),T=!!z,$=!A&&!!m&&!T;i.useEffect(()=>{if(A)return;if(g(null),!r||!m){w.current=null;return}if(z){w.current=null;return}const oe=`${r}::${m}::${p}`;if(w.current===oe)return;w.current=oe;let de=!1;return(async()=>{try{const je=s.getGitFileDiff(r,{path:m}),Se=_m,Le=new Promise((ee,te)=>{setTimeout(()=>te(new Error(`Timed out after ${Se}ms`)),Se)}),G=await Promise.race([je,Le]);if(de)return;u(r,m,{original:G.original??"",modified:G.modified??""})}catch(je){if(de)return;const Se=je instanceof Error?je.message:String(je);g(Se)}})(),()=>{de=!0,w.current===oe&&(w.current=null)}},[r,A,m,z,s,u,p]);const W=()=>!r||V.length===0?null:V.map(oe=>e.jsx(vb,{directory:r,filePath:oe.path,isVisible:oe.path===m,renderSideBySide:ae,wrapLines:S},oe.path)),q=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 gap-3 px-3 pb-3 pt-2",children:[F&&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(hb,{changedFiles:V,selectedFile:m,onSelectFile:K})]}),e.jsx(xt,{ref:E,outerClassName:"flex-1 min-h-0",className:"pr-2",children:e.jsx("div",{className:"flex flex-col gap-3",children:V.map(oe=>e.jsx(wb,{directory:r,file:oe,layout:H(oe),wrapLines:S,scrollRootRef:E,isSelected:oe.path===m,onSelect:J,registerSectionRef:U},oe.path))})})]}):null,ue=()=>r?l&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ts,{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"}):A?q():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[W(),$&&!T&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:y?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:y}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{g(null),h(oe=>oe+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ts,{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(cl,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:l&&!a?"Loading changes…":`${V.length} ${V.length===1?"file":"files"} changed`})]}),!D&&e.jsx(pb,{mode:C,onModeChange:ne}),O&&e.jsx(fb,{changedFiles:V,selectedFile:m,selectedFileEntry:Y,onSelectFile:K,isMobile:D,showModeSelector:D,mode:C,onModeChange:ne}),e.jsx("div",{className:"flex-1"}),Y&&e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>P(!N),className:R("h-5 w-5 p-0 transition-opacity",S?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:S?"Disable line wrap":"Enable line wrap",children:e.jsx(Mu,{className:"size-4"})}),Y&&L&&e.jsx(Tm,{mode:L==="side-by-side"?"side-by-side":"unified",onModeChange:X})]}),ue()]})},kb=()=>{const{git:s}=Nr(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=he(),{currentDirectory:o}=yt(),a=r?n.get(r)??void 0:void 0,c=t.find(p=>p.id===r)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:u,fetchStatus:m}=Qt(),f=zy(d??null);return i.useEffect(()=>{d&&(u(d),Qt.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},ya=Ae.forwardRef(({className:s,...r},t)=>e.jsx(Du,{className:R("peer inline-flex shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-foreground/30",s),style:{width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},...r,ref:t,children:e.jsx(Mp,{className:R("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"}})}));ya.displayName=Du.displayName;const Nb={},ea=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},Uc=s=>ea(s)??"__global__",Cb=s=>{const r=Object.entries(s??{}),t=r.filter(([,l])=>l?.status==="connected").length,n=r.length,o=r.some(([,l])=>l?.status==="failed"),a=r.some(([,l])=>l?.status==="needs_auth"||l?.status==="needs_client_registration");return{connected:t,total:n,hasFailed:o,hasAuthRequired:a}},Kn=Kt()(ss((s,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:t=>{const n=Uc(t??yt.getState().currentDirectory);return r().byDirectory[n]??Nb},refresh:async t=>{const n=ea(t?.directory??yt.getState().currentDirectory),o=Uc(n);t?.silent||s(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const c=(await Ee.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};s(d=>({byDirectory:{...d.byDirectory,[o]:c},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const l=a instanceof Error?a.message:"Failed to load MCP status";s(c=>({loadingKeys:{...c.loadingKeys,[o]:!1},lastErrorKeys:{...c.lastErrorKeys,[o]:l}}))}},connect:async(t,n)=>{const o=ea(n??yt.getState().currentDirectory);await Ee.getApiClient().mcp.connect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(t,n)=>{const o=ea(n??yt.getState().currentDirectory);await Ee.getApiClient().mcp.disconnect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function Mb(s){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",fillRule:"evenodd",viewBox:"-0.5 -0.5 25 25",...s,children:[e.jsx("path",{d:"M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"}),e.jsx("path",{d:"M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"})]})}const Db=s=>{if(!s)return"Unknown";switch(s.status){case"connected":return"Connected";case"failed":return`Failed: ${s.error||"Unknown error"}`;case"needs_auth":return"Needs authentication";case"needs_client_registration":return`Needs registration: ${s.error||""}`;default:return s.status}},Ab=s=>{switch(s?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Yi=({headerIconButtonClass:s})=>{const[r,t]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:l}=Ht(),d=yt(C=>C.currentDirectory)??null,u=Kn(C=>C.getStatusForDirectory(d)),m=Kn(C=>C.refresh),f=Kn(C=>C.connect),p=Kn(C=>C.disconnect),h=i.useCallback(C=>{C||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),t(C)},[]),y=i.useCallback(C=>{a.current||o(C)},[]),[g,w]=i.useState(!1),[b,v]=i.useState(null);i.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),i.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const j=i.useMemo(()=>Cb(u),[u]),k=i.useMemo(()=>Object.keys(u).sort((C,M)=>C.localeCompare(M)),[u]),x=i.useCallback(C=>{if(C?.preventDefault(),g)return;w(!0);const M=new Promise(S=>setTimeout(S,500));Promise.all([m({directory:d}),M]).finally(()=>{w(!1)})},[g,m,d]),N=()=>e.jsxs(e.Fragment,{children:[k.map(C=>{const M=u[C],S=Ab(M),A=M?.status==="connected",D=b===C,F=Db(M);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l?e.jsx("span",{className:R("h-2 w-2 rounded-full flex-shrink-0",S==="success"&&"bg-status-success",S==="error"&&"bg-status-error",S==="warning"&&"bg-status-warning",S==="default"&&"bg-muted-foreground/40"),"aria-label":F}):e.jsxs(dt,{delayDuration:300,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:R("h-2 w-2 rounded-full flex-shrink-0",S==="success"&&"bg-status-success",S==="error"&&"bg-status-error",S==="warning"&&"bg-status-warning",S==="default"&&"bg-muted-foreground/40"),"aria-label":F})}),e.jsx(ct,{side:"left",children:e.jsx("p",{children:F})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:C})]})}),e.jsx(ya,{checked:A,disabled:D,className:"data-[state=checked]:bg-status-info",onCheckedChange:async E=>{v(C);try{E?await f(C,d):await p(C,d)}finally{v(null)}}})]},C)}),k.length===0&&e.jsx("div",{className:"px-2 py-3 typography-ui-label text-muted-foreground text-center",children:"Configure MCP servers in Opencode config."})]}),P=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:R(s,"relative"),onClick:l?()=>t(!0):void 0,children:[e.jsx(Mb,{className:"h-[1.0625rem] w-[1.0625rem]"}),j.total>0&&e.jsx("span",{className:R("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",j.hasFailed?"bg-status-error":j.hasAuthRequired?"bg-status-warning":j.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return l?e.jsxs(e.Fragment,{children:[P,e.jsxs(js,{open:r,title:"MCP Servers",onClose:()=>t(!1),renderHeader:C=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"MCP Servers"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:g,onClick:x,"aria-label":"Refresh",children:e.jsx(Rr,{className:R("h-4 w-4",g&&"animate-spin")})}),C]})]}),children:[e.jsx("div",{className:"py-1",children:N()}),d&&e.jsx("div",{className:"px-2 py-1 border-t border-border/40 mt-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]}):e.jsxs(Yt,{open:r,onOpenChange:h,children:[e.jsxs(dt,{delayDuration:1e3,open:r?!1:n,onOpenChange:y,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:P})}),e.jsx(ct,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(Jt,{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:x,"aria-label":"Refresh",children:e.jsx(Rr,{className:R("h-4 w-4",g&&"animate-spin")})})]}),e.jsx(Ss,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:N()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{}),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})})]})]})]})},Eb=()=>{const s=_e(d=>d.setSessionSwitcherOpen),r=_e(d=>d.toggleSidebar),{isMobile:t}=Ht(),[n,o]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const l=i.useCallback(()=>{t?s(!0):r()},[t,s,r]),c="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground";return t||!n||!a?null:e.jsx("div",{className:"fixed top-[0.375rem] left-[5.25rem] z-[9999]",style:{pointerEvents:"auto","--padding-scale":"1"},children:e.jsx("button",{type:"button",onClick:l,"aria-label":"Open sessions",className:c,children:e.jsx(Da,{className:"h-5 w-5"})})})},Vc=()=>{const s=_e(U=>U.setSessionSwitcherOpen),r=_e(U=>U.toggleSidebar),t=_e(U=>U.setSettingsDialogOpen),n=_e(U=>U.toggleCommandPalette),o=_e(U=>U.toggleHelpDialog),a=_e(U=>U.isSidebarOpen),l=_e(U=>U.sidebarWidth),c=_e(U=>U.activeMainTab),d=_e(U=>U.setActiveMainTab),{getCurrentModel:u}=nt(),m=he(U=>U.getContextUsage),{isMobile:f}=Ht(),p=kb(),h=Ta(U=>U.available),y=i.useRef(null),[g,w]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Ae.useEffect(()=>{if(typeof window>"u")return;const U=typeof window.opencodeDesktop<"u";w(U)},[]);const v=u(),j=v&&typeof v.limit=="object"&&v.limit!==null?v.limit:null,k=j&&typeof j.context=="number"?j.context:0,x=j&&typeof j.output=="number"?j.output:0,N=m(k,x),P=_e(U=>U.isSessionSwitcherOpen),C=i.useCallback(()=>{if(typeof document>"u")return;const U=document.activeElement;if(!U)return;const Q=U.tagName;(Q==="INPUT"||Q==="TEXTAREA"||Q==="SELECT"||U.isContentEditable)&&U.blur()},[]),M=i.useCallback(()=>{if(f){C(),s(!P);return}r()},[C,f,P,s,r]),S=i.useCallback(()=>{f&&C(),s(!1),t(!0)},[C,f,s,t]),A="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground",D=i.useMemo(()=>g&&b?a?"pl-0":"pl-[8.0rem]":"pl-3",[g,b,a]),F=i.useCallback(()=>{if(typeof document>"u")return;const U=y.current?.getBoundingClientRect().height;U&&document.documentElement.style.setProperty("--oc-header-height",`${U}px`)},[]);Ae.useEffect(()=>{if(typeof window>"u")return;F();const U=y.current;if(!U||typeof ResizeObserver>"u")return()=>{};const Q=new ResizeObserver(()=>{F()});return Q.observe(U),window.addEventListener("resize",F),window.addEventListener("orientationchange",F),()=>{Q.disconnect(),window.removeEventListener("resize",F),window.removeEventListener("orientationchange",F)}},[F]),Ae.useEffect(()=>{F()},[F,f]);const E=i.useCallback(async U=>{if(!U.target.closest("button, a, input, select, textarea")&&U.button===0&&g)try{const{getCurrentWindow:Q}=await ls(async()=>{const{getCurrentWindow:K}=await import("./vendor-.bun-w0O-Y8Mh.js").then(ne=>ne.cB);return{getCurrentWindow:K}},__vite__mapDeps([0,1]));await Q().startDragging()}catch(Q){console.error("Failed to start window dragging:",Q)}},[g]),I=i.useCallback(async U=>{if(U.button===0&&g)try{const{getCurrentWindow:Q}=await ls(async()=>{const{getCurrentWindow:K}=await import("./vendor-.bun-w0O-Y8Mh.js").then(ne=>ne.cB);return{getCurrentWindow:K}},__vite__mapDeps([0,1]));await Q().startDragging()}catch(Q){console.error("Failed to start window dragging:",Q)}},[g]),_=i.useMemo(()=>[{id:"chat",label:"Chat",icon:Dp},{id:"diff",label:"Diff",icon:$s,badge:!f&&p>0?p:void 0},{id:"files",label:"Files",icon:Gs},{id:"terminal",label:"Terminal",icon:$r},{id:"git",label:"Git",icon:_t,showDot:f&&p>0}],[p,f]);Ae.useEffect(()=>{const U=Q=>{if(Es(Q)&&!Q.shiftKey&&!Q.altKey){const J=parseInt(Q.key,10);J>=1&&J<=_.length&&(Q.preventDefault(),d(_[J-1].id))}};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[_,d]);const V=(U,Q)=>{const J=c===U.id,K=U.icon,ne=U.id==="chat",X=U.id==="git";return e.jsxs(i.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(U.id),onMouseDown:J?I:void 0,className:R("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",J?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",J?"text-foreground":"text-muted-foreground",J&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",J&&ne&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",ne&&!(g&&b&&a)&&"border-l",X&&"border-r",ne&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...J&&ne&&a?{"--sidebar-w":g&&b?`${l}px`:"64px"}:{},...ne&&!(g&&b&&a)||X?{borderColor:"var(--interactive-border)"}:{}},"aria-label":U.label,"aria-selected":J,role:"tab",children:[f?e.jsx(K,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(K,{size:16}),e.jsx("span",{className:"header-tab-label",children:U.label})]}),ne&&!f&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(qi,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact"})}),U.badge!==void 0&&U.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:U.badge})]}),!Q&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},U.id)},Y=()=>e.jsxs("div",{onMouseDown:E,className:R("app-region-drag relative flex h-12 select-none items-center",D),role:"tablist","aria-label":"Main navigation",children:[!(g&&b)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:M,"aria-label":"Open sessions",className:`${A} mr-2.5`,children:e.jsx(Da,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:_.map((U,Q)=>V(U,Q===_.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:A,children:e.jsx(un,{className:"h-5 w-5"})})}),e.jsx(ct,{children:e.jsxs("p",{children:["Command Palette (",es(),"+K)"]})})]}),e.jsx(Yi,{headerIconButtonClass:A}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:A,children:e.jsx(on,{className:"h-5 w-5"})})}),e.jsx(ct,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",es(),"+.)"]})})]})]})]}),H=()=>e.jsxs("div",{className:"app-region-drag relative flex items-center justify-between gap-2 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:M,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open sessions",children:e.jsx(Ap,{className:"h-5 w-5"})}),N&&N.totalTokens>0&&c==="chat"&&e.jsx(qi,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact",isMobile:!0})]}),e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center",role:"tablist","aria-label":"Main navigation",children:_.map(U=>{const Q=c===U.id,J=U.icon;return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&C(),d(U.id)},"aria-label":U.label,"aria-selected":Q,role:"tab",className:R(A,"relative",Q&&"text-foreground"),children:[e.jsx(J,{className:"h-5 w-5"}),U.badge!==void 0&&U.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:U.badge}),U.showDot&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),e.jsx(ct,{children:e.jsx("p",{children:U.label})})]},U.id)})}),e.jsx(Yi,{headerIconButtonClass:A}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:S,"aria-label":"Open settings",className:R(A,"relative"),children:[e.jsx(nn,{className:"h-5 w-5"}),h&&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(ct,{children:e.jsx("p",{children:h?"Settings (Update available)":"Settings"})})]})]})]}),L=R("header-safe-area border-b relative z-10",g?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:y,className:L,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?H():Y()})};function Rl({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function Bm({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",s),...r})}function zm({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",s),...r})}function Wm({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:R("px-6",s),...r})}class is extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(Rl,{className:"w-full max-w-md",children:[e.jsx(Bm,{className:"text-center",children:e.jsxs(zm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(_i,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Wm,{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(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Os,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let Io=0;function us({...s}){return e.jsx(Ep,{"data-slot":"dialog",...s})}function Ib({...s}){return e.jsx(Tp,{"data-slot":"dialog-portal",...s})}const Hm=Ae.forwardRef(({className:s,...r},t)=>(Ae.useEffect(()=>(Io+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Io=Math.max(0,Io-1),Io===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Au,{ref:t,"data-slot":"dialog-overlay",className:R("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));Hm.displayName=Au.displayName;function ms({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Ib,{"data-slot":"dialog-portal",children:[e.jsx(Hm,{className:"rounded-none"}),e.jsxs(Ip,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:R("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",s),...o,children:[r,t&&e.jsxs(Pp,{"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(Gt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function hs({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",s),...r})}function tr({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",s),...r})}function gs({className:s,...r}){return e.jsx(Fp,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",s),...r})}function vs({className:s,...r}){return e.jsx(Rp,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",s),...r})}const Gc="https://github.com/btriapitsyn/openchamber/releases";async function Pb(){try{const s=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return s.ok?{success:!0}:{success:!1,error:(await s.json().catch(()=>({}))).error||`Server error: ${s.status}`}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Failed to install update"}}}async function Tb(s=30,r=2e3){for(let t=0;t<s;t++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,r))}return!1}const Xi=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Ae.useState(!1),[p,h]=Ae.useState("idle"),[y,g]=Ae.useState(null),w=t?.version?`${Gc}/tag/v${t.version}`:Gc,b=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",j=t?.updateCommand||"openchamber update";Ae.useEffect(()=>{s||(h("idle"),g(null))},[s]);const k=async()=>{try{await navigator.clipboard.writeText(j),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},x=Ae.useCallback(async()=>{h("updating"),g(null);const P=await Pb();if(!P.success){h("error"),g(P.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await Tb()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),N=p!=="idle"&&p!=="error";return e.jsx(us,{open:s,onOpenChange:N?void 0:r,children:e.jsxs(ms,{className:"max-w-md",children:[e.jsx(hs,{children:e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(Op,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(t?.currentVersion||t?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t?.currentVersion&&e.jsx("span",{className:"font-mono",children:t.currentVersion}),t?.currentVersion&&t?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),t?.version&&e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),v&&N&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ho,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[p==="updating"&&"Installing update...",p==="restarting"&&"Server restarting...",p==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),t?.body&&!N&&e.jsx(xt,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((P,C)=>/^\d+\.\d+\.\d+$/.test(P.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",P.trim(),`
82
+ `]},C):P.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(_p,{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:j}),e.jsx("button",{onClick:k,className:R("flex items-center justify-center p-2 rounded-md","text-muted-foreground hover:text-foreground hover:bg-accent","transition-colors",m&&"text-primary"),title:m?"Copied!":"Copy command",children:m?e.jsx(Bt,{className:"h-4 w-4"}):e.jsx(Eu,{className:"h-4 w-4"})})]})]}),!v&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[b,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${b}%`}})})]}),(l||y)&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:l||y})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(oa,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:c,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Or,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(Ho,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Os,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!N&&e.jsxs("button",{onClick:x,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Or,{className:"h-4 w-4"}),"Update Now"]}),v&&N&&e.jsxs("button",{disabled:!0,className:R("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(Ho,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},qc=264,Kc=200,Qc=500,Fb=40,Yc="openchamber:check-for-updates",Rb=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:l}=_e(),[c,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||qc),[f,p]=i.useState(!1),h=Ta(),y=i.useRef(!1),g=h.checkForUpdates,{available:w,downloaded:b,checking:v}=h,[j,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const S=typeof window.opencodeDesktop<"u";k(S)},[]),i.useEffect(()=>{if(typeof window>"u")return;const S=()=>{typeof window.opencodeDesktop<"u"&&(y.current=!0,g())};return window.addEventListener(Yc,S),()=>{window.removeEventListener(Yc,S)}},[g]),i.useEffect(()=>{y.current&&(v||(w||b?p(!0):Z.success("No updates available",{description:"You are running the latest version."}),y.current=!1))},[w,b,v]),i.useEffect(()=>{if(r||!c)return;const S=D=>{const F=D.clientX-u.current,E=Math.min(Qc,Math.max(Kc,m.current+F));o(E)},A=()=>{d(!1)};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",A,{once:!0}),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",A)}},[r,c,o]),i.useEffect(()=>{r&&c&&d(!1)},[r,c]);const N=i.useCallback(async S=>{if(S.button===0&&j)try{const{getCurrentWindow:A}=await ls(async()=>{const{getCurrentWindow:F}=await import("./vendor-.bun-w0O-Y8Mh.js").then(E=>E.cB);return{getCurrentWindow:F}},__vite__mapDeps([0,1]));await A().startDragging()}catch(A){console.error("Failed to start window dragging from sidebar:",A)}},[j]);if(r)return null;const P=s?Math.min(Qc,Math.max(Kc,n||qc)):0,C=j&&x,M=S=>{s&&(d(!0),u.current=S.clientX,m.current=P,S.preventDefault())};return e.jsxs("aside",{className:R("relative flex h-full overflow-hidden border-r",j?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",c?"transition-none":"",!s&&"border-r-0"),style:{width:`${P}px`,minWidth:`${P}px`,maxWidth:`${P}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||P===0,children:[s&&e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",c?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:M,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:R("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!s&&"pointer-events-none select-none opacity-0"),style:{width:`${P}px`,overflowX:"hidden"},"aria-hidden":!s,children:[C&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Fb}px`},onMouseDown:N,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(is,{children:t})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:R("flex items-center gap-2 rounded-md px-3 py-2","text-sm font-semibold text-muted-foreground","hover:text-foreground","transition-colors"),children:[e.jsx(nn,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),w||b?e.jsxs("button",{onClick:()=>p(!0),className:R("flex items-center gap-1.5 rounded-md px-2.5 py-1.5","text-xs font-medium","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(Or,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!j&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>l(!0),className:R("flex items-center justify-center rounded-md p-1.5","text-muted-foreground","hover:text-foreground hover:bg-muted/50","transition-colors"),children:e.jsx(cs,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Xi,{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 Ol({className:s,...r}){return e.jsx(mn,{"data-slot":"command",className:R("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function Ob({title:s="Command Palette",description:r="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(us,{...a,children:[e.jsxs(hs,{className:"sr-only",children:[e.jsx(gs,{children:s}),e.jsx(vs,{children:r})]}),e.jsx(ms,{className:R("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Ol,{className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta",children:t})})]})}function _l({className:s,...r}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(Xs,{className:"size-4 shrink-0 opacity-50"}),e.jsx(mn.Input,{"data-slot":"command-input",className:R("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",s),...r})]})}function $l({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(xt,{as:mn.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:R("scroll-py-1 overflow-x-hidden h-full min-h-0",s),scrollbarClassName:t??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:r})}function Ll({...s}){return e.jsx(mn.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function tn({className:s,...r}){return e.jsx(mn.Group,{"data-slot":"command-group",className:R("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",s),...r})}function ba({className:s,...r}){return e.jsx(mn.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",s),...r})}function as({className:s,...r}){return e.jsx(mn.Item,{"data-slot":"command-item",className:R("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...r})}function yr({className:s,...r}){const t=a=>{const l=a.trim().toLowerCase();return l==="ctrl"||l==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):l==="cmd"||l==="⌘"||l==="command"||l==="meta"?e.jsx(un,{className:"size-3.5"}):l==="shift"||l==="⇧"?e.jsx(po,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof r.children=="string"?r.children:"",o=n?n.split("+").map(a=>a.trim()).filter(Boolean):[];return e.jsx("span",{"data-slot":"command-shortcut",className:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,l)=>e.jsxs(Ae.Fragment,{children:[l>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${l}`)):r.children})}const Xc=["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"],Jc=["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 _b(){const s=Xc[Math.floor(Math.random()*Xc.length)],r=Jc[Math.floor(Math.random()*Jc.length)];return`${s}-${r}`}function Zc(s){const r=_b();return s&&s.trim()?`${s.trim().replace(/\/+$/,"")}/${r}`:r}async function $b(s,r,t=10){let n;try{const o=await _a(s);n=new Set(o?.all??[])}catch{return Zc(r)}for(let o=0;o<t;o++){const a=Zc(r);if(!n.has(a))return a}return null}const Um=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Mn=!1;async function za(){if(Mn)return null;const s=Lt.getState().getActiveProject();if(!s?.path)return Z.error("No active project",{description:"Please select a project first."}),null;const r=s.path;let t=!1;try{t=await Ur(r)}catch{}if(!t)return Z.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Mn=!0,_s("Creating new worktree session...");try{const n=s.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,l=await $b(r,o);if(!l)return Z.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const c=Um(l),u=await jl({projectDirectory:r,worktreeSlug:c,branch:l,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await $a(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=he.getState(),h=await p.createSession(void 0,u.path);if(!h)return await vm({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),Z.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const y=nt.getState(),g=y.agents;p.initializeNewOpenChamberSession(h.id,g),p.setSessionDirectory(h.id,u.path),p.setWorktreeMetadata(h.id,f);try{const v=y.getVisibleAgents();let j;if(y.settingsDefaultAgent){const k=v.find(x=>x.name===y.settingsDefaultAgent);k&&(j=k.name)}if(j||(j=v.find(k=>k.name==="build")?.name||v[0]?.name),j){y.setAgent(j),gt.getState().saveSessionAgentSelection(h.id,j);const k=y.settingsDefaultModel;if(k){const x=k.split("/");if(x.length===2){const[N,P]=x;if(y.getModelMetadata(N,P)){gt.getState().saveSessionModelSelection(h.id,N,P),gt.getState().saveAgentModelForSession(h.id,j,N,P);const M=y.settingsDefaultVariant;if(M){const D=y.providers.find(F=>F.id===N)?.models.find(F=>F.id===P)?.variants;D&&Object.prototype.hasOwnProperty.call(D,M)&&(y.setCurrentVariant(M),gt.getState().saveAgentModelVariantForSession(h.id,j,N,P,M))}}}}}}catch{}yt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const b=(await Ln(r)).filter(v=>v.trim().length>0);return b.length>0?(Z.success("Worktree created",{description:`Branch: ${l}. Running ${b.length} setup command${b.length===1?"":"s"}...`}),Sl(u.path,r,b).then(v=>{if(v.success)Z.success("Setup commands completed",{description:`All ${v.results.length} command${v.results.length===1?"":"s"} succeeded.`});else{const j=v.results.filter(x=>!x.success),k=v.results.filter(x=>x.success);Z.error("Setup commands failed",{description:`${j.length} of ${v.results.length} command${v.results.length===1?"":"s"} failed.`+(k.length>0?` ${k.length} succeeded.`:"")})}}).catch(()=>{Z.error("Setup commands failed",{description:"Could not execute setup commands."})})):Z.success("Worktree created",{description:`Branch: ${l}`}),h}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return Z.error("Failed to create worktree",{description:o}),null}finally{ks(),Mn=!1}}async function Lb(s,r){if(Mn)return null;let t=!1;try{t=await Ur(s)}catch{}if(!t)return Z.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Mn=!0,_s("Creating worktree session...");try{const n=Um(r),o=await jl({projectDirectory:s,worktreeSlug:n,branch:r,createBranch:!1}),a=await $a(o.path).catch(()=>{}),l=a?{...o,status:a}:o,c=he.getState(),d=await c.createSession(void 0,o.path);if(!d)return await vm({projectDirectory:s,path:o.path,force:!0}).catch(()=>{}),Z.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const u=nt.getState(),m=u.agents;c.initializeNewOpenChamberSession(d.id,m),c.setSessionDirectory(d.id,o.path),c.setWorktreeMetadata(d.id,l);try{const h=u.getVisibleAgents();let y;if(u.settingsDefaultAgent){const g=h.find(w=>w.name===u.settingsDefaultAgent);g&&(y=g.name)}if(y||(y=h.find(g=>g.name==="build")?.name||h[0]?.name),y){u.setAgent(y),gt.getState().saveSessionAgentSelection(d.id,y);const g=u.settingsDefaultModel;if(g){const w=g.split("/");if(w.length===2){const[b,v]=w;if(u.getModelMetadata(b,v)){gt.getState().saveSessionModelSelection(d.id,b,v),gt.getState().saveAgentModelForSession(d.id,y,b,v);const k=u.settingsDefaultVariant;if(k){const P=u.providers.find(C=>C.id===b)?.models.find(C=>C.id===v)?.variants;P&&Object.prototype.hasOwnProperty.call(P,k)&&(u.setCurrentVariant(k),gt.getState().saveAgentModelVariantForSession(d.id,y,b,v,k))}}}}}}catch{}yt.getState().setDirectory(o.path,{showOverlay:!1});try{await c.loadSessions()}catch{}const p=(await Ln(s)).filter(h=>h.trim().length>0);return p.length>0?(Z.success("Worktree created",{description:`Branch: ${r}. Running ${p.length} setup command${p.length===1?"":"s"}...`}),Sl(o.path,s,p).then(h=>{if(h.success)Z.success("Setup commands completed",{description:`All ${h.results.length} command${h.results.length===1?"":"s"} succeeded.`});else{const y=h.results.filter(w=>!w.success),g=h.results.filter(w=>w.success);Z.error("Setup commands failed",{description:`${y.length} of ${h.results.length} command${h.results.length===1?"":"s"} failed.`+(g.length>0?` ${g.length} succeeded.`:"")})}}).catch(()=>{Z.error("Setup commands failed",{description:"Could not execute setup commands."})})):Z.success("Worktree created",{description:`Branch: ${r}`}),d}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return Z.error("Failed to create worktree",{description:o}),null}finally{ks(),Mn=!1}}const Bb=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:l,toggleSidebar:c}=_e(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=he(),f=nt(I=>I.settingsAutoCreateWorktree),{currentDirectory:p}=yt(),{themeMode:h,setThemeMode:y}=Vr(),g=()=>{r(!1)},w=async()=>{n("chat"),a(!1),d(),g()},b=I=>{u(I),g()},v=I=>{y(I),g()},j=()=>{t(!0),g()},k=()=>{g(),za()},{isMobile:x}=Ht(),N=()=>{if(x){const{isSessionSwitcherOpen:I}=_e.getState();a(!I)}else c();g()},P=()=>{n("diff"),g()},C=()=>{n("git"),g()},M=()=>{n("terminal"),g()},S=()=>{o(!0),g()},A=()=>{Jn(),g()},D=()=>{l(!0),g()},F=m(p??""),E=i.useMemo(()=>F.slice(0,5),[F]);return e.jsxs(Ob,{open:s,onOpenChange:r,children:[e.jsx(_l,{placeholder:"Type a command or search..."}),e.jsxs($l,{children:[e.jsx(Ll,{children:"No results found."}),e.jsxs(tn,{heading:"Actions",children:[e.jsxs(as,{onSelect:N,children:[e.jsx(Da,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(yr,{children:[es()," + L"]})]}),e.jsxs(as,{onSelect:w,children:[e.jsx(Zt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(yr,{children:f?`Shift + ${es()} + N`:`${es()} + N`})]}),e.jsxs(as,{onSelect:k,children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(yr,{children:f?`${es()} + N`:`Shift + ${es()} + N`})]}),e.jsxs(as,{onSelect:j,children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(yr,{children:[es()," + ."]})]}),e.jsxs(as,{onSelect:P,children:[e.jsx($s,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(yr,{children:[es()," + 2"]})]}),e.jsxs(as,{onSelect:M,children:[e.jsx($r,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(yr,{children:[es()," + 3"]})]}),e.jsxs(as,{onSelect:C,children:[e.jsx(_t,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(yr,{children:[es()," + 4"]})]}),e.jsxs(as,{onSelect:D,children:[e.jsx(fr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(yr,{children:[es()," + T"]})]}),e.jsxs(as,{onSelect:S,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(yr,{children:[es()," + ,"]})]}),e.jsxs(as,{onSelect:A,children:[e.jsx(Os,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(ba,{}),e.jsxs(tn,{heading:"Theme",children:[e.jsxs(as,{onSelect:()=>v("light"),children:[e.jsx($p,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),h==="light"&&e.jsx(Bt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(as,{onSelect:()=>v("dark"),children:[e.jsx(Lp,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),h==="dark"&&e.jsx(Bt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(as,{onSelect:()=>v("system"),children:[e.jsx(Iu,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),h==="system"&&e.jsx(Bt,{className:"ml-auto h-4 w-4"})]})]}),E.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ba,{}),e.jsx(tn,{heading:"Recent Sessions",children:E.map(I=>e.jsxs(as,{onSelect:()=>b(I.id),children:[e.jsx(dl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:I.title||"Untitled Session"})]},I.id))})]})]})]})},zb=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Aa,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(un,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},Wb=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(i.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),zb(t,n)]},`${t}-${n}`))},Hb=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=_e(),t=nt(a=>a.settingsAutoCreateWorktree),n=es(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:un},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:on},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:Da},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:an},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:Pu},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:pr}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:t?"Create New Session in Worktree":"Create New Session",icon:t?_t:Zt},{keys:[`Shift + ${n} + N`],description:t?"Create New Session":"Create New Session in Worktree",icon:t?Zt:_t},{keys:[`${n} + I`],description:"Focus Chat Input",icon:Tu},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:An}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Bp},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:$s},{keys:[`${n} + 3`],description:"Open Files",icon:Gs},{keys:[`${n} + 4`],description:"Open Terminal",icon:$r},{keys:[`${n} + 5`],description:"Open Git Panel",icon:_t},{keys:[`${n} + T`],description:"Open Timeline",icon:fr},{keys:[`${n} + ,`],description:"Open Settings",icon:nn}]}];return e.jsx(us,{open:s,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(hs,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(vs,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((l,c)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.icon&&e.jsx(l.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:l.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l.keys)?l.keys:l.keys.split(" / ")).map((d,u)=>e.jsxs(i.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:Wb(d)})]},`${d}-${u}`))})]},c))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(on,{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"})]})]})]})})]})]})})},Ub={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"}},Vb=({className:s,size:r="md"})=>{const t=Ub[r];return e.jsx("div",{className:R("grid grid-cols-3",t.container,s),"aria-label":"Loading",children:Array.from({length:9},(n,o)=>e.jsx("div",{className:R("rounded-full bg-current animate-grid-pulse",t.dot),style:{animationDelay:`${(o%3+Math.floor(o/3))*150}ms`}},o))})},mi=new Set,fi=new Set,pi=new Set,Fn={onDeleteRequest(s){return mi.add(s),()=>{mi.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||mi.forEach(r=>r(s))},onCreateRequest(s){return fi.add(s),()=>{fi.delete(s)}},requestCreate(s){const r=s??{};fi.forEach(t=>t(r))},onDirectoryRequest(s){return pi.add(s),()=>{pi.delete(s)}},requestDirectoryDialog(){pi.forEach(s=>s())}};function Vm(s){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...s,children:e.jsx("path",{d:"M232.49,192.49l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,0,1,17-17L180,187V141L128,89,76,141V187l11.51-11.52a12,12,0,0,1,17,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L52,187V136a12,12,0,0,1,3.51-8.49L116,67V24a12,12,0,0,1,24,0V67l60.49,60.48A12,12,0,0,1,204,136v51l11.51-11.52a12,12,0,0,1,17,17Z",transform:"rotate(180 128 128)"})})}function kt({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:R("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",s),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...t})}function Gb({open:s,onOpenChange:r,projects:t,activeProjectId:n}){const[o,a]=i.useState(""),[l,c]=i.useState(new Map),[d,u]=i.useState(new Set),[m,f]=i.useState(null);i.useEffect(()=>{if(!s){a("");return}const w=t.find(b=>b.id===n);w&&u(new Set([w.id])),t.forEach(async b=>{c(v=>{const j=new Map(v);return j.set(b.id,{branches:null,worktrees:[],loading:!0,error:null}),j});try{const[v,j]=await Promise.all([_a(b.path),um(b.path)]);c(k=>{const x=new Map(k);return x.set(b.id,{branches:v,worktrees:j,loading:!1,error:null}),x})}catch(v){c(j=>{const k=new Map(j);return k.set(b.id,{branches:null,worktrees:[],loading:!1,error:v instanceof Error?v.message:"Failed to load"}),k})}})},[s,t,n]);const p=w=>{u(b=>{const v=new Set(b);return v.has(w)?v.delete(w):v.add(w),v})},h=async(w,b)=>{const v=`${w.id}:${b}`;f(v);try{await Lb(w.path,b),r(!1)}catch(j){console.error("Failed to create worktree:",j)}finally{f(null)}},y=(w,b)=>{if(!b.trim())return w;const v=b.toLowerCase();return w.filter(j=>j.toLowerCase().includes(v))},g=t.filter(w=>{const b=l.get(w.id);return b&&!b.error&&(b.loading||b.branches)});return e.jsx(us,{open:s,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[70vh] flex flex-col overflow-hidden gap-3",children:[e.jsxs(hs,{className:"flex-shrink-0",children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"h-5 w-5"}),"Branches & Worktrees"]}),e.jsx(vs,{children:"Start a new worktree session from any local branch"})]}),e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Xs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(kt,{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 b=l.get(w.id),v=d.has(w.id),j=b?.branches,k=b?.worktrees||[],x=new Set(k.map(M=>M.branch).filter(Boolean)),N=j?.all||[],C=y(N,o).filter(M=>!M.startsWith("remotes/")).filter(M=>!x.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(Is,{className:R("h-4 w-4 text-muted-foreground transition-transform",v&&"rotate-90")}),e.jsx(Js,{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}),b?.loading&&e.jsx(ts,{className:"h-4 w-4 text-muted-foreground animate-spin"}),j&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[C.length," branches"]})]}),v&&e.jsx("div",{className:"mt-1 space-y-1 pl-6",children:b?.loading?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:"Loading branches..."}):b?.error?e.jsx("div",{className:"px-2 py-2 text-destructive text-sm",children:b.error}):C.length===0?e.jsx("div",{className:"px-2 py-2 text-muted-foreground text-sm",children:o?"No matching branches":"No branches found"}):C.map(M=>{const S=j?.branches[M],A=S?.current,D=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(_t,{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:R("text-sm truncate",A&&"font-medium text-primary"),children:M}),A&&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:[S?.commit&&e.jsx("span",{className:"font-mono",children:S.commit.slice(0,7)}),S?.ahead!==void 0&&S.ahead>0&&e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["↑",S.ahead]}),S?.behind!==void 0&&S.behind>0&&e.jsxs("span",{className:"text-[color:var(--status-warning)]",children:["↓",S.behind]})]})]}),e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:()=>h(w,M),disabled:D,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:D?e.jsx(ts,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Zt,{className:"h-3.5 w-3.5 mr-1"}),"Worktree"]})})}),e.jsx(ct,{side:"left",children:"Create worktree for this branch"})]})]},M)})})]},w.id)})})})]})})}const ed="oc.sessions.projectCollapse",td="oc.sessions.expandedParents",sd=s=>{const r=new Date(s),t=new Date,n=(l,c)=>l.getFullYear()===c.getFullYear()&&l.getMonth()===c.getMonth()&&l.getDate()===c.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),n(r,t)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},ar=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},rd=s=>s.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),qb=({id:s,projectLabel:r,projectDescription:t,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:l,isDesktopRuntime:c,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:h,onNewWorktreeSession:y,onOpenBranchPicker:g,onOpenMultiRunLauncher:w,onClose:b,sentinelRef:v,children:j,settingsAutoCreateWorktree:k})=>{const{attributes:x,listeners:N,setNodeRef:P,isDragging:C}=Zp({id:s}),[M,S]=i.useState(!1);return e.jsxs("div",{ref:P,className:R("relative",C&&"opacity-40"),children:[c&&e.jsx("div",{ref:v,"data-project-id":s,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:R("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b select-none",!c&&"bg-sidebar"),style:{backgroundColor:c?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:l?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),onContextMenu:A=>{A.preventDefault(),S(!0)},children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...x,children:[e.jsxs(dt,{delayDuration:1500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...N,className:"flex-1 min-w-0 flex items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-sm cursor-grab active:cursor-grabbing",children:e.jsx("span",{className:R("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(ct,{side:"right",sideOffset:8,children:t})]}),e.jsxs(Yt,{open:M,onOpenChange:S,children:[e.jsx(Xt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",m?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:A=>A.stopPropagation(),children:e.jsx(Lr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"min-w-[180px]",children:[a&&!u&&k&&h&&e.jsxs(It,{onClick:h,children:[e.jsx(Zt,{className:"mr-1.5 h-4 w-4"}),"New Session"]}),a&&!u&&!k&&y&&e.jsxs(It,{onClick:y,children:[e.jsx(_t,{className:"mr-1.5 h-4 w-4"}),"New Session in Worktree"]}),a&&!u&&g&&e.jsxs(It,{onClick:g,children:[e.jsx(Fu,{className:"mr-1.5 h-4 w-4"}),"Browse Branches"]}),a&&!u&&e.jsxs(It,{onClick:w,children:[e.jsx(Vm,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(It,{onClick:b,className:"text-destructive focus:text-destructive",children:[e.jsx(Gt,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),a&&!u&&y&&k&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),y()},className:R("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(_t,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session in worktree"})})]}),(!k||!a)&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:A=>{A.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(Zt,{className:"h-4 w-4"})})}),e.jsx(ct,{side:"bottom",sideOffset:4,children:e.jsx("p",{children:"New session"})})]})]})}),j]})},Kb=({projectLabel:s,isActiveProject:r})=>e.jsx("div",{className:"bg-sidebar border border-border rounded-md shadow-lg px-2 py-1.5",style:{width:"max-content",maxWidth:"280px"},children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:R("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:s})})}),va=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,l]=i.useState(null),[c,d]=i.useState(""),[u,m]=i.useState(null),f=i.useRef(null),[p,h]=i.useState(new Set),[y,g]=i.useState(()=>new Map),w=i.useRef(new Set),b=i.useMemo(()=>ps(),[]),[v,j]=i.useState(new Set),[k,x]=i.useState(new Map),[N,P]=i.useState(new Set),[C,M]=i.useState(null),[S,A]=i.useState(!1),[D,F]=i.useState(null),[E,I]=i.useState(new Set),[_,V]=i.useState(null),Y=i.useRef(new Map),H=i.useRef(0),L=yt(B=>B.homeDirectory),U=yt(B=>B.currentDirectory),Q=yt(B=>B.setDirectory),J=Lt(B=>B.projects),K=Lt(B=>B.activeProjectId),ne=Lt(B=>B.addProject),X=Lt(B=>B.removeProject),ae=Lt(B=>B.setActiveProject),O=Lt(B=>B.setActiveProjectIdOnly),z=Lt(B=>B.reorderProjects),T=_e(B=>B.setActiveMainTab),$=_e(B=>B.setSessionSwitcherOpen),W=_e(B=>B.openMultiRunLauncher),q=nt(B=>B.settingsAutoCreateWorktree),ue=he(B=>B.sessions),oe=he(B=>B.sessionsByDirectory),de=he(B=>B.currentSessionId),je=he(B=>B.setCurrentSession),Se=he(B=>B.updateSessionTitle),Le=he(B=>B.shareSession),G=he(B=>B.unshareSession),ee=he(B=>B.sessionMemoryState),te=he(B=>B.sessionActivityPhase),xe=he(B=>B.permissions),me=he(B=>B.worktreeMetadata),Te=he(B=>B.availableWorktreesByProject),Ne=he(B=>B.getSessionsByDirectory),Be=he(B=>B.openNewSessionDraft),[fe,ht]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),bt=i.useMemo(()=>zt(),[]);i.useEffect(()=>{try{const B=b.getItem(td);if(B){const ye=JSON.parse(B);Array.isArray(ye)&&h(new Set(ye.filter($e=>typeof $e=="string")))}const ce=b.getItem(ed);if(ce){const ye=JSON.parse(ce);Array.isArray(ye)&&j(new Set(ye.filter($e=>typeof $e=="string")))}}catch{}},[b]),i.useEffect(()=>{typeof window>"u"||ht(typeof window.opencodeDesktop<"u")},[]);const Nt=i.useMemo(()=>[...ue].sort((B,ce)=>(ce.time?.updated||0)-(B.time?.updated||0)),[ue]);i.useEffect(()=>{let B=!1;const ce=J.map(ye=>({id:ye.id,path:ar(ye.path)})).filter(ye=>!!ye.path);return x(new Map),ce.length===0?()=>{B=!0}:(ce.forEach(ye=>{Ur(ye.path).then($e=>{B||x(Ue=>{const st=new Map(Ue);return st.set(ye.id,$e),st})}).catch(()=>{B||x($e=>{const Ue=new Map($e);return Ue.set(ye.id,null),Ue})})}),()=>{B=!0})},[J]);const Me=i.useMemo(()=>{const B=new Map;return Nt.forEach(ce=>{const ye=ce.parentID;ye&&B.set(ce.id,ye)}),B},[Nt]),re=i.useMemo(()=>{const B=new Map;return Nt.forEach(ce=>{const ye=ce.parentID;if(!ye)return;const $e=B.get(ye)??[];$e.push(ce),B.set(ye,$e)}),B.forEach(ce=>ce.sort((ye,$e)=>($e.time?.updated||0)-(ye.time?.updated||0))),B},[Nt]);i.useEffect(()=>{de&&h(B=>{const ce=new Set(B);let ye=Me.get(de)||null,$e=!1;for(;ye;)ce.has(ye)||(ce.add(ye),$e=!0),ye=Me.get(ye)||null;return $e?ce:B})},[de,Me]),i.useEffect(()=>{const B=new Set;Nt.forEach(ce=>{const ye=ar(ce.directory??null);ye&&B.add(ye)}),J.forEach(ce=>{const ye=ar(ce.path);ye&&B.add(ye)}),B.forEach(ce=>{const ye=y.get(ce);ye&&ye!=="unknown"||w.current.has(ce)||(w.current.add(ce),Ee.listLocalDirectory(ce).then(()=>{g($e=>{const Ue=new Map($e);return Ue.get(ce)==="exists"?$e:(Ue.set(ce,"exists"),Ue)})}).catch(()=>{g($e=>{const Ue=new Map($e);return Ue.get(ce)==="missing"?$e:(Ue.set(ce,"missing"),Ue)})}).finally(()=>{w.current.delete(ce)}))})},[Nt,J,y]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const et=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."})]}),be=i.useCallback((B,ce,ye,$e)=>{if(!ye){if($e&&$e!==K&&O($e),ce&&ce!==U&&Q(ce,{showOverlay:!1}),s&&(T("chat"),$(!1)),!t&&B===de){r?.(B);return}je(B),r?.(B)}},[K,t,U,de,s,r,T,O,je,Q,$]),we=i.useCallback(async()=>{a&&c.trim()&&(await Se(a,c.trim()),l(null),d(""))},[a,c,Se]),Ve=i.useCallback(()=>{l(null),d("")},[]),tt=i.useCallback(async B=>{const ce=await Le(B.id);ce&&ce.share?.url?Z.success("Session shared",{description:"You can copy the link from the menu."}):Z.error("Unable to share session")},[Le]),We=i.useCallback((B,ce)=>{navigator.clipboard.writeText(B).then(()=>{m(ce),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{Z.error("Failed to copy URL")})},[]),Oe=i.useCallback(async B=>{await G(B)?Z.success("Session unshared"):Z.error("Unable to unshare session")},[G]),rt=i.useCallback(B=>{const ce=[],ye=$e=>{(re.get($e)??[]).forEach(st=>{ce.push(st),ye(st.id)})};return ye(B),ce},[re]),vt=he(B=>B.deleteSession),mt=he(B=>B.deleteSessions),Tt=i.useCallback(async B=>{const ce=rt(B.id),ye=me.get(B.id);if(ye){const $e=ye.path,Ue=[],st=new Set;ue.forEach(ke=>{const Ye=me.get(ke.id);Ye&&Ye.path===$e&&!st.has(ke.id)&&(Ue.push(ke),st.add(ke.id),rt(ke.id).forEach(ot=>{st.has(ot.id)||(Ue.push(ot),st.add(ot.id))}))}),Fn.requestDelete({sessions:Ue,mode:"worktree",worktree:ye});return}if(ce.length===0)await vt(B.id)?Z.success("Session deleted"):Z.error("Failed to delete session");else{const $e=[B.id,...ce.map(ke=>ke.id)],{deletedIds:Ue,failedIds:st}=await mt($e);Ue.length>0&&Z.success(`Deleted ${Ue.length} session${Ue.length===1?"":"s"}`),st.length>0&&Z.error(`Failed to delete ${st.length} session${st.length===1?"":"s"}`)}},[rt,vt,mt,me,ue]),Ot=i.useCallback(()=>{fe&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(B=>{B.success&&B.path?ne(B.path,{id:B.projectId})||Z.error("Failed to add project",{description:"Please select a valid directory."}):B.error&&B.error!=="Directory selection cancelled"&&Z.error("Failed to select directory",{description:B.error})}).catch(B=>{console.error("Desktop: Error selecting directory:",B),Z.error("Failed to select directory")}):Fn.requestDirectoryDialog()},[ne,fe]),ve=i.useCallback(B=>{h(ce=>{const ye=new Set(ce);ye.has(B)?ye.delete(B):ye.add(B);try{b.setItem(td,JSON.stringify(Array.from(ye)))}catch{}return ye})},[b]),He=i.useCallback(B=>{const ce=re.get(B.id)??[];return{session:B,children:ce.map(ye=>He(ye)),worktree:me.get(B.id)??null}},[re,me]),Je=i.useCallback((B,ce,ye)=>{const $e=ar(ce??null),Ue=[...B].sort((jt,Ct)=>(Ct.time?.updated||0)-(jt.time?.updated||0)),st=new Map(Ue.map(jt=>[jt.id,jt])),ke=new Map;Ue.forEach(jt=>{const Ct=jt.parentID;if(!Ct)return;const Ut=ke.get(Ct)??[];Ut.push(jt),ke.set(Ct,Ut)}),ke.forEach(jt=>jt.sort((Ct,Ut)=>(Ut.time?.updated||0)-(Ct.time?.updated||0)));const Ye=new Map;ye.forEach(jt=>{if(jt.path){const Ct=ar(jt.path)??jt.path;Ye.set(Ct,jt)}});const Ze=jt=>{const Ct=ar(jt.directory??null),Ut=me.get(jt.id)??null;if(Ut)return Ut;if(Ct){const As=Ye.get(Ct)??null;if(As&&Ct!==$e)return As}return null},ot=jt=>{const Ct=ke.get(jt.id)??[];return{session:jt,children:Ct.map(Ut=>ot(Ut)),worktree:Ze(jt)}},Wt=Ue.filter(jt=>{const Ct=jt.parentID;return Ct?!st.has(Ct):!0}).map(jt=>ot(jt));return[{id:"all",label:"All sessions",description:$e?Zr($e,L):null,isMain:!0,worktree:null,directory:$e,sessions:Wt}]},[L,me]),Qe=i.useCallback(B=>{P(ce=>{const ye=new Set(ce);return ye.has(B)?ye.delete(B):ye.add(B),ye})},[]),ft=i.useCallback(B=>{H.current=Date.now()+150,j(ce=>{const ye=new Set(ce);ye.has(B)?ye.delete(B):ye.add(B);try{b.setItem(ed,JSON.stringify(Array.from(ye)))}catch{}return ye})},[b]),it=i.useMemo(()=>J.map(B=>({...B,normalizedPath:ar(B.path)})).filter(B=>!!B.normalizedPath),[J]),Pe=i.useCallback(B=>{const ce=bt?[]:Te.get(B.normalizedPath)??[],ye=[B.normalizedPath,...ce.map(st=>ar(st.path)??st.path).filter(st=>!!st)],$e=new Set,Ue=[];return ye.forEach(st=>{(oe.get(st)??Ne(st)).forEach(Ye=>{$e.has(Ye.id)||($e.add(Ye.id),Ue.push(Ye))})}),Ue},[Te,Ne,oe,bt]),ze=i.useMemo(()=>it.map(B=>{const ce=Pe(B),ye=Te.get(B.normalizedPath)??[],$e=Je(ce,B.normalizedPath,ye);return{project:B,groups:$e}}),[it,Pe,Je,Te]);i.useEffect(()=>{if(!fe)return;const B=new IntersectionObserver(ce=>{ce.forEach(ye=>{const $e=ye.target.dataset.projectId;$e&&I(Ue=>{const st=new Set(Ue);return ye.isIntersecting?st.delete($e):st.add($e),st})})},{threshold:0});return Y.current.forEach(ce=>{ce&&B.observe(ce)}),()=>B.disconnect()},[fe,ze]);const lt=i.useCallback((B,ce=0,ye,$e)=>{const Ue=B.session,st=ar(Ue.directory??null)??ar(ye??null),Ye=(st?y.get(st):null)==="missing",Ze=ee.get(Ue.id),ot=de===Ue.id,$t=Ue.title||"Untitled Session",Wt=B.children.length>0,jt=p.has(Ue.id),Ct=Ue.summary?.additions,Ut=Ue.summary?.deletions,As=typeof Ct=="number"||typeof Ut=="number";if(a===Ue.id)return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",ce>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:Vt=>{Vt.preventDefault(),we()},children:[e.jsx("input",{value:c,onChange:Vt=>d(Vt.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:Vt=>{Vt.key==="Escape"&&Ve()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Bt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Ve,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Gt,{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:[Wt?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:jt?e.jsx(Ft,{className:"h-3 w-3"}):e.jsx(Is,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:sd(Ue.time?.created||Date.now())}),Ue.share?e.jsx(Qa,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,As&&((Ct??0)!==0||(Ut??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,Ct??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ut??0)]})]}):null,Wt?e.jsxs("span",{className:"truncate",children:[B.children.length," ",B.children.length===1?"task":"tasks"]}):null]})]})},Ue.id);const sr=te?.get(Ue.id)??"idle",rr=sr==="busy"||sr==="cooldown",Cr=xe.get(Ue.id)?.length??0,Bn=Ze&&Ze.isZombie?e.jsx(_i,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(i.Fragment,{children:[e.jsx("div",{className:R("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",Ye?"opacity-75":"",ce>0&&"pl-[20px]"),onContextMenu:Vt=>{Vt.preventDefault(),V(Ue.id)},children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:Ye,onClick:()=>be(Ue.id,st,Ye,$e),className:R("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[rr?e.jsx(Vb,{size:"xs",className:"text-primary flex-shrink-0"}):null,e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:$t}),Cr>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(zp,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:Cr})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Wt?e.jsx("span",{role:"button",tabIndex:0,onClick:Vt=>{Vt.stopPropagation(),ve(Ue.id)},onKeyDown:Vt=>{(Vt.key==="Enter"||Vt.key===" ")&&(Vt.preventDefault(),Vt.stopPropagation(),ve(Ue.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":jt?"Collapse subsessions":"Expand subsessions",children:jt?e.jsx(Ft,{className:"h-3 w-3"}):e.jsx(Is,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:sd(Ue.time?.created||Date.now())}),Ue.share?e.jsx(Qa,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,B.worktree?e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(_t,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(ct,{side:"top",className:"text-xs",children:B.worktree.branch||B.worktree.label||"Worktree"})]}):null,As&&((Ct??0)!==0||(Ut??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,Ct??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ut??0)]})]}):null,Wt?e.jsxs("span",{className:"truncate",children:[B.children.length," ",B.children.length===1?"task":"tasks"]}):null,Ye?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(_i,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Bn,e.jsxs(Yt,{open:_===Ue.id,onOpenChange:Vt=>V(Vt?Ue.id:null),children:[e.jsx(Xt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:Vt=>Vt.stopPropagation(),onKeyDown:Vt=>Vt.stopPropagation(),children:e.jsx(Lr,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(It,{onClick:()=>{l(Ue.id),d($t)},className:"[&>svg]:mr-1",children:[e.jsx(br,{className:"mr-1 h-4 w-4"}),"Rename"]}),Ue.share?e.jsxs(e.Fragment,{children:[e.jsx(It,{onClick:()=>{Ue.share?.url&&We(Ue.share.url,Ue.id)},className:"[&>svg]:mr-1",children:u===Ue.id?e.jsxs(e.Fragment,{children:[e.jsx(Bt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(er,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(It,{onClick:()=>Oe(Ue.id),className:"[&>svg]:mr-1",children:[e.jsx(Wp,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(It,{onClick:()=>tt(Ue),className:"[&>svg]:mr-1",children:[e.jsx(Qa,{className:"mr-1 h-4 w-4"}),"Share"]}),B.worktree?e.jsxs(It,{onClick:()=>{$e&&$e!==K&&ae($e),T("chat"),s&&$(!1),Be({directoryOverride:B.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(_t,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(It,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Tt(Ue),children:[e.jsx(Bs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Wt&&jt?B.children.map(Vt=>lt(Vt,ce+1,st??ye,$e)):null]},Ue.id)},[y,ee,te,xe,de,p,a,c,we,Ve,ve,be,tt,We,Oe,Tt,u,s,K,ae,T,$,Be,_]),Ke=i.useCallback((B,ce,ye)=>{const $e=N.has(ce),Ue=n?10:5,st=B.sessions.length,ke=$e?B.sessions:B.sessions.slice(0,Ue),Ye=st-ke.length;return e.jsxs(e.Fragment,{children:[ke.map(Ze=>lt(Ze,0,B.directory,ye)),st===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,Ye>0&&!$e?e.jsxs("button",{type:"button",onClick:()=>Qe(ce),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 ",Ye," more ",Ye===1?"session":"sessions"]}):null,$e&&st>Ue?e.jsx("button",{type:"button",onClick:()=>Qe(ce),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})},[N,n,lt,Qe]),wt=Hp(rc(Jp,{activationConstraint:{distance:8}}),rc(Xp,{coordinateGetter:Yp})),Pt=i.useCallback(B=>{F(B.active.id)},[]),St=i.useCallback(B=>{const{active:ce,over:ye}=B;if(F(null),!ye||ce.id===ye.id)return;const $e=it.findIndex(st=>st.id===ce.id),Ue=it.findIndex(st=>st.id===ye.id);$e!==-1&&Ue!==-1&&z($e,Ue)},[it,z]),ge=i.useCallback(()=>{F(null)},[]),Ie=i.useMemo(()=>{if(!D)return null;const B=ze.find(ye=>ye.project.id===D);if(!B)return null;const ce=B.project;return{id:ce.id,label:rd(ce.label?.trim()||ac(ce.normalizedPath,L)||ce.normalizedPath),isActive:ce.id===K}},[D,ze,L,K]);return e.jsxs("div",{className:R("flex h-full flex-col text-foreground overflow-x-hidden",s?"":fe?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-8 select-none pl-3.5 pr-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("p",{className:"typography-ui-label font-medium text-muted-foreground",children:"Projects"}),e.jsx("span",{className:"typography-micro text-muted-foreground/50",children:J.length})]}),e.jsx("button",{type:"button",onClick:Ot,className:R("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!fe&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Up,{className:"h-4.5 w-4.5"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:R("space-y-1 pb-1 pl-2.5 pr-1",""),children:ze.length===0?et:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const B=ze.find($e=>$e.project.id===K)??ze[0];if(!B)return et;const ce=B.groups.find($e=>$e.isMain&&$e.sessions.length>0)??B.groups.find($e=>$e.sessions.length>0)??B.groups.find($e=>$e.isMain)??B.groups[0];if(!ce)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const ye=`${B.project.id}:${ce.id}`;return Ke(ce,ye,B.project.id)})()}):e.jsxs(Vp,{sensors:wt,collisionDetection:Gp,onDragStart:Pt,onDragEnd:St,onDragCancel:ge,children:[e.jsx(qp,{items:it.map(B=>B.id),strategy:Kp,children:ze.map(B=>{const ce=B.project,ye=ce.id,$e=rd(ce.label?.trim()||ac(ce.normalizedPath,L)||ce.normalizedPath),Ue=Zr(ce.normalizedPath,L),st=v.has(ye),ke=ye===K,Ye=k.get(ye),Ze=C===ye;return e.jsx(qb,{id:ye,projectLabel:$e,projectDescription:Ue,isCollapsed:st,isActiveProject:ke,isRepo:!!Ye,isHovered:Ze,isDesktopRuntime:fe,isStuck:E.has(ye),hideDirectoryControls:n,mobileVariant:s,onToggle:()=>ft(ye),onHoverChange:ot=>M(ot?ye:null),onNewSession:()=>{ye!==K&&ae(ye),T("chat"),s&&$(!1),Be({directoryOverride:ce.normalizedPath})},onNewWorktreeSession:()=>{ye!==K&&ae(ye),T("chat"),s&&$(!1),za()},onOpenBranchPicker:()=>A(!0),onOpenMultiRunLauncher:()=>{ye!==K&&ae(ye),W()},onClose:()=>X(ye),sentinelRef:ot=>{Y.current.set(ye,ot)},settingsAutoCreateWorktree:q,children:st?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:B.groups[0]?Ke(B.groups[0],`${ye}:all`,ye):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},ye)})}),e.jsx(Qp,{children:Ie?e.jsx(Kb,{projectLabel:Ie.label,isActiveProject:Ie.isActive}):null})]})}),e.jsx(Gb,{open:S,onOpenChange:A,projects:it,activeProjectId:K})]})},Wa=()=>{const[s,r]=Ae.useState(!1);Ae.useEffect(()=>{r(os())},[]);const t=Ae.useCallback(async a=>s?await wg(a):{success:!0,path:a},[s]),n=Ae.useCallback(async a=>s?await jg(a):{success:!0},[s]),o=Ae.useCallback(async a=>s?await Sg(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},nd=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:l,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=i.useMemo(()=>os(),[]),{isMobile:p}=Ht(),[h,y]=i.useState([]),[g,w]=i.useState(new Set),[b,v]=i.useState(!0),[j,k]=i.useState(!1),[x,N]=i.useState(""),[P,C]=i.useState(new Set),[M,S]=i.useState(null),[A,D]=i.useState(""),[F,E]=i.useState(!0),I=i.useRef(null),{requestAccess:_,startAccessing:V,isDesktop:Y}=Wa(),H=i.useRef(c),L=i.useCallback(G=>{if(!G)return G;if(G==="/"||G.length===0)return"/";let ee=G;for(;ee.length>1&&ee.endsWith("/");)ee=ee.slice(0,-1);return ee.length===0?"/":ee},[]),U=i.useMemo(()=>{if(!x)return null;const G=x.replace(/\\/g,"/");return L(G)},[x,L]),Q=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const G=d.replace(/\\/g,"/"),ee=L(G);if(ee&&ee!=="/")return ee}return U&&U!=="/"?U:null},[d,U,L]),J=i.useMemo(()=>typeof u=="boolean"?!!(u&&Q):!!Q,[u,Q]);i.useEffect(()=>{J||(v(!0),y([]))},[J]);const K=i.useCallback(G=>{if(!G||!J||!Q)return!1;const ee=G.replace(/\\/g,"/"),te=L(ee)??ee;if(te===Q)return!0;const xe=`${Q}/`;return te.startsWith(xe)},[J,Q,L]),ne=async G=>{if(J){if(a==="deferred"){r(G);return}if(Y){const ee=await _(G);ee.success&&ee.path?(await V(ee.path),r(ee.path)):(console.error("Failed to get directory access:",ee.error),r(G))}else r(G)}};i.useEffect(()=>{let G=!1;const ee=me=>{if(!me)return!1;const Te=L(me.replace(/\\/g,"/"));return!Te||Te==="/"?!1:(N(typeof Te=="string"?Te:me.replace(/\\/g,"/")),!0)};return d&&ee(d)||(async()=>{try{const me=await Ee.getFilesystemHome();if(!G&&ee(me))return}catch(me){console.warn("Failed to resolve filesystem home directory:",me)}try{const me=await Ee.getSystemInfo();if(!G&&ee(me?.homeDirectory))return}catch(me){console.warn("Failed to resolve home directory from system info:",me)}})(),()=>{G=!0}},[d,L]),i.useEffect(()=>{let G=!1;const ee=Te=>{if(G)return;const Ne=Te.filter(Be=>typeof Be=="string"&&Be.length>0).map(Be=>{const fe=Be.replace(/\\/g,"/");return L(fe)??fe});C(new Set(Ne))},te=()=>{try{const Te=localStorage.getItem("pinnedDirectories");if(!Te)return;const Ne=JSON.parse(Te);Array.isArray(Ne)&&ee(Ne)}catch(Te){console.warn("Failed to load pinned directories from local storage:",Te)}},xe=async()=>{try{let Te=[];if(f){const Ne=await zr();Te=Array.isArray(Ne?.pinnedDirectories)?Ne.pinnedDirectories:[]}else{const Ne=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(Ne.ok){const Be=await Ne.json();Te=Array.isArray(Be?.pinnedDirectories)?Be.pinnedDirectories:[]}}if(G)return;ee(Te)}catch(Te){console.warn("Failed to load pinned directories:",Te)}};te();const me=Te=>{const Ne=Te.detail;Ne&&Array.isArray(Ne.pinnedDirectories)&&ee(Ne.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",me),xe(),()=>{G=!0,window.removeEventListener("openchamber:settings-synced",me)}},[f,L]);const X=i.useRef(!0);i.useEffect(()=>{if(X.current){X.current=!1;return}const G={pinnedDirectories:Array.from(P)};ns(G)},[P]),i.useEffect(()=>{Q&&C(G=>{const ee=Array.from(G).map(te=>L(te.replace(/\\/g,"/"))??te).filter(te=>K(te));return new Set(ee)})},[Q,K,L]),i.useEffect(()=>{H.current!==c&&(H.current=c)},[c]);const ae=G=>{C(ee=>{if(!K(G))return ee;const te=L(G.replace(/\\/g,"/"))??G.replace(/\\/g,"/"),xe=new Set(ee);return xe.has(te)?xe.delete(te):xe.add(te),xe})},O=i.useMemo(()=>Array.from(P).map(G=>L(G.replace(/\\/g,"/"))??G).filter(G=>K(G)).map(G=>({path:G,name:G.split("/").pop()||G})).sort((G,ee)=>G.name.localeCompare(ee.name)),[P,K,L]),z=i.useCallback(async G=>{const ee=Ne=>c||!Ne.startsWith("."),te=Q;if(!J||!te)return[];const xe=G&&G.length>0?G:te,me=xe?xe.replace(/\\/g,"/"):null,Te=me?L(me)??me:null;if(Te){const Ne=`${te}/`;if(!(Te===te||Te.startsWith(Ne)))return[]}try{return(await Ee.listLocalDirectory(G)).filter(Be=>{if(!Be.isDirectory||!ee(Be.name))return!1;const fe=Be.path.replace(/\\/g,"/"),ht=L(fe)??fe,bt=ht===te?te:`${te}/`;return ht===te||ht.startsWith(bt)}).map(Be=>({name:Be.name,path:Be.path.replace(/\\/g,"/"),isDirectory:!0})).sort((Be,fe)=>Be.name.localeCompare(fe.name))}catch{try{const Be=await Ee.getApiClient().file.list({path:".",directory:G});return Be.data?Be.data.filter(fe=>{if(fe.type!=="directory"||!fe.name||!ee(fe.name))return!1;const ht=String(fe.absolute||fe.path||fe.name).replace(/\\/g,"/"),bt=L(ht)??ht,Nt=bt===te?te:`${te}/`;return bt===te||bt.startsWith(Nt)}).map(fe=>({name:fe.name||"",path:String(fe.absolute||fe.path||fe.name).replace(/\\/g,"/"),isDirectory:!0})).filter(fe=>fe.name!=="").sort((fe,ht)=>fe.name.localeCompare(ht.name)):[]}catch{return[]}}},[c,Q,L,J]),T=i.useRef(!1),$=i.useCallback(async()=>{if(!J||!Q){v(!0),y([]);return}T.current||v(!0);try{const G=await z(Q);y(G),T.current=!0}catch{}finally{v(!1)}},[J,Q,z]);i.useEffect(()=>{J&&(n==="inline"||j)&&$()},[n,j,J,$]);const W=async G=>{if(!J)return;const ee=g.has(G.path),te=new Set(g);if(ee){te.delete(G.path),w(te);return}te.add(G.path),w(te);const xe=await z(G.path),me=Te=>Te.map(Ne=>Ne.path===G.path?{...Ne,children:xe}:Ne.children?{...Ne,children:me(Ne.children)}:Ne);y(Te=>me(Te))};i.useEffect(()=>{M&&I.current&&(I.current.focus(),I.current.select())},[M]);const q=(G,ee=[])=>{const te="new_directory",xe=ee.map(Be=>Be.name);if(!xe.includes(te))return te;let me=1;const Te=new RegExp(`^${te}(\\d+)$`);for(const Be of xe){const fe=Be.match(Te);if(fe){const ht=parseInt(fe[1],10);ht>me&&(me=ht)}}let Ne=2;for(;xe.includes(`${te}${Ne}`);)Ne++;return`${te}${Math.max(Ne,me+1)}`},ue=async G=>{if(J){if(g.has(G.path)){const ee=q(G.path,G.children);D(ee)}else{const ee=new Set(g);if(ee.add(G.path),w(ee),G.children){const te=q(G.path,G.children);D(te)}else{const te=await z(G.path),xe=Te=>Te.map(Ne=>Ne.path===G.path?{...Ne,children:te}:Ne.children?{...Ne,children:xe(Ne.children)}:Ne);y(Te=>xe(Te));const me=q(G.path,te);D(me)}}S(G.path)}},oe=async()=>{if(!M||!J)return;const G=A.trim()||"new_directory",ee=`${M}/${G}`;try{await Ee.createDirectory(ee);const te=await z(M),xe=me=>me.map(Te=>Te.path===M?{...Te,children:te}:Te.children?{...Te,children:xe(Te.children)}:Te);y(me=>xe(me)),S(null),D("")}catch(te){console.error("Failed to create directory:",te)}},de=()=>{S(null),D("")},je=(G,ee=0)=>{const te=g.has(G.path),xe=G.isDirectory,me=P.has(G.path),Te=s===G.path,Ne=n==="inline",Be=e.jsxs(e.Fragment,{children:[xe&&e.jsx("button",{onClick:fe=>{fe.stopPropagation(),W(G)},className:R("hover:bg-accent rounded","p-0.5"),children:te?e.jsx(Ft,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Is,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!xe&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:fe=>{fe.stopPropagation(),ne(G.path),n==="dropdown"&&a==="immediate"&&k(!1)},onDoubleClick:fe=>{fe.stopPropagation(),l&&l(G.path)},className:R("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",Ne&&Te?"text-primary":"text-foreground"),children:[e.jsx(Gs,{className:R("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",Ne&&Te&&"text-primary")}),e.jsx("span",{className:R("font-medium truncate","typography-ui-label",Ne&&Te?"text-primary":"text-foreground"),children:G.name})]}),e.jsx("button",{onClick:fe=>{fe.stopPropagation(),ue(G)},className:R("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(Zt,{className:R("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:fe=>{fe.stopPropagation(),ae(G.path)},className:R("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:me?"Unpin directory":"Pin directory",children:me?e.jsx(Ya,{className:R("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(eh,{className:R("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:R("group flex items-center gap-1 rounded-lg mx-1 text-left transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",Te?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${ee*(p?12:14)+(p?4:6)}px`},children:Be}),te&&e.jsxs(e.Fragment,{children:[M===G.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(ee+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Gs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{ref:I,value:A,onChange:fe=>D(fe.target.value),onKeyDown:fe=>{fe.key==="Enter"?(fe.preventDefault(),fe.stopPropagation(),oe()):fe.key==="Escape"&&(fe.preventDefault(),fe.stopPropagation(),de())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),oe()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Bt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),de()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground"})})]}),G.children&&G.children.map(fe=>je(fe,ee+1))]})]},G.path):e.jsxs("div",{children:[e.jsxs(It,{className:R("flex items-center gap-1 cursor-pointer group",s===G.path&&"bg-accent"),style:{paddingLeft:`${ee*12+8}px`},onSelect:fe=>{fe.preventDefault()},children:[xe&&e.jsx("button",{onClick:fe=>{fe.stopPropagation(),W(G)},className:"p-0.5 hover:bg-accent rounded",children:te?e.jsx(Ft,{className:"h-3 w-3"}):e.jsx(Is,{className:"h-3 w-3"})}),!xe&&e.jsx("div",{className:"w-4"}),Be]}),te&&e.jsxs("div",{children:[M===G.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(ee+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Gs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{ref:I,value:A,onChange:fe=>D(fe.target.value),onKeyDown:fe=>{fe.key==="Enter"?(fe.preventDefault(),fe.stopPropagation(),oe()):fe.key==="Escape"&&(fe.preventDefault(),fe.stopPropagation(),de())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),oe()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Bt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:fe=>{fe.preventDefault(),fe.stopPropagation(),de()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground"})})]}),G.children&&G.children.map(fe=>je(fe,ee+1))]})]},G.path)},Se=(G,ee)=>{if(n==="inline"){const te=s===ee;return e.jsxs("div",{className:R("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",te?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>ne(ee),onDoubleClick:xe=>{xe.stopPropagation(),l&&l(ee)},className:R("flex flex-1 items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded min-w-0",te?"text-primary":"text-foreground"),children:[e.jsx(Gs,{className:R("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",te?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:R("typography-ui-label font-medium truncate flex-shrink-0",te?"text-primary":"text-foreground"),children:G}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:Zr(ee,x)})]}),e.jsx("button",{onClick:()=>ae(ee),className:R("hover:bg-accent rounded-md transition-opacity",p?"p-1.5 opacity-60":"p-1 opacity-0 group-hover:opacity-100"),title:"Unpin directory",children:e.jsx(Ya,{className:R("text-primary","h-3.5 w-3.5")})})]},ee)}return e.jsxs(It,{onSelect:te=>{te.preventDefault(),ne(ee),a==="immediate"&&k(!1)},className:R("flex items-start gap-2 cursor-pointer group py-2",s===ee&&"bg-accent"),children:[e.jsx(Gs,{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:G}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Zr(ee,x)})]}),e.jsx("button",{onClick:te=>{te.stopPropagation(),te.preventDefault(),ae(ee)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Ya,{className:"h-3 w-3 text-primary"})})]},ee)},Le=e.jsx(e.Fragment,{children:J?e.jsxs(e.Fragment,{children:[O.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>E(G=>!G),className:R("flex w-full items-center gap-1.5 typography-meta font-medium text-muted-foreground/80 hover:bg-accent/30 rounded transition-colors uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:[F?e.jsx(Ft,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Is,{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:O.length})]}),F&&O.map(({name:G,path:ee})=>Se(G,ee)),n==="dropdown"&&e.jsx(Ss,{}),n==="inline"&&F&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:R("typography-meta font-medium text-muted-foreground/80 flex items-center gap-1.5 uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:"Browse"}),b?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):h.map(G=>je(G)),!b&&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:R("overflow-hidden flex flex-col",o),children:e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:Le})}):e.jsxs(Yt,{open:j,onOpenChange:k,children:[e.jsx(Xt,{asChild:!0,children:e.jsxs(De,{variant:"ghost",className:R("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",t),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(Gs,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:Zr(s,x)})]}),e.jsx(Ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Jt,{align:"start",className:"w-[350px]",children:e.jsx(xt,{outerClassName:"h-full",className:"w-full",children:Le})})]})},Ha=(s,r=200)=>{const[t,n]=Ae.useState(s);return Ae.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},Gm=i.forwardRef(({inputValue:s,homeDirectory:r,onSelectSuggestion:t,visible:n,onClose:o,showHidden:a},l)=>{const[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(0),h=i.useRef(null),y=i.useRef([]),g=i.useCallback((x,N)=>{const P=x.trim().toLowerCase();if(!P)return 0;const C=N.toLowerCase();let M=0,S=-1,A=0;for(let D=0;D<P.length;D+=1){const F=P[D];if(!F||F===" ")continue;const E=C.indexOf(F,S+1);if(E===-1)return null;const I=E-S-1;if(I===0?A+=1:A=0,M+=10,M+=Math.max(0,18-E),M-=Math.max(0,I),E===0)M+=12;else{const _=C[E-1];(_==="/"||_==="_"||_==="-"||_==="."||_===" ")&&(M+=10)}M+=A>0?12:0,S=E}return M+=Math.max(0,24-Math.round(C.length/3)),M},[]),w=i.useCallback(x=>x.startsWith("~")&&r?x.replace(/^~/,r):x,[r]),b=i.useCallback(x=>{const N=w(x);if(N.endsWith("/"))return N;const P=N.lastIndexOf("/");return P===-1?"":P===0?"/":N.substring(0,P+1)},[w]),v=i.useCallback(x=>{const N=w(x);if(N.endsWith("/"))return"";const P=N.lastIndexOf("/");return P===-1?N:N.substring(P+1)},[w]),j=Ha(s,150);i.useEffect(()=>{if(!n||!j){d([]);return}const x=b(j),N=v(j).toLowerCase();if(!x){d([]);return}let P=!1;return m(!0),Ee.listLocalDirectory(x).then(C=>{if(P)return;const M=C.filter(A=>!(!A.isDirectory||!a&&A.name.startsWith("."))),S=N?M.map(A=>{const D=g(N,A.name);return D!==null?{entry:A,score:D}:null}).filter(A=>A!==null).sort((A,D)=>D.score-A.score||A.entry.name.localeCompare(D.entry.name)).map(A=>A.entry):M.sort((A,D)=>A.name.localeCompare(D.name));d(S.slice(0,10)),p(0)}).catch(()=>{P||d([])}).finally(()=>{P||m(!1)}),()=>{P=!0}},[n,j,b,v,a,g]),i.useEffect(()=>{y.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const x=N=>{const P=N.target;!P||!h.current||h.current.contains(P)||o()};return document.addEventListener("pointerdown",x,!0),()=>{document.removeEventListener("pointerdown",x,!0)}},[n,o]);const k=i.useCallback(x=>{const N=x.path.endsWith("/")?x.path:x.path+"/";t(N)},[t]);return i.useImperativeHandle(l,()=>({handleKeyDown:x=>{if(!n||c.length===0)return!1;const N=c.length;if(x.key==="Tab"){if(x.preventDefault(),x.shiftKey)p(P=>(P-1+N)%N);else if(N===1){const P=c[0];P&&k(P)}else p(P=>(P+1)%N);return!0}if(x.key==="ArrowDown")return x.preventDefault(),p(P=>(P+1)%N),!0;if(x.key==="ArrowUp")return x.preventDefault(),p(P=>(P-1+N)%N),!0;if(x.key==="Enter"){x.preventDefault();const P=(f%N+N)%N,C=c[P];return C&&k(C),o(),!0}return x.key==="Escape"?(x.preventDefault(),o(),!0):!1}}),[n,c,f,k,o]),!n||c.length===0&&!u?null:e.jsxs("div",{ref:h,className:"absolute z-[100] w-full max-h-48 bg-background border border-border rounded-lg shadow-lg top-full mt-1 left-0 flex flex-col overflow-hidden",children:[u?e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(Rr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:c.map((x,N)=>{const P=f===N;return e.jsxs("div",{ref:C=>{y.current[N]=C},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",P&&"bg-muted"),onClick:()=>{k(x),o()},onMouseEnter:()=>p(N),children:[e.jsx(Js,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:x.name})]},x.path)})}),e.jsx("div",{className:"px-3 py-1.5 border-t typography-meta text-muted-foreground bg-sidebar/50",children:"Tab cycle • ↑↓ navigate • Enter select"})]})});Gm.displayName="DirectoryAutocomplete";const od="directoryTreeShowHidden",Qb=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,isHomeReady:o}=yt(),{addProject:a,getActiveProject:l}=Lt(),[c,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,y]=i.useState(!1),[g,w]=i.useState(()=>{if(typeof window>"u")return!1;try{const X=window.localStorage.getItem(od);if(X==="true")return!0;if(X==="false")return!1}catch{}return!1}),{isDesktop:b,requestAccess:v,startAccessing:j}=Wa(),{isMobile:k}=Ht(),[x,N]=i.useState(!1),P=i.useRef(null),C=i.useCallback(X=>X?Zr(X,n):"",[n]);i.useEffect(()=>{if(s){p(!1),y(!1),N(!1);const ae=l()?.path||t||n||"";d(ae),m(C(ae))}},[s,t,n,C,l]),i.useEffect(()=>{!s||f||c||n&&o&&(d(n),p(!0),m("~"))},[s,f,c,n,o]),i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(od,g?"true":"false")}catch{}},[g]);const M=i.useCallback(()=>{r(!1)},[r]),S=i.useCallback(async X=>{if(!(!X||h)){y(!0);try{let ae=X,O;if(b){const T=await v(X);if(!T.success){Z.error("Unable to access directory",{description:T.error||"Desktop denied directory access."});return}ae=T.path??X,O=T.projectId;const $=await j(ae);if(!$.success){Z.error("Failed to open directory",{description:$.error||"Desktop could not grant file access."});return}}if(!a(ae,{id:O})){Z.error("Failed to add project",{description:"Please select a valid directory path."});return}M()}catch(ae){Z.error("Failed to select directory",{description:ae instanceof Error?ae.message:"Unknown error occurred."})}finally{y(!1)}}},[a,M,b,v,j,h]),A=i.useCallback(async()=>{const X=u.trim()||c;X&&await S(X)},[S,u,c]),D=i.useCallback(X=>{d(X),p(!0),m(C(X))},[C]),F=i.useCallback(async X=>{d(X),p(!0),m(C(X)),await S(X)},[S,C]),E=i.useCallback(X=>{const ae=X.target.value;if(m(ae),p(!0),N(ae.startsWith("/")||ae.startsWith("~")),ae.startsWith("/")||ae.startsWith("~")){const O=ae.startsWith("~")&&n?ae.replace(/^~/,n):ae;d(O)}},[n]),I=i.useCallback(X=>{P.current?.handleKeyDown(X)||X.key==="Enter"&&(X.preventDefault(),A())},[A]),_=i.useCallback(X=>{d(X),p(!0),m(C(X))},[C]),V=i.useCallback(()=>{N(!1)},[]),Y=i.useCallback(()=>{w(X=>!X)},[]),H=e.jsxs("button",{type:"button",onClick:Y,className:"flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground flex-shrink-0",children:[g?e.jsx(ul,{className:"h-4 w-4 text-primary"}):e.jsx(ml,{className:"h-4 w-4"}),"Show hidden"]}),L=e.jsxs(hs,{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(gs,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(vs,{className:"flex-1",children:"Choose a folder to add as a project."}),H]})]}),U=e.jsxs("div",{className:"relative",children:[e.jsx(kt,{value:u,onChange:E,onKeyDown:I,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(Gm,{ref:P,inputValue:u,homeDirectory:n,onSelectSuggestion:_,visible:x,onClose:V,showHidden:g})]}),Q=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(nd,{variant:"inline",currentPath:c??t,onSelectPath:D,onDoubleClickPath:F,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o})}),J=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:U}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:H}),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(nd,{variant:"inline",currentPath:c??t,onSelectPath:D,onDoubleClickPath:F,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:g,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),K=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[U,Q]}),ne=()=>e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:M,disabled:h,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(De,{onClick:A,disabled:h||!f||!c&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:h?"Adding...":"Add Project"})]});return k?e.jsx(js,{open:s,onClose:()=>r(!1),title:"Add project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:e.jsx("div",{className:"flex flex-row gap-2",children:ne()}),children:J}):e.jsx(us,{open:s,onOpenChange:r,children:e.jsxs(ms,{className:R("flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6"),onOpenAutoFocus:X=>{X.preventDefault()},children:[L,K,e.jsx(tr,{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:ne()})]})})},Po=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,Yb=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Xb=()=>{const[s,r]=i.useState(!1),[t,n]=i.useState(!1),o=i.useRef(new Set),[a,l]=i.useState(null),[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(!1),{deleteSession:h,deleteSessions:y,loadSessions:g,getWorktreeMetadata:w}=he(),{currentDirectory:b,homeDirectory:v,isHomeReady:j}=yt(),{projects:k,addProject:x,activeProjectId:N}=Lt(),{requestAccess:P,startAccessing:C}=Wa(),{isMobile:M,isTablet:S,hasTouchInput:A}=Ht(),D=M||S||A,F=i.useMemo(()=>{const $=(N?k.find(W=>W.id===N)??null:null)?.path??b;return Yb($)},[N,b,k]),E=i.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||c.some(T=>T.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,c]),I=i.useMemo(()=>{const T=a?.worktree;return T&&typeof T.branch=="string"&&T.branch.trim().length>0?!0:c.length>0&&c.every(({metadata:$})=>typeof $.branch=="string"&&$.branch.trim().length>0)},[a?.worktree,c]),_=a?.mode==="worktree",V=_,Y=f||!_||!I;i.useEffect(()=>{F&&(o.current.has(F)||Bx(F).then(()=>o.current.add(F)).catch(T=>{console.warn("Failed to ensure .openchamber directory is ignored:",T),o.current.delete(F)}))},[F]),i.useEffect(()=>{g()},[g,b]);const H=i.useMemo(()=>k.map(T=>`${T.id}:${T.path}`).join("|"),[k]),L=i.useRef(H);i.useEffect(()=>{H!==L.current&&(L.current=H,g())},[g,H]),i.useEffect(()=>{if(!(t||!j||k.length>0)){if(n(!0),os()){P("").then(async T=>{if(!T.success||!T.path){T.error&&T.error!=="Directory selection cancelled"&&Z.error("Failed to select directory",{description:T.error});return}const $=await C(T.path);if(!$.success){Z.error("Failed to open directory",{description:$.error||"Desktop could not grant file access."});return}x(T.path,{id:T.projectId})||Z.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(T=>{console.error("Desktop: Error selecting directory:",T),Z.error("Failed to select directory")});return}r(!0)}},[x,t,j,k.length,P,C]);const U=i.useCallback(T=>{l({sessions:T.sessions,dateLabel:T.dateLabel,mode:T.mode??"session",worktree:T.worktree??null})},[]),Q=i.useCallback(()=>{l(null),d([]),m(!1),p(!1)},[]);i.useEffect(()=>Fn.onDeleteRequest(T=>{U(T)}),[U]),i.useEffect(()=>Fn.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1);return}const T=a.sessions.map(W=>{const q=w(W.id);return q?{session:W,metadata:q}:null}).filter(W=>!!W);if(d(T),m(!1),T.length===0)return;let $=!1;return(async()=>{const W=await Promise.all(T.map(async({metadata:q})=>{if(q.status&&typeof q.status.isDirty=="boolean")return q.status;try{return await $a(q.path)}catch{return q.status}})).catch(q=>(console.warn("Failed to inspect worktree status before deletion:",q),T.map(({metadata:ue})=>ue.status)));$||!Array.isArray(W)||d(q=>q.map((ue,oe)=>({session:ue.session,metadata:{...ue.metadata,status:W[oe]??ue.metadata.status}})))})(),()=>{$=!0}},[a,w]),i.useEffect(()=>{I||m(!1)},[I]);const J=i.useCallback(async()=>{if(a){p(!0);try{const T=V,$=T&&u;if(a.sessions.length===0&&_&&a.worktree){const W=u&&I;await wm({projectDirectory:F,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:W});const q=W?"Worktree and remote branch removed.":"Worktree removed.";Z.success("Worktree removed",{description:Po(q)}),Q(),g();return}if(a.sessions.length===1){const W=a.sessions[0];if(!await h(W.id,{archiveWorktree:T,deleteRemoteBranch:$})){Z.error("Failed to delete session"),p(!1);return}const ue=T?$?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;Z.success("Session deleted",{description:Po(ue)})}else{const W=a.sessions.map(oe=>oe.id),{deletedIds:q,failedIds:ue}=await y(W,{archiveWorktree:T,deleteRemoteBranch:$});if(q.length>0){const oe=T?$?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,je=[ue.length>0?`${ue.length} session${ue.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,oe].filter(Boolean).join(" ");Z.success(`Deleted ${q.length} session${q.length===1?"":"s"}`,{description:Po(je||void 0)})}if(ue.length>0&&(Z.error(`Failed to delete ${ue.length} session${ue.length===1?"":"s"}`,{description:Po("Please try again in a moment.")}),q.length===0)){p(!1);return}}Q()}finally{p(!1)}}},[a,u,h,y,Q,V,_,I,F,g]),K=a?.worktree??c[0]?.metadata??null,ne=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}`:""}.`:"",X=a?e.jsxs("div",{className:R(_?"space-y-3":"space-y-2"),children:[a.sessions.length>0&&e.jsxs("div",{className:R(_?"rounded-lg bg-muted/30 p-3":"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3"),children:[_&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children: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:R(_?"mt-2 space-y-1":"space-y-0.5"),children:[a.sessions.slice(0,5).map(T=>e.jsxs("li",{className:R(_?"flex items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-muted-foreground":"typography-micro text-muted-foreground/80"),children:[e.jsx("span",{className:R(!_&&"hidden"),children:"•"}),e.jsx("span",{className:"truncate",children:T.title||"Untitled Session"})]},T.id)),a.sessions.length>5&&e.jsxs("li",{className:R(_?"px-2.5 py-1 text-xs text-muted-foreground/70":"typography-micro text-muted-foreground/70"),children:["+",a.sessions.length-5," more"]})]})]}),_?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(_t,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),K?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:K.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:K?Zr(K.path,v):"Worktree path unavailable."}),E&&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,ae=_?I?e.jsxs("button",{type:"button",onClick:()=>{Y||m(T=>!T)},disabled:Y,className:R("flex items-center gap-2 rounded-md px-2 py-1 text-sm text-muted-foreground transition-colors",Y?"cursor-not-allowed opacity-60":"hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[u?e.jsx(ul,{className:"size-4 text-primary"}):e.jsx(ml,{className:"size-4"}),"Delete remote branch"]}):e.jsx("span",{className:"text-xs text-muted-foreground/70",children:"Remote branch info unavailable"}):null,O=_?e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[ae,e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{variant:"ghost",onClick:Q,disabled:f,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:J,disabled:f,children:f?"Deleting…":"Delete worktree"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:Q,disabled:f,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:J,disabled:f,children:f?"Deleting…":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),z=_?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[D?e.jsx(js,{open:!!a,onClose:()=>{f||Q()},title:z,footer:e.jsx("div",{className:"flex justify-end gap-2",children:O}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[ne&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:ne}),X]})}):e.jsx(us,{open:!!a,onOpenChange:T=>{if(!T){if(f)return;Q()}},children:e.jsxs(ms,{className:R(_?"max-w-xl max-h-[70vh] flex flex-col overflow-hidden gap-3":"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2"),children:[e.jsxs(hs,{children:[e.jsxs(gs,{className:R(_&&"flex items-center gap-2"),children:[_&&e.jsx(Bs,{className:"h-5 w-5"}),z]}),ne&&e.jsx(vs,{children:ne})]}),e.jsx("div",{className:R(_&&"flex-1 min-h-0 overflow-y-auto space-y-2"),children:X}),e.jsx(tr,{className:"mt-2 gap-2 pt-1 pb-1",children:O})]})}),e.jsx(Qb,{open:s,onOpenChange:r})]})};function Jb(){return new Worker(th,{type:"module"})}const Zb=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function ev(s,r,t){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${s}:${r.length}:${t.length}:${n.length}:${o.length}`}function ad(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const tv=({children:s})=>{const r=rh(),t=Qt(c=>c.activeDirectory),n=Qt(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=Qt(c=>t?c.directories.get(t)?.diffCache.size??0:0),a=Ae.useRef(!1),l=Ae.useRef(new Map);return Ae.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Oi(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Ae.useEffect(()=>{if(!r||!t||!n||o===0)return;const c=Qt.getState().directories.get(t);if(!c||c.diffCache.size===0||(l.current.get(t)??0)>=c.lastStatusChange)return;l.current.set(t,c.lastStatusChange);let u=!1,m=null;const f=Array.from(c.diffCache.entries());let p=0;const h=y=>{if(u)return;const g=Date.now();for(;p<f.length&&!(y&&y.timeRemaining()<8||!y&&Date.now()-g>8);){const[w,b]=f[p];p+=1,gr(w);const v=ev(w,b.original,b.modified),j={name:w,contents:b.original,cacheKey:`old-${v}`},k={name:w,contents:b.modified,cacheKey:`new-${v}`},x=Oi(j,k),N={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(N,x)}p<f.length&&(m=ad(h))};return h(void 0),p<f.length&&(m=ad(h)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},sv=({children:s})=>{const t=Ba()?.currentTheme?.metadata?.variant==="dark";Om();const n=Ae.useMemo(()=>({theme:{dark:Tn.dark,light:Tn.light},themeType:t?"dark":"light",langs:Zb}),[t]);return e.jsx(sh,{poolOptions:{workerFactory:Jb,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(tv,{children:s})})},Ji=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),rv=(s,r)=>{const t=Ji(s),n=Ji(r);return`${t}-${n}`.substring(0,60)},id=(s,r)=>`${s}/${r}`,nv=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),ov=()=>{const s=Lt.getState(),r=s.activeProjectId,t=r?s.projects.find(c=>c.id===r)?.path:void 0;if(typeof t=="string"&&t.trim().length>0)return t;const n=yt.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,l=o.indexOf("/.openchamber/");return l>0?o.slice(0,l):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},to=Kt()(ss(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:l,setupCommands:c}=r;if(!t)return s({error:"Group name is required"}),null;if(!n)return s({error:"Prompt is required"}),null;if(o.length<1)return s({error:"Select at least 1 model"}),null;if(o.length>5)return s({error:"Maximum 5 models allowed"}),null;s({isLoading:!0,error:null});try{const d=ov();if(!d)return s({error:"No directory selected",isLoading:!1}),null;if(!await Ur(d))return s({error:"Not in a git repository",isLoading:!1}),null;const m=Ji(t),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,h=[],y=c?.filter(x=>x.trim().length>0)??[],g=new Map;for(const x of o){const N=`${x.providerID}:${x.modelID}`;g.set(N,(g.get(N)||0)+1)}const w=new Map;for(const x of o){const N=`${x.providerID}:${x.modelID}`,P=g.get(N)||1,C=(w.get(N)||0)+1;w.set(N,C);const M=rv(x.providerID,x.modelID),S=P>1?id(m,`${M}/${C}`):id(m,M);if(!S)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const A=nv(S);if(!A)return s({error:`Invalid branch name: ${S}`,isLoading:!1}),null;try{const D=await jl({projectDirectory:d,worktreeSlug:A,branch:S,createBranch:!0,startPoint:p}),F=P>1?`${m}/${x.providerID}/${x.modelID}/${C}`:`${m}/${x.providerID}/${x.modelID}`,E=await Ee.withDirectory(D.path,()=>Ee.createSession({title:F}));pt.getState().setWorktreeMetadata(E.id,D),h.push({sessionId:E.id,worktreePath:D.path,providerID:x.providerID,modelID:x.modelID,variant:x.variant})}catch(D){console.warn("[MultiRun] Failed to create session:",D)}}const b=c?.filter(x=>x.trim().length>0)??[];b.length>0&&xm(d,b).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const v=h.map(x=>x.sessionId),j=h[0]?.sessionId??null;if(v.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const k=l?.map(x=>({type:"file",mime:x.mime,filename:x.filename,url:x.url}));try{await pt.getState().loadSessions()}catch{}if(y.length>0)for(const x of h)Sl(x.worktreePath,d,y).then(N=>{if(!N.success){const P=N.results.filter(C=>!C.success);console.warn(`[MultiRun] Setup commands failed for ${x.worktreePath}:`,P)}}).catch(N=>{console.warn(`[MultiRun] Setup commands error for ${x.worktreePath}:`,N)});return(async()=>{try{await Promise.allSettled(h.map(async x=>{try{await Ee.withDirectory(x.worktreePath,()=>Ee.sendMessage({id:x.sessionId,providerID:x.providerID,modelID:x.modelID,variant:x.variant,text:n,agent:a,files:k}))}catch(N){console.warn("[MultiRun] Failed to start run:",N)}}))}catch(x){console.warn("[MultiRun] Failed to start runs:",x)}})(),s({isLoading:!1}),{groupSlug:m,sessionIds:v,firstSessionId:j}}catch(d){return s({error:d instanceof Error?d.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{s({error:null})}}),{name:"multirun-store"}));function Cs({...s}){return e.jsx(nh,{"data-slot":"select",...s})}function sn({...s}){return e.jsx(uh,{"data-slot":"select-group",...s})}function cn({...s}){return e.jsx(ih,{"data-slot":"select-value",...s})}function Ms({className:s,size:r="default",children:t,...n}){return e.jsxs(oh,{"data-slot":"select-trigger","data-size":r,className:R("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-muted data-[state=open]:bg-muted focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 data-[size=lg]:h-8 data-[size=lg]:py-1.5 data-[size=chip]:h-7 data-[size=chip]:py-1 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...n,children:[t,e.jsx(ah,{asChild:!0,children:e.jsx(Ft,{className:"size-4 opacity-50"})})]})}function Ds({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx(lh,{children:e.jsx(ch,{"data-slot":"select-content",className:R("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n&&"w-max min-w-0",s),position:t,...o,children:e.jsx(xt,{as:dh,outerClassName:R("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:R("p-1",t==="popper"&&(n?"h-[var(--radix-select-trigger-height)] w-max min-w-0 scroll-my-1":"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1")),children:r})})})}function Dn({className:s,...r}){return e.jsx(mh,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function qt({className:s,children:r,...t}){return e.jsxs(fh,{"data-slot":"select-item",className:R("hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",s),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(ph,{children:e.jsx(Bt,{className:"size-4"})})}),e.jsx(hh,{children:r})]})}function wa({className:s,...r}){return e.jsx(gh,{"data-slot":"select-separator",className:R("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}const av="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",iv=Object.assign({"../assets/provider-logos/gocode.svg":av}),Zi=new Map;for(const[s,r]of Object.entries(iv)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&Zi.set(t[1].toLowerCase(),r)}function qm(s){const r=s?.toLowerCase()??null,t=r?Zi.has(r):!1,n=r?Zi.get(r)??null:null,[o,a]=Ae.useState(t?"local":"remote");Ae.useEffect(()=>{a(t?"local":"remote")},[t,r]);const l=Ae.useCallback(()=>{a(c=>c==="local"&&t?"remote":"none")},[t]);return r?o==="local"&&n?{src:n,onError:l,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}:{src:null,onError:l,hasLogo:!1}}const ds=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:l}=qm(s),c=i.useCallback(()=>{a(),n?.()},[a,n]);return!l||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:R("dark:invert",t),onError:c})},Bl=s=>s.nativeEvent.isComposing||s.nativeEvent.keyCode===229,zl=()=>{const{providers:s}=nt(),{favoriteModels:r,recentModels:t}=_e(),n=i.useMemo(()=>r.map(({providerID:a,modelID:l})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null),[r,s]),o=i.useMemo(()=>t.map(({providerID:a,modelID:l})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!r.some(c=>c.providerID===a&&c.modelID===l)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},Km="h-7",ja=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,lv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),cv=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=lv.format(s);return r.endsWith(".0")?r.slice(0,-2):r},dv=({model:s,instanceIndex:r,totalSameModel:t,onRemove:n})=>{const o=s.displayName||`${s.providerID}/${s.modelID}`,a=t>1?`${o} (${r})`:o;return e.jsxs("div",{className:R("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",Km),children:[e.jsx(ds,{providerId:s.providerID,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:a}),e.jsx("button",{type:"button",onClick:n,className:"text-muted-foreground hover:text-foreground ml-0.5",children:e.jsx(Gt,{className:"h-3.5 w-3.5"})})]})},Qm=({selectedModels:s,onAdd:r,onRemove:t,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:l=!0,maxModels:c})=>{const{providers:d,modelsMetadata:u}=nt(),{favoriteModelsList:m,recentModelsList:f}=zl(),[p,h]=i.useState(!1),[y,g]=i.useState(""),[w,b]=i.useState(0),[v,j]=i.useState(null),k=i.useRef(null),x=i.useRef(null),N=i.useRef(null),P=i.useRef([]),C=i.useMemo(()=>{const Y=new Map;for(const H of s){const L=`${H.providerID}:${H.modelID}`;Y.set(L,(Y.get(L)||0)+1)}return Y},[s]),M=i.useCallback(Y=>s.filter(L=>L.providerID===Y.providerID&&L.modelID===Y.modelID).findIndex(L=>L.instanceId===Y.instanceId)+1,[s]),S=(Y,H)=>{const L=`${Y}/${H}`;return u.get(L)},A=Y=>{const H=Y?.name||Y?.id||"",L=String(H);return L.length>40?L.substring(0,37)+"...":L},D=i.useCallback((Y,H)=>{if(!y.trim())return!0;const L=y.toLowerCase();return Y.toLowerCase().includes(L)||H.toLowerCase().includes(L)},[y]),F=i.useMemo(()=>m.filter(({model:Y,providerID:H})=>{const U=d.find(J=>J.id===H)?.name||H,Q=A(Y);return D(Q,U)}),[m,d,D]),E=i.useMemo(()=>f.filter(({model:Y,providerID:H})=>{const U=d.find(J=>J.id===H)?.name||H,Q=A(Y);return D(Q,U)}),[f,d,D]),I=i.useMemo(()=>d.map(Y=>{const L=(Array.isArray(Y.models)?Y.models:[]).filter(U=>{const Q=A(U);return D(Q,Y.name||Y.id||"")});return{...Y,models:L}}).filter(Y=>Y.models.length>0),[d,D]),_=F.length>0||E.length>0||I.length>0;i.useEffect(()=>{if(p&&N.current){const H=N.current.getBoundingClientRect().top-100;j(Math.max(150,Math.min(400,H)))}},[p]),i.useEffect(()=>{p&&k.current&&k.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const Y=H=>{x.current&&!x.current.contains(H.target)&&(h(!1),g(""),b(0))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[p]),i.useEffect(()=>{b(0)},[y]);const V=(Y,H,L,U,Q,J)=>{const K=`${H}:${L}`,ne=C.get(K)||0,X=S(H,L),ae=cv(X?.limit?.context);return e.jsxs("button",{ref:O=>{P.current[Q]=O},type:"button",onClick:()=>{r({providerID:H,modelID:L,displayName:Y.name||L,instanceId:ja()})},onMouseEnter:()=>b(Q),className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",J?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:A(Y)}),ae&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:ae})]}),ne>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",ne]})]},`${U}-${K}`)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs("div",{className:"relative",ref:x,children:[e.jsxs(De,{ref:N,type:"button",variant:"outline",size:"sm",className:Km,onClick:()=>h(!p),children:[e.jsx(Zt,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const Y=[];F.forEach(({model:Q,providerID:J,modelID:K})=>{Y.push({model:Q,providerID:J,modelID:K,section:"fav"})}),E.forEach(({model:Q,providerID:J,modelID:K})=>{Y.push({model:Q,providerID:J,modelID:K,section:"recent"})}),I.forEach(Q=>{Q.models.forEach(J=>{Y.push({model:J,providerID:Q.id,modelID:J.id,section:"provider"})})});const H=Y.length,L=Q=>{if(!Bl(Q))if(Q.key==="ArrowDown"){Q.preventDefault(),Q.stopPropagation();const J=(w+1)%Math.max(1,H);b(J),setTimeout(()=>{P.current[J]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Q.key==="ArrowUp"){Q.preventDefault(),Q.stopPropagation();const J=(w-1+Math.max(1,H))%Math.max(1,H);b(J),setTimeout(()=>{P.current[J]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(Q.key==="Enter"){Q.preventDefault(),Q.stopPropagation();const J=Y[w];J&&r({providerID:J.providerID,modelID:J.modelID,displayName:J.model.name||J.modelID,instanceId:ja()})}else Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),h(!1),g(""),b(0))};let U=0;return e.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden bg-background shadow-lg w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(Xs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{ref:k,type:"text",placeholder:"Search models",value:y,onChange:Q=>g(Q.target.value),onKeyDown:L,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(xt,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!_&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),F.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(vr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),F.map(({model:Q,providerID:J,modelID:K})=>{const ne=U++;return V(Q,J,K,"fav",ne,w===ne)})]}),E.length>0&&e.jsxs(e.Fragment,{children:[F.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(fr,{className:"h-4 w-4"}),"Recent"]}),E.map(({model:Q,providerID:J,modelID:K})=>{const ne=U++;return V(Q,J,K,"recent",ne,w===ne)})]}),(F.length>0||E.length>0)&&I.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),I.map((Q,J)=>e.jsxs(i.Fragment,{children:[J>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(ds,{providerId:Q.id,className:"h-4 w-4 flex-shrink-0"}),Q.name]}),Q.models.map(K=>{const ne=U++;return V(K,Q.id,K.id,"provider",ne,w===ne)})]},Q.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),l&&s.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:s.map((Y,H)=>{const L=`${Y.providerID}:${Y.modelID}`,U=C.get(L)||1,Q=M(Y),K=d.find(z=>z.id===Y.providerID)?.models.find(z=>z.id===Y.modelID),ne=K?.variants?Object.keys(K.variants):[],X=ne.length>0,ae="__default__",O=Y.variant??ae;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(dv,{model:Y,instanceIndex:Q,totalSameModel:U,onRemove:()=>t(H)}),X&&e.jsxs(Cs,{value:O,onValueChange:z=>{if(!n)return;n(H,{...Y,variant:z===ae?void 0:z})},children:[e.jsxs(Ms,{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(pr,{className:R("h-3.5 w-3.5 flex-shrink-0",O===ae?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(cn,{placeholder:"Thinking"})]}),e.jsxs(Ds,{fitContent:!0,children:[e.jsx(qt,{value:ae,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),ne.map(z=>e.jsx(qt,{value:z,className:"pr-2 [&>span:first-child]:hidden",children:z},z))]})]})]},Y.instanceId)})})]}),o!==void 0&&s.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",c!==void 0?`to ${c} models`:"","."]})]})};function Wl(s){const[r,t]=i.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=i.useState(!1),[a,l]=i.useState(null);return i.useEffect(()=>{let c=!1;if(!s){l(null),o(!1),t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),l(null),(async()=>{try{const d=await Ur(s);if(c)return;if(l(d),!d){t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await _a(s).catch(()=>null);if(c)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(y=>!y.startsWith("remotes/")).sort((y,g)=>y.localeCompare(g)).forEach(y=>{m.push({value:y,label:y,group:"local"})}),u.all.filter(y=>y.startsWith("remotes/")).map(y=>y.replace(/^remotes\//,"")).sort((y,g)=>y.localeCompare(g)).forEach(y=>{m.push({value:y,label:y,group:"remote"})})),t(m)}finally{c||o(!1)}})(),()=>{c=!0}},[s]),{branches:r,isLoading:n,isGitRepository:a}}const Ym=({directory:s,value:r,onChange:t,className:n,disabled:o,id:a})=>{const{branches:l,isLoading:c,isGitRepository:d}=Wl(s),u=i.useMemo(()=>l.find(f=>f.value===r)?.label??null,[l,r]);i.useEffect(()=>{!l.some(p=>p.value===r)&&l.length>0&&t("HEAD")},[l,r,t]);const m=o||!d||c;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Cs,{value:r,onValueChange:t,disabled:m,children:[e.jsx(Ms,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(cn,{children:u}):e.jsx(cn,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs(Ds,{fitContent:!0,children:[e.jsxs(sn,{children:[e.jsx(Dn,{children:"Default"}),l.filter(f=>f.group==="special").map(f=>e.jsx(qt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),l.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(wa,{}),e.jsxs(sn,{children:[e.jsx(Dn,{children:"Local branches"}),l.filter(f=>f.group==="local").map(f=>e.jsx(qt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,l.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(wa,{}),e.jsxs(sn,{children:[e.jsx(Dn,{children:"Remote branches"}),l.filter(f=>f.group==="remote").map(f=>e.jsx(qt,{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."})]})},Xm=({value:s,onChange:r,className:t,disabled:n,id:o})=>{const a=nt(f=>f.getVisibleAgents),l=nt(f=>f.loadAgents),c=nt(f=>f.currentAgentName),d=a(),u=i.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(n)return;const f=s.trim();if(f.length>0&&u.some(y=>y.name===f))return;const p=typeof c=="string"&&c.trim().length>0?c.trim():null;if(p&&u.some(y=>y.name===p)){r(p);return}const h=u[0]?.name;h&&r(h)},[c,n,r,u,s]);const m=s.trim().length>0?s:void 0;return e.jsxs(Cs,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Ms,{id:o,size:"lg",className:t??"max-w-full typography-meta text-foreground",children:e.jsx(cn,{placeholder:"Select an agent"})}),e.jsx(Ds,{fitContent:!0,children:u.length>0&&e.jsx(sn,{children:u.map(f=>e.jsx(qt,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},uv=10*1024*1024,ld=5,cd=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=i.useState(""),[a,l]=i.useState(()=>s??""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState([]),[h,y]=i.useState(!1),[g,w]=i.useState([]),[b,v]=i.useState(!1),[j,k]=i.useState(!1),x=i.useRef(null),N=yt(T=>T.currentDirectory??null),P=i.useMemo(()=>{if(typeof window>"u")return null;const T=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof T=="string"&&T.trim().length>0?T.trim():null},[]),C=Lt(T=>T.activeProjectId),M=Lt(T=>T.projects),S=i.useMemo(()=>{if(C){const ue=M.find(oe=>oe.id===C);if(ue?.path)return ue.path}const T=N??P;if(!T)return null;const $=T.replace(/\\/g,"/").replace(/\/+$/,"")||T,q=$.indexOf("/.openchamber/");return q>0?$.slice(0,q):$.endsWith("/.openchamber")?$.slice(0,$.length-13):$},[C,M,N,P]),A=_e(T=>T.isSidebarOpen),[D,F]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),E=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const T=typeof window.opencodeDesktop<"u";F(T)},[]);const I=i.useMemo(()=>D&&E?A?"pl-0":"pl-[8.0rem]":"pl-3",[D,E,A]),[_,V]=i.useState("HEAD"),{isLoading:Y,isGitRepository:H}=Wl(N),L=to(T=>T.createMultiRun),U=to(T=>T.error),Q=to(T=>T.clearError);i.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&l(T=>T.trim().length>0?T:s)},[s]),i.useEffect(()=>{if(!S)return;let T=!1;return k(!0),(async()=>{try{const $=await Ln(S);T||w($)}catch{}finally{T||k(!1)}})(),()=>{T=!0}},[S]);const J=T=>{c.length>=ld||(d($=>[...$,T]),Q())},K=T=>{d($=>$.filter((W,q)=>q!==T)),Q()},ne=i.useCallback((T,$)=>{d(W=>W.map((q,ue)=>ue===T?$:q))},[]),X=async T=>{const $=T.target.files;if(!$)return;let W=0;for(let q=0;q<$.length;q++){const ue=$[q];if(ue.size>uv){Z.error(`File "${ue.name}" is too large (max 10MB)`);continue}try{const oe=await new Promise((je,Se)=>{const Le=new FileReader;Le.onload=()=>je(Le.result),Le.onerror=Se,Le.readAsDataURL(ue)}),de={id:ja(),filename:ue.name,mimeType:ue.type||"application/octet-stream",size:ue.size,dataUrl:oe};p(je=>[...je,de]),W++}catch(oe){console.error("File attach failed",oe),Z.error(`Failed to attach "${ue.name}"`)}}W>0&&Z.success(`Attached ${W} file${W>1?"s":""}`),x.current&&(x.current.value="")},ae=T=>{p($=>$.filter(W=>W.id!==T))},O=async T=>{if(T.preventDefault(),!!a.trim()&&!(c.length<2)){y(!0),Q();try{const $=c.map(({instanceId:de,...je})=>je),W=f.map(de=>({mime:de.mimeType,filename:de.filename,url:de.dataUrl})),q=g.filter(de=>de.trim().length>0),ue={name:n.trim(),prompt:a.trim(),models:$,agent:u||void 0,worktreeBaseBranch:_,files:W.length>0?W:void 0,setupCommands:q.length>0?q:void 0},oe=await L(ue);oe&&(oe.firstSessionId&&he.getState().setCurrentSession(oe.firstSessionId),r?.())}finally{y(!1)}}},z=!!(n.trim()&&a.trim()&&c.length>=2&&H&&!Y);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:R("flex h-12 items-center justify-between border-b app-region-drag",I),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("flex items-center gap-3",D&&E&&A&&"pl-4"),children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),t&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close",className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:e.jsx(Gt,{className:"h-5 w-5"})})}),e.jsx(ct,{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:O,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(kt,{id:"group-name",value:n,onChange:T=>o(T.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(Ym,{directory:N,value:_,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:_||"HEAD"}),"."]})]}),e.jsxs(xo,{open:b,onOpenChange:v,children:[e.jsxs(La,{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(T=>T.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",g.filter(T=>T.trim()).length," configured)"]})]}),e.jsx(Ft,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",b&&"rotate-180")})]}),e.jsx(yo,{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."]}),j?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[g.map((T,$)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(kt,{value:T,onChange:W=>{const q=[...g];q[$]=W.target.value,w(q)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const W=g.filter((q,ue)=>ue!==$);w(W)},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(Gt,{className:"h-4 w-4"})})]},$)),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(Zt,{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(Xm,{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(Ns,{id:"prompt",value:a,onChange:T=>l(T.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),e.jsx("input",{ref:x,type:"file",multiple:!0,className:"hidden",onChange:X,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(De,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>x.current?.click(),children:[e.jsx(aa,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(T=>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:[T.mimeType.startsWith("image/")?e.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:T.filename,children:T.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",T.size<1024?`${T.size}B`:T.size<1024*1024?`${(T.size/1024).toFixed(1)}KB`:`${(T.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>ae(T.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Gt,{className:"h-3.5 w-3.5"})})]},T.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(Qm,{selectedModels:c,onAdd:J,onRemove:K,onUpdate:ne,minModels:2,maxModels:ld})]}),U&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:U}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(De,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(De,{type:"submit",disabled:!z||h,children:h?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(xh,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},mv=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:l,isSessionSwitcherOpen:c}=_e(),d=Ae.useRef(null),u=Ae.useRef(null);return Ae.useEffect(()=>{if(!o||!a)return;const m=y=>{const g=y.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=y=>{if(!d.current)return;const g=y.touches[0];if(!g)return;g.clientX-d.current.x>10&&y.preventDefault()},p=y=>{if(!d.current)return;const g=y.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:b,time:v}=d.current,{x:j,y:k,time:x}=u.current,N=j-w,P=k-b,C=x-v,M=Math.abs(P)<Math.abs(N),S=C<=n,A=Math.abs(P)<t;N>=t&&M&&S&&A&&!c&&l(!0),d.current=null,u.current=null},h=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",m,{passive:!0,capture:!0}),document.addEventListener("touchmove",f,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",m,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,r,t,n,l,c]),null},Qn=s=>s==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:s==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;Ae.memo(()=>{const s=Ae.useRef(null),{addAttachedFile:r}=he(),{isMobile:t}=_e(),n=Pm(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",l=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],h=he.getState().attachedFiles.length;try{await r(p),he.getState().attachedFiles.length>h&&m++}catch(y){console.error("File attach failed",y),Z.error(y instanceof Error?y.message:"Failed to attach file")}}m>0&&Z.success(`Attached ${m} file${m>1?"s":""}`)},c=async u=>{const m=u.target.files;m&&(await l(m),s.current&&(s.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const y=p.map(g=>`${g?.name||"file"}: ${g?.reason||"skipped"}`).join(`
85
+ `);Z.error(`Some files were skipped:
86
+ ${y}`)}const h=f.map(y=>{if(!y?.dataUrl)return null;try{const[g,w]=y.dataUrl.split(","),b=y.mimeType||g?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!w)return null;const v=atob(w),j=new Uint8Array(v.length);for(let x=0;x<v.length;x++)j[x]=v.charCodeAt(x);const k=new Blob([j],{type:b});return new File([k],y.name||"file",{type:b})}catch(g){return console.error("Failed to decode VS Code picked file",g),null}}).filter(Boolean);h.length>0&&await l(h)}catch(u){console.error("VS Code file pick failed",u),Z.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:s,type:"file",multiple:!0,className:"hidden",onChange:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:R(o,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),title:"Attach files",children:e.jsx(aa,{className:R(a,"text-current")})})]})});const fv=Ae.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(hr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(cr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(Ea,{className:"h-3.5 w-3.5"}):e.jsx(cr,{className:"h-3.5 w-3.5"}),n=l=>l<1024?l+" B":l<1048576?(l/1024).toFixed(1)+" KB":(l/1048576).toFixed(1)+" MB",a=(l=>{const d=l.replace(/\\/g,"/").split("/");return d[d.length-1]||l})(s.filename);return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:s.source==="server"?"Server file":"Local file",children:s.source==="server"?e.jsx(yh,{className:"h-3 w-3 text-primary"}):e.jsx(Iu,{className:"h-3 w-3 text-muted-foreground"})}),t(),e.jsx("span",{title:s.serverPath||a,children:a}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",n(s.size),")"]}),e.jsx("button",{onClick:r,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(Gt,{className:"h-3 w-3"})})]})}),pv=Ae.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=he();return s.length===0?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Attached:"}),s.map(t=>e.jsx(fv,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),Jm=Ae.memo(({files:s,onShowPopup:r})=>{const t=s.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const m=d.replace(/\\/g,"/").split("/");return m[m.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(hr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(cr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Ea,{className:"h-3.5 w-3.5"}):e.jsx(cr,{className:"h-3.5 w-3.5"}):e.jsx(cr,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),l=t.filter(d=>!d.mime?.startsWith("image/")),c=i.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return t.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const m=n(d.filename)||"Image";return e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>c(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(hr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(ct,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Zm=Ae.memo(({message:s,sessionId:r,onEdit:t})=>{const n=lr(l=>l.removeFromQueue),o=i.useMemo(()=>{const l=s.content.split(`
87
+ `),c=l[0]||"",d=50;return c.length>d?c.substring(0,d)+"...":c+(l.length>1?"...":"")},[s.content]),a=s.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(bh,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>t(s),className:"flex items-center gap-1.5 hover:text-foreground transition-colors text-left",title:"Click to edit",children:[e.jsx("span",{className:"truncate max-w-[200px]",children:o||"(empty)"}),a>0&&e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["+",a," file",a>1?"s":""]})]}),e.jsx("button",{type:"button",onClick:()=>n(r,s.id),className:"ml-1 hover:text-destructive p-0.5 opacity-60 group-hover:opacity-100 transition-opacity",title:"Remove from queue",children:e.jsx(Gt,{className:"h-3 w-3"})})]})});Zm.displayName="QueuedMessageChip";const dd=[],ef=Ae.memo(({onEditMessage:s})=>{const r=he(a=>a.currentSessionId),t=lr(i.useCallback(a=>r?a.queuedMessages[r]??dd:dd,[r])),n=lr(a=>a.popToInput),o=i.useCallback(a=>{if(!r)return;const l=n(r,a.id);if(l){if(l.attachments&&l.attachments.length>0){const c=Ys.getState().attachedFiles;Ys.setState({attachedFiles:[...c,...l.attachments]})}s(l.content,l.attachments)}},[r,n,s]);return t.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),t.map(a=>e.jsx(Zm,{message:a,sessionId:r,onEdit:o},a.id))]})})});ef.displayName="QueuedMessageChips";const hv=i.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=yt(),{addServerFile:a}=he(),l=Ra(A=>A.searchFiles),c=Ha(s,180),[d,u]=i.useState([]),[m,f]=i.useState(!1),[p,h]=i.useState(0),[y,g]=i.useState(360),[w,b]=i.useState({}),[v,j]=i.useState({}),k=i.useRef([]),x=i.useRef([]),N=i.useRef([]),P=i.useRef(null),C=i.useCallback((A,D)=>{const F=A.trim().toLowerCase();if(!F)return 0;const E=D.toLowerCase();let I=0,_=-1,V=0;for(let Y=0;Y<F.length;Y+=1){const H=F[Y];if(!H||H===" ")continue;const L=E.indexOf(H,_+1);if(L===-1)return null;const U=L-_-1;if(U===0?V+=1:V=0,I+=10,I+=Math.max(0,18-L),I-=Math.max(0,U),L===0)I+=12;else{const Q=E[L-1];(Q==="/"||Q==="_"||Q==="-"||Q==="."||Q===" ")&&(I+=10)}I+=V>0?12:0,_=L}return I+=Math.max(0,24-Math.round(E.length/3)),I},[]);i.useEffect(()=>{const A=D=>{const F=D.target;!F||!P.current||P.current.contains(F)||t()};return document.addEventListener("pointerdown",A,!0),()=>{document.removeEventListener("pointerdown",A,!0)}},[t]),i.useEffect(()=>{if(!o){u([]);return}const D=(c??"").trim().toLowerCase();let F=!1;return f(!0),l(o,D,80).then(E=>{if(F)return;const I=D?E.map(_=>{const V=_.relativePath||_.name||_.path,Y=C(D,V);return Y===null?null:{file:_,score:Y,labelLength:V.length}}).filter(Boolean):E.map(_=>({file:_,score:0,labelLength:(_.relativePath||_.name||_.path).length}));I.sort((_,V)=>V.score-_.score||_.labelLength-V.labelLength||_.file.path.localeCompare(V.file.path)),u(I.slice(0,15).map(_=>_.file))}).catch(()=>{F||u([])}).finally(()=>{F||f(!1)}),()=>{F=!0}},[o,c,C,l]),i.useEffect(()=>{h(0),b({}),j({})},[d]),i.useEffect(()=>{k.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),i.useEffect(()=>{let A=null;const D=()=>{A!==null&&cancelAnimationFrame(A),A=requestAnimationFrame(()=>{const F={},E={};x.current.forEach((I,_)=>{if(!I)return;const Y=N.current[_]?.offsetWidth??I.scrollWidth,H=Math.max(0,Y-I.clientWidth),L=H>8;if(F[_]=L,L){const U=Math.max(.6,H/110);E[_]=U}}),b(F),j(E)})};return D(),window.addEventListener("resize",D),()=>{A!==null&&cancelAnimationFrame(A),window.removeEventListener("resize",D)}},[d]),i.useEffect(()=>{const A=x.current[p];if(!A)return;const D=()=>{const E=A.clientWidth;E>0&&g(E)};if(D(),typeof ResizeObserver>"u")return;const F=new ResizeObserver(D);return F.observe(A),()=>{F.disconnect()}},[p]);const M=i.useCallback(async A=>{await a(A.path,A.name),r(A)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:A=>{if(A==="Escape"){t();return}const D=d.length;if(D!==0){if(A==="ArrowDown"){h(F=>(F+1)%D);return}if(A==="ArrowUp"){h(F=>(F-1+D)%D);return}if(A==="Enter"||A==="Tab"){const F=(p%D+D)%D,E=d[F];E&&M(E)}}}}),[d,p,t,M]);const S=A=>{switch(A.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx($s,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx($s,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(cr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(hr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Ea,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:P,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(xt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:m?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Rr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((A,D)=>{const F=A.relativePath||A.name,E=Yu(F,{maxLength:45}),I=p===D,_=w[D]??!1,V=v[D]??2.6,Y=e.jsxs("div",{ref:H=>{k.current[D]=H},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",I&&"bg-muted"),onClick:()=>M(A),onMouseEnter:()=>h(D),children:[S(A),e.jsxs("span",{ref:H=>{x.current[D]=H},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:I?{"--file-mention-marquee-width":`${y}px`,"--file-mention-marquee-duration":`${V}s`}:void 0,"aria-label":F,children:[e.jsx("span",{ref:H=>{N.current[D]=H},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:F}),_&&I?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:F}):e.jsx("span",{className:"block truncate",children:E})]})]});return e.jsx(i.Fragment,{children:Y},A.path)}),d.length>0&&e.jsx("div",{className:"h-2"}),d.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),tf=i.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=he(fl(v=>{const j=v.currentSessionId;return{hasMessagesInCurrentSession:(j?v.messages.get(j)?.length??0:0)>0,currentSessionId:j}})),l=!!a,[c,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=Wr(),[h,y]=i.useState(0),g=i.useRef([]),w=i.useRef(null);i.useEffect(()=>{const v=j=>{const k=j.target;!k||!w.current||w.current.contains(k)||t()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[t]),i.useEffect(()=>{p()},[p]),i.useEffect(()=>{(async()=>{m(!0);try{const j=f.map(M=>({name:M.name,description:M.description,agent:M.agent??void 0,model:M.model??void 0,isBuiltIn:M.name==="init"||M.name==="review",scope:M.scope})),k=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],x=new Map;k.forEach(M=>x.set(M.name,M)),j.forEach(M=>x.set(M.name,M));const N=Array.from(x.values()),P=!o,C=(s?N.filter(M=>Rs(M.name,s)||M.description&&Rs(M.description,s)):N).filter(M=>P||M.name!=="init");C.sort((M,S)=>{const A=M.name.toLowerCase().startsWith(s.toLowerCase()),D=S.name.toLowerCase().startsWith(s.toLowerCase());return A&&!D?-1:!A&&D?1:M.name.localeCompare(S.name)}),d(C)}catch{const j=!o,k=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],x=(s?k.filter(N=>Rs(N.name,s)||N.description&&Rs(N.description,s)):k).filter(N=>j||N.name!=="init");d(x)}finally{m(!1)}})()},[s,o,l,f]),i.useEffect(()=>{y(0)},[c]),i.useEffect(()=>{g.current[h]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[h]),i.useImperativeHandle(n,()=>({handleKeyDown:v=>{const j=c.length;if(v==="Escape"){t();return}if(j!==0){if(v==="ArrowDown"){y(k=>(k+1)%j);return}if(v==="ArrowUp"){y(k=>(k-1+j)%j);return}if(v==="Enter"||v==="Tab"){const k=(h%j+j)%j,x=c[k];x&&r(x)}}}}),[c,h,t,r]);const b=v=>{switch(v.name){case"init":return e.jsx(cr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(En,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(jh,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(fr,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(wh,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx($r,{className:"h-3.5 w-3.5 text-cyan-500"});default:return v.isBuiltIn?e.jsx(vh,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(un,{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(xt,{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(Rr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((v,j)=>{const k=v.isBuiltIn,x=v.scope==="project";return e.jsxs("div",{ref:N=>{g.current[j]=N},className:R("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",j===h&&"bg-muted"),onClick:()=>r(v),onMouseEnter:()=>y(j),children:[e.jsx("div",{className:"mt-0.5",children:b(v)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-medium",children:["/",v.name]}),k?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):v.scope?e.jsx("span",{className:R("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",x?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:v.scope}):null,v.agent&&e.jsx("span",{className:"text-[10px] leading-none font-bold tracking-tight bg-[var(--surface-subtle)] text-[var(--surface-foreground)] border-[var(--interactive-border)] px-1.5 py-1 rounded border flex-shrink-0",children:v.agent})]}),v.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:v.description})]})]},v.name)}),c.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});tf.displayName="CommandAutocomplete";const gv=s=>s?s!=="primary":!1,sf=i.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{getVisibleAgents:m}=nt(),{agents:f,loadAgents:p}=Hr();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const g=m().filter(v=>gv(v.mode)).map(v=>{const j=f.find(k=>k.name===v.name);return{name:v.name,description:v.description,mode:v.mode??void 0,scope:j?.scope,isBuiltIn:j?Jr(j):!1}}),w=s.trim(),b=w.length?g.filter(v=>Rs(v.name,w)):g;b.sort((v,j)=>v.name.localeCompare(j.name)),d(b),l(0)},[m,s,f]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const y=g=>{const w=g.target;!w||!o.current||o.current.contains(w)||t()};return document.addEventListener("pointerdown",y,!0),()=>{document.removeEventListener("pointerdown",y,!0)}},[t]),i.useImperativeHandle(n,()=>({handleKeyDown:y=>{if(y==="Escape"){t();return}if(c.length){if(y==="ArrowDown"){l(g=>(g+1)%c.length);return}if(y==="ArrowUp"){l(g=>(g-1+c.length)%c.length);return}if(y==="Enter"||y==="Tab"){const g=c[(a+c.length)%c.length];g&&r(g.name)}}}}),[c,r,t,a]);const h=(y,g)=>{const w=y.isBuiltIn,b=y.scope==="project";return e.jsx("div",{ref:v=>{u.current[g]=v},className:R("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",g===a&&"bg-muted"),onClick:()=>r(y.name),onMouseEnter:()=>l(g),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["#",y.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"}):y.scope?e.jsx("span",{className:R("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",b?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:y.scope}):null]}),y.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:y.description})]})},y.name)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((y,g)=>h(y,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"})]})});sf.displayName="AgentMentionAutocomplete";const rf=i.forwardRef(({searchQuery:s,onSkillSelect:r,onClose:t},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=Qs();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const h=s.trim(),g=[...h.length?m.filter(w=>Rs(w.name,h)):m].sort((w,b)=>w.scope==="project"&&b.scope!=="project"?-1:w.scope!=="project"&&b.scope==="project"?1:w.name.localeCompare(b.name));d(g),l(0)},[m,s]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const h=y=>{const g=y.target;!g||!o.current||o.current.contains(g)||t()};return document.addEventListener("pointerdown",h,!0),()=>{document.removeEventListener("pointerdown",h,!0)}},[t]),i.useImperativeHandle(n,()=>({handleKeyDown:h=>{if(h==="Escape"){t();return}if(c.length){if(h==="ArrowDown"){l(y=>(y+1)%c.length);return}if(h==="ArrowUp"){l(y=>(y-1+c.length)%c.length);return}if(h==="Enter"||h==="Tab"){const y=c[a];y&&r(y.name)}}}}),[c,r,t,a]);const p=(h,y)=>{const g=h.scope==="project";return e.jsx("div",{ref:w=>{u.current[y]=w},className:R("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",y===a&&"bg-muted"),onClick:()=>r(h.name),onMouseEnter:()=>l(y),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold truncate",children:h.name}),e.jsx("span",{className:R("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 transition-colors",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(xt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((h,y)=>p(h,y))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No skills found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});rf.displayName="SkillAutocomplete";function xv({className:s,children:r,...t}){return e.jsxs(Sh,{"data-slot":"scroll-area",className:R("relative",s),...t,children:[e.jsx(kh,{"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(Nh,{})]})}function yv({className:s,orientation:r="vertical",...t}){return e.jsx(Ch,{"data-slot":"scroll-area-scrollbar",orientation:r,className:R("flex touch-none p-px select-none",r==="vertical"&&"h-full w-2.5 border-l border-l-transparent",r==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",s),...t,children:e.jsx(Mh,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const bv=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:l}=Ht(),c=l,{currentDirectory:d}=yt(),u=Ra(G=>G.searchFiles),[m,f]=i.useState(!1),[p,h]=i.useState(!1),[y,g]=i.useState(""),w=Ha(y,200),[b,v]=i.useState(new Set),[j,k]=i.useState(new Set),[x,N]=i.useState({}),P=i.useRef(new Set),C=i.useRef(new Set),[M,S]=i.useState([]),[A,D]=i.useState(!1),[F,E]=i.useState(!1),[I,_]=i.useState(!1),[V,Y]=i.useState(null),H=n??m,L=o??f,U=i.useCallback(G=>G.slice().sort((ee,te)=>ee.type!==te.type?ee.type==="directory"?-1:1:ee.name.localeCompare(te.name)),[]),Q=i.useCallback((G,ee)=>U(ee.filter(te=>!te.name.startsWith(".")).map(te=>{const xe=te.name,me=!te.isDirectory&&xe.includes(".")?xe.split(".").pop()?.toLowerCase():void 0;return{name:xe,path:te.path||`${G}/${xe}`,type:te.isDirectory?"directory":"file",size:0,extension:me}})),[U]),J=i.useCallback(async G=>{E(!0),Y(null);try{const ee=await Ee.listLocalDirectory(G),te=Q(G,ee.map(xe=>({name:xe.name,path:xe.path,isDirectory:xe.isDirectory})));P.current=new Set([G]),C.current=new Set,N({[G]:te}),k(new Set)}catch{Y("Failed to load directory contents"),P.current=new Set([G]),C.current=new Set,N({[G]:[]}),k(new Set)}finally{E(!1)}},[Q]),K=i.useCallback(async G=>{const ee=G.trim();if(ee&&!P.current.has(ee)&&!C.current.has(ee)){C.current=new Set(C.current),C.current.add(ee);try{const te=await Ee.listLocalDirectory(ee),xe=Q(ee,te.map(me=>({name:me.name,path:me.path,isDirectory:me.isDirectory})));P.current=new Set(P.current),P.current.add(ee),N(me=>({...me,[ee]:xe}))}catch{N(te=>te[ee]?te:{...te,[ee]:[]})}finally{C.current=new Set(C.current),C.current.delete(ee)}}},[Q]);i.useEffect(()=>{(H||p)&&d&&J(d)},[H,p,d,J]),i.useEffect(()=>{if(!(H||p)||!d){S([]),D(!1);return}const G=w.trim();if(!G){S([]),D(!1);return}let ee=!1;return D(!0),u(d,G,150).then(te=>{if(ee)return;const xe=te.map(me=>({name:me.name,path:me.path,type:"file",extension:me.extension,relativePath:me.relativePath,size:0}));S(xe)}).catch(()=>{ee||S([])}).finally(()=>{ee||D(!1)}),()=>{ee=!0}},[H,p,d,w,u]),i.useEffect(()=>{!H&&!p&&(v(new Set),g(""),S([]),D(!1))},[H,p]);const ne=G=>{if(G.type==="directory")return j.has(G.path)?e.jsx(Gs,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(Gs,{className:"h-3.5 w-3.5 text-primary/60"});switch(G.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx($s,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx($s,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(no,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(hr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(no,{className:"h-3.5 w-3.5 text-muted-foreground"})}},X=async G=>{j.has(G)?k(te=>{const xe=new Set(te);return xe.delete(G),xe}):(k(te=>{const xe=new Set(te);return xe.add(G),xe}),await K(G))},ae=G=>{v(r?ee=>{const te=new Set(ee);return te.has(G)?te.delete(G):te.add(G),te}:new Set([G]))},O=async()=>{const G=new Map;Object.values(x).forEach(xe=>{xe.forEach(me=>{me.type==="file"&&G.set(me.path,me)})});const ee=new Map(M.map(xe=>[xe.path,xe])),te=Array.from(b).map(xe=>G.get(xe)??ee.get(xe)).filter(xe=>!!xe);_(!0);try{await s(te),v(new Set),L(!1),h(!1)}finally{_(!1)}},z=i.useMemo(()=>d?x[d]??[]:[],[x,d]),T=y.trim().length>0,$=G=>x[G]??[],W=G=>{if(d&&G.startsWith(d)){const ee=G.substring(d.length);return ee.startsWith("/")?ee.substring(1):ee}return G.split("/").pop()||G},q=(G,ee)=>{const te=T?G.relativePath||W(G.path):G.name,xe=T&&te.includes("/")&&te.length>45,me=xe?Yu(te,{maxLength:c?42:48}):te,Te=e.jsxs("div",{className:R("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-muted cursor-pointer typography-ui-label text-foreground text-left",G.type==="file"&&b.has(G.path)&&"bg-primary/10"),style:{paddingLeft:`${ee*12}px`},onClick:Ne=>{Ne.preventDefault(),Ne.stopPropagation(),G.type==="file"&&ae(G.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ne(G)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":te,children:me})]}),G.type==="file"&&b.has(G.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return xe?e.jsxs(dt,{delayDuration:120,children:[e.jsx(ut,{asChild:!0,children:Te}),e.jsx(ct,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:te})})]},G.path):i.cloneElement(Te,{key:G.path})},ue=(G,ee)=>{const te=G.type==="directory",xe=te?$(G.path):[],me=j.has(G.path),Te=te&&me&&C.current.has(G.path)&&xe.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!te&&b.has(G.path)&&"bg-primary/10"),style:{paddingLeft:`${ee*12}px`},onClick:Ne=>{Ne.preventDefault(),Ne.stopPropagation(),te?X(G.path):ae(G.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ne(G)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:G.name}),!te&&b.has(G.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),te&&me&&xe.length>0&&e.jsx("div",{children:xe.map(Ne=>ue(Ne,ee+1))}),te&&me&&Te&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(ee+1)*12}px`},children:"Loading…"})]},G.path)},oe=b.size>0?`${b.size} file${b.size!==1?"s":""} selected`:"No files selected",de=e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 shrink-0",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:oe}),e.jsx(De,{size:"sm",onClick:O,disabled:b.size===0||I,className:"h-6 typography-meta",children:I?"Attaching...":"Attach Files"})]}),je=c?"flex-1 min-h-[240px]":"h-[300px]",Se=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(Xs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{value:y,onChange:G=>g(G.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:G=>G.stopPropagation()}),y&&e.jsx("button",{onClick:G=>{G.stopPropagation(),g("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Gt,{className:"h-3 w-3"})})]})}),e.jsxs(xv,{className:je,children:[F&&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..."})}),V&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:V})}),!F&&!V&&e.jsxs("div",{className:"py-1 px-2",children:[T?A?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):M.map(G=>q(G,0)):z.map(G=>ue(G,0)),!T&&z.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),T&&!A&&M.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),Le=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:G=>{G.preventDefault(),G.stopPropagation(),h(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:G=>{G.preventDefault(),G.stopPropagation(),L(!0)},children:t}):null,e.jsx(js,{open:H,onClose:()=>L(!1),title:"Select Project Files",footer:de,children:e.jsx("div",{className:"flex flex-col gap-0",children:Se})})]}):c?e.jsxs(e.Fragment,{children:[Le,e.jsx(js,{open:p,onClose:()=>h(!1),title:"Select Project Files",footer:de,children:e.jsx("div",{className:"flex flex-col gap-0",children:Se})})]}):e.jsxs(Yt,{open:H,onOpenChange:L,children:[e.jsx(Xt,{asChild:!0,children:t}),e.jsxs(Jt,{className:R("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[Se,e.jsx(Ss,{}),de]})]})},To=[{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 Er(s){if(!s||s==="build")return To[0];let r=0;for(let n=0;n<s.length;n++){const o=s.charCodeAt(n);r=(r<<5)-r+o,r=r&r}const t=1+Math.abs(r)%(To.length-1);return To[t]}const vv=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),nf=s=>vv(s),wv=s=>s?typeof s=="string"?s==="ask":nf(s)?Object.values(s).some(r=>r==="ask"):!1:!1,jv=s=>s?typeof s=="string"?s==="deny":nf(s)?Object.values(s).some(r=>r==="deny"):!1:!1,of=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=wv(t),o=jv(t),a=!n&&!o,l=r==="allow",c=r!=="deny",d=s==="allow"||s==="full",u=s==="ask";let m=s;d&&l&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:s!=="deny"&&c&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:l,webfetchNotDeny:c}},Fo=s=>s==="primary"||s==="all"||s===void 0||s===null,Sa=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},Ro=(s,r)=>{const t=Sa(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Sv=(s,r)=>{const t=Sa(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},kv=[{key:"tool_call",icon:Ia,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:pr,label:"Reasoning",isActive:s=>s?.reasoning===!0}],Nv={text:{icon:Tu,label:"Text"},image:{icon:hr,label:"Image"},video:{icon:Ah,label:"Video"},audio:{icon:Dh,label:"Audio"},pdf:{icon:Ea,label:"PDF"}},Cv=s=>s.trim().toLowerCase(),Gn=(s,r)=>{const t=r==="input"?s?.modalities?.input:s?.modalities?.output;return!Array.isArray(t)||t.length===0?[]:Array.from(new Set(t.map(o=>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}),Hs=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=Mv.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Oo=s=>typeof s!="number"||!Number.isFinite(s)?"—":Dv.format(s),hi=s=>kv.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),ud=s=>{if(!s)return"—";const r=s.match(/^(\d{4})-(\d{2})$/);if(r){const t=Number.parseInt(r[1],10),n=Number.parseInt(r[2],10)-1,o=new Date(Date.UTC(t,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return s},md=s=>{if(!s)return"—";const r=new Date(s);return Number.isNaN(r.getTime())?s:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(r)},fd=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:l,setProvider:c,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:h,getCurrentAgent:y,getVisibleAgents:g}=nt(),w=g(),{currentSessionId:b,messages:v,saveSessionAgentSelection:j,getSessionAgentSelection:k,saveAgentModelForSession:x,getAgentModelForSession:N,saveAgentModelVariantForSession:P,getAgentModelVariantForSession:C,analyzeAndSaveExternalSessionChoices:M,getSessionAgentEditMode:S,setSessionAgentEditMode:A}=he(),D=gt(se=>se.hasHydrated),{toggleFavoriteModel:F,isFavoriteModel:E,addRecentModel:I,isModelSelectorOpen:_,setModelSelectorOpen:V}=_e(),{favoriteModelsList:Y,recentModelsList:H}=zl(),{isMobile:L}=Ht(),U=qy(),Q=Pm(),J=L,[K,ne]=i.useState(null),[X,ae]=i.useState(null),[O,z]=i.useState(""),T=i.useCallback(()=>ne(null),[]),$=i.useCallback(()=>ae(null),[]),W=i.useRef(void 0),[q,ue]=i.useState(()=>{const se=new Set;return t&&se.add(t),se}),[oe,de]=i.useState(!1),je=_,Se=V,[Le,G]=i.useState(!1),ee=i.useId(),[te,xe]=i.useState(""),[me,Te]=i.useState(0),Ne=i.useRef([]);i.useEffect(()=>{K==="model"&&ue(()=>{const se=new Set;return t&&se.add(t),se})},[K,t]),i.useEffect(()=>{K!=="agent"&&de(!1),K!=="model"&&z("")},[K]);const Be=i.useRef(je);i.useEffect(()=>{const se=Be.current;Be.current=je,je||(G(!1),xe(""),Te(0),se&&!J&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[je,J]),i.useEffect(()=>{Te(0)},[te]);const fe=y?.(),ht=i.useMemo(()=>fe?Ro(fe.permission,"edit")??"ask":"deny",[fe]),bt=i.useMemo(()=>{if(fe)return Ro(fe.permission,"webfetch")},[fe]),Nt=i.useMemo(()=>{if(!fe)return;const se=Sv(fe.permission,"bash");return se||void 0},[fe]),Me=i.useMemo(()=>of({agentDefaultEditMode:ht,webfetchPermission:bt,bashPermission:Nt}),[ht,bt,Nt]),{cascadeDefaultMode:re,modeAvailability:et,autoApproveAvailable:be}=Me,we=!!(b&&a),Ve=we&&b&&a?S(b,a,re):re,tt={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},We=i.useCallback(se=>!et[se],[et]),Oe=i.useMemo(()=>!we||We(Ve)&&Ve!==re?re:Ve,[re,We,we,Ve]),rt=[{mode:"ask",label:tt.ask,disabled:We("ask")},{mode:"allow",label:tt.allow,disabled:We("allow")},{mode:"full",label:tt.full,disabled:We("full")}],vt=i.useMemo(()=>Qn(Oe),[Oe]),mt=!we||!be;i.useEffect(()=>{mt&&(de(!1),G(!1))},[mt]);const Tt=L?"mobile":Q?"vscode":"default",Ot=Tt==="mobile"?"h-9":Tt==="vscode"?"h-6":"h-8",ve=Tt==="mobile"?"h-5 w-5":"h-4 w-4",He=Tt==="mobile"?"h-5 w-5":"h-4 w-4",Je=J?"typography-micro":"typography-meta",Qe=Tt==="mobile"?"gap-x-2":Tt==="vscode"?"gap-x-1":"gap-x-3",ft=tt[Oe],it=i.useCallback((se,le=ve)=>{const pe=R(le,"flex-shrink-0"),Ce=Qn(se),qe={color:Ce?Ce.text:"var(--foreground)"};return se==="full"?e.jsx(br,{className:pe,style:qe}):se==="allow"?e.jsx(Uo,{className:pe,style:qe}):se==="deny"?e.jsx(An,{className:pe,style:qe}):e.jsx(on,{className:pe,style:qe})},[ve]),Pe=i.useCallback(se=>{mt||!b||!a||We(se)||(A(b,a,se,re),Se(!1),de(!1),G(!1))},[re,mt,b,a,A,Se,G,We]),ze=p(),lt=Array.isArray(ze?.models)?ze.models:[],Ke=t&&n?h(t,n):void 0,wt=hi(Ke),Pt=Gn(Ke,"input"),St=Gn(Ke,"output"),ge=i.useMemo(()=>`${t}/${n}`?m():[],[m,t,n]),Ie=ge.length>0,B=[{label:"Input",value:Oo(Ke?.cost?.input)},{label:"Output",value:Oo(Ke?.cost?.output)},{label:"Cache read",value:Oo(Ke?.cost?.cache_read)},{label:"Cache write",value:Oo(Ke?.cost?.cache_write)}],ce=[{label:"Context",value:Hs(Ke?.limit?.context)},{label:"Output",value:Hs(Ke?.limit?.output)}],ye=i.useRef(void 0),$e=b?v.get(b)?.length??-1:-1,Ue=i.useRef(null),st=i.useCallback((se,le,pe)=>{if(!se||!le)return"model-missing";const Ce=r.find(Re=>Re.id===se);return Ce?(Array.isArray(Ce.models)?Ce.models:[]).find(Re=>Re.id===le)?(c(se),d(le),b&&pe&&x(b,pe,se,le),"applied"):"model-missing":"provider-missing"},[r,c,d,b,x]);i.useEffect(()=>{if(!b){Ue.current=null;return}if(!D||r.length===0||w.length===0)return;(!Ue.current||Ue.current.sessionId!==b)&&(Ue.current={sessionId:b,resolved:!1,inFlight:!1});const se=Ue.current;if(!se||se.resolved||se.inFlight)return;let le=!1;const pe=()=>{if(le)return;const Re=Ue.current;Re&&Re.sessionId===b&&(Re.resolved=!0,Re.inFlight=!1)},Ce=()=>{const Re=k(b);if(Re){a!==Re&&f(Re);const Xe=N(b,Re);if(Xe){const Fe=st(Xe.providerId,Xe.modelId,Re);if(Fe==="applied")return"resolved";if(Fe==="provider-missing")return"waiting"}else return"resolved"}for(const Xe of w){const Fe=N(b,Xe.name);if(!Fe)continue;a!==Xe.name&&f(Xe.name),j(b,Xe.name);const at=st(Fe.providerId,Fe.modelId,Xe.name);if(at==="applied")return"resolved";if(at==="provider-missing")return"waiting"}return"continue"},Ge=()=>{if(w.length===0)return;const Re=w.filter(Fe=>Fo(Fe.mode)),Xe=w.find(Fe=>Fe.name==="build")||Re[0]||w[0];Xe&&(j(b,Xe.name),a!==Xe.name&&f(Xe.name),Xe.model?.providerID&&Xe.model?.modelID&&st(Xe.model.providerID,Xe.model.modelID,Xe.name))};return(async()=>{try{const Re=Ce();if(Re==="resolved"){pe();return}if(Re==="waiting"||$e===-1)return;if($e>0){se.inFlight=!0;try{const Xe=await M(b,w);if(le)return;if(Xe.size>0){let Fe=null,at=-1/0;for(const[Et,Dt]of Xe)Dt.timestamp>at&&(at=Dt.timestamp,Fe=Et);if(Fe){j(b,Fe),a!==Fe&&f(Fe);const Et=Xe.get(Fe);if(Et){const Dt=st(Et.providerId,Et.modelId,Fe);if(Dt==="applied"){pe();return}if(Dt==="provider-missing")return}else{pe();return}}}}catch(Xe){le||console.error("[ModelControls] Error resolving session from messages:",Xe)}finally{const Xe=Ue.current;!le&&Xe&&Xe.sessionId===b&&(Xe.inFlight=!1)}}Ge(),pe()}catch(Re){le||console.error("[ModelControls] Error in session switch:",Re)}})(),()=>{le=!0}},[b,$e,w,a,k,N,f,st,M,j,D,r]),i.useEffect(()=>{if(!D||!b||r.length===0||w.length===0)return;const le=k(b)||a;if(!le)return;const pe=N(b,le);if(!pe)return;const Ce=r.find(Xe=>Xe.id===pe.providerId);if(!Ce||!(Array.isArray(Ce.models)?Ce.models.some(Xe=>Xe.id===pe.modelId):!1))return;const qe=t===pe.providerId,Re=n===pe.modelId;qe&&Re||(le!==a&&f(le),st(pe.providerId,pe.modelId,le))},[D,b,a,t,n,r,w,k,N,st,f]),i.useEffect(()=>{if(!D)return;(async()=>{try{if(a!==ye.current&&(ye.current=a,a&&b)){await new Promise(Ce=>setTimeout(Ce,50));const le=N(b,a);if(le){const Ce=st(le.providerId,le.modelId,a);if(Ce==="applied"||Ce==="provider-missing")return}const pe=w.find(Ce=>Ce.name===a);if(pe?.model?.providerID&&pe?.model?.modelID&&st(pe.model.providerID,pe.model.modelID,a)==="provider-missing")return}}catch(le){console.error("[ModelControls] Agent change error:",le)}})()},[a,b,N,st,w,D]),i.useEffect(()=>{if(!D||!a){u(void 0);return}if(!t||!n){u(void 0);return}if(ge.length===0){u(void 0);return}if(o&&!ge.includes(o)){u(void 0);return}if(!b){if(!o){const pe=l&&ge.includes(l)?l:void 0;u(pe)}return}const se=C(b,a,t,n),le=se&&ge.includes(se)?se:void 0;u(le)},[ge,D,b,a,t,n,o,C,u,l]);const ke=i.useCallback(se=>{u(se),b&&a&&t&&n&&P(b,a,t,n,se)},[a,n,t,b,P,u]),Ye=se=>{try{f(se),Se(!1),b&&j(b,se),J&&T()}catch(le){console.error("[ModelControls] Handle agent change error:",le)}},Ze=(se,le)=>{try{const pe=st(se,le,a||void 0);if(pe!=="applied"){pe==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",se):pe==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:se,modelId:le});return}I(se,le),Se(!1),J&&T(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(pe){console.error("[ModelControls] Handle model change error:",pe)}},ot=se=>{const le=typeof se?.name=="string"?se.name:typeof se?.id=="string"?se.id:"";return le.length>40?le.substring(0,37)+"...":le},$t=()=>r.find(le=>le.id===t)?.name||t,Wt=()=>{if(!t||!n||lt.length===0)return"Not selected";const se=lt.find(le=>le.id===n);return ot(se)},jt=()=>{if(!a){const le=w.filter(Ge=>Fo(Ge.mode)),Ce=le.find(Ge=>Ge.name==="build")||le[0];return Ce?Ct(Ce.name):"Select Agent"}const se=w.find(le=>le.name===a);return Ct(se?se.name:a)},Ct=se=>se.charAt(0).toUpperCase()+se.slice(1),Ut=(se,le,pe)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:le,"aria-label":le,role:"img",children:e.jsx(se,{className:"h-3.5 w-3.5"})},pe),As=i.useCallback(se=>{ue(le=>{const pe=new Set(le);return pe.has(se)?pe.delete(se):pe.add(se),pe})},[]),sr=i.useCallback(se=>{W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{ae(se)},500)},[]),rr=i.useCallback(()=>{W.current&&clearTimeout(W.current)},[]);i.useEffect(()=>()=>{W.current&&clearTimeout(W.current)},[]);const Cr=()=>!J||X!=="model"?null:e.jsx(js,{open:!0,onClose:$,title:Ke?.name||Wt(),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()})]}),wt.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:wt.map(({key:se,icon:le,label:pe})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ut(le,pe,`cap-${se}`),e.jsx("span",{className:"typography-meta text-foreground",children:pe})]},se))})]}),(Pt.length>0||St.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:[Pt.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:Pt.map(({key:se,icon:le,label:pe})=>Ut(le,`${pe} input`,`input-${se}`))})]}),St.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:St.map(({key:se,icon:le,label:pe})=>Ut(le,`${pe} output`,`output-${se}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Hs(Ke?.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:Hs(Ke?.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:ud(Ke?.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:md(Ke?.release_date)})]})]})]})]})}),Bn=()=>{if(!J||X!=="agent"||!fe)return null;const se=!!(fe.prompt&&fe.prompt.trim().length>0),le=fe.model?.providerID&&fe.model?.modelID,pe=fe.temperature!==void 0||fe.topP!==void 0,Ce=Xe=>{const Fe=Sa(fe.permission)??[],at=Fe.some(Dt=>Dt.permission===Xe&&Dt.pattern!=="*"),Et=Ro(Fe,Xe)??"ask";return at?{mode:"ask",label:"Custom"}:Et==="allow"?{mode:"allow",label:"Allow"}:Et==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ge=Ce("edit"),qe=Ce("bash"),Re=Ce("webfetch");return e.jsx(js,{open:!0,onClose:$,title:Ct(fe.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[fe.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:fe.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:fe.mode==="primary"?"Primary":fe.mode==="subagent"?"Subagent":fe.mode==="all"?"All":"—"})]}),(le||pe)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),le&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[fe.model.providerID," / ",fe.model.modelID]}),pe&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[fe.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:fe.temperature})]}),fe.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:fe.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:[it(Ge.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ge.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:[it(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:[it(Re.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Re.label})]})]})]})]}),se&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(Uo,{className:"h-4 w-4 text-foreground"})]})})]})})},Vt=()=>{if(!J)return null;const se=O.trim(),le=r.map(pe=>{const Ce=Array.isArray(pe.models)?pe.models:[],Ge=se.length===0?!0:Rs(pe.name,se)||Rs(pe.id,se),qe=se.length===0?Ce:Ce.filter(Re=>{const Xe=ot(Re),Fe=typeof Re.id=="string"?Re.id:"";return Rs(Xe,se)||Rs(Fe,se)});return{provider:pe,providerModels:qe,matchesProvider:Ge}}).filter(({matchesProvider:pe,providerModels:Ce})=>pe||Ce.length>0);return e.jsx(js,{open:K==="model",onClose:T,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(Xs,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{value:O,onChange:pe=>z(pe.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),O&&e.jsx("button",{type:"button",onClick:()=>z(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(An,{className:"h-4 w-4"})})]})}),le.length===0&&e.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),!O&&Y.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(vr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Y.map(({model:pe,providerID:Ce,modelID:Ge})=>{const qe=Ce===t&&Ge===n,Re=h(Ce,Ge);return e.jsxs("button",{type:"button",onClick:()=>Ze(Ce,Ge),className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",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(ds,{providerId:Ce,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ot(pe)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Re?.limit?.context||Re?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Re?.limit?.context?`${Hs(Re?.limit?.context)} ctx`:"",Re?.limit?.context&&Re?.limit?.output?" • ":"",Re?.limit?.output?`${Hs(Re?.limit?.output)} out`:""]})})]},`fav-mobile-${Ce}-${Ge}`)})})]}),!O&&H.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(fr,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:H.map(({model:pe,providerID:Ce,modelID:Ge})=>{const qe=Ce===t&&Ge===n,Re=h(Ce,Ge);return e.jsxs("button",{type:"button",onClick:()=>Ze(Ce,Ge),className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",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(ds,{providerId:Ce,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ot(pe)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Re?.limit?.context||Re?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Re?.limit?.context?`${Hs(Re?.limit?.context)} ctx`:"",Re?.limit?.context&&Re?.limit?.output?" • ":"",Re?.limit?.output?`${Hs(Re?.limit?.output)} out`:""]})})]},`recent-mobile-${Ce}-${Ge}`)})})]}),le.map(({provider:pe,providerModels:Ce})=>{if(Ce.length===0&&!se.length)return null;const Ge=pe.id===t,qe=q.has(pe.id)||se.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>As(pe.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(ds,{providerId:pe.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:pe.name}),Ge&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),qe?e.jsx(Ft,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Is,{className:"h-3 w-3 text-muted-foreground"})]}),qe&&Ce.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Ce.map(Re=>{const Xe=Ge&&Re.id===n,Fe=h(pe.id,Re.id),at=hi(Fe).slice(0,3),Et=Gn(Fe,"input");return e.jsxs("div",{className:R("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 last:border-b-0","rounded-lg transition-colors",!Xe&&"hover:bg-muted",Xe?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Ze(pe.id,Re.id),className:R("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ot(Re)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Fe?.limit?.context||Fe?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Fe?.limit?.context?e.jsxs("span",{children:[Hs(Fe?.limit?.context)," ctx"]}):null,Fe?.limit?.context&&Fe?.limit?.output?e.jsx("span",{children:"•"}):null,Fe?.limit?.output?e.jsxs("span",{children:[Hs(Fe?.limit?.output)," out"]}):null]}),(at.length>0||Et.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...at,...Et].map(({key:Dt,icon:ws,label:zs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:zs,"aria-label":zs,children:e.jsx(ws,{className:"h-3 w-3"})},`meta-${pe.id}-${Re.id}-${Dt}`))})]})]}),e.jsx("button",{type:"button",onClick:Dt=>{Dt.preventDefault(),Dt.stopPropagation(),F(pe.id,Re.id)},className:R("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",E(pe.id,Re.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":E(pe.id,Re.id)?"Unfavorite":"Favorite",title:E(pe.id,Re.id)?"Remove from favorites":"Add to favorites",children:E(pe.id,Re.id)?e.jsx(vr,{className:"h-4 w-4"}):e.jsx(kn,{className:"h-4 w-4"})})]},Re.id)})})]},pe.id)})]})})},Gr=()=>{if(!J||!Ie)return null;const se=!o,le=pe=>{ke(pe),T(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(js,{open:K==="variant",onClose:T,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",se?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>le(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),se&&e.jsx(Bt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),ge.map(pe=>{const Ce=o===pe,Ge=pe.charAt(0).toUpperCase()+pe.slice(1);return e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",Ce?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>le(pe),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ge}),Ce&&e.jsx(Bt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},pe)})]})})},qr=()=>{if(!J)return null;const se=w.filter(le=>Fo(le.mode));return e.jsx(js,{open:K==="agent",onClose:T,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[se.map(le=>{const pe=le.name===a,Ce=Er(le.name);return e.jsxs("button",{type:"button",className:R("flex w-full flex-col gap-1 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary agent-list-item",Ce.class,pe?"active":"border-border/40"),onClick:()=>Ye(le.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-2 w-2 rounded-full",Ce.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:pe?{color:`var(${Ce.var})`}:void 0,children:Ct(le.name)})]}),le.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:le.description})]},le.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:mt,onClick:()=>{mt||de(le=>!le)},className:R("flex w-full items-center justify-between gap-2 px-2 py-1.5 text-left bg-transparent","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-t-xl",mt?"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:vt?vt.text:"var(--foreground)",mixBlendMode:"normal"},children:ft})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("flex items-center justify-center p-1",!vt&&"text-muted-foreground"),style:vt?{color:vt.text}:void 0,children:it(Oe,ve)}),e.jsx(Ft,{className:R("h-4 w-4 text-muted-foreground transition-transform",oe?"rotate-180":"")})]})]}),oe&&!mt&&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:rt.map(le=>{const pe=le.mode===Oe,Ce=Qn(le.mode);return e.jsxs("button",{type:"button",disabled:le.disabled,onClick:()=>Pe(le.mode),className:R("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",le.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",pe?"bg-primary/10":void 0),style:pe&&Ce?{backgroundColor:Ce.background??void 0}:void 0,children:[it(le.mode,ve),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:Ce?Ce.text:"var(--foreground)"},children:le.label})})]},le.mode)})})})]})]})})},Zl=()=>e.jsx(ct,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ke?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:Ke.name||Wt()}),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:wt.length>0?wt.map(({key:se,icon:le,label:pe})=>Ut(le,pe,`cap-${se}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),e.jsx("div",{className:"flex items-center gap-1.5",children:Pt.length>0?Pt.map(({key:se,icon:le,label:pe})=>Ut(le,`${pe} input`,`input-${se}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:St.length>0?St.map(({key:se,icon:le,label:pe})=>Ut(le,`${pe} output`,`output-${se}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),B.map(se=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:se.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:se.value})]},se.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),ce.map(se=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:se.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:se.value})]},se.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ud(Ke.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:md(Ke.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),fn=(se,le,pe,Ce,Ge,qe)=>{const Re=h(le,pe),Xe=hi(Re).map(xs=>({...xs,id:`cap-${xs.key}`})),Fe=[...Gn(Re,"input"),...Gn(Re,"output")],at=Array.from(new Map(Fe.map(xs=>[xs.key,xs])).values()).map(xs=>({...xs,id:`mod-${xs.key}`})),Et=[...Xe,...at],Dt=Hs(Re?.limit?.context),ws=t===le&&n===pe,zs=E(le,pe);return e.jsxs("div",{ref:xs=>{Ne.current[Ge]=xs},className:R("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:()=>Ze(le,pe),onMouseEnter:()=>Te(Ge),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(se)}),Re?.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:[Et.length>0&&e.jsx("div",{className:R("items-center gap-0.5",qe?"flex":"hidden group-hover:flex"),children:Et.map(({id:xs,icon:Zf,label:ec})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":ec,role:"img",title:ec,children:e.jsx(Zf,{className:"h-2.5 w-2.5"})},xs))}),ws&&e.jsx(Bt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:xs=>{xs.preventDefault(),xs.stopPropagation(),F(le,pe)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",zs?"text-yellow-500":"text-muted-foreground"),"aria-label":zs?"Unfavorite":"Favorite",title:zs?"Remove from favorites":"Add to favorites",children:zs?e.jsx(vr,{className:"h-3.5 w-3.5"}):e.jsx(kn,{className:"h-3.5 w-3.5"})})]})]},`${Ce}-${le}-${pe}`)},zn=(se,le,pe)=>pe.trim()?Rs(se,pe)||Rs(le,pe):!0,Ga=()=>{const se=Y.filter(({model:Fe,providerID:at})=>{const Dt=r.find(zs=>zs.id===at)?.name||at,ws=ot(Fe);return zn(ws,Dt,te)}),le=H.filter(({model:Fe,providerID:at})=>{const Dt=r.find(zs=>zs.id===at)?.name||at,ws=ot(Fe);return zn(ws,Dt,te)}),pe=r.map(Fe=>{const Et=(Array.isArray(Fe.models)?Fe.models:[]).filter(Dt=>{const ws=ot(Dt);return zn(ws,Fe.name||Fe.id||"",te)});return{...Fe,models:Et}}).filter(Fe=>Fe.models.length>0),Ce=se.length>0||le.length>0||pe.length>0,Ge=[];se.forEach(({model:Fe,providerID:at,modelID:Et})=>{Ge.push({model:Fe,providerID:at,modelID:Et,section:"fav"})}),le.forEach(({model:Fe,providerID:at,modelID:Et})=>{Ge.push({model:Fe,providerID:at,modelID:Et,section:"recent"})}),pe.forEach(Fe=>{Fe.models.forEach(at=>{Ge.push({model:at,providerID:Fe.id,modelID:at.id,section:"provider"})})});const qe=Ge.length,Re=Fe=>{if(Fe.key==="ArrowDown")Fe.preventDefault(),Fe.stopPropagation(),Te(at=>(at+1)%Math.max(1,qe)),setTimeout(()=>{const at=(me+1)%Math.max(1,qe);Ne.current[at]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Fe.key==="ArrowUp")Fe.preventDefault(),Fe.stopPropagation(),Te(at=>(at-1+Math.max(1,qe))%Math.max(1,qe)),setTimeout(()=>{const at=(me-1+Math.max(1,qe))%Math.max(1,qe);Ne.current[at]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Fe.key==="Enter"){Fe.preventDefault(),Fe.stopPropagation();const at=Ge[me];at&&Ze(at.providerID,at.modelID)}else Fe.key==="Escape"&&(Fe.preventDefault(),Fe.stopPropagation(),Se(!1))};let Xe=0;return e.jsxs(dt,{delayDuration:1e3,children:[J?e.jsxs("button",{type:"button",onClick:()=>ne("model"),onTouchStart:()=>sr("model"),onTouchEnd:rr,onTouchCancel:rr,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",Ot),children:[t?e.jsx(ds,{providerId:t,className:R(He,"flex-shrink-0")}):e.jsx(br,{className:R(He,"text-muted-foreground")}),e.jsx("span",{className:R("model-controls__model-label typography-micro font-medium truncate min-w-0",!L&&"max-w-[220px]"),children:Wt()})]}):e.jsxs(Yt,{open:je,onOpenChange:Se,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",Ot),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(ds,{providerId:t,className:R(He,"flex-shrink-0")}),e.jsx(br,{className:R(He,"text-primary/60 hidden")})]}):e.jsx(br,{className:R(He,"text-muted-foreground")}),e.jsx("span",{className:R("model-controls__model-label",Je,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:Wt()},`${t}-${n}`)]})})}),e.jsxs(Jt,{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(Xs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{type:"text",placeholder:"Search models",value:te,onChange:Fe=>xe(Fe.target.value),onKeyDown:Re,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(xt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Ce&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),se.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(vr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),se.map(({model:Fe,providerID:at,modelID:Et})=>{const Dt=Xe++;return fn(Fe,at,Et,"fav",Dt,me===Dt)})]}),le.length>0&&e.jsxs(e.Fragment,{children:[se.length>0&&e.jsx(Ss,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4"}),"Recent"]}),le.map(({model:Fe,providerID:at,modelID:Et})=>{const Dt=Xe++;return fn(Fe,at,Et,"recent",Dt,me===Dt)})]}),(se.length>0||le.length>0)&&pe.length>0&&e.jsx(Ss,{}),pe.map((Fe,at)=>e.jsxs(i.Fragment,{children:[at>0&&e.jsx(Ss,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ds,{providerId:Fe.id,className:"h-4 w-4 flex-shrink-0"}),Fe.name]}),Fe.models.map(Et=>{const Dt=Xe++;return fn(Et,Fe.id,Et.id,"provider",Dt,me===Dt)})]},Fe.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"})]})]}),Zl()]})},bo=()=>{if(!fe)return e.jsx(ct,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"No agent selected."})});const se=!!(fe.prompt&&fe.prompt.trim().length>0),le=fe.model?.providerID&&fe.model?.modelID,pe=fe.temperature!==void 0||fe.topP!==void 0,Ce=Xe=>{const Fe=Sa(fe.permission)??[],at=Fe.some(Dt=>Dt.permission===Xe&&Dt.pattern!=="*"),Et=Ro(Fe,Xe)??"ask";return at?{mode:"ask",label:"Custom"}:Et==="allow"?{mode:"allow",label:"Allow"}:Et==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ge=Ce("edit"),qe=Ce("bash"),Re=Ce("webfetch");return e.jsx(ct,{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:Ct(fe.name)}),fe.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:fe.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:fe.mode==="primary"?"Primary":fe.mode==="subagent"?"Subagent":fe.mode==="all"?"All":"—"})]}),(le||pe)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),le?e.jsxs("span",{className:"typography-meta text-foreground",children:[fe.model.providerID," / ",fe.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),pe&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[fe.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:fe.temperature})]}),fe.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:fe.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:[it(Ge.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ge.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:[it(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:[it(Re.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Re.label})]})]})]}),se&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(Uo,{className:"h-4 w-4 text-foreground"})]})]})})},qa=()=>{if(!Ie)return null;const se=o??"Default",le=!o,pe=le?"text-muted-foreground":"text-[color:var(--status-info)]";return J?e.jsxs("button",{type:"button",onClick:()=>ne("variant"),className:R("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ot,"cursor-pointer hover:opacity-70"),children:[e.jsx(pr,{className:R(He,"flex-shrink-0",pe)}),e.jsx("span",{className:R("model-controls__variant-label",Je,"font-medium truncate min-w-0",pe),children:se})]}):e.jsxs(dt,{delayDuration:800,children:[e.jsxs(Yt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:R("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ot),children:[e.jsx(pr,{className:R(He,"flex-shrink-0",pe)}),e.jsx("span",{className:R("model-controls__variant-label",Je,"font-medium min-w-0 truncate",U?"max-w-[180px]":void 0,pe),children:se})]})})}),e.jsxs(Jt,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Pr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(It,{className:"typography-meta",onSelect:()=>ke(void 0),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:"Default"}),le&&e.jsx(Bt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),ge.length>0&&e.jsx(Ss,{}),ge.map(Ce=>{const Ge=o===Ce,qe=Ce.charAt(0).toUpperCase()+Ce.slice(1);return e.jsx(It,{className:"typography-meta",onSelect:()=>ke(Ce),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}),Ge&&e.jsx(Bt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},Ce)})]})]}),e.jsx(ct,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",se]})})]})},Ka=()=>J?e.jsxs("button",{type:"button",onClick:()=>ne("agent"),onTouchStart:()=>sr("agent"),onTouchEnd:rr,onTouchCancel:rr,className:R("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ot,"cursor-pointer hover:opacity-70",J&&"ml-1"),children:[e.jsx(an,{className:R(He,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Er(a).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",Je,"font-medium truncate min-w-0"),style:a?{color:`var(${Er(a).var})`}:void 0,children:jt()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(dt,{delayDuration:1e3,children:[e.jsxs(Yt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ot),children:[e.jsx(an,{className:R(He,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Er(a).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",Je,"font-medium min-w-0 truncate",U?"max-w-[220px]":void 0),style:a?{color:`var(${Er(a).var})`}:void 0,children:jt()})]})})}),e.jsxs(Jt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[w.filter(se=>Fo(se.mode)).map(se=>e.jsx(It,{className:"typography-meta",onSelect:()=>Ye(se.name),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-1 w-1 rounded-full agent-dot",Er(se.name).class)}),e.jsx("span",{className:"font-medium",children:Ct(se.name)})]}),se.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:se.description})]})},se.name)),e.jsx(Ss,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:mt,onClick:()=>{mt||G(se=>!se)},className:R("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",mt?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Le,"aria-controls":ee,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:vt?vt.text:"var(--foreground)"},children:ft})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("flex items-center justify-center p-1",!vt&&"text-muted-foreground"),style:vt?{color:vt.text}:void 0,children:it(Oe)}),e.jsx(Ft,{className:R("h-3.5 w-3.5 transition-transform text-muted-foreground",Le?"rotate-180":"")})]})]}),Le&&!mt&&e.jsx("div",{id:ee,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:rt.map(se=>{const le=se.mode===Oe,pe=Qn(se.mode);return e.jsxs("button",{type:"button",disabled:se.disabled,onClick:()=>Pe(se.mode),className:R("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",se.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",le?"bg-primary/10":void 0),style:le&&pe?{backgroundColor:pe.background??void 0}:void 0,children:[it(se.mode,ve),e.jsx("span",{className:"typography-meta font-medium",style:{color:pe?pe.text:"var(--foreground)"},children:se.label})]},se.mode)})})]})]})]}),bo()]})}),ie=R("@container/model-controls flex items-center min-w-0",L&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:ie,children:e.jsxs("div",{className:R("flex items-center min-w-0 flex-1 justify-end",Qe,L&&"overflow-hidden"),children:[qa(),Ga(),Ka()]})}),Vt(),Gr(),qr(),Cr(),Bn()]})},Av=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,pd=(s,r)=>{if(typeof s!="string"||s.length===0)return{sanitizedText:s,mention:null};const t=r.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!s.includes("#"))return{sanitizedText:s,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let l;for(;(l=a.exec(s))!==null;){const c=l.index,d=c+l[0].length,u=c>0?s[c-1]:null;if(!Av(u))continue;const m={name:o.name,source:{value:l[0],start:c,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},af=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),el=Kt()(ss((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const n=he.getState().getDirectoryForSession(t),a=(n?await Ee.withDirectory(n,()=>Ee.getSessionTodos(t)):await Ee.getSessionTodos(t)).map(af);s(l=>{const c=new Map(l.sessionTodos);return c.set(t,a),{sessionTodos:c,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),s({isLoading:!1})}}},updateTodos:(t,n)=>{s(o=>{const a=new Map(o.sessionTodos);return a.set(t,n),{sessionTodos:a}})},getTodosForSession:t=>r().sessionTodos.get(t)||[],clearTodos:t=>{s(n=>{const o=new Map(n.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),Ev=(s,r)=>{const t=r.map(af);el.getState().updateTodos(s,t)},hd=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(vn.span,{...t,className:R("bg-[linear-gradient(110deg,#bfbfbf,35%,#000,50%,#bfbfbf,75%,#bfbfbf)] dark:bg-[linear-gradient(110deg,#404040,35%,#fff,50%,#404040,75%,#404040)]","bg-[length:200%_100%] bg-clip-text text-transparent",r),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:s})},{variant:"generate-effect",component:({children:s,className:r,...t})=>typeof s!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:s.split("").map((n,o)=>Ae.createElement(vn.span,{...t,key:n+String(o),className:R("inline-block whitespace-pre text-primary-foreground",r),initial:{opacity:0,filter:"blur(4px)",rotateX:90,y:5},whileInView:{opacity:1,filter:"blur(0px)",rotateX:0,y:0},transition:{ease:"easeOut",duration:.3,delay:o*.015},viewport:{once:!0}},n))})},{variant:"glitch",component:({children:s,className:r,...t})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...t,className:R("invisible",r),children:s}),e.jsx("span",{...t,className:R("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",r),children:s}),e.jsx("span",{...t,className:R("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",r),children:s})]})},{variant:"hover-enter",component:({children:s,className:r,...t})=>{if(typeof s!="string")return null;const n=.25,o=.025,a=s.split("").map(l=>l===" "?" ":l);return e.jsxs(vn.span,{...t,className:R("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((l,c)=>e.jsx(vn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))}),e.jsx("div",{className:R("absolute inset-0"),children:a.map((l,c)=>e.jsx(vn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:R("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:R("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:e.jsx("span",{...t,className:R("text-primary-muted",r),children:s})})}];function gi({variant:s="shine",className:r,...t}){const a=hd.find(l=>l.variant===s)?.component||hd[0].component;return e.jsx(Cu,{children:e.jsx(a,{...t,className:r})})}const gd=1500,Iv=2e3;function Pv({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:l}){const[c,d]=Ae.useState("idle"),[u,m]=Ae.useState(null),[f,p]=Ae.useState(!1),h=Ae.useRef(0),y=Ae.useRef(null),g=Ae.useRef(null),w=Ae.useRef(null),b=Ae.useRef(null),v=Ae.useRef(!1),j=Ae.useRef(!1),k=Ae.useRef(!1),x=Ae.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),w.current&&(clearTimeout(w.current),w.current=null)},[]),N=Ae.useCallback((F,E)=>{x(),y.current=null,m(F),p(E),d("showing"),h.current=Date.now(),v.current=!0},[x]),P=Ae.useCallback(()=>{if(g.current)return;const F=Date.now()-h.current,E=Math.max(0,gd-F);g.current=setTimeout(()=>{g.current=null;const I=y.current;I&&N(I.text,I.permission)},E)},[N]),C=Ae.useCallback(F=>{if(x(),y.current=null,!v.current){d("idle"),m(null),l?.(!1);return}if(F==="done"&&o&&b.current===o){d("idle"),m(null),v.current=!1,l?.(!1);return}F==="done"&&o&&(b.current=o),d(F),m(null),l?.(!0),w.current=setTimeout(()=>{w.current=null,d("idle"),v.current=!1,l?.(!1)},Iv)},[x,o,l]);if(Ae.useEffect(()=>{if(n&&!k.current){k.current=!0,C("aborted");return}if(k.current=!!n,a&&!j.current){j.current=!0,C("done");return}if(!a&&j.current&&(j.current=!1),!(c==="done"||c==="aborted")&&s){const E=Date.now()-h.current;if(c==="idle"||!u)N(s,!!t);else if(s!==u||!!t!==f){if(r)return;E>=gd?N(s,!!t):(y.current={text:s,permission:!!t},P())}}},[s,t,n,a,c,u,f,N,C,P,r]),Ae.useEffect(()=>()=>x(),[x]),Ae.useEffect(()=>{const F=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(x(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",F),()=>document.removeEventListener("visibilitychange",F)},[c,x]),c==="idle"&&!u)return null;let M,S=!0;c==="done"?(M="Done",S=!1):c==="aborted"?(M="Aborted",S=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const A=S?`${M}...`:M,D=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${D?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(gi,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(gi,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(gi,{variant:"shine",className:"typography-ui-header",children:A})})})}const xd={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:s})=>{const r=xd[s.status]||xd.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:s.content})})},yd=[],Fv=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:l,isComplete:c,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=i.useState(!1),h=he(E=>E.currentSessionId),y=el(E=>h?E.sessionTodos.get(h)??yd:yd),g=el(E=>E.loadTodos),{isMobile:w}=_e(),b=w||zt();i.useEffect(()=>{h&&g(h)},[h,g]);const v=i.useMemo(()=>{const E={in_progress:0,pending:1,completed:2,cancelled:3};return[...y].filter(I=>I.status!=="cancelled").sort((I,_)=>E[I.status]-E[_.status])},[y]),j=i.useMemo(()=>v.find(E=>E.status==="in_progress")||v.find(E=>E.status==="pending")||null,[v]),k=i.useMemo(()=>{const E=y.filter(_=>_.status!=="cancelled").length;return{completed:y.filter(_=>_.status==="completed").length,total:E}},[y]),x=v.some(E=>E.status==="in_progress"||E.status==="pending"),N=!m&&(o||!a),[P,C]=i.useState(!1),M=s||c||o||P||x||m,S=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const E=I=>{S.current&&!S.current.contains(I.target)&&p(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),!M)return null;const A=()=>p(E=>!E),D=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(An,{size:18,"aria-hidden":"true"})}):null,F=x?e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!b&&j?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:j.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[k.completed,"/",k.total]}),f?e.jsx(Aa,{className:"h-3.5 w-3.5"}):e.jsx(Ft,{className:"h-3.5 w-3.5"})]}):null;return e.jsx("div",{className:"chat-column mb-1",style:{containerType:"inline-size"},children:e.jsxs("div",{className:"flex items-center justify-between pr-[2ch] py-0.5 gap-2 h-[1.2rem]",children:[e.jsx("div",{className:"flex-1 flex items-center overflow-hidden min-w-0",children:m?e.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-[2ch]",children:e.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[e.jsx(An,{size:16,"aria-hidden":"true"}),"Aborted"]})}):N?e.jsx(Pv,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:l??null,isComplete:c,onResultVisibilityChange:C},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:S,children:[D,F,f&&x&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:R("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[k.completed,"/",k.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:v.map(E=>e.jsx(Tv,{todo:E},E.id))})]})]})]})})},tl=s=>!s||typeof s!="object"?!1:!!s.synthetic,bd=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>tl(r)),Rv=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!tl(t))?s.filter(t=>!tl(t)):s,Ov={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function _v(s){const r=he(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return i.useMemo(()=>{if(r==="idle")return Ov;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function Hl(){const s=he(r=>r.currentSessionId);return _v(s)}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},vd=s=>s.role==="assistant",Lv=s=>s.type==="reasoning",lf=s=>s.type==="text",wd=s=>{if(lf(s))return s.text;const r=s;if(typeof r.text=="string")return r.text;if(typeof r.content=="string")return r.content;if(typeof r.value=="string")return r.value},jd=s=>(lf(s)||Lv(s),s.time),Bv=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function cf(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=he(fl(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:l}=Hl(),c=i.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=i.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=c.filter(M=>vd(M.info)&&!bd(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const y=[...h].sort((M,S)=>{const A=typeof M.info.time?.created=="number"?M.info.time.created:null,D=typeof S.info.time?.created=="number"?S.info.time.created:null;return A!==null&&D!==null&&A!==D?A-D:M.info.id.localeCompare(S.info.id)}),g=y[y.length-1];let w,b;const v=new Set(["edit","write"]);for(let M=(g.parts??[]).length-1;M>=0;M-=1){const S=g.parts?.[M];if(S)switch(S.type){case"reasoning":{const A=S.time??jd(S);(!A||typeof A.end>"u")&&!w&&(w="reasoning");break}case"tool":{const A=S.state?.status;if((A==="running"||A==="pending")&&!w){const D=Bv(S);v.has(D)?w="editing":(w="tool",b=D)}break}case"text":{const A=wd(S)??"";if(typeof A=="string"&&A.trim().length>0){const D=jd(S);(!D||typeof D.end>"u")&&!w&&(w="text")}break}}}const j={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos",skill:"learning skill",question:"asking question"},k=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],x=M=>j[M]??`using ${M}`,N=()=>k[Math.floor(Math.random()*k.length)],P=w===void 0,C=w==="editing"?"editing file":w==="tool"&&b?x(b):w==="reasoning"?"thinking":w==="text"?"composing":N();return{activePartType:w,activeToolName:b,statusText:C,isGenericStatus:P}},[c]),u=i.useMemo(()=>{const h=s,y=h?n?.get(h)??null:null,g=!!(y&&!y.acknowledged);return{wasAborted:g,abortActive:g}},[s,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,y=o==="busy",g=l;let w="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?w="tooling":w=g?"cooldown":"streaming"),{activity:w,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:y,isCooldown:g,lifecyclePhase:y?"streaming":g?"cooldown":null,statusText:h?d.statusText:null,isGenericStatus:h?d.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:h,compactionDeadline:null,activePartType:h?d.activePartType:void 0,activeToolName:h?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:g}},[o,a,l,d,u]),f=i.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const y=c.filter(b=>vd(b.info)&&!bd(b.parts));if(y.length===0)return{isActive:h,characterCount:0};const g=y[y.length-1];let w=0;return(g.parts??[]).forEach(b=>{if(b.type!=="text")return;const v=wd(b)??"";typeof v=="string"&&v.trim().length>0&&(w+=v.length)}),{isActive:h,characterCount:w}},[c,a,d.activePartType]),p=i.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const h=s;return(h?t?.get(h)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[s,t,m]);return{forming:f,working:p}}const zv=8,Sd=[],Wv=s=>s==="primary"||s==="all"||s===void 0||s===null,df=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},kd=(s,r)=>{const t=df(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Hv=(s,r)=>{const t=df(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},_o=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=i.useState(""),[o,a]=i.useState(!1),[l,c]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState(!1),[p,h]=i.useState(""),[y,g]=i.useState(!1),[w,b]=i.useState(""),[v,j]=i.useState(!1),[k,x]=i.useState(""),[N,P]=i.useState(null),C=i.useRef(null),M=i.useRef(null),S=i.useRef(null),A=i.useRef(null),D=i.useRef(null),F=i.useRef(null),E=he(ie=>ie.sendMessage),I=he(ie=>ie.currentSessionId),_=he(ie=>ie.newSessionDraft?.open),V=he(ie=>ie.abortCurrentOperation),Y=he(ie=>ie.acknowledgeSessionAbort),H=he(ie=>ie.abortPromptSessionId),L=he(ie=>ie.abortPromptExpiresAt),U=he(ie=>ie.clearAbortPrompt),Q=he(ie=>ie.sessionAbortFlags),J=he(ie=>ie.attachedFiles),K=he(ie=>ie.addAttachedFile),ne=he(ie=>ie.addServerFile),X=he(ie=>ie.clearAttachedFiles),ae=he(ie=>ie.saveSessionAgentSelection),O=he(ie=>ie.consumePendingInputText),z=he(ie=>ie.pendingInputText),{currentProviderId:T,currentModelId:$,currentVariant:W,currentAgentName:q,setAgent:ue,getVisibleAgents:oe}=nt(),de=oe(),{isMobile:je,inputBarOffset:Se,isKeyboardOpen:Le,setTimelineDialogOpen:G}=_e(),{working:ee}=cf(),[te,xe]=i.useState(!1),me=i.useRef(null),Te=i.useRef(!1),Ne=i.useRef(!1),Be=lr(ie=>ie.queueModeEnabled),fe=lr(i.useCallback(ie=>I?ie.queuedMessages[I]??Sd:Sd,[I])),ht=lr(ie=>ie.addToQueue),bt=lr(ie=>ie.clearQueue),{phase:Nt}=Hl(),Me=i.useRef(Nt),re=i.useRef(!1),et=i.useCallback(ie=>{if(!je||ie.pointerType!=="touch")return;const se=C.current;if(!se||document.activeElement===se)return;ie.preventDefault(),ie.stopPropagation();const le=document.scrollingElement;le&&le.scrollTop!==0&&(le.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{se.focus({preventScroll:!0})}catch{se.focus()}const pe=se.value.length;try{se.setSelectionRange(pe,pe)}catch{}},[je]);i.useEffect(()=>{if(z!==null){const ie=O();ie&&(n(ie),setTimeout(()=>{C.current?.focus()},0))}},[z,O]);const be=i.useMemo(()=>{if(q)return de.find(ie=>ie.name===q)},[de,q]),we=i.useMemo(()=>be?kd(be.permission,"edit")??"ask":"deny",[be]),Ve=he(i.useCallback(ie=>!I||!q?void 0:ie.sessionAgentEditModes.get(I)?.get(q),[I,q])),tt=i.useMemo(()=>{if(be)return kd(be.permission,"webfetch")},[be]),We=i.useMemo(()=>{if(!be)return;const ie=Hv(be.permission,"bash");return ie||void 0},[be]),Oe=i.useMemo(()=>of({agentDefaultEditMode:we,webfetchPermission:tt,bashPermission:We}),[we,tt,We]),rt=!!(I&&q),vt=i.useMemo(()=>rt&&Ve&&Oe.modeAvailability[Ve]?Ve:Oe.cascadeDefaultMode,[Oe,rt,Ve]),mt=i.useMemo(()=>Qn(vt),[vt]),Tt=i.useCallback(ie=>zt()?`color-mix(in srgb, ${ie} 55%, transparent)`:ie,[]),Ot=i.useMemo(()=>{const ie=zt()?1:2;if(!mt)return{borderWidth:ie};const se=mt.border??mt.text;return{borderColor:Tt(se),borderWidth:ie}},[mt,Tt]),ve=t.trim()||J.length>0,He=fe.length>0,Je=ve||He,Qe=ee.isWorking,ft=i.useMemo(()=>I?H===I&&!!L:!1,[H,L,I]),it=i.useCallback(()=>{if(!ve||!I)return;const ie=t.replace(/^\n+|\n+$/g,""),se=J.map(le=>({...le}));ht(I,{content:ie,attachments:se.length>0?se:void 0}),n(""),se.length>0&&X(),je||C.current?.focus()},[ve,I,t,J,ht,X,je]),Pe=async ie=>{if(ie?.preventDefault(),!Je||!I&&!_)return;if(r?.({instant:!0,force:!0}),!T||!$){console.warn("Cannot send message: provider or model not selected");return}let se="",le=[],pe;const Ce=[];for(let Re=0;Re<fe.length;Re++){const Xe=fe[Re],{sanitizedText:Fe,mention:at}=pd(Xe.content,de);!pe&&at?.name&&(pe=at.name),Re===0?(se=Fe,le=Xe.attachments??[]):Ce.push({text:Fe,attachments:Xe.attachments})}if(ve){const Re=t.replace(/^\n+|\n+$/g,""),{sanitizedText:Xe,mention:Fe}=pd(Re,de),at=J.map(Et=>({...Et}));!pe&&Fe?.name&&(pe=Fe.name),fe.length===0?(se=Xe,le=at):Ce.push({text:Xe,attachments:at.length>0?at:void 0})}if(!se&&Ce.length===0)return;I&&He&&bt(I),n(""),J.length>0&&X(),je&&C.current?.blur();const Ge=se.trimStart();if(Ge.startsWith("/")){const Re=Ge.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Re==="undo"&&I){await he.getState().handleSlashUndo(I),r?.({instant:!0,force:!0});return}else if(Re==="redo"&&I){await he.getState().handleSlashRedo(I),r?.({instant:!0,force:!0});return}else if(Re==="timeline"&&I){G(!0),n("");return}else if(Re==="compact"&&I){try{const{opencodeClient:Xe}=await ls(async()=>{const{opencodeClient:Et}=await Promise.resolve().then(()=>_g);return{opencodeClient:Et}},void 0),Fe=Xe.getDirectory();if((await Xe.getApiClient().session.summarize({sessionID:I,directory:Fe||void 0,providerID:T,modelID:$})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Xe){console.error("Failed to compact session:",Xe),Z.error("Failed to compact session")}n("");return}}const qe=[...le,...Ce.flatMap(Re=>Re.attachments??[])];await E(se,T,$,q,le,pe,Ce.length>0?Ce:void 0,W).catch(Re=>{const Xe=Re instanceof Error?Re.message:typeof Re=="string"?Re:String(Re??""),Fe=Xe.toLowerCase();console.error("Message send failed:",Xe||Re);const at=Fe.includes("timeout")||Fe.includes("timed out")||Fe.includes("may still be processing")||Fe.includes("being processed")||Fe.includes("failed to fetch")||Fe.includes("networkerror")||Fe.includes("network error")||Fe.includes("gateway timeout")||Fe==="failed to send message";if(Fe.includes("payload too large")||Fe.includes("413")||Fe.includes("entity too large")){Z.error("Attachments are too large to send. Please try reducing the number or size of images."),qe.length>0&&Ys.setState({attachedFiles:qe});return}at||(qe.length>0&&Ys.setState({attachedFiles:qe}),Z.error(Xe||"Message failed to send. Attachments restored."))}),je||C.current?.focus()},ze=i.useRef(Pe);ze.current=Pe,i.useEffect(()=>{const ie=Me.current==="busy"||Me.current==="cooldown",se=Nt==="idle",le=I&&Q.has(I)&&(()=>{const pe=Q.get(I);return pe?Date.now()-pe.timestamp<2e3:!1})();ie&&se&&fe.length>0&&!re.current&&!le&&(re.current=!0,setTimeout(()=>{I&&T&&$&&ze.current(),re.current=!1},100)),Me.current=Nt},[Nt,fe.length,I,T,$,Q]);const lt=ie=>{if(!Bl(ie)){if(m&&A.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),A.current.handleKeyDown(ie.key);return}if(y&&D.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),D.current.handleKeyDown(ie.key);return}if(v&&F.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),F.current.handleKeyDown(ie.key);return}if(l&&S.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),S.current.handleKeyDown(ie.key);return}if(ie.key==="Tab"&&!m&&!y&&!l){ie.preventDefault(),Pt();return}if(ie.key==="Enter"&&!ie.shiftKey&&!je){ie.preventDefault();const se=ie.ctrlKey||ie.metaKey,le=ve&&I&&Nt!=="idle";Be?se||!le?Pe():it():se&&le?it():Pe()}}},Ke=i.useCallback(()=>{me.current&&(clearTimeout(me.current),me.current=null),xe(!0),me.current=setTimeout(()=>{xe(!1),me.current=null},1800)},[]),wt=i.useCallback(()=>{U(),Ke(),V()},[V,U,Ke]),Pt=()=>{const ie=de.filter(Ce=>Wv(Ce.mode));if(ie.length<=1)return;const le=(ie.findIndex(Ce=>Ce.name===q)+1)%ie.length,pe=ie[le];ue(pe.name),I&&ae(I,pe.name)},St=i.useCallback(()=>{const ie=C.current;if(!ie)return;ie.style.height="auto";const se=ie.ownerDocument?.defaultView,le=se?se.getComputedStyle(ie):null,pe=le?parseFloat(le.lineHeight):NaN,Ce=le?parseFloat(le.paddingTop):NaN,Ge=le?parseFloat(le.paddingBottom):NaN,qe=22,Xe=Number.isNaN(Ce)||Number.isNaN(Ge)?16:Ce+Ge,at=(Number.isNaN(pe)?qe:pe)*zv+Xe,Et=ie.scrollHeight||ie.offsetHeight,Dt=Math.min(Et,at);ie.style.height=`${Dt}px`,ie.style.maxHeight=`${at}px`,P(ws=>ws&&ws.height===Dt&&ws.maxHeight===at?ws:{height:Dt,maxHeight:at})},[]);i.useLayoutEffect(()=>{St()},[St,t,je]);const ge=i.useCallback((ie,se)=>{if(ie.startsWith("/")){const qe=ie.indexOf(" "),Re=ie.indexOf(`
88
+ `),Xe=Math.min(qe===-1?ie.length:qe,Re===-1?ie.length:Re);if(se<=Xe&&qe===-1){const Fe=ie.substring(1,Xe);h(Fe),f(!0),c(!1),g(!1),j(!1);return}}f(!1);const le=ie.substring(0,se),pe=le.lastIndexOf("#");if(pe!==-1){const qe=pe>0?le[pe-1]:null,Re=le.substring(pe+1),Xe=Re.includes(" ")||Re.includes(`
89
+ `);if((!qe||/\s/.test(qe))&&!Xe){b(Re),g(!0),c(!1);return}}g(!1),b("");const Ce=le.lastIndexOf("/");if(Ce!==-1){const qe=Ce>0?le[Ce-1]:null,Re=le.substring(Ce+1),Xe=Re.includes(" ")||Re.includes(`
90
+ `);if((!qe||/\s/.test(qe))&&!Xe){x(Re),j(!0),c(!1),g(!1);return}}j(!1),x("");const Ge=le.lastIndexOf("@");if(Ge!==-1){const qe=le.substring(Ge+1);!qe.includes(" ")&&!qe.includes(`
91
+ `)?(u(qe),c(!0)):c(!1)}else c(!1)},[b,h,u,g,f,c,j,x]),Ie=i.useCallback(ie=>{if(!ie)return;const se=C.current;if(!se){const qe=t+ie;n(qe),ge(qe,qe.length),requestAnimationFrame(()=>St());return}const le=se.selectionStart??t.length,pe=se.selectionEnd??t.length,Ce=`${t.substring(0,le)}${ie}${t.substring(pe)}`;n(Ce);const Ge=le+ie.length;requestAnimationFrame(()=>{const qe=C.current;qe&&(qe.selectionStart=Ge,qe.selectionEnd=Ge),St()}),ge(Ce,Ge)},[St,t,ge]),B=ie=>{const se=ie.target.value,le=ie.target.selectionStart??se.length;n(se),St(),ge(se,le)},ce=i.useCallback(async ie=>{const se=new Map;Array.from(ie.clipboardData.files||[]).forEach(Ge=>{Ge.type.startsWith("image/")&&se.set(`${Ge.name}-${Ge.size}`,Ge)}),Array.from(ie.clipboardData.items||[]).forEach(Ge=>{if(Ge.kind==="file"&&Ge.type.startsWith("image/")){const qe=Ge.getAsFile();qe&&se.set(`${qe.name}-${qe.size}`,qe)}});const le=Array.from(se.values());if(le.length===0||!I&&!_)return;ie.preventDefault();const pe=ie.clipboardData.getData("text");pe&&Ie(pe);let Ce=0;for(const Ge of le){const qe=he.getState().attachedFiles.length;try{await K(Ge),he.getState().attachedFiles.length>qe&&(Ce+=1)}catch(Re){console.error("Clipboard image attach failed",Re),Z.error(Re instanceof Error?Re.message:"Failed to attach image from clipboard")}}Ce>0&&Z.success(`Attached ${Ce} image${Ce>1?"s":""} from clipboard`)},[K,I,_,Ie]),ye=ie=>{const se=C.current?.selectionStart||0,pe=t.substring(0,se).lastIndexOf("@");if(pe!==-1){const Ce=t.substring(0,pe)+ie.name+t.substring(se);n(Ce)}c(!1),u(""),C.current?.focus()},$e=ie=>{const le=C.current?.selectionStart??t.length,Ce=t.substring(0,le).lastIndexOf("#");if(Ce!==-1){const Ge=t.substring(0,Ce)+`#${ie} `+t.substring(le);n(Ge);const qe=Ce+ie.length+2;requestAnimationFrame(()=>{C.current&&(C.current.selectionStart=qe,C.current.selectionEnd=qe),St(),ge(Ge,qe)})}g(!1),b(""),C.current?.focus()},Ue=ie=>{const le=C.current?.selectionStart??t.length,Ce=t.substring(0,le).lastIndexOf("/");if(Ce!==-1){const Ge=t.substring(0,Ce)+`${ie} `+t.substring(le);n(Ge);const qe=Ce+ie.length+1;requestAnimationFrame(()=>{C.current&&(C.current.selectionStart=qe,C.current.selectionEnd=qe),St(),ge(Ge,qe)})}j(!1),x(""),C.current?.focus()},st=ie=>{n(`/${ie.name} `);const se=C.current;se&&(se._commandMetadata=ie),f(!1),h(""),setTimeout(()=>{C.current&&(C.current.focus(),C.current.setSelectionRange(C.current.value.length,C.current.value.length))},0)};i.useEffect(()=>{I&&C.current&&!je&&C.current.focus()},[I,je]),i.useEffect(()=>{H&&H!==I&&U()},[H,I,U]);const ke=ie=>{ie.preventDefault(),ie.stopPropagation(),(I||_)&&!o&&a(!0)},Ye=ie=>{ie.preventDefault(),ie.stopPropagation(),ie.currentTarget===ie.target&&a(!1)},Ze=async ie=>{if(ie.preventDefault(),ie.stopPropagation(),a(!1),!I&&!_)return;const se=Array.from(ie.dataTransfer.files);let le=0;for(const pe of se){const Ce=he.getState().attachedFiles.length;try{await K(pe),he.getState().attachedFiles.length>Ce&&(le+=1)}catch(Ge){console.error("File attach failed",Ge),Z.error(Ge instanceof Error?Ge.message:"Failed to attach file")}}le>0&&Z.success(`Attached ${le} file${le>1?"s":""}`)},ot=i.useCallback(async ie=>{let se=0;for(const le of ie){const pe=he.getState().attachedFiles.length;try{await ne(le.path,le.name),he.getState().attachedFiles.length>pe&&(se+=1)}catch(Ce){console.error("Server file attach failed",Ce),Z.error(Ce instanceof Error?Ce.message:"Failed to attach file")}}se>0&&Z.success(`Attached ${se} file${se>1?"s":""}`)},[ne]),$t=i.useRef(null),[Wt,jt]=i.useState(!1),Ct=i.useCallback(async ie=>{let se=0;const le=Array.isArray(ie)?ie:Array.from(ie);for(const pe of le){const Ce=he.getState().attachedFiles.length;try{await K(pe),he.getState().attachedFiles.length>Ce&&(se+=1)}catch(Ge){console.error("File attach failed",Ge),Z.error(Ge instanceof Error?Ge.message:"Failed to attach file")}}se>0&&Z.success(`Attached ${se} file${se>1?"s":""}`)},[K]),Ut=i.useCallback(async()=>{try{const se=await(await fetch("/api/vscode/pick-files")).json(),le=Array.isArray(se?.files)?se.files:[],pe=Array.isArray(se?.skipped)?se.skipped:[];if(pe.length>0){const Ge=pe.map(qe=>`${qe?.name||"file"}: ${qe?.reason||"skipped"}`).join(`
92
+ `);Z.error(`Some files were skipped:
93
+ ${Ge}`)}const Ce=le.map(Ge=>{if(!Ge?.dataUrl)return null;try{const[qe,Re]=Ge.dataUrl.split(","),Xe=Ge.mimeType||qe?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Re)return null;const Fe=atob(Re),at=new Uint8Array(Fe.length);for(let Dt=0;Dt<Fe.length;Dt++)at[Dt]=Fe.charCodeAt(Dt);const Et=new Blob([at],{type:Xe});return new File([Et],Ge.name||"file",{type:Xe})}catch(qe){return console.error("Failed to decode VS Code picked file",qe),null}}).filter(Boolean);Ce.length>0&&await Ct(Ce)}catch(ie){console.error("VS Code file pick failed",ie),Z.error(ie instanceof Error?ie.message:"Failed to pick files in VS Code")}},[Ct]),As=i.useCallback(()=>{if(zt()){Ut();return}$t.current?.click()},[Ut]),sr=i.useCallback(async ie=>{const se=ie.target.files;se&&(await Ct(se),ie.target.value="")},[Ct]),rr="gap-x-1.5 gap-y-0",Cr=zt(),Bn=je?"px-1.5 py-1.5":Cr?"px-1.5 py-1":"px-2.5 py-1.5",Vt=je?"h-9 w-9":Cr?"h-[22px] w-[22px]":"h-7 w-7",Gr=je?"h-5 w-5":Cr?"h-4 w-4":"h-[18px] w-[18px]",qr=R(Vt,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),fn=!je&&ft&&Qe?e.jsx("button",{type:"button",onClick:wt,className:R(qr,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(An,{className:R(Gr)})}):e.jsx("button",{type:je?"button":"submit",disabled:!Je||!I&&!_,onPointerDownCapture:ie=>{!je||ie.pointerType!=="touch"||!Je||!I&&!_||(Ne.current=!0,ie.preventDefault(),ie.stopPropagation(),Pe())},onClick:ie=>{if(je){if(Ne.current){Ne.current=!1;return}ie.preventDefault(),Pe()}},className:R(qr,Je&&(I||_)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Ma,{className:R(Gr)})}),zn=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:$t,type:"file",multiple:!0,className:"hidden",onChange:sr,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(bv,{onFilesSelected:ot,multiSelect:!0,presentation:je?"modal":"dropdown",open:Wt,onOpenChange:jt,children:je?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx("button",{type:"button",className:qr,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(Ru,{className:R(Gr,"text-current")})})}),e.jsxs(Jt,{align:"start",children:[e.jsxs(It,{onSelect:()=>{requestAnimationFrame(()=>As())},children:[e.jsx(aa,{}),"Attach files"]}),e.jsxs(It,{onSelect:()=>{requestAnimationFrame(()=>{jt(!0)})},children:[e.jsx(Eh,{}),"Attach from project"]})]})]})]})]}),Ga=s?e.jsx("button",{type:"button",onClick:s,className:qr,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(an,{className:R(Gr,"text-current")})}):null,bo=e.jsxs(e.Fragment,{children:[zn,Ga]}),qa=ee.statusText;i.useEffect(()=>{const ie=!!ee.wasAborted;!Te.current&&ie&&!te&&(Ke(),I&&Y(I)),Te.current=ie},[Y,I,te,Ke,ee.wasAborted]),i.useEffect(()=>()=>{me.current&&(clearTimeout(me.current),me.current=null)},[]);const Ka=je&&Qe;return e.jsxs("form",{onSubmit:Pe,className:R("pt-0 pb-2 md:pb-4",je&&Le?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:je&&Se>0&&!Le?{marginBottom:`${Se}px`}:void 0,children:[e.jsx(Fv,{isWorking:ee.isWorking,statusText:qa,isGenericStatus:ee.isGenericStatus,isWaitingForPermission:ee.isWaitingForPermission,wasAborted:ee.wasAborted,abortActive:ee.abortActive,completionId:ee.lastCompletionId,isComplete:ee.isComplete,showAbort:Ka,onAbort:wt,showAbortStatus:te}),e.jsxs("div",{ref:M,className:R("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:ke,onDragLeave:Ye,onDrop:Ze,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:qr,onClick:()=>As(),title:"Attach files","aria-label":"Attach files",children:e.jsx(aa,{className:R(Gr,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(pv,{}),e.jsx(ef,{onEditMessage:ie=>{n(ie),setTimeout(()=>{C.current?.focus()},0)}}),e.jsxs("div",{className:R("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Ot,children:[m&&e.jsx(tf,{ref:A,searchQuery:p,onCommandSelect:st,onClose:()=>f(!1)}),y&&e.jsx(sf,{ref:D,searchQuery:w,onAgentSelect:$e,onClose:()=>g(!1)}),v&&e.jsx(rf,{ref:F,searchQuery:k,onSkillSelect:Ue,onClose:()=>j(!1)}),l&&e.jsx(hv,{ref:S,searchQuery:d,onFileSelect:ye,onClose:()=>c(!1)}),e.jsx(Ns,{ref:C,"data-chat-input":"true",value:t,onChange:B,onKeyDown:lt,onPaste:ce,onPointerDownCapture:et,placeholder:I||_?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!I&&!_,className:R("min-h-[52px] resize-none border-0 px-3 shadow-none rounded-t-xl rounded-b-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent",je?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:N?`${N.height}px`:void 0,maxHeight:N?`${N.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:R("rounded-b-xl bg-transparent",Bn,je?"flex items-center gap-x-1.5":R("flex items-center justify-between",rr)),"data-chat-input-footer":"true",children:je?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:bo}),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(fd,{className:R("w-full flex items-center justify-end min-w-0")})}),fn]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("flex items-center flex-shrink-0",rr),children:bo}),e.jsxs("div",{className:R("flex items-center flex-1 justify-end",rr,"md:gap-x-3"),children:[e.jsx(fd,{className:R("flex-1 min-w-0 justify-end")}),fn]})]})})]})]})]})};function xi({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:R("bg-accent animate-pulse rounded-xl",s),...r})}const Nd=(s,r,t,n,o=4)=>{const a=[];for(let l=0;l<o;l++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,m=l/o,f=(l+1)/o,p=(v,j,k)=>v+(j-v)*k,h=(v,j,k,x,N,P)=>{const C=p(v,j,N),M=p(x,k,N);return p(C,M,P)},y={x:h(s.x,r.x,t.x,n.x,d,m),y:h(s.y,r.y,t.y,n.y,d,m)},g={x:h(s.x,r.x,t.x,n.x,u,m),y:h(s.y,r.y,t.y,n.y,u,m)},w={x:h(s.x,r.x,t.x,n.x,u,f),y:h(s.y,r.y,t.y,n.y,u,f)},b={x:h(s.x,r.x,t.x,n.x,d,f),y:h(s.y,r.y,t.y,n.y,d,f)};a.push({path:`M${y.x} ${y.y} L${g.x} ${g.y} L${w.x} ${w.y} L${b.x} ${b.y} Z`,row:l,col:c})}return a},Ul=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=Ba();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const l=a?"white":"black",c=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,h=50,y={x:50,y:h-m},g={x:50-m*f,y:h-m*p},w={x:50+m*f,y:h-m*p},b={x:50,y:h},v={x:50-m*f,y:h+m*p},j={x:50+m*f,y:h+m*p},k={x:50,y:h+m},N=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(y.y+g.y+b.y+w.y)/4})`,P=Nd(g,b,k,v),C=Nd(b,w,j,k),M=Ae.useMemo(()=>{const S=[];for(let A=0;A<32;A++)S.push(.1+Math.random()*.5);return S},[]);return e.jsxs("svg",{width:r,height:t,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:s,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${b.x} ${b.y} L${g.x} ${g.y} L${v.x} ${v.y} L${k.x} ${k.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),P.map((S,A)=>e.jsx("path",{d:S.path,fill:u,opacity:M[A]},`left-${A}`)),e.jsx("path",{d:`M${b.x} ${b.y} L${w.x} ${w.y} L${j.x} ${j.y} L${k.x} ${k.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),C.map((S,A)=>e.jsx("path",{d:S.path,fill:u,opacity:M[A+16]},`right-${A}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${g.x} ${g.y} L${b.x} ${b.y} L${w.x} ${w.y} Z`,fill:"none",stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${N} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function Uv({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:l=!0,mode:c="popLayout"}){const[d,u]=Ae.useState(0),m=Ae.Children.toArray(s);Ae.useEffect(()=>{if(!l)return;const p=t*1e3,h=setInterval(()=>{u(y=>{const g=(y+1)%m.length;return a?.(g),g})},p);return()=>clearInterval(h)},[m.length,t,a,l]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:R("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(Ih,{mode:c,initial:!1,children:e.jsx(vn.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 s=Ba();let r=!0;s?r=s.currentTheme.metadata.variant!=="light":typeof window<"u"&&(r=window.matchMedia("(prefers-color-scheme: dark)").matches);const t=r?"rgba(255,255,255,0.4)":"rgba(0,0,0,0.4)";return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[e.jsx(Ul,{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:t},children:['"',n,'…"']},n))})]})},yi=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 Tr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Tr.instance||(Tr.instance=new Tr),Tr.instance}recordSessionStart(r){this.sessionStartTimes.set(r,Date.now())}getSessionStartTime(r){return this.sessionStartTimes.get(r)}shouldAnimateMessage(r,t){if(r.role!=="assistant"||this.seenMessageIds.has(r.id))return!1;const n=this.sessionStartTimes.get(t);if(!n)return this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created),!1;const o=r.time.created>n-5e3;return o||(this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created)),o}clearSession(r){this.sessionStartTimes.delete(r)}hasSessionTiming(r){return this.sessionStartTimes.has(r)}hasBeenAnimated(r){return this.seenMessageIds.has(r)}markMessageAsAnimated(r,t){this.seenMessageIds.add(r),this.messageCreationTimes.set(r,t)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function Vl(s){const r=s.colors.syntax,t=s.colors.surface;return{'code[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:r.base.comment,fontStyle:"italic"},prolog:{color:r.base.comment},doctype:{color:r.base.comment},cdata:{color:r.base.comment},punctuation:{color:r.tokens?.punctuation||t.mutedForeground},property:{color:r.tokens?.variableProperty||r.base.variable},tag:{color:r.tokens?.tag||r.base.keyword},"attr-name":{color:r.tokens?.tagAttribute||r.base.variable},"attr-value":{color:r.tokens?.tagAttributeValue||r.base.string},boolean:{color:r.tokens?.boolean||r.base.number},number:{color:r.base.number},constant:{color:r.tokens?.constant||r.base.number},symbol:{color:r.tokens?.constant||r.base.number},string:{color:r.base.string},char:{color:r.base.string},function:{color:r.base.function},builtin:{color:r.tokens?.functionBuiltin||r.base.function},"class-name":{color:r.tokens?.className||r.base.type},namespace:{color:r.tokens?.namespace||r.base.type,opacity:.8},keyword:{color:r.base.keyword},atrule:{color:r.base.keyword},selector:{color:r.base.function},operator:{color:r.base.operator},variable:{color:r.base.variable},regex:{color:r.tokens?.regex||r.base.string},url:{color:r.base.function,textDecoration:"underline"},entity:{color:r.base.function,cursor:"help"},".language-css .token.string":{color:r.base.string},".style .token.string":{color:r.base.string},deleted:{color:s.colors.status.error,backgroundColor:s.colors.status.errorBackground},inserted:{color:s.colors.status.success,backgroundColor:s.colors.status.successBackground},title:{color:s.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:t.mutedForeground},table:{color:r.base.function},blockquote:{color:t.mutedForeground,fontStyle:"italic"},important:{color:r.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:r.tokens?.decorator||r.base.function},annotation:{color:r.tokens?.decorator||r.base.function}}}const ys=({children:s,className:r})=>{const[t,n]=i.useState(!1);return i.useEffect(()=>{let o=null;const a=()=>n(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:R("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},Qv=({isUser:s,providerID:r,agentName:t,modelName:n,variant:o,isDarkTheme:a})=>{const{src:l,onError:c,hasLogo:d}=qm(r);return e.jsx(ys,{children:e.jsx("div",{className:R("pl-3","mb-2"),children:e.jsx("div",{className:R("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:s?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Ls,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&l?e.jsx("img",{src:l,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:c}):e.jsx(pr,{className:"h-4 w-4",style:{color:`var(${Er(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:R("font-bold typography-ui-header tracking-tight leading-none",s?"text-primary":"text-foreground"),children:s?"You":n||"Assistant"}),!s&&t&&e.jsxs("div",{className:R("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",Er(t).class),children:[e.jsx(an,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:t})]}),!s&&o&&e.jsxs("div",{className:R("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",o==="Default"?void 0:"agent-info"),style:o==="Default"?{"--agent-color":"var(--muted-foreground)","--agent-color-bg":"var(--muted-foreground)"}:void 0,children:[e.jsx(pr,{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),Cd=(s,r)=>{const t=s[Symbol.toPrimitive];if(typeof t=="function")try{if(t()===r)return s}catch{}try{Object.defineProperty(s,"toString",{value:()=>r,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(s,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0})}catch{}return s},Md=()=>{if(!zt()||typeof window>"u")return Wc;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=Cd({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=Cd({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return Wc},uf=()=>{const[s,r]=i.useState(Md);return i.useEffect(()=>{if(!zt()||typeof window>"u")return;const t=n=>{r(Md())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},mf=s=>{const r=[],t=[],n=s.querySelector("thead");n&&n.querySelectorAll("th").forEach(l=>r.push(l.innerText.trim()));const o=s.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(l=>{const c=l.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},ff=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
94
+ `)?`"${o.replace(/"/g,'""')}"`:o,n=[];return s.length>0&&n.push(s.map(t).join(",")),r.forEach(o=>n.push(o.map(t).join(","))),n.join(`
95
+ `)},Xv=({headers:s,rows:r})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return s.length>0&&n.push(s.map(t).join(" ")),r.forEach(o=>n.push(o.map(t).join(" "))),n.join(`
96
+ `)},Jv=({headers:s,rows:r})=>{if(s.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${s.map(t).join(" | ")} |`),n.push(`| ${s.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=s.map((l,c)=>t(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
97
+ `)},Zv=(s,r,t)=>{const n=new Blob([r],{type:t}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=s,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},ew=({tableRef:s})=>{const[r,t]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const l=async c=>{const d=s.current?.querySelector("table");if(d)try{const u=mf(d),m=c==="csv"?ff(u):Xv(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([m],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),t(!0),o(!1),setTimeout(()=>t(!1),2e3)}catch(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:r?e.jsx(Bt,{className:"size-3.5"}):e.jsx(er,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>l("tsv"),children:"TSV"})]})]})},tw=({tableRef:s})=>{const[r,t]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=l=>{n.current&&!n.current.contains(l.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const l=s.current?.querySelector("table");if(l)try{const c=mf(l),d=a==="csv"?ff(c):Jv(c);Zv(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(c){console.error("Failed to download table:",c)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>t(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(Or,{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"})]})]})},sw=({children:s,className:r})=>{const t=i.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:t,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(ew,{tableRef:t}),e.jsx(tw,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:R("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},rw=({children:s,className:r,style:t,...n})=>{const[o,a]=i.useState(!1),l=i.useRef(null),c=i.useMemo(()=>{if(!t)return t;const m={...t},f=y=>{if(typeof y!="string")return{value:void 0,vars:{}};const[g,...w]=y.split(";").map(v=>v.trim()).filter(Boolean),b={};for(const v of w){const j=v.indexOf(":");if(j===-1)continue;const k=v.slice(0,j).trim(),x=v.slice(j+1).trim();!k.startsWith("--")||x.length===0||(b[k]=x)}return{value:g,vars:b}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[y,g]of Object.entries(p.vars))m[y]=g;const h=f(t.color);h.value&&(m.color=h.value,m["--shiki-light"]=h.value);for(const[y,g]of Object.entries(h.vars))m[y]=g;return m},[t]),d=()=>l.current&&l.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:l,children:[e.jsx("pre",{...n,className:R(r),style:c,children:s}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(Bt,{className:"size-3.5"}):e.jsx(er,{className:"size-3.5"})})})]})},pf={pre:rw,table:sw},nw=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:l="assistant"})=>{const c=uf(),d=i.useMemo(()=>`markdown-${r?.id?`part-${r.id}`:`message-${t}`}`,[t,r?.id]),u=l==="tool"?"streamdown-content streamdown-tool":"streamdown-content",m=e.jsx("div",{className:R("break-words",o),children:e.jsx(Ou,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:pf,children:s})});return n?e.jsx(ys,{children:m},d):m},rn=({content:s,className:r,variant:t="assistant"})=>{const n=uf(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:R("break-words",r),children:e.jsx(Ou,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:pf,children:s})})},ow={thinking:{label:"Thinking",Icon:pr},justification:{label:"Justification",Icon:dl}},hf=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
98
+ `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
99
+ `).trim(),aw=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
100
+ `),n=r.indexOf("."),o=[t>=0?t:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},Gl=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=i.useState(!1),l=i.useMemo(()=>aw(s),[s]),{label:c,Icon:d}=ow[r];return i.useEffect(()=>{s.trim().length!==0&&t?.("structural")},[t,o,s]),!s||s.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(u=>!u),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(Ft,{className:"h-3.5 w-3.5"}):e.jsx(Is,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),l&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:l})})]}),o&&e.jsx("div",{className:R("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(xt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},gf=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=i.useMemo(()=>hf(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Gl,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},iw=s=>hf(s),lw=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const l=s,c=l.text,d=typeof c=="string"?c:l.content||l.value||"",u=i.useMemo(()=>a?iw(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=i.useRef(m);if(m||f)return p.current=!0,null;const h=l.time;return!(h&&typeof h.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(Gl,{text:u,variant:"justification",onContentChange:o,blockId:s.id||`${r}-reasoning-text`},s.id||`${r}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(nw,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},cw=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,dw=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[l,c]=i.useState(!1),[d,u]=i.useState(!1),m=i.useRef(null);i.useEffect(()=>{const h=m.current;if(!h||l)return;const y=()=>{u(h.scrollHeight>h.clientHeight)};y();const g=new ResizeObserver(y);return g.observe(h),()=>g.disconnect()},[a,l]);const f=i.useCallback(()=>{(d||l)&&c(h=>!h)},[d,l]);if(!a||a.trim().length===0)return null;const p=()=>{if(!t?.token||!a.includes(t.token))return a;const h=a.indexOf(t.token),y=a.slice(0,h),g=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[y,e.jsx("a",{href:cw(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:w=>w.stopPropagation(),children:t.token}),g]})};return e.jsx("div",{className:R("break-words whitespace-pre-wrap font-sans typography-markdown",!l&&"line-clamp-3",(d||l)&&"cursor-pointer"),ref:m,onClick:f,children:p()},s.id||`${r}-user-text`)},uw=i.memo(dw),mw=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},fw=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,pw=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Dd=(s,r)=>!s||typeof s!="object"?String(s):Gy(s,r||""),bi=(s,r,t)=>{let n=mw(s);if((r==="edit"||r==="multiedit")&&fw(n)&&(n=pw(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},hw=(s,r)=>{try{const t=s.trim().split(`
101
+ `).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,l,c]=a,d=Math.floor(l.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:R("w-full min-w-0 font-mono space-y-0.5",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:wr.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}},gw=(s,r,t)=>{try{const n=s.trim().split(`
102
+ `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const l=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(l){const[,c,d,u]=l,m=u!==void 0?d:"",f=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:m,content:f})}}),e.jsxs("div",{className:R("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:wr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,l])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:l.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:R("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},xw=(s,r,t)=>{try{const n=s.trim().split(`
103
+ `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(l=>{const c=l.lastIndexOf("/"),d=c>0?l.substring(0,c):"/",u=c>=0?l.substring(c+1):l;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:R("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:wr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(l=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[l,"/"]}),e.jsx("div",{className:R("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[l].sort().map(c=>e.jsxs("div",{className:R("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},l))]})}catch{return null}},yw=(s,r)=>{try{const t=JSON.parse(s);if(!Array.isArray(t))return null;const n={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:l,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:R("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:wr.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Bt,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||l))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||l))})]})]})}catch{return null}},bw=(s,r,t)=>{try{return e.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:wr.tool.popup,children:e.jsx(rn,{content:s,variant:"tool"})})}catch{return null}},xf=s=>{const r=s.split(`
104
+ `);let t="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const l=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=l?parseInt(l[1]):0,d=l?parseInt(l[2]):0,u=[];let m=d,f=o+1;for(;f<r.length&&!r[f].startsWith("@@")&&!r[f].startsWith("Index:");){const p=r[f];p.startsWith("+")?(u.push({type:"added",lineNumber:m,content:p.substring(1)}),m++):p.startsWith("-")?u.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(u.push({type:"context",lineNumber:m,content:p.substring(1)}),m++),f++}n.push({file:t,oldStart:c,newStart:d,lines:u}),o=f;continue}o++}return n},sl=(s,r,t)=>Uy(r,s,t),yf=s=>{const r="h-3.5 w-3.5 flex-shrink-0",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(Ph,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(_u,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(no,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx($r,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(Gs,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(Th,{className:r}):t==="glob"?e.jsx(Fh,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx($i,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx($i,{className:r}):t==="todowrite"||t==="todoread"?e.jsx($u,{className:r}):t==="skill"?e.jsx(Lu,{className:r}):t==="question"?e.jsx(Rh,{className:r}):t.startsWith("git")?e.jsx(_t,{className:r}):e.jsx(Ia,{className:r})},vw=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},ww=({start:s,end:r,active:t})=>{const[n,o]=i.useState(()=>Date.now());return i.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:vw(s,r,n)})},jw=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
105
+ `);let t=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&n++;return t===0&&n===0?null:{added:t,removed:n}},rl=(s,r,t)=>{if(t)return s.split("/").pop()||s;if(s.startsWith(r)){const n=s.substring(r.length);return n.startsWith("/")?n.substring(1):n}return s},Sw=s=>{const r=s.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!r)return null;const t=[],n=r[1],o=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let a;for(;(a=o.exec(n))!==null;)t.push({question:a[1],answer:a[2]});return t.length>0?t:null},kw=(s,r,t,n)=>{const o=r,a=o.metadata,l=o.input;if(s.tool==="question"&&l?.questions&&Array.isArray(l.questions)){const d=l.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((s.tool==="edit"||s.tool==="multiedit")&&l){const d=l?.filePath||l?.file_path||l?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return rl(d,n,t)}if((s.tool==="read"||s.tool==="write")&&l){const d=l?.filePath||l?.file_path||l?.path;if(typeof d=="string")return rl(d,n,t)}if(s.tool==="bash"&&l?.command&&typeof l.command=="string"){const d=l.command.split(`
106
+ `)[0];return t?d.substring(0,50):d.substring(0,100)}if(s.tool==="task"&&l?.description&&typeof l.description=="string")return t?l.description.substring(0,40):l.description.substring(0,80);if(s.tool==="skill"&&l?.name&&typeof l.name=="string")return l.name;const c=l?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},nl=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(xt,{outerClassName:R("w-full min-w-0 flex-none overflow-hidden",r,n),className:R("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",t),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:s})}),Nw=s=>{const r=s.state?.title;return typeof r=="string"&&r.trim().length>0?r:typeof s.tool=="string"&&s.tool.trim().length>0?s.tool:"tool"},Cw=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Mw=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o,sessionId:a})=>{const l=he(g=>g.setCurrentSession),c=i.useMemo(()=>s.filter(g=>g.state?.status==="completed"),[s]),d=typeof o=="string"?Cw(o):"",u=d.length>0,[m,f]=i.useState(!1),p=g=>{g.stopPropagation(),a&&l(a)};if(c.length===0&&!u&&!a)return null;const h=r?c:c.slice(-6),y=Math.max(0,c.length-h.length);return e.jsxs("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',t?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[c.length>0?e.jsx(nl,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[y>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",y," more…"]}):null,h.map((g,w)=>{const b=typeof g.tool=="string"&&g.tool.trim().length>0?g.tool:"tool",v=Nw(g),j=Dl(b).displayName;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:yf(b)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:j}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:v})]},g.id??`${b}-${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(oa,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-primary font-medium",children:"Open subAgent session"})]}),u?e.jsxs("div",{className:R("space-y-1",(c.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:g=>g.stopPropagation(),onClick:g=>{g.stopPropagation(),f(w=>!w)},children:[m?e.jsx(Ft,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Is,{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(nl,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(rn,{content:d,variant:"tool"})})}):null]}):null]})},Dw=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:xf(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,l)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(dr,{style:r,language:gr(typeof t?.file_path=="string"?t.file_path:typeof t?.filePath=="string"?t.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},l))})]},o))}),Aw=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
107
+ `),a=gr(t??"")||sl(s,"write",t?{filePath:t}:void 0),l=Math.max(o.length,1),c=l===1?"line 1":`lines 1-${l}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(dr,{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))})]})},Ew=({content:s,filePath:r,displayPath:t})=>{const n=Ki(r),o=r.toLowerCase().endsWith(".svg"),a=i.useMemo(()=>o&&!s.startsWith("data:")?`data:image/svg+xml;base64,${btoa(s)}`:s.startsWith("data:")?s:`data:${n};base64,${s}`,[s,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:t}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:t,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})},Iw=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:l})=>{const c=r,d=c.metadata,u=c.input,m=c.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",h=typeof d?.diff=="string"?d.diff:null,y=s.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,g=s.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,w=s.tool==="write"&&!!g,b=y?mo(y):!1,v=w?y?rl(y,o,n):"New file":null,j=i.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?Dd(u,s.tool):typeof u.content=="string"?u.content??"":Dd(u,s.tool),[u,s.tool]),k=j.trim().length>0,x=(P,C)=>e.jsx(nl,{maxHeightClass:C?.maxHeightClass,className:C?.className,disableHorizontal:C?.disableHorizontal,outerClassName:C?.outerClassName,children:P}),N=()=>{if(s.tool==="question"){if(r.status==="completed"&&f){const P=Sw(p);if(P&&P.length>0)return x(e.jsx("div",{className:"space-y-2",children:P.map((C,M)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:C.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:C.answer})]},M))}),{maxHeightClass:"max-h-[40vh]"})}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const P=yw(p,{unstyled:!0});return x(P??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(s.tool==="list"&&f){const P=hw(p,{unstyled:!0});return x(P??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="grep"&&f){const P=gw(p,n,{unstyled:!0});return x(P??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="glob"&&f){const P=xw(p,n,{unstyled:!0});return x(P??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="task"&&f)return x(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(rn,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const P=bw(p,t,{unstyled:!0});return x(P??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="codesearch"&&f)return x(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(rn,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return x(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(rn,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&h)return x(e.jsx(Dw,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const P=bi(p,s.tool,d),C=P.split(`
108
+ `),M=typeof u?.offset=="number"?u.offset:0,S=typeof u?.limit=="number"?u.limit:void 0,A=D=>D.trim().startsWith("(");return x(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:C.map((D,F)=>{const E=A(D),I=M+F+1,_=!E&&(S===void 0||F<S);return e.jsxs("div",{className:R("typography-code font-mono flex w-full min-w-0",E&&"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:_?I:""}),e.jsx("div",{className:"flex-1 min-w-0",children:E?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:D}):e.jsx(dr,{style:t,language:sl(P,s.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:D})})]},F)})}),{className:"p-1"})}return x(e.jsx(dr,{style:t,language:sl(bi(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...Vo.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:bi(p,s.tool,d)}),{className:"p-1"})}return x(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",l?"before:bottom-[-0.6rem]":"before:bottom-0"),children:s.tool==="todowrite"||s.tool==="todoread"||s.tool==="question"?N():e.jsxs(e.Fragment,{children:[w&&b?e.jsx("div",{className:"my-1",children:x(e.jsx(Ew,{content:g,filePath:y,displayPath:v??"New file"}))}):w?e.jsx("div",{className:"my-1",children:x(e.jsx(Aw,{content:g,syntaxTheme:t,filePath:y,displayPath:v??"New file"}))}):k?e.jsx("div",{className:"my-1",children:x(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:j}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,s.tool!=="write"&&r.status==="completed"&&"output"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),N()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})},ta=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:l=!1,hasNextTool:c=!1})=>{const d=s.state,u=yt(I=>I.currentDirectory),m=s.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",h=d.status==="error",y=i.useRef(r);i.useEffect(()=>{!f&&!m||y.current!==r&&(y.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const g=d,w=g.metadata,b=g.input,v=g.time,j=i.useRef({}),k=i.useRef(s.id);if(k.current!==s.id&&(k.current=s.id,j.current={}),m){if(typeof v?.start=="number"){const I=j.current.start;(typeof I!="number"||v.start<I)&&(j.current.start=v.start)}typeof v?.end=="number"&&(j.current.end=v.end)}const x=m?j.current.start??v?.start:v?.start,N=m?j.current.end??v?.end:v?.end,P=i.useMemo(()=>{if(!m)return;const I=w;return typeof I?.sessionId=="string"?I.sessionId:void 0},[m,w]),C=i.useMemo(()=>{if(!m)return[];const I=w?.summary;return Array.isArray(I)?I.filter(_=>typeof _=="object"&&_!==null):[]},[m,w]),M=i.useRef(C.length);i.useEffect(()=>{m&&M.current!==C.length&&(M.current=C.length,a?.("structural"))},[m,a,C.length]);const S=s.tool==="edit"||s.tool==="multiedit"?jw(w):null,A=kw(s,d,o,u),D=Dl(s.tool).displayName,F=i.useContext(Al),E=I=>{if(m||!F?.editor){t(s.id);return}let _;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(_=b?.filePath||b?.file_path||b?.path||w?.filePath||w?.file_path||w?.path),typeof _=="string"){I.stopPropagation();let V=_;_.startsWith("/")||(V=u.endsWith("/")?u+_:u+"/"+_),F.editor.openFile(V)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:E,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:I=>{I.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:yf(s.tool)}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Ft,{className:"h-3.5 w-3.5"}):e.jsx(Is,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:D})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[A&&e.jsx("span",{className:R("truncate",o&&"max-w-[120px]"),children:A}),S&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",S.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",S.removed]})]}),typeof x=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(ww,{start:x,end:typeof N=="number"?N:void 0,active:!!(m&&p&&typeof N!="number")})})]})]}),m&&(C.length>0||p||f||P)?e.jsx(Mw,{entries:C,isExpanded:r,hasPrevTool:l,hasNextTool:c,output:typeof g.output=="string"?g.output:void 0,sessionId:P}):null,!m&&r?e.jsx(Iw,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:l,hasNextTool:c}):null]})},Pw=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
109
+ `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
110
+ `).trim(),Tw=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=i.useMemo(()=>Pw(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Gl,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},Fw=i.memo(Tw),Rw=s=>{const r={tools:s.filter(n=>n.kind==="tool").length,reasoning:s.filter(n=>n.kind==="reasoning").length,justifications:s.filter(n=>n.kind==="justification").length},t=[];return r.tools>0&&t.push(`${r.tools} tool${r.tools>1?"s":""}`),r.reasoning>0&&t.push(`${r.reasoning} reasoning`),r.justifications>0&&t.push(`${r.justifications} justification${r.justifications>1?"s":""}`),t.join(", ")},Ad=s=>[...s].sort((r,t)=>{const n=typeof r.endedAt=="number"?r.endedAt:void 0,o=typeof t.endedAt=="number"?t.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),Ow=s=>{const r={},t=s.filter(n=>n.kind==="tool");return t.forEach((n,o)=>{const a=n.part.id;a&&(r[a]={hasPrev:o>0,hasNext:o<t.length-1})}),r},_w=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:l,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=i.useRef(r),[p,h]=i.useState(0);i.useEffect(()=>{if(f.current===r)return;const b=f.current===!1;f.current=r,c?.("structural"),r&&b&&h(v=>v+1)},[r,c]);const y=i.useMemo(()=>Ad(d?s.filter(b=>b.part.id&&u.has(b.id)):s),[s,d,u]),g=Rw(y),w=Ow(y);return y.length===0?null:e.jsx(ys,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl cursor-pointer"),onClick:t,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(oo,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Ft,{className:"h-3.5 w-3.5"}):e.jsx(Is,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(g||m)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[g&&e.jsx("span",{className:"truncate block",children:g}),m&&(m.additions>0||m.deletions>0)&&e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,m.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,m.deletions)]})]})]})]}),r&&e.jsx("div",{className:R("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:y.map((b,v)=>{const j=b.part.id||`group-part-${v}`,k=w[j],x=`${j}-exp${p}`;switch(b.kind){case"tool":return e.jsx(ys,{children:e.jsx(ta,{part:b.part,isExpanded:a.has(j),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:k?.hasPrev??!1,hasNextTool:k?.hasNext??!1})},x);case"reasoning":return e.jsx(ys,{children:e.jsx(gf,{part:b.part,messageId:b.messageId,onContentChange:c})},x);case"justification":return e.jsx(ys,{children:e.jsx(Fw,{part:b.part,messageId:b.messageId,onContentChange:c})},x);default:return null}})})]})})},$w=i.memo(_w),Lw=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:R("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),vi=i.memo(Lw),bf=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},vf=s=>{if(s.type!=="text")return!1;const r=bf(s);return!r||r.trim().length===0},Bw=(s,r={})=>{const{includeReasoning:t=!0}=r,n=s.some(o=>!o.synthetic);return s.filter(o=>!!o.synthetic&&n||!t&&o.type==="reasoning"?!1:!(o.type==="patch"))},zw=s=>{const r=s/1e3;if(r<60)return`${r.toFixed(1)}s`;const t=Math.floor(r/60),n=Math.round(r%60);return`${t}m ${n}s`},Ww=(s,r)=>{const t=i.useRef(null),n=i.useRef(null),[o,a]=i.useState(!1),l=i.useRef(s);l.current=s;const c=i.useRef(r);c.current=r;const d=i.useRef(!1),u=r.size>0;return i.useEffect(()=>{s&&s.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const m=l.current;if(!m)return;const f=Array.from(c.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),i.useEffect(()=>{s&&(!s.isWorking||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[u,s]),i.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},Hw=new Set(["task"]),bn=s=>typeof s=="string"&&Hw.has(s.toLowerCase()),Uw=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:l,onShowPopup:c,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=i.useState(!1),h=i.useRef(null),y=i.useMemo(()=>r.filter(C=>C.type!=="text"?!1:!vf(C)),[r]),g=d?.token;let w=!1;const b=!!a,v=!!l,j=!!(n??t),k=!!o,x=i.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),N=i.useCallback(()=>{!j||!b||!k||typeof window>"u"||(x(),p(!0),h.current=window.setTimeout(()=>{p(!1),h.current=null},1800))},[b,x,k,j]);i.useEffect(()=>{k||(p(!1),x())},[x,k]);const P=i.useCallback(C=>{!a||!k||(C.stopPropagation(),C.preventDefault(),a(),j&&N())},[k,j,a,N]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:j&&b&&k?N:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:y.map((C,M)=>{let S;return d&&g&&!w&&bf(C).includes(g)&&(S=d,w=!0),e.jsx(ys,{children:e.jsx(uw,{part:C,messageId:s,isMobile:t,agentMention:S})},`user-text-${M}`)})}),e.jsx(Jm,{files:r,onShowPopup:c}),b&&k||u||m?e.jsxs("div",{className:R("mt-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",f&&"opacity-100 pointer-events-auto"),children:[u&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Revert to this message",onPointerDown:C=>C.stopPropagation(),onClick:C=>{C.stopPropagation(),u()},children:e.jsx(En,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:C=>C.stopPropagation(),onClick:C=>{C.stopPropagation(),m()},children:e.jsx(_t,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Fork from here"})]}),b&&k&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":f||v?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:C=>C.stopPropagation(),onClick:P,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(Bt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(er,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Copy message"})]})]}):null]})},Vw=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:l,hasTouchInput:c,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:h,hasTextContent:y=!1,onCopyMessage:g,copiedMessage:w=!1,onAuxiliaryContentComplete:b,showReasoningTraces:v=!1,turnGroupingContext:j,errorMessage:k})=>{const[x,N]=i.useState(!1),P=i.useRef(null),C=!!g,M=!!w,S=!!(c??l),A=!t,D=i.useMemo(()=>r.filter(Pe=>!vf(Pe)).filter(Pe=>Pe.type!=="compaction"),[r]),F=i.useMemo(()=>D.filter(Pe=>Pe.type==="tool"),[D]),E=i.useMemo(()=>D.filter(Pe=>Pe.type==="text"),[D]),I=he(Pe=>Pe.createSessionFromAssistantMessage),_=_e(Pe=>Pe.openMultiRunLauncherWithPrompt),V=j?.isLastAssistantInTurn??!1,Y=n==="stop",H=F.length>0,L=i.useMemo(()=>F.some(Pe=>{const lt=(Pe.state??{})?.status;return lt==="pending"||lt==="running"||lt==="started"}),[F]),U=i.useCallback(Pe=>{const ze=Pe.state??{},lt=ze?.status;if(lt==="pending"||lt==="running"||lt==="started")return!1;const Ke=ze?.time??{},wt=typeof Ke?.end=="number"?Ke.end:void 0,Pt=typeof Ke?.start=="number"?Ke.start:void 0;return!(typeof wt!="number"||typeof Pt=="number"&&wt<Pt)},[]),Q=i.useMemo(()=>F.length===0?!0:L?!1:F.every(Pe=>U(Pe)),[F,L,U]),J=i.useMemo(()=>E.length===0?!0:E.every(Pe=>typeof Pe.time?.end=="number"),[E]),K=i.useMemo(()=>D.filter(Pe=>Pe.type==="reasoning"),[D]),ne=i.useMemo(()=>K.length===0?!0:K.every(Pe=>typeof Pe.time?.end=="number"),[K]),X=typeof n!="string",ae=K.length>0&&H&&(L||X||!Q),O=i.useMemo(()=>H?E.length===0?X||L||!Q:!0:E.length>0?ae:!1,[E.length,X,L,H,ae,Q]),z=A||O&&(!J||!Q||L||X)||ae,T=A||H&&(L||X||!Q),$=A||ae,W=H||K.length>0,q=E.length===0,ue=W&&q&&!T&&!$&&Q&&ne,oe=i.useRef(!1),de=i.useRef(!1);i.useEffect(()=>{de.current=!1},[s]),i.useEffect(()=>{if(!ue){oe.current=!1;return}oe.current||(oe.current=!0,b?.())},[ue,b]),i.useEffect(()=>{if(A){de.current=!1;return}if(H){de.current=!1;return}K.length!==0&&($||!ne||de.current||(de.current=!0,h?.("structural")))},[A,H,h,ne,K.length,$]);const je=!!y&&!A,Se=i.useCallback(()=>{P.current!==null&&typeof window<"u"&&(window.clearTimeout(P.current),P.current=null)},[]),Le=i.useCallback(()=>{!S||!C||!je||typeof window>"u"||(Se(),N(!0),P.current=window.setTimeout(()=>{N(!1),P.current=null},1800))},[C,Se,je,S]);i.useEffect(()=>{je||(N(!1),Se())},[Se,je]);const G=i.useCallback(Pe=>{!g||!je||(Pe.stopPropagation(),Pe.preventDefault(),g(),S&&Le())},[je,S,g,Le]),ee=i.useCallback(Pe=>{Pe.stopPropagation(),Pe.preventDefault(),I&&I(s)},[I,s]),te=i.useCallback(Pe=>{Pe.stopPropagation(),Pe.preventDefault();const ze=Nl(E);if(!ze.trim())return;const lt=`${ay}
111
+
112
+ ${ze}`;_(lt)},[E,_]);i.useEffect(()=>()=>{Se()},[Se]);const xe=i.useMemo(()=>{const Pe={},ze=F.filter(lt=>bn(lt.tool)||T?!1:U(lt));return ze.forEach((lt,Ke)=>{Pe[lt.id]={hasPrev:Ke>0,hasNext:Ke<ze.length-1}}),Pe},[F,T,U]),me=i.useMemo(()=>j?.activityParts??[],[j]),Te=i.useMemo(()=>j?me.filter(Pe=>Pe.messageId===s):[],[me,s,j]),Ne=i.useMemo(()=>j?j.activityGroupSegments.filter(Pe=>Pe.anchorMessageId===s):[],[s,j]),Be=i.useMemo(()=>{const Pe=new Map;return Te.forEach(ze=>{Pe.set(ze.part,ze)}),Pe},[Te]),fe=i.useMemo(()=>j?(v?me:me.filter(ze=>ze.kind==="tool")).filter(ze=>{if(ze.kind!=="tool")return!0;const lt=ze.part.tool;return!bn(lt)}):[],[me,v,j]),[ht,bt]=i.useState(!1);i.useEffect(()=>{if(!j)return;const Pe=j.activityGroupSegments.some(ze=>ze.afterToolPartId!==null);(fe.length>1||Pe&&fe.length>0)&&bt(!0)},[j,fe.length]);const Nt=!!(j&&ht),Me=i.useMemo(()=>{if(!j)return[];if(!Nt)return[];if(!j.isWorking)return[];const Pe=[];return Te.forEach(ze=>{if(j.previewedPartIds.has(ze.id)||!v&&ze.kind!=="tool")return;const lt=ze.part;if(ze.kind==="tool"){const Ke=lt;if(bn(Ke.tool)||T||!U(Ke))return}else if(ze.kind==="reasoning"){if(!v||$||typeof lt.time?.end!="number")return}else if(ze.kind==="justification"&&(!v||z||typeof lt.time?.end!="number"))return;Pe.push(ze)}),Pe},[Te,U,z,$,T,v,Nt,j]),re=i.useMemo(()=>{const Pe=new Set;return Me.forEach(ze=>{Pe.add(ze.id)}),Pe},[Me]),{isAnimating:et}=Ww(j,re),be=!!(j&&Nt&&fe.length>0&&Ne.length>0),we=i.useMemo(()=>F.filter(Pe=>bn(Pe.tool)),[F]),Ve=i.useMemo(()=>{const Pe=[],ze=Ke=>{!j||!be||Ne.filter(wt=>(wt.afterToolPartId??null)===Ke).forEach(wt=>{const Pt=v?wt.parts:wt.parts.filter(St=>St.kind==="tool");Pt.length!==0&&Pe.push(e.jsx($w,{parts:Pt,isExpanded:j.isGroupExpanded,onToggle:j.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:h,isWorking:j.isWorking,previewedPartIds:j.previewedPartIds,diffStats:j.diffStats},`progressive-group-${wt.id}`))})};ze(null),we.forEach(Ke=>{Pe.push(e.jsx(ys,{children:e.jsx(ta,{part:Ke,isExpanded:d.has(Ke.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ke.id}`)),ze(Ke.id)});const lt=[];return D.forEach((Ke,wt)=>{const Pt=Be.get(Ke);if(!Pt||!j)return;let St=null,ge=null;if(!Nt){if(Pt.kind==="tool"){const B=Ke;if(bn(B.tool))return;const ye=B.state?.time,$e=U(B);if(!(!T&&$e))return;const st=xe[B.id];ge=e.jsx(ys,{children:e.jsx(ta,{part:B,isExpanded:d.has(B.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:st?.hasPrev??!1,hasNextTool:st?.hasNext??!1})},`tool-${B.id}`),St=$e&&typeof ye?.end=="number"?ye.end:null}ge&&lt.push({part:Ke,index:wt,endTime:St,element:ge});return}if(!j.isWorking||j.isGroupExpanded||j.previewedPartIds.has(Pt.id)||!v&&Pt.kind!=="tool")return;const Ie=re.has(Pt.id);switch(Pt.kind){case"tool":{const B=Ke;if(bn(B.tool))break;const ye=B.state?.time,$e=U(B);if(!(!T&&$e))break;const st=xe[B.id],ke=e.jsx(ys,{children:e.jsx(ta,{part:B,isExpanded:d.has(B.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:h,hasPrevTool:st?.hasPrev??!1,hasNextTool:st?.hasNext??!1})},`tool-${B.id}`);ge=Ie?e.jsx(vi,{isMigrating:et,children:ke},`migrating-tool-${B.id}`):ke,St=$e&&typeof ye?.end=="number"?ye.end:null;break}case"reasoning":{if(!v)break;const B=Ke.time,ce=typeof B?.end=="number";if(!(ce&&!$))break;const $e=e.jsx(ys,{children:e.jsx(gf,{part:Ke,messageId:s,onContentChange:h})},`reasoning-${wt}`);ge=Ie?e.jsx(vi,{isMigrating:et,children:$e},`migrating-reasoning-${wt}`):$e,St=ce?B?.end??null:null;break}case"justification":{if(!v)break;const B=Ke.time,ce=typeof B?.end=="number";if(!(ce&&!z))break;const $e=e.jsx(ys,{children:e.jsx(lw,{part:Ke,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${wt}`);ge=Ie?e.jsx(vi,{isMigrating:et,children:$e},`migrating-text-${wt}`):$e,St=ce?B?.end??null:null;break}}ge&&lt.push({part:Ke,index:wt,endTime:St,element:ge})}),lt.sort((Ke,wt)=>Ke.endTime===null&&wt.endTime===null?Ke.index-wt.index:Ke.endTime===null?1:wt.endTime===null?-1:Ke.endTime-wt.endTime),lt.forEach(({element:Ke})=>{Pe.push(Ke)}),Pe},[Be,Ne,d,et,l,U,s,h,m,u,re,z,$,T,Nt,v,a,xe,j,D,we,be]),tt=j?.turnId,We=he(Pe=>Pe.currentSessionId),Oe=Mt(Pe=>{if(!tt||!We)return;const ze=Pe.messages.get(We);if(!ze)return;const lt=ze.find(Pt=>Pt.info?.id===tt);if(!lt)return;const wt=lt.info.summary?.body;return typeof wt=="string"&&wt.trim().length>0?wt:void 0}),rt=typeof j?.summaryBody=="string"&&j.summaryBody.trim().length>0?j.summaryBody:Oe,vt=i.useRef(void 0);rt&&rt.trim().length>0&&(vt.current=rt);const mt=i.useRef(tt);mt.current!==tt&&(mt.current=tt,vt.current=void 0);const Tt=vt.current,Ot=j?.isLastAssistantInTurn&&Tt&&Tt.trim().length>0,ve=!!k,He=V&&y&&(Y||!!k),[Je,Qe]=i.useState(!1),ft=i.useMemo(()=>{if(!V||!Y)return;const Pe=j?.userMessageCreatedAt;if(!(typeof Pe!="number"||typeof o!="number")&&!(o<=Pe))return zw(o-Pe)},[V,Y,j?.userMessageCreatedAt,o]),it=e.jsxs(e.Fragment,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{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:Pe=>Pe.stopPropagation(),onClick:ee,children:e.jsx(Oh,{className:"h-4 w-4"})})}),e.jsx(ct,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{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:Pe=>Pe.stopPropagation(),onClick:te,children:e.jsx(Vm,{className:"h-4 w-4"})})}),e.jsx(ct,{sideOffset:6,children:"Start new multi-run from this answer"})]}),g&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":x||M?"true":void 0,className:R("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!je&&"opacity-50"),disabled:!je,"aria-label":"Copy message text","aria-hidden":!je,onPointerDown:Pe=>Pe.stopPropagation(),onClick:G,onFocus:()=>{je&&N(!0)},onBlur:()=>{M||N(!1)},children:M?e.jsx(Bt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(er,{className:"h-3.5 w-3.5"})})}),e.jsx(ct,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:R("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&C&&je?Le:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ve,ve&&e.jsx(ys,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(rn,{content:k??""})})},"assistant-error"),Ot&&e.jsx(ys,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Qe(!0),onMouseLeave:()=>Qe(!1),children:[e.jsx(rn,{content:Tt}),He&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[ft?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(nc,{className:"h-3.5 w-3.5"}),ft]}):e.jsx("span",{}),e.jsx("div",{className:R("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",Je&&"opacity-100 pointer-events-auto"),children:it})]})]})},"summary-body")]}),e.jsx(Jm,{files:r,onShowPopup:m}),!Ot&&He&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[ft?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(nc,{className:"h-3.5 w-3.5"}),ft]}):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:it})]})]})})},Gw=({isUser:s,...r})=>s?e.jsx(Uw,{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(Vw,{...r}),Ed=i.memo(Gw),wi=s=>{const r=s,t=r?.clientRole,n=r?.role;return r?.userMessageMarker===!0||t==="user"||n==="user"||r?.origin==="user"||r?.source==="user"?{role:"user",isUser:!0}:{role:t||n||"assistant",isUser:!1}},qw=i.lazy(()=>ls(()=>import("./ToolOutputDialog-DTPUcxdH.js"),__vite__mapDeps([2,0,1,3,4]))),Kw=new Set(["task","edit","multiedit","write","bash"]),Id=s=>typeof s=="string"&&Kw.has(s.toLowerCase());function ji(s){const r=i.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&s!==void 0&&s!==null&&(r.current={hasValue:!0,value:s}),r.current.hasValue?r.current.value:s}const ir=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},Qw=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:l})=>{const{isMobile:c,hasTouchInput:d}=Ht(),{currentTheme:u}=Vr(),m=i.useRef(null),f=he(fl(ke=>({lifecyclePhase:ke.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const Ye=s.info.sessionID??ke.currentSessionId??null;return Ye?(ke.streamingMessageIds.get(Ye)??null)===s.info.id:!1})(),currentSessionId:ke.currentSessionId,getCurrentAgent:ke.getCurrentAgent,getSessionAgentSelection:ke.getSessionAgentSelection,getAgentModelForSession:ke.getAgentModelForSession,getSessionModelSelection:ke.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:y,getCurrentAgent:g,getSessionAgentSelection:w,getAgentModelForSession:b,getSessionModelSelection:v}=f,j=nt(ke=>ke.providers),k=_e(ke=>ke.showReasoningTraces),x=_e(ke=>ke.toolCallExpansion);i.useEffect(()=>{y&&Tr.getInstance().recordSessionStart(y)},[y]);const[N,P]=i.useState(null),[C,M]=i.useState(!1),[S,A]=i.useState(new Set),[D,F]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{A(new Set)},[s.info.id,x]);const I=i.useMemo(()=>wi(s.info),[s.info]).isUser,_=i.useMemo(()=>I?s.parts.map(ke=>ke.type==="compaction"?{type:"text",text:"/compact"}:ke):s.parts,[I,s.parts]),V=i.useMemo(()=>{if(I||!r)return null;const ke=ir(r.info,"clientRole"),Ye=ir(r.info,"role");if((typeof ke=="string"?ke:typeof Ye=="string"?Ye:void 0)!=="user")return null;const ot=ir(r.info,"mode"),$t=ir(r.info,"providerID"),Wt=ir(r.info,"modelID"),jt=ir(r.info,"variant"),Ct=typeof ot=="string"&&ot.trim().length>0?ot:void 0,Ut=typeof $t=="string"&&$t.trim().length>0?$t:void 0,As=typeof Wt=="string"&&Wt.trim().length>0?Wt:void 0,sr=typeof jt=="string"&&jt.trim().length>0?jt:void 0;return!Ct&&!Ut&&!As&&!sr?null:{agentName:Ct,providerId:Ut,modelId:As,variant:sr}},[I,r]),Y=i.useMemo(()=>{if(I)return;const ke=ir(s.info,"mode");if(typeof ke=="string"&&ke.trim().length>0)return ke;if(V?.agentName)return V.agentName;const Ye=s.info.sessionID;if(!Ye)return;const Ze=g(Ye);return Ze||(w(Ye)??void 0)},[I,s.info,V,g,w]),H=s.info.sessionID,L=I?null:ir(s.info,"providerID"),U=I?null:ir(s.info,"modelID"),Q=i.useMemo(()=>{if(I||!H)return null;if(V?.providerId&&V?.modelId)return{providerId:V.providerId,modelId:V.modelId};if(Y){const Ye=b(H,Y);if(Ye?.providerId&&Ye?.modelId)return Ye}const ke=v(H);return ke?.providerId&&ke?.modelId?ke:null},[I,H,Y,V,b,v]),J=i.useMemo(()=>I?null:typeof L=="string"&&L.trim().length>0?L:Q?.providerId??null,[I,L,Q]),K=i.useMemo(()=>I?null:typeof U=="string"&&U.trim().length>0?U:Q?.modelId??null,[I,U,Q]),ne=i.useMemo(()=>{if(!I&&J&&K&&j.length>0){const ke=j.find(Ye=>Ye.id===J);if(ke?.models&&Array.isArray(ke.models)){const ot=ke.models.find($t=>$t.id===K)?.name;return typeof ot=="string"?ot:void 0}}},[I,J,K,j]),X=i.useMemo(()=>{if(I||!J||!K)return!1;const ke=j.find(ot=>ot.id===J);if(!ke?.models||!Array.isArray(ke.models))return!1;const Ze=ke.models.find(ot=>ot.id===K)?.variants;return!!(Ze&&Object.keys(Ze).length>0)},[I,K,J,j]),ae=ji(Y),O=ji(J??void 0),z=ji(ne),T=ae??void 0,$=O??null,W=z??void 0,q=i.useMemo(()=>{const ke=s.info.time;return typeof ke?.completed=="number"?ke.completed:null},[s.info.time]),ue=i.useMemo(()=>I?!0:!!(q&&q>0),[I,q]),oe=i.useMemo(()=>{const ke=s.info.finish;return typeof ke=="string"?ke:void 0},[s.info]),de=i.useMemo(()=>Bw(_,{includeReasoning:k}),[_,k]),je=i.useMemo(()=>I||ue?de:[],[I,ue,de]),Se=i.useMemo(()=>I?[]:de.filter(ke=>ke.type==="text"),[I,de]),Le=i.useMemo(()=>I?[]:de.filter(Ye=>Ye.type==="tool"),[I,de]),G=i.useMemo(()=>{if(x==="collapsed"||x==="activity")return S;const ke=new Set;for(const Ze of Le){const ot=Ze.tool;Ze.id&&Id(ot)&&ke.add(Ze.id)}if(l?.isFirstAssistantInTurn)for(const Ze of l.activityParts){if(Ze.kind!=="tool")continue;const ot=Ze.part;ot.id&&Id(ot.tool)&&ke.add(ot.id)}const Ye=new Set(ke);for(const Ze of S)Ye.has(Ze)?Ye.delete(Ze):Ye.add(Ze);return Ye},[S,x,Le,l]),ee=i.useMemo(()=>{if(!I)return;const ke=s.parts.find($t=>$t.type==="agent");if(!ke)return;const Ye=ke,Ze=typeof Ye.name=="string"?Ye.name:void 0;if(!Ze)return;const ot=Ye.source&&typeof Ye.source.value=="string"&&Ye.source.value.trim().length>0?Ye.source.value:`#${Ze}`;return{name:Ze,token:ot}},[I,s.parts]),te=typeof oe!="string",xe=i.useMemo(()=>I?!1:Se.length===0||Le.length===0?te:!0,[Se.length,Le.length,te,I]),me=u?.metadata.variant,Te=i.useMemo(()=>me?me==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[me]),Ne=i.useMemo(()=>u?Vl(u):Te?qv:Kv,[u,Te]),Be=i.useMemo(()=>I?!1:Tr.getInstance().shouldAnimateMessage(s.info,y||s.info.sessionID),[s.info,y,I]),fe=i.useRef(!1),ht=i.useMemo(()=>r?wi(r.info):null,[r]),bt=i.useMemo(()=>t?wi(t.info):null,[t]),Nt=i.useMemo(()=>I||!bt?!1:!bt.isUser&&bt.role==="assistant",[I,bt]),Me=i.useMemo(()=>ue?"completed":p||(h?"streaming":"completed"),[ue,p,h]),re=i.useMemo(()=>{if(I)return!0;const ke=l?.headerMessageId;if(ke){if(s.info.id===ke){if(Me==="completed")return!0;const Ze=Me==="streaming"||Me==="cooldown",ot=fe.current;return Ze&&!ot&&(fe.current=!0),ot||Ze}return!1}return ht?ht.isUser:!0},[I,ht,l,Me,s.info]),et=i.useCallback(ke=>{navigator.clipboard.writeText(ke),P(ke),setTimeout(()=>P(null),2e3)},[]),be=l?.turnId,we=Mt(ke=>{if(!be)return;const Ye=s.info.sessionID;if(!Ye)return;const Ze=ke.messages.get(Ye);if(!Ze)return;const ot=Ze.find(jt=>jt.info?.id===be);if(!ot)return;const Wt=ot.info.summary?.body;return typeof Wt=="string"&&Wt.trim().length>0?Wt:void 0}),Ve=Mt(ke=>{if(!be)return;const Ye=s.info.sessionID;if(!Ye)return;const Ze=ke.messages.get(Ye);if(!Ze)return;const ot=Ze.find(Wt=>Wt.info?.id===be);if(!ot)return;const $t=ot.info.variant;return typeof $t=="string"&&$t.trim().length>0?$t:void 0}),tt=I?void 0:Ve??V?.variant,We=!I&&X?tt??"Default":void 0,Oe=typeof l?.summaryBody=="string"&&l.summaryBody.trim().length>0?l.summaryBody:we,rt=i.useRef(void 0);Oe&&Oe.trim().length>0&&(rt.current=Oe);const vt=i.useRef(be);vt.current!==be&&(vt.current=be,rt.current=void 0);const mt=rt.current,Tt=i.useMemo(()=>{if(I)return;const ke=s.info?.error;if(!ke)return;const Ye=typeof ke.data?.message=="string"?ke.data.message:void 0,Ze=typeof ke.message=="string"?ke.message:void 0,ot=typeof ke.name=="string"?ke.name:void 0,$t=Ye||Ze||ot;if($t)return`Opencode failed to send message with error:
113
+ \`${$t}\``},[I,s.info]),Ot=i.useMemo(()=>I?je.filter(Ze=>Ze.type==="text").map(Ze=>(Ze.text||Ze.content||"").trim()).filter(Ze=>Ze.length>0).join(`
114
+ `).replace(/\n\s*\n+/g,`
115
+ `):Tt&&Tt.trim().length>0?Tt:mt&&mt.trim().length>0?mt:Nl(je),[Tt,mt,je,I]),ve=Ot.length>0,He=i.useCallback(()=>{navigator.clipboard.writeText(Ot),M(!0),setTimeout(()=>M(!1),2e3)},[Ot]),Je=he(ke=>ke.revertToMessage),Qe=he(ke=>ke.forkFromMessage),ft=i.useCallback(()=>{!H||!s.info.id||Je(H,s.info.id)},[H,s.info.id,Je]),it=i.useCallback(()=>{!H||!s.info.id||Qe(H,s.info.id)},[H,s.info.id,Qe]),Pe=i.useCallback(ke=>{A(Ye=>{const Ze=new Set(Ye);return Ze.has(ke)?Ze.delete(ke):Ze.add(ke),Ze})},[]),ze=o??null,lt=i.useRef(!1),Ke=i.useRef(!1),wt=i.useRef(!1),Pt=i.useRef(!1),St=i.useRef(!1);i.useEffect(()=>{Ke.current=!1,wt.current=!1,Pt.current=!1,St.current=!1,lt.current=!1},[s.info.id]);const ge=i.useCallback(()=>{I||lt.current||(lt.current=!0,n?.("structural"))},[I,n]),Ie=i.useCallback(ke=>{ke.image&&F(ke)},[]),B=i.useCallback(ke=>{F(Ye=>({...Ye,open:ke}))},[]),ce=!!ir(s.info,"animationSettled"),ye=Me==="streaming",$e=i.useMemo(()=>I?!1:de.some(ke=>ke.type==="reasoning"),[I,de]),Ue=Be&&!ce&&!ye,st=!I&&Be&&Se.length>0&&!xe;return i.useEffect(()=>{if(ze?.onStreamingCandidate){if(!st){wt.current&&($e&&ze?.onReasoningBlock?ze.onReasoningBlock():ze?.onReservationCancelled&&ze.onReservationCancelled(),wt.current=!1);return}St.current||(St.current=!0,ze.onStreamingCandidate(),wt.current=!0)}},[ze,st,$e]),i.useEffect(()=>{ze?.onAnimationStart&&Ue&&(Pt.current||(ze.onAnimationStart(),Pt.current=!0))},[ze,Ue]),i.useEffect(()=>{if(I)return;const ke=ze?.onAnimatedHeightChange;if(!ke||!(Ue||st))return;const Ze=m.current;if(!Ze)return;if(typeof window>"u"||typeof ResizeObserver>"u"){ke(Ze.getBoundingClientRect().height);return}let ot=null;const $t=jt=>{if(typeof window>"u"){ke(jt);return}ot!==null&&window.cancelAnimationFrame(ot),ot=window.requestAnimationFrame(()=>{ke(jt)})},Wt=new ResizeObserver(jt=>{const Ct=jt[0];Ct&&$t(Ct.contentRect.height)});return Wt.observe(Ze),$t(Ze.getBoundingClientRect().height),()=>{ot!==null&&(window.cancelAnimationFrame(ot),ot=null),Wt.disconnect()}},[Ue,I,ze,st]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group w-full",re?"pt-2":"pt-0",I?"pb-2":Nt?"pb-0":"pb-2"),"data-message-id":s.info.id,ref:m,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:I?e.jsx(ys,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-xl rounded-br-xs bg-primary/10 dark:bg-primary/8 px-3.5 pt-2.5 pb-1.5",children:e.jsx(Ed,{messageId:s.info.id,parts:de,isUser:I,isMessageCompleted:ue,messageFinish:oe,syntaxTheme:Ne,isMobile:c,hasTouchInput:d,copiedCode:N,onCopyCode:et,expandedTools:S,onToggleTool:Pe,onShowPopup:Ie,streamPhase:Me,allowAnimation:Ue,onContentChange:n,shouldShowHeader:!1,hasTextContent:ve,onCopyMessage:He,copiedMessage:C,showReasoningTraces:k,onAuxiliaryContentComplete:ge,agentMention:ee,onRevert:ft,onFork:I?it:void 0,errorMessage:Tt})})})}):e.jsxs("div",{children:[re&&e.jsx(Yv,{isUser:I,providerID:$,agentName:T,modelName:W,variant:We,isDarkTheme:Te}),e.jsx(Ed,{messageId:s.info.id,parts:de,isUser:I,isMessageCompleted:ue,messageFinish:oe,messageCompletedAt:q??void 0,syntaxTheme:Ne,isMobile:c,hasTouchInput:d,copiedCode:N,onCopyCode:et,expandedTools:G,onToggleTool:Pe,onShowPopup:Ie,streamPhase:Me,allowAnimation:Ue,onContentChange:n,shouldShowHeader:re,hasTextContent:ve,onCopyMessage:He,copiedMessage:C,onAuxiliaryContentComplete:ge,showReasoningTraces:k,agentMention:ee,turnGroupingContext:l,errorMessage:Tt})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(qw,{popup:D,onOpenChange:B,syntaxTheme:Ne,isMobile:c})})]})},Yw=i.memo(Qw),Xw=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:xf(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file||t?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,l)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(dr,{style:r,language:gr(t||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},l))})]},o))}),Jw=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
116
+ `),o=gr(t??"")||"text",a=t?.split("/").pop()||"New file",l=Math.max(n.length,1),c=l===1?"line 1":`lines 1-${l}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${c})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(dr,{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))})]})},Zw=s=>{const r="h-3 w-3",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(br,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(_u,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx($r,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx($i,{className:r}):e.jsx(Ia,{className:r})},ej=s=>{const r=s.toLowerCase();return r==="edit"||r==="multiedit"||r==="str_replace"||r==="str_replace_based_edit_tool"?"edit":r==="write"||r==="create"||r==="file_write"?"write":r==="bash"||r==="shell"||r==="cmd"||r==="terminal"||r==="shell_command"?"bash":r==="webfetch"||r==="fetch"||r==="curl"||r==="wget"?"webfetch":s},tj=({permission:s,onResponse:r})=>{const[t,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:l}=he(),{currentTheme:c}=Vr(),d=i.useMemo(()=>Vl(c),[c]),u=async b=>{n(!0);try{await l(s.sessionID,s.id,b),a(!0),r?.(b)}catch{}finally{n(!1)}};if(o)return null;const m=s.permission||"unknown",f=m.toLowerCase(),p=(b,v="")=>{const j=s.metadata[b];return typeof j=="string"?j:typeof j=="number"?String(j):v},h=b=>{const v=s.metadata[b];return typeof v=="number"?v:void 0},y=b=>!!s.metadata[b],g=ej(m),w=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const j=p("command")||p("cmd")||p("script"),k=p("description"),x=p("cwd")||p("working_directory")||p("directory")||p("path"),N=h("timeout");return e.jsxs(e.Fragment,{children:[k&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:k}),x&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Working Directory:"})," ",e.jsx("code",{className:"px-1 py-0.5 bg-muted/30 rounded",children:x})]}),N&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",N,"ms"]}),j&&e.jsx("div",{children:e.jsx(dr,{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:j})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const j=p("path")||p("file_path")||p("filename")||p("filePath"),k=p("changes")||p("diff"),x=y("replace_all")||y("replaceAll");return e.jsxs(e.Fragment,{children:[x&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),k&&e.jsx(xt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Xw,{diff:k,syntaxTheme:d,filePath:j})})]})}if(f==="write"||f==="create"||f==="file_write"){const j=p("path")||p("file_path")||p("filename")||p("filePath"),k=p("content")||p("text")||p("data");return k?e.jsx(xt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Jw,{content:k,syntaxTheme:d,filePath:j})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const j=p("url")||p("uri")||p("endpoint"),k=p("method")||"GET",x=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,N=p("body")||p("data")||p("payload"),P=h("timeout"),C=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:k}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:j})]})]}),x&&Object.keys(x).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(xt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(dr,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(x,null,2)})})]}),N&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(xt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(dr,{language:typeof N=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof N=="object"?JSON.stringify(N,null,2):String(N)})})]}),(P||C)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[P&&e.jsxs("span",{children:["Timeout: ",P,"ms"]}),P&&C&&e.jsx("span",{children:" • "}),C&&e.jsxs("span",{children:["Response format: ",C]})]})]})}const b=p("command")||p("content")||p("action")||p("operation"),v=p("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(xt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(b)})})]}),Object.keys(s.metadata).length>0&&!b&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(xt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(s.metadata,null,2)})})]})]})};return e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20 bg-muted/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(on,{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:[Zw(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:g})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[s.patterns.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Patterns:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:s.patterns.join(", ")})]}),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:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Bt,{className:"h-3 w-3"}),"Allow Once"]}),s.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(fr,{className:"h-3 w-3"}),(()=>{const b=s.always||s.metadata.always||[];if(b.length===0)return"Always Allow";const j=b.slice(0,2).join(", ");return b.length>2?`Always: ${j}...`:`Always: ${j}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(fr,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(Gt,{className:"h-3 w-3"}),"Deny"]}),t&&e.jsx("div",{className:"ml-auto typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},Si="summary",sj=({question:s})=>{const{respondToQuestion:r,rejectQuestion:t}=he(),[n,o]=i.useState("0"),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState({}),[f,p]=i.useState({}),[h,y]=i.useState({}),g=i.useMemo(()=>s.questions??[],[s.questions]),w=n===Si,b=w?-1:Math.max(0,Math.min(g.length-1,Number(n)||0)),v=w?null:g[b];i.useEffect(()=>{o("0"),m({}),p({}),y({}),d(!1)},[s.id]);const j=i.useMemo(()=>{const E=g.map((I,_)=>({value:String(_),label:I.header?.trim()||`Q${_+1}`}));return g.length>1&&E.push({value:Si,label:"Summary"}),E},[g]),k=i.useCallback(E=>{if(!!f[E])return(h[E]??"").trim()||"(no answer)";const _=u[E]??[];return _.length>0?_.join(", "):"(no answer)"},[f,h,u]),x=!!v?.multiple,N=u[b]??[],P=!!f[b],C=i.useMemo(()=>{if(g.length===0)return!1;for(let E=0;E<g.length;E+=1){if(!!f[E]){if(!(h[E]??"").trim())return!1;continue}if((u[E]??[]).length===0)return!1}return!0},[f,h,g.length,u]),M=i.useCallback(()=>{const E=[];for(let I=0;I<g.length;I+=1){if(!!f[I]){const V=(h[I]??"").trim();E.push(V?[V]:[]);continue}E.push(u[I]??[])}return E},[f,h,g.length,u]),S=i.useCallback(E=>{v&&(p(I=>({...I,[b]:!1})),m(I=>{const _=I[b]??[];if(x){const Y=_.includes(E)?_.filter(H=>H!==E):[..._,E];return{...I,[b]:Y}}return{...I,[b]:[E]}}))},[b,v,x]),A=i.useCallback(()=>{p(E=>({...E,[b]:!0})),m(E=>({...E,[b]:[]}))},[b]),D=i.useCallback(async()=>{if(C){l(!0);try{const E=M();await r(s.sessionID,s.id,E),d(!0)}catch{}finally{l(!1)}}},[M,s.id,s.sessionID,C,r]),F=i.useCallback(async()=>{l(!0);try{await t(s.sessionID,s.id),d(!0)}catch{}finally{l(!1)}},[s.id,s.sessionID,t]);return c||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(on,{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:[j.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:j.map(E=>{const I=n===E.value,_=E.value===Si;return e.jsxs("button",{type:"button",onClick:()=>o(E.value),className:R("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",I?"bg-muted/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-muted/20"),children:[_?e.jsx($u,{className:"h-3 w-3"}):null,E.label]},E.value)})}):null,w?e.jsx("div",{className:"space-y-2",children:g.map((E,I)=>{const _=k(I),V=_!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(I)),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:E.header||`Question ${I+1}`}),e.jsx("div",{className:R("typography-meta",V?"text-foreground":"text-muted-foreground/50 italic"),children:_})]},I)})}):v?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:v.question}),x?e.jsx("div",{className:"typography-micro text-muted-foreground mb-1.5",children:"Select multiple"}):null,e.jsxs("div",{className:"space-y-0.5",children:[v.options.map((E,I)=>{const _=N.includes(E.label),V=/\(recommended\)/i.test(E.label);return e.jsx("button",{type:"button",onClick:()=>S(E.label),disabled:a,className:R("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",_?"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:_?e.jsx(_h,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(Li,{className:"h-3.5 w-3.5 text-muted-foreground/50"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:R("typography-meta break-all",_?"text-foreground font-medium":"text-foreground/80"),children:E.label}),V?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),E.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:E.description}):null]})]})},`${I}:${E.label}`)}),e.jsx("button",{type:"button",onClick:A,disabled:a,className:R("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",P?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ho,{className:R("h-3.5 w-3.5",P?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:R("typography-meta",P?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),P?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:E=>{if(E){E.style.height="auto";const I=20,_=I*2,V=I*4;E.style.height=`${Math.min(Math.max(E.scrollHeight,_),V)}px`}},value:h[b]??"",onChange:E=>{const I=E.target;I.style.height="auto";const _=20,V=_*2,Y=_*4;I.style.height=`${Math.min(Math.max(I.scrollHeight,V),Y)}px`,y(H=>({...H,[b]:I.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:D,disabled:a||!C,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(Bt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:F,disabled:a,className:R("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(Gt,{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]})]})})})},rj=new Set(["task"]),Pd=s=>typeof s=="string"&&rj.has(s.toLowerCase()),nj=s=>{const r=[];let t=null;return s.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(t={turnId:n.info.id,userMessage:n,assistantMessages:[]},r.push(t)):o==="assistant"&&t&&t.assistantMessages.push(n)}),r},oj=s=>{for(const r of s.assistantMessages)if(r.info.finish==="stop"){const n=r.parts.find(o=>o.type==="text");if(n){const o=n.text??n.content;if(typeof o=="string"&&o.trim().length>0)return o}}},aj=s=>{const r=oj(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let b=0,v=0,j=0;o.forEach(k=>{if(!k)return;const x=typeof k.additions=="number"?k.additions:0,N=typeof k.deletions=="number"?k.deletions:0;(x!==0||N!==0)&&(j+=1),b+=x,v+=N}),j>0&&(t={additions:b,deletions:v,files:j})}let a=!1,l=!1;s.assistantMessages.forEach(b=>{b.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(l=!0)})});const c=[];let d=0;s.assistantMessages.forEach(b=>{const v=b.info.id;b.info.finish,b.parts.forEach(j=>{const k=typeof j.id=="string"&&j.id.trim().length>0?j.id:`${v}-activity-${d++}`;if(j.type==="tool"){const N=j.state?.time,P=typeof N?.end=="number"?N.end:void 0;c.push({id:k,turnId:s.turnId,messageId:v,kind:"tool",part:j,endedAt:P});return}if(j.type==="reasoning"){const x=j.text??j.content;if(typeof x!="string"||x.trim().length===0)return;const N=j.time,P=typeof N?.end=="number"?N.end:void 0;c.push({id:k,turnId:s.turnId,messageId:v,kind:"reasoning",part:j,endedAt:P});return}})});const u=[],m=new WeakMap;c.forEach(b=>{m.set(b.part,b)});const f=new Map,p=[],h=new Map;let y=null;s.assistantMessages.forEach(b=>{const v=b.info.id;b.parts.forEach(j=>{if(j.type==="tool"){const N=j.tool;if(Pd(N)){const P=typeof j.id=="string"&&j.id.trim().length>0?j.id:`${v}-task-${p.length+1}`;f.has(P)||(f.set(P,v),p.push(P)),y=P;return}}const k=m.get(j);if(!k)return;if(k.kind==="tool"){const N=k.part.tool;if(Pd(N))return}const x=h.get(y)??[];x.push(k),h.set(y,x)})});const g=b=>{if(b.length===0)return;const v=new Map;b.forEach(x=>{v.set(x.messageId,(v.get(x.messageId)??0)+1)});let j,k=0;for(const x of s.assistantMessages){const N=v.get(x.info.id)??0;if(N>0&&!j&&(j=x.info.id),k+=N,k>=2)return x.info.id}return j};return[null,...p].forEach(b=>{const v=h.get(b)??[];if(v.length===0)return;const j=b===null?g(v):f.get(b);j&&u.push({id:`${s.turnId}:${j}:${b??"start"}`,anchorMessageId:j,afterToolPartId:b,parts:v})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:l,summaryBody:r,diffStats:t}},ij=s=>{const{isWorking:r}=Hl(),t=i.useMemo(()=>nj(s),[s]),n=i.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=i.useMemo(()=>{const g=new Map;return t.forEach(w=>{g.set(w.userMessage.info.id,w),w.assistantMessages.forEach(b=>{g.set(b.info.id,w)})}),g},[t]),a=i.useMemo(()=>{const g=new Map;return t.forEach(w=>{g.set(w.turnId,aj(w))}),g},[t]),[l,c]=i.useState(()=>new Map),d=_e(g=>g.toolCallExpansion),u=d==="activity"||d==="detailed";i.useEffect(()=>{c(new Map)},[d]);const m=i.useCallback(g=>{const w=l.get(g);return w||{isExpanded:u,previewedPartIds:new Set}},[l,u]),f=i.useCallback(g=>{c(w=>{const b=new Map(w),v=b.get(g)??{isExpanded:u,previewedPartIds:new Set};return b.set(g,{...v,isExpanded:!v.isExpanded}),b})},[u]),p=i.useCallback((g,w)=>{w.length!==0&&c(b=>{const v=new Map(b),j=v.get(g)??{isExpanded:u,previewedPartIds:new Set},k=new Set(j.previewedPartIds);return w.forEach(x=>{x&&x.trim().length>0&&k.add(x)}),v.set(g,{...j,previewedPartIds:k}),v})},[u]),h=i.useCallback(g=>o.get(g),[o]),y=i.useCallback(g=>{const w=o.get(g);if(!w||!w.assistantMessages.some(Y=>Y.info.id===g))return;const v=a.get(w.turnId),j=v?.activityParts??[],k=v?.activityGroupSegments??[],x=!!v?.hasTools,N=!!v?.hasReasoning,P=v?.summaryBody,C=v?.diffStats,M=w.assistantMessages[0]?.info.id,S=g===M,A=w.assistantMessages[w.assistantMessages.length-1]?.info.id,D=g===A,F=M,E=m(w.turnId),I=r&&n===w.turnId,_=w.userMessage.info.time,V=typeof _?.created=="number"?_.created:void 0;return{turnId:w.turnId,isFirstAssistantInTurn:S,isLastAssistantInTurn:D,summaryBody:P,activityParts:j,activityGroupSegments:k,headerMessageId:F,hasTools:x,hasReasoning:N,diffStats:C,userMessageCreatedAt:V,isWorking:I,isGroupExpanded:E.isExpanded,previewedPartIds:E.previewedPartIds,toggleGroup:()=>f(w.turnId),markPartsPreviewed:Y=>p(w.turnId,Y)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:y}},lj=({messages:s,permissions:r,questions:t,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:l,onLoadOlder:c,scrollToBottom:d,pendingAnchorId:u})=>{i.useEffect(()=>{r.length===0&&t.length===0||n("permission")},[r,t,n]);const m=i.useMemo(()=>{const p=new Set;return s.filter(h=>{const y=h.info?.id;if(typeof y=="string"){if(p.has(y))return!1;p.add(y)}return!0}).map(h=>({...h,parts:Rv(h.parts)}))},[s]),{getContextForMessage:f}=ij(m);return e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:l?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:c,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:m.map((p,h)=>e.jsx(Yw,{message:p,previousMessage:h>0?m[h-1]:void 0,nextMessage:h<m.length-1?m[h+1]:void 0,onContentChange:n,animationHandlers:o(p.info.id),scrollToBottom:d,isPendingAnchor:u===p.info.id,turnGroupingContext:f(p.info.id)},p.info.id))}),(t.length>0||r.length>0)&&e.jsxs("div",{children:[t.map(p=>e.jsx(sj,{question:p},p.id)),r.map(p=>e.jsx(tj,{permission:p},p.id))]})]})},cj=i.memo(lj);function dj(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const wf=i.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:l,className:c,children:d,...u},m)=>{const f=i.useRef(null),p=i.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const y=i.useMemo(()=>{const v={...l};return v["--scroll-shadow-size"]=`${t}px`,v},[t,l]),g=i.useCallback((v,j,k,x,N)=>{const P=`${x}${N.charAt(0).toUpperCase()}${N.slice(1)}Scroll`;j&&k?(v.dataset[P]="true",v.removeAttribute(`data-${x}-scroll`),v.removeAttribute(`data-${N}-scroll`)):(v.dataset[`${x}Scroll`]=String(j),v.dataset[`${N}Scroll`]=String(k),v.removeAttribute(`data-${x}-${N}-scroll`))},[]),w=i.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(j=>{v.removeAttribute(`data-${j}-scroll`)})},[]),b=i.useCallback(()=>{const v=f.current;if(!v)return;if(!n){w(v);return}const j=s==="vertical"?v.scrollTop>r:v.scrollLeft>r;let k=s==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&s==="vertical"&&(k=!1),g(v,j,k,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const x=j&&k?"both":j?s==="vertical"?"top":"left":k?s==="vertical"?"bottom":"right":"none";x!==p.current&&(p.current=x,a?.(x))},[w,o,n,r,a,s,g]);return i.useEffect(()=>{const v=f.current;if(!v)return;const j=()=>b(),k=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null,x=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return b(),v.addEventListener("scroll",j,{passive:!0}),k?.observe(v),x?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",j),k?.disconnect(),x?.disconnect()}},[b]),e.jsx("div",{...u,ref:dj(f,m),className:c,"data-orientation":s,"data-scroll-shadow":h??!0,style:y,children:d})});wf.displayName="ScrollShadow";const uj=160,mj=({containerRef:s})=>{const[r,t]=i.useState(!0),n=i.useRef(!0),o=i.useRef(!1),a=i.useRef(null),l=i.useRef(null),c=i.useRef(0),d=i.useRef(0),u=i.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,l.current=null},[]),m=i.useCallback(j=>{const k=s.current;if(!k){u();return}l.current===null&&(l.current=j);const x=Math.min(1,(j-l.current)/uj),N=1-Math.pow(1-x,3),P=c.current,C=d.current,M=P+(C-P)*N;if(k.scrollTop=M,x<1){a.current=window.requestAnimationFrame(m);return}k.scrollTop=C,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=i.useCallback((j,k)=>{const x=s.current;if(!x)return;const N=Math.max(0,j),P=k?.instant??!1;if(o.current=!1,typeof window>"u"||P){u(),x.scrollTop=N;const M=N<=1;n.current!==M&&(n.current=M,t(M));return}if(u(),Math.abs(N-x.scrollTop)<=.5){x.scrollTop=N;const M=N<=1;n.current!==M&&(n.current=M,t(M));return}c.current=x.scrollTop,d.current=N,l.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=i.useCallback(()=>{o.current=!0},[]),h=i.useCallback(()=>{o.current=!0},[]),y=i.useCallback(()=>o.current,[]),g=i.useCallback(()=>s.current?.scrollTop??0,[s]),w=i.useCallback(()=>s.current?.scrollHeight??0,[s]),b=i.useCallback(()=>s.current?.clientHeight??0,[s]),v=i.useCallback(()=>{const j=s.current;if(!j)return;o.current&&a.current!==null&&u();const k=j.scrollTop<=1;n.current!==k&&(n.current=k,t(k))},[u,s]);return i.useEffect(()=>{const j=s.current;if(j)return j.addEventListener("wheel",h,{passive:!0}),j.addEventListener("touchstart",h,{passive:!0}),()=>{j.removeEventListener("wheel",h),j.removeEventListener("touchstart",h)}},[s,h]),i.useEffect(()=>()=>{u()},[u]),i.useMemo(()=>({handleScroll:v,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:y,getScrollTop:g,getScrollHeight:w,getClientHeight:b}),[v,f,p,r,y,g,w,b])},Td=typeof window<"u"?i.useLayoutEffect:i.useEffect,Fd=50,Rd=40,fj=.2,pj=.1,hj=150,Us=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},gj=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},xj=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:l,sessionActivityPhase:c})=>{const d=i.useRef(null),u=mj({containerRef:d}),[m,f]=i.useState(null),[p,h]=i.useState(0),[y,g]=i.useState(!1),[w,b]=i.useState(null),v=i.useRef(null),j=i.useRef(null),k=i.useRef(r.length),x=i.useRef(r.length>0?Us(r[0]):null),N=i.useRef(r.length>0?Us(r[r.length-1]):null),P=i.useRef(0),C=i.useRef(0),M=i.useRef(void 0),S=i.useRef(null),A=i.useRef(!1),D=i.useRef(!1),F=i.useRef(null),E=s?c?.get(s)??"idle":"idle",I=i.useCallback(O=>{const z=Math.max(0,O);P.current!==z&&(P.current=z,h(z))},[]),_=i.useCallback(()=>{const O=d.current;O&&(C.current=O.clientHeight)},[]),V=i.useCallback(()=>{if(!m)return null;const O=d.current;return O?O.querySelector(`[data-message-id="${m}"]`):null},[m]),Y=i.useCallback(()=>{const O=d.current,z=P.current;if(!O||z<=0)return!0;const T=O.scrollHeight-z;return O.scrollTop+O.clientHeight<T},[]),H=i.useCallback((O,z)=>{const T=O.offsetHeight,$=O.offsetTop;if(T>z*fj){const q=z*pj;return $+T-q}else return $-Fd},[]),L=i.useCallback(()=>{const O=d.current;if(!O||!S.current)return;const z=V();if(!z)return;const T=O.clientHeight,$=O.scrollHeight,q=H(z,T)+T,ue=P.current,oe=$-ue;if(!A.current&&oe<q){const de=q-oe;de>ue&&(I(de),s&&S.current&&n(s,S.current,de))}},[H,s,V,n,I]),U=i.useCallback(()=>{const O=d.current;if(!O){g(!1);return}if(w){g(!1);return}if(!(O.scrollHeight>O.clientHeight)){g(!1);return}const T=O.scrollHeight-O.scrollTop-O.clientHeight,$=P.current;if($>0){const W=O.scrollHeight-$,q=O.scrollTop+O.clientHeight;g(q<W)}else g(T>Rd)},[w]),Q=i.useCallback(O=>{const z=d.current;if(!z)return;const T=z.scrollHeight-z.scrollTop-z.clientHeight;if(D.current&&E==="idle"&&!a&&!O?.force&&T>Rd)return;O?.force&&(D.current=!1);const W=z.scrollHeight-z.clientHeight;u.scrollToPosition(Math.max(0,W),O)},[E,a,u]),J=i.useCallback(O=>{if(v.current===O)return;v.current=O,b(O);const z=d.current;if(!z){b(null);return}const T=z.scrollHeight,$=P.current,W=T-$,q=C.current>0?C.current:z.clientHeight,oe=W-Fd,de=oe+q;let je=0;W<de&&(je=de-W),je!==$&&I(je),s&&n(s,O,je),A.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(oe,{instant:!0}),window.requestAnimationFrame(()=>{b(null)})})},[s,u,n,I]),K=i.useCallback(O=>{const z=d.current;if(!z||!s)return;O?.isTrusted&&(D.current=!0),u.handleScroll(),U(),E==="idle"&&P.current>0&&Y()&&(I(0),S.current=null,f(null),n(s,null,0));const{scrollTop:T,scrollHeight:$,clientHeight:W}=z,q=(T+W/2)/Math.max($,1),ue=Math.floor(q*r.length);t(s,ue)},[s,E,Y,u,r.length,n,U,I,t]);i.useEffect(()=>{const O=d.current;if(O)return O.addEventListener("scroll",K,{passive:!0}),()=>{O.removeEventListener("scroll",K)}},[K]),Td(()=>{if(typeof window>"u")return;_();const O=()=>{M.current!==void 0&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{_()},hj)};return window.addEventListener("resize",O),()=>{window.removeEventListener("resize",O),M.current!==void 0&&window.clearTimeout(M.current)}},[_]),i.useEffect(()=>{if(s&&s!==j.current){j.current=s,Tr.getInstance().recordSessionStart(s),k.current=r.length,x.current=r.length>0?Us(r[0]):null,N.current=r.length>0?Us(r[r.length-1]):null;const O=o(s);E!=="idle"&&O&&O.anchorId?(S.current=O.anchorId,v.current=O.anchorId,A.current=!0,f(O.anchorId),P.current=O.spacerHeight,h(O.spacerHeight),window.requestAnimationFrame(()=>{const T=d.current;if(!T)return;const $=T.querySelector(`[data-message-id="${O.anchorId}"]`);if($){const W=T.clientHeight,q=H($,W);u.scrollToPosition(q,{instant:!0})}})):(v.current=null,S.current=null,A.current=!1,f(null),P.current=0,h(0),window.requestAnimationFrame(()=>{Q({instant:!0,force:!0})})),b(null),g(!1),D.current=!1,F.current=null}},[E,s,Q,r.length,o]),Td(()=>{if(a){k.current=r.length,x.current=r.length>0?Us(r[0]):null,N.current=r.length>0?Us(r[r.length-1]):null;return}if(j.current!==s)return;const O=k.current,z=r.length;if(z>O&&O>0){const T=x.current,$=Us(r[0]),W=Us(r[z-1]),q=N.current,ue=T!==null&&$!==T,oe=q!==null&&W!==q,de=ue&&!oe,je=oe&&!ue;if(de){S.current=null,A.current=!1,f(null),I(0),k.current=z,x.current=$,N.current=W;return}if(je){const Le=r.slice(O,z).find(gj);if(Le){const G=Us(Le);G&&(S.current=G,f(G),J(G))}else L()}}k.current=z,x.current=r.length>0?Us(r[0]):null,N.current=r.length>0?Us(r[r.length-1]):null},[s,a,L,J,r]),i.useEffect(()=>{const O=d.current;if(!O||typeof ResizeObserver>"u")return;const z=new ResizeObserver(()=>{L(),U()});return z.observe(O),()=>{z.disconnect()}},[L,U]),i.useEffect(()=>{if(typeof window>"u"){U();return}const O=window.requestAnimationFrame(()=>{U()});return()=>{window.cancelAnimationFrame(O)}},[s,r.length,U]),i.useEffect(()=>{m&&(L(),U())},[m,L,U]),i.useEffect(()=>{const O=F.current;F.current=E,O!==null&&O!=="idle"&&E==="idle"&&P.current>0&&Y()&&S.current!==null&&(I(0),S.current=null,A.current=!1,f(null),s&&n(s,null,0))},[E,s,Y,n,I]),i.useEffect(()=>{U()},[p,U]);const ne=i.useRef(new Map),X=i.useCallback(()=>{L(),U()},[L,U]),ae=i.useCallback(O=>{const z=ne.current.get(O);if(z)return z;const T={onChunk:()=>{L()},onComplete:()=>{L()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{L()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return ne.current.set(O,T),T},[L]);return{scrollRef:d,handleMessageContentChange:X,getAnimationHandlers:ae,showScrollButton:y,scrollToBottom:Q,spacerHeight:p,pendingAnchorId:w,hasActiveAnchor:m!==null}};function yj(s){const t=Date.now()-s,n=Math.floor(t/1e3),o=Math.floor(n/60),a=Math.floor(o/60),l=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:l<7?`${l}d ago`:new Date(s).toLocaleDateString()}const bj=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=he(g=>g.currentSessionId),o=Mt(g=>n?g.messages.get(n)||[]:[]),a=he(g=>g.revertToMessage),l=he(g=>g.forkFromMessage),c=he(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=>Od(w.parts).toLowerCase().includes(g))},[p,m]),y=async g=>{if(n){u(g);try{await l(n,g),await c(),r(!1)}finally{u(null)}}};return n?e.jsx(us,{open:s,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(hs,{children:[e.jsxs(gs,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(vs,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(Xs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(kt,{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=Od(g.parts),b=g.info.time.created,v=yj(b),j=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:()=>{t?.(g.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[j,"."]}),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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:async k=>{k.stopPropagation(),await a(n,g.info.id),r(!1)},children:e.jsx(En,{className:"h-4 w-4"})})}),e.jsx(ct,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:k=>{k.stopPropagation(),y(g.info.id)},disabled:d===g.info.id,children:d===g.info.id?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(_t,{className:"h-4 w-4"})})}),e.jsx(ct,{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(En,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Undo to this point (message text will populate input)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function Od(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const jf=()=>{const{currentSessionId:s,messages:r,permissions:t,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:l,loadMoreMessages:c,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,sessionMemoryState:f,openNewSessionDraft:p,isSyncing:h,messageStreamStates:y,trimToViewportWindow:g,sessionActivityPhase:w,newSessionDraft:b}=he(),{isTimelineDialogOpen:v,setTimelineDialogOpen:j}=_e(),k=i.useMemo(()=>s?o.get(s)??null:null,[s,o]),{isMobile:x}=Ht(),N=!!b?.open;i.useEffect(()=>{!s&&!N&&p()},[s,N,p]);const P=i.useMemo(()=>s?r.get(s)||[]:[],[s,r]),C=i.useMemo(()=>s?t.get(s)||[]:[],[s,t]),M=i.useMemo(()=>s?n.get(s)||[]:[],[s,n]);i.useMemo(()=>[...C,...M],[C,M]);const{scrollRef:S,handleMessageContentChange:A,getAnimationHandlers:D,showScrollButton:F,scrollToBottom:E,spacerHeight:I,pendingAnchorId:_,hasActiveAnchor:V}=xj({currentSessionId:s,sessionMessages:P,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,isSyncing:h,isMobile:x,sessionActivityPhase:w}),H=!!i.useMemo(()=>s?f.get(s)??null:null,[s,f])?.hasMoreAbove,[L,U]=i.useState(!1);i.useEffect(()=>{U(!1)},[s]);const Q=i.useRef(null);i.useLayoutEffect(()=>{if(!(!s||s===Q.current)&&(Q.current=s,!V)){const ne=S.current;ne&&(ne.scrollTop=ne.scrollHeight-ne.clientHeight)}},[s,S,V]);const J=i.useCallback(async()=>{if(!s||L)return;const ne=S.current,X=ne?.scrollHeight??null,ae=ne?.scrollTop??null;U(!0);try{if(await c(s,"up"),ne&&X!==null&&ae!==null){const O=ne.scrollHeight-X;ne.scrollTop=ae+O}}finally{U(!1)}},[s,L,c,S]),K=i.useCallback(ne=>{const X=S.current;if(!X)return;const ae=X.querySelector(`[data-message-id="${ne}"]`);if(ae){const O=X.getBoundingClientRect(),$=ae.getBoundingClientRect().top-O.top+X.scrollTop-50;X.scrollTo({top:$,behavior:"smooth"})}},[S]);return i.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await l(s)}finally{typeof window>"u"?E():window.requestAnimationFrame(()=>{E()})}})()},[s,l,r,E]),!s&&!N?e.jsx("div",{className:"flex flex-col h-full bg-background",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(yi,{})}):!s&&N?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(yi,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(_o,{scrollToBottom:E})})]}):s?a&&P.length===0&&!k&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-column space-y-4",children:[1,2,3].map(X=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(xi,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(xi,{className:"h-4 w-24"}),e.jsx(xi,{className:"h-20 w-full"})]})]},X))})}),e.jsx(_o,{scrollToBottom:E})]}):P.length===0&&!k?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(yi,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(_o,{scrollToBottom:E})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(wf,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:S,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!_,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(cj,{messages:P,permissions:C,questions:M,onMessageContentChange:A,getAnimationHandlers:D,hasMoreAbove:H,isLoadingOlder:L,onLoadOlder:J,scrollToBottom:E,pendingAnchorId:_}),I>0&&V&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:I},"aria-hidden":"true"})]})}),e.jsx(Cl,{containerRef:S})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[F&&P.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(De,{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($n,{className:"h-4 w-4"})})}),e.jsx(_o,{scrollToBottom:E})]}),e.jsx(bj,{open:v,onOpenChange:j,onScrollToMessage:K})]}):null};class Sf extends i.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(Rl,{className:"w-full max-w-md",children:[e.jsx(Bm,{className:"text-center",children:e.jsxs(zm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx($h,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Wm,{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(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Os,{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 so=()=>{const s=he(r=>r.currentSessionId);return e.jsx(Sf,{sessionId:s||void 0,children:e.jsx(jf,{})})},_d=12,vj=[{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"}],wj=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=vj,onComplete:a})=>{const l=Ae.useRef(!1);Ae.useEffect(()=>{!s&&l.current&&a?.(),s&&(l.current=!0)},[s,a]);const c=Ae.useMemo(()=>Array.from({length:_d},(d,u)=>{const m=Math.PI*2*u/_d;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:R("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:c.map((m,f)=>{const p=m.x*d.radius,h=m.y*d.radius,y={"--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:y},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},jj=({durationMs:s=3400}={})=>{const[r,t]=Ae.useState({isActive:!1,cycle:0}),n=Ae.useRef(null),o=Ae.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Ae.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ae.useCallback(()=>{o(),t(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{t(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},s)},[o,s]);return Ae.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:l,dismissFireworks:a}},kf=i.createContext(void 0),$d=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=jj(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(kf.Provider,{value:a,children:[s,e.jsx(wj,{isActive:r,burstKey:t})]})},Sj=()=>{const s=i.useContext(kf);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},Rn=Kt()(ss(Ps((s,r)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:t=>{s({selectedProfileId:t})},loadProfiles:async()=>{s({isLoading:!0});const t=r().profiles;try{const n=await zx();return s({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),s({profiles:t,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const t=await Gx();if(t&&t.userName&&t.userEmail){const n={id:"global",name:"Global Identity",userName:t.userName,userEmail:t.userEmail,authType:t.sshCommand?"ssh":void 0,sshKey:t.sshCommand?t.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};s({globalIdentity:n})}else s({globalIdentity:null});return!0}catch(t){return console.error("Failed to load global git identity:",t),s({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const t=await Vx();return s({discoveredCredentials:t}),!0}catch(t){return console.error("Failed to discover git credentials:",t),s({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const t=n=>{if(typeof n!="string")return null;const o=n.trim();return o.length>0?o:null};try{let n=null;if(os()){const o=await zr();n=t(o?.defaultGitIdentityId)}else{const o=Zs()?.settings;if(o)try{const l=(await o.load())?.settings||{};n=t(l.defaultGitIdentityId)}catch{}if(n===null)try{const a=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(a.ok){const l=await a.json().catch(()=>null);n=t(l?.defaultGitIdentityId)}}catch{}}return s({defaultGitIdentityId:n}),!0}catch(n){return console.error("Failed to load default git identity setting:",n),!1}},setDefaultGitIdentityId:async t=>{try{const n=typeof t=="string"?t.trim():"",o=n.length>0?n:"";return await ns({defaultGitIdentityId:o}),s({defaultGitIdentityId:o.length>0?o:null}),!0}catch(n){return console.error("Failed to save default git identity setting:",n),!1}},createProfile:async t=>{try{const n={...t,id:t.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:t.color||"keyword",icon:t.icon||"branch"};return await Wx(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(t,n)=>{try{const o=r().profiles.find(l=>l.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Hx(t,a),await r().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async t=>{try{return await Ux(t),r().selectedProfileId===t&&s({selectedProfileId:null}),await r().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:t=>{const{profiles:n,globalIdentity:o}=r();return t==="global"?o||void 0:n.find(a=>a.id===t)},getUnimportedCredentials:()=>{const{profiles:t,discoveredCredentials:n}=r();return n.filter(o=>!t.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Ts(()=>ps()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Rn);const kj=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Nj=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:l=!1})=>{const[c,d]=i.useState(!1),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,y]=i.useState(""),[g,w]=i.useState(!1),b=i.useRef(null),v=i.useMemo(()=>kj(h),[h]),j=i.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(S=>S.toLowerCase().includes(M)):r},[u,r]),k=i.useMemo(()=>{const M=u.toLowerCase();return M?t.filter(S=>S.toLowerCase().includes(M)):t},[u,t]),x=M=>{if(M===s){d(!1);return}o(M),d(!1),m("")},N=()=>{p(!0),setTimeout(()=>b.current?.focus(),50)},P=async()=>{if(!(!v||g)){w(!0);try{await a(v),y(""),p(!1),d(!1)}finally{w(!1)}}},C=()=>{y(""),p(!1)};return i.useEffect(()=>{c||(m(""),p(!1),y(""))},[c]),e.jsxs(Yt,{open:c,onOpenChange:d,children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:l,children:[e.jsx(_t,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(Ft,{className:"size-4 opacity-60"})]})})}),e.jsxs(ct,{sideOffset:8,children:["Switch branch (",r.length," local · ",t.length," remote)"]})]}),e.jsx(Jt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Ol,{className:"h-full min-h-0",children:[e.jsx(_l,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs($l,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Ll,{children:"No branches found."}),e.jsx(tn,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:b,placeholder:"New branch name",value:h,onChange:M=>y(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),P()):M.key==="Escape"&&(M.preventDefault(),C())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:P,disabled:!v||g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:g?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(Zt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:C,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Gt,{className:"size-4"})})]}):e.jsxs(as,{onSelect:N,children:[e.jsx(Zt,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(ba,{}),e.jsxs(tn,{heading:"Local branches",children:[j.map(M=>e.jsxs(as,{onSelect:()=>x(M),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:M}),(n?.[M]?.ahead||n?.[M]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[M].ahead||0," ahead ·"," ",n[M].behind||0," behind"]})]}),s===M&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${M}`)),j.length===0&&e.jsx(as,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(ba,{}),e.jsxs(tn,{heading:"Remote branches",children:[k.map(M=>e.jsx(as,{onSelect:()=>x(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),k.length===0&&e.jsx(as,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},Cj=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Mj=({currentBranch:s,onRename:r})=>{const[t,n]=i.useState(!1),[o,a]=i.useState(s||""),[l,c]=i.useState(!1),d=i.useRef(null),u=()=>{!s||!r||(a(s),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!s||!r||!o.trim())return;const h=Cj(o);if(h===s){n(!1);return}c(!0);try{await r(s,h),n(!1),a("")}finally{c(!1)}},f=()=>{n(!1),a("")},p=h=>{h.key==="Enter"?(h.preventDefault(),m()):h.key==="Escape"&&(h.preventDefault(),f())};return t?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:h=>{h.preventDefault(),m()},children:[e.jsx(_t,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:h=>a(h.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:l?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(Bt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Gt,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx(_t,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate typography-ui-label font-normal text-foreground",children:s||"Detached HEAD"})]}),r&&s&&e.jsx(De,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(ho,{className:"size-4"})})]})},Dj=({syncAction:s,onFetch:r,onPull:t,onPush:n,disabled:o})=>{const a=o||s!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[s==="fetch"?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(Rr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(ct,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[s==="pull"?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx($n,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(ct,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[s==="push"?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(po,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(ct,{sideOffset:8,children:"Push changes"})]})]})},Aj={branch:_t,briefcase:gl,house:hl,graduation:pl,code:$s,heart:Bu,user:Ls},Ej={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function Nf(s){return s&&Ej[s]||"var(--primary)"}const Ld=({icon:s,className:r,colorToken:t})=>{const n=Aj[s??"branch"]??Ls;return e.jsx(n,{className:r,style:{color:Nf(t)}})},Ij=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(Yt,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:Nf(s?.color)},disabled:o,children:[n?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(Ld,{icon:s?.icon,colorToken:s?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:s?.name||"No identity"}),e.jsx(Ft,{className:"size-4 opacity-60"})]})})}),e.jsxs(ct,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:s?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:s?.userEmail||"No email configured"})]})]}),e.jsx(Jt,{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(It,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ld,{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))})]})},Pj=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:l,onPush:c,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:h,isApplyingIdentity:y,isWorktreeMode:g})=>s?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(Mj,{currentBranch:s.current,onRename:m}):e.jsx(Nj,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(dt,{delayDuration:800,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 px-1.5 typography-meta text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(po,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.ahead})]}),!!s.tracking&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx($n,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(ct,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(Dj,{syncAction:o,onFetch:a,onPull:l,onPush:c,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(Ij,{activeProfile:f,identities:p,onSelect:h,isApplying:y})]}):null,Tj=({behind:s,onPull:r,isPulling:t})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(cl,{className:"size-10 text-emerald-500/60 mb-4"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:"Working tree clean"}),e.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:"All changes have been committed"}),s>0&&e.jsxs(De,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx($n,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),Cf={"?":{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"}},Fj=Cf.M;function Rj(s){const r=s.index?.trim(),t=s.working_dir?.trim();return r&&r!=="?"?r.charAt(0):t?t.charAt(0):r?.charAt(0)||t?.charAt(0)||"M"}function Oj(s){const r=Rj(s);return Cf[r]??Fj}const _j=i.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:l,stats:c}){const d=Ae.useMemo(()=>Oj(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=Ae.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=Ae.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),y=Ae.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":t,"aria-label":`Select ${r.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t?e.jsx(ul,{className:"size-4 text-primary"}):e.jsx(ml,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:d.color},title:u,"aria-label":u,children:d.code}),e.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path}),e.jsxs("span",{className:"shrink-0 typography-micro",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",f]})]}),e.jsxs(dt,{delayDuration:200,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:y,disabled:l,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:l?e.jsx(ts,{className:"size-3.5 animate-spin"}):e.jsx(En,{className:"size-3.5"})})}),e.jsx(ct,{sideOffset:8,children:"Revert changes"})]})]})})}),$j=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:l,onViewDiff:c,onRevertFile:d})=>{const u=r.size,m=s.length;return e.jsxs("section",{className:"flex flex-col rounded-xl border border-border/60 bg-background/70",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[u,"/",m]}),m>0&&e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:l,disabled:u===0,children:"None"})]})]})]}),e.jsx(xt,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:s.map(f=>e.jsx(_j,{file:f,checked:r.has(f.path),stats:t?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>c(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function dn({className:s,variant:r,...t}){return e.jsx(De,{variant:r,size:"sm",className:R("h-7 px-2 py-0",s),...t})}const ki=38,Bd=200,Lj=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=i.useRef(null);return i.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${ki}px`;const l=Math.min(Math.max(a.scrollHeight,ki),Bd);a.style.height=`${l}px`},[s]),e.jsx(Ns,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:R("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:ki,maxHeight:Bd}})},Bj=({highlights:s,onInsert:r,onClear:t})=>{if(s.length===0)return null;const n=()=>{r(),t()};return e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"AI highlights"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx($n,{className:"size-4"})})}),e.jsx(ct,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:s.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},zj=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:l,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f,gitmojiEnabled:p,onOpenGitmojiPicker:h})=>{const y=s>0,g=r.trim()&&y&&m===null;return e.jsxs(xo,{open:y,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:y?`${s} file${s===1?"":"s"} selected`:"No files selected"})]}),e.jsx(yo,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(Bj,{highlights:n,onInsert:o,onClear:a}),e.jsx(Lj,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),p&&e.jsxs(De,{variant:"outline",size:"sm",onClick:h,className:"w-fit",type:"button",children:[e.jsx(Lh,{className:"size-4"}),"Add gitmoji"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:l,disabled:c||m!==null||s===0||f,"aria-label":"Generate commit message",children:c?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(Pu,{className:"size-4 text-primary"})})}),e.jsx(ct,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(dn,{variant:"outline",onClick:d,disabled:!g||c,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cl,{className:"size-4"}),"Commit"]})}),e.jsx(dn,{variant:"default",onClick:u,disabled:!g||c,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(ts,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(po,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function zd(s){const r=new Date(s);return Number.isNaN(r.getTime())?s:r.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Wj(s){switch(s){case"A":return"text-emerald-500";case"D":return"text-red-500";case"M":return"text-amber-500";case"R":return"text-blue-500";default:return"text-muted-foreground"}}const Hj=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:R("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",r?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:s.message}),e.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[e.jsx("span",{className:"truncate min-w-[3ch]",title:s.author_name,children:s.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:zd(s.date),children:zd(s.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:s.hash.slice(0,8)}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:l=>{l.stopPropagation(),a(s.hash)},children:e.jsx(er,{className:"size-3"})})}),e.jsx(ct,{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(ts,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(l=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:R("font-semibold w-3 text-center",Wj(l.changeType)),children:l.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:l.path,children:l.path}),!l.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",l.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",l.deletions]})]}),l.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},l.path))})})]}),Uj=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Vj=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:l,loadingCommitHashes:c,onCopyHash:d})=>{const[u,m]=i.useState(!0);return s?e.jsxs(xo,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(La,{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(Cs,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Ms,{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(cn,{placeholder:"Commits"})}),e.jsx(Ds,{children:Uj.map(f=>e.jsx(qt,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Aa,{className:"size-4 text-muted-foreground"}):e.jsx(Ft,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(yo,{children:e.jsx(xt,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:s.all.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"No commits found"})}):e.jsx("ul",{className:"divide-y divide-border/60",children:s.all.map(f=>e.jsx(Hj,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:l.get(f.hash)??[],isLoadingFiles:c.has(f.hash),onCopyHash:d},f.hash))})})})]}):null},Mf="gitmojiCache",Gj=1e3*60*60*24*7,Df="1",qj="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Af=s=>{if(!s||typeof s!="object")return!1;const r=s;return typeof r.emoji=="string"&&typeof r.code=="string"&&typeof r.description=="string"},Kj=()=>{if(typeof window>"u")return null;try{const s=localStorage.getItem(Mf);if(!s)return null;const r=JSON.parse(s);return!r||r.version!==Df||typeof r.fetchedAt!="number"||!Array.isArray(r.gitmojis)?null:{gitmojis:r.gitmojis.filter(Af),fetchedAt:r.fetchedAt,version:r.version}}catch{return null}},Qj=s=>{if(!(typeof window>"u"))try{const r={gitmojis:s,fetchedAt:Date.now(),version:Df};localStorage.setItem(Mf,JSON.stringify(r))}catch{return}},Yj=s=>Date.now()-s.fetchedAt<Gj;let qn=null;const Xj=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=yt(),o=s?t.get(s)??void 0:void 0,l=r.find(c=>c.id===s)?.directory;return o?.path??l??n??void 0},Jj=()=>{const{git:s}=Nr(),r=Xj(),{currentSessionId:t,worktreeMetadata:n}=he(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:l,defaultGitIdentityId:c,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=Rn(),f=Ml(r??null),p=Am(r??null),h=Em(r??null),y=Ly(r??null),g=By(r??null),w=Qt(ge=>ge.isLoadingStatus),b=Qt(ge=>ge.isLoadingLog),{setActiveDirectory:v,fetchAll:j,fetchStatus:k,fetchBranches:x,fetchLog:N,fetchIdentity:P,setLogMaxCount:C}=Qt(),M=i.useMemo(()=>!qn||qn.directory!==r?null:qn,[r]),S=nt(ge=>ge.settingsGitmojiEnabled),[A,D]=i.useState(M?.commitMessage??""),[F,E]=i.useState(!1),[I,_]=i.useState(null),[V,Y]=i.useState(null),[H,L]=i.useState(25),[U,Q]=i.useState(!1),{triggerFireworks:J}=Sj(),K=i.useRef(new Map),ne=i.useRef(0),X=i.useCallback(()=>{ne.current+=1,Q(!0)},[]),ae=i.useCallback(()=>{ne.current=Math.max(0,ne.current-1),ne.current===0&&Q(!1)},[]),[O,z]=i.useState(()=>new Set(M?.selectedPaths??[])),[T,$]=i.useState(!1),[W,q]=i.useState(new Set),[ue,oe]=i.useState(!1),[de,je]=i.useState([]),Se=i.useCallback(()=>{je([])},[]),[Le,G]=i.useState(new Set),[ee,te]=i.useState(new Map),[xe,me]=i.useState(new Set),[Te,Ne]=i.useState(null),[Be,fe]=i.useState([]),[ht,bt]=i.useState(""),Nt=i.useCallback(ge=>{navigator.clipboard.writeText(ge).then(()=>{Z.success("Commit hash copied")}).catch(()=>{Z.error("Failed to copy")})},[]),Me=i.useCallback(ge=>{G(Ie=>{const B=new Set(Ie);return B.has(ge)?B.delete(ge):B.add(ge),B})},[]);i.useEffect(()=>{if(!r||!s)return;const ge=Array.from(Le).filter(Ie=>!ee.has(Ie)&&!xe.has(Ie));if(ge.length!==0){me(Ie=>{const B=new Set(Ie);for(const ce of ge)B.add(ce);return B});for(const Ie of ge)s.getCommitFiles(r,Ie).then(B=>{te(ce=>new Map(ce).set(Ie,B.files))}).catch(B=>{console.error("Failed to fetch commit files:",B),te(ce=>new Map(ce).set(Ie,[]))}).finally(()=>{me(B=>{const ce=new Set(B);return ce.delete(Ie),ce})})}},[Le,r,s,ee,xe]),i.useEffect(()=>()=>{if(!r){qn=null;return}qn={directory:r,selectedPaths:Array.from(O),commitMessage:A}},[A,r,O]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!s?.getRemoteUrl){Ne(null);return}s.getRemoteUrl(r).then(Ne).catch(()=>Ne(null))},[r,s]),i.useEffect(()=>{if(!S){fe([]);return}let ge=!1;const Ie=Kj();return Ie&&(fe(Ie.gitmojis),Yj(Ie))?()=>{ge=!0}:((async()=>{try{const ce=await fetch(qj);if(!ce.ok)throw new Error(`Failed to load gitmojis: ${ce.statusText}`);const ye=await ce.json(),$e=Array.isArray(ye.gitmojis)?ye.gitmojis.filter(Af):[];ge||(fe($e),Qj($e))}catch(ce){ge||console.warn("Failed to load gitmoji list:",ce)}})(),()=>{ge=!0})},[S]),i.useEffect(()=>{r&&(v(r),Qt.getState().directories.get(r)?.status||j(r,s,{force:!0}))},[r,v,j,s]);const re=i.useCallback(async(ge=!0)=>{if(r)try{await Promise.all([k(r,s),x(r,s)])}catch(Ie){if(ge){const B=Ie instanceof Error?Ie.message:"Failed to refresh repository state";Z.error(B)}}},[r,s,k,x]),et=i.useCallback(async()=>{r&&await N(r,s,H)},[r,s,N,H]),be=i.useCallback(async()=>{r&&await P(r,s)},[r,s,P]);i.useEffect(()=>{if(!r||!s?.hasLocalIdentity||f!==!0)return;const ge=typeof c=="string"?c.trim():"";if(!ge||ge==="global"||K.current.get(r)===ge)return;let B=!1;return(async()=>{try{const ye=await s.hasLocalIdentity?.(r);if(B||ye===!0)return;X(),await s.setGitIdentity(r,ge),K.current.set(r,ge),await be()}catch(ye){console.warn("Failed to auto-apply default git identity:",ye)}finally{B||ae()}})(),()=>{B=!0}},[X,r,c,ae,s,f,be]);const we=i.useMemo(()=>{if(!p)return[];const ge=p.files??[],Ie=new Map;for(const B of ge)Ie.set(B.path,B);return Array.from(Ie.values()).sort((B,ce)=>B.path.localeCompare(ce.path))},[p]);i.useEffect(()=>{if(!p||we.length===0){z(new Set),$(!1);return}z(ge=>{const Ie=new Set,B=ge??new Set;for(const ce of we)B.has(ce.path)?Ie.add(ce.path):T||Ie.add(ce.path);return Ie})},[p,we,T]);const Ve=async ge=>{if(r){_(ge);try{if(ge==="fetch")await s.gitFetch(r),Z.success("Fetched latest updates");else if(ge==="pull"){const Ie=await s.gitPull(r);Z.success(`Pulled ${Ie.files.length} file${Ie.files.length===1?"":"s"}`)}else ge==="push"&&(await s.gitPush(r),Z.success("Pushed to remote"));await re(!1),await et()}catch(Ie){const B=Ie instanceof Error?Ie.message:`Failed to ${ge==="pull"?"pull":ge}`;Z.error(B)}finally{_(null)}}},tt=async(ge={})=>{if(!r)return;if(!A.trim()){Z.error("Please enter a commit message");return}const Ie=Array.from(O).sort();if(Ie.length===0){Z.error("Select at least one file to commit");return}const B=ge.pushAfter?"commitAndPush":"commit";Y(B);try{await s.createGitCommit(r,A.trim(),{files:Ie}),Z.success("Commit created successfully"),D(""),z(new Set),$(!1),Se(),await re(),ge.pushAfter?(await s.gitPush(r),Z.success("Pushed to remote"),J(),await re(!1)):await re(!1),await et()}catch(ce){const ye=ce instanceof Error?ce.message:"Failed to create commit";Z.error(ye)}finally{Y(null)}},We=i.useCallback(async()=>{if(r){if(O.size===0){Z.error("Select at least one file to describe");return}oe(!0);try{const{message:ge}=await s.generateCommitMessage(r,Array.from(O)),Ie=ge.subject?.trim()??"",B=Array.isArray(ge.highlights)?ge.highlights:[];Ie&&D(Ie),je(B),Z.success("Commit message generated")}catch(ge){const Ie=ge instanceof Error?ge.message:"Failed to generate commit message";Z.error(Ie)}finally{oe(!1)}}},[r,O,s]),Oe=async ge=>{if(!r||!p)return;const Ie=p.current??null;try{await s.createBranch(r,ge,Ie??"HEAD"),Z.success(`Created branch ${ge}`);let B=!1;try{await s.checkoutBranch(r,ge),await s.gitPush(r,{remote:"origin",branch:ge,options:["--set-upstream"]}),B=!0}catch(ce){const ye=ce instanceof Error?ce.message:"Unable to push new branch to origin.";Z.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",ye]})})}finally{if(Ie)try{await s.checkoutBranch(r,Ie)}catch(ce){console.warn("Failed to restore original branch after creation:",ce)}}await re(),await et(),B&&Z.success(`Upstream set for ${ge}`)}catch(B){const ce=B instanceof Error?B.message:"Failed to create branch";throw Z.error(ce),B}},rt=async(ge,Ie)=>{if(r)try{await s.renameBranch(r,ge,Ie),Z.success(`Renamed branch ${ge} to ${Ie}`),await re(),await et()}catch(B){const ce=B instanceof Error?B.message:`Failed to rename branch ${ge} to ${Ie}`;Z.error(ce)}},vt=async ge=>{if(!r)return;const Ie=ge.replace(/^remotes\//,"");if(p?.current!==Ie)try{await s.checkoutBranch(r,Ie),Z.success(`Checked out ${Ie}`),await re(),await et()}catch(B){const ce=B instanceof Error?B.message:`Failed to checkout ${Ie}`;Z.error(ce)}},mt=async ge=>{if(r){X();try{await s.setGitIdentity(r,ge.id),Z.success(`Applied "${ge.name}" to repository`),await be()}catch(Ie){const B=Ie instanceof Error?Ie.message:"Failed to apply git identity";Z.error(B)}finally{ae()}}},Tt=i.useMemo(()=>h?.all?h.all.filter(ge=>!ge.startsWith("remotes/")).sort():[],[h]),Ot=i.useMemo(()=>h?.all?h.all.filter(ge=>ge.startsWith("remotes/")).map(ge=>ge.replace(/^remotes\//,"")).sort():[],[h]),ve=i.useMemo(()=>{const ge=new Map;l&&ge.set(l.id,l);let Ie=null;if(Te)try{let B=Te.trim();B.startsWith("git@")&&(B=`https://${B.slice(4).replace(":","/")}`),B.endsWith(".git")&&(B=B.slice(0,-4));const ce=new URL(B);Ie=ce.hostname+ce.pathname}catch{}for(const B of a){if(B.authType!=="token"){ge.set(B.id,B);continue}const ce=B.host;if(!ce){ge.set(B.id,B);continue}if(!ce.includes("/")){ge.set(B.id,B);continue}Ie&&Ie===ce&&ge.set(B.id,B)}return Array.from(ge.values())},[a,l,Te]),He=i.useMemo(()=>{if(g?.userName&&g?.userEmail){const ge=a.find(Ie=>Ie.userName===g.userName&&Ie.userEmail===g.userEmail);return ge||(l&&l.userName===g.userName&&l.userEmail===g.userEmail?l:{id:"local-config",name:g.userName,userName:g.userName,userEmail:g.userEmail,sshKey:g.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return l??null},[g,a,l]),Je=we.length,Qe=O.size,ft=w||I!==null||V!==null,it=Je>0,Pe=ge=>{z(Ie=>{const B=new Set(Ie);return B.has(ge)?B.delete(ge):B.add(ge),B}),$(!0)},ze=()=>{const ge=new Set(we.map(Ie=>Ie.path));z(ge),$(!0)},lt=()=>{z(new Set),$(!0)},Ke=i.useCallback(async ge=>{if(r){q(Ie=>{const B=new Set(Ie);return B.add(ge),B});try{await s.revertGitFile(r,ge),Z.success(`Reverted ${ge}`),await re(!1)}catch(Ie){const B=Ie instanceof Error?Ie.message:"Failed to revert changes";Z.error(B)}finally{q(Ie=>{const B=new Set(Ie);return B.delete(ge),B})}}},[r,re,s]),wt=i.useCallback(()=>{if(de.length===0)return;const ge=de.map(Ie=>Ie.trim()).filter(Boolean);if(ge.length===0){Se();return}D(Ie=>{const B=Ie.trim(),ce=B.length>0?`
117
+
118
+ `:"";return`${B}${ce}${ge.join(`
119
+ `)}`.trim()})},[de,Se]),Pt=i.useCallback((ge,Ie)=>{const B=Ie||ge;D(ce=>{const ye=ce.trimStart();return ye.startsWith(ge)||Ie&&ye.startsWith(Ie)?ce:`${B.endsWith(" ")?B:`${B} `}${ce}`.trimStart()}),bt(""),E(!1)},[]),St=i.useCallback(ge=>{L(ge),r&&(C(r,ge),N(r,s,ge))},[r,C,N,s]);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(ts,{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(_t,{className:"mb-3 size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Not a Git repository"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Choose a different directory or initialize Git to use this workspace."})]}):e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background","data-keyboard-avoid":"true",children:[e.jsx(Pj,{status:p,localBranches:Tt,remoteBranches:Ot,branchInfo:h?.branches,syncAction:I,onFetch:()=>Ve("fetch"),onPull:()=>Ve("pull"),onPush:()=>Ve("push"),onCheckoutBranch:vt,onCreateBranch:Oe,onRenameBranch:rt,activeIdentityProfile:He,availableIdentities:ve,onSelectIdentity:mt,isApplyingIdentity:U,isWorktreeMode:!!o}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[it?e.jsx($j,{changeEntries:we,selectedPaths:O,diffStats:p?.diffStats,revertingPaths:W,onToggleFile:Pe,onSelectAll:ze,onClearSelection:lt,onViewDiff:ge=>_e.getState().navigateToDiff(ge),onRevertFile:Ke}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(Tj,{behind:p?.behind??0,onPull:()=>Ve("pull"),isPulling:I==="pull"})}),we.length>0&&e.jsx(zj,{selectedCount:Qe,commitMessage:A,onCommitMessageChange:D,generatedHighlights:de,onInsertHighlights:wt,onClearHighlights:Se,onGenerateMessage:We,isGeneratingMessage:ue,onCommit:()=>tt({pushAfter:!1}),onCommitAndPush:()=>tt({pushAfter:!0}),commitAction:V,isBusy:ft,gitmojiEnabled:S,onOpenGitmojiPicker:()=>E(!0)})]}),e.jsx(Vj,{log:y,isLogLoading:b,logMaxCount:H,onLogMaxCountChange:St,expandedCommitHashes:Le,onToggleCommit:Me,commitFilesMap:ee,loadingCommitHashes:xe,onCopyHash:Nt})]})}),e.jsx(us,{open:F,onOpenChange:E,children:e.jsxs(ms,{className:"max-w-md p-0 overflow-hidden",children:[e.jsx(hs,{className:"px-4 pt-4",children:e.jsx(gs,{children:"Pick a gitmoji"})}),e.jsxs(Ol,{className:"h-[420px]",children:[e.jsx(_l,{placeholder:"Search gitmojis...",value:ht,onValueChange:bt}),e.jsxs($l,{children:[e.jsx(Ll,{children:"No gitmojis found."}),e.jsx(tn,{children:(Be.length===0?[]:Be.filter(ge=>{const Ie=ht.trim().toLowerCase();return Ie?ge.emoji.includes(Ie)||ge.code.toLowerCase().includes(Ie)||ge.description.toLowerCase().includes(Ie):!0})).map(ge=>e.jsxs(as,{onSelect:()=>Pt(ge.emoji,ge.code),children:[e.jsx("span",{className:"text-lg",children:ge.emoji}),e.jsx("span",{className:"typography-ui-label text-foreground",children:ge.code}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:ge.description})]},ge.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."})})},Zj=1e6;function Yr(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const $o=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Wd=Kt((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=Yr(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=Yr(t);s(a=>{const l=new Map(a.sessions),c=l.get(o),u=!c||c.terminalSessionId!==n.sessionId?$o(o):c??$o(o);return l.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:l}})},setConnecting:(t,n)=>{const o=Yr(t);s(a=>{const l=new Map(a.sessions),c=l.get(o)??$o(o);return l.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(t,n)=>{if(!n)return;const o=Yr(t);s(a=>{const l=new Map(a.sessions),c=l.get(o)??$o(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>Zj&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return l.set(o,{...c,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:l,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=Yr(t);s(o=>{const a=new Map(o.sessions),l=a.get(n);return l&&a.set(n,{...l,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const n=Yr(t);s(o=>{const a=new Map(o.sessions),l=a.get(n);return l?(a.set(n,{...l,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const n=Yr(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),Ef=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),e0=[{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'}],t0=[{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'}],If=s=>Object.fromEntries(s.map(r=>[r.id,r])),Hd=If(e0),Xr=If(t0),s0="ibm-plex-sans",sa="ibm-plex-mono";function r0(s){const{colors:r}=s,t=r.syntax.base;return{background:r.surface.background,foreground:t.foreground,cursor:r.interactive.cursor,cursorAccent:r.surface.background,selectionBackground:r.interactive.selection,selectionForeground:r.interactive.selectionForeground,selectionInactiveBackground:r.interactive.selection+"50",black:r.surface.muted,red:r.status.error,green:r.status.success,yellow:r.status.warning,blue:t.function,magenta:t.keyword,cyan:t.type,white:t.foreground,brightBlack:t.comment,brightRed:r.status.error,brightGreen:r.status.success,brightYellow:r.status.warning,brightBlue:t.function,brightMagenta:t.keyword,brightCyan:t.type,brightWhite:r.surface.elevatedForeground}}function n0(s,r,t,n){const a=`${s}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!0,fontSize:r,lineHeight:1.15,fontFamily:a,allowTransparency:!1,theme:{background:t.background,foreground:t.foreground,cursor:t.cursor,cursorAccent:t.cursorAccent,selectionBackground:t.selectionBackground,selectionForeground:t.selectionForeground,black:t.black,red:t.red,green:t.green,yellow:t.yellow,blue:t.blue,magenta:t.magenta,cyan:t.cyan,white:t.white,brightBlack:t.brightBlack,brightRed:t.brightRed,brightGreen:t.brightGreen,brightYellow:t.brightYellow,brightBlue:t.brightBlue,brightMagenta:t.brightMagenta,brightCyan:t.brightCyan,brightWhite:t.brightWhite},scrollback:5e4,ghostty:n}}let Ni=null;function o0(){return Ni||(Ni=Wh.load()),Ni}function a0(s){if(typeof window>"u")return null;const r=[s,...Array.from(s.querySelectorAll("*"))];let t=null;for(const n of r){const a=window.getComputedStyle(n).overflowY;if(!(a!=="auto"&&a!=="scroll")){if(n.scrollHeight-n.clientHeight>2)return n;t||(t=n)}}return t}const ol=i.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d},u)=>{const m=i.useRef(null),f=i.useRef(null),p=i.useRef(null),h=i.useRef(null),y=i.useRef(t),g=i.useRef(n),w=i.useRef(null),b=i.useRef(""),v=i.useRef(null),j=i.useRef(!1),k=i.useRef(null),x=i.useRef(null),N=i.useRef(null),P=i.useRef(0),C=i.useRef(null),[,M]=i.useReducer(H=>H+1,0),[S,A]=i.useReducer(H=>H+1,0);y.current=t,g.current=n;const D=i.useCallback((H,L)=>{const U=C.current,Q=m.current;if(!U||!Q)return;const J=Q.getBoundingClientRect(),K=J.left+J.width/2,ne=J.top+J.height-12,X=typeof H=="number"?H:K,ae=typeof L=="number"?L:ne,O=8,z=Math.max(O,Math.min(J.width-O,X-J.left)),T=Math.max(O,Math.min(J.height-O,ae-J.top));U.style.left=`${z}px`,U.style.top=`${T}px`,U.style.bottom="";try{U.focus({preventScroll:!0})}catch{try{U.focus()}catch{}}},[]),F=i.useCallback(()=>{b.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,j.current=!1,k.current=null},[]),E=i.useCallback(()=>{const H=h.current,L=p.current,U=m.current;if(!H||!L||!U)return;const Q=U.getBoundingClientRect();if(!(Q.width<24||Q.height<24))try{H.fit();const J={cols:L.cols,rows:L.rows},K=w.current;(!K||K.cols!==J.cols||K.rows!==J.rows)&&(w.current=J,g.current(J.cols,J.rows))}catch{}},[]),I=i.useCallback(()=>{if(j.current)return;const H=p.current;if(!H){F();return}if(!b.current)return;const L=b.current;b.current="",j.current=!0,H.write(L,()=>{j.current=!1,b.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,I()}):I())})},[F]),_=i.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,I()}):I())},[I]),V=i.useCallback(H=>{H&&(b.current+=H,_())},[_]),Y=i.useCallback(()=>{if(x.current?.(),x.current=null,N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),!d){P.current=0;return}const H=m.current;if(!H)return;const L=p.current;if(!L)return;P.current=0;const U=2.2,Q=2.8,J=25,K=.25,ne=8,X=.05,ae=.015,O={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},z=()=>typeof performance<"u"?performance.now():Date.now(),T=Math.max(12,Math.round(l*1.35));let $=0;const W=ee=>{if(!ee)return!1;const te=L.getViewportY(),xe=$+ee,me=Math.trunc(xe/T);return $=xe-me*T,me!==0&&L.scrollLines(me),L.getViewportY()!==te},q=()=>{O.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(O.rafId),O.rafId=null},ue={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const ee=Object.assign(O,{pointerId:null,startX:null,startY:null,moved:!1}),te=6,xe=Be=>{if(Be.pointerType==="touch"){q(),ee.pointerId=Be.pointerId,ee.startX=Be.clientX,ee.startY=Be.clientY,ee.moved=!1,ee.lastY=Be.clientY,ee.lastTime=z(),ee.velocity=0;try{H.setPointerCapture(Be.pointerId)}catch{}}},me=Be=>{if(Be.pointerType!=="touch"||ee.pointerId!==Be.pointerId)return;if(ee.startX!==null&&ee.startY!==null&&!ee.moved){const we=Be.clientX-ee.startX,Ve=Be.clientY-ee.startY;Math.hypot(we,Ve)>=te&&(ee.moved=!0)}if(ee.lastY===null){ee.lastY=Be.clientY,ee.lastTime=z();return}const fe=ee.lastY,ht=ee.lastTime??z(),bt=z();ee.lastY=Be.clientY,ee.lastTime=bt;const Nt=fe-Be.clientY;if(Math.abs(Nt)<1)return;const Me=Math.max(bt-ht,8),re=U+Math.min(Q,Math.abs(Nt)/J),et=Nt*re,be=et/Me;ee.velocity=ee.velocity*(1-K)+be*K,ee.velocity>ne?ee.velocity=ne:ee.velocity<-ne&&(ee.velocity=-ne),ee.moved&&(Be.cancelable&&Be.preventDefault(),Be.stopPropagation()),W(et)},Te=Be=>{if(Be.pointerType!=="touch"||ee.pointerId!==Be.pointerId)return;const fe=!ee.moved;ee.pointerId=null,ee.startX=null,ee.startY=null,ee.moved=!1,ee.lastY=null,ee.lastTime=null;try{H.releasePointerCapture(Be.pointerId)}catch{}if(fe){D(Be.clientX,Be.clientY);return}if(typeof window>"u")return;if(Math.abs(ee.velocity)<X){ee.velocity=0;return}let ht=z();const bt=()=>{const Nt=z(),Me=Math.max(Nt-ht,8);ht=Nt;const re=W(ee.velocity*Me)??!1,et=Math.sign(ee.velocity),be=Math.max(0,Math.abs(ee.velocity)-ae*Me);if(ee.velocity=be*et,!re||be<=X){q(),ee.velocity=0;return}ee.rafId=window.requestAnimationFrame(bt)};ee.rafId=window.requestAnimationFrame(bt)};H.addEventListener("pointerdown",xe,ue),H.addEventListener("pointermove",me,ue),H.addEventListener("pointerup",Te,ue),H.addEventListener("pointercancel",Te,ue);const Ne=H.style.touchAction;H.style.touchAction="manipulation",x.current=()=>{q(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),P.current=0,H.removeEventListener("pointerdown",xe,ue),H.removeEventListener("pointermove",me,ue),H.removeEventListener("pointerup",Te,ue),H.removeEventListener("pointercancel",Te,ue),H.style.touchAction=Ne};return}const de=6,je=ee=>{ee.touches.length===1&&(q(),O.lastY=ee.touches[0].clientY,O.lastTime=z(),O.velocity=0,O.startX=ee.touches[0].clientX,O.startY=ee.touches[0].clientY,O.didMove=!1)},Se=ee=>{if(ee.touches.length!==1){O.lastY=null,O.lastTime=null,O.velocity=0,O.startX=null,O.startY=null,O.didMove=!1,q();return}const te=ee.touches[0].clientX,xe=ee.touches[0].clientY;if(O.startX!==null&&O.startY!==null&&!O.didMove){const Me=te-O.startX,re=xe-O.startY;Math.hypot(Me,re)>=de&&(O.didMove=!0)}if(O.lastY===null){O.lastY=xe,O.lastTime=z();return}const me=O.lastY,Te=O.lastTime??z(),Ne=z();O.lastY=xe,O.lastTime=Ne;const Be=me-xe;if(Math.abs(Be)<1)return;const fe=Math.max(Ne-Te,8),ht=U+Math.min(Q,Math.abs(Be)/J),bt=Be*ht,Nt=bt/fe;O.velocity=O.velocity*(1-K)+Nt*K,O.velocity>ne?O.velocity=ne:O.velocity<-ne&&(O.velocity=-ne),O.didMove&&(ee.preventDefault(),ee.stopPropagation()),W(bt)},Le=ee=>{const te=!O.didMove;O.lastY=null,O.lastTime=null;const xe=O.velocity;if(O.startX=null,O.startY=null,O.didMove=!1,te){const Ne=ee.changedTouches?.[0];D(Ne?.clientX,Ne?.clientY);return}if(typeof window>"u")return;if(Math.abs(xe)<X){O.velocity=0;return}let me=z();const Te=()=>{const Ne=z(),Be=Math.max(Ne-me,8);me=Ne;const fe=W(O.velocity*Be)??!1,ht=Math.sign(O.velocity),bt=Math.max(0,Math.abs(O.velocity)-ae*Be);if(O.velocity=bt*ht,!fe||bt<=X){q(),O.velocity=0;return}O.rafId=window.requestAnimationFrame(Te)};O.rafId=window.requestAnimationFrame(Te)};H.addEventListener("touchstart",je,ue),H.addEventListener("touchmove",Se,ue),H.addEventListener("touchend",Le,ue),H.addEventListener("touchcancel",Le,ue);const G=H.style.touchAction;H.style.touchAction="manipulation",x.current=()=>{q(),N.current!==null&&typeof window<"u"&&(window.clearTimeout(N.current),N.current=null),P.current=0,H.removeEventListener("touchstart",je,ue),H.removeEventListener("touchmove",Se,ue),H.removeEventListener("touchend",Le,ue),H.removeEventListener("touchcancel",Le,ue),H.style.touchAction=G}},[d,D,l]);return i.useEffect(()=>{let H=!1,L=null,U=null,Q=[];const J=m.current;return J?(J.tabIndex=0,(async()=>{try{const ne=await o0();if(H)return;const X=n0(a,l,o,ne),ae=new Bh(X),O=new zh;L=ae,p.current=ae,h.current=O,ae.loadAddon(O),ae.open(J),A();const z=a0(J);z?(z.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=z,M()):f.current=null,E(),Y(),ae.focus(),Q=[ae.onData(T=>{y.current(T)})],U=new ResizeObserver(()=>{E()}),U.observe(J),typeof window<"u"&&window.setTimeout(()=>{E()},0)}catch{}})(),()=>{H=!0,x.current?.(),x.current=null,Q.forEach(ne=>ne.dispose()),U?.disconnect(),L?.dispose(),p.current=null,h.current=null,f.current=null,w.current=null,F()}):void 0},[E,a,l,Y,o,F]),i.useEffect(()=>{const H=p.current;H&&(H.reset(),F(),w.current=null,E(),H.focus())},[s,S,E,F]),i.useEffect(()=>(Y(),()=>{x.current?.(),x.current=null}),[Y,s]),i.useEffect(()=>{const H=p.current;if(!H)return;if(r.length===0){k.current!==null&&(H.reset(),F(),E());return}const L=k.current;let U;if(L===null)U=r;else{const Q=r.findIndex(J=>J.id===L);U=Q>=0?r.slice(Q+1):r}U.length>0&&V(U.map(Q=>Q.data).join("")),k.current=r[r.length-1].id},[r,S,V,E,F]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){D();return}p.current?.focus()},clear:()=>{const H=p.current;H&&(H.reset(),F(),E())},fit:()=>{E()}}),[d,D,E,F]),e.jsxs("div",{ref:m,className:R("relative h-full w-full terminal-viewport-container",c),style:{backgroundColor:o.background},onClick:H=>{d?D(H.clientX,H.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:C,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,"aria-hidden":"true",style:{position:"absolute",left:0,top:0,width:1,height:1,opacity:0,zIndex:1,background:"transparent",color:"transparent",caretColor:"transparent",resize:"none",overflow:"hidden",whiteSpace:"nowrap",border:"none",padding:0,margin:0,outline:"none"},onInput:H=>{const L=String(H.currentTarget.value||"");if(!L)return;const U=L.replace(/\r\n|\r|\n/g,"\r");y.current(U),H.currentTarget.value=""},onKeyDown:H=>{H.key==="Backspace"&&(H.currentTarget.value||y.current(""))}}):null,f.current&&!d?e.jsx(Cl,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});ol.displayName="TerminalViewport";const Ud=13,i0={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Lo={ctrl:"5",cmd:"3"},l0={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},c0=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${Lo[r]}A`;case"arrow-down":return`\x1B[1;${Lo[r]}B`;case"arrow-right":return`\x1B[1;${Lo[r]}C`;case"arrow-left":return`\x1B[1;${Lo[r]}D`}return i0[s]??null},d0=()=>{const{terminal:s}=Nr(),{currentTheme:r}=Vr(),{monoFont:t}=Ef(),{isMobile:n,hasTouchInput:o}=Ht(),{currentSessionId:a,sessions:l,worktreeMetadata:c}=he(),d=a?c.get(a)??void 0:void 0,u=i.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const te=l.find(me=>me.id===a),xe=typeof te?.directory=="string"?te.directory:null;return xe&&xe.length>0?xe:null},[a,l,d]),{currentDirectory:m,homeDirectory:f}=yt(),p=u||m||null,h=i.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),y=Wd(),g=y.sessions,w=y.setTerminalSession,b=y.setConnecting,v=y.appendToBuffer,j=y.clearTerminalSession,k=y.removeTerminalSession,x=y.clearBuffer,N=i.useMemo(()=>{if(p)return g.get(p)},[g,p]),P=N?.terminalSessionId??null,C=N?.bufferChunks??[],M=N?.bufferLength??0,S=N?.isConnecting??!1,A=P,[D,F]=i.useState(null),[E,I]=i.useState(!1),[_,V]=i.useState(null),[Y,H]=i.useState(!1),L=i.useRef(null),U=i.useRef(null),Q=i.useRef(A),J=i.useRef(p),K=i.useRef(null),X=_e(te=>te.activeMainTab)==="terminal";i.useEffect(()=>{Q.current=A},[A]),i.useEffect(()=>{J.current=p},[p]),i.useEffect(()=>{!n&&_!==null&&V(null)},[n,_,V]),i.useEffect(()=>{!A&&_!==null&&V(null)},[A,_,V]);const ae=i.useCallback(()=>{L.current?.(),L.current=null,U.current=null},[]);i.useEffect(()=>()=>{ae(),Q.current=null},[ae]);const O=i.useCallback(te=>{if(U.current===te)return;ae();const xe=s.connect(te,{onEvent:me=>{const Te=J.current;if(Te)switch(me.type){case"connected":{(me.runtime||me.ptyBackend)&&console.log(`[Terminal] connected runtime=${me.runtime??"unknown"} pty=${me.ptyBackend??"unknown"}`),b(Te,!1),F(null),I(!1),K.current?.focus();break}case"reconnecting":{const Ne=me.attempt??0,Be=me.maxAttempts??3;F(`Reconnecting (${Ne}/${Be})...`),I(!1);break}case"data":{me.data&&v(Te,me.data);break}case"exit":{const Ne=typeof me.exitCode=="number"?me.exitCode:null,Be=typeof me.signal=="number"?me.signal:null;v(Te,`\r
120
+ [Process exited${Ne!==null?` with code ${Ne}`:""}${Be!==null?` (signal ${Be})`:""}]\r
121
+ `),j(Te),b(Te,!1),F("Terminal session ended"),I(!1),ae();break}}},onError:(me,Te)=>{const Ne=J.current;if(!Ne)return;const Be=Te?`Connection failed: ${me.message}`:me.message||"Terminal stream connection error";F(Be),I(!!Te),Te&&(b(Ne,!1),ae(),k(Ne))}},l0);L.current=()=>{xe.close(),U.current=null},U.current=te},[v,j,ae,k,b,s,F]);i.useEffect(()=>{let te=!1;if(!p){F(a?"No working directory available for terminal.":"Select a session to open the terminal."),ae();return}return(async()=>{const me=p;if(!J.current||J.current!==me)return;let Ne=Wd.getState().getTerminalSession(me)?.terminalSessionId??null;if(!Ne){F(null),I(!1),b(me,!0);try{const Be=await s.createSession({cwd:me});if(te){try{await s.close(Be.sessionId)}catch{}return}w(me,Be),Ne=Be.sessionId}catch(Be){te||(F(Be instanceof Error?Be.message:"Failed to start terminal session"),I(!0),b(me,!1));return}}!Ne||te||(Q.current=Ne,O(Ne))})(),()=>{te=!0,Q.current=null,ae()}},[a,p,A,k,b,w,O,ae,s]);const z=i.useCallback(async()=>{if(!p||Y)return;H(!0),F(null),I(!1),ae();const te=Q.current;try{if(s.restartSession&&te){const xe=await s.restartSession(te,{cwd:p});w(p,xe),Q.current=xe.sessionId,O(xe.sessionId)}else{if(te)try{await s.close(te)}catch{}k(p)}}catch(xe){F(xe instanceof Error?xe.message:"Failed to restart terminal"),I(!0)}finally{H(!1)}},[p,Y,ae,s,w,O,k]),T=i.useCallback(async()=>{if(p&&!Y){H(!0),F(null),I(!1),ae();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}k(p),x(p),K.current?.clear(),await new Promise(te=>setTimeout(te,100));try{b(p,!0);const te=await s.createSession({cwd:p});w(p,te),Q.current=te.sessionId,O(te.sessionId)}catch(te){F(te instanceof Error?te.message:"Failed to create terminal"),I(!0),b(p,!1)}finally{H(!1)}}},[p,Y,ae,s,k,x,b,w,O]),$=i.useCallback(()=>{if(!p)return;x(p),K.current?.clear(),K.current?.focus();const te=Q.current;te&&s.sendInput(te,"\f").catch(xe=>{F(xe instanceof Error?xe.message:"Failed to refresh prompt")})},[x,p,F,s]),W=i.useCallback(te=>{if(!te)return;let xe=te,me=!1;if(_&&te.length>0){const Ne=te[0];if(Ne.length===1&&/[a-zA-Z]/.test(Ne)){const Be=Ne.toUpperCase();(_==="ctrl"||_==="cmd")&&(xe=String.fromCharCode(Be.charCodeAt(0)&31),me=!0)}me||(me=!0)}const Te=Q.current;Te&&(s.sendInput(Te,xe).catch(Ne=>{F(Ne instanceof Error?Ne.message:"Failed to send input")}),me&&(V(null),K.current?.focus()))},[_,V,s]),q=i.useCallback((te,xe)=>{const me=Q.current;me&&s.resize({sessionId:me,cols:te,rows:xe}).catch(()=>{})},[s]),ue=i.useCallback(te=>{V(xe=>xe===te?null:te),K.current?.focus()},[V]),oe=i.useCallback(te=>{const xe=c0(te,_);xe&&(W(xe),V(null),K.current?.focus())},[_,W,V]);i.useEffect(()=>{if(!n||!_||!A)return;const te=xe=>{if(xe.repeat)return;const me=xe.key;if(!me||me==="Control"||me==="Meta"||me==="Alt"||me==="Shift")return;const Te=me.length===1?me.toLowerCase():me,Ne=xe.code??"",Be=Ne.startsWith("Key")&&Ne.length===4?Ne.slice(3).toUpperCase():null,fe=me.length===1&&/[a-zA-Z]/.test(me)?me.toUpperCase():Be,ht={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(Te in ht){xe.preventDefault(),xe.stopPropagation(),oe(ht[Te]);return}if(_==="ctrl"&&fe&&fe.length===1&&fe>="A"&&fe<="Z"){const bt=String.fromCharCode(fe.charCodeAt(0)&31);xe.preventDefault(),xe.stopPropagation(),W(bt),V(null),K.current?.focus()}};return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[_,oe,W,n,V,A]);const de=i.useMemo(()=>{const te=Xr[sa].stack;if(typeof window>"u")return(Xr[t]??Xr[sa]).stack;const me=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return me&&me.trim().length>0?me.trim():(Xr[t]??Xr[sa]).stack??te},[t]),je=i.useMemo(()=>r0(r),[r]),Se=i.useMemo(()=>`${p??"no-dir"}::${A??"pending"}`,[p,A]);i.useEffect(()=>{if(!X)return;const te=K.current;if(!te)return;const xe=()=>{te.fit()};if(typeof window<"u"){const me=window.requestAnimationFrame(()=>{xe(),te.focus()}),Te=[220,400].map(Ne=>window.setTimeout(xe,Ne));return()=>{window.cancelAnimationFrame(me),Te.forEach(Ne=>window.clearTimeout(Ne))}}xe()},[X,Se,A]);const Le=D?.includes("Reconnecting"),G=D?Le?e.jsx(Hh,{size:20,className:"text-amber-400"}):e.jsx(Gt,{size:20,className:"text-destructive"}):A&&!S&&!Y?e.jsx(Uo,{size:20,className:"text-emerald-400"}):S||Y?e.jsx(Li,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Li,{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:z,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const ee=!A||S||Y;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[G,e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:$,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(Bs,{size:16}),"Clear"]}),e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:z,disabled:Y,title:"Restart terminal session",type:"button",children:[e.jsx(Os,{size:16,className:R((S||Y)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(De,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>oe("esc"),disabled:ee,children:"Esc"}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("tab"),disabled:ee,children:[e.jsx(oc,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(De,{type:"button",size:"sm",variant:_==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ue("ctrl"),disabled:ee,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:_==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ue("cmd"),disabled:ee,children:[e.jsx(un,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-up"),disabled:ee,children:[e.jsx(po,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-left"),disabled:ee,children:[e.jsx(zu,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-down"),disabled:ee,children:[e.jsx($n,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-right"),disabled:ee,children:[e.jsx(oc,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("enter"),disabled:ee,children:[e.jsx(En,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:je.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:X?n?e.jsx(ol,{ref:te=>{K.current=te},sessionKey:Se,chunks:C,onInput:W,onResize:q,theme:je,fontFamily:de,fontSize:Ud,enableTouchScroll:o},Se):e.jsx(xt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(ol,{ref:te=>{K.current=te},sessionKey:Se,chunks:C,onInput:W,onResize:q,theme:je,fontFamily:de,fontSize:Ud,enableTouchScroll:o},Se)}):null}),D&&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:D}),E&&e.jsx(De,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:T,disabled:Y,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},u0=s=>s.slice().sort((r,t)=>r.type!==t.type?r.type==="directory"?-1:1:r.name.localeCompare(t.name)),Ar=s=>s.replace(/\\/g,"/"),m0=new Set(["node_modules"]),f0=s=>m0.has(s),p0=s=>{const r=Ar(s);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},h0=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=yt(),o=s?t.get(s)??void 0:void 0,l=r.find(c=>c.id===s)?.directory;return o?.path??l??n??""},g0=2e5,Vd=2e5,x0=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"]),y0=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"]),b0=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),v0=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),Gd=s=>{const r=s?.toLowerCase();return r&&x0.has(r)?e.jsx($s,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&y0.has(r)?e.jsx($s,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&b0.has(r)?e.jsx(hr,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&v0.has(r)?e.jsx(no,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(no,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},w0=()=>{const{files:s,runtime:r}=Nr(),{currentTheme:t}=Vr(),n=i.useMemo(()=>Vl(t),[t]),{isMobile:o}=Ht(),a=h0(),l=Ar(a),c=Ra(ve=>ve.searchFiles),[d,u]=i.useState(""),m=Ha(d,200),f=i.useRef(null),[p,h]=i.useState(!1),[y,g]=i.useState(o),[w,b]=i.useState(new Set),[v,j]=i.useState({}),k=i.useRef(new Set),x=i.useRef(new Set),[N,P]=i.useState([]),[C,M]=i.useState(!1),[S,A]=i.useState(null),[D,F]=i.useState(""),[E,I]=i.useState(!1),[_,V]=i.useState(null),[Y,H]=i.useState(""),[L,U]=i.useState(null),[Q,J]=i.useState(""),K=i.useRef(!1),ne=i.useRef(null),X=he(ve=>ve.sendMessage),ae=he(ve=>ve.currentSessionId),{currentProviderId:O,currentModelId:z,currentAgentName:T,currentVariant:$}=nt(),W=gt(ve=>ve.getSessionAgentSelection),q=gt(ve=>ve.getAgentModelForSession),ue=gt(ve=>ve.getAgentModelVariantForSession),oe=_e(ve=>ve.setActiveMainTab),{inputBarOffset:de,isKeyboardOpen:je}=_e(),Se=i.useCallback((ve,He)=>{if(He&&L){const Je=Math.min(L.start,ve),Qe=Math.max(L.end,ve);U({start:Je,end:Qe})}else U({start:ve,end:ve})},[L]),Le=i.useCallback((ve,He)=>{if(He.preventDefault(),He.shiftKey&&L){Se(ve,!0);return}K.current=!0,ne.current=ve,U({start:ve,end:ve})},[Se,L]),G=i.useCallback(ve=>{if(!K.current||ne.current===null)return;const He=Math.min(ne.current,ve),Je=Math.max(ne.current,ve);U({start:He,end:Je})},[]),ee=i.useCallback(()=>{K.current=!1},[]),te=i.useCallback(ve=>{if(L){const He=Math.min(L.start,L.end,ve),Je=Math.max(L.start,L.end,ve);if(ve<L.start||ve>L.end){U({start:He,end:Je});return}}U({start:ve,end:ve})},[L]);i.useEffect(()=>{const ve=()=>{K.current=!1};return document.addEventListener("mouseup",ve),()=>document.removeEventListener("mouseup",ve)},[]),i.useEffect(()=>{U(null),J("")},[S?.path]),i.useEffect(()=>{if(!L)return;const ve=Je=>{const Qe=Je.target;document.querySelector("[data-comment-ui]")?.contains(Qe)||Qe.closest("[data-line-number]")||Qe.closest("[data-sonner-toast]")||Qe.closest("[data-sonner-toaster]")||(U(null),J(""))},He=setTimeout(()=>{document.addEventListener("click",ve)},100);return()=>{clearTimeout(He),document.removeEventListener("click",ve)}},[L]);const xe=i.useCallback((ve,He)=>{const Je=ve.split(`
122
+ `),Qe=Math.max(1,He.start),ft=Math.min(Je.length,He.end);return Qe>ft?"":Je.slice(Qe-1,ft).join(`
123
+ `)},[]),me=i.useCallback(async()=>{if(!L||!Q.trim()||!S)return;if(!ae){Z.error("Select a session to send comment");return}const ve=W(ae)||T,He=ve?q(ae,ve):null,Je=He?.providerId||O,Qe=He?.modelId||z;if(!Je||!Qe){Z.error("Select a model to send comment");return}const ft=ve&&Je&&Qe?ue(ae,ve,Je,Qe)??$:$,it=xe(D,L),Pe=gr(S.path)||"text",ze=S.name,lt=L.start,Ke=L.end,wt=`Comment on \`${ze}\` lines ${lt}-${Ke}:
124
+ \`\`\`${Pe}
125
+ ${it}
126
+ \`\`\`
127
+
128
+ ${Q}`;J(""),U(null),oe("chat");try{await X(wt,Je,Qe,ve,void 0,void 0,void 0,ft)}catch(Pt){console.error("Failed to send comment",Pt)}},[L,Q,S,D,ae,O,z,T,$,xe,X,oe,W,q,ue]),Te=i.useCallback((ve,He)=>{const Je=He.filter(Qe=>Qe&&typeof Qe.name=="string"&&Qe.name.length>0).filter(Qe=>!Qe.name.startsWith(".")).filter(Qe=>!f0(Qe.name)).map(Qe=>{const ft=Qe.name,it=Ar(Qe.path||`${ve}/${ft}`),Pe=Qe.isDirectory?"directory":"file",ze=Pe==="file"&&ft.includes(".")?ft.split(".").pop()?.toLowerCase():void 0;return{name:ft,path:it,type:Pe,extension:ze}});return u0(Je)},[]),Ne=i.useCallback(async ve=>{const He=Ar(ve.trim());if(He&&!(k.current.has(He)||x.current.has(He))){x.current=new Set(x.current),x.current.add(He);try{let Je;r.isDesktop?Je=(await s.listDirectory(He,{respectGitignore:!0})).entries.map(it=>({name:it.name,path:it.path,isDirectory:it.isDirectory})):Je=(await Ee.listLocalDirectory(He,{respectGitignore:!0})).map(it=>({name:it.name,path:it.path,isDirectory:it.isDirectory}));const Qe=Te(He,Je);k.current=new Set(k.current),k.current.add(He),j(ft=>({...ft,[He]:Qe}))}catch{j(Je=>({...Je,[He]:Je[He]??[]}))}finally{x.current=new Set(x.current),x.current.delete(He)}}},[s,Te,r.isDesktop]),Be=i.useCallback(async()=>{const ve=Ar(a.trim());ve&&(k.current=new Set,x.current=new Set,b(new Set),j({}),await Ne(ve))},[a,Ne]);i.useEffect(()=>{a&&(Be(),A(null),F(""),V(null),H(""),h(!1))},[a,Be]);const fe=i.useCallback((ve,He)=>{const Je=ve.trim().toLowerCase();if(!Je)return 0;const Qe=He.toLowerCase();let ft=0,it=-1,Pe=0;for(let ze=0;ze<Je.length;ze+=1){const lt=Je[ze];if(!lt||lt===" ")continue;const Ke=Qe.indexOf(lt,it+1);if(Ke===-1)return null;const wt=Ke-it-1;if(wt===0?Pe+=1:Pe=0,ft+=10,ft+=Math.max(0,18-Ke),ft-=Math.max(0,wt),Ke===0)ft+=12;else{const Pt=Qe[Ke-1];(Pt==="/"||Pt==="_"||Pt==="-"||Pt==="."||Pt===" ")&&(ft+=10)}ft+=Pe>0?12:0,it=Ke}return ft+=Math.max(0,24-Math.round(Qe.length/3)),ft},[]);i.useEffect(()=>{if(!a){P([]),M(!1);return}const ve=m.trim();if(!ve){P([]),M(!1);return}const He=ve.toLowerCase();let Je=!1;return M(!0),c(a,ve,150).then(Qe=>{if(Je)return;const it=Qe.filter(ze=>!p0(ze.path)).map(ze=>{const lt=ze.relativePath||ze.name||ze.path,Ke=fe(He,lt);return Ke===null?null:{hit:ze,score:Ke,labelLength:lt.length}}).filter(Boolean);it.sort((ze,lt)=>lt.score-ze.score||ze.labelLength-lt.labelLength||ze.hit.path.localeCompare(lt.hit.path));const Pe=it.map(({hit:ze})=>({name:ze.name,path:Ar(ze.path),type:"file",extension:ze.extension,relativePath:ze.relativePath}));P(Pe)}).catch(()=>{Je||P([])}).finally(()=>{Je||M(!1)}),()=>{Je=!0}},[a,m,fe,c]);const ht=i.useCallback(async ve=>{if(s.readFile)return(await s.readFile(ve)).content??"";const He=await fetch(`/api/fs/read?path=${encodeURIComponent(ve)}`);if(!He.ok){const Je=await He.json().catch(()=>({error:He.statusText}));throw new Error(Je.error||"Failed to read file")}return He.text()},[s]),bt=i.useCallback(async ve=>{A(ve),V(null),H("");const He=mo(ve.path);o&&h(!0);const Je=ve.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&He&&!Je){F(""),I(!0);return}if(!r.isDesktop&&He&&!Je){F(""),I(!1);return}I(!0);try{const Qe=await ht(ve.path);F(Qe)}catch(Qe){F(""),V(Qe instanceof Error?Qe.message:"Failed to read file")}finally{I(!1)}},[o,ht,r.isDesktop]),Nt=i.useCallback(async ve=>{const He=Ar(ve);b(Je=>{const Qe=new Set(Je);return Qe.has(He)?Qe.delete(He):Qe.add(He),Qe}),k.current.has(He)||await Ne(He)},[Ne]),Me=i.useCallback((ve,He)=>(v[ve]??[]).map(Qe=>{const ft=Qe.type==="directory",it=ft&&w.has(Qe.path),Pe=S?.path===Qe.path,ze=ft&&x.current.has(Qe.path);return e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>{ft?Nt(Qe.path):bt(Qe)},className:R("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",Pe?"bg-accent/70":"hover:bg-accent/40"),style:{paddingLeft:`${8+He*12}px`},children:[ft?ze?e.jsx(ts,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):it?e.jsx(Uh,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(Vh,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Gd(Qe.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:Qe.path,children:Qe.name})]}),ft&&it&&e.jsx("ul",{className:"flex flex-col gap-1",children:Me(Qe.path,He+1)})]},Qe.path)}),[v,w,bt,S?.path,Nt]),re=S?.path&&gr(S.path)||"text",et=D.length>Vd?`${D.slice(0,Vd)}
129
+
130
+ … truncated …`:D,be=et.length<=g0,we=!!(S?.path&&mo(S.path)),Ve=!!(S?.path&&S.path.toLowerCase().endsWith(".svg")),tt=i.useMemo(()=>{if(!S?.path)return"";const ve=Ar(S.path);if(l&&ve.startsWith(l)){const He=ve.slice(l.length);return He.startsWith("/")?He.slice(1):He}return ve},[S?.path,l]),We=!!(S&&(!we||Ve)&&D.length>0),Oe=S?.path&&we?r.isDesktop?Ve?`data:${Ki(S.path)};utf8,${encodeURIComponent(D)}`:Y:Ve?`data:${Ki(S.path)};utf8,${encodeURIComponent(D)}`:`/api/fs/raw?path=${encodeURIComponent(S.path)}`:"",rt=i.useCallback(({rows:ve,stylesheet:He,useInlineStyles:Je})=>{const Qe=Math.max(3,String(ve.length).length+1);return e.jsx("div",{"data-code-viewer":!0,children:ve.map((ft,it)=>{const Pe=it+1,ze=L!==null&&Pe>=L.start&&Pe<=L.end;return e.jsxs("div",{"data-line-row":Pe,"data-selected":ze?"true":void 0,onMouseEnter:o?void 0:()=>G(Pe),style:{display:"flex",alignItems:"flex-start",lineHeight:"1.5rem",position:"relative",backgroundColor:ze?"color-mix(in srgb, var(--accent) 70%, transparent)":void 0},children:[e.jsx("span",{"data-line-number":Pe,onMouseDown:o?void 0:lt=>Le(Pe,lt),onMouseUp:o?void 0:ee,onClick:o?()=>te(Pe):void 0,style:{width:`calc(${Qe}ch + 0.75rem + 0.75rem)`,flexShrink:0,paddingLeft:"0.75rem",paddingRight:"1.75ch",textAlign:"right",color:"hsl(var(--muted-foreground))",opacity:.35,fontSize:"0.8em",lineHeight:"1.5rem",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:"pointer",touchAction:"manipulation"},children:Pe}),e.jsx("code",{style:{flex:1,minWidth:0,display:"block",whiteSpace:y?"pre-wrap":"pre",overflowWrap:y?"break-word":"normal",tabSize:2,paddingRight:"0.75rem",userSelect:L?"none":void 0,WebkitUserSelect:L?"none":void 0},children:Gh({node:ft,stylesheet:He,useInlineStyles:Je,key:it})})]},it)})})},[y,L,o,Le,G,ee,te]);i.useEffect(()=>{let ve=!1;return(async()=>{if(!r.isDesktop||!S?.path||!we||Ve){H("");return}V(null);try{if(s.readFileBinary){const it=await s.readFileBinary(S.path);ve||H(it.dataUrl);return}const Qe=(await ls(()=>import("./vendor-.bun-w0O-Y8Mh.js").then(it=>it.cA),__vite__mapDeps([0,1]))).convertFileSrc;if(!Qe)return;const ft=Qe(S.path,"asset");ve||H(ft)}catch(Je){ve||(H(""),V(Je instanceof Error?Je.message:"Failed to read file"))}finally{ve||I(!1)}})(),()=>{ve=!0}},[s,we,Ve,r.isDesktop,S?.path]);const vt=()=>!L||!S?null:e.jsx("div",{"data-comment-ui":!0,className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-background flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Ns,{value:Q,onChange:ve=>{J(ve.target.value);const He=ve.target;He.style.height="auto";const Qe=20*5+8;He.style.height=`${Math.min(He.scrollHeight,Qe)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!o,rows:1,onKeyDown:ve=>{ve.key==="Enter"&&(ve.metaKey||ve.ctrlKey)&&(ve.preventDefault(),me()),ve.key==="Escape"&&(ve.preventDefault(),U(null),J(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[S.name,":",L.start,"-",L.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!o&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[es(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:ve=>{Q.trim()&&(ve.preventDefault(),me())},onClick:()=>{o||me()},disabled:!Q.trim(),className:R("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",Q.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Ma,{className:"h-[18px] w-[18px]"})})]})]})]})}),mt=e.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[o&&p&&e.jsx("button",{type:"button",onClick:()=>h(!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(Wu,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:S?S.name:"Select a file"}),S&&!o&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:tt,children:tt})]}),e.jsxs("div",{className:"flex items-center gap-0",children:[S&&!we&&e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>g(!y),className:R("h-5 w-5 p-0 transition-opacity",y?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:y?"Disable line wrap":"Enable line wrap",children:e.jsx(Mu,{className:"size-4"})}),We&&e.jsxs(De,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(D),Z.success("Copied")}catch{Z.error("Copy failed")}},className:"gap-1",children:[e.jsx(Eu,{className:"h-4 w-4"}),"Copy"]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 relative",children:e.jsx(xt,{outerClassName:"h-full",className:"h-full",children:S?E?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):_?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:_}):we?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:Oe,alt:S?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):e.jsx("div",{className:"py-3",children:e.jsx(dr,{language:be?re:"text",style:n,PreTag:"div",renderer:rt,customStyle:{margin:0,padding:0,background:"transparent",fontSize:"var(--text-code)",lineHeight:"1.5rem",overflowX:"auto",overflowY:"visible",whiteSpace:"normal"},codeTagProps:{style:{fontStyle:"normal",lineHeight:"1.5rem"}},children:et},L?`${L.start}-${L.end}`:"none")}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),L&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:o?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:R("pointer-events-auto pb-2 transition-none w-full flex justify-center",o&&je?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:o&&!je&&de>0?`${de}px`:"16px"},"data-keyboard-avoid":"true",children:vt()})})]}),Tt=!!(l&&v[l]),Ot=e.jsxs("section",{className:R("flex min-h-0 flex-col overflow-hidden",o?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[e.jsxs("div",{className:R("flex items-center gap-2 py-2",o?"px-3":"px-2"),children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Xs,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(kt,{ref:f,value:d,onChange:ve=>u(ve.target.value),placeholder:"Search files…",className:"h-8 pl-8 pr-8 typography-meta"}),d.trim().length>0&&e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{u(""),f.current?.focus()},children:e.jsx(Gt,{className:"h-4 w-4"})})]}),e.jsx(De,{variant:"ghost",size:"sm",onClick:()=>{Be()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(Rr,{className:"h-4 w-4"})})]}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:R("py-2",o?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:C?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(ts,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):N.length>0?N.map(ve=>{const He=S?.path===ve.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{bt(ve)},className:R("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",He?"bg-accent/70":"hover:bg-accent/40"),children:[Gd(ve.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:ve.path,children:ve.relativePath??ve.path})]})},ve.path)}):Tt?Me(l,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading…"})})})]});return e.jsx("div",{className:"flex h-full min-h-0 overflow-hidden bg-background",children:o?p?mt:Ot:e.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[e.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:Ot}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:mt})]})})},Pf=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:dl},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:pr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:un},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:Lu},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:oo},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:_t},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:nn}],j0={},S0={},k0={};Pf.forEach(s=>{j0[s.id]=s.label,S0[s.id]=s.description,k0[s.id]=s});const N0=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",C0=s=>{if(!Array.isArray(s))return[];const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},qd=s=>{const r=C0(s);if(r.length===0)return;const t={};for(const l of r)l.permission&&((t[l.permission]||={})[l.pattern]=l.action);const n=t["*"]?.["*"],o=Object.keys(t);if(o.length===1&&o[0]==="*"&&Object.keys(t["*"]||{}).length===1&&t["*"]?.["*"])return t["*"]["*"];const a={};for(const l of o){const c=t[l],d=Object.keys(c);if(d.length===1&&d[0]==="*"&&l!=="*"){const u=c["*"],m=N0(l);if(n){if(u===n)continue}else if(u===m)continue;a[l]=u}else l==="*"&&d.length===1&&d[0]==="*"?a[l]=c["*"]:a[l]=c}return Object.keys(a).length>0?a:void 0},M0=({onItemSelect:s})=>{const[r,t]=i.useState(null),[n,o]=i.useState(""),{selectedAgentName:a,agents:l,setSelectedAgent:c,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=Hr(),{setSidebarOpen:p}=_e(),{isMobile:h}=Ht(),[y,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const b=y?"bg-transparent":w?"bg-background":"bg-sidebar",v=()=>{const D="new-agent";let F=D,E=1;for(;l.some(I=>I.name===F);)F=`${D}-${E}`,E++;d({name:F,scope:"user"}),c(F),s?.(),h&&p(!1)},j=async D=>{if(Jr(D)){Z.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${D.name}"?`)&&(await m(D.name)?Z.success(`Agent "${D.name}" deleted successfully`):Z.error("Failed to delete agent"))},k=async D=>{Jr(D)&&window.confirm(`Are you sure you want to reset agent "${D.name}" to its default configuration?`)&&(await m(D.name)?Z.success(`Agent "${D.name}" reset to default`):Z.error("Failed to reset agent"))},x=D=>{const F=D.name;let E=1,I=`${F}-copy`;for(;l.some(H=>H.name===I);)E++,I=`${F}-copy-${E}`;const _=D,V=D.model?.providerID&&D.model?.modelID?`${D.model.providerID}/${D.model.modelID}`:null,Y=D;d({name:I,scope:_.scope||"user",description:D.description,model:V,temperature:D.temperature,top_p:D.topP,prompt:D.prompt,mode:D.mode,permission:qd(D.permission),disable:Y.disable}),c(I),h&&p(!1)},N=D=>{o(D.name),t(D)},P=async()=>{if(!r)return;const D=n.trim().replace(/\s+/g,"-");if(!D){Z.error("Agent name is required");return}if(D===r.name){t(null);return}if(l.some(_=>_.name===D)){Z.error("An agent with this name already exists");return}const F=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,E=r;await u({name:D,description:r.description,model:F,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:qd(r.permission),disable:E.disable,scope:E.scope})?await m(r.name)?(Z.success(`Agent renamed to "${D}"`),c(D)):Z.error("Failed to remove old agent after rename"):Z.error("Failed to rename agent"),t(null)},C=D=>{switch(D){case"primary":return e.jsx(an,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Uu,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(Hu,{className:"h-3 w-3 text-primary"});default:return null}},M=l.filter(D=>!lm(D)),S=M.filter(Jr),A=M.filter(D=>!Jr(D));return e.jsxs("div",{className:R("flex h-full flex-col",b),children:[e.jsx("div",{className:R("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(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Zt,{className:"size-4"})})]})}),e.jsx(xt,{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(ao,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),S.map(D=>e.jsx(Kd,{agent:D,isSelected:a===D.name,onSelect:()=>{c(D.name),s?.(),h&&p(!1)},onReset:()=>k(D),onDuplicate:()=>x(D),getAgentModeIcon:C},D.name))]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Agents"}),A.map(D=>e.jsx(Kd,{agent:D,isSelected:a===D.name,onSelect:()=>{c(D.name),s?.(),h&&p(!1)},onRename:()=>N(D),onDelete:()=>j(D),onDuplicate:()=>x(D),getAgentModeIcon:C},D.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:D=>!D&&t(null),children:e.jsxs(ms,{children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Rename Agent"}),e.jsxs(vs,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(kt,{value:n,onChange:D=>o(D.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:D=>{D.key==="Enter"&&P()}}),e.jsxs(tr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(dn,{onClick:P,children:"Rename"})]})]})})]})},Kd=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:l,getAgentModeIcon:c})=>{const d=s;return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s.name}),c(s.mode),(d.scope||Jr(s))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:Jr(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(De,{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(Lr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(It,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(ho,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(It,{onClick:u=>{u.stopPropagation(),l()},children:[e.jsx(er,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(It,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Os,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(It,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Fs({className:s,variant:r,...t}){return e.jsx(De,{variant:r,size:"sm",className:R("h-6 px-2 text-xs",s),...t})}const D0=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),A0=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=D0.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Ua=({providerId:s,modelId:r,onChange:t,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:l}=nt(),c=_e(K=>K.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=_e(),{favoriteModelsList:f,recentModelsList:p}=zl(),{isMobile:h}=Ht(),y=c||h,[g,w]=i.useState(!1),[b,v]=i.useState(new Set),[j,k]=i.useState(!1),[x,N]=i.useState(""),[P,C]=i.useState(0),M=i.useRef([]),S=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),A=i.useMemo(()=>S?a.filter(K=>S.has(String(K.id))):a,[a,S]),D=()=>w(!1),F=K=>{v(ne=>{const X=new Set(ne);return X.has(K)?X.delete(K):X.add(K),X})};i.useEffect(()=>{j||(N(""),C(0))},[j]),i.useEffect(()=>{C(0)},[x]);const E=K=>{const ne=K?.name||K?.id||"",X=String(ne);return X.length>40?X.substring(0,37)+"...":X},I=(K,ne)=>{const X=`${K}/${ne}`;return l.get(X)},_=(K,ne)=>{t(K,ne),K&&ne&&m(K,ne),k(!1)},V=(K,ne)=>{if(!x.trim())return!0;const X=x.toLowerCase();return K.toLowerCase().includes(X)||ne.toLowerCase().includes(X)},Y=(K,ne,X,ae,O,z)=>{const T=I(ne,X),$=A0(T?.limit?.context),W=s===ne&&r===X,q=u(ne,X);return e.jsxs("div",{ref:ue=>{M.current[O]=ue},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",z?"bg-accent":"hover:bg-accent/50"),onClick:()=>_(ne,X),onMouseEnter:()=>C(O),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:E(K)}),$?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:$}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[W&&e.jsx(Bt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),d(ne,X)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",q?"text-yellow-500":"text-muted-foreground"),"aria-label":q?"Unfavorite":"Favorite",title:q?"Remove from favorites":"Add to favorites",children:q?e.jsx(vr,{className:"h-3.5 w-3.5"}):e.jsx(kn,{className:"h-3.5 w-3.5"})})]})]},`${ae}-${ne}-${X}`)},H=f.filter(({model:K,providerID:ne})=>{if(S&&!S.has(ne))return!1;const ae=a.find(z=>z.id===ne)?.name||ne,O=E(K);return V(O,ae)}),L=p.filter(({model:K,providerID:ne})=>{if(S&&!S.has(ne))return!1;const ae=a.find(z=>z.id===ne)?.name||ne,O=E(K);return V(O,ae)}),U=A.map(K=>{const X=(Array.isArray(K.models)?K.models:[]).filter(ae=>{const O=E(ae);return V(O,K.name||K.id||"")});return{...K,models:X}}).filter(K=>K.models.length>0),Q=H.length>0||L.length>0||U.length>0,J=()=>y?e.jsx(js,{open:g,onClose:D,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:K,providerID:ne,modelID:X})=>{const ae=ne===s&&X===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ae?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{_(ne,X),D()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{providerId:ne,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:E(K)})]})}),e.jsx("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),d(ne,X)},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(vr,{className:"h-4 w-4"})})]},`fav-mobile-${ne}-${X}`)})})]}),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:K,providerID:ne,modelID:X})=>{const ae=ne===s&&X===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ae?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{_(ne,X),D()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{providerId:ne,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:E(K)})]})}),e.jsx("button",{onClick:O=>{O.preventDefault(),O.stopPropagation(),d(ne,X)},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(kn,{className:"h-4 w-4"})})]},`recent-mobile-${ne}-${X}`)})})]}),A.map(K=>{const ne=Array.isArray(K.models)?K.models:[];if(ne.length===0)return null;const X=K.id===s,ae=b.has(K.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:()=>F(K.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ds,{providerId:K.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:K.name}),X&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),ae?e.jsx(Ft,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Is,{className:"h-3 w-3 text-muted-foreground"})]}),ae&&e.jsx("div",{className:"border-t border-border/20",children:ne.map(O=>{const z=K.id===s&&O.id===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",z?"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:()=>{_(K.id,O.id),D()},children:e.jsx("span",{className:"font-medium truncate",children:E(O)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:T=>{T.preventDefault(),T.stopPropagation(),d(K.id,O.id)},className:R("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(K.id,O.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(K.id,O.id)?"Unfavorite":"Favorite",children:u(K.id,O.id)?e.jsx(vr,{className:"h-4 w-4"}):e.jsx(kn,{className:"h-4 w-4"})}),z&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},O.id)})})]},K.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:()=>{_("",""),D()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[y?e.jsxs("button",{type:"button",onClick:()=>w(!0),className:R("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[s?e.jsx(ds,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(br,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s&&r?`${s}/${r}`:"Select model..."})]}),e.jsx(Ft,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Yt,{open:j,onOpenChange:k,children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",n),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(ds,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(br,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(br,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s&&r?`${s}/${r}`:"Not selected"}),e.jsx(Ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Jt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const K=[];H.forEach(({model:O,providerID:z,modelID:T})=>{K.push({model:O,providerID:z,modelID:T,section:"fav"})}),L.forEach(({model:O,providerID:z,modelID:T})=>{K.push({model:O,providerID:z,modelID:T,section:"recent"})}),U.forEach(O=>{O.models.forEach(z=>{K.push({model:z,providerID:O.id,modelID:z.id,section:"provider"})})});const ne=K.length,X=O=>{if(O.key==="ArrowDown"){O.preventDefault(),O.stopPropagation();const z=(P+1)%Math.max(1,ne);C(z),setTimeout(()=>{M.current[z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(O.key==="ArrowUp"){O.preventDefault(),O.stopPropagation();const z=(P-1+Math.max(1,ne))%Math.max(1,ne);C(z),setTimeout(()=>{M.current[z]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(O.key==="Enter"){O.preventDefault(),O.stopPropagation();const z=K[P];z&&_(z.providerID,z.modelID)}else O.key==="Escape"&&(O.preventDefault(),O.stopPropagation(),k(!1))};let ae=0;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(Xs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{type:"text",placeholder:"Search models",value:x,onChange:O=>N(O.target.value),onKeyDown:X,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(xt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:R("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>_("",""),children:[e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!s&&!r&&e.jsx(Bt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ss,{}),!Q&&x&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),H.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(vr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),H.map(({model:O,providerID:z,modelID:T})=>{const $=ae++;return Y(O,z,T,"fav",$,P===$)})]}),L.length>0&&e.jsxs(e.Fragment,{children:[H.length>0&&e.jsx(Ss,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4"}),"Recent"]}),L.map(({model:O,providerID:z,modelID:T})=>{const $=ae++;return Y(O,z,T,"recent",$,P===$)})]}),(H.length>0||L.length>0)&&U.length>0&&e.jsx(Ss,{}),U.map((O,z)=>e.jsxs(i.Fragment,{children:[z>0&&e.jsx(Ss,{}),e.jsxs(Pr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ds,{providerId:O.id,className:"h-4 w-4 flex-shrink-0"}),O.name]}),O.models.map(T=>{const $=ae++;return Y(T,O.id,T.id,"provider",$,P===$)})]},O.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"})]})})()})]}),J()]})},E0=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],Sr=s=>s==="allow"||s==="ask"||s==="deny",I0=s=>{if(Sr(s))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const r=s["*"];if(Sr(r))return r}},P0=s=>{if(Sr(s))return{entries:{"*":s}};if(!s||typeof s!="object"||Array.isArray(s))return{entries:{}};const r={};for(const[t,n]of Object.entries(s)){const o=I0(n);o!==void 0&&(r[t]=o)}return{entries:r}},T0=s=>{const r={...s},t=r["*"];return Sr(t)?(delete r["*"],{defaultOverride:t,overrides:r}):{defaultOverride:"default",overrides:r}},Va=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",ra=(s,r)=>r==="default"?Va(s):r,Qd=(s,r)=>{const t={...s};for(const[n,o]of Object.entries(s)){if(n==="*")continue;const a=ra(n,r),l=Va(n);if(!(Sr(o)&&o!==l)){if(Sr(o)&&o===a){delete t[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const c=o,d=Object.keys(c),u=c["*"];if(u!==void 0&&u!==l)continue;d.length===1&&d[0]==="*"&&u===a&&delete t[n]}}}return t},Tf=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},F0=s=>{const r=Tf(s);if(!r||r.length===0)return{entries:{}};const t={};for(const a of r)!a.permission||a.permission==="invalid"||a.pattern==="*"&&(t[a.permission]=a.action);const n=t["*"],o={};for(const[a,l]of Object.entries(t)){if(a==="*"){o[a]=l;continue}const c=Va(a);if(n){if(l===n)continue}else if(l===c)continue;o[a]=l}return{entries:o}},R0=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:l}=Hr();nt();const c=s?r(s):null,d=!!(a&&a.name===s&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,y]=i.useState(""),[g,w]=i.useState("subagent"),[b,v]=i.useState(""),[j,k]=i.useState(void 0),[x,N]=i.useState(void 0),[P,C]=i.useState(""),[M,S]=i.useState("default"),[A,D]=i.useState({}),[F,E]=i.useState(""),[I,_]=i.useState(!1),V=yt($=>$.currentDirectory??null),[Y,H]=i.useState([]),L=uo($=>$.permissions);i.useEffect(()=>{let $=!1;return(async()=>{const q=await Ee.listToolIds({directory:V});if($)return;const ue=new Set(["write","patch","multiedit"]),oe=q.map(de=>typeof de=="string"?de.trim():"").filter(Boolean).filter(de=>de!=="*").filter(de=>de!=="invalid").filter(de=>!ue.has(de));H(Array.from(new Set(oe)).sort((de,je)=>de.localeCompare(je)))})(),()=>{$=!0}},[V]);const U=i.useMemo(()=>{const $=new Set;for(const W of o){const q=Tf(W.permission);if(q)for(const ue of q)ue.permission&&ue.permission!=="*"&&ue.permission!=="invalid"&&$.add(ue.permission)}for(const W of L.values())for(const q of W){const ue=q.permission?.trim();ue&&ue!=="invalid"&&$.add(ue)}for(const W of Y)$.add(W);return Array.from($).sort((W,q)=>W.localeCompare(q))},[o,L,Y]),Q=i.useCallback($=>{const W=A[$];if(Sr(W))return W;if(W&&typeof W=="object"&&!Array.isArray(W)){const q=W["*"];if(Sr(q))return q}},[A]),J=i.useCallback($=>{const W=A[$];return!W||typeof W!="object"||Array.isArray(W)?0:Object.keys(W).filter(ue=>ue!=="*").length},[A]),K=i.useCallback(($,W)=>{$!=="*"&&D(q=>{const ue={...q},oe=ue[$],de=ra($,M),je=Va($),Se=W===de&&W===je;if(oe&&typeof oe=="object"&&!Array.isArray(oe)){const Le={...oe};Le["*"]=W;const G=Object.keys(Le).filter(ee=>ee!=="*");return Se&&G.length===0?(delete ue[$],ue):(ue[$]=Le,ue)}return Se?(delete ue[$],ue):(ue[$]=W,ue)})},[M]),ne=i.useCallback($=>{D(W=>{if(!($ in W))return W;const q={...W};return delete q[$],q})},[]),X=i.useMemo(()=>{const $=Object.entries(A).filter(([W])=>W!=="*");return $.sort(([W],[q])=>W.localeCompare(q)),$},[A]),ae=i.useMemo(()=>{const $=new Set;for(const W of E0)$.add(W);for(const W of U)$.add(W);for(const W of Object.keys(A))$.delete(W);return Array.from($).sort((W,q)=>W.localeCompare(q))},[U,A]),O=i.useCallback($=>{const W=F.trim();if(!W)return;const q=ra(W,M);if($===q){const ue=M==="default"?"OpenCode defaults":`Default Permissions ("${M}")`;Z.message(`"${W}" already matches ${ue} (${q}).`),E("");return}K(W,$),E("")},[F,K,M]),z=i.useCallback($=>$==="webfetch"?"WebFetch":$==="websearch"?"WebSearch":$==="codesearch"?"CodeSearch":$==="doom_loop"?"Doom Loop":$==="external_directory"?"External Directory":$==="todowrite"?"TodoWrite":$==="todoread"?"TodoRead":$.split(/[_-]+/g).filter(Boolean).map(W=>W.charAt(0).toUpperCase()+W.slice(1)).join(" "),[]);i.useEffect(()=>{E("");const $=W=>{const q=T0(W);S(q.defaultOverride),D(Qd(q.overrides,q.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),y(a.description||""),w(a.mode||"subagent"),v(a.model||""),k(a.temperature),N(a.top_p),C(a.prompt||"");const W=P0(a.permission);$(W.entries);return}if(c&&s===c.name){y(c.description||""),w(c.mode||"subagent"),c.model?.providerID&&c.model?.modelID?v(`${c.model.providerID}/${c.model.modelID}`):v(""),k(c.temperature),N(c.topP),C(c.prompt||"");const W=F0(c.permission);$(W.entries)}},[a,d,c,s]);const T=async()=>{const $=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!$){Z.error("Agent name is required");return}if(d&&o.some(W=>W.name===$)){Z.error("An agent with this name already exists");return}_(!0);try{const W=b.trim(),q={name:$,description:h.trim()||void 0,mode:g,model:W===""?null:W,temperature:j,top_p:x,prompt:P.trim()||void 0,permission:(()=>{const oe=Qd(A,M),de=M==="default"?oe:{"*":M,...oe},je=["doom_loop","external_directory"];for(const Le of je)if(!(Le in de)){const G=A[Le];Sr(G)?de[Le]=G:de[Le]=ra(Le,M)}return Object.keys(de).length===0?d?void 0:null:de})(),scope:d?f:void 0};let ue;d?(ue=await t(q),ue&&l(null)):ue=await n($,q),ue?Z.success(d?"Agent created successfully":"Agent updated successfully"):Z.error(d?"Failed to create agent":"Failed to update agent")}catch(W){console.error("Error saving agent:",W);const q=W instanceof Error&&W.message?W.message:"An error occurred while saving";Z.error(q)}finally{_(!1)}};return s?e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Agent":s})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"@"}),e.jsx(kt,{value:u,onChange:$=>m($.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Cs,{value:f,onValueChange:$=>p($),children:[e.jsxs(Ms,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ls,{className:"h-4 w-4"}):e.jsx(Js,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Ds,{align:"end",children:[e.jsx(qt,{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(Ls,{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(qt,{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(Js,{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(Ns,{value:h,onChange:$=>y($.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(Fs,{variant:g==="primary"?"default":"outline",onClick:()=>w("primary"),className:R("gap-2",g==="primary"?void 0:"text-foreground"),children:[e.jsx(an,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Fs,{variant:g==="subagent"?"default":"outline",onClick:()=>w("subagent"),className:R("gap-2",g==="subagent"?void 0:"text-foreground"),children:[e.jsx(Hu,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Fs,{variant:g==="all"?"default":"outline",onClick:()=>w("all"),className:R("gap-2",g==="all"?void 0:"text-foreground"),children:[e.jsx(Uu,{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(Ua,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:($,W)=>{v($&&W?`${$}/${W}`:"")}})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Temperature",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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 W=Math.max(0,(j!==void 0?j:.7)-.1);k(parseFloat(W.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(Xa,{className:"h-3.5 w-3.5"})}),e.jsx(kt,{type:"text",inputMode:"decimal",value:j!==void 0?j:"",onChange:$=>{const W=$.target.value;if(W===""){k(void 0);return}const q=parseFloat(W);!isNaN(q)&&q>=0&&q<=2&&k(q)},onBlur:$=>{const W=$.target.value;if(W!==""){const q=parseFloat(W);if(!isNaN(q)){const ue=Math.max(0,Math.min(2,q));k(parseFloat(ue.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 W=Math.min(2,(j!==void 0?j:.7)+.1);k(parseFloat(W.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(Zt,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Top P",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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 W=Math.max(0,(x!==void 0?x:.9)-.1);N(parseFloat(W.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(Xa,{className:"h-3.5 w-3.5"})}),e.jsx(kt,{type:"text",inputMode:"decimal",value:x!==void 0?x:"",onChange:$=>{const W=$.target.value;if(W===""){N(void 0);return}const q=parseFloat(W);!isNaN(q)&&q>=0&&q<=1&&N(q)},onBlur:$=>{const W=$.target.value;if(W!==""){const q=parseFloat(W);if(!isNaN(q)){const ue=Math.max(0,Math.min(1,q));N(parseFloat(ue.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 W=Math.min(1,(x!==void 0?x:.9)+.1);N(parseFloat(W.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(Zt,{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(Ns,{value:P,onChange:$=>C($.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(De,{size:"sm",variant:M==="default"?"default":"outline",onClick:()=>S("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(De,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>S("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>S("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:M==="deny"?"default":"outline",onClick:()=>S("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:M==="default"?"Uses OpenCode defaults unless overridden below.":"Applies to any permission without an explicit override below."}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{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(Cs,{value:F,onValueChange:E,children:[e.jsx(Ms,{className:"h-8 w-full sm:w-72",children:F?e.jsx("span",{className:"truncate",children:z(F)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(Ds,{children:ae.map($=>e.jsx(qt,{value:$,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:z($)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:$})]})},$))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:"outline",disabled:!F,onClick:()=>O("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:"outline",disabled:!F,onClick:()=>O("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:"outline",disabled:!F,onClick:()=>O("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),X.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:X.map(([$])=>{const W=Q($),q=J($),ue=z($);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:ue}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:$}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block this operation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Remove:"})," Return to default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Note:"}),' Buttons set the "*" rule only']}),q>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",q," pattern rules preserved"]}):null]})})]})]}),e.jsxs(De,{size:"sm",variant:"outline",onClick:()=>ne($),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(Xa,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:W==="allow"?"default":"outline",onClick:()=>K($,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:W==="ask"?"default":"outline",onClick:()=>K($,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:W==="deny"?"default":"outline",onClick:()=>K($,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},$)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(De,{size:"sm",variant:"default",onClick:T,disabled:I,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Pa,{className:"h-3 w-3"}),I?"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(ao,{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"})]})})},O0=({onItemSelect:s})=>{const[r,t]=i.useState(null),[n,o]=i.useState(""),{selectedCommandName:a,commands:l,setSelectedCommand:c,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=Wr(),{setSidebarOpen:p}=_e(),{isMobile:h}=Ht(),[y,g]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const b=y?"bg-transparent":w?"bg-background":"bg-sidebar",v=()=>{const S="new-command";let A=S,D=1;for(;l.some(F=>F.name===A);)A=`${S}-${D}`,D++;d({name:A,scope:"user"}),c(A),s?.(),h&&p(!1)},j=async S=>{if(wn(S)){Z.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${S.name}"?`)&&(await m(S.name)?Z.success(`Command "${S.name}" deleted successfully`):Z.error("Failed to delete command"))},k=async S=>{wn(S)&&window.confirm(`Are you sure you want to reset command "${S.name}" to its default configuration?`)&&(await m(S.name)?Z.success(`Command "${S.name}" reset to default`):Z.error("Failed to reset command"))},x=S=>{const A=S.name;let D=1,F=`${A}-copy`;for(;l.some(E=>E.name===F);)D++,F=`${A}-copy-${D}`;d({name:F,scope:S.scope||"user",description:S.description,template:S.template,agent:S.agent,model:S.model,subtask:S.subtask}),c(F),h&&p(!1)},N=S=>{o(S.name),t(S)},P=async()=>{if(!r)return;const S=n.trim().replace(/\s+/g,"-");if(!S){Z.error("Command name is required");return}if(S===r.name){t(null);return}if(l.some(D=>D.name===S)){Z.error("A command with this name already exists");return}await u({name:S,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(Z.success(`Command renamed to "${S}"`),c(S)):Z.error("Failed to remove old command after rename"):Z.error("Failed to rename command"),t(null)},C=l.filter(wn),M=l.filter(S=>!wn(S));return e.jsxs("div",{className:R("flex h-full flex-col",b),children:[e.jsx("div",{className:R("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",l.length]}),e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Zt,{className:"size-4"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx($r,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No commands configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[C.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Commands"}),[...C].sort((S,A)=>S.name.localeCompare(A.name)).map(S=>e.jsx(Yd,{command:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),h&&p(!1)},onReset:()=>k(S),onDuplicate:()=>x(S)},S.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Commands"}),[...M].sort((S,A)=>S.name.localeCompare(A.name)).map(S=>e.jsx(Yd,{command:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),h&&p(!1)},onRename:()=>N(S),onDelete:()=>j(S),onDuplicate:()=>x(S)},S.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:S=>!S&&t(null),children:e.jsxs(ms,{children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Rename Command"}),e.jsxs(vs,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(kt,{value:n,onChange:S=>o(S.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&P()}}),e.jsxs(tr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(dn,{onClick:P,children:"Rename"})]})]})})]})},Yd=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:l})=>e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["/",s.name]}),(s.scope||wn(s))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:wn(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(De,{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(Lr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(It,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(ho,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(It,{onClick:c=>{c.stopPropagation(),l()},children:[e.jsx(er,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(It,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(Os,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(It,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),Ff=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=Hr(),a=o(),l=_e(y=>y.isMobile),{isMobile:c}=Ht(),d=l||c,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=y=>{r(y)},h=()=>d?e.jsx(js,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(y=>{const g=y.name===s;return e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",g?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(y.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:y.name}),y.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:y.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},y.name)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{p(""),f()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No agent (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[d?e.jsxs("button",{type:"button",onClick:()=>m(!0),className:R("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ao,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s||"Select agent..."})]}),e.jsx(Ft,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",t),children:[e.jsx(ao,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s||"Not selected"}),e.jsx(Ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Jt,{className:"max-w-[300px]",children:[a.map(y=>e.jsx(It,{className:"typography-meta",onSelect:()=>p(y.name),children:e.jsx("span",{className:"font-medium",children:y.name})},y.name)),e.jsx(It,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},_0=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:l}=Wr(),c=s?r(s):null,d=!!(a&&a.name===s&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[h,y]=i.useState(""),[g,w]=i.useState(""),[b,v]=i.useState(""),[j,k]=i.useState(""),[x,N]=i.useState(!1),[P,C]=i.useState(!1);i.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),y(a.description||""),w(a.agent||""),v(a.model||""),k(a.template||""),N(a.subtask||!1)):c&&(y(c.description||""),w(c.agent||""),v(c.model||""),k(c.template||""),N(c.subtask||!1))},[c,d,s,o,a]);const M=async()=>{const S=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!S){Z.error("Command name is required");return}if(!j.trim()){Z.error("Command template is required");return}if(d&&o.some(A=>A.name===S)){Z.error("A command with this name already exists");return}C(!0);try{const A=g.trim(),D=b.trim(),F=j.trim(),E={name:S,description:h.trim()||void 0,agent:A===""?null:A,model:D===""?null:D,template:F,subtask:x,scope:d?f:void 0};let I;d?(I=await t(E),I&&l(null)):I=await n(S,E),I?Z.success(d?"Command created successfully":"Command updated successfully"):Z.error(d?"Failed to create command":"Failed to update command")}catch(A){console.error("Error saving command:",A),Z.error("An error occurred while saving")}finally{C(!1)}};return s?e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Command":`/${s}`})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"/"}),e.jsx(kt,{value:u,onChange:S=>m(S.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Cs,{value:f,onValueChange:S=>p(S),children:[e.jsxs(Ms,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ls,{className:"h-4 w-4"}):e.jsx(Js,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Ds,{align:"end",children:[e.jsx(qt,{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(Ls,{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(qt,{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(Js,{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(Ns,{value:h,onChange:S=>y(S.target.value),placeholder:"What does this command do?",rows:3})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model & Agent Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and agent for command execution"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(Ff,{agentName:g,onChange:S=>w(S)}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Agent to execute this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(Ua,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:(S,A)=>{v(S&&A?`${S}/${A}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:S=>N(S.target.checked),className:"sr-only"}),e.jsx("div",{className:R("w-5 h-5 rounded border-2 flex items-center justify-center",x?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:x&&e.jsx(Bt,{className:"w-3 h-3 text-primary-foreground"})})]}),"Force Subagent Invocation"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Force command to run in a subagent context"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(Ns,{value:j,onChange:S=>k(S.target.value),placeholder:`Your command template here...
131
+
132
+ Use $ARGUMENTS to reference user input.
133
+ Use !\`shell command\` to inject shell output.
134
+ Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Replaced with everything the user types after the command name.",e.jsx("br",{}),'Example: "/deploy staging" makes $ARGUMENTS = "staging"']})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"!`command`"}),e.jsx("span",{children:"- Inject shell command output"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Executes shell command and replaces this placeholder with its output.",e.jsx("br",{}),"Example: !`git branch --show-current` gets current branch name"]})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"@filename"}),e.jsx("span",{children:"- Include file contents"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(De,{size:"sm",variant:"default",onClick:M,disabled:P,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Pa,{className:"h-3 w-3"}),P?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx($r,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a command from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})},$0=({onItemSelect:s})=>{const[r,t]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:l,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=Qs(),{setSidebarOpen:h}=_e(),{isMobile:y}=Ht(),[g,w]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||w(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const v=g?"bg-transparent":b?"bg-background":"bg-sidebar",j=()=>{const S="new-skill";let A=S,D=1;for(;l.some(F=>F.name===A);)A=`${S}-${D}`,D++;d({name:A,scope:"user",description:""}),c(A),s?.(),y&&h(!1)},k=async S=>{window.confirm(`Are you sure you want to delete skill "${S.name}"?`)&&(await m(S.name)?Z.success(`Skill "${S.name}" deleted successfully`):Z.error("Failed to delete skill"))},x=async S=>{const A=S.name;let D=1,F=`${A}-copy`;for(;l.some(I=>I.name===F);)D++,F=`${A}-copy-${D}`;const E=await p(S.name);if(!E){Z.error("Failed to load skill details for duplication");return}d({name:F,scope:S.scope||"user",description:(E.sources.md.fields.includes("description"),""),instructions:""}),c(F),y&&h(!1)},N=S=>{o(S.name),t(S)},P=async()=>{if(!r)return;const S=n.trim().replace(/\s+/g,"-").toLowerCase();if(!S){Z.error("Skill name is required");return}if(S===r.name){t(null);return}if(l.some(F=>F.name===S)){Z.error("A skill with this name already exists");return}if(!await p(r.name)){Z.error("Failed to load skill details"),t(null);return}await u({name:S,description:"Renamed skill",scope:r.scope})?await m(r.name)?(Z.success(`Skill renamed to "${S}"`),c(S)):Z.error("Failed to remove old skill after rename"):Z.error("Failed to rename skill"),t(null)},C=l.filter(S=>S.scope==="project"),M=l.filter(S=>S.scope==="user");return e.jsxs("div",{className:R("flex h-full flex-col",v),children:[e.jsx("div",{className:R("border-b px-3",y?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",l.length]}),e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:j,children:e.jsx(Zt,{className:"size-4"})})]})}),e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Vu,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No skills configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[C.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Project Skills"}),C.map(S=>e.jsx(Xd,{skill:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),y&&h(!1)},onRename:()=>N(S),onDelete:()=>k(S),onDuplicate:()=>x(S)},S.name))]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"User Skills"}),M.map(S=>e.jsx(Xd,{skill:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),y&&h(!1)},onRename:()=>N(S),onDelete:()=>k(S),onDuplicate:()=>x(S)},S.name))]})]})}),e.jsx(us,{open:r!==null,onOpenChange:S=>!S&&t(null),children:e.jsxs(ms,{children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Rename Skill"}),e.jsxs(vs,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(kt,{value:n,onChange:S=>o(S.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&P()}}),e.jsxs(tr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(dn,{onClick:P,children:"Rename"})]})]})})]})},Xd=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsx("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:s.scope}),s.source==="claude"&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"claude"})]})}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(De,{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(Lr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(It,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(ho,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(It,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(er,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(It,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function Rf({tabs:s,value:r,onValueChange:t,className:n,isInteractive:o=!0,animate:a=!0}){const l=i.useRef(null),c=i.useRef(null),d=i.useCallback(()=>{const u=l.current,m=c.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:h}=m,y=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(y).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{d()},[d,r,s.length]),i.useEffect(()=>{const u=l.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:R("relative isolate w-full",n),children:[e.jsx("div",{ref:l,"aria-hidden":!0,className:R("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children:s.map(u=>{const m=u.icon;return e.jsxs("div",{className:"flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold",children:[m?e.jsx(m,{className:"h-4 w-4"}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})}),e.jsx("div",{className:"relative z-20 flex h-9 items-center gap-1 rounded-lg bg-muted/20 px-1.5",children:s.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?c:null,type:"button",onClick:()=>{o&&t(u.value)},className:R("flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold transition-colors duration-150",m?"text-accent-foreground":"text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-pressed":m,"aria-disabled":!o,tabIndex:o?0:-1,children:[f?e.jsx(f,{className:R("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const L0=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,B0=s=>{const r=s.trim(),t=r.match(/^git@github\.com:([^/\s]+)\/([^\s#]+)$/i);if(t)return`${t[1]}/${t[2].replace(/\.git$/i,"")}`;const n=r.match(/^https?:\/\/github\.com\/([^/\s]+)\/([^\s#]+)$/i);if(n)return`${n[1]}/${n[2].replace(/\.git$/i,"")}`;const o=r.match(/^([^/\s]+)\/([^/\s]+)(?:\/.+)?$/);return o?`${o[1]}/${o[2].replace(/\.git$/i,"")}`:r},z0=async()=>{try{if(os())return await zr();const s=Zs()?.settings;if(s)return(await s.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},W0=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=go(),a=Rn(S=>S.defaultGitIdentityId),l=Rn(S=>S.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[h,y]=i.useState([]),[g,w]=i.useState(null),[b,v]=i.useState(!1),[j,k]=i.useState([]),[x,N]=i.useState(null);i.useEffect(()=>{s&&(d(""),m(""),p(""),w(null),v(!1),k([]),N(null),l(),(async()=>{const S=await z0(),A=Array.isArray(S?.skillCatalogs)?S?.skillCatalogs:[];y(A||[])})())},[s,l]);const P=i.useMemo(()=>{const S=u.trim(),A=f.trim();return h.some(D=>{const F=(D.source||"").trim(),E=(D.subpath||"").trim();return F===S&&E===A})},[h,u,f]),C=async()=>{const S=u.trim();if(!S){Z.error("Repository source is required");return}c.trim()||d(B0(S)),v(!1),w(null);const A=await t({source:S,subpath:f.trim()||void 0,gitIdentityId:x||void 0});if(!A.ok){if(A.error?.kind==="authRequired"){if(zt()){Z.error("Private repositories are not supported in VS Code yet");return}const F=A.error.identities||[];if(k(F),!x&&F.length>0){const E=a&&a!=="global"&&F.some(I=>I.id===a)?a:F[0].id;N(E)}Z.error("Authentication required. Select a Git identity and scan again.");return}Z.error(A.error?.message||"Failed to scan repository");return}const D=A.items?.length||0;if(w(D),D===0){Z.error("No skills found in this repository"),v(!1);return}k([]),v(!0),Z.success(`Found ${D} skill(s)`)},M=async()=>{const S=c.trim(),A=u.trim(),D=f.trim();if(!S){Z.error("Catalog name is required");return}if(!A){Z.error("Repository source is required");return}if(!b){Z.error("Scan the repository before adding this catalog");return}if(P){Z.error("This catalog already exists");return}const F={id:L0(),label:S,source:A,...D?{subpath:D}:{},...x?{gitIdentityId:x}:{}},E=[...h,F];try{await ns({skillCatalogs:E}),y(E),Z.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(I){Z.error(I instanceof Error?I.message:"Failed to save catalog")}};return e.jsx(us,{open:s,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Add skills catalog"}),e.jsxs(vs,{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(kt,{value:c,onChange:S=>d(S.target.value),placeholder:"e.g. Team Skills"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Repository"}),e.jsx(kt,{value:u,onChange:S=>{m(S.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(kt,{value:f,onChange:S=>{p(S.target.value),v(!1),w(null)},placeholder:"e.g. skills"})]}),j.length>0&&!zt()?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(Cs,{value:x||"",onValueChange:S=>N(S),children:[e.jsx(Ms,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:j.find(S=>S.id===x)?.name||"Choose identity"})}),e.jsx(Ds,{align:"start",children:j.map(S=>e.jsx(qt,{value:S.id,className:"pr-2 [&>span:first-child]:hidden",children:S.name},S.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,g!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",g," skill(s) found"]}):null,P?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(tr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(De,{variant:"outline",onClick:()=>{C()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(Fu,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(De,{variant:"default",onClick:()=>{M()},disabled:!b||P||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},H0=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=i.useState({});i.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const l=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},c=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(us,{open:s,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-2xl",children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Skills already exist"}),e.jsx(vs,{children:"Some selected skills are already installed in this scope. Choose whether to skip or overwrite them."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[t.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(De,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(De,{variant:"outline",size:"sm",onClick:()=>l("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:t.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label truncate",children:d.skillName}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Installed in ",d.scope," scope"]})]}),e.jsxs(Cs,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Ms,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Ds,{align:"end",children:[e.jsx(qt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(qt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(tr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(dn,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},U0=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=go(),[a,l]=i.useState("user"),[c,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{s&&(l("user"),d(!1),m([]),p(null))},[s]);const h=async y=>{const g={skillDir:y.skillDir};t?.clawdhub&&(g.clawdhub={slug:t.clawdhub.slug,version:t.clawdhub.version});const w=await n({source:y.source,subpath:y.subpath,gitIdentityId:t?.gitIdentityId,scope:y.scope,selections:[g],conflictPolicy:"prompt",conflictDecisions:y.conflictDecisions});if(w.ok){Z.success("Skill installed successfully"),r(!1);return}if(w.error?.kind==="conflicts"){p({source:y.source,subpath:y.subpath,scope:y.scope,skillDir:y.skillDir}),m(w.error.conflicts),d(!0);return}if(w.error?.kind==="authRequired"){Z.error(w.error.message||"Authentication required");return}Z.error(w.error?.message||"Failed to install skill")};return t?e.jsxs(e.Fragment,{children:[e.jsx(us,{open:s,onOpenChange:r,children:e.jsxs(ms,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Install skill"}),e.jsxs(vs,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:t.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:t.warnings?.length?e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-3 py-2",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Warnings"}),e.jsx("ul",{className:"mt-1 space-y-1",children:t.warnings.map(y=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:y},y))})]}):null}),e.jsxs(tr,{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(Cs,{value:a,onValueChange:y=>l(y),children:[e.jsx(Ms,{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(Ls,{className:"h-4 w-4"}):e.jsx(Js,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Ds,{align:"start",children:[e.jsx(qt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ls,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(qt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Js,{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(De,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(De,{className:"w-full sm:w-auto",variant:"default",disabled:o||!t.installable,onClick:()=>{h({source:t.repoSource,subpath:t.repoSubpath,scope:a,skillDir:t.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(H0,{open:c,onOpenChange:d,conflicts:u,onConfirm:y=>{f&&(h({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:y}),d(!1))}})]}):null},V0=async()=>{try{if(os())return await zr();const s=Zs()?.settings;if(s)return(await s.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},G0=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,isLoadingCatalog:c,lastCatalogError:d}=go(),[u,m]=i.useState(""),[f,p]=i.useState(!1),[h,y]=i.useState(!1),[g,w]=i.useState(null),[b,v]=i.useState(!1);i.useEffect(()=>{l()},[l]);const j=i.useMemo(()=>o?n[o]||[]:[],[n,o]),k=i.useMemo(()=>{const C=u.trim().toLowerCase();return C?j.filter(M=>{const S=M.skillName.toLowerCase(),A=(M.description||"").toLowerCase(),D=(M.frontmatterName||"").toLowerCase();return S.includes(C)||A.includes(C)||D.includes(C)}):j},[j,u]),x=i.useMemo(()=>t.find(C=>C.id===o)||null,[t,o]),N=!!(o&&o.startsWith("custom:")),P=async()=>{if(!(!o||!N)&&window.confirm("Remove this catalog?")){v(!0);try{const C=await V0(),S=(Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[]).filter(A=>A.id!==o);await ns({skillCatalogs:S}),await l({refresh:!0})}finally{v(!1)}}};return e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Rf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:s,onValueChange:r,animate:!1}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Skills Catalog"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Browse curated repositories and install skills into your OpenCode configuration."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Source"}),e.jsxs(Cs,{value:o||"",onValueChange:C=>a(C),children:[e.jsx(Ms,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x?.label||"Select source"})}),e.jsx(Ds,{align:"start",children:t.map(C=>e.jsx(qt,{value:C.id,className:"pr-2 [&>span:first-child]:hidden",children:C.label},C.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(De,{type:"button",variant:"outline",onClick:()=>{l({refresh:!0})},disabled:c,className:"gap-2",children:[e.jsx(Rr,{className:"h-4 w-4"}),"Refresh"]}),N?e.jsxs(De,{type:"button",variant:"outline",onClick:()=>{P()},disabled:b,className:"gap-2",children:[e.jsx(Bs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(De,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Zt,{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(kt,{value:u,onChange:C=>m(C.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:c?"Loading…":`${k.length} skill(s)`})]}),d?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:k.length===0?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):k.map(C=>{const M=C.installed?.isInstalled,S=C.installed?.scope;return e.jsx("div",{className:"rounded-lg border bg-muted/10 px-3 py-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label truncate",children:C.skillName}),M?e.jsxs("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:["installed (",S||"unknown",")"]}):null,C.installable?null:e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"not installable"})]}),C.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:C.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),C.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[C.clawdhub.owner?e.jsxs("span",{children:["by ",C.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Or,{className:"h-3 w-3"}),C.clawdhub.downloads?.toLocaleString()??0]}),(C.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kn,{className:"h-3 w-3"}),C.clawdhub.stars]}):null,e.jsxs("span",{children:["v",C.clawdhub.version]})]}):null,C.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:C.warnings.join(" · ")}):null]}),e.jsx(De,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!C.installable,onClick:()=>{w(C),y(!0)},children:"Install"})]})},`${C.sourceId}:${C.skillDir}`)})}),e.jsx(W0,{open:f,onOpenChange:p}),e.jsx(U0,{open:h,onOpenChange:y,item:g})]})})},q0=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=Qs(),u=s?r(s):null,m=!!(l&&l.name===s&&!u),f=!!(s&&!u&&!l),[p,h]=i.useState("manual");i.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),i.useEffect(()=>{f&&d(null)},[f,d]);const y=m?e.jsx(Rf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,w]=i.useState(""),[b,v]=i.useState("user"),[j,k]=i.useState(""),[x,N]=i.useState(""),[P,C]=i.useState([]),[M,S]=i.useState([]),[A,D]=i.useState(!1),[F,E]=i.useState(!1),[I,_]=i.useState(""),[V,Y]=i.useState(""),[H,L]=i.useState(!1),[U,Q]=i.useState(""),[J,K]=i.useState(""),[ne,X]=i.useState(null),[ae,O]=i.useState(!1),[z,T]=i.useState(""),$=m?g.trim()!==""||j.trim()!==""||x.trim()!==""||M.length>0:j!==I||x!==V,W=ne?J!==z:U.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)w(l.name||""),v(l.scope||"user"),k(l.description||""),N(l.instructions||""),_(""),Y(""),C([]),S(l.pendingFiles||[]);else if(s&&u){E(!0);try{const Le=await t(s);if(Le){const G=Le.sources.md;k(G.description||""),N(G.instructions||""),_(G.description||""),Y(G.instructions||""),C(G.supportingFiles||[])}}catch(Le){console.error("Failed to load skill details:",Le)}finally{E(!1)}}})()},[u,m,s,a,l,t,p]);const q=async()=>{const Se=m?g.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!Se){Z.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(Se)||Se.length>64){Z.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!j.trim()){Z.error("Description is required");return}if(m&&a.some(Le=>Le.name===Se)){Z.error("A skill with this name already exists");return}D(!0);try{const Le={name:Se,description:j.trim(),instructions:x.trim()||void 0,scope:m?b:void 0,supportingFiles:m&&M.length>0?M:void 0};let G;m?(G=await n(Le),G&&(c(null),S([]),d(Se))):(G=await o(Se,Le),G&&(_(j.trim()),Y(x.trim()))),G?Z.success(m?"Skill created successfully":"Skill updated successfully"):Z.error(m?"Failed to create skill":"Failed to update skill")}catch(Le){console.error("Error saving skill:",Le),Z.error("An error occurred while saving")}finally{D(!1)}},ue=()=>{X(null),Q(""),K(""),T(""),L(!0)},oe=async Se=>{if(X(Se),Q(Se),m){const G=M.find(ee=>ee.path===Se)?.content||"";K(G),T(G),L(!0);return}if(s){O(!0),L(!0);try{const{readSupportingFile:Le}=Qs.getState(),G=await Le(s,Se);K(G||""),T(G||"")}catch{Z.error("Failed to load file content"),K(""),T("")}finally{O(!1)}}},de=async()=>{if(!U.trim()){Z.error("File name is required");return}const Se=U.trim(),Le=ne!==null;if(m){if(Le)S(te=>te.map(xe=>xe.path===ne?{path:Se,content:J}:xe)),Z.success(`File "${Se}" updated`);else{if(M.some(te=>te.path===Se)){Z.error("A file with this name already exists");return}S(te=>[...te,{path:Se,content:J}]),Z.success(`File "${Se}" added`)}L(!1),X(null);return}if(!s){Z.error("No skill selected");return}const{writeSupportingFile:G}=Qs.getState();if(await G(s,Se,J)){Z.success(Le?`File "${Se}" updated`:`File "${Se}" created`),L(!1),X(null);const te=await t(s);te&&C(te.sources.md.supportingFiles||[])}else Z.error(Le?"Failed to update file":"Failed to create file")},je=async Se=>{if(m){S(Le=>Le.filter(G=>G.path!==Se)),Z.success(`File "${Se}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${Se}"?`)){const{deleteSupportingFile:Le}=Qs.getState();if(await Le(s,Se)){Z.success(`File "${Se}" deleted`);const ee=await t(s);ee&&C(ee.sources.md.supportingFiles||[])}else Z.error("Failed to delete file")}};return m&&p==="external"?e.jsx(G0,{mode:p,onModeChange:h}):!s&&!l||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Vu,{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"})]})}):F?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(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[m?y:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":s}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[u.scope==="project"?"Project":"User"," skill",u.source==="claude"&&" (Claude-compatible)"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure skill identity and description"})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{value:g,onChange:Se=>w(Se.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(Cs,{value:b,onValueChange:Se=>v(Se),children:[e.jsxs(Ms,{className:"!h-9 w-auto gap-1.5",children:[b==="user"?e.jsx(Ls,{className:"h-4 w-4"}):e.jsx(Js,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:b})]}),e.jsxs(Ds,{align:"end",children:[e.jsx(qt,{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(Ls,{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(qt,{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(Js,{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(Ns,{value:j,onChange:Se=>k(Se.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(Ns,{value:x,onChange:Se=>N(Se.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(De,{variant:"outline",size:"sm",onClick:ue,className:"gap-1.5",children:[e.jsx(Zt,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const Se=m?M:P;return Se.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:Se.map(Le=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-muted/30 hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>oe(Le.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(cr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:Le.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(De,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:G=>{G.stopPropagation(),je(Le.path)},children:e.jsx(Bs,{className:"h-3.5 w-3.5"})})]},Le.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(De,{size:"sm",variant:"default",onClick:q,disabled:A||!$,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Pa,{className:"h-3 w-3"}),A?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(us,{open:H,onOpenChange:Se=>{L(Se),Se||X(null)},children:e.jsxs(ms,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(hs,{className:"flex-shrink-0",children:[e.jsx(gs,{children:ne?"Edit Supporting File":"Add Supporting File"}),e.jsx(vs,{children:ne?"Modify the file content":"Create a new file in the skill directory"})]}),ae?e.jsx("div",{className:"flex-1 flex items-center justify-center py-8",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading file content..."})}):e.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"File Path"}),e.jsx(kt,{value:U,onChange:Se=>Q(Se.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:ne!==null}),!ne&&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(Ns,{value:J,onChange:Se=>K(Se.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(tr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>{L(!1),X(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(dn,{onClick:de,disabled:ae||!W,children:ne?"Save Changes":"Create File"})]})]})})]})})},K0="__add_provider__",Q0=({onItemSelect:s})=>{const r=nt(u=>u.providers),t=nt(u=>u.selectedProviderId),n=nt(u=>u.setSelectedProvider),{isMobile:o}=Ht(),[a,l]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||l(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",d),children:[e.jsx("div",{className:R("border-b px-3",o?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",r.length]}),e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(K0),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Zt,{className:"size-4"})})]})}),e.jsx(xt,{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(oo,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No providers found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]}):r.map(u=>{const m=Array.isArray(u.models)?u.models.length:0,f=u.id===t;return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{type:"button",onClick:()=>{n(u.id),s?.()},className:"flex min-w-0 flex-1 items-center gap-2 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsx(ds,{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)})})]})},Y0=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Jd=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=Y0.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Zd="__add_provider__",On=s=>typeof s=="object"&&s!==null,eu=s=>{const r=typeof s.type=="string"?s.type:"",t=`${s.name??""} ${s.label??""}`.toLowerCase(),n=`${r} ${t}`.toLowerCase();return n.includes("oauth")?"oauth":n.includes("api")?"api":r.toLowerCase()},X0=s=>{if(!On(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>On(o)));return r},J0=s=>{if(typeof s=="string")return{id:s};if(!On(s))return null;const r=typeof s.id=="string"&&s.id||typeof s.providerID=="string"&&s.providerID||typeof s.slug=="string"&&s.slug||typeof s.name=="string"&&s.name;if(!r)return null;const t=typeof s.name=="string"?s.name:void 0;return{id:r,name:t}},Z0=s=>{let r=[];Array.isArray(s)?r=s:On(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>J0(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},eS=()=>{const s=nt(T=>T.providers),r=nt(T=>T.selectedProviderId),t=nt(T=>T.setSelectedProvider),n=nt(T=>T.getModelMetadata),[o,a]=i.useState({}),[l,c]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,h]=i.useState(""),[y,g]=i.useState(null),[w,b]=i.useState({}),[v,j]=i.useState({}),[k,x]=i.useState([]),[N,P]=i.useState(!1),[C,M]=i.useState(null),[S,A]=i.useState(""),[D,F]=i.useState(""),[E,I]=i.useState(!1);i.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),i.useEffect(()=>{let T=!0;return(async()=>{c(!0);try{const W=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!W.ok)throw new Error(`Auth methods request failed (${W.status})`);const q=await W.json().catch(()=>({}));if(!T)return;a(X0(q))}catch(W){if(!T)return;console.error("Failed to load provider auth methods:",W),Z.error("Failed to load provider authentication methods")}finally{T&&c(!1)}})(),()=>{T=!1}},[]),i.useEffect(()=>{let T=!0;return(async()=>{P(!0),M(null);try{const W=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!W.ok)throw new Error(`Provider list request failed (${W.status})`);const q=await W.json().catch(()=>({}));if(!T)return;x(Z0(q))}catch(W){if(!T)return;console.error("Failed to load available providers:",W),M("Unable to load provider list")}finally{T&&P(!1)}})(),()=>{T=!1}},[]);const _=i.useMemo(()=>new Set(s.map(T=>T.id)),[s]),V=i.useMemo(()=>k.filter(T=>!_.has(T.id)),[k,_]);i.useEffect(()=>{if(r===Zd){if(!S&&V.length>0){A(V[0].id);return}S&&!V.some(T=>T.id===S)&&A(V[0]?.id??"")}},[r,S,V]);const Y=s.find(T=>T.id===r),H=async T=>{const $=d[T]?.trim()??"";if(!$){Z.error("API key is required");return}const W=`api:${T}`;f(W);try{const q=await fetch(`/api/auth/${encodeURIComponent(T)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:$})}),ue=await q.json().catch(()=>null);if(!q.ok){const oe=ue?.error||"Failed to save API key";throw new Error(oe)}Z.success("API key saved"),u(oe=>({...oe,[T]:""})),await Jn({scopes:["providers"],mode:"active"}),t(T)}catch(q){console.error("Failed to save API key:",q),Z.error("Failed to save API key")}finally{f(null)}},L=async(T,$)=>{const W=`oauth:${T}:${$}`;f(W);try{const q=await fetch(`/api/provider/${encodeURIComponent(T)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:$})}),ue=await q.json().catch(()=>null);if(!q.ok){const ee=ue?.error||"Failed to start OAuth flow";throw new Error(ee)}const oe=On(ue)?ue:{},de=On(oe.data)?oe.data:oe,je=typeof de.url=="string"&&de.url||typeof de.verification_uri_complete=="string"&&de.verification_uri_complete||typeof de.verification_uri=="string"&&de.verification_uri||void 0,Se=typeof de.instructions=="string"&&de.instructions||typeof de.message=="string"&&de.message||void 0,Le=typeof de.user_code=="string"&&de.user_code||typeof de.code=="string"&&de.code||typeof de.userCode=="string"&&de.userCode||void 0;if(!je&&!Se&&!Le)throw new Error("No OAuth details returned");const G=`${T}:${$}`;j(ee=>({...ee,[G]:{url:je,instructions:Se,userCode:Le}})),je&&window.open(je,"_blank","noopener,noreferrer"),g({providerId:T,methodIndex:$}),Z.message("Complete the OAuth flow in your browser")}catch(q){console.error("Failed to start OAuth flow:",q),Z.error("Failed to start OAuth flow")}finally{f(null)}},U=async(T,$)=>{const W=`${T}:${$}`,q=w[W]?.trim(),ue=`oauth-complete:${T}:${$}`;f(ue);try{const oe={method:$};q&&(oe.code=q);const de=await fetch(`/api/provider/${encodeURIComponent(T)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(oe)}),je=await de.json().catch(()=>null);if(!de.ok){const Se=je?.error||"Failed to complete OAuth flow";throw new Error(Se)}Z.success("OAuth connection completed"),b(Se=>({...Se,[W]:""})),g(null),await Jn({scopes:["providers"],mode:"active"}),t(T)}catch(oe){console.error("Failed to complete OAuth flow:",oe),Z.error("Failed to complete OAuth flow")}finally{f(null)}},Q=async T=>{try{await navigator.clipboard.writeText(T),Z.success("OAuth link copied")}catch($){console.error("Failed to copy OAuth link:",$),Z.error("Failed to copy OAuth link")}},J=async T=>{try{await navigator.clipboard.writeText(T),Z.success("Device code copied")}catch($){console.error("Failed to copy device code:",$),Z.error("Failed to copy device code")}},K=async T=>{const $=`disconnect:${T}`;f($);try{const W=await fetch(`/api/provider/${encodeURIComponent(T)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),q=await W.json().catch(()=>null);if(!W.ok){const ue=q?.error||"Failed to disconnect provider";throw new Error(ue)}Z.success("Provider disconnected"),await Jn({scopes:["providers"],mode:"active"})}catch(W){console.error("Failed to disconnect provider:",W),Z.error("Failed to disconnect provider")}finally{f(null)}},ne=r===Zd;if(!ne&&s.length===0)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(oo,{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(ne)return e.jsx(xt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Connect provider"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:"Choose a provider to connect and set up its authentication."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Provider"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select a provider that is not connected yet."})]}),N?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):C?e.jsx("p",{className:"typography-meta text-muted-foreground",children:C}):V.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(Yt,{open:E,onOpenChange:T=>{I(T),T||F("")},children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("button",{type:"button",className:R("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:S?"text-foreground":"text-muted-foreground",children:S?V.find(T=>T.id===S)?.name||S:"Select provider"}),e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Jt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:T=>T.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:T=>T.stopPropagation(),children:[e.jsx(Xs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:D,onChange:T=>F(T.target.value),onKeyDown:T=>T.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(xt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const T=V.filter($=>{const W=D.toLowerCase();return($.name||$.id).toLowerCase().includes(W)||$.id.toLowerCase().includes(W)});return T.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):T.map($=>e.jsxs(It,{onSelect:()=>{A($.id),I(!1),F("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:$.name||$.id}),S===$.id&&e.jsx(Bt,{className:"h-4 w-4 text-primary"})]},$.id))})()})]})]})]}),S&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),l?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{type:"password",value:d[S]??"",onChange:T=>u($=>({...$,[S]:T.target.value})),placeholder:"sk-..."}),e.jsx(De,{size:"sm",onClick:()=>H(S),disabled:m===`api:${S}`,className:"h-8",children:m===`api:${S}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),(()=>{const $=(o[S]??[]).filter(W=>eu(W)==="oauth");return $.length===0?null:e.jsx("div",{className:"space-y-3",children:$.map((W,q)=>{const ue=W.label||W.name||`OAuth method ${q+1}`,oe=`${S}:${q}`,de=y?.providerId===S&&y?.methodIndex===q;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:ue}),(W.description||W.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(W.description||W.help)})]}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>L(S,q),disabled:m===`oauth:${S}:${q}`,className:"h-8",children:"Connect"})]}),v[oe]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[oe]?.instructions}),v[oe]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{value:v[oe]?.userCode,readOnly:!0}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>J(v[oe]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[oe]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{value:v[oe]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(De,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[oe]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>Q(v[oe]?.url??""),className:"h-8",children:"Copy link"})]})]}),de&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{value:w[oe]??"",onChange:je=>b(Se=>({...Se,[oe]:je.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(De,{size:"sm",onClick:()=>U(S,q),disabled:m===`oauth-complete:${S}:${q}`,className:"h-8",children:m===`oauth-complete:${S}:${q}`?"Saving…":"Complete"})]})]},`${S}-${ue}`)})})})()]})]})]})});if(!Y)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(oo,{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 X=Array.isArray(Y.models)?Y.models:[],O=(o[Y.id]??[]).filter(T=>eu(T)==="oauth"),z=X.filter(T=>{const $=typeof T?.name=="string"?T.name:"",W=typeof T?.id=="string"?T.id:"",q=p.trim().toLowerCase();return q?$.toLowerCase().includes(q)||W.toLowerCase().includes(q):!0});return e.jsx(xt,{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(ds,{providerId:Y.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:Y.name||Y.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",Y.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),l?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{type:"password",value:d[Y.id]??"",onChange:T=>u($=>({...$,[Y.id]:T.target.value})),placeholder:"sk-..."}),e.jsx(De,{size:"sm",onClick:()=>H(Y.id),disabled:m===`api:${Y.id}`,className:"h-8",children:m===`api:${Y.id}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),e.jsx("div",{className:"pt-2 border-t border-border/40",children:e.jsx(De,{size:"sm",variant:"outline",onClick:()=>K(Y.id),disabled:m===`disconnect:${Y.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${Y.id}`?"Disconnecting…":"Disconnect provider"})}),O.length>0&&e.jsx("div",{className:"space-y-3",children:O.map((T,$)=>{const W=T.label||T.name||`OAuth method ${$+1}`,q=`${Y.id}:${$}`,ue=y?.providerId===Y.id&&y?.methodIndex===$;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:W}),(T.description||T.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(T.description||T.help)})]}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>L(Y.id,$),disabled:m===`oauth:${Y.id}:${$}`,className:"h-8",children:"Connect"})]}),v[q]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[q]?.instructions}),v[q]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{value:v[q]?.userCode,readOnly:!0}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>J(v[q]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[q]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{value:v[q]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(De,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[q]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(De,{size:"sm",variant:"outline",onClick:()=>Q(v[q]?.url??""),className:"h-8",children:"Copy link"})]})]}),ue&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(kt,{value:w[q]??"",onChange:oe=>b(de=>({...de,[q]:oe.target.value})),placeholder:"Paste authorization code"}),e.jsx(De,{size:"sm",onClick:()=>U(Y.id,$),disabled:m===`oauth-complete:${Y.id}:${$}`,className:"h-8",children:m===`oauth-complete:${Y.id}:${$}`?"Saving…":"Complete"})]})]},`${Y.id}-${W}`)})})]})]}),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(kt,{value:p,onChange:T=>h(T.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:z.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):z.map(T=>{const $=typeof T?.id=="string"?T.id:"",W=typeof T?.name=="string"?T.name:$,q=$?n(Y.id,$):void 0,ue=Jd(q?.limit?.context),oe=Jd(q?.limit?.output),de=[];return q?.tool_call&&de.push({key:"tools",icon:Ia,label:"Tool calling"}),q?.reasoning&&de.push({key:"reasoning",icon:pr,label:"Reasoning"}),q?.attachment&&de.push({key:"image",icon:hr,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:W}),(ue||oe)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[ue?`${ue} ctx`:"",ue&&oe?" · ":"",oe?`${oe} out`:""]}),de.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:de.map(({key:je,icon:Se,label:Le})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Le,"aria-label":Le,children:e.jsx(Se,{className:"h-3 w-3"})},je))})]},$)})})]})]})})},tS={branch:_t,briefcase:gl,house:hl,graduation:pl,code:$s,heart:Bu},sS={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},rS=({onItemSelect:s})=>{const{selectedProfileId:r,defaultGitIdentityId:t,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:l,loadProfiles:c,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=Rn(),{setSidebarOpen:h}=_e(),{isMobile:y}=Ht(),[g,w]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>zt(),[]);i.useEffect(()=>{typeof window>"u"||w(typeof window.opencodeDesktop<"u")},[]);const v=p();i.useEffect(()=>{c(),d(),u(),m()},[c,d,u,m]);const j=C=>{a(`import:${C.host}:${C.username}`),s?.(),y&&h(!1)},k=g?"bg-transparent":b?"bg-background":"bg-sidebar",x=()=>{a("new"),s?.(),y&&h(!1)},N=async C=>{window.confirm(`Are you sure you want to delete profile "${C.name}"?`)&&(await l(C.id)?Z.success(`Profile "${C.name}" deleted successfully`):Z.error("Failed to delete profile"))},P=async C=>{const M=t===C?null:C;if(!await f(M)){Z.error("Failed to update default identity");return}Z.success(M?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:R("flex h-full flex-col",k),children:[e.jsx("div",{className:R("border-b px-3",y?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",n.length]}),e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:x,children:e.jsx(Zt,{className:"size-4"})})]})}),e.jsxs(xt,{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(tu,{profile:o,isSelected:r==="global",isDefault:t==="global",onSelect:()=>{a("global"),s?.(),y&&h(!1)},onToggleDefault:()=>P("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(_t,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:n.map(C=>e.jsx(tu,{profile:C,isSelected:r===C.id,isDefault:t===C.id,onSelect:()=>{a(C.id),s?.(),y&&h(!1)},onToggleDefault:()=>P(C.id),onDelete:()=>N(C)},C.id))}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Discovered Credentials"}),e.jsx("p",{className:"px-2 pb-2 typography-micro text-muted-foreground/60",children:"Found in ~/.git-credentials"}),v.map(C=>e.jsx(oS,{credential:C,onImport:()=>j(C)},`${C.host}-${C.username}`))]})]})]})},tu=({profile:s,isSelected:r,isDefault:t=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=tS[s.icon||"branch"]||_t,d=sS[s.color||""],u=s.authType||"ssh";return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:n,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(c,{className:"w-4 h-4 flex-shrink-0",style:{color:d}}),e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:u}),t&&e.jsx("span",{className:"typography-micro text-primary bg-primary/12 px-1 rounded flex-shrink-0 leading-none pb-px border border-primary/25",children:"default"})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:u==="token"&&s.host?s.host:s.userEmail})]}),(o||!l&&a)&&e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(De,{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(Lr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(It,{onClick:m=>{m.stopPropagation(),o()},children:t?"Unset default":"Set as default"}),!l&&a&&e.jsxs(It,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(Bs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},nS=s=>{const r=s.split("/");return r.length>=3?r[r.length-1]:s},oS=({credential:s,onImport:r})=>{const t=nS(s.host),n=s.host.includes("/");return e.jsx("div",{className:"group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 hover:dark:bg-accent/40 hover:bg-primary/6",children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t})}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n?s.host:s.username})]}),e.jsxs(De,{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(Or,{className:"h-3 w-3"}),"Import"]})]})})},su=[{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)"}],aS=[{key:"branch",Icon:_t,label:"Branch"},{key:"briefcase",Icon:gl,label:"Work"},{key:"house",Icon:hl,label:"Personal"},{key:"graduation",Icon:pl,label:"School"},{key:"code",Icon:$s,label:"Code"}],iS=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=Rn(),a=i.useMemo(()=>{if(s?.startsWith("import:")){const[,E,I]=s.split(":");return{host:E,username:I}}return null},[s]),l=i.useMemo(()=>s&&s!=="new"&&!a?r(s):null,[s,r,a]),c=s==="new"||a!==null,d=s==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[h,y]=i.useState(""),[g,w]=i.useState("ssh"),[b,v]=i.useState(""),[j,k]=i.useState(""),[x,N]=i.useState("keyword"),[P,C]=i.useState("branch"),[M,S]=i.useState(!1);i.useEffect(()=>{if(a){const E=a.host.split("/"),I=E.length>=3?E[E.length-1]:a.host;m(I),p(a.username),y(""),w("token"),v(""),k(a.host),N("string"),C("code")}else c?(m(""),p(""),y(""),w("ssh"),v(""),k(""),N("keyword"),C("branch")):l&&(m(l.name),p(l.userName),y(l.userEmail),w(l.authType||"ssh"),v(l.sshKey||""),k(l.host||""),N(l.color||"keyword"),C(l.icon||"branch"))},[l,c,s,a]);const A=async()=>{if(!f.trim()||!h.trim()){Z.error("User name and email are required");return}if(g==="token"&&!j.trim()){Z.error("Host is required for token-based authentication");return}S(!0);try{const E={name:u.trim()||f.trim(),userName:f.trim(),userEmail:h.trim(),authType:g,sshKey:g==="ssh"&&b.trim()||null,host:g==="token"&&j.trim()||null,color:x,icon:P};let I;if(c)I=await t(E);else if(s)I=await n(s,E);else return;I?Z.success(c?"Profile created successfully":"Profile updated successfully"):Z.error(c?"Failed to create profile":"Failed to update profile")}catch(E){console.error("Error saving profile:",E),Z.error("An error occurred while saving")}finally{S(!1)}},D=async()=>{if(!(!s||c)&&confirm("Are you sure you want to delete this profile?"))try{await o(s)?Z.success("Profile deleted successfully"):Z.error("Failed to delete profile")}catch(E){console.error("Error deleting profile:",E),Z.error("An error occurred while deleting")}},F=i.useMemo(()=>su.find(I=>I.key===x)?.cssVar||"var(--syntax-keyword)",[x]);return s?e.jsx(xt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:a?"Import Credential":c?"New Git Profile":d?"Global Identity":u||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:a?`Import token credential for ${a.host} - please fill in your email address`:c?"Create a new Git identity profile for your repositories":d?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!d&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(kt,{value:u,onChange:E=>m(E.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:su.map(E=>e.jsx("button",{onClick:()=>N(E.key),className:R("w-8 h-8 rounded-lg border-2 transition-all",x===E.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:E.cssVar},title:E.label},E.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:aS.map(E=>{const I=E.Icon;return e.jsx("button",{onClick:()=>C(E.key),className:R("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",P===E.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:E.label,children:e.jsx(I,{className:"w-4 h-4",style:{color:F}})},E.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(kt,{value:f,onChange:E=>p(E.target.value),placeholder:"John Doe",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(kt,{type:"email",value:h,onChange:E=>y(E.target.value),placeholder:"john@example.com",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Authentication Type",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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:R("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(qh,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>w("token"),className:R("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(Kh,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(kt,{value:b,onChange:E=>v(E.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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{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(kt,{value:j,onChange:E=>k(E.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!c&&e.jsxs(De,{size:"sm",variant:"destructive",onClick:D,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Bs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:R("flex gap-2",c&&"ml-auto"),children:e.jsxs(De,{size:"sm",variant:"default",onClick:A,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Pa,{className:"h-3 w-3"}),M?"Saving...":"Save Profile"]})})]})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ls,{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 Ci(s,r,t){return Math.min(t,Math.max(r,s))}const ka=Ae.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:l,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=Ae.useRef(null);Ae.useImperativeHandle(f,()=>p.current);const[h,y]=Ae.useState(()=>String(s));Ae.useEffect(()=>{document.activeElement!==p.current&&y(String(s))},[s]);const g=Ae.useCallback(()=>{p.current?.focus()},[]),w=Ae.useCallback(S=>{const A=Ci(S,t,n);r(A),y(String(A))},[n,t,r]),b=Ae.useCallback(()=>{const S=Number(h);return Number.isFinite(S)?S:s},[h,s]),v=Ae.useCallback(()=>{w(b()+o),g()},[w,b,g,o]),j=Ae.useCallback(()=>{w(b()-o),g()},[w,b,g,o]),k=S=>{const A=S.target.value;y(A);const D=Number(A);Number.isFinite(D)&&r(Ci(D,t,n))},x=S=>{const A=Number(h);if(!Number.isFinite(A))y(String(s));else{const D=Ci(A,t,n);D!==A&&r(D),y(String(D))}c?.(S)},N=S=>{if(S.key==="ArrowUp"){S.preventDefault(),v();return}if(S.key==="ArrowDown"){S.preventDefault(),j();return}d?.(S)},P=b(),C=u||P<=t,M=u||P>=n;return e.jsxs("div",{className:R("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",l),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:k,onBlur:x,onKeyDown:N,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:R("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:M,onClick:v,className:R("flex flex-1 items-center justify-center","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(Aa,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:C,onClick:j,className:R("flex flex-1 items-center justify-center border-t border-border","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(Ft,{className:"h-3.5 w-3.5"})})]})]})});ka.displayName="NumberInput";const lS=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],ru=[{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"}],nu=[{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."}],ou=[{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."}],ql=({visibleSettings:s})=>{const{isMobile:r}=Ht(),t=_e(x=>x.showReasoningTraces),n=_e(x=>x.setShowReasoningTraces),o=_e(x=>x.toolCallExpansion),a=_e(x=>x.setToolCallExpansion),l=_e(x=>x.fontSize),c=_e(x=>x.setFontSize),d=_e(x=>x.padding),u=_e(x=>x.setPadding),m=_e(x=>x.inputBarOffset),f=_e(x=>x.setInputBarOffset),p=_e(x=>x.diffLayoutPreference),h=_e(x=>x.setDiffLayoutPreference),y=_e(x=>x.diffViewMode),g=_e(x=>x.setDiffViewMode),w=lr(x=>x.queueModeEnabled),b=lr(x=>x.setQueueMode),{themeMode:v,setThemeMode:j}=Vr(),k=x=>s?s.includes(x):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[k("theme")&&!zt()&&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:lS.map(x=>e.jsx(Fs,{variant:v===x.value?"default":"outline",className:R(v===x.value?void 0:"text-foreground"),onClick:()=>j(x.value),children:x.label},x.value))})]}),k("fontSize")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Font Size"})}),e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:l,onChange:x=>c(Number(x.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(ka,{value:l,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Fs,{type:"button",variant:"ghost",onClick:()=>c(100),disabled:l===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(Os,{className:"h-3.5 w-3.5"})})]})]}),k("spacing")&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Spacing"})}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:d,onChange:x=>u(Number(x.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Spacing percentage"}),e.jsx("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:d}),e.jsx(Fs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Os,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:d,onChange:x=>u(Number(x.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(ka,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Fs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Os,{className:"h-3.5 w-3.5"})})]})]}),k("inputBarOffset")&&r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Input Bar Offset"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Raise the input bar for phones with curved screen edges."})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:m,onChange:x=>f(Number(x.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[m,"px"]}),e.jsx(Fs,{type:"button",variant:"ghost",onClick:()=>f(0),disabled:m===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(Os,{className:"h-3.5 w-3.5"})})]})]}),k("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:ru.find(x=>x.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:ru.map(x=>e.jsx(Fs,{variant:o===x.value?"default":"outline",className:R(o===x.value?void 0:"text-foreground"),onClick:()=>a(x.value),children:x.label},x.value))})]}),k("diffLayout")&&!r&&!zt()&&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:nu.map(x=>e.jsx(Fs,{variant:p===x.id?"default":"outline",className:R(p===x.id?void 0:"text-foreground"),onClick:()=>h(x.id),children:x.label},x.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:nu.find(x=>x.id===p)?.description})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff view (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose whether the Diff tab defaults to a single file or all files."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:ou.map(x=>e.jsx(Fs,{variant:y===x.id?"default":"outline",className:R(y===x.id?void 0:"text-foreground"),onClick:()=>g(x.id),children:x.label},x.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:ou.find(x=>x.id===y)?.description})]})]}),k("reasoning")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:t,onChange:x=>n(x.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),k("queueMode")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:w,onChange:x=>b(x.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Queue messages by default"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5",children:w?`Enter queues messages, ${es()}+Enter sends immediately.`:`Enter sends immediately, ${es()}+Enter queues messages.`})]})]})},au="https://github.com/btriapitsyn/openchamber",cS=800,Of=()=>{const[s,r]=i.useState(!1),[t,n]=i.useState(!1),o=Ta(),{isMobile:a}=Ht(),l=o.info?.currentVersion||"unknown",c=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(t){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(Z.success("You are on the latest version"),c.current=!1)},cS);return()=>clearTimeout(u)}},[o.checking,t,o.available,o.error]);const d=o.checking||t;return a?e.jsxs("div",{className:"w-full space-y-2",children:[e.jsxs("button",{onClick:()=>Jn(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Os,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",l]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:R("typography-meta text-muted-foreground/60 hover:text-muted-foreground disabled:cursor-default",d&&"animate-pulse [animation-duration:1s]"),children:"Check updates"}),!d&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:"flex items-center gap-1 typography-meta text-primary hover:underline",children:[e.jsx(Or,{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(Bi,{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(Gu,{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(zi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Xi,{open:s,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]}):e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:l})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ho,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!o.checking&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:R("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Or,{className:"h-4 w-4"}),"Update to ",o.info?.version]}),!o.checking&&!o.available&&!o.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"})]}),o.error&&e.jsx("p",{className:"typography-meta text-destructive",children:o.error}),e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:o.checking,className:R("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:"Check for updates"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("a",{href:au,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(zi,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Xi,{open:s,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]})},dS=1440*60*1e3,_f=5,iu=1440*60*1e3,Mi=s=>s.time?.updated??s.time?.created??0,lu=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=_f,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*dS,l=[...s].sort((d,u)=>Mi(u)-Mi(d)),c=new Set(l.slice(0,n).map(d=>d.id));return l.filter(d=>{if(!d?.id||c.has(d.id)||d.id===r||d.share)return!1;const u=Mi(d);return u?u<a:!1}).map(d=>d.id)},$f=s=>{const r=s?.autoRun!==!1,t=he(g=>g.sessions),n=he(g=>g.currentSessionId),o=he(g=>g.isLoading),a=he(g=>g.deleteSessions),l=_e(g=>g.autoDeleteEnabled),c=_e(g=>g.autoDeleteAfterDays),d=_e(g=>g.autoDeleteLastRunAt),u=_e(g=>g.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),h=i.useMemo(()=>c<=0?[]:lu({sessions:t,currentSessionId:n,cutoffDays:c}),[c,n,t]),y=i.useCallback(async({force:g=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!l||c<=0)&&!g)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const w=Date.now();if(!g&&d&&w-d<iu)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const b=lu({sessions:t,currentSessionId:n,cutoffDays:c,now:w});if(b.length===0)return u(w),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(b,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[c,l,d,n,a,o,t,u]);return i.useEffect(()=>{if(!r||!l||c<=0||o||t.length===0)return;const g=Date.now();d&&g-d<iu||y()},[c,l,d,r,o,t.length,y]),{candidates:h,isRunning:m,runCleanup:y,keepRecentCount:_f}},Di=1,Ai=365,Lf=()=>{const{isMobile:s}=Ht(),r=_e(p=>p.autoDeleteEnabled),t=_e(p=>p.autoDeleteAfterDays),n=_e(p=>p.setAutoDeleteEnabled),o=_e(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(t));i.useEffect(()=>{l(String(t))},[t]);const{candidates:c,isRunning:d,runCleanup:u}=$f({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){Z.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&Z.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&Z.error(`Failed to delete ${p.failedIds.length} session${p.failedIds.length===1?"":"s"}`)},[u]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session retention"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:r,onChange:p=>n(p.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const h=p.target.value;if(l(h),h.trim()==="")return;const y=Number(h);if(!Number.isFinite(y))return;const g=Math.min(Ai,Math.max(Di,Math.round(y)));o(g)},onBlur:()=>{if(a.trim()===""){l(String(t));return}const p=Number(a);if(!Number.isFinite(p)){l(String(t));return}const h=Math.min(Ai,Math.max(Di,Math.round(p)));o(h),l(String(h))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(ka,{value:t,onValueChange:o,min:Di,max:Ai,step:1,"aria-label":"Retention period in days"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days since last activity"})]}),e.jsx(Fs,{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]})]})},cu="opencode",du="big-pickle",uS=(s,r)=>{if(s){const o=s.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===cu)?.models.some(o=>o.id===du))return{providerId:cu,modelId:du};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},Bf=()=>{const s=nt(A=>A.setProvider),r=nt(A=>A.setModel),t=nt(A=>A.setAgent),n=nt(A=>A.setCurrentVariant),o=nt(A=>A.setSettingsDefaultModel),a=nt(A=>A.setSettingsDefaultVariant),l=nt(A=>A.setSettingsDefaultAgent),c=nt(A=>A.settingsAutoCreateWorktree),d=nt(A=>A.setSettingsAutoCreateWorktree),u=nt(A=>A.providers),[m,f]=i.useState(),[p,h]=i.useState(),[y,g]=i.useState(),[w,b]=i.useState(!0),v=i.useMemo(()=>uS(m,u),[m,u]),j=i.useMemo(()=>zt(),[]);i.useEffect(()=>{(async()=>{try{let D=null;if(os())D=await zr();else{const F=Zs()?.settings;if(F)try{const I=(await F.load())?.settings;I&&(D={defaultModel:typeof I.defaultModel=="string"?I.defaultModel:void 0,defaultVariant:typeof I.defaultVariant=="string"?I.defaultVariant:void 0,defaultAgent:typeof I.defaultAgent=="string"?I.defaultAgent:void 0})}catch{}if(!D){const E=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});E.ok&&(D=await E.json())}}if(D){const F=typeof D.defaultModel=="string"&&D.defaultModel.trim().length>0?D.defaultModel.trim():void 0,E=typeof D.defaultVariant=="string"&&D.defaultVariant.trim().length>0?D.defaultVariant.trim():void 0,I=typeof D.defaultAgent=="string"&&D.defaultAgent.trim().length>0?D.defaultAgent.trim():void 0;F!==void 0&&f(F),E!==void 0&&h(E),I!==void 0&&g(I)}}catch(D){console.warn("Failed to load defaults settings:",D)}finally{b(!1)}})()},[]);const k=i.useCallback(async(A,D)=>{const F=A&&D?`${A}/${D}`:void 0;f(F),h(void 0),a(void 0),n(void 0),o(F),A&&D&&u.find(I=>I.id===A)&&(s(A),r(D));try{if(await ns({defaultModel:F??"",defaultVariant:""}),!os()){const E=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:F})});E.ok||console.warn("Failed to save default model to server:",E.status,E.statusText)}}catch(E){console.warn("Failed to save default model:",E)}},[u,n,s,r,o,a]),x="__default__",N=i.useCallback(async A=>{const D=A===x?void 0:A||void 0;h(D),a(D),n(D);try{await ns({defaultVariant:D??""})}catch(F){console.warn("Failed to save default variant:",F)}},[n,a]),P=i.useCallback(async A=>{const D=A||void 0;g(D),l(D),A&&t(A);try{await ns({defaultAgent:D??""})}catch(F){console.warn("Failed to save default agent:",F)}},[t,l]),C=i.useMemo(()=>{if(!v.providerId||!v.modelId)return[];const F=u.find(E=>E.id===v.providerId)?.models.find(E=>E.id===v.modelId)?.variants;return F?Object.keys(F):[]},[v.modelId,v.providerId,u]),M=C.length>0;i.useEffect(()=>{!M&&p&&(h(void 0),a(void 0),n(void 0),ns({defaultVariant:""}).catch(()=>{}))},[p,n,a,M]);const S=i.useCallback(async A=>{const D=A.target.checked;d(D);try{await ns({autoCreateWorktree:D})}catch(F){console.warn("Failed to save auto create worktree setting:",F)}},[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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{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(Ua,{providerId:v.providerId,modelId:v.modelId,onChange:k})]}),M&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default thinking"}),e.jsxs(Cs,{value:p??x,onValueChange:N,children:[e.jsx(Ms,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(cn,{placeholder:"Thinking"})}),e.jsxs(Ds,{children:[e.jsx(qt,{value:x,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),C.map(A=>e.jsx(qt,{value:A,className:"pr-2 [&>span:first-child]:hidden",children:A},A))]})]})]}),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(Ff,{agentName:y||"",onChange:P})]})]}),(v.providerId||y)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",v.providerId&&e.jsxs("span",{className:"text-foreground",children:[v.providerId,"/",v.modelId,M?` (${p??"default"})`:""]}),v.providerId&&y&&" / ",y&&e.jsx("span",{className:"text-foreground",children:y})]}),!j&&e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:c,onChange:S}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Always create worktree for new sessions"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5 mt-1",children:c?`New session (Worktree): ${es()} + N • New session (Standard): Shift + ${es()} + N`:`New session (Standard): ${es()} + N • New session (Worktree): Shift + ${es()} + N`})]})]})},ro="opencode",uu="big-pickle",mS=(s,r)=>{if(s){const o=s.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===ro)?.models.some(o=>o.id===uu))return{providerId:ro,modelId:uu};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},fS=()=>{const s=nt(f=>f.settingsCommitMessageModel),r=nt(f=>f.setSettingsCommitMessageModel),t=nt(f=>f.settingsGitmojiEnabled),n=nt(f=>f.setSettingsGitmojiEnabled),o=nt(f=>f.providers),[a,l]=i.useState(!0),c=i.useMemo(()=>o.filter(f=>f.id===ro),[o]),d=i.useMemo(()=>{const f=s?.startsWith(`${ro}/`)?s:void 0;return mS(f,c)},[s,c]);i.useEffect(()=>{(async()=>{try{let p=null;if(os())p=await zr();else{const h=Zs()?.settings;if(h)try{const g=(await h.load())?.settings;g&&(p={commitMessageModel:typeof g.commitMessageModel=="string"?g.commitMessageModel:void 0,gitmojiEnabled:typeof g.gitmojiEnabled=="boolean"?g.gitmojiEnabled:void 0})}catch{}if(!p){const y=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});y.ok&&(p=await y.json())}}if(p){const h=typeof p.commitMessageModel=="string"&&p.commitMessageModel.trim().length>0?p.commitMessageModel.trim():void 0;r(h),typeof p.gitmojiEnabled=="boolean"&&n(p.gitmojiEnabled)}}catch(p){console.warn("Failed to load git settings:",p)}finally{l(!1)}})()},[r,n]);const u=i.useCallback(async(f,p)=>{const h=f&&p?`${f}/${p}`:void 0;r(h);try{await ns({commitMessageModel:h??""})}catch(y){console.warn("Failed to save commit message model:",y)}},[r]),m=i.useCallback(async f=>{const p=f.target.checked;n(p);try{await ns({gitmojiEnabled:p})}catch(h){console.warn("Failed to save gitmoji setting:",h)}},[n]);return a?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit Messages"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{sideOffset:8,className:"max-w-xs",children:"Configure how commit messages are generated."})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("fieldset",{className:"flex flex-col gap-1.5",children:[e.jsx("legend",{className:"typography-ui-label text-muted-foreground",children:"Model for generation"}),e.jsx(Ua,{providerId:d.providerId,modelId:d.modelId,onChange:u,allowedProviderIds:[ro]}),e.jsxs("p",{className:"typography-meta text-muted-foreground mt-1",children:["This model will be used to analyze diffs and suggest commit messages.",!s&&e.jsxs(e.Fragment,{children:[" Default: ",e.jsx("span",{className:"text-foreground",children:"opencode/big-pickle"})]})]})]}),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:m}),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."})]})]})]})},pS=()=>{const s=Lt(O=>O.getActiveProject()),r=Lt(O=>O.updateWorktreeDefaults),t=s?.path??null,n=s?.worktreeDefaults,o=Ml(t),a=Em(t),{sessions:l,getWorktreeMetadata:c}=he(),[d,u]=i.useState(n?.branchPrefix??""),[m,f]=i.useState(n?.baseBranch??"HEAD"),[p,h]=i.useState([]),[y,g]=i.useState(!1),[w,b]=i.useState(!1),[v,j]=i.useState(null),[k,x]=i.useState(null),[N,P]=i.useState([]),[C,M]=i.useState(!1),S=".openchamber",A=i.useCallback((O,z)=>{const T=O.replace(/\\/g,"/").replace(/\/+$/,""),$=!T||T==="/"?`/${S}`:`${T}/${S}`;return z?`${$}/${z}`:$},[]),D=i.useCallback(async()=>{if(!(!t||v===!1))try{const z=(await In(t)).map(q=>Pn(t,q)),$=`${A(t,"")}/`,W=z.filter(q=>q.path.startsWith($));P(W)}catch{}},[t,v,A]);i.useEffect(()=>{if(!t)return;let O=!1;return b(!0),M(!0),j(null),x(null),P([]),(async()=>{try{const z=await Ur(t);if(O)return;if(j(z),z){const[T,$]=await Promise.all([_a(t),In(t).catch(()=>[])]);if(!O){T&&x({all:T.all,current:T.current});const W=$.map(de=>Pn(t,de)),ue=`${`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/${S}`}/`,oe=W.filter(de=>de.path.startsWith(ue));P(oe)}}}catch{}finally{O||(b(!1),M(!1))}})(),()=>{O=!0}},[t]),i.useEffect(()=>{if(!t)return;let O=!1;return g(!0),(async()=>{try{const z=await Ln(t);O||h(z.length>0?z:[""])}catch{O||h([""])}finally{O||g(!1)}})(),()=>{O=!0}},[t]),i.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const F=k??a,E=v??o,I=i.useMemo(()=>{const O=[],z=F?.current?`Current (HEAD: ${F.current})`:"Current (HEAD)";return O.push({value:"HEAD",label:z,group:"special"}),F&&(F.all.filter(W=>!W.startsWith("remotes/")).sort((W,q)=>W.localeCompare(q)).forEach(W=>{O.push({value:W,label:W,group:"local"})}),F.all.filter(W=>W.startsWith("remotes/")).map(W=>W.replace(/^remotes\//,"")).sort((W,q)=>W.localeCompare(q)).forEach(W=>{O.push({value:W,label:W,group:"remote"})})),O},[F]),_=i.useRef(null),V=i.useCallback(O=>{u(O),_.current=O},[]),Y=i.useCallback(O=>{s?.id&&(r(s.id,{branchPrefix:O}),_.current=null)},[s?.id,r]),H=i.useCallback(()=>{Y(d)},[d,Y]);i.useEffect(()=>()=>{_.current!==null&&s?.id&&r(s.id,{branchPrefix:_.current})},[s?.id,r]);const L=i.useCallback(O=>{f(O),s?.id&&r(s.id,{baseBranch:O})},[s?.id,r]),U=i.useCallback((O,z)=>{h(T=>{const $=[...T];return $[O]=z,$})},[]),Q=i.useCallback(()=>{h(O=>[...O,""])},[]),J=i.useCallback(O=>{h(z=>z.filter((T,$)=>$!==O))},[]),K=i.useCallback(async()=>{if(!t)return;const O=p.filter(z=>z.trim().length>0);await xm(t,O)},[t,p]),ne=i.useCallback(()=>{K()},[K]),X=i.useCallback(O=>{const z=O.path.replace(/\\/g,"/").replace(/\/+$/,""),T=l.filter(de=>{if(c(de.id)?.path===O.path)return!0;const Se=de.directory;return!!(Se&&Se.replace(/\\/g,"/").replace(/\/+$/,"")===z)}),$=new Set(T.map(de=>de.id)),W=de=>{const je=l.filter(Le=>{const G=Le.parentID;return G&&de.has(G)});if(je.length===0)return[];const Se=new Set(je.map(Le=>Le.id));return[...je,...W(Se)]},q=W($),ue=new Set,oe=[...T,...q].filter(de=>ue.has(de.id)?!1:(ue.add(de.id),!0));Fn.requestDelete({sessions:oe,mode:"worktree",worktree:O})},[l,c]),ae=i.useMemo(()=>l.map(O=>O.id).join(","),[l]);return i.useEffect(()=>{v&&t&&D()},[ae,v,t,D]),t?w?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):E===!1?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Worktree settings are only available for Git repositories."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Branch prefix"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{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(kt,{value:d,onChange:O=>V(O.target.value),onBlur:H,placeholder:"feature",className:"max-w-xs"})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Base branch"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ct,{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(Cs,{value:m,onValueChange:L,children:[e.jsx(Ms,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(cn,{placeholder:"Select a branch"})}),e.jsxs(Ds,{children:[e.jsxs(sn,{children:[e.jsx(Dn,{children:"Default"}),I.filter(O=>O.group==="special").map(O=>e.jsx(qt,{value:O.value,children:O.label},O.value))]}),I.some(O=>O.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(wa,{}),e.jsxs(sn,{children:[e.jsx(Dn,{children:"Local branches"}),I.filter(O=>O.group==="local").map(O=>e.jsx(qt,{value:O.value,children:O.label},O.value))]})]}),I.some(O=>O.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(wa,{}),e.jsxs(sn,{children:[e.jsx(Dn,{children:"Remote branches"}),I.filter(O=>O.group==="remote").map(O=>e.jsx(qt,{value:O.value,children:O.label},O.value))]})]})]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Setup commands"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Run automatically when a new worktree is created. Use ",e.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_WORKTREE_PATH"})," for the project root."]})]}),y?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((O,z)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(kt,{value:O,onChange:T=>U(z,T.target.value),onBlur:ne,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{J(z),setTimeout(K,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(Gt,{className:"h-4 w-4"})})]},z)),e.jsxs("button",{type:"button",onClick:Q,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Zt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Existing worktrees"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(cs,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ct,{sideOffset:8,className:"max-w-xs",children:["Worktrees created under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})," directory. Deleting a worktree will also remove any linked sessions."]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Manage worktrees for this project"})]}),C?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):N.length===0?e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["No worktrees found under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})]}):e.jsx("div",{className:"space-y-1",children:N.map(O=>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:O.label||O.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:O.relativePath||O.path})]}),e.jsx("button",{type:"button",onClick:()=>X(O),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 ${O.branch||O.label}`,children:e.jsx(Bs,{className:"h-4 w-4"})})]},O.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},hS=()=>{const s=_e(d=>d.nativeNotificationsEnabled),r=_e(d=>d.setNativeNotificationsEnabled),t=_e(d=>d.notificationMode),n=_e(d=>d.setNotificationMode),[o,a]=i.useState("default");i.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission)},[]);const l=async d=>{if(d&&typeof Notification<"u"&&Notification.permission==="default")try{const u=await Notification.requestPermission();a(u),u==="granted"?r(!0):Z.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(u){console.error("Failed to request notification permission:",u),Z.error("Failed to request notification permission")}else r(!!(d&&o==="granted"))},c=typeof Notification<"u"&&Notification.permission==="granted";return ln()?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Native Notifications"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Show browser notifications when an assistant completes a task."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable native notifications"}),e.jsx(ya,{checked:s&&c,onCheckedChange:l,className:"data-[state=checked]:bg-status-info"})]}),s&&c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Always notify"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"When off, only notifies if the window is out of focus."})]}),e.jsx(ya,{checked:t==="always",onCheckedChange:d=>n(d?"always":"hidden-only"),className:"data-[state=checked]:bg-status-info"})]}),o==="denied"&&e.jsx("p",{className:"typography-micro text-destructive",children:"Notification permission denied. Enable notifications in your browser settings."}),o==="granted"&&!s&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Notifications are enabled in your browser. Toggle the switch above to activate them."})]}):null},gS=({section:s})=>{const{isMobile:r}=Ht(),t=r&&ln();if(!s)return e.jsxs(xt,{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(ql,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Bf,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Lf,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Of,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(xS,{});case"chat":return e.jsx(yS,{});case"sessions":return e.jsx(bS,{});case"git":return e.jsx(vS,{});case"notifications":return e.jsx(wS,{});default:return null}};return e.jsx(xt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},xS=()=>e.jsx(ql,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),yS=()=>e.jsx(ql,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),bS=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bf,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Lf,{})})]}),vS=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(fS,{}),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(pS,{})]})]}),wS=()=>e.jsx(hS,{}),jS=[{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}],SS=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=Ht(),n=t&&ln(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>zt(),[]),c=i.useMemo(()=>ln(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>jS.filter(m=>!(m.webOnly&&!c||m.hideInVSCode&&l)),[c,l]),u=o?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",u),children:[e.jsx(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:d.map(m=>{const f=s===m.id;return e.jsx("div",{className:R("group relative rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{onClick:()=>r(m.id),className:"w-full text-left flex flex-col gap-0 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:m.label}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:m.items.join(" · ")})]})},m.id)})}),n&&e.jsx("div",{className:"border-t px-3 py-4",children:e.jsx(Of,{})})]})},kS=s=>{let r=Pf.filter(o=>o.id!=="sessions");s&&(r=r.filter(o=>o.id!=="git-identities"));const t=r.find(o=>o.id==="settings"),n=r.filter(o=>o.id!=="settings");return t?[t,...n]:r},Ei=200,Ii=500,NS=264,CS=940,al=({onClose:s,forceMobile:r})=>{const t=Ht(),n=r??t.isMobile,[o,a]=i.useState("settings"),[l,c]=i.useState("visual"),[d,u]=i.useState(!1),[m,f]=i.useState(()=>typeof window<"u"?Math.min(Ii,Math.max(Ei,Math.floor(window.innerWidth*.2))):NS),[p,h]=i.useState(!1),[y,g]=i.useState(!1),[w,b]=i.useState(0),v=i.useRef(null),j=i.useRef(0),k=i.useRef(m),[x,N]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),P=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),C=i.useMemo(()=>zt(),[]),M=i.useMemo(()=>kS(C),[C]);i.useEffect(()=>{typeof window>"u"||N(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const z=v.current;if(!z)return;const T=new ResizeObserver($=>{for(const W of $)b(W.contentRect.width)});return T.observe(z),b(z.clientWidth),()=>T.disconnect()},[]);const S=Lt(z=>z.projects),A=Lt(z=>z.activeProjectId),D=Lt(z=>z.setActiveProject),F=i.useMemo(()=>[...S].sort((z,T)=>(z.label||z.path).localeCompare(T.label||T.path)),[S]),E=i.useMemo(()=>F.length===0?null:F.find(z=>z.id===A)??F[0],[A,F]),I=i.useCallback(z=>z.replace(/[-_]/g," ").replace(/\b\w/g,T=>T.toUpperCase()),[]),_=i.useMemo(()=>{if(!E)return"Project";const z=E.label&&E.label.trim().length>0?E.label:E.path.split("/").filter(Boolean).pop()||E.path;return I(z)},[E,I]),V=F.length>0&&!C,Y=w===0||w>=CS;i.useEffect(()=>{if(o==="agents"){setTimeout(()=>{Hr.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{Wr.getState().loadCommands()},0);return}o==="skills"&&(Qs.getState().loadSkills(),go.getState().loadCatalog())},[A,o]),i.useEffect(()=>{if(typeof window>"u")return;const z=()=>{if(!p){const T=Math.min(Ii,Math.max(Ei,Math.floor(window.innerWidth*.2)));f(T)}};return window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[p]),i.useEffect(()=>{if(!y)return;const z=$=>{const W=$.clientX-j.current,q=Math.min(Ii,Math.max(Ei,k.current+W));f(q),h(!0)},T=()=>g(!1);return window.addEventListener("pointermove",z),window.addEventListener("pointerup",T,{once:!0}),()=>{window.removeEventListener("pointermove",z),window.removeEventListener("pointerup",T)}},[y]);const H=z=>{g(!0),j.current=z.clientX,k.current=m,z.preventDefault()},L=i.useCallback(async z=>{if(!z.target.closest("button, a, input, select, textarea")&&z.button===0&&x)try{const{getCurrentWindow:T}=await ls(async()=>{const{getCurrentWindow:W}=await import("./vendor-.bun-w0O-Y8Mh.js").then(q=>q.cB);return{getCurrentWindow:W}},__vite__mapDeps([0,1]));await T().startDragging()}catch(T){console.error("Failed to start window dragging:",T)}},[x]),U=i.useCallback(async z=>{if(z.button===0&&x)try{const{getCurrentWindow:T}=await ls(async()=>{const{getCurrentWindow:W}=await import("./vendor-.bun-w0O-Y8Mh.js").then(q=>q.cB);return{getCurrentWindow:W}},__vite__mapDeps([0,1]));await T().startDragging()}catch(T){console.error("Failed to start window dragging:",T)}},[x]),Q=i.useCallback(z=>{a(z),u(!1)},[]),J=i.useCallback(()=>{n&&u(!0)},[n]),K=()=>{switch(o){case"settings":return e.jsx(SS,{selectedSection:l,onSelectSection:z=>{c(z),J()}});case"agents":return e.jsx(M0,{onItemSelect:J});case"commands":return e.jsx(O0,{onItemSelect:J});case"skills":return e.jsx($0,{onItemSelect:J});case"providers":return e.jsx(Q0,{onItemSelect:J});case"git-identities":return e.jsx(rS,{onItemSelect:J});default:return null}},ne=()=>{switch(o){case"agents":return e.jsx(R0,{});case"commands":return e.jsx(_0,{});case"skills":return e.jsx(q0,{});case"providers":return e.jsx(eS,{});case"git-identities":return e.jsx(iS,{});case"settings":return e.jsx(gS,{section:l});default:return null}},X=es(),ae=i.useMemo(()=>x&&P?"pl-[5.75rem]":"",[x,P]),O=x&&P;return e.jsxs("div",{ref:v,className:R("flex h-full flex-col overflow-hidden",x?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:L,className:R("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&ae,x?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[n&&d&&e.jsx("button",{type:"button",onClick:()=>u(!1),"aria-label":"Back",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(Wu,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:R("flex items-center",n?"gap-1":"h-full"),children:[!n&&O&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),M.map(({id:z,label:T,icon:$})=>{const W=o===z,q=$;return n?e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>Q(z),className:R("relative flex h-9 w-9 items-center justify-center rounded-md transition-colors","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",W?"text-foreground":"text-muted-foreground"),"aria-pressed":W,"aria-label":T,children:e.jsx(q,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(ct,{children:e.jsx("p",{children:T})})]},z):e.jsxs(i.Fragment,{children:[e.jsxs("button",{onClick:()=>Q(z),onMouseDown:W?U:void 0,className:R("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",W?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",W?"text-foreground":"text-muted-foreground"),"aria-pressed":W,"aria-label":T,children:[e.jsx(q,{className:"h-4 w-4",weight:"regular"}),Y&&e.jsx("span",{children:T})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},z)})]}),(s||V)&&e.jsxs("div",{className:R("flex items-center gap-2",n?"":"pr-3"),children:[V&&e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:_,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(Js,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:_,className:R("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 text-foreground outline-none hover:text-foreground/80 focus-visible:ring-2 focus-visible:ring-ring",!n&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:_}),e.jsx(Ft,{className:"size-4 opacity-50"})]})}),e.jsx(Jt,{align:"end",className:"w-auto",children:e.jsx(ha,{value:E?.id??"",onValueChange:z=>{z&&D(z)},children:F.map(z=>{const T=z.label?.trim()?z.label.trim():z.path.split("/").filter(Boolean).pop()||z.path,$=I(T);return e.jsx(ga,{value:z.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:$})},z.id)})})})]}),s&&e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",className:R("inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",!n&&"app-region-no-drag"),children:e.jsx(Gt,{className:"h-5 w-5"})})}),e.jsx(ct,{children:e.jsxs("p",{children:["Close Settings (",X,"+,)"]})})]})]})]}),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(is,{children:ne()})}):e.jsx("div",{className:R("flex-1 overflow-hidden",C?"bg-background":"bg-sidebar"),children:e.jsx(is,{children:K()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:R("relative overflow-hidden border-r",x?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":C?"bg-background":"bg-sidebar",y?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",y?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:H,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(is,{children:K()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(is,{children:ne()})})]})})]})},MS=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:l,isMultiRunLauncherOpen:c,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=_e(),{isMobile:m}=Ht(),[f,p]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");i.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),mv({enabled:!0});const h=Ta(b=>b.checkForUpdates);i.useEffect(()=>{const b=setTimeout(()=>{h()},3e3);return()=>clearTimeout(b)},[h]),i.useEffect(()=>{_e.getState().isMobile!==m&&t(m)},[m,t]),i.useEffect(()=>{if(typeof window>"u")return;let b;const v=()=>{b!==void 0&&window.clearTimeout(b),b=window.setTimeout(()=>{_e.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v),b!==void 0&&window.clearTimeout(b)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const b=document.documentElement;let v=0,j=!1,k=0,x=null;const N=_e.getState().setKeyboardOpen,P=()=>{x&&(x.style.setProperty("--oc-keyboard-avoid-offset","0px"),x.removeAttribute("data-keyboard-avoid-active"),x=null)},C=E=>{if(!E)return null;const I=E.closest("[data-keyboard-avoid]");if(I)return I;if(E.classList.contains("overlay-scrollbar-container")){const _=E.parentElement;if(_ instanceof HTMLElement)return _}return E},M=()=>{v=0,j=!0,b.style.setProperty("--oc-keyboard-inset","0px"),N(!1)},S=()=>{const E=window.visualViewport,I=E?Math.round(E.height):window.innerHeight,_=E?Math.max(0,Math.round(E.offsetTop)):0;b.style.setProperty("--oc-visual-viewport-offset-top",`${_}px`);const V=document.activeElement,Y=V?.tagName,L=Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||!!V?.isContentEditable,U=Math.round(b.clientHeight||window.innerHeight),Q=I+_,J=Math.max(0,U-Q),ne=J>=(L?120:180)?J:0;if(j)ne===0&&(j=!1),v=0;else if(v===0)ne>0&&L&&(v=ne);else{const z=!L&&I>k+6;ne===0?(v=0,N(!1)):z?M():(ne>0&&L||ne>v)&&(v=ne,N(!0))}b.style.setProperty("--oc-keyboard-inset",`${v}px`),k=I;const ae=/iPad|iPhone|iPod/.test(navigator.userAgent)&&v>0?34:0;b.style.setProperty("--oc-keyboard-home-indicator",`${ae}px`);const O=L?C(V):null;if(!m||!O||!V)P();else{O!==x&&(P(),x=O);const z=_+I,$=V.getBoundingClientRect().bottom-z,W=8,q=Math.max(v,ne),ue=$>W&&q>0?Math.min($,q):0,oe=x;oe&&(oe.style.setProperty("--oc-keyboard-avoid-offset",`${ue}px`),oe.setAttribute("data-keyboard-avoid-active","true"))}if(m&&L){const z=document.scrollingElement;z&&z.scrollTop!==0&&(z.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};S();const A=window.visualViewport;A?.addEventListener("resize",S),A?.addEventListener("scroll",S),window.addEventListener("resize",S),window.addEventListener("orientationchange",S);const D=E=>{const I=E.target;if(!I)return;const _=I.tagName;(_==="INPUT"||_==="TEXTAREA"||_==="SELECT"||I.isContentEditable)&&(j=!1),S()};document.addEventListener("focusin",D,!0);const F=E=>{const I=E.target;if(!I)return;const _=I.tagName;if(_==="INPUT"||_==="TEXTAREA"||_==="SELECT"||I.isContentEditable){const Y=E.relatedTarget,H=Y?.tagName;if(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||Y?.isContentEditable)return;M()}};return document.addEventListener("focusout",F,!0),()=>{A?.removeEventListener("resize",S),A?.removeEventListener("scroll",S),window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S),document.removeEventListener("focusin",D,!0),document.removeEventListener("focusout",F,!0),P()}},[m]);const y=i.useMemo(()=>{switch(r){case"git":return e.jsx(Jj,{});case"diff":return e.jsx(Sb,{});case"terminal":return e.jsx(d0,{});case"files":return e.jsx(w0,{});default:return null}},[r]),g=r==="chat",w=a&&!m;return e.jsx(sv,{children:e.jsxs("div",{className:R("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(Bb,{}),e.jsx(Hb,{}),e.jsx(Xb,{}),m?e.jsxs(e.Fragment,{children:[!(a||c)&&e.jsx(Vc,{}),e.jsx("div",{className:R("flex flex-1 overflow-hidden bg-background",(a||c)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:R("absolute inset-0",!g&&"invisible"),children:e.jsx(is,{children:e.jsx(so,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(is,{children:y})})]})}),e.jsx(js,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(va,{mobileVariant:!0})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(is,{children:e.jsx(cd,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(is,{children:e.jsx(al,{onClose:()=>l(!1)})})})]}):e.jsxs(e.Fragment,{children:[!w&&e.jsx(Rb,{isOpen:s,isMobile:m,children:e.jsx(va,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:R("absolute inset-0 flex flex-col",(w||c)&&"invisible"),children:[e.jsx(Vc,{}),e.jsx("div",{className:"flex flex-1 overflow-hidden bg-background",children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:R("absolute inset-0",!g&&"invisible"),children:e.jsx(is,{children:e.jsx(so,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(is,{children:y})})]})})]}),c&&e.jsx("div",{className:R("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(is,{children:e.jsx(cd,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),w&&e.jsx("div",{className:R("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(is,{children:e.jsx(al,{onClose:()=>l(!1)})})})]}),!w&&e.jsx(Eb,{})]})})},DS=550,AS=1400,ES=280,IS=()=>{const s=Nr(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),t=i.useMemo(()=>{const F=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof F=="string"&&F.trim().length>0?F.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[l,c]=i.useState(0),d=i.useRef(null),u=he(F=>F.currentSessionId),m=he(F=>F.sessions),f=i.useMemo(()=>u?m.find(F=>F.id===u)?.title||"Session":null,[u,m]),p=he(F=>!!F.newSessionDraft?.open),h=he(F=>F.openNewSessionDraft),[y,g]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),w=nt(F=>F.isInitialized),b=nt(F=>F.initializeApp),v=he(F=>F.loadSessions),j=he(F=>F.loadMessages),k=he(F=>F.messages),[x,N]=i.useState(()=>w),[P,C]=i.useState(!1),M=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const F=s.vscode;F&&F.executeCommand("openchamber.setActiveSession",u,f)},[f,u,s.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const S=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const F=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(F==="connected"||F==="connecting"||F==="error"||F==="disconnected")&&g(F);const E=I=>{const V=I.detail?.status;(V==="connected"||V==="connecting"||V==="error"||V==="disconnected")&&g(V)};return window.addEventListener("openchamber:connection-status",E),()=>window.removeEventListener("openchamber:connection-status",E)},[]),i.useEffect(()=>{const F=E=>{const _=E.detail?.view;_==="settings"?a("settings"):_==="chat"?a("chat"):_==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",F),()=>window.removeEventListener("openchamber:navigate",F)},[]),i.useEffect(()=>{(async()=>{if(P||x||y!=="connected")return;const E=Date.now();if(!(E-M.current<750)){M.current=E,C(!0);try{const I=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();I&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:w}),w||await b();const _=nt.getState();if(!_.isInitialized||!_.isConnected||_.providers.length===0||_.agents.length===0)return;await v();const V=he.getState().error;if(I&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:_.providers.length,agents:_.agents.length,sessions:he.getState().sessions.length,sessionsError:V}),typeof V=="string"&&V.length>0)return;N(!0)}catch{}finally{C(!1)}}})()},[y,w,x,b,P,v]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!x||y!=="connected")){if(!t){n.current=!0,h();return}m.some(F=>F.id===t)&&(n.current=!0,he.getState().setCurrentSession(t))}},[y,x,t,h,m,r]),i.useEffect(()=>{(async()=>{if(!x||y!=="connected"||o!=="chat"||p||!u)return;if(!(k.has(u)&&(k.get(u)?.length||0)>0))try{await j(u)}catch{}})()},[y,u,o,x,j,k,p]),i.useEffect(()=>{const F=d.current;if(!F)return;const E=new ResizeObserver(I=>{for(const _ of I)c(_.contentRect.width)});return E.observe(F),c(F.clientWidth),()=>E.disconnect()},[]);const A=l>0&&l<DS,D=l>=AS;return i.useEffect(()=>{D&&o==="sessions"&&r==="sidebar"&&a("chat")},[D,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(Bo,{title:m.find(F=>F.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(is,{children:e.jsx(so,{})})})]}):o==="settings"?e.jsx(al,{onClose:()=>a(D?"chat":"sessions"),forceMobile:A}):D?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:ES},children:e.jsx(va,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(Bo,{title:p&&!u?"New session":m.find(F=>F.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(is,{children:e.jsx(so,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Bo,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(va,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Bo,{title:p&&!u?"New session":m.find(F=>F.id===u)?.title||"Chat",showBack:!0,onBack:S,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(is,{children:e.jsx(so,{})})})]})})},Bo=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c})=>{const{getCurrentModel:d}=nt(),u=he(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,y=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&&t&&e.jsx("button",{onClick:t,className:"inline-flex h-7 w-7 items-center justify-center text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(zu,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:s,children:s}),n&&e.jsx("button",{onClick:n,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"New session",children:e.jsx(Zt,{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(ao,{className:"h-5 w-5"})}),l&&e.jsx(Yi,{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(nn,{className:"h-5 w-5"})}),c&&y&&y.totalTokens>0&&e.jsx(qi,{totalTokens:y.totalTokens,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit??0,size:"compact"})]})},il=".openchamber",zo=s=>{const r=Lt.getState(),t=r.activeProjectId,n=t?r.projects.find(c=>c.id===t)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof s=="string"?Rt(s):"",a=`/${il}/`,l=o.indexOf(a);return l>0?o.slice(0,l):s?Rt(s):null},Rt=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},mu=s=>{const r=Rt(s);return!r||r==="/"?`/${il}`:`${r}/${il}`},PS=(s,r)=>{const t=Rt(s);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const l=Rt(o);if(l)return l}const a=typeof n.name=="string"?n.name.trim():"";return!a||!t?null:`${t}/${a}`}).filter(n=>!!n)},TS=async s=>{const r=Rt(s);if(!r)return[];try{const n=(await Ee.listLocalDirectory(r)).filter(o=>o.isDirectory);return PS(r,n)}catch{return[]}},Ir=(s,r)=>{const t=Rt(s),n=Rt(r);if(!t||!n)return!1;if(t===n)return!0;const o=n==="/"?"/":`${n}/`;return t.startsWith(o)},zf=async(s,r)=>{const t=Rt(r);if(!t)return t;try{const n=await s.path.get({directory:t});return Rt(n.data?.directory??"")||t}catch{return t}},Wf=async(s,r)=>{const t=Rt(r);if(!t)return[];const n=await zf(s,t),o=l=>l.filter(c=>{const d=Rt(c.directory??"");return d?Ir(d,t)||n!==t&&Ir(d,n):!1}),a=async l=>{const c=await s.session.list({directory:l});return Array.isArray(c.data)?c.data:[]};try{const l=o(await a(t));if(l.length>0)return l}catch{}if(n&&n!==t)try{const l=o(await a(n));if(l.length>0)return l}catch{}try{const l=await s.session.list(void 0),c=Array.isArray(l.data)?l.data:[];return o(c)}catch{return[]}},FS=async(s,r)=>{const t=new Map;s.sessions.forEach(o=>{o.worktreeMetadata&&t.set(Rt(o.path),o.worktreeMetadata)});const n=Array.from(new Set(s.sessions.map(o=>Rt(o.path)))).filter(Boolean).filter(o=>!t.has(o));if(n.length===0)return t;try{const o=await In(r),a=new Map(o.map(l=>[Rt(l.worktree),l]));n.forEach(l=>{const c=a.get(l);c&&t.set(l,Pn(r,c))})}catch{}return t},Pi=async s=>{const{apiClient:r,group:t,projectDirectory:n,worktreePaths:o}=s,a=await FS(t,n),l=he.getState(),c=Array.from(new Set(o.map(p=>Rt(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<c.length;){const p=c[u];u+=1;const h=t.sessions.filter(v=>Rt(v.path)===p).map(v=>v.id),y=l.getSessionsByDirectory(p),g=Array.isArray(y)?y.map(v=>v.id):[];let w=[];if(g.length===0)try{w=(await Wf(r,p)).map(j=>j.id)}catch{w=[]}const b=Array.from(new Set([...g,...w,...h].filter(Boolean)));m.push({worktreePath:p,sessionIds:b,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,c.length)},f)),m};function RS(s){if(!s)return null;const r=s.split("/");if(r.length<3)return null;const t=r[0];if(!t||t.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),l=r.length>=4&&!isNaN(a)&&String(a)===o,c=l?r.slice(2,-1):r.slice(2);if(c.length===0)return null;const d=c.join("/");return{groupSlug:t,provider:n,model:d,index:l?a:1}}const Fr=Kt()(ss((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=yt.getState().currentDirectory,n=zo(t);if(!n){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Rt(n),a=mu(o),l=r().groups;s({isLoading:!0,error:null});try{const c=Ee.getApiClient(),d=await zf(c,o),u=mu(d);let m=new Map,f=[];try{f=await In(o),m=new Map(f.map(j=>[Rt(j.worktree),j]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const k=await c.session.list({directory:o}),x=Array.isArray(k.data)?k.data:[];if(x.some(N=>{const P=Rt(N.directory??"");return Ir(P,a)||Ir(P,u)}))return x}catch{}const j=await c.session.list(void 0);return Array.isArray(j.data)?j.data:[]},h=async j=>{const k=new Map,x=5;let N=0;const P=async()=>{for(;N<j.length;){const C=j[N];N+=1;const M=Rt(C);if(M)try{(await Wf(c,M)).forEach(A=>k.set(A.id,A))}catch(S){console.debug("Failed to fetch sessions from worktree:",M,S)}}};return await Promise.all(Array.from({length:Math.min(x,j.length)},P)),Array.from(k.values())};let g=(await p()).filter(j=>{const k=Rt(j.directory??"");return k?Ir(k,a)||Ir(k,u):!1});if(g.length===0){const j=new Set;f.map(x=>Rt(x.worktree)).filter(x=>Ir(x,a)||Ir(x,u)).forEach(x=>j.add(x));const k=Array.from(new Set([a,u].map(x=>Rt(x)).filter(Boolean)));await Promise.all(k.map(async x=>{(await TS(x)).forEach(P=>j.add(P))})),j.size>0&&(g=await h(Array.from(j)))}const w=new Map;for(const j of g){const k=j.time?.updated??0;w.set(j.id,typeof k=="number"?k:0)}const b=new Map;for(const j of g){const k=RS(j.title);if(!k)continue;const x=Rt(j.directory),N=m.get(x),P={id:j.id,path:x,providerId:k.provider,modelId:k.model,instanceNumber:k.index,branch:N?.branch??"",displayLabel:`${k.provider}/${k.model}`,worktreeMetadata:N?Pn(o,N):void 0},C=b.get(k.groupSlug);C?C.push(P):b.set(k.groupSlug,[P])}const v=Array.from(b.entries()).map(([j,k])=>{const x=k.reduce((N,P)=>{const C=w.get(P.id)??0;return Math.max(N,C)},0);return{name:j,sessions:k.sort((N,P)=>{const C=N.providerId.localeCompare(P.providerId);if(C!==0)return C;const M=N.modelId.localeCompare(P.modelId);return M!==0?M:N.instanceNumber-P.instanceNumber}),lastActive:x||Date.now(),sessionCount:k.length}});v.sort((j,k)=>j.name.localeCompare(k.name)),s({groups:v,isLoading:!1,error:null})}catch(c){console.error("Failed to load agent groups:",c),s({groups:l.length>0?l:[],isLoading:!1,error:c instanceof Error?c.message:"Failed to load agent groups"})}},selectGroup:t=>{const{groups:n}=r(),o=n.find(a=>a.name===t);s({selectedGroupName:t,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:t=>{s({selectedSessionId:t})},deleteGroup:async t=>{const n=r().groups.find(l=>l.name===t);if(!n)return!1;const o=yt.getState().currentDirectory,a=zo(o);if(!a)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const l=Ee.getApiClient(),c=await Pi({apiClient:l,group:n,projectDirectory:Rt(a),worktreePaths:n.sessions.map(f=>f.path)}),d=he.getState(),u=new Set;c.forEach(({worktreePath:f,sessionIds:p,metadata:h})=>{p.forEach(y=>{u.add(y),h&&(d.setWorktreeMetadata(y,h),d.setSessionDirectory(y,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&s({error:"Failed to delete some sessions"}),r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(l){return s({error:l instanceof Error?l.message:"Failed to delete group"}),!1}finally{s({isLoading:!1})}},deleteGroupWorktree:async(t,n)=>{const o=r().groups.find(d=>d.name===t);if(!o)return!1;const a=Rt(n);if(!a)return!1;const l=yt.getState().currentDirectory,c=zo(l);if(!c)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const d=Ee.getApiClient(),u=await Pi({apiClient:d,group:o,projectDirectory:Rt(c),worktreePaths:[a]}),m=he.getState(),f=new Set;u.forEach(({worktreePath:y,sessionIds:g,metadata:w})=>{g.forEach(b=>{f.add(b),w&&(m.setWorktreeMetadata(b,w),m.setSessionDirectory(b,y))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups();const h=r().groups.find(y=>y.name===t);if(!h)return r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===t){const y=r().selectedSessionId,g=new Set(h.sessions.map(w=>w.id));(!y||!g.has(y))&&s({selectedSessionId:h.sessions[0]?.id??null})}return p.length===0}catch(d){return s({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{s({isLoading:!1})}},keepOnlyGroupWorktree:async(t,n)=>{const o=r().groups.find(m=>m.name===t);if(!o)return!1;const a=Rt(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Rt(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=yt.getState().currentDirectory,u=zo(d);if(!u)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const m=Ee.getApiClient(),f=await Pi({apiClient:m,group:o,projectDirectory:Rt(u),worktreePaths:c}),p=he.getState(),h=new Set;f.forEach(({worktreePath:g,sessionIds:w,metadata:b})=>{w.forEach(v=>{h.add(v),b&&(p.setWorktreeMetadata(v,b),p.setSessionDirectory(v,g))})});const{failedIds:y}=await p.deleteSessions(Array.from(h),{archiveWorktree:!0,silent:!0});if(y.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===t){const g=r().groups.find(b=>b.name===t),w=g?.sessions.find(b=>Rt(b.path)===a)??g?.sessions[0]??null;s({selectedSessionId:w?.id??null})}return y.length===0}catch(m){return s({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{s({isLoading:!1})}},getSelectedGroup:()=>{const{groups:t,selectedGroupName:n}=r();return n?t.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:t}=r(),n=r().getSelectedGroup();return!n||!t?null:n.sessions.find(o=>o.id===t)??null},clearError:()=>{s({error:null})}}),{name:"agent-groups-store"})),OS=s=>{const t=Date.now()-s,n=Math.floor(t/(60*1e3)),o=Math.floor(t/(3600*1e3)),a=Math.floor(t/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},_S=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=Fr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),Z.info(`Deleting "${s.name}"...`),await u(s.name))Z.success(`Deleted "${s.name}"`);else{const p=Fr.getState().error;Z.error(p||`Failed to delete "${s.name}"`)}d(!1),l(!1)},[u,s.name,c]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),onClick:t,children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col gap-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[e.jsx(_t,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:OS(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(Yt,{open:n,onOpenChange:o,children:[e.jsx(Xt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:f=>f.stopPropagation(),children:e.jsx(Lr,{className:"h-3.5 w-3.5"})})}),e.jsx(Jt,{align:"end",className:"min-w-[140px]",children:e.jsx(It,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(us,{open:a,onOpenChange:l,children:e.jsxs(ms,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(hs,{children:[e.jsx(gs,{children:"Delete agent group"}),e.jsxs(vs,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(tr,{children:[e.jsx(De,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},$S=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Fr(),f=yt(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(b=>b.name.toLowerCase().includes(w))},[o,d]),y=l?h:h.slice(0,p),g=h.length-p;return e.jsxs("div",{className:R("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",s),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Xs,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(kt,{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(De,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Zt,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label",children:"New Agent Group"})]})}),e.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),u&&e.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."})]}),e.jsxs(xt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[y.map(w=>e.jsx(_S,{group:w,isSelected:r===w.name,onSelect:()=>t?.(w.name)},w.name)),!l&&g>0&&e.jsxs("button",{type:"button",onClick:()=>c(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",g,")"]}),l&&h.length>p&&e.jsx("button",{type:"button",onClick:()=>c(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&h.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},LS=10*1024*1024,BS=5,zS=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=i.useState(""),[a,l]=i.useState(""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState("HEAD"),[h,y]=i.useState([]),[g,w]=i.useState(!1),[b,v]=i.useState([]),[j,k]=i.useState(!1),[x,N]=i.useState(!1),P=i.useRef(null),C=i.useRef(null),M=yt(X=>X.currentDirectory??null),{isGitRepository:S,isLoading:A}=Wl(M),D=i.useMemo(()=>{if(typeof window>"u")return null;const X=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof X=="string"&&X.trim().length>0?X.trim():null},[]),F=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),E=Lt(X=>X.activeProjectId),I=Lt(X=>X.projects),_=i.useMemo(()=>{if(F&&D)return D;if(E){const T=I.find($=>$.id===E);if(T?.path)return T.path}const X=M??D;if(!X)return null;const ae=X.replace(/\\/g,"/").replace(/\/+$/,"")||X,z=ae.indexOf("/.openchamber/");return z>0?ae.slice(0,z):ae.endsWith("/.openchamber")?ae.slice(0,ae.length-13):ae},[E,I,M,D,F]);i.useEffect(()=>{if(!_)return;let X=!1;return N(!0),(async()=>{try{const ae=await Ln(_);X||v(ae)}catch{}finally{X||N(!1)}})(),()=>{X=!0}},[_]);const V=i.useCallback(X=>{c.length>=BS||d(ae=>[...ae,X])},[c.length]),Y=i.useCallback(X=>{d(ae=>ae.filter((O,z)=>z!==X))},[]),H=i.useCallback((X,ae)=>{d(O=>O.map((z,T)=>T===X?ae:z))},[]),L=async X=>{const ae=X.target.files;if(!ae)return;let O=0;for(let z=0;z<ae.length;z++){const T=ae[z];if(T.size>LS){Z.error(`File "${T.name}" is too large (max 10MB)`);continue}try{const $=await new Promise((q,ue)=>{const oe=new FileReader;oe.onload=()=>q(oe.result),oe.onerror=ue,oe.readAsDataURL(T)}),W={id:ja(),filename:T.name,mimeType:T.type||"application/octet-stream",size:T.size,dataUrl:$};y(q=>[...q,W]),O++}catch($){console.error("File attach failed",$),Z.error(`Failed to attach "${T.name}"`)}}O>0&&Z.success(`Attached ${O} file${O>1?"s":""}`),P.current&&(P.current.value="")},U=X=>{y(ae=>ae.filter(O=>O.id!==X))},Q=g||t,J=!!(n.trim()&&a.trim()&&c.length>=1&&S&&!A),K=async X=>{if(X.preventDefault(),!(!J||Q)){w(!0);try{const ae=c.map(({providerID:T,modelID:$,displayName:W,variant:q})=>({providerID:T,modelID:$,displayName:W,variant:q})),O=h.length>0?h.map(T=>({mime:T.mimeType,filename:T.filename,url:T.dataUrl})):void 0,z=b.filter(T=>T.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:ae,agent:u||void 0,worktreeBaseBranch:f,files:O,setupCommands:z.length>0?z:void 0}),o(""),l(""),d([]),m(""),y([]),p("HEAD")}catch(ae){console.error("Failed to create agent group:",ae),Z.error("Failed to create agent group")}finally{w(!1)}}},ne=X=>{Bl(X)||X.key==="Enter"&&!X.shiftKey&&(X.preventDefault(),J&&!Q&&K(X))};return e.jsx("div",{className:R("flex flex-col items-center justify-center h-full w-full p-4",s),children:e.jsxs("form",{onSubmit:K,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(kt,{id:"group-name",value:n,onChange:X=>o(X.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[e.jsx(_t,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Ym,{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(xo,{open:j,onOpenChange:k,children:[e.jsxs(La,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",b.filter(X=>X.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",b.filter(X=>X.trim()).length," configured)"]})]}),e.jsx(Ft,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",j&&"rotate-180")})]}),e.jsx(yo,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),x?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[b.map((X,ae)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(kt,{value:X,onChange:O=>{const z=[...b];z[ae]=O.target.value,v(z)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const O=b.filter((z,T)=>T!==ae);v(O)},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(Gt,{className:"h-4 w-4"})})]},ae)),e.jsxs("button",{type:"button",onClick:()=>v([...b,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Zt,{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(Xm,{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(Qm,{selectedModels:c,onAdd:V,onRemove:Y,onUpdate:H,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(Ns,{ref:C,id:"prompt",value:a,onChange:X=>l(X.target.value),onKeyDown:ne,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(X=>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:[X.mimeType.startsWith("image/")?e.jsx(hr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(cr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:X.filename,children:X.filename}),e.jsx("button",{type:"button",onClick:()=>U(X.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Gt,{className:"h-3.5 w-3.5"})})]},X.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:P,type:"file",multiple:!0,className:"hidden",onChange:L,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>P.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(Ru,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[c.length," model",c.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!J||Q,className:R("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",J?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:Q?e.jsx(Qh,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Ma,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},WS=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Fr(),{setCurrentSession:l,currentSessionId:c}=he(),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useMemo(()=>t?s.sessions.find(j=>j.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),h=i.useCallback(j=>{n(j.id),l(j.id)},[n,l]);i.useEffect(()=>{if(s.sessions.length>0){const j=t?s.sessions.find(k=>k.id===t)??s.sessions[0]:s.sessions[0];j&&(j.id!==c&&l(j.id),t||n(j.id))}},[s.name,s.sessions,t,c,n,l]);const y=p?.id===c,g=i.useCallback(()=>{if(!p?.path){Z.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{Z.success("Worktree path copied")}).catch(()=>{Z.error("Failed to copy path")})},[p?.path]),w=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),b=i.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),v=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(Z.info("Removing worktree..."),await o(s.name,d.path))Z.success("Worktree removed");else{const k=Fr.getState().error;Z.error(k||"Failed to remove worktree");return}else if(Z.info("Removing other worktrees..."),await a(s.name,d.path))Z.success("Removed other worktrees");else{const k=Fr.getState().error;Z.error(k||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,s.name,m,a,d]);return e.jsxs("div",{className:R("flex h-full flex-col bg-background",r),children:[e.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(_t,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),s.sessions.length>0&&e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs(De,{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(ds,{providerId:p.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsx("span",{className:"truncate typography-body",children:p.modelId}),p.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",p.instanceNumber]})]})}),e.jsx(Ft,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Jt,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:s.sessions.map(j=>e.jsxs(It,{onClick:()=>h(j),className:"flex items-center gap-2 py-2",children:[e.jsx(ds,{providerId:j.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:j.modelId}),j.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",j.instanceNumber]})]}),j.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(_t,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:j.worktreeMetadata?.label||j.branch})]})]}),p?.id===j.id&&e.jsx(Bt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},j.id))})]})}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(De,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Lr,{className:"h-4 w-4"})})}),e.jsxs(Jt,{align:"end",className:"min-w-[220px]",children:[e.jsx(It,{onSelect:j=>{j.preventDefault(),w()},variant:"destructive",children:"Remove this worktree"}),e.jsx(It,{onSelect:j=>{j.preventDefault(),b()},children:"Leave this one, remove others"}),e.jsxs(It,{onClick:j=>{j.stopPropagation(),g()},disabled:!p?.path,children:[e.jsx(er,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(us,{open:!!d,onOpenChange:j=>{j||u(null)},children:e.jsxs(ms,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(hs,{children:[e.jsx(gs,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(vs,{children:d?.kind==="remove"?e.jsxs(e.Fragment,{children:["Remove ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):e.jsxs(e.Fragment,{children:["Keep ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label})," and remove the other worktrees in ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"."]})})]}),e.jsxs(tr,{children:[e.jsx(De,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(De,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{v()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?y?e.jsx(Sf,{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(ds,{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"})})})]})},HS=({className:s})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[t,n]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=nt(j=>j.isInitialized),a=nt(j=>j.initializeApp),l=he(j=>j.loadSessions),c=yt(j=>j.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Fr(),{createMultiRun:h,isLoading:y}=to();i.useEffect(()=>{if(!r)return;const j=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(j==="connected"||j==="connecting"||j==="error"||j==="disconnected")&&n(j);const k=x=>{const P=x.detail?.status;(P==="connected"||P==="connecting"||P==="error"||P==="disconnected")&&n(P)};return window.addEventListener("openchamber:connection-status",k),()=>window.removeEventListener("openchamber:connection-status",k)},[r]),i.useEffect(()=>{if(!r||t!=="connected")return;const j=Date.now();if(j-d.current<750)return;d.current=j;const k=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof k=="string"&&k.trim().length>0)try{c(k,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const N=nt.getState();if(!N.isInitialized||!N.isConnected||N.providers.length===0||N.agents.length===0)return;await l(),rs()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:N.providers.length,agents:N.agents.length,sessions:he.getState().sessions.length})}catch{}})()},[t,o,a,r,l,c]);const g=i.useCallback(j=>{m(j)},[m]),w=i.useCallback(()=>{m(null)},[m]),b=i.useCallback(async j=>{Z.info(`Creating agent group "${j.name}" with ${j.models.length} model(s)...`);const k=await h(j);if(k){Z.success(`Agent group "${j.name}" created with ${k.sessionIds.length} session(s)`);const x=k.groupSlug,N=async(P=6)=>{for(let C=0;C<P;C+=1){if(await p(),Fr.getState().groups.some(S=>S.name===x))return!0;await new Promise(S=>setTimeout(S,500))}return!1};try{await he.getState().loadSessions()}catch{}await N(),m(x)}else{const x=to.getState().error;Z.error(x||"Failed to create agent group")}},[h,p,m]),v=f();return e.jsxs("div",{className:R("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx($S,{selectedGroupName:u,onGroupSelect:g,onNewAgent:w})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(WS,{group:v}):e.jsx(zS,{onCreateGroup:b,isCreating:y})})]})},Ti=({...s})=>{const{theme:r="system"}=Yh();return e.jsx(Xh,{theme:r,className:"toaster group",closeButton:!0,style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--error-bg":"var(--popover)","--error-text":"var(--popover-foreground)","--error-border":"var(--border)","--success-bg":"var(--popover)","--success-text":"var(--popover-foreground)","--success-border":"var(--border)","--warning-bg":"var(--popover)","--warning-text":"var(--popover-foreground)","--warning-border":"var(--border)","--info-bg":"var(--popover)","--info-text":"var(--popover-foreground)","--info-border":"var(--border)"},...s})},US=(s=5e3)=>{const[r,t]=Ae.useState(null);return Ae.useEffect(()=>{if(!os())return;let n=!1,o=null;const a=async()=>{const l=await yg();n||(t(l),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},VS=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=he(),c=US(4e3),d=i.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=i.useMemo(()=>r.map(f=>{const p=t.get(f.id)?.length||0,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,t,n,o]),m=t.size;return e.jsxs(Rl,{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(Jh,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:s,children:e.jsx(Gt,{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," / ",fs.MAX_SESSIONS]})]})]}),c&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:c.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[c.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:c.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[fs.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:[fs.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:[fs.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(xt,{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(Zh,{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>fs.VIEWPORT_MESSAGES?"text-warning":""}`,children:[f.messageCount," msgs"]}),f.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",f.backgroundCount]})]})]},f.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Bs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(ct,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(ct,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:r.map(f=>({id:f.id,title:f.title})),currentSessionId:o,cachedSessions:Array.from(t.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(ct,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},GS="openchamber-message-cursors",_n="cursors",qS=1,Hf="openchamber.messageCursors",Kl=()=>typeof window<"u",Ql=()=>Kl()&&typeof indexedDB<"u",Uf=()=>Ql()?new Promise((s,r)=>{const t=indexedDB.open(GS,qS);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(_n)||n.createObjectStore(_n)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),Vf=()=>{if(!Kl())return{};try{const s=window.localStorage.getItem(Hf);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},KS=s=>{if(Kl())try{window.localStorage.setItem(Hf,JSON.stringify(s))}catch{}},QS=async(s,r,t)=>{if(!s||!r)return;if(Ql())try{const o=await Uf();await new Promise((a,l)=>{const c=o.transaction(_n,"readwrite");c.objectStore(_n).put({messageId:r,completedAt:t},s),c.oncomplete=()=>a(),c.onerror=()=>l(c.error??new Error("Cursor write failed")),c.onabort=()=>l(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=Vf();n[s]={messageId:r,completedAt:t},KS(n)},YS=async s=>{if(!s)return null;if(Ql())try{const t=await Uf(),n=await new Promise((o,a)=>{const l=t.transaction(_n,"readonly"),d=l.objectStore(_n).get(s);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),l.onerror=()=>a(l.error??new Error("Cursor read failed")),l.onabort=()=>a(l.error??new Error("Cursor read aborted"))});return t.close(),n}catch{}return Vf()[s]??null},XS=50,JS=750,fu=new WeakMap,pu=s=>{if(!s||!Array.isArray(s))return 0;const r=fu.get(s);if(r!==void 0)return r;let t=0;for(let n=0;n<s.length;n++){const o=s[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(t+=a.length)}}return fu.set(s,t),t},ZS=10,hu=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.indexOf("_"),n=t>=0?r.slice(t+1):r;return!n||n.length<ZS?null:n},gu=(s,r)=>{const t=hu(s),n=hu(r);return!t||!n||t.length!==n.length?!0:t>n},ll=new Map,xu=(s,r)=>{const t=`${s}:${r}`,n=ll.get(t);if(n&&n.sessionId===s)return n.message;const l=(he.getState().messages.get(s)||[]).find(c=>c.info.id===r)||null;return ll.set(t,{sessionId:s,message:l}),l},ek=s=>{const r=s.split(/[-_]/),t=[];let n=0;for(;n<r.length;){const o=r[n];if(/^\d+$/.test(o)&&n+1<r.length&&/^\d+$/.test(r[n+1])){const a=`${o}.${r[n+1]}`;t.push(a),n+=2;continue}t.push(o),n+=1}return t.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")},tk=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,sessions:u,getWorktreeMetadata:m,loadMessages:f,loadSessions:p,updateSession:h,removeSessionFromStore:y}=he(),{checkConnection:g}=nt(),w=_e(Me=>Me.nativeNotificationsEnabled),b=_e(Me=>Me.notificationMode),v=yt(Me=>Me.currentDirectory),j=i.useMemo(()=>{if(!c)return;try{const re=m?.(c);if(re?.path)return re.path}catch(re){console.warn("Failed to inspect worktree metadata for session directory:",re)}const Me=u.find(re=>re.id===c);if(Me&&typeof Me.directory=="string"&&Me.directory.trim().length>0)return Me.directory.trim()},[c,m,u]),k=i.useMemo(()=>{if(j&&j.length>0)return j;if(typeof v=="string"&&v.trim().length>0)return v.trim()},[j,v]);i.useEffect(()=>{let Me=!1;const re=async()=>{try{const be=await Ee.listPendingPermissions();if(Me||be.length===0)return;be.forEach(we=>{o(we)})}catch{}},et=async()=>{try{const we=Lt.getState().projects.map(Oe=>Oe.path),Ve=u.map(Oe=>Oe.directory),tt=[k,...we,...Ve],We=await Ee.listPendingQuestions({directories:tt});if(Me||We.length===0)return;We.forEach(Oe=>{a(Oe)})}catch{}};return re(),et(),()=>{Me=!0}},[o,a,k,u]);const x=i.useCallback(Me=>{if(typeof Me!="string")return null;const re=Me.trim();if(!re)return null;const et=re.replace(/\\/g,"/");return et.length>1?et.replace(/\/+$/,""):et},[]),N=i.useCallback(Me=>{if(!Me)return null;try{const et=m?.(Me),be=x(et?.path??null);if(be)return be}catch{}const re=u.find(et=>et.id===Me);return x(re?.directory??null)},[m,x,u]),P=_e(Me=>Me.setEventStreamStatus),C=i.useRef(null),M=i.useCallback((Me,re)=>{const et=re??null,be=C.current;if(!(be&&be.status===Me&&be.hint===et)){if(C.current={status:Me,hint:et},rs()){const Ve={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[Me]??"[INFO]",tt=et?`${Ve} SSE ${Me}: ${et}`:`${Ve} SSE ${Me}`;console.info(tt)}P(Me,et)}},[P]),S=i.useCallback((Me,re)=>{if(!Me)return Promise.resolve();const et=Date.now();if(L.current)return L.current;if(et-U.current<JS)return Promise.resolve();const be=f(Me).catch(we=>{console.warn(`[useEventStream] Failed to resync messages (${re}):`,we)}).finally(()=>{L.current=null,U.current=Date.now()});return L.current=be,be},[f]),A=i.useCallback(async Me=>{rs()&&console.info("[useEventStream] Bootstrapping state:",Me);try{await Promise.all([p(),c?S(c,Me):Promise.resolve()])}catch(re){console.warn("[useEventStream] Bootstrap failed:",Me,re)}},[c,p,S]),D=i.useCallback((Me,re,et)=>{rs()&&console.debug(`[MessageTracker] ${Me}: ${re}`,et)},[]),F=i.useCallback(Me=>{rs()&&console.debug(`[MessageTracker] ${Me}: reported`)},[]),E=i.useRef(null),I=i.useRef(null),_=i.useRef(0);i.useRef(new Set);const V=i.useRef(new Map),Y=i.useRef(null),H=i.useRef(!1),L=i.useRef(null),U=i.useRef(0),Q=i.useRef(new Set),J=i.useRef(new Set),K=i.useRef(new Set),ne=i.useRef(new Set),X=i.useCallback(()=>{if(typeof document>"u")return"visible";const Me=document.visibilityState;return Me==="hidden"&&document.hasFocus()?"visible":Me},[]),ae=i.useRef(X()),O=i.useRef(typeof navigator>"u"?!0:navigator.onLine),z=i.useRef(!1),T=i.useRef(null),$=i.useRef(null),W=i.useRef(Date.now()),q=i.useRef(!1),ue=i.useCallback(Me=>{const re=Date.now();re-W.current>25e3&&(A(Me),W.current=re)},[A]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(q.current=!0)},[]);const oe=i.useRef(new Map),de=i.useRef(new Map),je=i.useRef(0),Se=i.useRef(null),Le=i.useRef(c),G=i.useRef(null),ee=i.useRef(null);i.useEffect(()=>{Le.current=c},[c]);const te=i.useCallback((Me,re)=>{if(!Me)return;const et=Date.now(),be=V.current,we=be.get(Me);if(we&&et-we<3e3)return;be.set(Me,et);const Ve=tt=>{if(typeof re=="string"&&re.trim().length>0)return re.trim();try{const Oe=m?.(tt);if(Oe?.path)return Oe.path}catch{}const We=u.find(Oe=>Oe.id===tt);return We&&typeof We.directory=="string"&&We.directory.trim().length>0?We.directory.trim():null};setTimeout(async()=>{try{const tt=Ve(Me),We=tt?await Ee.withDirectory(tt,()=>Ee.getSession(Me)):await Ee.getSession(Me);if(We){const Oe={};typeof We.title=="string"&&We.title.length>0&&(Oe.title=We.title),We.summary!==void 0&&(Oe.summary=We.summary),Object.keys(Oe).length>0&&d(Me,Oe)}}catch(tt){console.warn("Failed to refresh session metadata:",tt)}},100)},[d,m,u]),xe=i.useCallback((Me,re)=>{if(he.getState().sessionActivityPhase?.get(Me)===re){de.current=new Map(he.getState().sessionActivityPhase??new Map);return}const be=oe.current.get(Me);be&&(clearTimeout(be),oe.current.delete(Me));const we=new Map(he.getState().sessionActivityPhase??new Map);if(we.set(Me,re),de.current=we,he.setState({sessionActivityPhase:we}),re==="cooldown"){const Ve=setTimeout(()=>{if(oe.current.delete(Me),he.getState().sessionActivityPhase?.get(Me)==="cooldown"){const We=new Map(he.getState().sessionActivityPhase??new Map);We.set(Me,"idle"),de.current=We,he.setState({sessionActivityPhase:We})}},2e3);oe.current.set(Me,Ve)}},[]),me=i.useCallback(async()=>{const Me=Date.now();if(Se.current)return Se.current;if(Me-je.current<1500)return;je.current=Me;const re=be=>{const we=new Set,Ve=new Set(u.map(We=>We.id));Object.entries(be).forEach(([We,Oe])=>{if(!We||!Oe)return;we.add(We);const rt=Oe.type==="busy"||Oe.type==="retry"?"busy":"idle";xe(We,rt)});const tt=he.getState().sessionActivityPhase;if(tt)for(const[We,Oe]of tt.entries())Ve.has(We)&&(Oe==="busy"||Oe==="cooldown")&&!we.has(We)&&xe(We,"idle")},et=(async()=>{try{const be=await Ee.getGlobalSessionStatus();if(be&&Object.keys(be).length>0){re(be);return}const we=new Set;u.forEach(rt=>{const vt=N(rt.id);vt&&we.add(vt)});const Ve=x(k??null);Ve&&we.add(Ve);const tt=Array.from(we);if(tt.length===0){const rt=await Ee.getSessionStatus();rt&&re(rt);return}const We=await Promise.allSettled(tt.map(rt=>Ee.getSessionStatusForDirectory(rt))),Oe={};if(We.forEach(rt=>{rt.status!=="fulfilled"||!rt.value||Object.assign(Oe,rt.value)}),Object.keys(Oe).length===0&&Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(vt=>vt==="busy"||vt==="cooldown")&&!await Ee.checkHealth().catch(()=>!1))return;re(Oe)}catch{}})().finally(()=>{Se.current=null});return Se.current=et,et},[k,x,N,u,xe]);i.useEffect(()=>{const Me=c??null,re=G.current,et=N(Me),be=ee.current;re&&Me&&re!==Me&&be&&et&&be!==et&&me(),G.current=Me,ee.current=et},[c,me,N]);const Te=i.useCallback(Me=>{if(W.current=Date.now(),rs()&&console.debug("[useEventStream] Received event:",Me.type,Me.properties),!Me.properties)return;const re=Me.properties;if(!new Set(["session.abort","session.error"]).has(Me.type)){const be=(typeof re.session=="object"&&re.session!==null?re.session:null)||(typeof re.sessionInfo=="object"&&re.sessionInfo!==null?re.sessionInfo:null);if(be){const we=be,Ve=typeof we.id=="string"&&we.id.length>0?we.id:typeof we.sessionID=="string"&&we.sessionID.length>0?we.sessionID:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:typeof re.id=="string"&&re.id.length>0?re.id:void 0;if(Ve){const tt=typeof we.title=="string"?we.title:typeof re.title=="string"?re.title:void 0,We=typeof we.summary=="object"&&we.summary!==null?we.summary:typeof re.summary=="object"&&re.summary!==null?re.summary:void 0;if(tt!==void 0||We!==void 0){const Oe={};tt!==void 0&&(Oe.title=tt),We!==void 0&&(Oe.summary=We),d(Ve,Oe)}}}}switch(Me.type){case"server.connected":g();break;case"global.disposed":case"server.instance.disposed":{A("server_disposed_event");break}case"openchamber:session-activity":{const be=typeof re.sessionId=="string"?re.sessionId:null,we=typeof re.phase=="string"?re.phase:null;be&&(we==="idle"||we==="busy"||we==="cooldown")&&(xe(be,we),te(be,typeof re.directory=="string"?re.directory:null));break}case"mcp.tools.changed":{const be=typeof re.directory=="string"?re.directory:k;Kn.getState().refresh({directory:be??null,silent:!0});break}case"session.status":if(q.current)break;{const be=typeof re.sessionID=="string"?re.sessionID:null,we=typeof re.status=="object"&&re.status!==null?re.status:null,Ve=typeof we?.type=="string"?we.type:null;be&&Ve&&(xe(be,Ve==="busy"||Ve==="retry"?"busy":"idle"),te(be,typeof re.directory=="string"?re.directory:null))}break;case"message.part.updated":{const be=typeof re.part=="object"&&re.part!==null?re.part:null;if(!be)break;const we=be,Ve=typeof re.info=="object"&&re.info!==null?re.info:re,tt=typeof Ve.sessionID=="string"?Ve.sessionID:null,We=typeof we.sessionID=="string"&&we.sessionID.length>0?we.sessionID:typeof tt=="string"&&tt.length>0?tt:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:null,Oe=typeof Ve.id=="string"?Ve.id:null,rt=typeof we.messageID=="string"&&we.messageID.length>0?we.messageID:typeof Oe=="string"&&Oe.length>0?Oe:typeof re.messageID=="string"&&re.messageID.length>0?re.messageID:null;if(!We||!rt){rs()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:we.sessionID??tt??re.sessionID,messageID:we.messageID??Oe??re.messageID});break}const vt=We,mt=rt,Tt=he.getState().sessionMemoryState.get(vt)?.trimmedHeadMaxId;if(Tt&&!gu(mt,Tt)){rs()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:vt,messageId:mt,trimmedHeadMaxId:Tt});break}let Ot="assistant";if(Ve&&typeof Ve.role=="string")Ot=Ve.role;else{const He=xu(vt,mt);if(He){const Je=He.info.role;typeof Je=="string"&&(Ot=Je)}}if(D(mt,"part_received",{role:Ot}),Ot==="user"&&we.synthetic===!0){D(mt,"skipped_synthetic_user_part");break}const ve={...be,type:be.type||"text"};D(mt,"addStreamingPart_called"),s(vt,mt,ve,Ot);break}case"message.updated":{const be=typeof re.info=="object"&&re.info!==null?re.info:re,we=be,Ve=typeof we.sessionID=="string"&&we.sessionID.length>0?we.sessionID:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:null,tt=typeof we.id=="string"&&we.id.length>0?we.id:typeof re.messageID=="string"&&re.messageID.length>0?re.messageID:null;if(!Ve||!tt){rs()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:we.sessionID??re.sessionID,messageID:we.id??re.messageID});break}const We=Ve,Oe=tt,rt=he.getState().sessionMemoryState.get(We)?.trimmedHeadMaxId;if(rt&&!gu(Oe,rt)){rs()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:We,messageId:Oe,trimmedHeadMaxId:rt});break}if(q.current&&rs())try{const St=re.parts||we.parts||[],Ie=(Array.isArray(St)?St.filter(B=>B?.type==="text"):[]).map(B=>{const ce=B;return typeof ce?.text=="string"?ce.text:typeof ce?.content=="string"?ce.content:""}).join(`
135
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:Oe,role:we.role,status:we.status,textLen:Ie.length,textPreview:Ie.slice(0,120),partsCount:Array.isArray(St)?St.length:0})}catch{}if(D(Oe,"message_updated",{role:we.role}),we.role==="user"){const St=re.parts||we.parts,ge=Array.isArray(St)?St:[],Ie={...be,userMessageMarker:!0,clientRole:"user"};if(t(We,Oe,Ie),ge.length>0)for(let B=0;B<ge.length;B++){const ce=ge[B];if(ce.synthetic===!0)continue;const ye={...ce,type:ce?.type||"text",sessionID:ce?.sessionID||We,messageID:ce?.messageID||Oe};s(We,Oe,ye,"user")}D(Oe,"user_message_created_from_event",{partsCount:ge.length});break}const vt=xu(We,Oe),mt=pu(vt?.parts||[]),Tt=vt?.info?.finish==="stop",Ot=re.parts||we.parts,ve=Array.isArray(Ot)?Ot:[],He=ve.length>0,Qe=typeof(we.time||{})?.completed=="number";if(!He&&!Qe)break;const ft=be.finish,it=typeof ft=="string"?ft:null,Pe=it==="stop";if(we.role==="assistant"&&He){const St=pu(ve);if(mt>0&&St+XS<mt&&!Pe){D(Oe,"skipped_shrinking_update",{incomingLen:St,existingLen:mt});break}if(q.current){const Ie=mt>0&&St<mt,B=ve.some(ye=>{if(!ye||ye.type!=="text")return!1;const $e=ye;return typeof $e.text=="string"&&$e.text.length>0});if(Ie&&!(Pe&&B)){D(Oe,"desktop_shrinking_update_suppressed",{incomingLen:St,existingLen:mt});break}}}if(t(We,Oe,be),He&&we.role!=="user"){const Ie=(he.getState().messages.get(We)||[]).find(ye=>ye.info.id===Oe),B=!Ie||Ie.parts.length===0;D(Oe,B?"server_parts_injected":"server_parts_refreshed",{count:ve.length});const ce=q.current&&we.role==="assistant"?ve.filter(ye=>ye?.type!=="text"):ve;for(let ye=0;ye<ce.length;ye++){const $e=ce[ye],Ue={...$e,type:$e?.type||"text",sessionID:$e?.sessionID||We,messageID:$e?.messageID||Oe};s(We,Oe,Ue,we.role),D(Oe,`server_part_${ye}`)}}const ze=be.time,lt=ze?.completed,Ke=typeof lt=="number"&&Number.isFinite(lt),wt=it==="stop"||Tt;if(be.role==="assistant"&&(Ke||wt)&&be.role==="assistant"){const ge=he.getState().messages.get(We)||[];let Ie=null,B="";for(let ke=0;ke<ge.length;ke++){const Ye=ge[ke];Ye.info.role==="assistant"&&Ye.info.id>B&&(B=Ye.info.id,Ie=Ye.info.id)}if(c===We&&Oe!==Ie)break;if(!wt&&q.current){D(Oe,"desktop_completion_without_stop");break}const ye=Ke?lt:Date.now();if(Ke||t(We,Oe,{...be,time:{...ze??{},completed:ye}}),D(Oe,"completed",{timeCompleted:ye}),F(Oe),QS(We,Oe,ye),r(We,Oe),it==="stop"&&ln()&&w&&(b==="always"||ae.current==="hidden")){const Ye=K.current;if(!Ye.has(Oe)){Ye.add(Oe);const Ze=Zs();if(Ze?.notifications){const ot=we.mode||"agent",$t=we.modelID||"assistant",Wt=`${ot.charAt(0).toUpperCase()+ot.slice(1)} agent is ready`,jt=`${ek($t)} completed the task`;Ze.notifications.notifyAgentCompletion({title:Wt,body:jt,tag:Oe})}}}q.current||it==="stop"&&he.getState().sessionActivityPhase?.get(We)==="busy"&&xe(We,"cooldown");const $e=be.sessionID,Ue=typeof $e=="string"&&$e.length>0?$e:We;te(Ue,typeof re.directory=="string"?re.directory:null),be.summary&&typeof Ue=="string"&&n(Ue,null)}break}case"session.created":case"session.updated":{const be=typeof re.info=="object"&&re.info!==null?re.info:typeof re.sessionInfo=="object"&&re.sessionInfo!==null?re.sessionInfo:typeof re.session=="object"&&re.session!==null?re.session:re,we=typeof be.id=="string"&&be.id.length>0?be.id:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:typeof re.id=="string"&&re.id.length>0?re.id:void 0;if(we){const Ve=typeof be.time=="object"&&be.time!==null?be.time:typeof re.time=="object"&&re.time!==null?re.time:null,tt=Ve&&typeof Ve.compacting=="number"?Ve.compacting:null;n(we,tt);const We=typeof be.directory=="string"?be.directory:typeof re.directory=="string"?re.directory:null,Oe={...be,id:we,...We?{directory:We}:{}};h(Oe)}break}case"session.deleted":{const be=typeof re.sessionID=="string"?re.sessionID:typeof re.id=="string"?re.id:null;be&&y(be);break}case"session.abort":{const be=typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:null,we=typeof re.messageID=="string"&&re.messageID.length>0?re.messageID:null;be&&we&&r(be,we);break}case"permission.asked":{if(!("sessionID"in re)||typeof re.sessionID!="string")break;const be=re;o(be);const we=`${be.sessionID}:${be.id}`;Q.current.has(we)||setTimeout(()=>{if(Le.current===be.sessionID||!he.getState().permissions.get(be.sessionID)?.some(Oe=>Oe.id===be.id))return;Q.current.add(we);const We=he.getState().sessions.find(Oe=>Oe.id===be.sessionID)?.title||"Session";ls(async()=>{const{toast:Oe}=await import("./vendor-.bun-w0O-Y8Mh.js").then(rt=>rt.cz);return{toast:Oe}},__vite__mapDeps([0,1])).then(({toast:Oe})=>{Oe.warning("Permission required",{description:We,action:{label:"Open",onClick:()=>{_e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in re)||typeof re.sessionID!="string")break;const be=re;a(be);const we=`${be.sessionID}:${be.id}`;if(ln()&&w&&(b==="always"||ae.current==="hidden")){const tt=ne.current;if(!tt.has(we)){tt.add(we);const We=Zs();We?.notifications&&We.notifications.notifyAgentCompletion({title:"Input needed",body:"Agent is waiting for your response",tag:we})}}J.current.has(we)||setTimeout(()=>{if(Le.current===be.sessionID||!he.getState().questions.get(be.sessionID)?.some(Oe=>Oe.id===be.id))return;J.current.add(we);const We=he.getState().sessions.find(Oe=>Oe.id===be.sessionID)?.title||"Session";ls(async()=>{const{toast:Oe}=await import("./vendor-.bun-w0O-Y8Mh.js").then(rt=>rt.cz);return{toast:Oe}},__vite__mapDeps([0,1])).then(({toast:Oe})=>{Oe.info("Input needed",{description:We,action:{label:"Open",onClick:()=>{_e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"question.replied":{const be=typeof re.sessionID=="string"?re.sessionID:null,we=typeof re.requestID=="string"?re.requestID:null;be&&we&&l(be,we);break}case"todo.updated":{const be=typeof re.sessionID=="string"?re.sessionID:null,we=Array.isArray(re.todos)?re.todos:null;be&&we&&Ev(be,we);break}}},[c,w,b,s,r,t,o,a,l,g,te,n,d,D,F,xe,h,y,A,k]),Ne=i.useCallback(()=>{const Me=X();return ae.current=Me,Me==="visible"&&O.current},[X]),Be=i.useCallback(()=>{rs()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:q.current,hasUnsubscribe:!!E.current,currentSessionId:Le.current,effectiveDirectory:k,onlineStatus:O.current,visibilityState:ae.current,lastEventTimestamp:W.current,reconnectAttempts:_.current})},[k]),fe=i.useCallback(async()=>!0,[]),ht=i.useCallback(()=>{if(H.current){rs()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(H.current=!0,I.current&&(clearTimeout(I.current),I.current=null),E.current){const Me=E.current;E.current=null;try{Me()}catch(re){console.warn("[useEventStream] Error during unsubscribe:",re)}}H.current=!1},[]),bt=i.useCallback(async Me=>{if(Be(),!Ne()){z.current=!0,O.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}q.current&&(await fe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),Me?.resetAttempts&&(_.current=0),ht(),W.current=Date.now(),M("connecting",null),rs()&&console.info("[useEventStream] Starting event stream...");const re=be=>{console.warn("Event stream error:",be)},et=()=>{const be=z.current;if(_.current=0,z.current=!1,W.current=Date.now(),M("connected",null),g(),Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(Ve=>Ve==="busy"||Ve==="cooldown")&&me(),be)A("sse_reconnected");else{const Ve=Le.current;Ve&&setTimeout(()=>{S(Ve,"sse_reconnected").then(()=>te(Ve)).catch(tt=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",tt)})},0)}};if(rs()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:k,isCleaningUp:H.current}),H.current){rs()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const be=Ee.subscribeToGlobalEvents(Ve=>{const tt=Ve.payload,We=Ve.payload,Oe=typeof We.properties=="object"&&We.properties!==null?We.properties:{},rt=Ve.directory&&Ve.directory!=="global"?{...Oe,directory:Ve.directory}:Oe;Te({type:typeof tt.type=="string"?tt.type:"",properties:rt})},re,et),we=()=>{try{be()}catch(Ve){console.warn("[useEventStream] Error during unsubscribe:",Ve)}};H.current?we():E.current=we}catch(be){console.error("[useEventStream] Error during subscription:",be),re(be)}},[Ne,ht,M,g,S,te,Te,k,me,fe,Be,A]),Nt=i.useCallback(Me=>{if(!Ne()){z.current=!0,ht(),O.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}const re=_.current+1;_.current=re;const et=Me??`Retrying (${re})`;M("reconnecting",et);const be=re<=3?Math.min(1e3*Math.pow(2,re-1),8e3):Math.min(2e3*Math.pow(2,re-3),32e3),we=Math.floor(Math.random()*250),Ve=be+we;I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{bt({resetAttempts:!1})},Ve)},[Ne,ht,M,bt]);i.useEffect(()=>{const Me=oe.current;typeof window<"u"&&(window.__messageTracker=D);let re=null;q.current&&typeof window<"u"&&(re=rt=>{const vt=typeof rt.detail?.sessionId=="string"?rt.detail.sessionId:null,mt=typeof rt.detail?.phase=="string"?rt.detail.phase:null;vt&&(mt==="idle"||mt==="busy"||mt==="cooldown")&&(xe(vt,mt),te(vt))},window.addEventListener("openchamber:session-activity",re));const et=()=>{T.current&&(clearTimeout(T.current),T.current=null)},be=()=>{T.current||(T.current=setTimeout(()=>{const rt=X();ae.current=rt,rt!=="visible"?(ht(),z.current=!0,M("paused","Paused while hidden")):et()},5e3))},we=()=>{if(ae.current=X(),ae.current==="visible"){if(et(),ue("visibility_restore"),z.current||!E.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const rt=Le.current;rt&&(S(rt,"visibility_restore").catch(()=>{}),te(rt)),me(),M("connecting","Resuming stream"),bt({resetAttempts:!0})}}else M("paused","Paused while hidden"),be()},Ve=()=>{if(ae.current=X(),ae.current==="visible"&&(et(),ue("window_focus"),z.current||!E.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const rt=Le.current;rt&&(te(rt),S(rt,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(vt=>console.warn("[useEventStream] Failed to refresh messages:",vt))),me(),M("connecting","Resuming stream"),bt({resetAttempts:!0})}},tt=()=>{O.current=!0,ue("network_restored"),(z.current||!E.current)&&(M("connecting","Network restored"),bt({resetAttempts:!0}))},We=()=>{O.current=!1,z.current=!0,M("offline","Waiting for network"),ht()};typeof document<"u"&&document.addEventListener("visibilitychange",we),typeof window<"u"&&(window.addEventListener("online",tt),window.addEventListener("offline",We),window.addEventListener("focus",Ve));const Oe=setTimeout(()=>{bt({resetAttempts:!0})},100);return $.current&&clearInterval($.current),$.current=setInterval(()=>{if(!Ne())return;const rt=Date.now();Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(mt=>mt==="busy"||mt==="cooldown")&&me(),rt-W.current>45e3&&Promise.resolve().then(async()=>{try{await Ee.checkHealth()?W.current=Date.now():Nt("Refreshing stalled stream")}catch(mt){console.warn("Health check after stale stream failed:",mt),Nt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Oe),re&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",re),typeof document<"u"&&document.removeEventListener("visibilitychange",we),typeof window<"u"&&(window.removeEventListener("online",tt),window.removeEventListener("offline",We),window.removeEventListener("focus",Ve)),et(),$.current&&(clearInterval($.current),$.current=null),Me.forEach(rt=>clearTimeout(rt)),Me.clear(),ll.clear(),K.current.clear(),ne.current.clear(),z.current=!1,ae.current=X(),O.current=typeof navigator>"u"?!0:navigator.onLine,ht(),Y.current&&(clearTimeout(Y.current),Y.current=null),M("idle",null)}},[k,D,X,ht,M,bt,Nt,f,te,xe,me,Ne,p,ue,S])},sk=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=he(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=_e(),{themeMode:p,setThemeMode:h}=Vr(),{working:y}=cf(),g=i.useRef(null),w=i.useRef(null),b=i.useRef(!1),v=i.useCallback(()=>{w.current&&(clearTimeout(w.current),w.current=null),g.current=null,n()},[n]);i.useEffect(()=>{const j=k=>{if(Es(k)&&k.key==="k"&&(k.preventDefault(),a()),Es(k)&&k.shiftKey&&k.key.toLowerCase()==="l"){const N=Zs()?.diagnostics;if(!N||(k.preventDefault(),b.current))return;b.current=!0,N.downloadLogs().then(({fileName:P,content:C})=>{const M=P||"openchamber.log",S=new Blob([C],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),D=document.createElement("a");D.href=A,D.download=M,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(A)}).finally(()=>{b.current=!1});return}if(Es(k)&&k.key==="."&&(k.preventDefault(),l()),Es(k)&&k.key.toLowerCase()==="n"){k.preventDefault();const x=zt(),N=nt.getState().settingsAutoCreateWorktree;if(x?!1:N?!k.shiftKey:k.shiftKey){u("chat"),d(!1),za();return}u("chat"),d(!1),s()}if(Es(k)&&k.key==="/"){k.preventDefault();const x=["light","dark","system"],P=(x.indexOf(p)+1)%x.length;h(x[P])}if(Es(k)&&!k.shiftKey&&k.key.toLowerCase()==="t"){k.preventDefault();const{isTimelineDialogOpen:x,setTimelineDialogOpen:N}=_e.getState();N(!x);return}if(Es(k)&&!k.shiftKey&&k.key===","){k.preventDefault();const{isSettingsDialogOpen:x}=_e.getState();m(!x);return}if(Es(k)&&!k.shiftKey&&k.key.toLowerCase()==="l"){k.preventDefault();const{isMobile:x,isSessionSwitcherOpen:N}=_e.getState();x?d(!N):c();return}if(Es(k)&&!k.shiftKey&&k.key.toLowerCase()==="i"){k.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Es(k)&&k.shiftKey&&k.key.toLowerCase()==="m"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:N,isHelpDialogOpen:P,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S,isModelSelectorOpen:A}=_e.getState();if(x||N||P||C||M||!(S==="chat"))return;k.preventDefault(),f(!A);return}if(Es(k)&&k.shiftKey&&k.key.toLowerCase()==="t"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:N,isHelpDialogOpen:P,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=_e.getState();if(x||N||P||C||M||!(S==="chat"))return;const F=nt.getState();if(F.getCurrentModelVariants().length===0)return;k.preventDefault(),F.cycleCurrentVariant();const I=nt.getState().currentVariant,_=he.getState(),V=_.currentSessionId,Y=nt.getState().currentAgentName,H=nt.getState().currentProviderId,L=nt.getState().currentModelId;V&&Y&&H&&L&&_.saveAgentModelVariantForSession(V,Y,H,L,I);return}if(k.key==="Escape"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:N,isHelpDialogOpen:P,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=_e.getState();if(x){k.preventDefault(),m(!1),v();return}if(N||P||C||M||!(S==="chat")){v();return}const F=o;if(!(y.canAbort&&!!F)){v();return}const I=Date.now(),_=g.current;if(_&&I<_){k.preventDefault(),v(),r();return}k.preventDefault();const V=t(3e3)??I+3e3;g.current=V,w.current&&clearTimeout(w.current);const Y=Math.max(V-I,0);w.current=setTimeout(()=>{g.current&&Date.now()>=g.current&&v()},Y||0);return}};return window.addEventListener("keydown",j),()=>{window.removeEventListener("keydown",j)}},[s,r,a,l,c,d,u,m,f,h,p,y,t,v,o]),i.useEffect(()=>()=>{v()},[v])},yu="openchamber:menu-action",rk=s=>{const{openNewSessionDraft:r}=he(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=_e(),{addProject:u}=Lt(),{requestAccess:m,startAccessing:f}=Wa(),{setThemeMode:p}=Vr(),h=i.useRef(!1),y=i.useCallback(()=>{os()?m("").then(async g=>{if(!g.success||!g.path){g.error&&g.error!=="Directory selection cancelled"&&Z.error("Failed to select directory",{description:g.error});return}const w=await f(g.path);if(!w.success){Z.error("Failed to open directory",{description:w.error||"Desktop could not grant file access."});return}u(g.path,{id:g.projectId})||Z.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(g=>{console.error("Desktop: Error selecting directory:",g),Z.error("Failed to select directory")}):Fn.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const g=w=>{switch(w.detail){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":t();break;case"new-session":l("chat"),a(!1),r();break;case"new-worktree-session":l("chat"),a(!1),za();break;case"change-workspace":y();break;case"open-git-tab":{const{activeMainTab:v}=_e.getState();l(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=_e.getState();l(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=_e.getState();l(v==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":s?.();break;case"help-dialog":n();break;case"download-logs":{const j=Zs()?.diagnostics;if(!j||h.current)break;h.current=!0,j.downloadLogs().then(({fileName:k,content:x})=>{const N=k||"openchamber.log",P=new Blob([x],{type:"text/plain;charset=utf-8"}),C=URL.createObjectURL(P),M=document.createElement("a");M.href=C,M.download=N,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(C),Z.success("Logs saved",{description:`Downloaded to ~/Downloads/${N}`})}).catch(()=>{Z.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(yu,g),()=>window.removeEventListener(yu,g)},[r,t,n,o,a,l,c,d,p,s,y])},nk=s=>s.role==="assistant",bu=s=>{const r=s.info;if(!nk(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},na=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},vu=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Zn(n)).join(" ").replace(/\s+/g," ").trim(),ok=(s,r)=>{if(!s||!na(s.info))return-1;const t=vu(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((l,c)=>{if(!na(l.info))return;const d=vu(l),u=!!(t&&d&&d===t),m=typeof l.info?.time?.created=="number"?l.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=c,a=p);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(l=>{if(!na(l.info))return!1;const c=typeof l.info?.time?.created=="number"?l.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},ak=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=he(),n=i.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=i.useRef(void 0),a=i.useRef(0),l=i.useCallback(async()=>{if(!s||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(s)||[],m=he.getState().sessionMemoryState.get(s)?.isStreaming?fs.VIEWPORT_MESSAGES:fs.HISTORICAL_MESSAGES,f=m+fs.FETCH_BUFFER,p=await Ee.getSessionMessages(s,f),h=await YS(s);if(!p)return;const y=d[d.length-1];if(y){const g=p.findIndex(v=>v.info.id===y.info.id),b=g===-1?ok(y,p):g;if(b!==-1)if(b<p.length-1){const v=p.slice(b+1);console.log(`[SYNC] Found ${v.length} new messages to append`);const j=[...d,...v],{syncMessages:k}=he.getState();k(s,j)}else{const v=p[b],j=d[d.length-1],k=bu(v),x=bu(j);if(k&&!x){console.log("[SYNC] Last message completed on server");const N=[...d.slice(0,-1),v],{syncMessages:P}=he.getState();P(s,N)}}else if(na(y.info)){const v=p.slice(-m);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:j}=he.getState();j(s,v)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(h){const g=p.findIndex(w=>w.info.id===h.messageId);if(g!==-1){if(g<p.length-1){const b=p.slice(g+1).slice(-m);if(b.length>0){console.log(`[SYNC] Restoring ${b.length} messages after cursor`);const{syncMessages:v}=he.getState();v(s,b)}}}else if(p.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const w=p.slice(-m),{syncMessages:b}=he.getState();b(s,w)}}else if(p.length>0){const g=p.slice(-m);console.log(`[SYNC] Loading last ${g.length} messages`);const{syncMessages:w}=he.getState();w(s,g)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);i.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),l()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[l]),i.useEffect(()=>{if(!s||n)return;const c=()=>{document.visibilityState==="visible"&&l(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,l]),i.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),l())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[l])},ik=()=>{i.useEffect(()=>{let s=!1;return(async()=>{try{const t=await Ee.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const l=a,c=l.type==="busy"||l.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&he.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function lk(){const{git:s}=Nr(),r=yt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=he(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=Qt(),u=i.useMemo(()=>{const m=t?o.get(t)??void 0:void 0,p=n.find(h=>h.id===t)?.directory??null;return m?.path??p??r??null},[t,n,o,r]);i.useEffect(()=>{if(!u||!s){c();return}return a(u),d(u,s),l(s),()=>{c()}},[u,s,a,l,c,d])}function ck({children:s}){return lk(),e.jsx(e.Fragment,{children:s})}const dk=()=>{const[{isUpdating:s,message:r},t]=i.useState(()=>Lg());return i.useEffect(()=>$g(t),[]),s?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[e.jsx(Ul,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Gf={getLastAssistantMessage(){const s=he.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const t=s.messages.get(r);if(!t||t.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=t.length-1;n>=0;n--){const o=t[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const h={id:p.id,type:p.type};return p.type==="text"?(h.text=p.text,h.textLength=p.text?.length||0):p.type==="tool"?(h.tool=p.tool,h.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(h.isStepMarker=!0),h}),l=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),c=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!l&&!c&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:l,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!l&&!c}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!l&&!c&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(s,r=80){return!s||typeof s!="string"||s.length<=r?s:s.substring(0,r)+"…"},truncateMessages(s){return s.map(r=>({...r,parts:(r.parts||[]).map(t=>{const n={...t};return"text"in t&&(n.text=this.truncateString(t.text)),"textPreview"in t&&(n.textPreview=this.truncateString(t.textPreview)),t.state&&(n.state={...t.state},"output"in t.state&&(n.state.output=this.truncateString(t.state.output)),"error"in t.state&&(n.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(n.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),n})}))},getAllMessages(s=!1){const r=he.getState(),t=r.currentSessionId;if(!t)return console.log("[ERROR] No active session"),[];const n=r.messages.get(t)||[];return console.log(`[MESSAGES] Total messages in session: ${n.length}`),n.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),s?this.truncateMessages(n):n},async getAppStatus(){const s=yt.getState(),r=he.getState(),t=Lt.getState(),n=s.currentDirectory||null,o=Ee.getDirectory()??null,a=r.sessions||[],l=new Set,c={};a.forEach(C=>{const M=C.directory;typeof M=="string"&&M.trim().length>0?(l.add(M),c[M]=(c[M]??0)+1):c["(none)"]=(c["(none)"]??0)+1});const d=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(C){return{available:!1,error:C instanceof Error?C.message:String(C)}}})(),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 C=>{try{return await C.json()}catch{return null}},h=async C=>{try{return await C.text()}catch{return null}},y=async C=>{try{const M=await fetch(C);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,b=null,v=null;const j=n?`/api/path?directory=${encodeURIComponent(n)}`:"/api/path";g=await y(j);const k=n?`/api/project/current?directory=${encodeURIComponent(n)}`:"/api/project/current";w=await y(k),b=await y("/api/config/settings");try{const C=await fetch("/api/health"),M=C.headers.get("content-type")||"",S=await h(C);v={status:C.status,ok:C.ok,contentType:M,type:M.includes("application/json")?"json":"html",preview:S?S.slice(0,120):null}}catch(C){v={error:C instanceof Error?C.message:String(C)}}let x={isGitRepo:null};if(n)try{x.isGitRepo=await Ur(n)}catch(C){x={isGitRepo:null,error:C instanceof Error?C.message:String(C)}}const N=t.projects.map(C=>({id:C.id,path:C.path,label:C.label})),P={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:s.homeDirectory||null,isHomeReady:s.isHomeReady,hasPersistedDirectory:s.hasPersistedDirectory,isSwitchingDirectory:s.isSwitchingDirectory},projects:{total:t.projects.length,activeProjectId:t.activeProjectId,samples:N},sessions:{total:a.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:l.size,directorySamples:Array.from(l).slice(0,5),directoryCounts:c},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:x,localStorage:d,opencode:{pathInfo:g,projectInfo:w,health:v},openchamber:{settingsInfo:b}};return console.log("[DEBUG] App status snapshot:",P),P},async buildDiagnosticsReport(){const s=await this.getAppStatus();return JSON.stringify(s,null,2)},async copyDiagnosticsReport(){const s=await this.buildDiagnosticsReport();return typeof navigator<"u"&&navigator.clipboard?(await navigator.clipboard.writeText(s),{ok:!0,report:s}):{ok:!1,report:s}},checkLastMessage(){const s=this.getLastAssistantMessage();if(!s)return!1;const r=s.isEmpty||s.isEmptyResponse;return r?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:s.messageId,isEmpty:s.isEmpty,isEmptyResponse:s.isEmptyResponse,partsCount:s.partsCount}),s.parts.length>0&&console.log("Parts:",s.parts)):console.log("[OK] Last message looks good!"),r},getStreamingState(){const s=he.getState(),r=s.currentSessionId?s.streamingMessageIds.get(s.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:r,streamingMessageIds:Array.from(s.streamingMessageIds.entries()),messageStreamStates:Array.from(s.messageStreamStates.entries())}),{streamingMessageId:r,streamingMessageIds:s.streamingMessageIds,streamStates:s.messageStreamStates}},findEmptyMessages(){const s=he.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(s.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],l=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!l&&!c});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
136
+ `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
137
+ `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
138
+ `),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)
139
+ `),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(s={}){const{includeNonAssistant:r=!1,verbose:t=!0,maxTableRows:n=25}=s,o=he.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const l=o.messages.get(a)||[],c=r?l:l.filter(p=>p.info.role==="assistant"),d={totalMessages:l.length,analyzedMessages:c.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const h=p.filter(y=>typeof y=="number");return h.length>0?Math.max(...h):null},f=c.map((p,h)=>{const y=p.info??{},g=Array.isArray(p.parts)?p.parts:[],w=y.time??{},b=u(w.completed),v=b!==null,j=g.filter(D=>D.type==="tool"),k=g.filter(D=>D.type==="reasoning"),x=m(j.map(D=>u(D.state?.time?.end??D.state?.time?.start))),N=m(k.map(D=>u(D.time?.end??D.time?.start))),P=m([x,N].filter(D=>D!==null)),C=j.some(D=>["pending","running","started"].includes(D.state?.status)),M=k.some(D=>typeof D.time?.end!="number");j.length>0&&(d.withTools+=1),k.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const S=!!(v&&typeof x=="number"&&b<x);S&&(d.completedBeforeTool+=1);const A=!!(v&&typeof N=="number"&&b<N);return A&&(d.completedBeforeReasoning+=1),v&&C&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:y.id,role:y.role,completedAt:b,latestToolTimestamp:x,latestReasoningTimestamp:N,latestPartTimestamp:P,completed_missing:!v,completed_before_tool:S,completed_before_reasoning:A,running_tools_when_completed:!!(v&&C),reasoning_open_when_completed:!!(v&&M),has_tools:j.length>0,has_reasoning:k.length>0}});return t&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const s=he.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(s.messages.get(r)||[]).filter(w=>w.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(w=>w.type==="step-finish"),l=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&l),p=s.messageStreamStates,h=o.info.sessionID?s.streamingMessageIds.get(o.info.sessionID)??null:null,y=p.get(o.info.id),g=o.info.id===h;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",l),console.log("messageIsComplete:",f),console.log("lifecycle phase:",y?.phase),console.log("isStreamingCandidate:",g),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:l,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Gf,rs()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",s=>{try{const r=s.message||"",t=s.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&s.preventDefault()}catch{}}));const uk=({open:s,onOpenChange:r})=>{const[t,n]=i.useState(null),[o,a]=i.useState(!1),[l,c]=i.useState(!1),d=i.useCallback(async()=>{if(!o){a(!0),c(!1);try{(await Gf.copyDiagnosticsReport()).ok?(c(!0),Z.success("Diagnostics copied")):Z.error("Copy failed")}catch(m){Z.error("Copy failed"),console.error("Failed to copy diagnostics:",m)}finally{a(!1)}}},[o]);i.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:p}=await ls(async()=>{const{getVersion:y}=await import("./vendor-.bun-w0O-Y8Mh.js").then(g=>g.cC);return{getVersion:y}},__vite__mapDeps([0,1])),h=await p();n(h)}catch{n("1.5.2")}})():n("1.5.2")},[s]);const u=t;return e.jsx(us,{open:s,onOpenChange:r,children:e.jsx(ms,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(Ul,{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:R("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:l?"Diagnostics copied":"Copy diagnostics"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Includes OpenChamber state, OpenCode health, directories, and projects."})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Bi,{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(Gu,{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(zi,{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 Fi({apis:s,children:r}){return e.jsx(Al.Provider,{value:s,children:r})}const mk="curl -fsSL https://opencode.ai/install | bash",fk=3e3;function pk({onCopy:s}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:s,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(er,{className:"h-4 w-4"})})]})}const hk=3e4;function gk({onCliAvailable:s}){const[r,t]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),hk);return()=>clearTimeout(m)},[]),i.useEffect(()=>{l(typeof window.opencodeDesktop<"u")},[]);const c=i.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await ls(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-w0O-Y8Mh.js").then(y=>y.cB);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(mk),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return i.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,fk);return m(),()=>clearInterval(f)},[d,s]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(oa,{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(Bt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(pk,{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(oa,{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 xk=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=_e();return e.jsx(uk,{open:s,onOpenChange:r})};function yk({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=nt(),{error:o,clearError:a,loadSessions:l}=he(),c=yt(x=>x.currentDirectory),d=yt(x=>x.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=Ef(),[h,y]=i.useState(()=>s.runtime.isDesktop),[g,w]=i.useState(()=>s.runtime.isVSCode),[b,v]=i.useState(()=>s.runtime.isDesktop?bg():!0);i.useEffect(()=>{y(s.runtime.isDesktop),w(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),i.useEffect(()=>(uc(s),()=>uc(null)),[s]),i.useEffect(()=>{if(typeof document>"u")return;const x=document.documentElement,N=Hd[f]?.stack??Hd[s0].stack,P=Xr[p]?.stack??Xr[sa].stack;x.style.setProperty("--font-sans",N),x.style.setProperty("--font-heading",N),x.style.setProperty("--font-family-sans",N),x.style.setProperty("--font-mono",P),x.style.setProperty("--font-family-mono",P),x.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=N)},[f,p]),i.useEffect(()=>{if(t){const N=setTimeout(()=>{const P=document.getElementById("initial-loading");P&&(P.classList.add("fade-out"),setTimeout(()=>{P.remove()},300))},150);return()=>clearTimeout(N)}},[t]),i.useEffect(()=>{const x=setTimeout(()=>{const N=document.getElementById("initial-loading");N&&!t&&(N.classList.add("fade-out"),setTimeout(()=>{N.remove()},300))},5e3);return()=>clearTimeout(x)},[t]),i.useEffect(()=>{(async()=>g||await r())()},[r,g]),i.useEffect(()=>{if(d)return;(async()=>g||n&&(Ee.setDirectory(c),await l()))()},[c,d,l,n,g]),tk(),sk();const j=i.useCallback(()=>{m(x=>!x)},[]);rk(j),ak(),ik(),$f(),i.useEffect(()=>{const x=N=>{Es(N)&&N.shiftKey&&N.key==="D"&&(N.preventDefault(),m(P=>!P))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const k=i.useCallback(()=>{v(!0),window.location.reload()},[]);return h&&!b?e.jsx(is,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(gk,{onCliAvailable:k})})}):g?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(is,{children:e.jsx(Fi,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(HS,{}),e.jsx(Ti,{})]})})}):e.jsx(is,{children:e.jsx(Fi,{apis:s,children:e.jsx($d,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(IS,{}),e.jsx(Ti,{})]})})})}):e.jsx(is,{children:e.jsx(Fi,{apis:s,children:e.jsx(ck,{children:e.jsx($d,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(MS,{}),e.jsx(Ti,{}),e.jsx(dk,{}),e.jsx(xk,{}),u&&e.jsx(VS,{onClose:()=>m(!1)})]})})})})})}const qf=async()=>{if(typeof window>"u")return;let s=null,r=null;try{s=window.localStorage.getItem("homeDirectory"),r=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const t=yt.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&!zt()&&t.setDirectory(r,{showOverlay:!1})},Kf="/auth/session",bk=async()=>fetch(Kf,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),wu=async s=>fetch(Kf,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Yl=({children:s})=>e.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),e.jsx("div",{className:"relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:s})]}),vk=({message:s="Preparing workspace…"})=>e.jsx(Yl,{children:e.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/90 px-6 py-5 text-center shadow-none backdrop-blur",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:s})})}),wk=({onRetry:s})=>e.jsx(Yl,{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(De,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),jk=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},Sk=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},kk=({children:s})=>{const r=i.useMemo(()=>os(),[]),t=i.useMemo(()=>zt(),[]),n=r||t,[o,a]=i.useState(()=>n?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),h=i.useRef(n),y=i.useRef(!1),g=i.useCallback(async()=>{if(n){a("authenticated");return}a(b=>b==="authenticated"?b:"pending");try{const b=await bk();if(b.ok){a("authenticated"),f("");return}if(b.status===401){a("locked");return}a("error")}catch(b){console.warn("Failed to check session status:",b),a("error")}},[n]);i.useEffect(()=>{n||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"||y.current||d)return;const b=jk();b&&(y.current=!0,Sk(),u(!0),f(""),wu(b).then(v=>{if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(v=>{console.warn("Failed to submit URL token:",v),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),i.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await em(),await tm(),await qf()))())},[n,o]);const w=async b=>{if(b.preventDefault(),!(!l||d)){u(!0),f("");try{const v=await wu(l);if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(v){console.warn("Failed to submit UI password:",v),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(vk,{}):o==="error"?e.jsx(wk,{onRetry:()=>{g()}}):o==="locked"?e.jsx(Yl,{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(eg,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(kt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:l,onChange:b=>{c(b.target.value),m&&f("")},className:"pl-10","aria-invalid":!!m||void 0,"aria-describedby":m?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(De,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(tg,{className:"h-4 w-4"})})]}),m&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:m})]})]})}):e.jsx(e.Fragment,{children:s})},Ri=s=>{if(!s||typeof s!="string")return null;const r=s.trim();if(!r.startsWith("#"))return null;let t=r.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(c=>c+c).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,l=n&255;return`${o} ${a} ${l}`};class Nk{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const t=[];return t.push(...this.generateTailwindVariables(r)),t.push(...this.generatePrimaryColors(r.colors.primary)),t.push(...this.generateSurfaceColors(r.colors.surface)),t.push(...this.generateInteractiveColors(r.colors.interactive)),t.push(...this.generateStatusColors(r.colors.status)),t.push(...this.generateSyntaxColors(r.colors.syntax)),t.push(...this.generateComponentColors(r.colors,r)),t.push(...this.generateTypographyVariables()),r.config&&t.push(...this.generateConfigVariables(r.config)),t.join(`
140
+ `)}generateTailwindVariables(r){const t=[];t.push(` --background: ${r.colors.surface.background} !important;`),t.push(` --foreground: ${r.colors.surface.foreground} !important;`),t.push(` --muted: ${r.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --card: ${r.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${r.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${r.colors.interactive.border} !important;`),t.push(` --input: ${r.colors.interactive.border} !important;`),t.push(` --primary: ${r.colors.primary.base} !important;`),t.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --secondary: ${r.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${r.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --destructive: ${r.colors.status.error} !important;`),t.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),t.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&t.push(` --radius: ${r.config.radius.md} !important;`);const n=Ri(r.colors.surface.muted),o=Ri(r.colors.surface.subtle),a=Ri(r.colors.interactive.border);t.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const l=r.metadata.variant==="dark",c=l?.8:.95,d=l?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return r.colors.charts?.series&&Array.isArray(r.colors.charts.series)&&r.colors.charts.series.forEach((u,m)=>{t.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(t.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(t.push(` --loading-spinner: ${r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),t}apply(r){const t=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
141
+ ${t}
142
+ }
143
+
144
+ .dark {
145
+ ${t}
146
+ }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
147
+ ${t}
148
+ }
149
+
150
+ :root:not(.dark) {
151
+ ${t}
152
+ }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",r.metadata.variant)}generatePrimaryColors(r){const t=[];return t.push(` --primary-base: ${r.base};`),t.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),t.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),t.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),t.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),t.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),t}generateSurfaceColors(r){const t=[];return t.push(` --surface-background: ${r.background};`),t.push(` --surface-foreground: ${r.foreground};`),t.push(` --surface-muted: ${r.muted};`),t.push(` --surface-muted-foreground: ${r.mutedForeground};`),t.push(` --surface-elevated: ${r.elevated};`),t.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),t.push(` --surface-overlay: ${r.overlay};`),t.push(` --surface-subtle: ${r.subtle};`),t}generateInteractiveColors(r){const t=[];return t.push(` --interactive-border: ${r.border};`),t.push(` --interactive-border-hover: ${r.borderHover};`),t.push(` --interactive-border-focus: ${r.borderFocus};`),t.push(` --interactive-selection: ${r.selection};`),t.push(` --interactive-selection-foreground: ${r.selectionForeground};`),t.push(` --interactive-focus: ${r.focus};`),t.push(` --interactive-focus-ring: ${r.focusRing};`),t.push(` --interactive-cursor: ${r.cursor};`),t.push(` --interactive-hover: ${r.hover};`),t.push(` --interactive-active: ${r.active};`),t}generateStatusColors(r){const t=[];return t.push(` --status-error: ${r.error};`),t.push(` --status-error-foreground: ${r.errorForeground};`),t.push(` --status-error-background: ${r.errorBackground};`),t.push(` --status-error-border: ${r.errorBorder};`),t.push(` --status-warning: ${r.warning};`),t.push(` --status-warning-foreground: ${r.warningForeground};`),t.push(` --status-warning-background: ${r.warningBackground};`),t.push(` --status-warning-border: ${r.warningBorder};`),t.push(` --status-success: ${r.success};`),t.push(` --status-success-foreground: ${r.successForeground};`),t.push(` --status-success-background: ${r.successBackground};`),t.push(` --status-success-border: ${r.successBorder};`),t.push(` --status-info: ${r.info};`),t.push(` --status-info-foreground: ${r.infoForeground};`),t.push(` --status-info-background: ${r.infoBackground};`),t.push(` --status-info-border: ${r.infoBorder};`),t}generateSyntaxColors(r){const t=[];t.push(` --syntax-background: ${r.base.background};`),t.push(` --syntax-foreground: ${r.base.foreground};`),t.push(` --syntax-comment: ${r.base.comment};`),t.push(` --syntax-keyword: ${r.base.keyword};`),t.push(` --syntax-string: ${r.base.string};`),t.push(` --syntax-number: ${r.base.number};`),t.push(` --syntax-function: ${r.base.function};`),t.push(` --syntax-variable: ${r.base.variable};`),t.push(` --syntax-type: ${r.base.type};`),t.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(r){const t=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(r,t){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),r.chat?n.push(...this.generateChatColors(r.chat,t)):n.push(...this.generateDefaultChatColors(t)),r.tools?n.push(...this.generateToolColors(r.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(r,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r.heading1||o};`),n.push(` --markdown-heading2: ${r.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${r.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${r.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const t=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${r.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${r.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${r.colors.interactive.border};`),t}generateChatColors(r,t){const n=[],o=r.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const t=[];return t.push(` --chat-background: ${r.colors.surface.background};`),t.push(` --chat-user-message: ${r.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),t.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${r.colors.interactive.border};`),t.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),t}generateToolColors(r,t){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const t=[];return t.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),t.push(` --tools-title: ${r.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${r.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${r.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${r.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(r){const t=[];return r&&(r.fonts&&(r.fonts.sans&&(t.push(` --font-sans: ${r.fonts.sans};`),t.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(t.push(` --font-mono: ${r.fonts.mono};`),t.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&t.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&t.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&t.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&t.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&t.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&t.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&t.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&t.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&t.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&t.push(` --transition-slow: ${r.transitions.slow};`))),t}generateTypographyVariables(){const r=[],t=zt()?Ag:xl;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${t.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${t.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${t.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${t.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${t.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${t.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,t){return r.startsWith("#")?`${r}${Math.round(t*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,t){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),l=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${l}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),l=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${l}, ${t})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}darken(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,l=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return r}lighten(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)+o,l=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return r}adjustHue(r,t){return this.lighten(r,t/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const Xl={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"}}},Jl={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"}}},fo=[Xl,Jl];function Na(s){return fo.find(r=>r.metadata.id===s)}const Qf=Xl.metadata.id,Yf=Jl.metadata.id,Ck=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Xf=s=>s==="dark"?Jl:Xl,Mk=s=>(fo.find(t=>t.metadata.variant===s)??Xf(s)).metadata.id,Wo=(s,r)=>{const t=Na(s);return t&&t.metadata.variant===r?t:fo.find(o=>o.metadata.variant===r)??Xf(r)},Dk=typeof window<"u"?i.useLayoutEffect:i.useEffect,Ca=(s,r)=>{if(!s)return r==="light"?Qf:Yf;const t=Na(s);return t&&t.metadata.variant===r?t.metadata.id:Mk(r)},Ak=s=>{let r=Qf,t=Yf,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),l=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const f=Na(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?t=f.metadata.id:r=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);r=Ca(a,"light"),t=Ca(l,"dark")}if(s){const o=Na(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function Ek({children:s,defaultThemeId:r}){const t=Ae.useMemo(()=>new Nk,[]),[n,o]=Ae.useState(()=>Ak(r)),[a,l]=Ae.useState(()=>Ck()),[c,d]=Ae.useState(()=>typeof window>"u"||!zt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Ae.useMemo(()=>zt(),[]),m=Ae.useMemo(()=>u&&c?c:n.themeMode==="light"?Wo(n.lightThemeId,"light"):n.themeMode==="dark"||a?Wo(n.darkThemeId,"dark"):Wo(n.lightThemeId,"light"),[u,n,a,c]),f=Ae.useMemo(()=>u&&c?[c,...fo]:fo,[u,c]);Ae.useEffect(()=>{if(!u)return;const k=P=>{d(P);const C=P.metadata.variant==="dark"?"dark":"light",M=_e.getState();M.theme!==C&&M.setTheme(C)},x=P=>{const C=P.detail;C?.theme&&k(C.theme)},N=window.__OPENCHAMBER_VSCODE_THEME__;return N&&k(N),window.addEventListener("openchamber:vscode-theme",x),()=>window.removeEventListener("openchamber:vscode-theme",x)},[u]);const p=Ae.useCallback(k=>{if(typeof document>"u")return;const x=k.colors.surface.background;os()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=x;let N=document.querySelector('meta[name="theme-color"]');N||(N=document.createElement("meta"),N.setAttribute("name","theme-color"),document.head.appendChild(N)),N.setAttribute("content",x);const P=k.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let C=document.querySelector(`meta[name="theme-color"][media="${P}"]`);C||(C=document.createElement("meta"),C.setAttribute("name","theme-color"),C.setAttribute("media",P),document.head.appendChild(C)),C.setAttribute("content",x)},[]),h=Ae.useCallback(k=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",k)},[]);Dk(()=>{if(typeof window>"u")return;t.apply(m),h(u),p(m);const k=document.documentElement;k.classList.remove("light","dark"),k.classList.add(m.metadata.variant)},[h,t,m,u,p]),Ae.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const k=window.matchMedia("(prefers-color-scheme: dark)"),x=N=>{l(N.matches)};return l(k.matches),k.addEventListener("change",x),()=>k.removeEventListener("change",x)},[n.themeMode]),Ae.useEffect(()=>{typeof window>"u"||(localStorage.setItem("themeMode",n.themeMode),localStorage.setItem("lightThemeId",n.lightThemeId),localStorage.setItem("darkThemeId",n.darkThemeId),localStorage.setItem("useSystemTheme",String(n.themeMode==="system")),localStorage.setItem("selectedThemeId",m.metadata.id),localStorage.setItem("selectedThemeVariant",m.metadata.variant==="light"?"light":"dark"))},[n,m]),Ae.useEffect(()=>{ns({themeId:m.metadata.id,themeVariant:m.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[m.metadata.id,m.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),Ae.useEffect(()=>{if(typeof window>"u")return;const k=x=>{const N=x.detail;N&&o(P=>{let C=P.themeMode;N.useSystemTheme===!0?C="system":N.useSystemTheme===!1&&(N.themeVariant==="dark"||N.themeVariant==="light")&&(C=N.themeVariant);let M=P.lightThemeId;typeof N.lightThemeId=="string"&&N.lightThemeId.length>0&&(M=Ca(N.lightThemeId,"light"));let S=P.darkThemeId;return typeof N.darkThemeId=="string"&&N.darkThemeId.length>0&&(S=Ca(N.darkThemeId,"dark")),C===P.themeMode&&M===P.lightThemeId&&S===P.darkThemeId?P:{themeMode:C,lightThemeId:M,darkThemeId:S}})};return window.addEventListener("openchamber:settings-synced",k),()=>window.removeEventListener("openchamber:settings-synced",k)},[]);const y=Ae.useCallback(k=>{const x=f.find(N=>N.metadata.id===k);x&&o(N=>x.metadata.variant==="dark"?N.darkThemeId===x.metadata.id&&N.themeMode==="dark"?N:{...N,darkThemeId:x.metadata.id,themeMode:"dark"}:N.lightThemeId===x.metadata.id&&N.themeMode==="light"?N:{...N,lightThemeId:x.metadata.id,themeMode:"light"})},[f]),g=Ae.useCallback(k=>{o(x=>x.themeMode===k?x:{...x,themeMode:k})},[]),w=Ae.useCallback(k=>{if(k){o(N=>N.themeMode==="system"?N:{...N,themeMode:"system"});return}const x=m.metadata.variant==="dark"?"dark":"light";o(N=>N.themeMode===x?N:{...N,themeMode:x})},[m.metadata.variant]),b=Ae.useCallback(k=>{const x=f.find(N=>N.metadata.id===k&&N.metadata.variant==="light");x&&o(N=>N.lightThemeId===x.metadata.id?N:{...N,lightThemeId:x.metadata.id})},[f]),v=Ae.useCallback(k=>{const x=f.find(N=>N.metadata.id===k&&N.metadata.variant==="dark");x&&o(N=>N.darkThemeId===x.metadata.id?N:{...N,darkThemeId:x.metadata.id})},[f]),j={currentTheme:m,availableThemes:f,setTheme:y,isSystemPreference:n.themeMode==="system",setSystemPreference:w,themeMode:n.themeMode,setThemeMode:g,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:b,setDarkThemePreference:v};return e.jsx(El.Provider,{value:j,children:s})}const Ik=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:l}=_e();return i.useLayoutEffect(()=>{t(),o(),l()},[r,t,n,o,a,l]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&t()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[r,t]),e.jsx(e.Fragment,{children:s})};let ju=!1;const Pk=()=>{if(ju||typeof window>"u")return;ju=!0;let s={showReasoningTraces:_e.getState().showReasoningTraces,autoDeleteEnabled:_e.getState().autoDeleteEnabled,autoDeleteAfterDays:_e.getState().autoDeleteAfterDays},r=null,t=null;const n=()=>{const a=r;r=null,t=null,a&&Object.keys(a).length>0&&ns(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};_e.subscribe(a=>{const l={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};l.showReasoningTraces!==s.showReasoningTraces&&(c.showReasoningTraces=l.showReasoningTraces),l.autoDeleteEnabled!==s.autoDeleteEnabled&&(c.autoDeleteEnabled=l.autoDeleteEnabled),l.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(c.autoDeleteAfterDays=l.autoDeleteAfterDays),s=l,Object.keys(c).length>0&&o(c)})};let Su=!1;const ku="openchamber-typography-base",Tk=()=>{if(typeof document>"u")return;const r=`:root {
153
+ ${Object.entries(xl).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
154
+ `)}
155
+ }
156
+ `,t=document.getElementById(ku);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=ku,n.textContent=r,document.head.appendChild(n)},Fk=()=>{Su||typeof window>"u"||(Su=!0,Tk())},Rk=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await em();await tm();Pk();Fk();await qf();typeof window<"u"&&(window.debugContextTokens=()=>{const s=window.__zustand_session_store__;if(!s)return;const r=s.getState(),t=r.currentSessionId;if(!t)return;const o=(r.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const l=o[o.length-1].info.tokens;l&&typeof l=="object"&&console.debug("Token breakdown:",{base:(l.input||0)+(l.output||0)+(l.reasoning||0),cache:l.cache?(l.cache.read||0)+(l.cache.write||0):0}),r.sessionContextUsage.get(t);const c=window.__zustand_config_store__;if(c){const d=c.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Jf=document.getElementById("root");if(!Jf)throw new Error("Root element not found");sg.createRoot(Jf).render(e.jsx(Ae.StrictMode,{children:e.jsx(Ek,{children:e.jsx(Ik,{children:e.jsx(kk,{children:e.jsx(yk,{apis:Rk})})})})}));if(typeof window<"u"){const s=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(r){console.warn("Failed to notify desktop runtime that renderer is ready:",r)}};s(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&s()})}const $k=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{us as D,rn as S,ms as a,Tm as b,R as c,hw as d,gw as e,Dd as f,gr as g,xw as h,bw as i,$k as m,xf as p,yw as r,Vo as t};