@openchamber/web 1.4.1 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,122 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CpaXrlrC.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-CBMeCbbW.js","assets/index-CbGhBA-v.js","assets/index-Cx6NUrC-.css"])))=>i.map(i=>d[i]);
2
- import{t as zu,c as Hu,j as e,R as Uu,T as Wu,P as Vu,C as qu,A as Gu,a as Ku,b as It,d as Pt,p as gs,e as xs,f as Yu,_ as Ks,g as l,r as Xu,i as zt,I as Qu,k as Ju,l as Zu,m as em,n as tm,o as sm,q as rm,s as nm,u as Mt,v as om,S as am,L as im,w as zc,x as lm,y as cm,z as dm,B as Se,D as Fi,E as ja,F as um,G as kt,K as Ka,H as mm,U as ts,Z as fm,Y as _s,Q as ar,W as ns,O as So,J as pm,M as wr,N as Sr,V as Ur,X as Sa,$ as fs,a0 as Hc,a1 as hm,a2 as gm,a3 as xm,a4 as ym,a5 as bm,a6 as wm,a7 as vm,a8 as Wn,a9 as jm,aa as Sm,ab as ka,ac as Wr,ad as se,ae as _t,af as vr,ag as kr,ah as jn,ai as Ht,aj as km,ak as Nm,al as Uc,am as Ya,an as Yr,ao as Wc,ap as Vr,aq as Cm,ar as ko,as as Mm,at as Ss,au as Oo,av as Sn,aw as Ws,ax as zs,ay as Dm,az as Es,aA as ms,aB as Vc,aC as Am,aD as Em,aE as Im,aF as Tm,aG as Fm,aH as Pm,aI as Rm,aJ as Lm,aK as Om,aL as $m,aM as _m,aN as Bm,aO as zm,aP as _r,aQ as $o,aR as Hm,aS as Xa,aT as Qa,aU as Um,aV as Wm,aW as Vm,aX as so,aY as rr,aZ as Gs,a_ as qm,a$ as Vs,b0 as hn,b1 as Gm,b2 as No,b3 as Km,b4 as kn,b5 as Ja,b6 as Ym,b7 as Xm,b8 as Qm,b9 as Jm,ba as Zm,bb as ef,bc as tf,bd as Na,be as Vn,bf as Co,bg as sf,bh as rf,bi as gn,bj as Rr,bk as nf,bl as of,bm as af,bn as lf,bo as hs,bp as qc,bq as cf,br as Gc,bs as df,bt as uf,bu as Ca,bv as mf,bw as Kc,bx as Ps,by as xn,bz as Yc,bA as ff,bB as Xr,bC as pf,bD as Xc,bE as Za,bF as ei,bG as ti,bH as hf,bI as gf,bJ as xf,bK as yf,bL as bf,bM as wf,bN as vf,bO as Pi,bP as Qc,bQ as jf,bR as Ri,bS as ro,bT as si,bU as Jc,bV as Zc,bW as nr,bX as Li,bY as Mo,bZ as ed,b_ as Ma,b$ as td,c0 as Da,c1 as Sf,c2 as kf,c3 as Nf,c4 as Cf,c5 as Mf,c6 as Df,c7 as Af,c8 as Ef}from"./vendor-.bun-CpaXrlrC.js";import{c as If,l as Tf,g as Ff,r as Pf,d as Rf,a as Lf,b as Of,e as $f,u as _f,f as Bf,h as zf,i as Hf,j as Uf,k as Wf}from"./index-CbGhBA-v.js";function O(...s){return zu(Hu(s))}const sd=(s,r)=>{const t=s??"",n=Math.max(16,r?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>i)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},no=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function ls(s,r){if(!s)return"";const t=no(s);if(t==="/")return"/";const n=r?no(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 _o(s,r){if(!s)return"/";const t=no(s);if(!t||t==="/")return"/";const n=r?no(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Vf({delayDuration:s=0,...r}){return e.jsx(Ku,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function Qe({delayDuration:s=0,...r}){return e.jsx(Vf,{delayDuration:s,children:e.jsx(Uu,{"data-slot":"tooltip",...r})})}function Je({...s}){return e.jsx(Wu,{"data-slot":"tooltip-trigger",...s})}function Xe({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(Vu,{children:e.jsxs(qu,{"data-slot":"tooltip-content",sideOffset:r,className:O("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(Gu,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Bo=null;const Oi=()=>{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}}},qf=()=>{if(typeof window>"u"||!window.localStorage)return Oi();const s=window.localStorage,r=Oi();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}}},rs=()=>(Bo||(Bo=qf()),Bo),ri={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Gf={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function $i(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const qs={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)"}}},qn={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...qs.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:qn.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...qs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:qn.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...qs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:qn.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...qs.tool.inline})},Fe=It()(Pt(gs((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,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(ri);if(o===1){for(const[i]of a)n.style.removeProperty($i(i));return}for(const[i,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty($i(i),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=r(),n=document.documentElement,o=t/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(i=>i.providerID===t&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===t&&i.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{s(o=>{const a=o.recentModels.filter(i=>!(i.providerID===t&&i.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||s(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)},setMultiRunLauncherOpen:t=>{s(n=>({isMultiRunLauncherOpen:t,multiRunLauncherPrefillPrompt:t?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:t=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:t,isSessionSwitcherOpen:!1})}}),{name:"ui-store",storage:xs(()=>rs()),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})}),{name:"ui-store"})),Xt=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Dt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,ni=()=>typeof window>"u"?!1:!Xt()&&!Dt(),ir=()=>Xt()?window.opencodeDesktop??null:null,rd=()=>{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},nd=async()=>{const s=ir();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},Kf=async()=>{const s=ir();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Yf=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Qr=async()=>{const s=rd();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Xf=async s=>{const r=rd();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},Qf=async s=>{const r=ir();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)}}},Jf=async s=>{const r=ir();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)}}},Zf=async s=>{const r=ir();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)}}},ep=async()=>{const s=ir();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},tp=async s=>{const r=ir();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},sp=async()=>{const s=ir();if(!s||!s.restartToUpdate)return!1;try{return await s.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};async function rp(){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 np(){return Xt()?"desktop":ni()?"web":null}const _i={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Do=It()((s,r)=>({..._i,checkForUpdates:async()=>{const t=np();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await ep():t==="web"&&(n=await rp()),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 tp(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 sp()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(_i)}})),op="/api",ap=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,ip=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(ap.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}},lp=()=>{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},Cn=s=>s.replace(/\\/g,"/"),zo=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class cp{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(r=op){const n=lp()||r;this.baseUrl=ip(n),this.client=Yu({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({query: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({query: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({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});return Array.isArray(r.data)?r.data:[]}async createSession(r){const t=await this.client.session.create({query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{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({path:{id:r},query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({path:{id:r},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||!1}async updateSession(r,t){const n=await this.client.session.update({path:{id:r},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{title:t}});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r){return(await this.client.session.messages({path:{id:r},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const t=r.toLowerCase();return t.startsWith("text/")&&t!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async convertHeicToJpeg(r){try{const t=(await Ks(async()=>{const{default:f}=await import("./vendor-.bun-CpaXrlrC.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),i=new Uint8Array(a.length);for(let f=0;f<a.length;f++)i[f]=a.charCodeAt(f);const c=new Blob([i],{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(!this.shouldNormalizeToTextPlain(r.mime))return r;let t=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),a=r.url.substring(n);t=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:t}}async sendMessage(r){const t=Date.now(),n=r.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const i=await this.normalizeFilePart(a),c={type:"file",mime:i.mime,filename:i.filename,url:i.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 i of a.files){const c=await this.normalizeFilePart(i),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({path:{id:r.id},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,parts:o}}),n}async abortSession(r){return!!(await this.client.session.abort({path:{id:r},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,throwOnError:!0})).data}async revertSession(r,t,n){const o=await this.client.session.revert({path:{id:r},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{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({path:{id:r},query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!t.data)throw new Error("Failed to unrevert session");return t.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const i=await a.json().catch(()=>null);return!i||typeof i!="object"?{}:i}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async respondToPermission(r,t,n){return(await this.client.postSessionIdPermissionsPermissionId({path:{id:r,permissionID:t},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{response:n}})).data||!1}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({query: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({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}catch{return[]}}subscribeToEvents(r,t,n,o){this.sseAbortController&&this.sseAbortController.abort();const a=new AbortController;this.sseAbortController=a;let i;return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const c=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",c);const d=async u=>{try{const m={query:c?{directory:c}:void 0,signal:a.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:p=>{p instanceof Error&&p.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",p),t&&!a.signal.aborted&&t(p))},onSseEvent:p=>{if(a.signal.aborted)return;p.id&&typeof p.id=="string"&&(i=p.id);const h=p.data;h&&typeof h=="object"&&r(h)}};i&&(m.lastEventId=i,m.headers={...m.headers||{},"Last-Event-ID":i});const f=await this.client.event.subscribe(m);n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const p of f.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}if(!a.signal.aborted){const p=Math.min(3e3*Math.pow(2,u),3e4);await new Promise(h=>setTimeout(h,p)),await d(u+1)}}catch(m){if(m?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",m),t&&t(m);const f=Math.min(3e3*Math.pow(2,u),3e4);await new Promise(p=>setTimeout(p,f)),a.signal.aborted||await d(u+1)}};try{await d(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortController===a&&(this.sseAbortController=null)}})(),()=>{this.sseAbortController===a&&(this.sseAbortController=null),a.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}
3
- // 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({query: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({query: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({query: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=zo();if(t?.createDirectory)try{return await t.createDirectory(r)}catch(a){const i=a instanceof Error?a.message:String(a);throw new Error(i||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r){const t=zo();if(t)try{const n=await t.listDirectory(r||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:Cn(o.path),isDirectory:!!o.isDirectory,isFile:!o.isDirectory,isSymbolicLink:!1}))}catch(n){throw console.error("Failed to list directory contents:",n),n}try{const n=new URLSearchParams;r&&r.trim().length>0&&n.set("path",r);const o=n.toString(),a=await fetch(`${this.baseUrl}/fs/list${o?`?${o}`:""}`);if(!a.ok){const c=await a.json().catch(()=>({})),d=typeof c.error=="string"?c.error:"Failed to list directory";throw new Error(d)}const i=await a.json();return!i||!Array.isArray(i.entries)?[]:i.entries}catch(n){throw console.error("Failed to list directory contents:",n),n}}async searchFiles(r,t){const n=zo(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Cn(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=Cn(f.path),h=p.split("/").filter(Boolean).pop()||p,y=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?Cn(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 i=new URLSearchParams;o&&o.length>0&&i.set("directory",o),typeof r=="string"&&i.set("q",r),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&i.set("limit",String(t.limit));const c=`${this.baseUrl}/fs/search${i.toString()?`?${i.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 nd();if(r)return r;try{const t=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok){const o=await t.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await t.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(t){return console.warn("Failed to resolve filesystem home directory:",t),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const t=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",t,"with path:",r);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},i=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const Le=new cp,Aa=new Set;function Ao(s){return Aa.add(s),()=>{Aa.delete(s)}}function ps(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 Aa)try{const i=a(o);i instanceof Promise&&i.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function yn(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const oi="Updating OpenCode configuration...";let $s=0,or=oi;const Ea=new Set;function oo(){const s={isUpdating:$s>0,message:or};Ea.forEach(r=>r(s))}function ks(s){$s+=1,$s===1?(or=s||oi,oo()):s&&(or=s,oo())}function ss(){$s!==0&&($s-=1,$s===0&&(or=oi,oo()))}function Ns(s){or===s&&$s>0||(or=s,$s>0&&oo())}function dp(s){return Ea.add(s),s({isUpdating:$s>0,message:or}),()=>{Ea.delete(s)}}function up(){return{isUpdating:$s>0,message:or}}const Mn=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},Lr=s=>s.builtIn||s.native===!0,od=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},ad=s=>s.filter(r=>!od(r)),dn="useAgentsStore",ao=s=>new Promise(r=>setTimeout(r,s)),mp=2e4,Bi=300,zi=4,fp=800,pp=200,hp=2e3,Jr=It()(Pt(gs((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;let n=null;for(let o=0;o<3;o++)try{const a=await Le.listAgents(),i=Mn(),c=i?`?directory=${encodeURIComponent(i)}`:"",d=await Promise.all(a.map(async u=>{try{const m=await fetch(`/api/config/agents/${encodeURIComponent(u.name)}${c}`);if(m.ok){const f=await m.json(),p=f.scope??f.sources?.md?.scope??f.sources?.json?.scope;return{...u,scope:p}}}catch{}return u}));return s({agents:d,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),s({agents:t,isLoading:!1}),!1},createAgent:async t=>{ks("Creating agent configuration…");let n=!1;try{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.tools&&Object.keys(t.tools).length>0&&(o.tools=t.tools),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),t.scope&&(o.scope=t.scope);const a=Mn(),i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},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 Br({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadAgents();return m&&ps("agents",{source:dn}),m}catch{return!1}finally{n||ss()}},updateAgent:async(t,n)=>{ks("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.tools!==void 0&&(a.tools=n.tools),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const i=Mn(),c=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},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 Br({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadAgents();return f&&ps("agents",{source:dn}),f}catch{return!1}finally{o||ss()}},deleteAgent:async t=>{ks("Deleting agent configuration…");let n=!1;try{const o=Mn(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE"}),c=await i.json().catch(()=>null);if(!i.ok){const m=c?.error||"Failed to delete agent";throw new Error(m)}if(c?.requiresReload??!0)return n=!0,await Br({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadAgents();return u&&ps("agents",{source:dn}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||ss()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return ad(t)}}),{name:"agents-store",storage:xs(()=>rs()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Jr);async function gp(s){const r=typeof s=="number"&&s>0?Math.min(s,Bi):0;r>0&&await ao(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<mp;){n+=1,Ns(`Waiting for OpenCode… (attempt ${n})`);try{if(await Le.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=zi&&a<1200?Bi:Math.min(fp+Math.max(0,n-zi)*pp,hp);await ao(i)}throw o||new Error("OpenCode did not become ready in time")}async function Br(s={}){const{message:r,delayMs:t}=s;try{Ns(r||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("agents-store"),window.localStorage.removeItem("config-store"))}catch{}try{await gp(t),Ns("Refreshing providers and agents…");const n=lt.getState(),o=Jr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),ps("agents",{source:dn})}catch{Ns("OpenCode reload failed. Please retry refreshing configuration manually."),await ao(1500)}finally{ss()}}async function xp(s){await Br(s)}async function un(s){ks("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 n=t?.error||"Failed to reload configuration";throw new Error(n)}t?.requiresReload?await Br({message:t.message,delayMs:t.reloadDelayMs}):await Br(s)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),Ns("Failed to reload configuration. Please try again."),await ao(2e3),ss(),r}}let Hi=null;Hi||(Hi=Ao(s=>{if(s.source!==dn&&yn(s,"agents")){const{loadAgents:r}=Jr.getState();r()}}));let id=null;const Ui=s=>{id=s},Nr=()=>id,Rs=It()(Pt(gs((s,r)=>({queuedMessages:{},queueModeEnabled:!1,addToQueue:(t,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};s(i=>{const c=i.queuedMessages[t]??[];return{queuedMessages:{...i.queuedMessages,[t]:[...c,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const i=(o.queuedMessages[t]??[]).filter(c=>c.id!==n);if(i.length===0){const{[t]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:i}}})},popToInput:(t,n)=>{const i=(r().queuedMessages[t]??[]).find(c=>c.id===n);return i?(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}}}),i):null},clearQueue:t=>{s(n=>{const{[t]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{s({queuedMessages:{}})},setQueueMode:t=>{s({queueModeEnabled:t}),es({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:xs(()=>rs()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),Wi=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},yp=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},bp=s=>{const r=Fe.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},wp=async()=>{if(typeof window>"u")return null;if(Xt()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return Wi(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=yp(r);return Wi(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}},Gn=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.pinnedDirectories)&&s.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(s.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},vp=s=>{if(!Array.isArray(s))return;const r=[],t=new Set;for(const n of s){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",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||!i||!c||t.has(a)||(t.add(a),r.push({id:a,label:i,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},ld=()=>{const s=Fe.persist;if(s&&typeof s=="object")return s},cd=()=>Nr()?.settings??null,Kn=s=>{const r=Fe.getState(),t=Rs.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)},Vi=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),Array.isArray(r.approvedDirectories)&&(t.approvedDirectories=r.approvedDirectories.filter(o=>typeof o=="string"&&o.length>0)),Array.isArray(r.securityScopedBookmarks)&&(t.securityScopedBookmarks=r.securityScopedBookmarks.filter(o=>typeof o=="string"&&o.length>0)),Array.isArray(r.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(o=>typeof o=="string"&&o.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.defaultAgent=="string"&&r.defaultAgent.length>0&&(t.defaultAgent=r.defaultAgent),typeof r.queueModeEnabled=="boolean"&&(t.queueModeEnabled=r.queueModeEnabled);const n=vp(r.skillCatalogs);return n&&(t.skillCatalogs=n),t},jp=async()=>{const s=cd();if(s)try{const r=await s.load();return Vi(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 Vi(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},dd=async()=>{if(typeof window>"u")return;const s=ld(),r=t=>{Gn(t);const n=()=>Kn(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=Xt()?await Qr():await jp();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},es=async s=>{if(typeof window>"u")return;if(Xt()){try{const t=await Xf(s);t&&(Gn(t),Kn(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=cd();if(r)try{const t=await r.save(s);t&&(Gn(t),Kn(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&&(Gn(n),Kn(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},ud=async()=>{if(typeof window>"u")return;const s=ld();try{const r=await wp();if(!r)return;const t=()=>bp(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)}},Sp="https://models.dev/api.json",kp="/api/openchamber/models-metadata",qi="opencode",Gi="big-pickle",Np=async()=>{try{if(Xt()){const n=await Qr();return{defaultModel:n?.defaultModel,defaultAgent:n?.defaultAgent}}const s=Nr()?.settings;if(s)try{const o=(await s.load())?.settings;if(o)return{defaultModel:typeof o?.defaultModel=="string"?o.defaultModel:void 0,defaultAgent:typeof o?.defaultAgent=="string"?o.defaultAgent:void 0}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const t=await r.json();return{defaultModel:typeof t?.defaultModel=="string"?t.defaultModel:void 0,defaultAgent:typeof t?.defaultAgent=="string"?t.defaultAgent:void 0}}catch{return{}}},Ki=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]}},Cp=s=>s?.toLowerCase?.()??"",Mp=s=>s==="primary"||s==="all"||s===void 0||s===null,bn=s=>typeof s=="object"&&s!==null,io=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),Dp=s=>{if(!bn(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!io(t)||n&&!io(n))return!1}return!0},Ap=s=>{if(!bn(s))return!1;const r=s;return r.models===void 0||bn(r.models)},md=(s,r)=>{const t=Cp(s);return!t||!r?"":`${t}/${r}`},Ep=s=>{const r=new Map;if(!bn(s))return r;for(const[t,n]of Object.entries(s)){if(!Ap(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!bn(a)))for(const[i,c]of Object.entries(a)){if(!Dp(c))continue;const d=typeof i=="string"&&i.length>0?i: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:io(c.modalities.input)?c.modalities.input:void 0,output:io(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=md(o,d);m&&r.set(m,u)}}return r},Ip=async()=>{if(typeof fetch!="function")return new Map;const s=[kp,Sp];for(const r of s){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(r,a);if(!i.ok)throw new Error(`Metadata request to ${r} returned status ${i.status}`);const c=await i.json();return Ep(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},Tp=s=>new Promise(r=>setTimeout(r,s)),lt=It()(Pt(gs((s,r)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultAgent:void 0,loadProviders:async()=>{const t=r().providers,n=r().defaultProviders;let o=null;for(let a=0;a<3;a++)try{const i=Ip(),c=await Le.getProviders(),d=Array.isArray(c?.providers)?c.providers:[],u=c?.default||{},m=d.map(p=>{const h=p.models??{},y=Object.keys(h).map(g=>h[g]);return{...p,models:y}});s({providers:m,defaultProviders:u});const f=await i;f.size>0&&s({modelsMetadata:f});return}catch(i){o=i;const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}console.error("Failed to load providers:",o),s({providers:t,defaultProviders:n})},setProvider:t=>{const{providers:n}=r(),o=n.find(a=>a.id===t);if(o){const i=o.models[0]?.id||"";s({currentProviderId:t,currentModelId:i,selectedProviderId:t})}},setModel:t=>{s({currentModelId:t})},setSelectedProvider:t=>{s({selectedProviderId:t})},saveAgentModelSelection:(t,n,o)=>{s(a=>({agentModelSelections:{...a.agentModelSelections,[t]:{providerId:n,modelId:o}}}))},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async()=>{const t=r().agents;let n=null;for(let o=0;o<3;o++)try{const[a,i]=await Promise.all([Le.listAgents(),Np()]),c=Array.isArray(a)?a:[];s({agents:c,settingsDefaultModel:i.defaultModel,settingsDefaultAgent:i.defaultAgent});const{providers:d}=r();if(c.length===0)return s({currentAgentName:void 0}),!0;const u=c.filter(x=>Mp(x.mode)),f=u.find(x=>x.name==="build")||u[0]||c[0];let p;const h=(x,v)=>{const S=d.find(N=>N.id===x);return S?S.models.some(N=>N.id===v):!1},y={};if(i.defaultAgent){const x=c.find(v=>v.name===i.defaultAgent);x?p=x:y.defaultAgent=""}p||(p=f),s({currentAgentName:p.name});let g,w;if(i.defaultModel){const x=Ki(i.defaultModel);x&&h(x.providerId,x.modelId)?(g=x.providerId,w=x.modelId):y.defaultModel=""}if(!g&&p?.model?.providerID&&p?.model?.modelID&&h(p.model.providerID,p.model.modelID)&&(g=p.model.providerID,w=p.model.modelID),!g)if(h(qi,Gi))g=qi,w=Gi;else{const x=d[0];x&&x.models[0]&&(g=x.id,w=x.models[0].id)}return g&&w&&s({currentProviderId:g,currentModelId:w}),Object.keys(y).length>0&&(s({settingsDefaultModel:y.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultAgent:y.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),es(y).catch(()=>{})),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),s({agents:t}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a}=r();if(s({currentAgentName:t}),t&&typeof window<"u"){const i=window.__zustand_session_store__;if(i){const c=i.getState(),{currentSessionId:d,isOpenChamberCreatedSession:u,initializeNewOpenChamberSession:m,getAgentModelForSession:f}=c;d&&i.setState(p=>{const h=new Map(p.currentAgentContext);return h.set(d,t),{currentAgentContext:h}}),d&&u(d)&&(f(d,t)||m(d,n))}}if(t&&typeof window<"u"){const i=window.__zustand_session_store__;if(i){const{currentSessionId:d,getAgentModelForSession:u}=i.getState();if(d&&u(d,t))return}if(a){const d=Ki(a);if(d&&o.find(m=>m.id===d.providerId)?.models.some(m=>m.id===d.modelId)){s({currentProviderId:d.providerId,currentModelId:d.modelId});return}}const c=n.find(d=>d.name===t);if(c?.model?.providerID&&c?.model?.modelID){const d=o.find(u=>u.id===c.model.providerID);d&&d.models.find(m=>m.id===c.model.modelID)&&s({currentProviderId:c.model.providerID,currentModelId:c.model.modelID,selectedProviderId:c.model.providerID})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Le.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await Tp(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{console.log("Starting app initialization...");const t=await r().checkConnection();if(console.log("Connection check result:",t),!t){console.log("Server not connected"),s({isConnected:!1});return}console.log("Initializing app..."),await Le.initApp(),console.log("Loading providers..."),await r().loadProviders(),console.log("Loading agents..."),await r().loadAgents(),s({isInitialized:!0,isConnected:!0}),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=md(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return ad(t)}}),{name:"config-store",storage:xs(()=>rs()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=lt);let Yi=null;Yi||(Yi=Ao(async s=>{const r=[];if(yn(s,"agents")){const{loadAgents:t}=lt.getState();r.push(t().then(()=>{}))}if(yn(s,"providers")){const{loadProviders:t}=lt.getState();r.push(t())}r.length>0&&await Promise.all(r)}));const Vt={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Fp=180,is=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Zr(s){const r=is();return r?r.checkIsGitRepository(s):If(s)}async function Pp(s){const r=is();return r?r.getGitStatus(s):Ff(s)}async function fd(s){const r=is();return r?r.getGitBranches(s):Wf(s)}async function Rp(s,r){const t=is();return t?t.deleteGitBranch(s,r):Rf(s,r)}async function Lp(s,r){const t=is();return t?t.deleteRemoteBranch(s,r):Lf(s,r)}async function Op(s){const r=is();return r?r.listGitWorktrees(s):Tf(s)}async function $p(s,r){const t=is();return t?t.addGitWorktree(s,r):Of(s,r)}async function pd(s,r){const t=is();return t?t.removeGitWorktree(s,r):Pf(s,r)}async function _p(s){const r=is();return r?r.ensureOpenChamberIgnored(s):Uf(s)}async function Bp(){const s=is();return s?s.getGitIdentities():Hf()}async function zp(s){const r=is();return r?r.createGitIdentity(s):Bf(s)}async function Hp(s,r){const t=is();return t?t.updateGitIdentity(s,r):_f(s,r)}async function Up(s){const r=is();return r?r.deleteGitIdentity(s):$f(s)}async function Wp(s){const r=is();return r?r.getCurrentGitIdentity(s):zf(s)}const Vp=".openchamber",Ys=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Xi=(s,r)=>{const t=Ys(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},hd=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",qp=async s=>{try{await Le.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function Gp(s,r){const t=Ys(s),n=Xi(t,Vp);return await qp(n),Xi(n,r)}async function gd(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,i=Ys(r),c=await Gp(i,t),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await $p(i,d),{path:c,branch:n,label:hd(n),projectDirectory:i,relativePath:c.startsWith(`${i}/`)?c.slice(i.length+1):c}}async function Qi(s){const{projectDirectory:r,path:t,force:n}=s,o=Ys(r);await pd(o,{path:t,force:n})}async function Kp(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:i}=s,c=Ys(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await pd(c,{path:t,force:o}),d&&(await Rp(c,{branch:d,force:!0}),a))try{await Lp(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function lo(s){const r=Ys(s);return Op(r)}async function Ia(s){const r=Ys(s),t=await Pp(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function co(s,r){const t=Ys(s),n=Ys(r.worktree);return{path:n,branch:r.branch??"",label:hd(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const Yp=new Set(["init","review"]),Or=s=>Yp.has(s.name),mn="useCommandsStore",Ta=s=>new Promise(r=>setTimeout(r,s)),Xp=2e4,Ji=300,Zi=4,Qp=800,Jp=200,Zp=2e3,en=It()(Pt(gs((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=await Le.listCommandsWithDetails(),i=yt.getState().currentDirectory,c=i?`?directory=${encodeURIComponent(i)}`:"",d=await Promise.all(a.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${c}`);if(m.ok){const f=await m.json(),p=f.scope??f.sources?.md?.scope;return{...u,scope:p}}}catch{}return u}));return s({commands:d,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{ks("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),t.scope&&(o.scope=t.scope),console.log("[CommandsStore] Command config to save:",o);const a=yt.getState().currentDirectory,i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},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 Ho({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&ps("commands",{source:mn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||ss()}},updateCommand:async(t,n)=>{ks("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=yt.getState().currentDirectory,c=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json"},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 Ho({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&ps("commands",{source:mn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||ss()}},deleteCommand:async t=>{ks("Deleting command configuration…");let n=!1;try{const o=yt.getState().currentDirectory,a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE"}),c=await i.json().catch(()=>null);if(!i.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 Ho({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&ps("commands",{source:mn}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||ss()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:xs(()=>rs()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=en);async function eh(s){const r=typeof s=="number"&&s>0?Math.min(s,Ji):0;r>0&&await Ta(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Xp;){n+=1,Ns(`Waiting for OpenCode… (attempt ${n})`);try{if(await Le.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=Zi&&a<1200?Ji:Math.min(Qp+Math.max(0,n-Zi)*Jp,Zp);await Ta(i)}throw o||new Error("OpenCode did not become ready in time")}async function Ho(s={}){const{message:r,delayMs:t}=s;try{Ns(r||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("commands-store"),window.localStorage.removeItem("config-store"))}catch(n){console.warn("[CommandsStore] Failed to prepare config refresh:",n)}try{await eh(t),Ns("Refreshing providers and commands…");const n=lt.getState(),o=en.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),ps("commands",{source:mn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Ns("OpenCode reload failed. Please retry refreshing configuration manually."),await Ta(1500)}finally{ss()}}let el=null;el||(el=Ao(s=>{if(s.source!==mn&&yn(s,"commands")){const{loadCommands:r}=en.getState();r()}}));const th=3e4,sh=40,rh=60,nh=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},ai=It()(Pt((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=rh){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=nh(a,i,o),d=Date.now(),u=r().cache[c];if(u&&d-u.timestamp<th)return u.files;const m=r().inFlight[c];if(m)return m;const f=Le.searchFiles(i,{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>sh;){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 i={...a.cache},c=a.cacheKeys.filter(m=>m.startsWith(o)?(delete i[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"})),Ot=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var oh={};let js=null;const vs=rs(),tl=vs.getItem("lastDirectory"),ah=typeof tl=="string"&&tl.length>0,Dn=(s,r)=>((r?.showOverlay??!0)&&ks("Switching project directory…"),Le.setOpenCodeWorkingDirectory(s).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),An=(s,r,t)=>{const{showOverlay:n}=r,o=()=>{try{ye.getState().loadSessions()}catch(a){console.error("Failed to reload sessions after directory change:",a)}};(async()=>{let a=null;try{a=await s}catch(i){console.error("Failed to update OpenCode working directory:",i),n&&(Ns("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),ss()),t?.(a),o();return}try{if(a&&a.restarted){try{typeof window<"u"&&window.localStorage&&window.localStorage.removeItem("commands-store")}catch(i){console.warn("Failed to reset commands-store cache:",i)}await xp({message:"Refreshing OpenCode configuration…"});try{await en.getState().loadCommands();try{ps("commands",{source:"useCommandsStore"})}catch(i){console.warn("Failed to emit command configuration change:",i)}}catch(i){console.warn("Failed to reload commands after directory change:",i)}}else n&&ss()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(Ns("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),ss())}finally{t?.(a),o()}})()},En=s=>{try{ai.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},ih=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},lh=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},Yn=(s,r)=>{const t=lh(s,r);return ih(t)},uo=()=>{if(typeof window<"u"){const r=vs.getItem("homeDirectory")||js||null,t=vs.getItem("lastDirectory");if(t)return Yn(t,r);if(js)return js;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 js=n,vs.setItem("homeDirectory",n),n;if(r)return js=r,r}const s=typeof process<"u"&&oh?.HOME;return s||process?.cwd?.()||"/"},ch=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},dh=s=>(js=s,typeof window<"u"&&vs.setItem("homeDirectory",s),es({homeDirectory:s}),s),xd=async()=>{const s=n=>{const o=ch(n);return o?dh(o):null};try{const n=await Le.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Le.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 nd(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=uo(),t=s(r);return t||r},yr=uo();yr&&Le.setDirectory(yr);const uh=!!(yr&&yr!=="/"),yt=It()(Pt((s,r)=>({currentDirectory:yr,directoryHistory:[yr],historyIndex:0,homeDirectory:yr,hasPersistedDirectory:ah,isHomeReady:uh,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=js||r().homeDirectory||vs.getItem("homeDirectory"),a=Yn(t,o);Ot()&&console.log("[DirectoryStore] setDirectory called with path:",a);const i=n?.showOverlay??!0;Le.setDirectory(a),En();const c=Dn(a,{showOverlay:i});Ot()&&console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),s(d=>{const u=[...d.directoryHistory.slice(0,d.historyIndex+1),a];return vs.setItem("lastDirectory",a),es({lastDirectory:a}),{currentDirectory:a,directoryHistory:u,historyIndex:u.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),An(c,{showOverlay:i},()=>{s(d=>d.currentDirectory!==a?{}:d.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})},goBack:()=>{const t=r();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];Le.setDirectory(o),En();const a=Dn(o);vs.setItem("lastDirectory",o),es({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),An(a,{showOverlay:!0},()=>{s(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goForward:()=>{const t=r();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];Le.setDirectory(o),En();const a=Dn(o);vs.setItem("lastDirectory",o),es({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),An(a,{showOverlay:!0},()=>{s(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=js||r().homeDirectory||uo();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=js||uo();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=js||r().homeDirectory||await xd();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;js=o;const a=n.homeDirectory!==o,i=vs.getItem("lastDirectory"),c=typeof i=="string"&&i.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?Yn(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(g=>Yn(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=!0):(h||p)&&(y.currentDirectory=m,y.directoryHistory=f,y.historyIndex=Math.min(n.historyIndex,f.length-1),y.isSwitchingDirectory=!0),s(()=>y),(d||h)&&u){const g=d?o:m;Le.setDirectory(g),En(),vs.setItem("lastDirectory",g),es({lastDirectory:g});const w=Dn(g,{showOverlay:!1});An(w,{showOverlay:!1},()=>{s(x=>x.currentDirectory!==g?{}:x.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}es({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&xd().then(s=>{yt.getState().synchronizeHomeDirectory(s)});const yd=rs(),bd="oc.sessionSelectionByDirectory",Uo=".openchamber",mh=()=>{try{const s=yd.getItem(bd);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 Xn=null;const ii=()=>(Xn||(Xn=mh()),Xn),wd=s=>{Xn=s;try{yd.setItem(bd,JSON.stringify(s))}catch{}},vd=s=>{if(!s)return null;const t=ii()[s];return typeof t=="string"?t:null},dr=(s,r)=>{if(!s)return;const t={...ii()};r?t[s]=r:delete t[s],wd(t)},sl=(s,r)=>{if(!s)return;const t=vd(s);if(!t)return;if(!new Set(r).has(t)){const o={...ii()};delete o[s],wd(o)}},rl=async(s,r)=>{const t=s.status??await Ia(s.path).catch(()=>{});await Kp({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},Wt=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},Qs=(s,r)=>{const t=s.find(n=>n.id===r);return t?Wt(t.directory??null):null},fh=async(s,r,t)=>{const n=Wt(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:Wt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await lo(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(t);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const i=new Map;a.forEach(u=>{const m=co(n,u),f=Wt(m.path)??m.path;f!==n&&i.set(f,m)});let c=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=i.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},et=It()(Pt(gs((s,r)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],loadSessions:async()=>{s({isLoading:!0,error:null});try{const n=yt.getState().currentDirectory??Le.getDirectory()??null,o=Le.getApiClient(),a=async b=>{const C=await o.session.list({query:b?{directory:b}:void 0});return Array.isArray(C.data)?C.data:[]},i=Wt(n),c=i?await Zr(i).catch(()=>!1):!1,d=await a(i||null),u=[];let m=[];if(n&&c&&i){const b=`${i}/${Uo}`;try{const C=new Set;(await Le.listLocalDirectory(i)).some($=>$.isDirectory&&$.name===Uo)&&(await Le.listLocalDirectory(b)).filter(q=>q.isDirectory).forEach(q=>{const ce=/^([A-Za-z]:)?\//.test(q.path)?q.path:`${b}/${q.name}`;C.add(Wt(ce)??ce)});const L=await lo(i);Array.isArray(L)&&(m=L.map($=>co(i,$)).filter($=>$.path.includes(`/${Uo}/`)),m.forEach($=>C.add($.path))),C.size>0&&(await Promise.allSettled(Array.from(C).map(q=>a(q)))).forEach(q=>{q.status==="fulfilled"&&Array.isArray(q.value)&&u.push(...q.value)})}catch{m=[]}}const f=new Set;i&&f.add(i),m.forEach(b=>{const C=Wt(b.path);C&&f.add(C)});const p=[...d,...u].filter(b=>{const C=b.directory??i??null,A=Wt(C);return A?f.has(A):!1}),h=r(),y=h.lastLoadedDirectory??null,g=n!==y;let w=[...p],x=h.currentSessionId;const v=b=>{w=[b,...w.filter(C=>C.id!==b.id)]};if(g)x=w.length>0?w[0].id:null;else if(x){if(!w.some(C=>C.id===x)){const C=h.sessions.find(A=>A.id===x);if(C)v(C);else try{const A=await Le.getSession(x);v(A)}catch{x=w.length>0?w[0].id:null}}}else x=w.length>0?w[0].id:null;const S=w.reduce((b,C)=>(b.some(A=>A.id===C.id)||b.push(C),b),[]);x&&!S.some(b=>b.id===x)&&(x=S.length>0?S[0].id:null);const N=new Set(S.map(b=>b.id)),k=(b=>{if(!b)return null;const C=Qs(S,b);if(C)return C;const A=Qs(h.sessions,b);return A||null})(x)??i??n??null;if(n&&sl(n,N),k){sl(k,N);const b=vd(k);b&&N.has(b)&&(x=b)}let F=null;try{F=await fh(S,n,h.worktreeMetadata)}catch(b){console.debug("Failed to refresh worktree metadata during session load:",b)}const I=(()=>{const b=F??h.worktreeMetadata;if(!g||!i)return b;const C=new Map;return b.forEach((A,P)=>{Wt(A.projectDirectory)===i&&C.set(P,A)}),C})(),M=(()=>{if(!x)return i??null;const b=I.get(x)?.path;if(b)return Wt(b)??b;const C=Qs(S,x);return C||(i??null)})();try{Le.setDirectory(M??void 0)}catch(b){console.warn("Failed to sync OpenCode directory after session load:",b)}s({sessions:S,currentSessionId:x,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:I,availableWorktrees:m}),dr(M??n,x)}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(),i=Wt(a.currentDirectory),c=Wt(n??Le.getDirectory()??i),d=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=r(),m=new Set(u.sessions.map(y=>y.id)),f={id:d,title:t||"New session",parentID:o??void 0,directory:c??null,projectID:u.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(s(y=>({sessions:[f,...y.sessions],currentSessionId:d,webUICreatedSessions:new Set([...y.webUICreatedSessions,d]),isLoading:!1})),c)try{Le.setDirectory(c)}catch(y){console.warn("Failed to sync OpenCode directory after session creation:",y)}const p=y=>{s(g=>({sessions:g.sessions.map(x=>x.id===d?y:x),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(g.webUICreatedSessions).filter(x=>x!==d),y.id])})),dr(c??null,y.id)},h=async()=>{const y=Le.getApiClient(),g=20;for(let w=0;w<g;w+=1){try{const x=await y.session.list({query:c?{directory:c}:void 0}),S=(Array.isArray(x.data)?x.data:[]).find(N=>!(m.has(N.id)||t&&N.title&&N.title!==t));if(S)return S}catch(x){console.debug("Session poll attempt failed:",x)}await new Promise(x=>setTimeout(x,2e3))}return null};try{const y=()=>Le.createSession({title:t,parentID:o??void 0});let g=null;try{g=c?await Le.withDirectory(c,y):await y()}catch(w){console.warn("Direct session create failed or timed out, falling back to polling:",w)}return g||(g=await h()),g?(p(g),g):(s(w=>({sessions:w.sessions.filter(x=>x.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(w.webUICreatedSessions).filter(x=>x!==d)),isLoading:!1,error:"Failed to create session"})),null)}catch(y){return s(g=>({sessions:g.sessions.filter(w=>w.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(g.webUICreatedSessions).filter(w=>w!==d)),isLoading:!1,error:y instanceof Error?y.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{s({isLoading:!0,error:null});const o=r().worktreeMetadata.get(t),a=Qs(r().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await rl(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Le.deleteSession(t);if(!(i?await Le.withDirectory(i,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(w=>w.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(w=>Wt(w.path)!==Wt(o.path)):p.availableWorktrees;return{sessions:h,currentSessionId:m,isLoading:!1,worktreeMetadata:y,availableWorktrees:g}});const f=i??Le.getDirectory()??null;return dr(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 i=[],c=[],d=new Set,u=[],m=new Set;for(const w of o)try{const x=r().worktreeMetadata.get(w),v=Qs(r().sessions,w),S=x?.path??v;x&&n?.archiveWorktree&&!m.has(x.path)&&(await rl(x,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(w),u.push({path:x.path,projectDirectory:x.projectDirectory}),m.add(x.path));const N=()=>Le.deleteSession(w);(S?await Le.withDirectory(S,N):await N())?(i.push(w),x?.path&&!u.some(k=>k.path===x.path)&&u.push({path:x.path,projectDirectory:x.projectDirectory})):c.push(w)}catch{c.push(w)}const f=yt.getState();u.forEach(({path:w,projectDirectory:x})=>{f.currentDirectory===w&&f.setDirectory(x,{showOverlay:!1})});const p=new Set(i),h=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let y=null;s(w=>{const x=w.sessions.filter(j=>!p.has(j.id));w.currentSessionId&&p.has(w.currentSessionId)?y=null:y=w.currentSessionId;const v=new Map(w.worktreeMetadata);for(const j of p)v.delete(j);for(const j of d)v.delete(j);const S=new Set(u.map(j=>Wt(j.path)).filter(j=>!!j)),N=S.size>0?w.availableWorktrees.filter(j=>!S.has(Wt(j.path)??j.path)):w.availableWorktrees;return{sessions:x,currentSessionId:y,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:N}});const g=Le.getDirectory()??null;return dr(g,y),{deletedIds:i,failedIds:c}},updateSessionTitle:async(t,n)=>{try{const o=Qs(r().sessions,t),a=r().worktreeMetadata.get(t),i=()=>Le.updateSession(t,n),c=a?.path??o,d=c?await Le.withDirectory(c,i):await i();s(u=>({sessions:u.sessions.map(m=>m.id===t?d:m)}))}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=Qs(r().sessions,t),o=Le.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Le.getDirectory();return o.session.share({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Le.withDirectory(i,c):await c();return d.data?(s(u=>({sessions:u.sessions.map(m=>m.id===t?d.data: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=Qs(r().sessions,t),o=Le.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Le.getDirectory();return o.session.unshare({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Le.withDirectory(i,c):await c();return d.data?(s(u=>({sessions:u.sessions.map(m=>m.id===t?d.data: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=Le.getDirectory()??null;dr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:()=>{const{sessions:t}=r();return t},applySessionMetadata:(t,n)=>{!t||!n||s(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const i=o.sessions[a],c=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,m={...i,...n,time:c,summary:d,share:u},f=m.title!==i.title||m.parentID!==i.parentID||m.directory!==i.directory||m.version!==i.version||m.projectID!==i.projectID||JSON.stringify(m.time)!==JSON.stringify(i.time)||JSON.stringify(m.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(i.share??null),p=[...o.sessions];return p[a]=f?m:i,f?{sessions:p}:o})},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}}),c&&dr(c,null),n&&dr(n,t))},updateSession:t=>{s(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:xs(()=>rs()),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}),merge:(s,r)=>{if(!(u=>typeof u=="object"&&u!==null)(s))return r;const n=Array.isArray(s.sessions)?s.sessions:r.sessions,o=typeof s.currentSessionId=="string"||s.currentSessionId===null?s.currentSessionId:r.currentSessionId,a=Array.isArray(s.webUICreatedSessions)?s.webUICreatedSessions:[],i=Array.isArray(s.worktreeMetadata)?s.worktreeMetadata:[],c=Array.isArray(s.availableWorktrees)?s.availableWorktrees:r.availableWorktrees,d=typeof s.lastLoadedDirectory=="string"?s.lastLoadedDirectory:r.lastLoadedDirectory??null;return{...r,...s,sessions:n,currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:c,lastLoadedDirectory:d}}}),{name:"session-store"})),jd="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.",ph="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: ",Wo=s=>typeof s=="string"&&s.trim()===jd.trim(),Vo=(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},sn=(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},nl=new Map,Sd=s=>{const r=nl.get(s);r&&(clearTimeout(r),nl.delete(s))},ur=s=>{for(const r of s)Sd(r)},wn=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>wn(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>wn(r)).join("")}return""},fn=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:fn(n)).join("");const t=wn(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||wn(o.delta)||""}return""}).join(""):"")},rn=(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=wn(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},ol=10*1024*1024,hh=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"}},gh=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"}},xh=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},yh=s=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<s.length;n+=3){const o=s[n]??0,a=s[n+1],i=s[n+2],c=o<<16|(a??0)<<8|(i??0);t+=r[c>>18&63],t+=r[c>>12&63],t+=typeof a=="number"?r[c>>6&63]:"=",t+=typeof i=="number"?r[c&63]:"="}return t},Ls=It()(Pt(gs((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=ol;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 10MB.`);const i=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],c=gh(t);!i.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(x=>x.serverPath===t&&x.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,u;if(!c)try{const x=Le.getApiClient(),v=t.lastIndexOf("/"),S=v>0?t.substring(0,v):"/",N=v>0?t.substring(v+1):t,j=await x.file.read({query:{path:N,directory:S}});j.data&&"content"in j.data?(c=j.data.content,d=j.data.encoding??void 0,u=j.data.mimeType??void 0):c=""}catch(x){console.error("Failed to read server file:",x),c=`[File: ${n}]`}const m=u||hh(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return yh(v)})(),h=d==="base64"?xh(p):new TextEncoder().encode(c||"").length;if(h>ol)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);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(x=>({attachedFiles:[...x.attachedFiles,w]}))},removeAttachedFile:t=>{s(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{s({attachedFiles:[]})}}),{name:"file-store",storage:xs(()=>rs()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),bh=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),wh=s=>s?bh.has(s.toLowerCase()):!1,vh=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},jh=s=>{if(s)try{const r=vh();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},Qn=s=>{const r=jh(s);if(!r)return"ask";const t=r.permission?.edit;return t==="allow"||t==="ask"||t==="deny"||t==="full"?t:(r.tools?r.tools.edit!==!1:!0)?"ask":"deny"},al=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},qo=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return al(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:al(t.tokens)},Go=(s,r,t)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),c=Math.min(i,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}},nn=["ask","allow","full"],gt=It()(Pt(gs((s,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{s(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=r();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{s(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=r();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{s(i=>{const c=new Map(i.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},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a}=r(),i=new Map,c=(f,p)=>{if("mode"in f&&f.mode&&typeof f.mode=="string"&&n.find(w=>w.name===f.mode))return f.mode;if(f.providerID&&f.modelID){const g=n.find(w=>w.model?.providerID===f.providerID&&w.model?.modelID===f.modelID);if(g)return g.name}const{currentAgentContext:h}=r(),y=h.get(t);if(y&&n.find(g=>g.name===y))return y;if(p>0&&f.providerID&&f.modelID){const w=(o.get(t)||[]).filter(x=>x.info.role==="assistant").sort((x,v)=>x.info.time.created-v.info.time.created);for(let x=p-1;x>=0;x--){const S=w[x].info;if(S.providerID===f.providerID&&S.modelID===f.modelID){if(S.mode&&typeof S.mode=="string"&&n.find(k=>k.name===S.mode))return S.mode;const N=n.find(j=>j.model?.providerID===S.providerID&&j.model?.modelID===S.modelID);if(N)return N.name}}}return f.providerID&&f.modelID&&n.find(w=>w.name==="build")?"build":null},d=o.get(t)||[],u=d.filter(f=>f.info.role==="assistant"||f.info.role==="user").sort((f,p)=>f.info.time.created-p.info.time.created),m=d.filter(f=>f.info.role==="assistant").sort((f,p)=>f.info.time.created-p.info.time.created);for(let f=0;f<u.length;f++){const p=u[f],{info:h}=p,y=h;if(y.providerID&&y.modelID){const g=c(y,m.indexOf(p));if(g&&n.find(w=>w.name===g)){const w={providerId:y.providerID,modelId:y.modelID,timestamp:h.time.created},x=i.get(g);(!x||w.timestamp>x.timestamp)&&i.set(g,w)}}}for(const[f,p]of i)a(t,f,p.providerId,p.modelId);return i},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=Go(0,n,o),c=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(t)||[]).filter(S=>S.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],h=p.info.id,y=S=>{const N=()=>{s(j=>{const k=j.sessionContextUsage.get(t);if(k&&k.totalTokens===S.totalTokens&&k.percentage===S.percentage&&k.contextLimit===S.contextLimit&&(k.outputLimit??0)===(S.outputLimit??0)&&(k.normalizedOutput??0)===(S.normalizedOutput??0)&&k.thresholdLimit===S.thresholdLimit&&k.lastMessageId===S.lastMessageId)return j;const F=new Map(j.sessionContextUsage);return F.set(t,S),{sessionContextUsage:F}})};typeof queueMicrotask=="function"?queueMicrotask(N):typeof window<"u"?window.setTimeout(N,0):setTimeout(N,0)},g=r().sessionContextUsage.get(t);if(g&&g.lastMessageId===h){const S=g.normalizedOutput??g.outputLimit??0,N=g.contextLimit!==c||S!==d||g.thresholdLimit!==u;if(N&&g.totalTokens>0){const j=g.totalTokens/u*100,k={totalTokens:g.totalTokens,percentage:Math.min(j,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return y(k),k}if(!N&&g.totalTokens>0)return g}const w=qo(p);if(w===0)return g||null;const x=Go(w,n,o),v={totalTokens:w,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit,normalizedOutput:x.normalizedOutput,thresholdLimit:x.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=qo(d);if(u===0)return;const m=Go(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 i=0;const c=()=>{i++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&qo(u)>0){r().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=Qn(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Qn(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||nn.includes(o)&&s(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Qn(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=r().getSessionAgentEditMode(t,n,a),c=nn.indexOf(i),d=nn.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%nn.length,f=nn[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:xs(()=>rs()),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())]),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(([o,a])=>{t.set(o,new Map(a))});const n=new Map;return s?.sessionAgentEditModes&&s.sessionAgentEditModes.forEach(([o,a])=>{n.set(o,new Map(a))}),{...r,...s,sessionModelSelections:new Map(s?.sessionModelSelections||[]),sessionAgentSelections:new Map(s?.sessionAgentSelections||[]),sessionAgentModelSelections:t,currentAgentContext:new Map(s?.currentAgentContext||[]),sessionContextUsage:new Map(s?.sessionContextUsage||[]),sessionAgentEditModes:n,hasHydrated:!0}}}),{name:"context-store"})),il=(s,r)=>{const t=new Map(s);return t.delete(r),t};let Ko=[],Yo=null;const Sh=50,kh=3e4,mr=new Map,In=new Map,Tr=new Map,Nh=10,mo=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<Nh?null:n},Tn=(s,r)=>{const t=mo(s),n=mo(r);return!t||!n||t.length!==n.length?!0:t>n},Ch=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},$r=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),fo=s=>s?.finish==="stop",ll=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??""}`}}},cl=new Set,po=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(ll).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=ll(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},Mh=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=$r(t),a=$r(n),i=fo(s.info),c=fo(r.info);let d=n;return i&&o>=a?d=po(t,n):c&&a>=o?d=po(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},Xo=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]=Mh(r[a],n)}return r},Dh=(s,r)=>{let t=r,n=r?mo(r):null;for(const o of s){const a=o?.info?.id,i=mo(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Ts=(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},Fr=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},Fn=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},Ah=(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},dl=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),Eh=async s=>{if(s)try{const r=et.getState(),t=r.getWorktreeMetadata(s);if(t?.path)return t.path;const n=r.sessions.find(a=>a.id===s);return typeof n?.directory=="string"&&n.directory.length>0?n.directory:void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},ul=s=>{if(!s)return null;try{return et.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},ml=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},Qo=async(s,r)=>{const t=await Eh(s);return t?Le.withDirectory(t,r):r()},ot=It()(Pt(gs((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=Vt.VIEWPORT_MESSAGES)=>{const o=await Qo(t,()=>Le.getSessionMessages(t)),a=ul(t),i=ml(o,a),c=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(c?i.filter(m=>{const f=m?.info?.id;return f?Tn(f,c):!0}):i).slice(-n);s(m=>{const f=new Map(m.messages),p=m.messages.get(t)||[],h=new Map(p.filter(M=>typeof M.info?.id=="string").map(M=>[M.info.id,M])),y=u.map(M=>{const b={...M.info,clientRole:M.info?.clientRole??M.info.role,userMessageMarker:M.info.role==="user"?!0:M.info?.userMessageMarker},C=(Array.isArray(M.parts)?M.parts:[]).map(P=>{if(P?.type==="text"){const L=P.text??P.content??"";if(Wo(L))return{...P,synthetic:!0}}return P}),A=b?.id?h.get(b.id):void 0;if(A&&A.info.role==="assistant"){const P=Array.isArray(A.parts)?A.parts:[],L=$r(P),$=$r(C);if(fo(A.info)&&L>$){const ee=po(P,C);return{...M,info:b,parts:ee}}}return{...M,info:b,parts:C}}),g=Xo(y),w=new Set(p.map(M=>M.info.id)),x=new Set(g.map(M=>M.info.id)),v=[];w.forEach(M=>{x.has(M)||v.push(M)}),f.set(t,g);const S=new Map(m.sessionMemoryState),N=m.sessionMemoryState.get(t);S.set(t,{...N,viewportAnchor:g.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:N?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const j={messages:f,sessionMemoryState:S};ur(v);const k=sn(m.messageStreamStates,v);if(k!==m.messageStreamStates&&(j.messageStreamStates=k),v.length>0){const M=m.streamingMessageIds.get(t);M&&v.includes(M)&&(j.streamingMessageIds=Ts(j.streamingMessageIds??m.streamingMessageIds,t,null))}if(v.length>0){const M=Fn(j.messageSessionIndex??m.messageSessionIndex,v);M!==(j.messageSessionIndex??m.messageSessionIndex)&&(j.messageSessionIndex=M)}if(v.length>0){const M=new Map(m.pendingAssistantParts);let b=!1;v.forEach(C=>{M.delete(C)&&(b=!0)}),b&&(j.pendingAssistantParts=M)}const F=j.messageSessionIndex??m.messageSessionIndex;let I=F;return g.forEach(M=>{const b=M?.info?.id;typeof b=="string"&&b.length>0&&(I=Fr(I,b,t))}),I!==F&&(j.messageSessionIndex=I),j})},sendMessage:async(t,n,o,a,i,c,d,u)=>{if(!i)throw new Error("No session selected");const m=i;r().sessionAbortFlags.has(m)&&s(f=>{const p=new Map(f.sessionAbortFlags);return p.delete(m),{sessionAbortFlags:p}}),await Qo(m,async()=>{try{let f=t;if(t.startsWith("/")){const h=t.indexOf(" "),y=h===-1?t.substring(1):t.substring(1,h),g=h===-1?"":t.substring(h+1).trim(),w=Le.getApiClient(),x=Le.getDirectory();if(y==="init"){const v=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await w.session.init({path:{id:m},body:{messageID:v,providerID:n,modelID:o},query:x?{directory:x}:void 0});return}if(y==="summarize"){await w.session.summarize({path:{id:m},body:{providerID:n,modelID:o},query:x?{directory:x}:void 0});return}try{const v=await Le.getCommandDetails(y);v?.template?f=v.template.replace(/\$ARGUMENTS/g,g):f=t}catch(v){console.error("Command template resolution failed:",v),f=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(h=>{const y=h.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=Tr.get(m);g&&(clearTimeout(g),Tr.delete(m));const w=new Map(h.sessionMemoryState);return w.set(m,{...y,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:w}});try{const h=new AbortController;s(w=>{const x=new Map(w.abortControllers);return x.set(m,h),{abortControllers:x}});const y=(c??[]).map(w=>({type:"file",mime:w.mimeType,filename:w.filename,url:w.dataUrl}));s(w=>{const x=new Set(w.pendingAssistantHeaderSessions);x.add(m);const v=new Map(w.pendingUserMessageMetaBySession);return v.set(m,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o}),{pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}});const g=u?.map(w=>({text:w.text,files:w.attachments?.map(x=>({type:"file",mime:x.mimeType,filename:x.filename,url:x.dataUrl}))}));if(await Le.sendMessage({id:m,providerID:n,modelID:o,text:f,agent:a,files:y.length>0?y:void 0,additionalParts:g,agentMentions:d?[{name:d}]:void 0}),y.length>0)try{Ls.getState().clearAttachedFiles()}catch(w){console.error("Failed to clear attached files after send",w)}s(w=>{const x=new Map(w.abortControllers);return x.delete(m),{abortControllers:x}})}catch(h){let y="Network error while sending message. The message may still be processing.";if(h.name==="AbortError")y="Request timed out. The message may still be processing.";else if(h.message?.includes("504")||h.message?.includes("Gateway")){y="Gateway timeout - your message is being processed. Please wait for response.",s(g=>{const w=new Map(g.abortControllers);return w.delete(m),{abortControllers:w}});return}else h.message&&(y=h.message);throw s(g=>{const w=new Map(g.abortControllers);w.delete(m);const x=new Set(g.pendingAssistantHeaderSessions);x.delete(m);const v=new Map(g.pendingUserMessageMetaBySession);return v.delete(m),{abortControllers:w,pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}}),new Error(y)}}catch(f){let p="Network error while sending message. The message may still be processing.";throw f.name==="AbortError"?p="Request timed out. The message may still be processing.":f.response?.status===401?p="Session not found or unauthorized. Please refresh the page.":f.response?.status===502?p="OpenCode is restarting. Please wait a moment and try again.":f.message?.includes("504")||f.message?.includes("Gateway")?p="Gateway timeout - your message is being processed. Please wait for response.":f.message&&(p=f.message),s(h=>{const y=new Map(h.abortControllers);y.delete(m);const g=new Set(h.pendingAssistantHeaderSessions);g.delete(m);const w=new Map(h.pendingUserMessageMetaBySession);return w.delete(m),{abortControllers:y,pendingAssistantHeaderSessions:g,pendingUserMessageMetaBySession:w}}),new Error(p)}})},abortCurrentOperation:async t=>{if(!t)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=Ah(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=mr.get(u);m&&(clearTimeout(m),mr.delete(u),In.delete(u))}c.size>0&&ur(c);const d=Date.now();s(u=>{const m=sn(u.messageStreamStates,c),f=u.messages.get(t)??[];let p=!1,h=u.messages;if(f.length>0&&c.size>0){const x=f.map(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const S=(v.parts??[]).map(N=>{if(N.type==="reasoning"){const j=N,k={...j.time??{}};return typeof k.end!="number"&&(k.end=d),{...j,time:k}}if(N.type==="tool"){const j=N,k={...j.state??{}};return(k.status==="running"||k.status==="pending")&&(k.status="aborted"),{...j,state:k}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:S}});p&&(h=new Map(u.messages),h.set(t,x))}const y=u.sessionMemoryState.get(t);let g=u.sessionMemoryState;if(y){const x=new Map(u.sessionMemoryState);x.set(t,{...y,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),g=x}const w=new Map(u.sessionAbortFlags);return w.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:g,sessionAbortFlags:w,abortControllers:(()=>{const x=new Map(u.abortControllers);return x.delete(t),x})(),streamingMessageIds:Ts(u.streamingMessageIds,t,null),...p?{messages:h}:{}}}),Le.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=r();if(cl.has(n))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!Tn(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>Vt.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={},x=Fr(h.messageSessionIndex,n,t);x!==h.messageSessionIndex&&(w.messageSessionIndex=x);const v=M=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(t)))return M;const C=new Map(h.sessionAbortFlags);return C.delete(t),{...M,sessionAbortFlags:C}},S=M=>{const b=M||"",C=In.get(n);if(b&&C===b){const L=r();if(dl(L,t,n)){const $=mr.get(n);$&&(clearTimeout($),mr.delete(n)),setTimeout(()=>{const q=r();typeof q.forceCompleteMessage=="function"&&q.forceCompleteMessage(t,n,"timeout"),q.completeStreamingMessage(t,n)},100)}}In.set(n,b);const A=mr.get(n);A&&clearTimeout(A);const P=setTimeout(()=>{const L=r();typeof L.forceCompleteMessage=="function"&&L.forceCompleteMessage(t,n,"timeout"),dl(L,t,n)&&L.completeStreamingMessage(t,n),mr.delete(n),In.delete(n)},8e3);mr.set(n,P)},N=t!==i,j=h.sessionMemoryState.get(t);if(N&&j?.isStreaming){g.length>=Vt.BACKGROUND_STREAMING_BUFFER&&g.shift();const M=new Map(h.sessionMemoryState);M.set(t,{...j,backgroundMessageCount:(j.backgroundMessageCount||0)+1}),h.sessionMemoryState=M}if(f==="assistant"){const M=h.sessionMemoryState.get(t);if(M){const b=Date.now(),C=new Map(h.sessionMemoryState);C.set(t,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??b,lastAccessedAt:b,isZombie:!1}),h.sessionMemoryState=C}}const k=fn(o);if(Wo(k)&&(o.synthetic=!0),Ch()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:k.length,snapshotParts:u.length})}catch{}const F=w.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const M=Ts(F,t,n);M!==F&&(w.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const I=g.findIndex(M=>M.info.id===n);if(I!==-1&&f==="user"){const M=g[I],b=M.parts.findIndex($=>$.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const C=rn(o,b!==-1?M.parts[b]:void 0);window.__messageTracker?.(n,`user_part_type:${C.type||"unknown"}`);const A={...M};b!==-1?A.parts=A.parts.map(($,q)=>q===b?C:$):A.parts=[...A.parts,C];const P=[...g];P[I]=A;const L=new Map(h.messages);return L.set(t,P),v({messages:L})}if(f==="assistant"&&I!==-1){const M=g[I],b=M.parts.findIndex(q=>q.id===o.id),C=rn(o,b!==-1?M.parts[b]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const A={...M};b!==-1?A.parts=A.parts.map((q,ee)=>ee===b?C:q):A.parts=[...A.parts,C];const P=[...g];P[I]=A;const L=new Map(h.messages);L.set(t,P),w.messageStreamStates=Vo(h.messageStreamStates,n);const $=Ts(w.streamingMessageIds??h.streamingMessageIds,t,n);return $!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=$,window.__messageTracker?.(n,"streamingId_set")),C.type==="text"?S(C.text||""):S(""),v({messages:L,...w})}if(I===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const fe=rn(o);window.__messageTracker?.(n,`new_user_part_type:${fe.type||"unknown"}`);const je=h.pendingUserMessageMetaBySession.get(t),W=gt.getState(),te=je?.mode??W.getSessionAgentSelection(t)??W.getCurrentAgent(t),oe=typeof te=="string"&&te.trim().length>0?te.trim():void 0,V=je?.providerID??(h.lastUsedProvider?.providerID||void 0),ue=je?.modelID??(h.lastUsedProvider?.modelID||void 0);je&&(w.pendingUserMessageMetaBySession=il(h.pendingUserMessageMetaBySession,t));const ge={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...oe?{mode:oe}:{},...V?{providerID:V}:{},...ue?{modelID:ue}:{},time:{created:Date.now()}},parts:[fe]},ie=[...g,ge];ie.sort((Ce,Ie)=>{const K=Ce.info?.time?.created||0,G=Ie.info?.time?.created||0;return K-G});const De=new Map(h.messages);return De.set(t,ie),v({messages:De})}if(o?.type==="text"){const fe=fn(o).trim();if(fe.length>0){const je=[...g].reverse().find(W=>W.info.role==="user");if(je){const W=je.parts.map(te=>fn(te)).join("").trim();if(W.length>0&&W===fe)return cl.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const M=rn(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?S(M.text||""):S("");const b=h.pendingAssistantParts.get(n),C=b?[...b.parts]:[],A=C.findIndex(fe=>fe.id===M.id);A!==-1?C[A]=M:C.push(M);const P=new Map(h.pendingAssistantParts);P.set(n,{sessionId:t,parts:C});const L=h.lastUsedProvider?.providerID||"",$=h.lastUsedProvider?.modelID||"",q=Date.now(),ee=Le.getDirectory()??"/",ce=gt.getState(),_=ce.getSessionAgentSelection(t)??ce.getCurrentAgent(t),z=typeof _=="string"&&_.trim().length>0?_.trim():void 0,D=h.pendingAssistantHeaderSessions.has(t);if(D){const fe=new Set(h.pendingAssistantHeaderSessions);fe.delete(t),w.pendingAssistantHeaderSessions=fe}const X={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:q},agent:z||"default",model:{providerID:L,modelID:$},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:q},parentID:n,modelID:$,providerID:L,mode:z||"default",...D?{openchamberHeaderAnchor:!0}:{},path:{cwd:ee,root:ee},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:C},he=[...g,X],ae=new Map(h.messages);if(ae.set(t,he),f==="assistant"){w.messageStreamStates=Vo(h.messageStreamStates,n);const fe=Ts(w.streamingMessageIds??h.streamingMessageIds,t,n);fe!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=fe,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:ae,pendingAssistantParts:P,...w})}else{const M=g[I],b=M.parts.findIndex($=>$.id===o.id),C=rn(o,b!==-1?M.parts[b]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const A={...M};b!==-1?A.parts=A.parts.map(($,q)=>q===b?C:$):A.parts=[...A.parts,C];const P=[...g];P[I]=A;const L=new Map(h.messages);if(L.set(t,P),A.info.role==="assistant"){w.messageStreamStates=Vo(h.messageStreamStates,n);const $=Ts(w.streamingMessageIds??h.streamingMessageIds,t,n);$!==(w.streamingMessageIds??h.streamingMessageIds)&&(w.streamingMessageIds=$,window.__messageTracker?.(n,"streamingId_set"))}return C.type==="text"?S(C.text||""):S(""),v({messages:L,...w})}})},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,i);return}Ko.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),Yo||(Yo=setTimeout(()=>{const c=[...Ko];Ko=[],Yo=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Sh))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};s(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],u=d.findIndex(j=>j.info.id===n);if(u===-1)return i;const m=d[u];if(!m)return i;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 x=m.parts.map(j=>{if(!j)return j;if(j.type==="tool"){const k=j.state;if(!k)return j;const F=k.status,I=F==="running"||F==="pending"||F==="started",M=!k.time||typeof k.time?.end!="number";if(I||M){const b={...k};return I&&(b.status="completed"),M&&(b.time={...k.time??{},end:f}),w=!0,{...j,state:b}}return j}if(j.type==="reasoning"){const k=j.time;return!k||typeof k.end!="number"?(w=!0,{...j,time:{...k??{},end:f}}):j}if(j.type==="text"){const k=j.time;return k&&typeof k.end!="number"?(w=!0,{...j,time:{...k,end:f}}):j}return j});if(!y&&!w)return i;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:g,parts:w?x:m.parts},S=[...d];S[u]=v;const N=new Map(i.messages);return N.set(c,S),{messages:N}})},markMessageStreamSettled:t=>{s(n=>{Sd(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,u)=>{if(i)return;const m=d.findIndex(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,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),ur([t])},updateMessageInfo:(t,n,o)=>{s(c=>{const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!Tn(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(t)??[]],f=m.findIndex(I=>I.info.id===n),p=c.pendingAssistantParts.get(n),h=(I=[],M=[])=>{if(!M.length)return I;const b=[...I];return M.forEach(C=>{const A=b.findIndex(P=>P.id===C.id);A===-1?b.push(C):b[A]=C}),b},y=I=>{if(!I)return I;const M=I.clientRole??I.role,b=M==="user"?!0:I.userMessageMarker;return{...I,clientRole:M,...b?{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 ee=m[0]?.info,ce=typeof ee?.time?.created=="number"?ee.time.created:null,_=typeof ee?.id=="string"?ee.id:null,z=o,D=typeof z?.time?.created=="number"?z.time.created:null,H=typeof z?.id=="string"?z.id:n;let X=!1;if(D!==null&&ce!==null&&(X=D<ce),!X&&H&&_&&(X=H.localeCompare(_)<0),X)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const I=y(o);if(I&&I.role==="user"){const q=p?.parts??[],ee=c.pendingUserMessageMetaBySession.get(t),ce={info:{...I,userMessageMarker:!0,clientRole:"user",...ee?.mode?{mode:ee.mode}:{},...ee?.providerID?{providerID:ee.providerID}:{},...ee?.modelID?{modelID:ee.modelID}:{}},parts:q.length>0?[...q]:[]},_=new Map(c.messages),z=[...m,ce];z.sort((X,he)=>{const ae=X.info?.time?.created||0,fe=he.info?.time?.created||0;return ae-fe}),_.set(t,z);const D={messages:_,...ee?{pendingUserMessageMetaBySession:il(c.pendingUserMessageMetaBySession,t)}:{}},H=Fr(D.messageSessionIndex??c.messageSessionIndex,n,t);if(H!==(D.messageSessionIndex??c.messageSessionIndex)&&(D.messageSessionIndex=H),p){const X=new Map(c.pendingAssistantParts);X.delete(n),D.pendingAssistantParts=X}return D}if(!I||I.role!=="assistant")return c;const M=p?.parts??[],b=c.pendingAssistantHeaderSessions.has(t),C={info:{...I,animationSettled:I?.animationSettled??!1,...b?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},A=new Map(c.messages),P=[...m,C];A.set(t,P);const L={messages:A,...b?{pendingAssistantHeaderSessions:(()=>{const q=new Set(c.pendingAssistantHeaderSessions);return q.delete(t),q})()}:{}},$=Fr(L.messageSessionIndex??c.messageSessionIndex,n,t);if($!==(L.messageSessionIndex??c.messageSessionIndex)&&(L.messageSessionIndex=$),p){const q=new Map(c.pendingAssistantParts);q.delete(n),L.pendingAssistantParts=q}return L}const g=m[f],w=g.info;if(w.userMessageMarker===!0||w.clientRole==="user"||w.role==="user"){const I={...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&&!I.mode&&M.mode&&(I.mode=M.mode);const b={...g,info:I},C=new Map(c.messages),A=[...m];if(A[f]=b,C.set(t,A),M){const P=new Map(c.pendingUserMessageMetaBySession);return P.delete(t),{messages:C,pendingUserMessageMetaBySession:P}}return{messages:C}}const v={...g.info,...o};o.role&&o.role!==g.info.role&&(v.role=g.info.role),v.clientRole=v.clientRole??g.info.clientRole??g.info.role,v.clientRole==="user"&&(v.userMessageMarker=!0);const S=p?.parts?h(g.parts,p.parts):g.parts,N={...g,info:v,parts:S},j=new Map(c.messages),k=[...m];k[f]=N,j.set(t,k);const F={messages:j};if(p){const I=new Map(c.pendingAssistantParts);I.delete(n),F.pendingAssistantParts=I}return F});const a=o?.finish,i=o?.role;typeof a=="string"&&i!=="user"&&setTimeout(()=>{r().completeStreamingMessage(t,n)},0)},completeStreamingMessage:(t,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(a&&(i.streamingMessageIds=Ts(o.streamingMessageIds,t,null),i.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),i.messageStreamStates=d}Object.keys(i).length>0&&s(i),o.pendingAssistantParts.has(n)&&s(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),ur([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=Tr.get(t);d&&(clearTimeout(d),Tr.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}}),Tr.delete(t)},2e3);Tr.set(t,u)}},syncMessages:(t,n)=>{const o=ul(t),a=ml(n,o),i=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=i?a.filter(d=>{const u=d?.info?.id;return u?Tn(u,i):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(j=>typeof j.info?.id=="string").map(j=>[j.info.id,j])),p=c.map(j=>{const k={...j.info,clientRole:j.info?.clientRole??j.info.role,userMessageMarker:j.info.role==="user"?!0:j.info?.userMessageMarker,animationSettled:j.info.role==="assistant"?j.info?.animationSettled??!0:j.info?.animationSettled},F=(Array.isArray(j.parts)?j.parts:[]).map(b=>{if(b?.type==="text"){const C=b.text??b.content??"";if(Wo(C))return{...b,synthetic:!0}}return b}),I=typeof k?.id=="string"?k.id:void 0,M=I?f.get(I):void 0;if(M&&M.info.role==="assistant"){const b=Array.isArray(M.parts)?M.parts:[],C=$r(b),A=$r(F);if(fo(M.info)&&C>A){const L=po(b,F);return{...j,info:k,parts:L}}}return{...j,info:k,parts:F}}),h=Xo(p),y=new Set(m.map(j=>j.info.id)),g=new Set(h.map(j=>j.info.id)),w=[];y.forEach(j=>{g.has(j)||w.push(j)}),u.set(t,h);const x={messages:u,isSyncing:!0};ur(w);const v=sn(d.messageStreamStates,w);if(v!==d.messageStreamStates&&(x.messageStreamStates=v),w.length>0){const j=d.streamingMessageIds.get(t);j&&w.includes(j)&&(x.streamingMessageIds=Ts(x.streamingMessageIds??d.streamingMessageIds,t,null))}if(w.length>0){const j=Fn(x.messageSessionIndex??d.messageSessionIndex,w);j!==(x.messageSessionIndex??d.messageSessionIndex)&&(x.messageSessionIndex=j)}if(w.length>0){const j=new Map(d.pendingAssistantParts);let k=!1;w.forEach(F=>{j.delete(F)&&(k=!0)}),k&&(x.pendingAssistantParts=j)}const S=x.messageSessionIndex??d.messageSessionIndex;let N=S;return h.forEach(j=>{const k=j?.info?.id;typeof k=="string"&&k.length>0&&(N=Fr(N,k,t))}),N!==S&&(x.messageSessionIndex=N),x}),setTimeout(()=>{s({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{s(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=n+kh;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&s(n=>{const o=n.sessionAbortFlags.get(t);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,n)=>{s(o=>{const a=o.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},i=new Map(o.sessionMemoryState);return i.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:i}})},updateActiveTurnAnchor:(t,n,o)=>{s(a=>{const i=a.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},c=new Map(a.sessionMemoryState);return c.set(t,{...i,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=Vt.VIEWPORT_MESSAGES,o)=>{const a=r(),i=a.messages.get(t);if(!i||i.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const m=Math.min(i.length,u+n);m===i.length&&m-u<n&&(u=Math.max(0,m-n));const f=i.slice(u,m),p=i.slice(0,u),h=new Set(f.map(g=>g.info.id)),y=i.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 x=new Map(g.sessionMemoryState),v={...c,viewportAnchor:d-u,trimmedHeadMaxId:Dh(p,c.trimmedHeadMaxId)};x.set(t,v);const S={messages:w,sessionMemoryState:x};ur(y);const N=sn(g.messageStreamStates,y);if(N!==g.messageStreamStates&&(S.messageStreamStates=N),y.length>0){const F=g.streamingMessageIds.get(t);F&&y.includes(F)&&(S.streamingMessageIds=Ts(S.streamingMessageIds??g.streamingMessageIds,t,null))}if(y.length>0){const F=Fn(S.messageSessionIndex??g.messageSessionIndex,y);F!==(S.messageSessionIndex??g.messageSessionIndex)&&(S.messageSessionIndex=F)}const j=S.messageSessionIndex??g.messageSessionIndex;let k=j;return f.forEach(F=>{const I=F?.info?.id;typeof I=="string"&&I.length>0&&(k=Fr(k,I,t))}),k!==j&&(S.messageSessionIndex=k),S})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=Vt.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=i[0][0];s(d=>{const m=(d.messages.get(c)||[]).map(N=>N.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c),p.delete(c);const h={messages:f,sessionMemoryState:p},y=new Map(d.pendingAssistantParts);let g=!1;y.forEach((N,j)=>{N.sessionId===c&&(y.delete(j),g=!0)}),g&&(h.pendingAssistantParts=y);const w=new Map(d.sessionCompactionUntil);w.delete(c)&&(h.sessionCompactionUntil=w),ur(m);const x=sn(d.messageStreamStates,m);x!==d.messageStreamStates&&(h.messageStreamStates=x);const v=Fn(h.messageSessionIndex??d.messageSessionIndex,m);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const S=Ts(d.streamingMessageIds,c,null);if(S!==d.streamingMessageIds&&(h.streamingMessageIds=S),d.abortControllers.has(c)){const N=new Map(d.abortControllers);N.delete(c),h.abortControllers=N}return h})},loadMoreMessages:async(t,n="up")=>{const o=r(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const c=await Qo(t,()=>Le.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=c.findIndex(m=>m.info.id===d.info.id);if(u>0){const m=Math.min(Vt.VIEWPORT_MESSAGES,u),f=c.slice(u-m,u);s(p=>{const h=[...f,...a],y=Xo(h),g=new Map(p.messages);g.set(t,y);const w=Math.max(0,y.length-a.length),x=new Map(p.sessionMemoryState);return x.set(t,{...i,viewportAnchor:i.viewportAnchor+w,hasMoreAbove:u-m>0,totalAvailableMessages:c.length}),{messages:g,sessionMemoryState:x}})}else u===0&&s(m=>{const f=new Map(m.sessionMemoryState);return f.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:f}})}},getLastMessageModel:t=>{const{messages:n}=r(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:xs(()=>rs()),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"})),Ih=s=>typeof s=="object"&&s!==null,Th=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},Fh=async(s,r)=>{try{const t=et.getState(),n=t.getWorktreeMetadata(s);if(n?.path)return Le.withDirectory(n.path,r);const o=t.sessions.find(i=>i.id===s),a=typeof o?.directory=="string"&&o.directory.length>0?o.directory:void 0;if(a)return Le.withDirectory(a,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},ho=It()(Pt(gs((s,r)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o)return;const a=t.type?.toLowerCase?.()??null;let i=n?.currentAgentContext?.get(o);if(i||(i=n?.sessionAgentSelections?.get(o)??void 0),!i&&typeof window<"u"){const m=window.__zustand_config_store__;m?.getState&&(i=m.getState().currentAgentName??void 0)}const c=Qn(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&wh(a)){r().respondToPermission(o,t.id,"once").catch(()=>{});return}s(m=>{const f=m.permissions.get(o)||[],p=new Map(m.permissions);return p.set(o,[...f,t]),{permissions:p}})},respondToPermission:async(t,n,o)=>{await Fh(t,()=>Le.respondToPermission(t,n,o)),o==="reject"&&await ot.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:xs(()=>rs()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!Ih(s))return r;const t=Th(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),li=s=>s.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
4
- `).replace(/\n\s*\n+/g,`
5
- `),pn=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},fl=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return pn(n);const o=s.find(a=>a.id===r);return o?pn(o.directory??null):null},ye=It()(Pt((s,r)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions: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:[],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:()=>et.getState().loadSessions(),openNewSessionDraft:t=>{s({newSessionDraft:{open:!0,directoryOverride:t?.directoryOverride??null,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const n=lt.getState(),o=n.getVisibleAgents();let a;if(n.settingsDefaultAgent){const i=o.find(c=>c.name===n.settingsDefaultAgent);i&&(a=i.name)}a||(a=o.find(i=>i.name==="build")?.name||o[0]?.name),a&&n.setAgent(a)}catch{}},closeNewSessionDraft:()=>{const t=et.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 et.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=ot.getState(),{messages:o,lastUsedProvider:a}=n;let i,c;if(o.forEach((x,v)=>{const S=x.find(N=>N.info?.id===t);S&&!i&&(i=S,c=v)}),!i||i.info.role!=="assistant")return;const d=li(i.parts);if(!d.trim())return;const u=et.getState(),m=fl(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}=lt.getState(),g=p||a?.providerID,w=h||a?.modelID;!g||!w||await Le.sendMessage({id:f.id,providerID:g,modelID:w,text:d,prefaceText:jd,agent:y??void 0})},deleteSession:(t,n)=>et.getState().deleteSession(t,n),deleteSessions:(t,n)=>et.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>et.getState().updateSessionTitle(t,n),shareSession:t=>et.getState().shareSession(t),unshareSession:t=>et.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=et.getState().currentSessionId,o=fl(et.getState().sessions,t,et.getState().getWorktreeMetadata),a=Le.getDirectory()??yt.getState().currentDirectory??null,i=o??a;try{Le.setDirectory(i??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,Vt.VIEWPORT_MESSAGES)}et.getState().setCurrentSession(t),t&&(r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,Fp)),r().evictLeastRecentlyUsed()},loadMessages:t=>ot.getState().loadMessages(t),sendMessage:async(t,n,o,a,i,c,d)=>{const u=r().newSessionDraft,m=typeof a=="string"&&a.trim().length>0?a.trim():void 0,f=x=>{s(v=>{const S=new Map(v.sessionActivityPhase??new Map);return S.set(x,"busy"),{sessionActivityPhase:S}})},p=x=>{s(v=>{const S=new Map(v.sessionActivityPhase??new Map);return S.set(x,"idle"),{sessionActivityPhase:S}})};if(u?.open){const x=await et.getState().createSession(u.title,u.directoryOverride??null,u.parentID??null);if(!x?.id)throw new Error("Failed to create session");const v=lt.getState(),S=v.currentAgentName,N=m??S,j=v.currentProviderId,k=v.currentModelId;if(j&&k)try{gt.getState().saveSessionModelSelection(x.id,j,k)}catch{}if(N){try{gt.getState().saveSessionAgentSelection(x.id,N)}catch{}if(j&&k)try{gt.getState().saveAgentModelForSession(x.id,N,j,k)}catch{}}try{et.getState().initializeNewOpenChamberSession(x.id,v.agents)}catch{}r().closeNewSessionDraft(),f(x.id);try{return await ot.getState().sendMessage(t,n,o,N,x.id,i,c,d)}catch(F){throw p(x.id),F}}const h=et.getState().currentSessionId,y=h?gt.getState().getSessionAgentSelection(h):null,g=lt.getState().currentAgentName,w=m||y||g||void 0;if(h&&w)try{gt.getState().saveSessionAgentSelection(h,w)}catch{}h&&f(h);try{return await ot.getState().sendMessage(t,n,o,w,h||void 0,i,c,d)}catch(x){throw h&&p(h),x}},abortCurrentOperation:()=>{const t=et.getState().currentSessionId;return ot.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=et.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&&ot.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=et.getState().currentSessionId||t;return ot.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>ot.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>ot.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>ot.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>ot.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:gt.getState().currentAgentContext,sessionAgentSelections:gt.getState().sessionAgentSelections,getSessionAgentEditMode:gt.getState().getSessionAgentEditMode};return ho.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>ho.getState().respondToPermission(t,n,o),clearError:()=>et.getState().clearError(),getSessionsByDirectory:t=>et.getState().getSessionsByDirectory(t),getLastMessageModel:t=>ot.getState().getLastMessageModel(t),getCurrentAgent:t=>gt.getState().getCurrentAgent(t),syncMessages:(t,n)=>ot.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>et.getState().applySessionMetadata(t,n),addAttachedFile:t=>Ls.getState().addAttachedFile(t),addServerFile:(t,n,o)=>Ls.getState().addServerFile(t,n,o),removeAttachedFile:t=>Ls.getState().removeAttachedFile(t),clearAttachedFiles:()=>Ls.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>ot.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>ot.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>ot.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=et.getState().currentSessionId;return ot.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=et.getState().currentSessionId;return ot.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>ot.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),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=ot.getState().messages;return gt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>et.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>et.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>et.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>et.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>et.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>et.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=et.getState().currentSessionId;if(!o)return null;const a=ot.getState().messages;return gt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=ot.getState().messages;return gt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=ot.getState().messages;return gt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=ot.getState().messages.get(t)||[],o=et.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=ot.getState().messages;return gt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>et.getState().updateSession(t),revertToMessage:async(t,n)=>{const a=(ot.getState().messages.get(t)||[]).find(m=>m.info.id===n);let i="";a&&a.info.role==="user"&&(i=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
6
- `).trim());const c=await Le.revertSession(t,n);et.getState().updateSession(c);const d=ot.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);ot.getState().syncMessages(t,f)}}i&&s({pendingInputText:i})},setPendingInputText:t=>{s({pendingInputText:t})},consumePendingInputText:()=>{const t=r().pendingInputText;return t!==null&&s({pendingInputText:null}),t}}),{name:"composed-session-store"}));et.subscribe((s,r)=>{if(s.sessions===r.sessions&&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)return;const t=ye.getState().newSessionDraft?.open;ye.setState({sessions:s.sessions,currentSessionId:t?null:s.currentSessionId,lastLoadedDirectory:s.lastLoadedDirectory,isLoading:s.isLoading,error:s.error,webUICreatedSessions:s.webUICreatedSessions,worktreeMetadata:s.worktreeMetadata,availableWorktrees:s.availableWorktrees})});ot.subscribe((s,r)=>{if(s.messages===r.messages&&s.sessionMemoryState===r.sessionMemoryState&&s.messageStreamStates===r.messageStreamStates&&s.sessionCompactionUntil===r.sessionCompactionUntil&&s.sessionAbortFlags===r.sessionAbortFlags&&s.streamingMessageIds===r.streamingMessageIds&&s.abortControllers===r.abortControllers&&s.lastUsedProvider===r.lastUsedProvider&&s.isSyncing===r.isSyncing)return;const t=new Map;s.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const c=i.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}}}}}),ye.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})});Ls.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&ye.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||ye.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});ho.subscribe((s,r)=>{s.permissions!==r.permissions&&ye.setState({permissions:s.permissions})});yt.subscribe((s,r)=>{const t=pn(s.currentDirectory??null),n=pn(r.currentDirectory??null);if(t===n)return;const o=ye.getState().newSessionDraft;if(!o?.open)return;const a=pn(o.directoryOverride);a&&a!==n||ye.setState(i=>({newSessionDraft:{...i.newSessionDraft,directoryOverride:t,parentID:null}}))});const Ph=ye.getState().newSessionDraft?.open;ye.setState({sessions:et.getState().sessions,currentSessionId:Ph?null:et.getState().currentSessionId,lastLoadedDirectory:et.getState().lastLoadedDirectory,isLoading:et.getState().isLoading,error:et.getState().error,webUICreatedSessions:et.getState().webUICreatedSessions,worktreeMetadata:et.getState().worktreeMetadata,availableWorktrees:et.getState().availableWorktrees,messages:ot.getState().messages,sessionMemoryState:ot.getState().sessionMemoryState,messageStreamStates:ot.getState().messageStreamStates,sessionCompactionUntil:ot.getState().sessionCompactionUntil,sessionAbortFlags:ot.getState().sessionAbortFlags,streamingMessageIds:ot.getState().streamingMessageIds,abortControllers:ot.getState().abortControllers,lastUsedProvider:ot.getState().lastUsedProvider,isSyncing:ot.getState().isSyncing,permissions:ho.getState().permissions,attachedFiles:Ls.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__=ye);const ci=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=l.useState(!1),[c,d]=l.useState({length:0,offset:0}),[u,m]=l.useState({length:0,offset:0}),f=l.useRef(null),p=l.useRef(null),h=l.useRef(!1),y=l.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),g=l.useRef(null),w=l.useCallback(()=>{const M=s.current;if(!M)return;const{scrollHeight:b,clientHeight:C,scrollTop:A,scrollWidth:P,clientWidth:L,scrollLeft:$}=M,q=8;if(b>C){const ee=Math.max(C-q*2,0),ce=C/b*ee,_=Math.max(r,Math.min(ee,ce)),z=Math.max(ee-_,0),D=Math.max(b-C,1),H=A/D*z;d({length:_,offset:H})}else d({length:0,offset:0});if(!o&&P>L){const ee=Math.max(L-q*2,0),ce=L/P*ee,_=Math.max(r,Math.min(ee,ce)),z=Math.max(ee-_,0),D=Math.max(P-L,1),H=$/D*z;m({length:_,offset:H})}else m({length:0,offset:0})},[s,r,o]),x=l.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),v=l.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{w(),i(!0),x()})},[x,w]);l.useEffect(()=>{const M=s.current;if(!M)return;w(),i(!0),x(),M.addEventListener("scroll",v,{passive:!0});const b=typeof ResizeObserver<"u"?new ResizeObserver(()=>w()):null;b?.observe(M);const C=typeof MutationObserver<"u"?new MutationObserver(()=>w()):null;return C?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),b?.disconnect(),C?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,v,x,w]);const S=(M,b)=>{const C=s.current;C&&(h.current=!0,y.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:C.scrollTop,scrollLeft:C.scrollLeft},g.current=b,i(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},N=M=>{if(!h.current)return;const b=s.current;if(!b)return;const C=g.current;if(C==="vertical"){const{pointerY:A,scrollTop:P}=y.current,L=M.clientY-A,$=b.clientHeight,q=Math.max($-c.length,1),ee=Math.max(b.scrollHeight-b.clientHeight,1),ce=L/q*ee;b.scrollTop=P+ce}else if(C==="horizontal"){const{pointerX:A,scrollLeft:P}=y.current,L=M.clientX-A,$=b.clientWidth,q=Math.max($-u.length,1),ee=Math.max(b.scrollWidth-b.clientWidth,1),ce=L/q*ee;b.scrollLeft=P+ce}},j=M=>{h.current&&(h.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),x())},k=c.length>0,F=u.length>0;if(!k&&!F)return null;const I=8;return e.jsxs("div",{className:O("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[k&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${I+c.offset}px`,right:`${I/2}px`},onPointerDown:M=>S(M,"vertical"),onPointerMove:N,onPointerUp:j,onPointerCancel:j}),F&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${I+u.offset}px`,bottom:`${I/2}px`},onPointerDown:M=>S(M,"horizontal"),onPointerMove:N,onPointerUp:j,onPointerCancel:j})]})},tt=l.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const h=l.useRef(null);return l.useImperativeHandle(p,()=>h.current,[]),e.jsxs("div",{className:O("relative flex flex-col min-h-0 w-full overflow-hidden",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(i,{ref:h,className:O("overlay-scrollbar-target overlay-scrollbar-container",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(ci,{containerRef:h,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});tt.displayName="ScrollableOverlay";const pl="mobile-overlay-root",Rh=()=>{if(typeof document>"u")return null;let s=document.getElementById(pl);return s||(s=document.createElement("div"),s.id=pl,document.body.appendChild(s)),s},cs=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:c})=>{const d=l.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Rh()),l.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=i??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:O("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(zt,{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(tt,{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 Xu.createPortal(m,d.current)},Fa=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,c]=l.useState(!1),d=l.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=l.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c(!0)},500)},[]),y=l.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);l.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const g=e.jsxs("div",{className:O("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(Qu,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:O(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[g,e.jsx(cs,{open:i,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:O("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:g}),e.jsx(Xe,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(w=>e.jsx("p",{className:"typography-micro leading-tight",children:w},w))})})]})},on={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},kd=(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 Jo(){const s=window.innerWidth,r=typeof window.matchMedia=="function",t=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=s>on.md&&s<=on.lg,m=s<=on.md;let f=d&&m,p=d&&!f&&u,h=!d||s>on.lg,y="desktop";c?(f=!1,p=!1,h=!0,y="desktop"):f?y="mobile":p?y="tablet":(h=!0,y="desktop"),kd(c,y,d);let g="xs";for(const[w,x]of Object.entries(on))s>=x&&(g=w);return{isMobile:f,isTablet:p,isDesktop:h,deviceType:y,screenWidth:s,breakpoint:g,hasTouchInput:d}}function Nt(){const[s,r]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Jo());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(Jo())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(Jo())},a=[],i=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 i(t),i(n),()=>{a.forEach(c=>c())}},[]),l.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||c||d>0;kd(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const Pn=5e3,Lh=1e4,Oh=5e3,$h=1e4,_h=25,Bh=4,hl=15e3,Fs=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),zh=(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},Hh=(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!!zh(s.diffStats,r.diffStats)},Uh=(s,r)=>{const t=new Set;if(!r)return t;const n=s?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),i=new Map(o.map(f=>[f.path,f])),c=new Set([...a.keys(),...i.keys()]);for(const f of c){const p=a.get(f),h=i.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},At=It()(Pt((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:Pn,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,Fs()),s({activeDirectory:t,directories:a})}else s({activeDirectory:t})},getDirectoryState:t=>r().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:i}=r();let c=i.get(t);c||(c=Fs()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(i);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(Hh(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??Fs(),h=Uh(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 x=h.size>0;f.set(t,{...p,isGitRepo:!0,status:m,diffCache:w,lastStatusFetch:Date.now(),lastStatusChange:x?Date.now():p.lastStatusChange}),s({directories:f})}else{const f=new Map(r().directories),p=f.get(t)??Fs();f.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),s({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||s({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{s({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(r().directories),i=a.get(t)??Fs();a.set(t,{...i,branches:o}),s({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{s({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=r(),i=a.get(t),c=o??i?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),u=new Map(r().directories),m=u.get(t)??Fs();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),i=a.get(t)??Fs();a.set(t,{...i,identity:o}),s({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{s({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=r();let i=a.get(t);if(!i){i=Fs();const f=new Map(a);f.set(t,i),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>$h||!u.log)&&await r().fetchLog(t,n),await r().fetchIdentity(t,n),r().fetchAllDiffs(t,n)},getDiff:(t,n)=>r().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(r().directories),i=a.get(t)??Fs(),c=new Map(i.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,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,_h);if(c.length===0)return;let d=0;const u=[],m=()=>{const v=d;return d+=1,v<c.length?c[v]:null},f=async v=>{const S=n.getGitFileDiff(t,{path:v}),N=new Promise((k,F)=>{setTimeout(()=>F(new Error(`Timed out after ${hl}ms`)),hl)}),j=await Promise.race([S,N]);return{path:v,diff:{original:j.original??"",modified:j.modified??""}}},p=async()=>{for(;;){const v=m();if(!v)return;try{u.push(await f(v.path))}catch{}}},h=Math.min(Bh,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),x=Date.now();u.forEach(v=>{w.set(v.path,{...v.diff,fetchedAt:x})}),y.set(t,{...g,diffCache:w}),s({directories:y})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??Fs();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:Pn});else{const m=Math.min(a+Oh,Lh);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:Pn})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:Pn}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),Nd=s=>At(r=>s?r.directories.get(s)?.status??null:null),Wh=s=>At(r=>s?r.directories.get(s)?.branches??null:null),Vh=s=>At(r=>s?r.directories.get(s)?.log??null:null),qh=s=>At(r=>s?r.directories.get(s)?.identity??null:null),Cd=s=>At(r=>s?r.directories.get(s)?.isGitRepo??null:null),Gh=s=>At(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function Gt({...s}){return e.jsx(Ju,{"data-slot":"dropdown-menu",...s})}function Kt({...s}){return e.jsx(Zu,{"data-slot":"dropdown-menu-trigger",...s})}function Yt({className:s,sideOffset:r=4,...t}){return e.jsx(em,{children:e.jsx(tm,{"data-slot":"dropdown-menu-content",sideOffset:r,className:O("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 St({className:s,inset:r,variant:t="default",...n}){return e.jsx(om,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:O("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 Kh({...s}){return e.jsx(sm,{"data-slot":"dropdown-menu-radio-group",...s})}function Yh({className:s,children:r,...t}){return e.jsxs(rm,{"data-slot":"dropdown-menu-radio-item",className:O("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(nm,{children:e.jsx(Mt,{className:"size-3"})})}),r]})}function zr({className:s,inset:r,...t}){return e.jsx(im,{"data-slot":"dropdown-menu-label","data-inset":r,className:O("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function Os({className:s,...r}){return e.jsx(am,{"data-slot":"dropdown-menu-separator",className:O("bg-border -mx-1 my-0.5 h-px",s),...r})}const Xh={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"}]}};function di(s){return Xh[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Qh(s,r,t){const n=di(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=Cr(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 Cr(s){const r=s.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",jsonc:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",cc:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",dart:"dart",r:"r",lua:"lua",vim:"vim",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",md:"markdown",mdx:"markdown",rst:"text",txt:"text",dockerfile:"dockerfile",makefile:"makefile",gitignore:"text",env:"text",conf:"text",cfg:"text",ini:"ini",sql:"sql",diff:"diff",patch:"diff"}[r||""]||null}const Jh=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Md(s){const r=s.split(".").pop()?.toLowerCase();return Jh.includes(r||"")}function Zh(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 eg(s,r){if(!s)return"";const t=n=>{const o=s[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=t("command");if(n)return n}if(r==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((r==="edit"||r==="multiedit")&&typeof s=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof s=="object"){const n=t("content");if(n)return n}return typeof s=="object"?Object.entries(s).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${i}: ${c}`}).join(`
7
- `):String(s)}const ui=l.createContext(null),Mr=()=>{const s=l.useContext(ui);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},Dd=s=>{const r=Mr();return s(r)},tg=()=>Dd(s=>s.runtime.isDesktop),Ad=()=>Dd(s=>s.runtime.isVSCode),sg=lm("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg typography-ui-label font-medium transition-[background-color,border-color,color,box-shadow,opacity] duration-150 ease-in-out disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-none hover:bg-primary/90",destructive:"bg-destructive text-white shadow-none hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-none hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-none hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-lg gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-lg px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function ve({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?zc:"button";return e.jsx(a,{"data-slot":"button",className:O(sg({variant:r,size:t,className:s})),...o})}const rg=({mode:s,onModeChange:r,className:t})=>{const n=l.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(ve,{size:"sm",variant:"ghost",className:O("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(cm,{className:"h-3 w-3"}):e.jsx(dm,{className:"h-3 w-3"})})},mi=Se.createContext(void 0);function Dr(){const s=Se.useContext(mi);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function Eo(){return Se.useContext(mi)}const ng="Flexoki",og="dark",ag={"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"},ig=[{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"}}],lg={name:ng,type:og,colors:ag,tokenColors:ig},cg="Flexoki",dg="light",ug={"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"},mg=[{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"}}],fg={name:cg,type:dg,colors:ug,tokenColors:mg},fi="flexoki-dark",pi="flexoki-light",pg=lg,hg=fg;function Ed(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 Id(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 hi=Id(pg,fi,"dark"),gi=Id(hg,pi,"light");Ed(hi,fi);Ed(gi,pi);const qr={dark:fi,light:pi},gl=[gi,hi];let xl=!1;function Td(){xl||(Fi(qr.dark,async()=>hi),Fi(qr.light,async()=>gi),xl=!0)}const gg=`
8
- :host {
9
- font-family: var(--font-mono);
10
- font-size: var(--text-code);
11
- }
12
-
13
- :host, pre, [data-diffs], [data-code] {
14
- transform: translateZ(0);
15
- -webkit-transform: translateZ(0);
16
- -webkit-backface-visibility: hidden;
17
- backface-visibility: hidden;
18
- }
19
-
20
- pre, [data-code] {
21
- font-family: var(--font-mono);
22
- font-size: var(--text-code);
23
- }
24
-
25
- [data-code] {
26
- -webkit-overflow-scrolling: touch;
27
- }
28
- /* Reduce hunk separator height */
29
- [data-separator-content] {
30
- height: 24px !important;
31
- }
32
- [data-expand-button] {
33
- height: 24px !important;
34
- width: 24px !important;
35
- }
36
- [data-separator-multi-button] {
37
- row-gap: 0 !important;
38
- }
39
- [data-expand-up] {
40
- height: 12px !important;
41
- min-height: 12px !important;
42
- max-height: 12px !important;
43
- margin: 0 !important;
44
- margin-top: 3px !important;
45
- padding: 0 !important;
46
- border-radius: 4px 4px 0 0 !important;
47
- }
48
- [data-expand-down] {
49
- height: 12px !important;
50
- min-height: 12px !important;
51
- max-height: 12px !important;
52
- margin: 0 !important;
53
- margin-top: -3px !important;
54
- padding: 0 !important;
55
- border-radius: 0 0 4px 4px !important;
56
- }
57
- `;function xg(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 yl=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=Eo()?.currentTheme?.metadata?.variant==="dark";Td();const d=Se.useRef(null),u=Se.useMemo(()=>{const f=xg(n,s,r);if(d.current?.key===f)return d.current.fileDiff;const p={name:n,contents:s,cacheKey:`old-${f}`},h={name:n,contents:r,cacheKey:`new-${f}`},y=ja(p,h);return d.current={key:f,fileDiff:y},y},[n,s,r,t]),m=Se.useMemo(()=>({theme:{dark:qr.dark,light:qr.light},themeType:c?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!1,enableHoverUtility:!1,unsafeCSS:gg}),[c,o,a]);return typeof window>"u"?null:e.jsx(tt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(um,{fileDiff:u,options:m})})},yg=1100,bg=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},bl=(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]})},wg=l.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=l.useCallback(i=>{if(!o)return i;const c=i.lastIndexOf("/");return c>=0?i.slice(c+1):i},[o]);return s.length===0?null:e.jsxs(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[t?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(t.path)}),bl(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(kt,{className:"size-4 opacity-50"})]})}),e.jsx(Yt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Kh,{value:r??"",onValueChange:n,children:s.map(i=>e.jsx(Yh,{value:i.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(i.path)}),e.jsx("span",{className:"ml-auto",children:bl(i.insertions,i.deletions)})]})},i.path))})})]})}),vg=l.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",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:i,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"}})]})]})})}),jg=l.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=l.useMemo(()=>Cr(s)||"text",[s]);return Md(s)?e.jsx(vg,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(yl,{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(yl,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),Sg=l.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=At(l.useCallback(c=>c.directories.get(s)?.diffCache.get(r)??null,[s,r])),i=l.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return i?e.jsx(jg,{filePath:r,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),kg=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=ye(),{currentDirectory:n}=yt(),o=s?t.get(s)??void 0:void 0,i=r.find(c=>c.id===s)?.directory;return o?.path??i??n??void 0},Ng=()=>{const{git:s}=Mr(),r=kg(),{screenWidth:t,isMobile:n}=Nt(),o=Cd(r??null),a=Nd(r??null),i=At(_=>_.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=At(),[m,f]=l.useState(null),[p,h]=l.useState(0),[y,g]=l.useState(null),w=l.useRef(null),x=Fe(_=>_.pendingDiffFile),v=Fe(_=>_.setPendingDiffFile),S=Fe(_=>_.diffLayoutPreference),N=Fe(_=>_.diffFileLayout),j=Fe(_=>_.setDiffFileLayout),k=Fe(_=>_.diffWrapLines),F=Fe(_=>_.setDiffWrapLines),I=n||k,M=l.useMemo(()=>{if(!a?.files)return[];const _=a.diffStats??{};return a.files.map(z=>({...z,insertions:_[z.path]?.insertions??0,deletions:_[z.path]?.deletions??0,isNew:bg(z)})).sort((z,D)=>z.path.localeCompare(D.path))},[a]),b=l.useMemo(()=>m?M.find(_=>_.path===m)??null:null,[M,m]),C=l.useMemo(()=>{if(!b)return null;const _=N[b.path];if(_)return _;if(S==="inline")return"inline";if(S==="side-by-side")return"side-by-side";const z=t<yg;return b.isNew||z?"inline":"side-by-side"},[b,N,S,t]);l.useEffect(()=>{r&&(c(r),At.getState().directories.get(r)?.status||d(r,s))},[r,c,d,s]),l.useEffect(()=>{x&&(f(x),v(null))},[x,v]),l.useEffect(()=>{!m&&!x&&M.length>0&&f(M[0].path)},[M,m,x]),l.useEffect(()=>{m&&M.length>0&&(M.some(z=>z.path===m)||f(M[0]?.path??null))},[M,m]);const A=l.useCallback(_=>{f(_)},[]),P=(C??"side-by-side")==="side-by-side",L=At(l.useCallback(_=>!r||!m?null:_.directories.get(r)?.diffCache.get(m)??null,[r,m])),$=!!L,q=!!m&&!$;l.useEffect(()=>{if(g(null),!r||!m){w.current=null;return}if(L){w.current=null;return}const _=`${r}::${m}::${p}`;if(w.current===_)return;w.current=_;let z=!1;return(async()=>{try{const D=s.getGitFileDiff(r,{path:m}),H=15e3,X=new Promise((ae,fe)=>{setTimeout(()=>fe(new Error(`Timed out after ${H}ms`)),H)}),he=await Promise.race([D,X]);if(z)return;u(r,m,{original:he.original??"",modified:he.modified??""})}catch(D){if(z)return;const H=D instanceof Error?D.message:String(D);g(H)}})(),()=>{z=!0,w.current===_&&(w.current=null)}},[r,m,L,s,u,p]);const ee=()=>!r||M.length===0?null:M.map(_=>e.jsx(Sg,{directory:r,filePath:_.path,isVisible:_.path===m,renderSideBySide:P,wrapLines:I},_.path)),ce=()=>r?i&&!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."}):M.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Working tree clean — no changes to display"}):e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[ee(),q&&!$&&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(_=>_+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(Ka,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${M.length} ${M.length===1?"file":"files"} changed`})]}),e.jsx(wg,{changedFiles:M,selectedFile:m,selectedFileEntry:b,onSelectFile:A,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),b&&e.jsx("button",{type:"button",onClick:()=>F(!k),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${I?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:I?"Disable line wrap":"Enable line wrap",children:e.jsx(mm,{className:"size-4"})}),b&&C&&e.jsx(rg,{mode:C==="side-by-side"?"side-by-side":"unified",onModeChange:_=>{if(!b)return;const z=_==="side-by-side"?"side-by-side":"inline";j(b.path,z)}})]}),ce()]})},Cg=()=>{const{git:s}=Mr(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=ye(),{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}=At(),f=Gh(d??null);return l.useEffect(()=>{d&&(u(d),At.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},Mg=()=>{const s=Fe(d=>d.setSessionSwitcherOpen),r=Fe(d=>d.toggleSidebar),{isMobile:t}=Nt(),[n,o]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=l.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:i,"aria-label":"Open sessions",className:c,children:e.jsx(So,{className:"h-5 w-5"})})})},wl=()=>{const s=Fe(D=>D.setSessionSwitcherOpen),r=Fe(D=>D.toggleSidebar),t=Fe(D=>D.setSettingsDialogOpen),n=Fe(D=>D.toggleCommandPalette),o=Fe(D=>D.toggleHelpDialog),a=Fe(D=>D.isSidebarOpen),i=Fe(D=>D.sidebarWidth),c=Fe(D=>D.activeMainTab),d=Fe(D=>D.setActiveMainTab),{getCurrentModel:u}=lt(),m=ye(D=>D.getContextUsage),{isMobile:f}=Nt(),p=Cg(),h=Do(D=>D.available),y=l.useRef(null),[g,w]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Se.useEffect(()=>{if(typeof window>"u")return;const D=typeof window.opencodeDesktop<"u";w(D)},[]);const v=u(),S=v&&typeof v.limit=="object"&&v.limit!==null?v.limit:null,N=S&&typeof S.context=="number"?S.context:0,j=S&&typeof S.output=="number"?S.output:0,k=m(N,j),F=Fe(D=>D.isSessionSwitcherOpen),I=l.useCallback(()=>{if(typeof document>"u")return;const D=document.activeElement;if(!D)return;const H=D.tagName;(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||D.isContentEditable)&&D.blur()},[]),M=l.useCallback(()=>{if(f){I(),s(!F);return}r()},[I,f,F,s,r]),b=l.useCallback(()=>{f&&I(),s(!1),t(!0)},[I,f,s,t]),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",A=l.useMemo(()=>g&&x?a?"pl-0":"pl-[8.0rem]":"pl-3",[g,x,a]),P=l.useCallback(()=>{if(typeof document>"u")return;const D=y.current?.getBoundingClientRect().height;D&&document.documentElement.style.setProperty("--oc-header-height",`${D}px`)},[]);Se.useEffect(()=>{if(typeof window>"u")return;P();const D=y.current;if(!D||typeof ResizeObserver>"u")return()=>{};const H=new ResizeObserver(()=>{P()});return H.observe(D),window.addEventListener("resize",P),window.addEventListener("orientationchange",P),()=>{H.disconnect(),window.removeEventListener("resize",P),window.removeEventListener("orientationchange",P)}},[P]),Se.useEffect(()=>{P()},[P,f]);const L=l.useCallback(async D=>{if(!D.target.closest("button, a, input, select, textarea")&&D.button===0&&g)try{const{getCurrentWindow:H}=await Ks(async()=>{const{getCurrentWindow:he}=await import("./vendor-.bun-CpaXrlrC.js").then(ae=>ae.c9);return{getCurrentWindow:he}},__vite__mapDeps([0,1]));await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[g]),$=l.useCallback(async D=>{if(D.button===0&&g)try{const{getCurrentWindow:H}=await Ks(async()=>{const{getCurrentWindow:he}=await import("./vendor-.bun-CpaXrlrC.js").then(ae=>ae.c9);return{getCurrentWindow:he}},__vite__mapDeps([0,1]));await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[g]),q=l.useMemo(()=>[{id:"chat",label:"Chat",icon:fm},{id:"diff",label:"Diff",icon:_s,badge:!f&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:ar},{id:"git",label:"Git",icon:ns,showDot:f&&p>0}],[p,f]);Se.useEffect(()=>{const D=H=>{if((H.metaKey||H.ctrlKey)&&!H.shiftKey&&!H.altKey){const X=parseInt(H.key,10);X>=1&&X<=q.length&&(H.preventDefault(),d(q[X-1].id))}};return window.addEventListener("keydown",D),()=>window.removeEventListener("keydown",D)},[q,d]);const ee=(D,H)=>{const X=c===D.id,he=D.icon,ae=D.id==="chat",fe=D.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(D.id),onMouseDown:X?$:void 0,className:O("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",X?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",X?"text-foreground":"text-muted-foreground",X&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",X&&ae&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",ae&&!(g&&x&&a)&&"border-l",fe&&"border-r",ae&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...X&&ae&&a?{"--sidebar-w":g&&x?`${i}px`:"64px"}:{},...ae&&!(g&&x&&a)||fe?{borderColor:"var(--interactive-border)"}:{}},"aria-label":D.label,"aria-selected":X,role:"tab",children:[f?e.jsx(he,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),e.jsx("span",{className:"header-tab-label",children:D.label})]}),ae&&!f&&k&&k.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Fa,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})}),D.badge!==void 0&&D.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:D.badge})]}),!H&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},D.id)},ce=()=>e.jsxs("div",{onMouseDown:L,className:O("app-region-drag relative flex h-12 select-none items-center",A),role:"tablist","aria-label":"Main navigation",children:[!(g&&x)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:M,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(So,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:q.map((D,H)=>ee(D,H===q.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(Qe,{delayDuration:500,children:[e.jsx(Je,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:C,children:e.jsx(Sr,{className:"h-5 w-5"})})}),e.jsx(Xe,{children:e.jsx("p",{children:"Command Palette (Ctrl+X)"})})]}),e.jsxs(Qe,{delayDuration:500,children:[e.jsx(Je,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:C,children:e.jsx(Ur,{className:"h-5 w-5"})})}),e.jsx(Xe,{children:e.jsx("p",{children:"Keyboard Shortcuts (Ctrl+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(pm,{className:"h-5 w-5"})}),k&&k.totalTokens>0&&c==="chat"&&e.jsx(Fa,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact",isMobile:!0})]}),e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center",role:"tablist","aria-label":"Main navigation",children:q.map(D=>{const H=c===D.id,X=D.icon;return e.jsxs(Qe,{delayDuration:500,children:[e.jsx(Je,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&I(),d(D.id)},"aria-label":D.label,"aria-selected":H,role:"tab",className:O(C,"relative",H&&"text-foreground"),children:[e.jsx(X,{className:"h-5 w-5"}),D.badge!==void 0&&D.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:D.badge}),D.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(Xe,{children:e.jsx("p",{children:D.label})})]},D.id)})}),e.jsxs(Qe,{delayDuration:500,children:[e.jsx(Je,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:b,"aria-label":"Open settings",className:O(C,"relative"),children:[e.jsx(wr,{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(Xe,{children:e.jsx("p",{children:h?"Settings (Update available)":"Settings"})})]})]})]}),z=O("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:z,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?_():ce()})};function xi({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:O("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function Fd({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:O("@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 Pd({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:O("leading-none font-semibold",s),...r})}function Rd({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:O("px-6",s),...r})}class Bt extends l.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(xi,{className:"w-full max-w-md",children:[e.jsx(Fd,{className:"text-center",children:e.jsxs(Pd,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Sa,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Rd,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The application encountered an unexpected error. This has been logged for debugging."}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(fs,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let Rn=0;function os({...s}){return e.jsx(hm,{"data-slot":"dialog",...s})}function Dg({...s}){return e.jsx(ym,{"data-slot":"dialog-portal",...s})}const Ld=Se.forwardRef(({className:s,...r},t)=>(Se.useEffect(()=>(Rn+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Rn=Math.max(0,Rn-1),Rn===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Hc,{ref:t,"data-slot":"dialog-overlay",className:O("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));Ld.displayName=Hc.displayName;function as({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Dg,{"data-slot":"dialog-portal",children:[e.jsx(Ld,{className:"rounded-none"}),e.jsxs(gm,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:O("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(xm,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(zt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ds({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:O("flex flex-col gap-2 text-center sm:text-left",s),...r})}function Bs({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:O("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",s),...r})}function us({className:s,...r}){return e.jsx(bm,{"data-slot":"dialog-title",className:O("typography-markdown leading-none font-semibold text-foreground",s),...r})}function Is({className:s,...r}){return e.jsx(wm,{"data-slot":"dialog-description",className:O("text-muted-foreground typography-ui-label",s),...r})}const vl="https://github.com/btriapitsyn/openchamber/releases";async function Ag(){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 Eg(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 Pa=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Se.useState(!1),[p,h]=Se.useState("idle"),[y,g]=Se.useState(null),w=t?.version?`${vl}/tag/v${t.version}`:vl,x=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",S=t?.updateCommand||"openchamber update";Se.useEffect(()=>{s||(h("idle"),g(null))},[s]);const N=async()=>{try{await navigator.clipboard.writeText(S),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},j=Se.useCallback(async()=>{h("updating"),g(null);const F=await Ag();if(!F.success){h("error"),g(F.error||"Update failed");return}h("restarting"),await new Promise(M=>setTimeout(M,2e3)),h("reconnecting"),await Eg()?window.location.reload():(h("error"),g("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),k=p!=="idle"&&p!=="error";return e.jsx(os,{open:s,onOpenChange:k?void 0:r,children:e.jsxs(as,{className:"max-w-md",children:[e.jsx(ds,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(vm,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(t?.currentVersion||t?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t?.currentVersion&&e.jsx("span",{className:"font-mono",children:t.currentVersion}),t?.currentVersion&&t?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),t?.version&&e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),v&&k&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wn,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[p==="updating"&&"Installing update...",p==="restarting"&&"Server restarting...",p==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),t?.body&&!k&&e.jsx(tt,{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((F,I)=>/^\d+\.\d+\.\d+$/.test(F.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",F.trim(),`
58
- `]},I):F.replace(/^- /gm,"• ").trim()+`
59
-
60
- `)})}),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(jm,{className:"h-4 w-4"}),e.jsx("span",{children:"Or update via terminal:"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-2 bg-muted rounded-md font-mono text-sm text-foreground overflow-x-auto",children:S}),e.jsx("button",{onClick:N,className:O("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(Mt,{className:"h-4 w-4"}):e.jsx(Sm,{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:[x,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${x}%`}})})]}),(i||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:i||y})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:w,target:"_blank",rel:"noopener noreferrer",className:O("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(ka,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:c,className:O("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Wr,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:O("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(Wn,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:O("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(fs,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!k&&e.jsxs("button",{onClick:j,className:O("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Wr,{className:"h-4 w-4"}),"Update Now"]}),v&&k&&e.jsxs("button",{disabled:!0,className:O("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(Wn,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},jl=264,Sl=200,kl=500,Ig=40,Nl="openchamber:check-for-updates",Tg=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=Fe(),[c,d]=l.useState(!1),u=l.useRef(0),m=l.useRef(n||jl),[f,p]=l.useState(!1),h=Do(),y=l.useRef(!1),g=h.checkForUpdates,{available:w,downloaded:x,checking:v}=h,[S,N]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const b=typeof window.opencodeDesktop<"u";N(b)},[]),l.useEffect(()=>{if(typeof window>"u")return;const b=()=>{typeof window.opencodeDesktop<"u"&&(y.current=!0,g())};return window.addEventListener(Nl,b),()=>{window.removeEventListener(Nl,b)}},[g]),l.useEffect(()=>{y.current&&(v||(w||x?p(!0):se.success("No updates available",{description:"You are running the latest version."}),y.current=!1))},[w,x,v]),l.useEffect(()=>{if(r||!c)return;const b=A=>{const P=A.clientX-u.current,L=Math.min(kl,Math.max(Sl,m.current+P));o(L)},C=()=>{d(!1)};return window.addEventListener("pointermove",b),window.addEventListener("pointerup",C,{once:!0}),()=>{window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",C)}},[r,c,o]),l.useEffect(()=>{r&&c&&d(!1)},[r,c]);const k=l.useCallback(async b=>{if(b.button===0&&S)try{const{getCurrentWindow:C}=await Ks(async()=>{const{getCurrentWindow:P}=await import("./vendor-.bun-CpaXrlrC.js").then(L=>L.c9);return{getCurrentWindow:P}},__vite__mapDeps([0,1]));await C().startDragging()}catch(C){console.error("Failed to start window dragging from sidebar:",C)}},[S]);if(r)return null;const F=s?Math.min(kl,Math.max(Sl,n||jl)):0,I=S&&j,M=b=>{s&&(d(!0),u.current=b.clientX,m.current=F,b.preventDefault())};return e.jsxs("aside",{className:O("relative flex h-full overflow-hidden border-r",S?"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:`${F}px`,minWidth:`${F}px`,maxWidth:`${F}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||F===0,children:[s&&e.jsx("div",{className:O("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:O("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:`${F}px`,overflowX:"hidden"},"aria-hidden":!s,children:[I&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Ig}px`},onMouseDown:k,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Bt,{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:O("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(wr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),w||x?e.jsxs("button",{onClick:()=>p(!0),className:O("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(Wr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!S&&e.jsxs(Qe,{children:[e.jsx(Je,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:O("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(_t,{className:"h-4 w-4"})})}),e.jsx(Xe,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Pa,{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 Od({className:s,...r}){return e.jsx(kr,{"data-slot":"command",className:O("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function Fg({title:s="Command Palette",description:r="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(os,{...a,children:[e.jsxs(ds,{className:"sr-only",children:[e.jsx(us,{children:s}),e.jsx(Is,{children:r})]}),e.jsx(as,{className:O("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Od,{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 $d({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(vr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(kr.Input,{"data-slot":"command-input",className:O("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 _d({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(tt,{as:kr.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:O("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 Bd({...s}){return e.jsx(kr.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function Hr({className:s,...r}){return e.jsx(kr.Group,{"data-slot":"command-group",className:O("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 go({className:s,...r}){return e.jsx(kr.Separator,{"data-slot":"command-separator",className:O("bg-border -mx-1 h-px",s),...r})}function $t({className:s,...r}){return e.jsx(kr.Item,{"data-slot":"command-item",className:O("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 Js({className:s,...r}){const t=a=>{const i=a.trim().toLowerCase();return i==="ctrl"||i==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?e.jsx(Sr,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(jn,{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:O("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,i)=>e.jsxs(Se.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):r.children})}const Pg=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setSessionCreateDialogOpen:n,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,toggleSidebar:c}=Fe(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=ye(),{currentDirectory:f}=yt(),{themeMode:p,setThemeMode:h}=Dr(),y=()=>{r(!1)},g=async()=>{o("chat"),i(!1),d(),y()},w=P=>{u(P),y()},x=P=>{h(P),y()},v=()=>{t(!0),y()},S=()=>{n(!0),y()},{isMobile:N}=Nt(),j=()=>{if(N){const{isSessionSwitcherOpen:P}=Fe.getState();i(!P)}else c();y()},k=()=>{o("diff"),y()},F=()=>{o("git"),y()},I=()=>{o("terminal"),y()},M=()=>{a(!0),y()},b=()=>{un(),y()},C=m(f??""),A=l.useMemo(()=>C.slice(0,5),[C]);return e.jsxs(Fg,{open:s,onOpenChange:r,children:[e.jsx($d,{placeholder:"Type a command or search..."}),e.jsxs(_d,{children:[e.jsx(Bd,{children:"No results found."}),e.jsxs(Hr,{heading:"Actions",children:[e.jsxs($t,{onSelect:j,children:[e.jsx(So,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsx(Js,{children:"Ctrl + L"})]}),e.jsxs($t,{onSelect:g,children:[e.jsx(Ht,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Js,{children:"Ctrl + N"})]}),e.jsxs($t,{onSelect:S,children:[e.jsx(ns,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Js,{children:"Shift + Ctrl + N"})]}),e.jsxs($t,{onSelect:v,children:[e.jsx(Ur,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsx(Js,{children:"Ctrl + H"})]}),e.jsxs($t,{onSelect:k,children:[e.jsx(_s,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsx(Js,{children:"Ctrl + E"})]}),e.jsxs($t,{onSelect:F,children:[e.jsx(ns,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsx(Js,{children:"Ctrl + G"})]}),e.jsxs($t,{onSelect:I,children:[e.jsx(ar,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsx(Js,{children:"Ctrl + T"})]}),e.jsxs($t,{onSelect:M,children:[e.jsx(wr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsx(Js,{children:"Ctrl + ,"})]}),e.jsxs($t,{onSelect:b,children:[e.jsx(fs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(go,{}),e.jsxs(Hr,{heading:"Theme",children:[e.jsxs($t,{onSelect:()=>x("light"),children:[e.jsx(km,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),p==="light"&&e.jsx(Mt,{className:"ml-auto h-4 w-4"})]}),e.jsxs($t,{onSelect:()=>x("dark"),children:[e.jsx(Nm,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),p==="dark"&&e.jsx(Mt,{className:"ml-auto h-4 w-4"})]}),e.jsxs($t,{onSelect:()=>x("system"),children:[e.jsx(Uc,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),p==="system"&&e.jsx(Mt,{className:"ml-auto h-4 w-4"})]})]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(go,{}),e.jsx(Hr,{heading:"Recent Sessions",children:A.map(P=>e.jsxs($t,{onSelect:()=>w(P.id),children:[e.jsx(Ya,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})]},P.id))})]})]})]})},Rg=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(ko,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="shift"||t==="⇧"?e.jsx(Mm,{className:"h-3.5 w-3.5"},`shift-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(Sr,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},Lg=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(l.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),Rg(t,n)]},`${t}-${n}`))},Og=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=Fe(),t=[{category:"Navigation & Commands",items:[{keys:["Ctrl + X"],description:"Open Command Palette",icon:Sr},{keys:["Ctrl + H"],description:"Show Keyboard Shortcuts (this dialog)",icon:Ur},{keys:["Ctrl + L"],description:"Toggle Session Sidebar",icon:So},{keys:["Ctrl + M"],description:"Open Model Selector",icon:Yr}]},{category:"Session Management",items:[{keys:["Ctrl + N"],description:"Create New Session",icon:Ht},{keys:["Shift + Ctrl + N"],description:"Open Worktree Creator",icon:ns},{keys:["Ctrl + I"],description:"Focus Chat Input",icon:Wc},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Vr}]},{category:"Interface",items:[{keys:["⌘ + /","Ctrl + /"],description:"Cycle Theme (Light → Dark → System)",icon:Cm},{keys:["Ctrl + E"],description:"Open Diff Panel",icon:_s},{keys:["Ctrl + G"],description:"Open Git Panel",icon:ns},{keys:["Ctrl + T"],description:"Open Terminal",icon:ar},{keys:["Ctrl + ,"],description:"Open Settings",icon:wr}]}];return e.jsx(os,{open:s,onOpenChange:r,children:e.jsxs(as,{className:"max-w-2xl",children:[e.jsxs(ds,{children:[e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(wr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Is,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsx("div",{className:"space-y-4 mt-3",children:t.map(n=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:n.category}),e.jsx("div",{className:"space-y-1",children:n.items.map((o,a)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[o.icon&&e.jsx(o.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:o.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(o.keys)?o.keys:o.keys.split(" / ")).map((i,c)=>e.jsxs(l.Fragment,{children:[c>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:Lg(i)})]},`${i}-${c}`))})]},a))})]},n.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(Ur,{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.jsx("li",{children:"• Use Command Palette (Ctrl + X) 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"})]})]})]})})]})})},Zo=new Set,ea=new Set,ta=new Set,hr={onDeleteRequest(s){return Zo.add(s),()=>{Zo.delete(s)}},requestDelete(s){s.sessions.length&&Zo.forEach(r=>r(s))},onCreateRequest(s){return ea.add(s),()=>{ea.delete(s)}},requestCreate(s){const r=s??{};ea.forEach(t=>t(r))},onDirectoryRequest(s){return ta.add(s),()=>{ta.delete(s)}},requestDirectoryDialog(){ta.forEach(s=>s())}};function zd(s){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...s,children:e.jsx("path",{d:"M232.49,192.49l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,0,1,17-17L180,187V141L128,89,76,141V187l11.51-11.52a12,12,0,0,1,17,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L52,187V136a12,12,0,0,1,3.51-8.49L116,67V24a12,12,0,0,1,24,0V67l60.49,60.48A12,12,0,0,1,204,136v51l11.51-11.52a12,12,0,0,1,17,17Z",transform:"rotate(180 128 128)"})})}const $g=".openchamber",Cl="oc.sessions.groupCollapse",Ml="oc.sessions.expandedParents",Dl=s=>{const r=new Date(s),t=new Date,n=(i,c)=>i.getFullYear()===c.getFullYear()&&i.getMonth()===c.getMonth()&&i.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(",","")},Us=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},_g=(s,r)=>{const t=Us(s),n=Array.from(r.values())[0];if(n?.projectDirectory)return Us(n.projectDirectory);if(!t)return null;const o=`/${$g}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},Ra=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,i]=l.useState(null),[c,d]=l.useState(""),[u,m]=l.useState(null),f=l.useRef(null),[p,h]=l.useState(new Set),[y,g]=l.useState(()=>new Map),w=l.useRef(new Set),x=l.useMemo(()=>rs(),[]),[v,S]=l.useState(new Set),[N,j]=l.useState(null),[k,F]=l.useState(new Set),[I,M]=l.useState(null),[b,C]=l.useState(new Set),A=l.useRef(new Map),P=yt(J=>J.currentDirectory),L=yt(J=>J.homeDirectory),$=yt(J=>J.setDirectory),q=Fe(J=>J.setActiveMainTab),ee=Fe(J=>J.setSessionSwitcherOpen),ce=Fe(J=>J.openMultiRunLauncher),_=ye(J=>J.getSessionsByDirectory),z=ye(J=>J.currentSessionId),D=ye(J=>J.setCurrentSession),H=ye(J=>J.updateSessionTitle),X=ye(J=>J.shareSession),he=ye(J=>J.unshareSession),ae=ye(J=>J.sessionMemoryState),fe=ye(J=>J.sessionActivityPhase),je=ye(J=>J.worktreeMetadata),W=ye(J=>J.availableWorktrees),te=ye(J=>J.openNewSessionDraft),[oe,V]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const J=x.getItem(Cl);if(J){const re=JSON.parse(J);Array.isArray(re)&&S(new Set(re.filter(le=>typeof le=="string")))}const ke=x.getItem(Ml);if(ke){const re=JSON.parse(ke);Array.isArray(re)&&h(new Set(re.filter(le=>typeof le=="string")))}}catch{}},[x]),l.useEffect(()=>{typeof window>"u"||V(typeof window.opencodeDesktop<"u")},[]);const ue=_(P),ge=l.useMemo(()=>[...ue].sort((J,ke)=>(ke.time?.created||0)-(J.time?.created||0)),[ue]);l.useEffect(()=>{if(!P){j(null);return}let J=!1;return Zr(P).then(ke=>{J||j(ke)}).catch(()=>{J||j(null)}),()=>{J=!0}},[P]);const ie=l.useMemo(()=>new Map(ge.map(J=>[J.id,J])),[ge]),De=l.useMemo(()=>{const J=new Map;return ge.forEach(ke=>{const re=ke.parentID;re&&J.set(ke.id,re)}),J},[ge]),Ce=l.useMemo(()=>{const J=new Map;return ge.forEach(ke=>{const re=ke.parentID;if(!re)return;const le=J.get(re)??[];le.push(ke),J.set(re,le)}),J.forEach(ke=>ke.sort((re,le)=>(le.time?.created||0)-(re.time?.created||0))),J},[ge]);l.useEffect(()=>{z&&h(J=>{const ke=new Set(J);let re=De.get(z)||null,le=!1;for(;re;)ke.has(re)||(ke.add(re),le=!0),re=De.get(re)||null;return le?ke:J})},[z,De]);const Ie=l.useMemo(()=>_g(P,je),[P,je]);l.useEffect(()=>{const J=new Set;ge.forEach(ke=>{const re=Us(ke.directory??null);re&&J.add(re)}),Ie&&J.add(Ie),J.forEach(ke=>{const re=y.get(ke);re&&re!=="unknown"||w.current.has(ke)||(w.current.add(ke),Le.listLocalDirectory(ke).then(()=>{g(le=>{const Ae=new Map(le);return Ae.get(ke)==="exists"?le:(Ae.set(ke,"exists"),Ae)})}).catch(()=>{g(le=>{const Ae=new Map(le);return Ae.get(ke)==="missing"?le:(Ae.set(ke,"missing"),Ae)})}).finally(()=>{w.current.delete(ke)}))})},[ge,Ie,y]),l.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const K=l.useMemo(()=>_o(P,L),[P,L]),G=l.useMemo(()=>ls(P,L),[P,L]),T=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."})]}),Y=l.useCallback((J,ke)=>{if(!ke){if(s&&(q("chat"),ee(!1)),!t&&J===z){r?.(J);return}D(J),r?.(J)}},[t,z,s,r,q,D,ee]),E=l.useCallback(async()=>{a&&c.trim()&&(await H(a,c.trim()),i(null),d(""))},[a,c,H]),B=l.useCallback(()=>{i(null),d("")},[]),U=l.useCallback(async J=>{const ke=await X(J.id);ke&&ke.share?.url?se.success("Session shared",{description:"You can copy the link from the menu."}):se.error("Unable to share session")},[X]),be=l.useCallback((J,ke)=>{navigator.clipboard.writeText(J).then(()=>{m(ke),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{se.error("Failed to copy URL")})},[]),Q=l.useCallback(async J=>{await he(J)?se.success("Session unshared"):se.error("Unable to unshare session")},[he]),xe=l.useCallback(J=>{const ke=[],re=le=>{(Ce.get(le)??[]).forEach($e=>{ke.push($e),re($e.id)})};return re(J),ke},[Ce]),He=ye(J=>J.deleteSession),Ke=ye(J=>J.deleteSessions),ze=l.useCallback(async J=>{const ke=xe(J.id);if(ke.length===0)await He(J.id)?se.success("Session deleted"):se.error("Failed to delete session");else{const re=[J.id,...ke.map($e=>$e.id)],{deletedIds:le,failedIds:Ae}=await Ke(re);le.length>0&&se.success(`Deleted ${le.length} session${le.length===1?"":"s"}`),Ae.length>0&&se.error(`Failed to delete ${Ae.length} session${Ae.length===1?"":"s"}`)}},[xe,He,Ke]),st=l.useCallback(J=>{q("chat"),s&&ee(!1),te({directoryOverride:J??null})},[te,q,ee,s]),it=l.useCallback(()=>{hr.requestCreate({worktreeMode:"create"})},[]),at=l.useCallback(()=>{oe&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(J=>{J.success&&J.path?$(J.path,{showOverlay:!0}):J.error&&J.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:J.error})}).catch(J=>{console.error("Desktop: Error selecting directory:",J),se.error("Failed to select directory")}):hr.requestDirectoryDialog()},[oe,$]),ct=l.useCallback(J=>{h(ke=>{const re=new Set(ke);re.has(J)?re.delete(J):re.add(J);try{x.setItem(Ml,JSON.stringify(Array.from(re)))}catch{}return re})},[x]),ut=l.useCallback(J=>{const ke=Ce.get(J.id)??[];return{session:J,children:ke.map(re=>ut(re))}},[Ce]),pt=l.useMemo(()=>{const J=new Map,ke=Us(Ie??null),re=new Map,le=new Set;W.forEach(Ue=>{if(Ue.path){const We=Us(Ue.path)??Ue.path;le.add(We),re.set(We,Ue)}});const Ae=Ue=>{const We=Us(Ue.directory??null),Ze=je.get(Ue.id),de=((Ze?.path?le.has(Us(Ze.path)??Ze.path):!1)?Ze:null)??(We?re.get(We)??null:null),we=!de&&(We&&ke?We===ke:!We&&!!ke),Me=we?"main":de?.path??We??Ue.id,Pe=de?.path??We??ke??null;if(!J.has(Me)){const qe=we?"Main workspace":de?.label||de?.branch||_o(Pe||"",L)||"Worktree",bt=de?.relativePath?ls(de.relativePath,L):Pe?ls(Pe,L):null;J.set(Me,{id:Me,label:qe,description:bt,isMain:we,worktree:de,directory:Pe,sessions:[]})}return J.get(Me)};return ge.filter(Ue=>{const We=Ue.parentID;return We?!ie.has(We):!0}).forEach(Ue=>{const We=Ae(Ue),Ze=ut(Ue);We.sessions.push(Ze)}),J.has("main")||J.set("main",{id:"main",label:"Main workspace",description:ke?ls(ke,L):null,isMain:!0,worktree:null,directory:ke,sessions:[]}),re.forEach((Ue,We)=>{const Ze=Ue.path;J.has(Ze)||J.set(Ze,{id:Ze,label:Ue.label||Ue.branch||_o(We,L)||"Worktree",description:Ue.relativePath?ls(Ue.relativePath,L):ls(We,L),isMain:!1,worktree:Ue,directory:We,sessions:[]})}),J.forEach(Ue=>{Ue.sessions.sort((We,Ze)=>(Ze.session.time?.created||0)-(We.session.time?.created||0))}),Array.from(J.values()).sort((Ue,We)=>Ue.isMain!==We.isMain?Ue.isMain?-1:1:(Ue.label||"").localeCompare(We.label||""))},[ge,je,W,Ie,L,ut,ie]),vt=l.useCallback(J=>{S(ke=>{const re=new Set(ke);re.has(J)?re.delete(J):re.add(J);try{x.setItem(Cl,JSON.stringify(Array.from(re)))}catch{}return re})},[x]),xt=l.useCallback(J=>{F(ke=>{const re=new Set(ke);return re.has(J)?re.delete(J):re.add(J),re})},[]);l.useEffect(()=>{if(!oe)return;const J=new IntersectionObserver(ke=>{ke.forEach(re=>{const le=re.target.dataset.groupId;le&&C(Ae=>{const $e=new Set(Ae);return re.isIntersecting?$e.delete(le):$e.add(le),$e})})},{threshold:0});return A.current.forEach(ke=>{ke&&J.observe(ke)}),()=>J.disconnect()},[oe,pt]);const mt=l.useCallback((J,ke=0,re)=>{const le=J.session,Ae=Us(le.directory??null)??Us(re??null),Ue=(Ae?y.get(Ae):null)==="missing",We=ae.get(le.id),Ze=z===le.id,me=le.title||"Untitled Session",de=J.children.length>0,we=p.has(le.id),Me=le.summary?.additions,Pe=le.summary?.deletions,qe=typeof Me=="number"||typeof Pe=="number";if(a===le.id)return e.jsx("div",{className:O("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",ke>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:ft=>{ft.preventDefault(),E()},children:[e.jsx("input",{value:c,onChange:ft=>d(ft.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:ft=>{ft.key==="Escape"&&B()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Mt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:B,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(zt,{className:"size-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[de?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:we?e.jsx(kt,{className:"h-3 w-3"}):e.jsx(Ss,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Dl(le.time?.created||Date.now())}),le.share?e.jsx(Oo,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,qe&&((Me??0)!==0||(Pe??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,Me??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Pe??0)]})]}):null,de?e.jsxs("span",{className:"truncate",children:[J.children.length," ",J.children.length===1?"task":"tasks"]}):null]})]})},le.id);const bt=fe?.get(le.id)??"idle",Et=bt==="busy"||bt==="cooldown",Ct=We&&We.isZombie?e.jsx(Sa,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(l.Fragment,{children:[e.jsx("div",{className:O("group relative flex items-center rounded-md px-1.5 py-1",Ze?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",Ue?"opacity-75":"",ke>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:Ue,onClick:()=>Y(le.id,Ue),className:O("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground"),children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:e.jsx("span",{className:O("truncate typography-ui-label font-normal text-foreground",Et&&"animate-pulse [animation-duration:1.8s]"),children:me})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[de?e.jsx("span",{role:"button",tabIndex:0,onClick:ft=>{ft.stopPropagation(),ct(le.id)},onKeyDown:ft=>{(ft.key==="Enter"||ft.key===" ")&&(ft.preventDefault(),ft.stopPropagation(),ct(le.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":we?"Collapse subsessions":"Expand subsessions",children:we?e.jsx(kt,{className:"h-3 w-3"}):e.jsx(Ss,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Dl(le.time?.created||Date.now())}),le.share?e.jsx(Oo,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,qe&&((Me??0)!==0||(Pe??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,Me??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Pe??0)]})]}):null,de?e.jsxs("span",{className:"truncate",children:[J.children.length," ",J.children.length===1?"task":"tasks"]}):null,Ue?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Sa,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Ct,e.jsxs(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:O("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:ft=>ft.stopPropagation(),onKeyDown:ft=>ft.stopPropagation(),children:e.jsx(Sn,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(St,{onClick:()=>{i(le.id),d(me)},className:"[&>svg]:mr-1",children:[e.jsx(Ws,{className:"mr-1 h-4 w-4"}),"Rename"]}),le.share?e.jsxs(e.Fragment,{children:[e.jsx(St,{onClick:()=>{le.share?.url&&be(le.share.url,le.id)},className:"[&>svg]:mr-1",children:u===le.id?e.jsxs(e.Fragment,{children:[e.jsx(Mt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(zs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(St,{onClick:()=>Q(le.id),className:"[&>svg]:mr-1",children:[e.jsx(Dm,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(St,{onClick:()=>U(le),className:"[&>svg]:mr-1",children:[e.jsx(Oo,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(St,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>ze(le),children:[e.jsx(Es,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),de&&we?J.children.map(ft=>mt(ft,ke+1,Ae??re)):null]},le.id)},[y,ae,fe,z,p,a,c,E,B,ct,Y,U,be,Q,ze,u,s]);return e.jsxs("div",{className:O("flex h-full flex-col text-foreground overflow-x-hidden",s?"":oe?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-14 select-none px-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center gap-0",children:[e.jsxs("button",{type:"button",onClick:at,className:O("group flex min-w-0 flex-1 items-center gap-2 rounded-md px-0 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!oe&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:G||"/",children:[e.jsx("span",{className:O("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!oe&&"bg-sidebar/60"),children:e.jsx(ms,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}),e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("p",{className:"truncate whitespace-nowrap typography-ui font-semibold text-muted-foreground group-hover:text-foreground",children:K||"/"})})]}),N?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:it,className:O("inline-flex h-10 w-7 flex-shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!oe&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",title:"Manage worktrees",children:e.jsx(Vc,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}),e.jsx("button",{type:"button",onClick:ce,className:O("inline-flex h-10 w-7 flex-shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!oe&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"New Multi-Run",title:"New Multi-Run",children:e.jsx(zd,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})})]}):null]})}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:O("space-y-1 pb-1 pl-2.5 pr-1",""),children:pt.length===0?T:n&&pt.length===1&&pt[0].isMain||o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const J=pt.find(Ue=>Ue.isMain)??pt[0],ke=n?10:7,re=J.sessions.length,le=k.has(J.id),Ae=le?J.sessions:J.sessions.slice(0,ke),$e=re-Ae.length;return re===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."}):e.jsxs(e.Fragment,{children:[Ae.map(Ue=>mt(Ue,0,J.directory)),$e>0&&!le?e.jsxs("button",{type:"button",onClick:()=>xt(J.id),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 ",$e," more ",$e===1?"session":"sessions"]}):null,le&&re>ke?e.jsx("button",{type:"button",onClick:()=>xt(J.id),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]})})()}):pt.map(J=>e.jsxs("div",{className:"relative",children:[oe&&e.jsx("div",{ref:ke=>{A.current.set(J.id,ke)},"data-group-id":J.id,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("button",{type:"button",onClick:()=>vt(J.id),className:O("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b transition-colors duration-150",oe?b.has(J.id)?"bg-sidebar":"bg-transparent":"bg-sidebar"),style:{borderColor:I===J.id?"var(--color-border)":v.has(J.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>M(J.id),onMouseLeave:()=>M(null),"aria-label":v.has(J.id)?"Expand group":"Collapse group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1",children:[e.jsx("span",{className:"typography-micro font-medium text-muted-foreground truncate group-hover/header:text-foreground",children:J.label}),!n&&e.jsx("span",{role:"button",tabIndex:0,className:O("inline-flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground"),"aria-label":"Create session in this group",onClick:ke=>{ke.stopPropagation(),st(J.directory)},onKeyDown:ke=>{(ke.key==="Enter"||ke.key===" ")&&(ke.stopPropagation(),st(J.directory))},children:e.jsx(Ht,{className:"h-4.5 w-4.5"})})]})}),v.has(J.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const ke=k.has(J.id),re=n?10:7,le=J.sessions.length,Ae=ke?J.sessions:J.sessions.slice(0,re),$e=le-Ae.length;return e.jsxs(e.Fragment,{children:[Ae.map(Ue=>mt(Ue,0,J.directory)),le===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,$e>0&&!ke?e.jsxs("button",{type:"button",onClick:()=>xt(J.id),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 ",$e," more ",$e===1?"session":"sessions"]}):null,ke&&le>re?e.jsx("button",{type:"button",onClick:()=>xt(J.id),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]})})()})]},J.id))})]})};function dt({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:O("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),...t})}function Ms({...s}){return e.jsx(Am,{"data-slot":"select",...s})}function gr({...s}){return e.jsx(Lm,{"data-slot":"select-group",...s})}function xo({...s}){return e.jsx(Tm,{"data-slot":"select-value",...s})}function Ds({className:s,size:r="default",children:t,...n}){return e.jsxs(Em,{"data-slot":"select-trigger","data-size":r,className:O("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-[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(Im,{asChild:!0,children:e.jsx(kt,{className:"size-4 opacity-50"})})]})}function As({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx(Fm,{children:e.jsx(Pm,{"data-slot":"select-content",className:O("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(tt,{as:Rm,outerClassName:O("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:O("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 xr({className:s,...r}){return e.jsx(Om,{"data-slot":"select-label",className:O("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function Ft({className:s,children:r,...t}){return e.jsxs($m,{"data-slot":"select-item",className:O("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(_m,{children:e.jsx(Mt,{className:"size-4"})})}),e.jsx(Bm,{children:r})]})}function yo({className:s,...r}){return e.jsx(zm,{"data-slot":"select-separator",className:O("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}function yi({tabs:s,value:r,onValueChange:t,className:n,isInteractive:o=!0,animate:a=!0}){const i=l.useRef(null),c=l.useRef(null),d=l.useCallback(()=>{const u=i.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 l.useLayoutEffect(()=>{d()},[d,r,s.length]),l.useEffect(()=>{const u=i.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:O("relative isolate w-full",n),children:[e.jsx("div",{ref:i,"aria-hidden":!0,className:O("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:O("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:O("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const Hd=()=>{const[s,r]=Se.useState(!1);Se.useEffect(()=>{r(Xt())},[]);const t=Se.useCallback(async a=>s?await Qf(a):{success:!0,path:a},[s]),n=Se.useCallback(async a=>s?await Jf(a):{success:!0},[s]),o=Se.useCallback(async a=>s?await Zf(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},Al=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=l.useMemo(()=>Xt(),[]),[p,h]=l.useState([]),[y,g]=l.useState(new Set),[w,x]=l.useState(!0),[v,S]=l.useState(!1),[N,j]=l.useState(""),[k,F]=l.useState(new Set),[I,M]=l.useState(null),[b,C]=l.useState(""),[A,P]=l.useState(!0),L=l.useRef(null),{requestAccess:$,startAccessing:q,isDesktop:ee}=Hd(),ce=l.useRef(c),_=l.useCallback(K=>{if(!K)return K;if(K==="/"||K.length===0)return"/";let G=K;for(;G.length>1&&G.endsWith("/");)G=G.slice(0,-1);return G.length===0?"/":G},[]),z=l.useMemo(()=>{if(!N)return null;const K=N.replace(/\\/g,"/");return _(K)},[N,_]),D=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const K=d.replace(/\\/g,"/"),G=_(K);if(G&&G!=="/")return G}return z&&z!=="/"?z:null},[d,z,_]),H=l.useMemo(()=>typeof u=="boolean"?!!(u&&D):!!D,[u,D]);l.useEffect(()=>{H||(x(!0),h([]))},[H]);const X=l.useCallback(K=>{if(!K||!H||!D)return!1;const G=K.replace(/\\/g,"/"),T=_(G)??G;if(T===D)return!0;const Y=`${D}/`;return T.startsWith(Y)},[H,D,_]),he=async K=>{if(H){if(a==="deferred"){r(K);return}if(ee){const G=await $(K);G.success&&G.path?(await q(G.path),r(G.path)):(console.error("Failed to get directory access:",G.error),r(K))}else r(K)}};l.useEffect(()=>{let K=!1;const G=E=>{if(!E)return!1;const B=_(E.replace(/\\/g,"/"));return!B||B==="/"?!1:(j(typeof B=="string"?B:E.replace(/\\/g,"/")),!0)};return d&&G(d)||(async()=>{try{const E=await Le.getFilesystemHome();if(!K&&G(E))return}catch(E){console.warn("Failed to resolve filesystem home directory:",E)}try{const E=await Le.getSystemInfo();if(!K&&G(E?.homeDirectory))return}catch(E){console.warn("Failed to resolve home directory from system info:",E)}})(),()=>{K=!0}},[d,_]),l.useEffect(()=>{let K=!1;const G=B=>{if(K)return;const U=B.filter(be=>typeof be=="string"&&be.length>0).map(be=>{const Q=be.replace(/\\/g,"/");return _(Q)??Q});F(new Set(U))},T=()=>{try{const B=localStorage.getItem("pinnedDirectories");if(!B)return;const U=JSON.parse(B);Array.isArray(U)&&G(U)}catch(B){console.warn("Failed to load pinned directories from local storage:",B)}},Y=async()=>{try{let B=[];if(f){const U=await Qr();B=Array.isArray(U?.pinnedDirectories)?U.pinnedDirectories:[]}else{const U=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(U.ok){const be=await U.json();B=Array.isArray(be?.pinnedDirectories)?be.pinnedDirectories:[]}}if(K)return;G(B)}catch(B){console.warn("Failed to load pinned directories:",B)}};T();const E=B=>{const U=B.detail;U&&Array.isArray(U.pinnedDirectories)&&G(U.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",E),Y(),()=>{K=!0,window.removeEventListener("openchamber:settings-synced",E)}},[f,_]);const ae=l.useRef(!0);l.useEffect(()=>{if(ae.current){ae.current=!1;return}const K={pinnedDirectories:Array.from(k)};es(K)},[k]),l.useEffect(()=>{D&&F(K=>{const G=Array.from(K).map(T=>_(T.replace(/\\/g,"/"))??T).filter(T=>X(T));return new Set(G)})},[D,X,_]),l.useEffect(()=>{ce.current!==c&&(ce.current=c,g(new Set))},[c]);const fe=K=>{F(G=>{if(!X(K))return G;const T=_(K.replace(/\\/g,"/"))??K.replace(/\\/g,"/"),Y=new Set(G);return Y.has(T)?Y.delete(T):Y.add(T),Y})},je=l.useMemo(()=>Array.from(k).map(K=>_(K.replace(/\\/g,"/"))??K).filter(K=>X(K)).map(K=>({path:K,name:K.split("/").pop()||K})).sort((K,G)=>K.name.localeCompare(G.name)),[k,X,_]),W=l.useCallback(async K=>{const G=U=>c||!U.startsWith("."),T=D;if(!H||!T)return[];const Y=K&&K.length>0?K:T,E=Y?Y.replace(/\\/g,"/"):null,B=E?_(E)??E:null;if(B){const U=`${T}/`;if(!(B===T||B.startsWith(U)))return[]}try{return(await Le.listLocalDirectory(K)).filter(be=>{if(!be.isDirectory||!G(be.name))return!1;const Q=be.path.replace(/\\/g,"/"),xe=_(Q)??Q,He=xe===T?T:`${T}/`;return xe===T||xe.startsWith(He)}).map(be=>({name:be.name,path:be.path.replace(/\\/g,"/"),isDirectory:!0})).sort((be,Q)=>be.name.localeCompare(Q.name))}catch{try{const be=await Le.getApiClient().file.list({query:{path:".",directory:K}});return be.data?be.data.filter(Q=>{if(Q.type!=="directory"||!Q.name||!G(Q.name))return!1;const xe=String(Q.absolute||Q.path||Q.name).replace(/\\/g,"/"),He=_(xe)??xe,Ke=He===T?T:`${T}/`;return He===T||He.startsWith(Ke)}).map(Q=>({name:Q.name||"",path:String(Q.absolute||Q.path||Q.name).replace(/\\/g,"/"),isDirectory:!0})).filter(Q=>Q.name!=="").sort((Q,xe)=>Q.name.localeCompare(xe.name)):[]}catch{return[]}}},[c,D,_,H]),te=l.useCallback(async()=>{if(!H||!D){x(!0),h([]);return}x(!0);try{const K=await W(D);h(K)}catch{}finally{x(!1)}},[H,D,W]);l.useEffect(()=>{H&&(n==="inline"||v)&&te()},[n,v,H,te]);const oe=async K=>{if(!H)return;const G=y.has(K.path),T=new Set(y);if(G){T.delete(K.path),g(T);return}T.add(K.path),g(T);const Y=await W(K.path),E=B=>B.map(U=>U.path===K.path?{...U,children:Y}:U.children?{...U,children:E(U.children)}:U);h(B=>E(B))};l.useEffect(()=>{I&&L.current&&(L.current.focus(),L.current.select())},[I]);const V=(K,G=[])=>{const T="new_directory",Y=G.map(be=>be.name);if(!Y.includes(T))return T;let E=1;const B=new RegExp(`^${T}(\\d+)$`);for(const be of Y){const Q=be.match(B);if(Q){const xe=parseInt(Q[1],10);xe>E&&(E=xe)}}let U=2;for(;Y.includes(`${T}${U}`);)U++;return`${T}${Math.max(U,E+1)}`},ue=async K=>{if(H){if(y.has(K.path)){const G=V(K.path,K.children);C(G)}else{const G=new Set(y);if(G.add(K.path),g(G),K.children){const T=V(K.path,K.children);C(T)}else{const T=await W(K.path),Y=B=>B.map(U=>U.path===K.path?{...U,children:T}:U.children?{...U,children:Y(U.children)}:U);h(B=>Y(B));const E=V(K.path,T);C(E)}}M(K.path)}},ge=async()=>{if(!I||!H)return;const K=b.trim()||"new_directory",G=`${I}/${K}`;try{await Le.createDirectory(G);const T=await W(I),Y=E=>E.map(B=>B.path===I?{...B,children:T}:B.children?{...B,children:Y(B.children)}:B);h(E=>Y(E)),M(null),C("")}catch(T){console.error("Failed to create directory:",T)}},ie=()=>{M(null),C("")},De=(K,G=0)=>{const T=y.has(K.path),Y=K.isDirectory,E=k.has(K.path),B=s===K.path,U=n==="inline",be=e.jsxs(e.Fragment,{children:[Y&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),oe(K)},className:"p-0.5 hover:bg-accent rounded",children:T?e.jsx(kt,{className:"h-3 w-3"}):e.jsx(Ss,{className:"h-3 w-3"})}),!Y&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:Q=>{Q.stopPropagation(),he(K.path),n==="dropdown"&&a==="immediate"&&S(!1)},onDoubleClick:Q=>{Q.stopPropagation(),i&&i(K.path)},className:O("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",U&&B?"text-primary":"text-foreground"),children:[T?e.jsx(ms,{className:O("h-3.5 w-3.5 text-muted-foreground",U&&B&&"text-primary")}):e.jsx(ms,{className:O("h-3.5 w-3.5 text-muted-foreground",U&&B&&"text-primary")}),e.jsx("span",{className:O("typography-ui-label font-medium truncate",U&&B?"text-primary":"text-foreground"),children:K.name})]}),e.jsx("button",{onClick:Q=>{Q.stopPropagation(),ue(K)},className:O("p-1 hover:bg-accent rounded transition-opacity",m?"opacity-70":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:Q=>{Q.stopPropagation(),fe(K.path)},className:O("p-1 hover:bg-accent rounded transition-opacity",m?"opacity-70":"opacity-0 group-hover:opacity-100"),title:E?"Unpin directory":"Pin directory",children:E?e.jsx($o,{className:"h-3 w-3 text-primary"}):e.jsx(Hm,{className:"h-3 w-3 text-muted-foreground"})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:O("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",B?"text-primary":"text-foreground"),style:{paddingLeft:`${G*12+8}px`},children:be}),T&&e.jsxs(e.Fragment,{children:[I===K.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(G+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ms,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{ref:L,value:b,onChange:Q=>C(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"?(Q.preventDefault(),Q.stopPropagation(),ge()):Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),ie())},onBlur:ge,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),ge()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Mt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),ie()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground"})})]}),K.children&&K.children.map(Q=>De(Q,G+1))]})]},K.path):e.jsxs("div",{children:[e.jsxs(St,{className:O("flex items-center gap-1 cursor-pointer group",s===K.path&&"bg-accent"),style:{paddingLeft:`${G*12+8}px`},onSelect:Q=>{Q.preventDefault()},children:[Y&&e.jsx("button",{onClick:Q=>{Q.stopPropagation(),oe(K)},className:"p-0.5 hover:bg-accent rounded",children:T?e.jsx(kt,{className:"h-3 w-3"}):e.jsx(Ss,{className:"h-3 w-3"})}),!Y&&e.jsx("div",{className:"w-4"}),be]}),T&&e.jsxs("div",{children:[I===K.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(G+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ms,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{ref:L,value:b,onChange:Q=>C(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"?(Q.preventDefault(),Q.stopPropagation(),ge()):Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),ie())},onBlur:ge,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),ge()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Mt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),ie()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground"})})]}),K.children&&K.children.map(Q=>De(Q,G+1))]})]},K.path)},Ce=(K,G)=>{if(n==="inline"){const T=s===G;return e.jsxs("div",{className:O("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>he(G),onDoubleClick:Y=>{Y.stopPropagation(),i&&i(G)},className:O("flex flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",T?"text-primary":"text-foreground"),children:[e.jsx(ms,{className:O("h-3.5 w-3.5 text-muted-foreground",T&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:O("typography-ui-label font-medium truncate",T?"text-primary":"text-foreground"),children:K}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:ls(G,N)})]})]}),e.jsx("button",{onClick:()=>fe(G),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx($o,{className:"h-3 w-3 text-primary"})})]},G)}return e.jsxs(St,{onSelect:T=>{T.preventDefault(),he(G),a==="immediate"&&S(!1)},className:O("flex items-start gap-2 cursor-pointer group py-2",s===G&&"bg-accent"),children:[e.jsx(ms,{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:K}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:ls(G,N)})]}),e.jsx("button",{onClick:T=>{T.stopPropagation(),T.preventDefault(),fe(G)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx($o,{className:"h-3 w-3 text-primary"})})]},G)},Ie=e.jsx(e.Fragment,{children:H?e.jsxs(e.Fragment,{children:[je.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>P(K=>!K),className:"flex w-full items-center gap-1.5 px-2 py-1.5 typography-meta font-semibold text-muted-foreground hover:bg-accent/30 rounded transition-colors",children:[A?e.jsx(kt,{className:"h-3.5 w-3.5"}):e.jsx(Ss,{className:"h-3.5 w-3.5"}),e.jsx(_r,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/70",children:je.length})]}),A&&je.map(({name:K,path:G})=>Ce(K,G)),n==="dropdown"&&e.jsx(Os,{}),n==="inline"&&A&&e.jsx("div",{className:"mx-2 my-1.5 border-t border-border/30"})]}),e.jsxs("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground flex items-center gap-1.5",children:[e.jsx(ms,{className:"h-3.5 w-3.5"}),"Browse"]}),w?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):p.map(K=>De(K)),!w&&p.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:O("overflow-hidden rounded-xl border border-border/40 bg-sidebar/70",o),children:e.jsx(tt,{outerClassName:"max-h-full",className:"w-full",children:Ie})}):e.jsxs(Gt,{open:v,onOpenChange:S,children:[e.jsx(Kt,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",className:O("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(ms,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:ls(s,N)})]}),e.jsx(kt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Yt,{align:"start",className:"w-[350px]",children:e.jsx(tt,{outerClassName:"h-full",className:"w-full",children:Ie})})]})},El="directoryTreeShowHidden",Bg=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=yt(),[i,c]=l.useState(null),[d,u]=l.useState(""),[m,f]=l.useState(!1),[p,h]=l.useState(!1),[y,g]=l.useState(()=>{if(typeof window>"u")return!1;try{const z=window.localStorage.getItem(El);if(z==="true")return!0;if(z==="false")return!1}catch{}return!1}),{isDesktop:w,requestAccess:x,startAccessing:v}=Hd(),{isMobile:S}=Nt(),N=l.useCallback(z=>z?ls(z,n):"",[n]);l.useEffect(()=>{if(s){f(!1),h(!1);const z=t||n||"";c(z),u(N(z))}},[s,t,n,N]),l.useEffect(()=>{!s||m||i||n&&a&&(c(n),f(!0),u("~"))},[s,m,i,n,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(El,y?"true":"false")}catch{}},[y]);const j=l.useCallback(()=>{r(!1)},[r]),k=l.useCallback(async z=>{if(!(!z||p)){if(z===t){j();return}h(!0);try{let D=z;if(w){const H=await x(z);if(!H.success){se.error("Unable to access directory",{description:H.error||"Desktop denied directory access."});return}D=H.path??z;const X=await v(D);if(!X.success){se.error("Failed to open directory",{description:X.error||"Desktop could not grant file access."});return}}o(D),j()}catch(D){se.error("Failed to select directory",{description:D instanceof Error?D.message:"Unknown error occurred."})}finally{h(!1)}}},[t,j,w,x,o,v,p]),F=l.useCallback(async()=>{const z=d.trim()||i;z&&await k(z)},[k,d,i]),I=l.useCallback(z=>{c(z),f(!0),u(N(z))},[N]),M=l.useCallback(async z=>{c(z),f(!0),u(N(z)),await k(z)},[k,N]),b=l.useCallback(z=>{const D=z.target.value;if(u(D),f(!0),D.startsWith("/")||D.startsWith("~")){const H=D.startsWith("~")&&n?D.replace(/^~/,n):D;c(H)}},[n]),C=l.useCallback(z=>{z.key==="Enter"&&(z.preventDefault(),F())},[F]),A=l.useCallback(()=>{g(z=>!z)},[]),P=e.jsxs(ds,{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(us,{children:"Select project directory"}),e.jsx(Is,{className:"hidden sm:block",children:"Choose the working directory for sessions and OpenCode operations."})]}),L=e.jsx(dt,{value:d,onChange:b,onKeyDown:C,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),$=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 sm:p-2 sm:flex-none",children:e.jsx(Al,{variant:"inline",currentPath:i??t,onSelectPath:I,onDoubleClickPath:M,className:"h-full sm:min-h-[280px] sm:h-[380px]",selectionBehavior:"deferred",showHidden:y,rootDirectory:a?n:null,isRootReady:a})}),q=e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground",children:[y?e.jsx(Xa,{className:"h-4 w-4 text-primary"}):e.jsx(Qa,{className:"h-4 w-4"}),"Show hidden"]}),ee=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:L}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:q}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 overflow-hidden",children:e.jsx(Al,{variant:"inline",currentPath:i??t,onSelectPath:I,onDoubleClickPath:M,className:"h-full",selectionBehavior:"deferred",showHidden:y,rootDirectory:a?n:null,isRootReady:a,alwaysShowActions:!0})})]}),ce=e.jsxs(tt,{outerClassName:"flex-1 min-h-0 overflow-hidden",className:"directory-dialog-body sm:px-0 sm:pb-0 flex flex-col gap-3",children:[L,e.jsx("div",{className:"flex items-center justify-end",children:q}),$]}),_=()=>e.jsxs(e.Fragment,{children:[e.jsx(ve,{variant:"ghost",onClick:j,disabled:p,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(ve,{onClick:F,disabled:p||!m||!i&&!d.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:p?"Applying...":"Open Directory"})]});return S?e.jsx(cs,{open:s,onClose:()=>r(!1),title:"Select 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:_()}),children:ee}):e.jsx(os,{open:s,onOpenChange:r,children:e.jsxs(as,{className:O("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:z=>{z.preventDefault()},children:[P,ce,e.jsx(Bs,{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-3",children:_()})]})})},bo=".openchamber",sa=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,zg=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Ud=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Wd=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ln=(s,r)=>{const t=Wd(s),n=Ud(r),o=!t||t==="/"?`/${bo}`:`${t}/${bo}`;return n?`${o}/${n}`:o},Hg=()=>{const[s,r]=l.useState(!1),[t,n]=l.useState(!1),[o,a]=l.useState("new"),[i,c]=l.useState(""),[d,u]=l.useState(""),[m,f]=l.useState("HEAD"),[p,h]=l.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[y,g]=l.useState(!1),[w,x]=l.useState([]),[v,S]=l.useState(!1),[N,j]=l.useState(null),[k,F]=l.useState(!1),[I,M]=l.useState(null),[b,C]=l.useState(!1),A=l.useRef(new Set),[P,L]=l.useState(null),[$,q]=l.useState([]),[ee,ce]=l.useState(!1),[_,z]=l.useState(!1),{sessions:D,createSession:H,deleteSession:X,deleteSessions:he,loadSessions:ae,initializeNewOpenChamberSession:fe,setWorktreeMetadata:je,setSessionDirectory:W,getWorktreeMetadata:te,isLoading:oe}=ye(),{currentDirectory:V,homeDirectory:ue,hasPersistedDirectory:ge,isHomeReady:ie}=yt(),{agents:De}=lt(),{isSessionCreateDialogOpen:Ce,setSessionCreateDialogOpen:Ie}=Fe(),{isMobile:K,isTablet:G,hasTouchInput:T}=Nt(),Y=K||G||T,E=l.useMemo(()=>Wd(V),[V]),B=l.useMemo(()=>zg(i),[i]),U=l.useMemo(()=>o==="existing"?d.trim():B,[d,B,o]),be=l.useMemo(()=>Ud(U),[U]),Q=l.useMemo(()=>!E||!be?"":Ln(E,be),[E,be]),xe=I===!0,He=l.useMemo(()=>{const me=p.find(de=>de.value===m);return me?me.label:m==="HEAD"?"Current (HEAD)":m},[p,m]),Ke=l.useMemo(()=>(P?.worktree?.status?.isDirty??!1)||$.some(me=>me.metadata.status?.isDirty),[P?.worktree?.status?.isDirty,$]),ze=l.useMemo(()=>{const me=P?.worktree;return me&&typeof me.branch=="string"&&me.branch.trim().length>0?!0:$.length>0&&$.every(({metadata:de})=>typeof de.branch=="string"&&de.branch.trim().length>0)},[P?.worktree,$]),st=P?.mode==="worktree",it=st,at=_||!st||!ze;l.useEffect(()=>{E&&(A.current.has(E)||_p(E).then(()=>A.current.add(E)).catch(me=>{console.warn("Failed to ensure .openchamber directory is ignored:",me),A.current.delete(E)}))},[E]),l.useEffect(()=>{ae()},[ae,V]),l.useEffect(()=>{!t&&ie&&!ge&&(r(!0),n(!0))},[ge,t,ie]),l.useEffect(()=>{if(!Ce){a("new"),c(""),u(""),f("HEAD"),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),g(!1),x([]),j(null),S(!1),F(!1),M(null),C(!1);return}if(!E){a("new"),u(""),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),f("HEAD"),x([]),M(null),F(!1);return}let me=!1;return S(!0),g(!0),F(!0),j(null),(async()=>{try{const de=await Zr(E);if(me)return;if(M(de),!de)a("new"),u(""),h([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),f("HEAD"),x([]),j(null);else{const[we,Me]=await Promise.all([lo(E),fd(E).catch(()=>null)]);if(me)return;const Pe=[],qe=Me?.current?`Current (HEAD: ${Me.current})`:"Current (HEAD)";if(Pe.push({value:"HEAD",label:qe,group:"special"}),Me){const Ye=Me.all.filter(_e=>!_e.startsWith("remotes/")).sort((_e,Ve)=>_e.localeCompare(Ve)),wt=Me.current&&!Me.current.startsWith("remotes/")?Me.current:Ye[0]??"";u(_e=>{const Ve=_e.trim();return Ve&&Ye.includes(Ve)?Ve:wt}),Ye.forEach(_e=>{Pe.push({value:_e,label:_e,group:"local"})}),Me.all.filter(_e=>_e.startsWith("remotes/")).map(_e=>_e.replace(/^remotes\//,"")).sort((_e,Ve)=>_e.localeCompare(Ve)).forEach(_e=>{Pe.push({value:_e,label:_e,group:"remote"})})}h(Pe),f(Ye=>Pe.some(wt=>wt.value===Ye)?Ye:"HEAD");const bt=we.map(Ye=>co(E,Ye)),Ct=`${Ln(E,"")}/`,ft=bt.filter(Ye=>Ye.path.startsWith(Ct));x(ft)}}catch(de){if(me)return;const we=de instanceof Error?de.message:"Failed to load worktrees";j(we)}finally{me||(S(!1),g(!1),F(!1))}})(),()=>{me=!0}},[Ce,E]);const ct=l.useCallback(me=>{L({sessions:me.sessions,dateLabel:me.dateLabel,mode:me.mode??"session",worktree:me.worktree??null})},[]),ut=l.useCallback(()=>{L(null),q([]),ce(!1),z(!1)},[]);l.useEffect(()=>hr.onDeleteRequest(me=>{ct(me)}),[ct]),l.useEffect(()=>hr.onDirectoryRequest(()=>{r(!0)}),[]),l.useEffect(()=>hr.onCreateRequest(()=>{a("new"),c(""),u(""),f("HEAD"),j(null),Ie(!0)}),[Ie]),l.useEffect(()=>{if(!P){q([]),ce(!1);return}const me=P.sessions.map(we=>{const Me=te(we.id);return Me?{session:we,metadata:Me}:null}).filter(we=>!!we);if(q(me),ce(!1),me.length===0)return;let de=!1;return(async()=>{const we=await Promise.all(me.map(async({metadata:Me})=>{if(Me.status&&typeof Me.status.isDirty=="boolean")return Me.status;try{return await Ia(Me.path)}catch{return Me.status}})).catch(Me=>(console.warn("Failed to inspect worktree status before deletion:",Me),me.map(({metadata:Pe})=>Pe.status)));de||!Array.isArray(we)||q(Me=>Me.map((Pe,qe)=>({session:Pe.session,metadata:{...Pe.metadata,status:we[qe]??Pe.metadata.status}})))})(),()=>{de=!0}},[P,te]),l.useEffect(()=>{ze||ce(!1)},[ze]);const pt=l.useCallback(me=>{c(me),j(null)},[]),vt=l.useCallback(async()=>{if(!(!E||!I))try{const de=(await lo(E)).map(qe=>co(E,qe)),Me=`${Ln(E,"")}/`,Pe=de.filter(qe=>qe.path.startsWith(Me));x(Pe)}catch{}},[E,I]),xt=l.useRef(null);l.useEffect(()=>{xt.current?.mode==="worktree"&&!P&&vt(),xt.current=P},[P,vt]);const mt=l.useCallback(()=>{if(!E){const Me="Select a project directory first.";return j(Me),se.error(Me),!1}const me=U,de=be;if(!me){const Me=o==="existing"?"Select an existing branch for the new worktree.":"Provide a branch name for the new worktree.";return j(Me),se.error(Me),!1}if(!de){const Me="Provide a branch name that can be used as a folder.";return j(Me),se.error(Me),!1}const we=Ln(E,de);if(w.some(Me=>Me.path===we)){const Me="A worktree with this folder already exists.";return j(Me),se.error(Me),!1}return j(null),!0},[E,o,U,be,w]),J=async()=>{if(b||oe||!mt())return;C(!0),j(null);let me=null;try{const de=U,we=be,Me=o==="new",qe=await gd({projectDirectory:E,worktreeSlug:we,branch:de,createBranch:Me,startPoint:Me&&m&&m!=="HEAD"?m:void 0});me=qe;const bt=await Ia(qe.path).catch(()=>{}),Et=bt?{...qe,status:bt}:qe,Ct=await H(void 0,qe.path);if(!Ct){await Qi({projectDirectory:E,path:qe.path,force:!0}).catch(()=>{});const ft="Failed to create session for worktree";j(ft),se.error(ft);return}fe(Ct.id,De),W(Ct.id,qe.path),je(Ct.id,Et),await vt(),c(""),u(""),se.success("Worktree created")}catch(de){me&&await Qi({projectDirectory:E,path:me.path,force:!0}).catch(()=>{});const we=de instanceof Error?de.message:"Failed to create worktree";j(we),se.error(we)}finally{C(!1)}},ke=l.useCallback(me=>{const de=D.filter(we=>te(we.id)?.path===me.path);hr.requestDelete({sessions:de,mode:"worktree",worktree:me})},[D,te]),re=l.useCallback(async()=>{if(P){z(!0);try{const me=it,de=me&&ee;if(P.sessions.length===1){const we=P.sessions[0];if(!await X(we.id,{archiveWorktree:me,deleteRemoteBranch:de})){se.error("Failed to delete session"),z(!1);return}const Pe=me?de?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;se.success("Session deleted",{description:sa(Pe)})}else{const we=P.sessions.map(qe=>qe.id),{deletedIds:Me,failedIds:Pe}=await he(we,{archiveWorktree:me,deleteRemoteBranch:de});if(Me.length>0){const qe=me?de?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,Et=[Pe.length>0?`${Pe.length} session${Pe.length===1?"":"s"} could not be deleted.`:P.dateLabel?`Removed all sessions from ${P.dateLabel}.`:void 0,qe].filter(Boolean).join(" ");se.success(`Deleted ${Me.length} session${Me.length===1?"":"s"}`,{description:sa(Et||void 0)})}if(Pe.length>0&&(se.error(`Failed to delete ${Pe.length} session${Pe.length===1?"":"s"}`,{description:sa("Please try again in a moment.")}),Me.length===0)){z(!1);return}}ut()}finally{z(!1)}}},[P,ee,X,he,ut,it]),le=e.jsxs("div",{className:"space-y-4 w-full min-w-0",children:[e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Create worktree"}),e.jsxs("p",{className:"typography-meta text-muted-foreground/80",children:["Branch-specific directory under ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:bo}),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(yi,{tabs:[{value:"new",label:"New branch"},{value:"existing",label:"Existing branch"}],value:o,onValueChange:me=>{if(a(me),j(null),me==="existing"&&!d){const de=p.find(we=>we.group==="local")?.value??"";de&&u(de)}},animate:!1}),o==="new"?e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-base-branch-select",children:"Base branch"}),e.jsxs(Ms,{value:m,onValueChange:f,disabled:!xe||k||y,children:[e.jsx(Ds,{id:"worktree-base-branch-select",size:"lg",className:"w-full typography-meta text-foreground",children:e.jsx(xo,{placeholder:y?"Loading branches…":"Select a branch"})}),e.jsxs(As,{children:[e.jsxs(gr,{children:[e.jsx(xr,{children:"Default"}),p.filter(me=>me.group==="special").map(me=>e.jsx(Ft,{value:me.value,children:me.label},me.value))]}),p.some(me=>me.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(yo,{}),e.jsxs(gr,{children:[e.jsx(xr,{children:"Local branches"}),p.filter(me=>me.group==="local").map(me=>e.jsx(Ft,{value:me.value,children:me.label},me.value))]})]}),p.some(me=>me.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(yo,{}),e.jsxs(gr,{children:[e.jsx(xr,{children:"Remote branches"}),p.filter(me=>me.group==="remote").map(me=>e.jsx(Ft,{value:me.value,children:me.label},me.value))]})]})]})]}),e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-branch-input",children:"New branch name"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(dt,{id:"worktree-branch-input",value:i,onChange:me=>pt(me.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!xe||k,onKeyDown:me=>{me.key==="Enter"&&!b&&J()}}),e.jsx(ve,{onClick:J,disabled:b||oe||!xe||!U,className:"h-8",children:b?"Creating…":"Create"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-existing-branch-select",children:"Existing branch"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Ms,{value:d,onValueChange:me=>{u(me),j(null)},disabled:!xe||k||y||!p.some(me=>me.group==="local"),children:[e.jsx(Ds,{id:"worktree-existing-branch-select",size:"lg",className:"flex-1 typography-meta text-foreground",children:e.jsx(xo,{placeholder:y?"Loading branches…":"Select a branch"})}),e.jsx(As,{children:e.jsxs(gr,{children:[e.jsx(xr,{children:"Local branches"}),p.filter(me=>me.group==="local").map(me=>e.jsx(Ft,{value:me.value,children:me.label},me.value))]})})]}),e.jsx(ve,{onClick:J,disabled:b||oe||!xe||!U,className:"h-8",children:b?"Creating…":"Create"})]}),!y&&!p.some(me=>me.group==="local")?e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"No local branches found. Fetch or create a branch first."}):null]}),U?e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:o==="existing"?e.jsxs(e.Fragment,{children:["Uses branch"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:U})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:ls(Q,ue)})]}):e.jsxs(e.Fragment,{children:["Creates branch"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:U})," ","from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:He})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:ls(Q,ue)})]})}):null]}),N&&e.jsx("p",{className:"typography-meta text-destructive",children:N}),!xe&&!k&&e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Current directory is not a Git repository."})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3 overflow-hidden min-w-0",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Existing worktrees"})}),v?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading worktrees…"}):w.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 text-muted-foreground",children:bo}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:w.map(me=>{const de=me.relativePath||(me.path.startsWith(E+"/")?me.path.slice(E.length+1):me.path);return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/30 bg-sidebar-accent/20 px-3 py-2 min-w-0",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-meta font-medium text-foreground",children:me.label||me.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:de})]}),e.jsx("button",{type:"button",onClick:()=>ke(me),className:"flex-shrink-0 flex h-7 w-7 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":`Delete worktree ${me.branch||me.label}`,children:e.jsx(Es,{className:"h-4 w-4"})})]},me.path)})})]})]}),Ae=e.jsx(ve,{variant:"ghost",onClick:()=>Ie(!1),disabled:b,children:"Close"}),$e=P?.worktree??$[0]?.metadata??null,Ue=P?P.mode==="worktree"?`This removes the selected worktree and ${P.sessions.length===1?"1 linked session":`${P.sessions.length} linked sessions`}.`:`This action permanently removes ${P.sessions.length===1?"1 session":`${P.sessions.length} sessions`}${P.dateLabel?` from ${P.dateLabel}`:""}.`:"",We=P?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsxs("ul",{className:"space-y-0.5",children:[P.sessions.slice(0,3).map(me=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:me.title||"Untitled Session"},me.id)),P.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",P.sessions.length-3," more"]})]})}),st?e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),$e?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:$e.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:$e?ls($e.path,ue):"Worktree path unavailable."}),Ke&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),ze?e.jsxs("button",{type:"button",onClick:()=>{at||ce(me=>!me)},disabled:at,className:O("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",at?"cursor-not-allowed opacity-60":"hover:bg-sidebar/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[e.jsx("span",{className:"mt-0.5 flex size-5 items-center justify-center text-muted-foreground",children:ee?e.jsx(Xa,{className:"size-4 text-primary"}):e.jsx(Qa,{className:"size-4"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Delete remote branch"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:ee?"Remote branch on origin will also be removed.":"Keep the remote branch intact."})]})]}):e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Remote branch information unavailable for this worktree."})]}):e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,Ze=e.jsxs(e.Fragment,{children:[e.jsx(ve,{variant:"ghost",onClick:ut,disabled:_,children:"Cancel"}),e.jsx(ve,{variant:"destructive",onClick:re,disabled:_,children:_?"Deleting…":st?"Delete worktree":P?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[Y?e.jsx(cs,{open:Ce,onClose:()=>Ie(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Ae}),children:e.jsx("div",{className:"space-y-2 pb-2",children:le})}):e.jsx(os,{open:Ce,onOpenChange:Ie,children:e.jsxs(as,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2 overflow-hidden",children:[e.jsx(ds,{children:e.jsx(us,{children:"Worktree Manager"})}),le,e.jsx(Bs,{className:"mt-2 gap-2 pt-1 pb-1",children:Ae})]})}),Y?e.jsx(cs,{open:!!P,onClose:()=>{_||ut()},title:P?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Ze}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[Ue&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Ue}),We]})}):e.jsx(os,{open:!!P,onOpenChange:me=>{if(!me){if(_)return;ut()}},children:e.jsxs(as,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(ds,{children:[e.jsx(us,{children:P?.sessions.length===1?"Delete session":"Delete sessions"}),Ue&&e.jsx(Is,{children:Ue})]}),We,e.jsx(Bs,{className:"mt-2 gap-2 pt-1 pb-1",children:Ze})]})}),e.jsx(Bg,{open:s,onOpenChange:r})]})};function Ug(){return new Worker(Um,{type:"module"})}const Wg=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Vg(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 Il(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const qg=({children:s})=>{const r=Vm(),t=At(c=>c.activeDirectory),n=At(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=At(c=>t?c.directories.get(t)?.diffCache.size??0:0),a=Se.useRef(!1),i=Se.useRef(new Map);return Se.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=ja(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Se.useEffect(()=>{if(!r||!t||!n||o===0)return;const c=At.getState().directories.get(t);if(!c||c.diffCache.size===0||(i.current.get(t)??0)>=c.lastStatusChange)return;i.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,x]=f[p];p+=1,Cr(w);const v=Vg(w,x.original,x.modified),S={name:w,contents:x.original,cacheKey:`old-${v}`},N={name:w,contents:x.modified,cacheKey:`new-${v}`},j=ja(S,N),k={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(k,j)}p<f.length&&(m=Il(h))};return h(void 0),p<f.length&&(m=Il(h)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},Gg=({children:s})=>{const t=Eo()?.currentTheme?.metadata?.variant==="dark";Td();const n=Se.useMemo(()=>({theme:{dark:qr.dark,light:qr.light},themeType:t?"dark":"light",langs:Wg}),[t]);return e.jsx(Wm,{poolOptions:{workerFactory:Ug,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(qg,{children:s})})},Cs=Se.forwardRef(({className:s,...r},t)=>e.jsx(tt,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:O("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),...r}));Cs.displayName="Textarea";const Kg="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",Yg=Object.assign({"../assets/provider-logos/gocode.svg":Kg}),La=new Map;for(const[s,r]of Object.entries(Yg)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&La.set(t[1].toLowerCase(),r)}function Vd(s){const r=s?.toLowerCase()??null,t=r?La.has(r):!1,n=r?La.get(r)??null:null,[o,a]=Se.useState(t?"local":"remote");Se.useEffect(()=>{a(t?"local":"remote")},[t,r]);const i=Se.useCallback(()=>{a(c=>c==="local"&&t?"remote":"none")},[t]);return r?o==="local"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const qt=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=Vd(s),c=l.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:O("dark:invert",t),onError:c})},Oa=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),Xg=(s,r)=>{const t=Oa(s),n=Oa(r);return`${t}-${n}`.substring(0,60)},Tl=(s,r)=>`${s}/${r}`,Qg=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Jg=()=>yt.getState().currentDirectory??null,ra=It()(Pt(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:i}=r;if(!t)return s({error:"Group name is required"}),null;if(!n)return s({error:"Prompt is required"}),null;if(o.length<2)return s({error:"Select at least 2 models"}),null;if(o.length>5)return s({error:"Maximum 5 models allowed"}),null;s({isLoading:!0,error:null});try{const c=Jg();if(!c)return s({error:"No directory selected",isLoading:!1}),null;if(!await Zr(c))return s({error:"Not in a git repository",isLoading:!1}),null;const u=Oa(t),m=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",f=m!=="HEAD"?m:void 0,p=[],h=new Map;for(const v of o){const S=`${v.providerID}:${v.modelID}`;h.set(S,(h.get(S)||0)+1)}const y=new Map;for(const v of o){const S=`${v.providerID}:${v.modelID}`,N=h.get(S)||1,j=(y.get(S)||0)+1;y.set(S,j);const k=Xg(v.providerID,v.modelID),F=N>1?Tl(u,`${k}-${j}`):Tl(u,k);if(!F)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const I=Qg(F);if(!I)return s({error:`Invalid branch name: ${F}`,isLoading:!1}),null;try{const M=await gd({projectDirectory:c,worktreeSlug:I,branch:F,createBranch:!0,startPoint:f}),b=await Le.withDirectory(M.path,()=>Le.createSession({title:`${v.providerID}/${v.modelID}`}));et.getState().setWorktreeMetadata(b.id,M),p.push({sessionId:b.id,worktreePath:M.path,providerID:v.providerID,modelID:v.modelID})}catch(M){console.warn("[MultiRun] Failed to create session:",M)}}const g=p.map(v=>v.sessionId),w=p[0]?.sessionId??null;if(g.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const x=i?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));return(async()=>{try{await Promise.allSettled(p.map(async v=>{try{await Le.withDirectory(v.worktreePath,()=>Le.sendMessage({id:v.sessionId,providerID:v.providerID,modelID:v.modelID,text:n,agent:a,files:x}))}catch(S){console.warn("[MultiRun] Failed to start run:",S)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),s({isLoading:!1}),{sessionIds:g,firstSessionId:w}}catch(c){return s({error:c instanceof Error?c.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{s({error:null})}}),{name:"multirun-store"})),bi=()=>{const{providers:s}=lt(),{favoriteModels:r,recentModels:t}=Fe(),n=l.useMemo(()=>r.map(({providerID:a,modelID:i})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[r,s]),o=l.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!r.some(c=>c.providerID===a&&c.modelID===i)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},Zg=10*1024*1024,ex=5,$a=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,qd="h-7",tx=({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:O("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",qd),children:[e.jsx(qt,{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(zt,{className:"h-3.5 w-3.5"})})]})},sx=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),rx=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=sx.format(s);return r.endsWith(".0")?r.slice(0,-2):r},nx=({selectedModels:s,onAdd:r,onRemove:t})=>{const{providers:n,modelsMetadata:o}=lt(),{favoriteModelsList:a,recentModelsList:i}=bi(),[c,d]=l.useState(!1),[u,m]=l.useState(""),[f,p]=l.useState(0),h=l.useRef(null),y=l.useRef(null),g=l.useRef([]),w=l.useMemo(()=>{const b=new Map;for(const C of s){const A=`${C.providerID}:${C.modelID}`;b.set(A,(b.get(A)||0)+1)}return b},[s]),x=l.useCallback(b=>s.filter(A=>A.providerID===b.providerID&&A.modelID===b.modelID).findIndex(A=>A.instanceId===b.instanceId)+1,[s]),v=(b,C)=>{const A=`${b}/${C}`;return o.get(A)},S=b=>{const C=b?.name||b?.id||"",A=String(C);return A.length>40?A.substring(0,37)+"...":A},N=l.useCallback((b,C)=>{if(!u.trim())return!0;const A=u.toLowerCase();return b.toLowerCase().includes(A)||C.toLowerCase().includes(A)},[u]),j=l.useMemo(()=>a.filter(({model:b,providerID:C})=>{const P=n.find($=>$.id===C)?.name||C,L=S(b);return N(L,P)}),[a,n,N]),k=l.useMemo(()=>i.filter(({model:b,providerID:C})=>{const P=n.find($=>$.id===C)?.name||C,L=S(b);return N(L,P)}),[i,n,N]),F=l.useMemo(()=>n.map(b=>{const A=(Array.isArray(b.models)?b.models:[]).filter(P=>{const L=S(P);return N(L,b.name||b.id||"")});return{...b,models:A}}).filter(b=>b.models.length>0),[n,N]),I=j.length>0||k.length>0||F.length>0;l.useEffect(()=>{c&&h.current&&h.current.focus()},[c]),l.useEffect(()=>{if(!c)return;const b=C=>{y.current&&!y.current.contains(C.target)&&(d(!1),m(""),p(0))};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[c]),l.useEffect(()=>{p(0)},[u]);const M=(b,C,A,P,L,$)=>{const q=`${C}:${A}`,ee=w.get(q)||0,ce=v(C,A),_=rx(ce?.limit?.context);return e.jsxs("button",{ref:z=>{g.current[L]=z},type:"button",onClick:()=>{r({providerID:C,modelID:A,displayName:b.name||A,instanceId:$a()})},onMouseEnter:()=>p(L),className:O("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",$?"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:S(b)}),_&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:_})]}),ee>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",ee]})]},`${P}-${q}`)};return e.jsx("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:y,children:[e.jsxs(ve,{type:"button",variant:"outline",size:"sm",className:qd,onClick:()=>d(!c),children:[e.jsx(Ht,{className:"h-3.5 w-3.5 mr-1"}),"Add model"]}),c&&(()=>{const b=[];j.forEach(({model:L,providerID:$,modelID:q})=>{b.push({model:L,providerID:$,modelID:q,section:"fav"})}),k.forEach(({model:L,providerID:$,modelID:q})=>{b.push({model:L,providerID:$,modelID:q,section:"recent"})}),F.forEach(L=>{L.models.forEach($=>{b.push({model:$,providerID:L.id,modelID:$.id,section:"provider"})})});const C=b.length,A=L=>{if(L.key==="ArrowDown"){L.preventDefault(),L.stopPropagation();const $=(f+1)%Math.max(1,C);p($),setTimeout(()=>{g.current[$]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(L.key==="ArrowUp"){L.preventDefault(),L.stopPropagation();const $=(f-1+Math.max(1,C))%Math.max(1,C);p($),setTimeout(()=>{g.current[$]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(L.key==="Enter"){L.preventDefault(),L.stopPropagation();const $=b[f];$&&r({providerID:$.providerID,modelID:$.modelID,displayName:$.model.name||$.modelID,instanceId:$a()})}else L.key==="Escape"&&(L.preventDefault(),L.stopPropagation(),d(!1),m(""),p(0))};let P=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(vr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{ref:h,type:"text",placeholder:"Search models",value:u,onChange:L=>m(L.target.value),onKeyDown:A,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(tt,{outerClassName:"max-h-[400px] flex-1",children:e.jsxs("div",{className:"p-1",children:[!I&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),j.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Vs,{className:"h-4 w-4 text-primary"}),"Favorites"]}),j.map(({model:L,providerID:$,modelID:q})=>{const ee=P++;return M(L,$,q,"fav",ee,f===ee)})]}),k.length>0&&e.jsxs(e.Fragment,{children:[j.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(hn,{className:"h-4 w-4"}),"Recent"]}),k.map(({model:L,providerID:$,modelID:q})=>{const ee=P++;return M(L,$,q,"recent",ee,f===ee)})]}),(j.length>0||k.length>0)&&F.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),F.map((L,$)=>e.jsxs(l.Fragment,{children:[$>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(qt,{providerId:L.id,className:"h-4 w-4 flex-shrink-0"}),L.name]}),L.models.map(q=>{const ee=P++;return M(q,L.id,q.id,"provider",ee,f===ee)})]},L.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),s.map((b,C)=>{const A=`${b.providerID}:${b.modelID}`,P=w.get(A)||1,L=x(b);return e.jsx(tx,{model:b,instanceIndex:L,totalSameModel:P,onRemove:()=>t(C)},b.instanceId)})]})})},Fl=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=l.useState(""),[a,i]=l.useState(()=>s??""),[c,d]=l.useState([]),[u,m]=l.useState([]),[f,p]=l.useState(!1),h=l.useRef(null),y=yt(D=>D.currentDirectory??null),g=Fe(D=>D.isSidebarOpen),[w,x]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),v=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const D=typeof window.opencodeDesktop<"u";x(D)},[]);const S=l.useMemo(()=>w&&v?g?"pl-0":"pl-[8.0rem]":"pl-3",[w,v,g]),[N,j]=l.useState("HEAD"),[k,F]=l.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[I,M]=l.useState(!1),[b,C]=l.useState(null),A=ra(D=>D.createMultiRun),P=ra(D=>D.error),L=ra(D=>D.clearError);l.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&i(D=>D.trim().length>0?D:s)},[s]),l.useEffect(()=>{let D=!1;if(!y){C(null),M(!1),F([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),j("HEAD");return}return M(!0),C(null),(async()=>{try{const H=await Zr(y);if(D)return;if(C(H),!H){F([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),j("HEAD");return}const X=await fd(y).catch(()=>null);if(D)return;const he=[],ae=X?.current?`Current (HEAD: ${X.current})`:"Current (HEAD)";he.push({value:"HEAD",label:ae,group:"special"}),X&&(X.all.filter(W=>!W.startsWith("remotes/")).sort((W,te)=>W.localeCompare(te)).forEach(W=>{he.push({value:W,label:W,group:"local"})}),X.all.filter(W=>W.startsWith("remotes/")).map(W=>W.replace(/^remotes\//,"")).sort((W,te)=>W.localeCompare(te)).forEach(W=>{he.push({value:W,label:W,group:"remote"})})),F(he),j(fe=>he.some(je=>je.value===fe)?fe:"HEAD")}finally{D||M(!1)}})(),()=>{D=!0}},[y]);const $=D=>{c.length>=ex||(d(H=>[...H,D]),L())},q=D=>{d(H=>H.filter((X,he)=>he!==D)),L()},ee=async D=>{const H=D.target.files;if(!H)return;let X=0;for(let he=0;he<H.length;he++){const ae=H[he];if(ae.size>Zg){se.error(`File "${ae.name}" is too large (max 10MB)`);continue}try{const fe=await new Promise((W,te)=>{const oe=new FileReader;oe.onload=()=>W(oe.result),oe.onerror=te,oe.readAsDataURL(ae)}),je={id:$a(),filename:ae.name,mimeType:ae.type||"application/octet-stream",size:ae.size,dataUrl:fe};m(W=>[...W,je]),X++}catch(fe){console.error("File attach failed",fe),se.error(`Failed to attach "${ae.name}"`)}}X>0&&se.success(`Attached ${X} file${X>1?"s":""}`),h.current&&(h.current.value="")},ce=D=>{m(H=>H.filter(X=>X.id!==D))},_=async D=>{if(D.preventDefault(),!!a.trim()&&!(c.length<2)){p(!0),L();try{const H=c.map(({instanceId:fe,...je})=>je),X=u.map(fe=>({mime:fe.mimeType,filename:fe.filename,url:fe.dataUrl})),he={name:n.trim(),prompt:a.trim(),models:H,worktreeBaseBranch:N,files:X.length>0?X:void 0},ae=await A(he);ae&&(ae.firstSessionId&&ye.getState().setCurrentSession(ae.firstSessionId),r?.())}finally{p(!1)}}},z=!!(n.trim()&&a.trim()&&c.length>=2&&b&&!I);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:O("flex h-12 items-center justify-between border-b app-region-drag",S),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:O("flex items-center gap-3",w&&v&&g&&"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(Qe,{delayDuration:500,children:[e.jsx(Je,{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(zt,{className:"h-5 w-5"})})}),e.jsx(Xe,{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:_,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(dt,{id:"group-name",value:n,onChange:D=>o(D.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.jsxs(Ms,{value:N,onValueChange:j,disabled:!b||I,children:[e.jsx(Ds,{id:"multirun-worktree-base-branch",size:"lg",className:"max-w-full typography-meta text-foreground",children:e.jsx(xo,{placeholder:I?"Loading branches…":"Select a branch"})}),e.jsxs(As,{fitContent:!0,children:[e.jsxs(gr,{children:[e.jsx(xr,{children:"Default"}),k.filter(D=>D.group==="special").map(D=>e.jsx(Ft,{value:D.value,className:"w-auto whitespace-nowrap",children:D.label},D.value))]}),k.some(D=>D.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(yo,{}),e.jsxs(gr,{children:[e.jsx(xr,{children:"Local branches"}),k.filter(D=>D.group==="local").map(D=>e.jsx(Ft,{value:D.value,className:"w-auto whitespace-nowrap",children:D.label},D.value))]})]}):null,k.some(D=>D.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(yo,{}),e.jsxs(gr,{children:[e.jsx(xr,{children:"Remote branches"}),k.filter(D=>D.group==="remote").map(D=>e.jsx(Ft,{value:D.value,className:"w-auto whitespace-nowrap",children:D.label},D.value))]})]}):null]})]}),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:N||"HEAD"}),"."]}),b===!1?e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."}):null]})]}),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(Cs,{id:"prompt",value:a,onChange:D=>i(D.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:h,type:"file",multiple:!0,className:"hidden",onChange:ee,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(ve,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>h.current?.click(),children:[e.jsx(so,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),u.map(D=>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:[D.mimeType.startsWith("image/")?e.jsx(rr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(Gs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:D.filename,children:D.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",D.size<1024?`${D.size}B`:D.size<1024*1024?`${(D.size/1024).toFixed(1)}KB`:`${(D.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>ce(D.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(zt,{className:"h-3.5 w-3.5"})})]},D.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("span",{className:"ml-1 font-normal text-muted-foreground",children:"(select at least 2, maximum 5)"})]}),e.jsx(nx,{selectedModels:c,onAdd:$,onRemove:q})]}),P&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:P}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(ve,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(ve,{type:"submit",disabled:!z||f,children:f?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(qm,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},ox=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=Fe(),d=Se.useRef(null),u=Se.useRef(null);return Se.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:x,time:v}=d.current,{x:S,y:N,time:j}=u.current,k=S-w,F=N-x,I=j-v,M=Math.abs(F)<Math.abs(k),b=I<=n,C=Math.abs(F)<t;k>=t&&M&&b&&C&&!c&&i(!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,i,c]),null},cn=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;Se.memo(()=>{const s=Se.useRef(null),{addAttachedFile:r}=ye(),{isMobile:t}=Fe(),n=Ad(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",i=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],h=ye.getState().attachedFiles.length;try{await r(p),ye.getState().attachedFiles.length>h&&m++}catch(y){console.error("File attach failed",y),se.error(y instanceof Error?y.message:"Failed to attach file")}}m>0&&se.success(`Attached ${m} file${m>1?"s":""}`)},c=async u=>{const m=u.target.files;m&&(await i(m),s.current&&(s.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const y=p.map(g=>`${g?.name||"file"}: ${g?.reason||"skipped"}`).join(`
61
- `);se.error(`Some files were skipped:
62
- ${y}`)}const h=f.map(y=>{if(!y?.dataUrl)return null;try{const[g,w]=y.dataUrl.split(","),x=y.mimeType||g?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!w)return null;const v=atob(w),S=new Uint8Array(v.length);for(let j=0;j<v.length;j++)S[j]=v.charCodeAt(j);const N=new Blob([S],{type:x});return new File([N],y.name||"file",{type:x})}catch(g){return console.error("Failed to decode VS Code picked file",g),null}}).filter(Boolean);h.length>0&&await i(h)}catch(u){console.error("VS Code file pick failed",u),se.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:s,type:"file",multiple:!0,className:"hidden",onChange:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:O(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(so,{className:O(a,"text-current")})})]})});const ax=Se.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(rr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(Gs,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(No,{className:"h-3.5 w-3.5"}):e.jsx(Gs,{className:"h-3.5 w-3.5"}),n=i=>i<1024?i+" B":i<1048576?(i/1024).toFixed(1)+" KB":(i/1048576).toFixed(1)+" MB",a=(i=>{const d=i.replace(/\\/g,"/").split("/");return d[d.length-1]||i})(s.filename);return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:s.source==="server"?"Server file":"Local file",children:s.source==="server"?e.jsx(Gm,{className:"h-3 w-3 text-primary"}):e.jsx(Uc,{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(zt,{className:"h-3 w-3"})})]})}),ix=Se.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=ye();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(ax,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),Gd=Se.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(rr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(Gs,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(No,{className:"h-3.5 w-3.5"}):e.jsx(Gs,{className:"h-3.5 w-3.5"}):e.jsx(Gs,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),c=l.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return t.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const m=n(d.filename)||"Image";return e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{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(rr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(Xe,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Kd=Se.memo(({message:s,sessionId:r,onEdit:t})=>{const n=Rs(i=>i.removeFromQueue),o=l.useMemo(()=>{const i=s.content.split(`
63
- `),c=i[0]||"",d=50;return c.length>d?c.substring(0,d)+"...":c+(i.length>1?"...":"")},[s.content]),a=s.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(Km,{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(zt,{className:"h-3 w-3"})})]})});Kd.displayName="QueuedMessageChip";const Pl=[],Yd=Se.memo(({onEditMessage:s})=>{const r=ye(a=>a.currentSessionId),t=Rs(l.useCallback(a=>r?a.queuedMessages[r]??Pl:Pl,[r])),n=Rs(a=>a.popToInput),o=l.useCallback(a=>{if(!r)return;const i=n(r,a.id);if(i){if(i.attachments&&i.attachments.length>0){const c=Ls.getState().attachedFiles;Ls.setState({attachedFiles:[...c,...i.attachments]})}s(i.content,i.attachments)}},[r,n,s]);return t.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),t.map(a=>e.jsx(Kd,{message:a,sessionId:r,onEdit:o},a.id))]})})});Yd.displayName="QueuedMessageChips";const Xd=(s,r=200)=>{const[t,n]=Se.useState(s);return Se.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},lx=l.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=yt(),{addServerFile:a}=ye(),i=ai(C=>C.searchFiles),c=Xd(s,180),[d,u]=l.useState([]),[m,f]=l.useState(!1),[p,h]=l.useState(0),[y,g]=l.useState(360),[w,x]=l.useState({}),[v,S]=l.useState({}),N=l.useRef([]),j=l.useRef([]),k=l.useRef([]),F=l.useRef(null),I=l.useCallback((C,A)=>{const P=C.trim().toLowerCase();if(!P)return 0;const L=A.toLowerCase();let $=0,q=-1,ee=0;for(let ce=0;ce<P.length;ce+=1){const _=P[ce];if(!_||_===" ")continue;const z=L.indexOf(_,q+1);if(z===-1)return null;const D=z-q-1;if(D===0?ee+=1:ee=0,$+=10,$+=Math.max(0,18-z),$-=Math.max(0,D),z===0)$+=12;else{const H=L[z-1];(H==="/"||H==="_"||H==="-"||H==="."||H===" ")&&($+=10)}$+=ee>0?12:0,q=z}return $+=Math.max(0,24-Math.round(L.length/3)),$},[]);l.useEffect(()=>{const C=A=>{const P=A.target;!P||!F.current||F.current.contains(P)||t()};return document.addEventListener("pointerdown",C,!0),()=>{document.removeEventListener("pointerdown",C,!0)}},[t]),l.useEffect(()=>{if(!o){u([]);return}const A=(c??"").trim().toLowerCase();let P=!1;return f(!0),i(o,A,80).then(L=>{if(P)return;const $=A?L.map(q=>{const ee=q.relativePath||q.name||q.path,ce=I(A,ee);return ce===null?null:{file:q,score:ce,labelLength:ee.length}}).filter(Boolean):L.map(q=>({file:q,score:0,labelLength:(q.relativePath||q.name||q.path).length}));$.sort((q,ee)=>ee.score-q.score||q.labelLength-ee.labelLength||q.file.path.localeCompare(ee.file.path)),u($.slice(0,15).map(q=>q.file))}).catch(()=>{P||u([])}).finally(()=>{P||f(!1)}),()=>{P=!0}},[o,c,I,i]),l.useEffect(()=>{h(0),x({}),S({})},[d]),l.useEffect(()=>{N.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),l.useEffect(()=>{let C=null;const A=()=>{C!==null&&cancelAnimationFrame(C),C=requestAnimationFrame(()=>{const P={},L={};j.current.forEach(($,q)=>{if(!$)return;const ce=k.current[q]?.offsetWidth??$.scrollWidth,_=Math.max(0,ce-$.clientWidth),z=_>8;if(P[q]=z,z){const D=Math.max(.6,_/110);L[q]=D}}),x(P),S(L)})};return A(),window.addEventListener("resize",A),()=>{C!==null&&cancelAnimationFrame(C),window.removeEventListener("resize",A)}},[d]),l.useEffect(()=>{const C=j.current[p];if(!C)return;const A=()=>{const L=C.clientWidth;L>0&&g(L)};if(A(),typeof ResizeObserver>"u")return;const P=new ResizeObserver(A);return P.observe(C),()=>{P.disconnect()}},[p]);const M=l.useCallback(async C=>{await a(C.path,C.name),r(C)},[a,r]);l.useImperativeHandle(n,()=>({handleKeyDown:C=>{if(C==="Escape"){t();return}const A=d.length;if(A!==0){if(C==="ArrowDown"){h(P=>(P+1)%A);return}if(C==="ArrowUp"){h(P=>(P-1+A)%A);return}if(C==="Enter"||C==="Tab"){const P=(p%A+A)%A,L=d[P];L&&M(L)}}}}),[d,p,t,M]);const b=C=>{switch(C.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(Gs,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(rr,{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"})}};return e.jsxs("div",{ref:F,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(tt,{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(kn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((C,A)=>{const P=C.relativePath||C.name,L=sd(P,{maxLength:45}),$=p===A,q=w[A]??!1,ee=v[A]??2.6,ce=e.jsxs("div",{ref:_=>{N.current[A]=_},className:O("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",$&&"bg-muted"),onClick:()=>M(C),onMouseEnter:()=>h(A),children:[b(C),e.jsxs("span",{ref:_=>{j.current[A]=_},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:$?{"--file-mention-marquee-width":`${y}px`,"--file-mention-marquee-duration":`${ee}s`}:void 0,"aria-label":P,children:[e.jsx("span",{ref:_=>{k.current[A]=_},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:P}),q&&$?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:P}):e.jsx("span",{className:"block truncate",children:L})]})]});return e.jsx(l.Fragment,{children:ce},C.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"})]})}),Qd=l.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o}=ye(Ja(y=>{const g=y.currentSessionId;return{hasMessagesInCurrentSession:(g?y.messages.get(g)?.length??0:0)>0}})),[a,i]=l.useState([]),[c,d]=l.useState(!1),[u,m]=l.useState(0),f=l.useRef([]),p=l.useRef(null);l.useEffect(()=>{const y=g=>{const w=g.target;!w||!p.current||p.current.contains(w)||t()};return document.addEventListener("pointerdown",y,!0),()=>{document.removeEventListener("pointerdown",y,!0)}},[t]),l.useEffect(()=>{(async()=>{d(!0);try{const w=(await Le.listCommands()).map(k=>({name:k.name,description:k.description,agent:k.agent,model:k.model,isBuiltIn:!1})),x=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],v=new Map;x.forEach(k=>v.set(k.name,k)),w.forEach(k=>v.set(k.name,k));const S=Array.from(v.values()),N=!o,j=(s?S.filter(k=>k.name.toLowerCase().includes(s.toLowerCase())||k.description&&k.description.toLowerCase().includes(s.toLowerCase())):S).filter(k=>N||k.name!=="init");j.sort((k,F)=>{const I=k.name.toLowerCase().startsWith(s.toLowerCase()),M=F.name.toLowerCase().startsWith(s.toLowerCase());return I&&!M?-1:!I&&M?1:k.name.localeCompare(F.name)}),i(j)}catch{const g=!o,w=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],x=(s?w.filter(v=>v.name.toLowerCase().includes(s.toLowerCase())||v.description&&v.description.toLowerCase().includes(s.toLowerCase())):w).filter(v=>g||v.name!=="init");i(x)}finally{d(!1)}})()},[s,o]),l.useEffect(()=>{m(0)},[a]),l.useEffect(()=>{f.current[u]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[u]),l.useImperativeHandle(n,()=>({handleKeyDown:y=>{const g=a.length;if(y==="Escape"){t();return}if(g!==0){if(y==="ArrowDown"){m(w=>(w+1)%g);return}if(y==="ArrowUp"){m(w=>(w-1+g)%g);return}if(y==="Enter"||y==="Tab"){const w=(u%g+g)%g,x=a[w];x&&r(x)}}}}),[a,u,t,r]);const h=y=>{switch(y.name){case"init":return e.jsx(Gs,{className:"h-3.5 w-3.5 text-green-500"});case"summarize":return e.jsx(Xm,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(ar,{className:"h-3.5 w-3.5 text-cyan-500"});default:return y.isBuiltIn?e.jsx(Ym,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(Sr,{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-[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(tt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(kn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[a.map((y,g)=>e.jsxs("div",{ref:w=>{f.current[g]=w},className:O("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",g===u&&"bg-muted"),onClick:()=>r(y),onMouseEnter:()=>m(g),children:[e.jsx("div",{className:"mt-0.5",children:h(y)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-medium",children:["/",y.name]}),y.agent&&e.jsx("span",{className:"typography-meta text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:y.agent})]}),y.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:y.description})]})]},y.name)),a.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"})]})});Qd.displayName="CommandAutocomplete";const cx=s=>s?s!=="primary":!1,Jd=l.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=l.useRef(null),[a,i]=l.useState(0),[c,d]=l.useState([]),{getVisibleAgents:u}=lt();l.useEffect(()=>{const p=u().filter(g=>cx(g.mode)).map(g=>({name:g.name,description:g.description,mode:g.mode??void 0})),h=s.trim().toLowerCase(),y=h.length?p.filter(g=>g.name.toLowerCase().includes(h)):p;y.sort((g,w)=>g.name.localeCompare(w.name)),d(y),i(0)},[u,s]),l.useEffect(()=>{const f=p=>{const h=p.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",f,!0),()=>{document.removeEventListener("pointerdown",f,!0)}},[t]),l.useImperativeHandle(n,()=>({handleKeyDown:f=>{if(f==="Escape"){t();return}if(c.length){if(f==="ArrowDown"){i(p=>(p+1)%c.length);return}if(f==="ArrowUp"){i(p=>(p-1+c.length)%c.length);return}if(f==="Enter"||f==="Tab"){const p=c[(a+c.length)%c.length];p&&r(p.name)}}}}),[c,r,t,a]);const m=(f,p)=>e.jsx("div",{className:O("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",p===a&&"bg-muted"),onClick:()=>r(f.name),onMouseEnter:()=>i(p),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["#",f.name]})}),f.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:f.description})]})},f.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(tt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c.length?e.jsx("div",{children:c.map((f,p)=>m(f,p))}):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"})]})});Jd.displayName="AgentMentionAutocomplete";function dx({className:s,children:r,...t}){return e.jsxs(Qm,{"data-slot":"scroll-area",className:O("relative",s),...t,children:[e.jsx(Jm,{"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(ux,{}),e.jsx(Zm,{})]})}function ux({className:s,orientation:r="vertical",...t}){return e.jsx(ef,{"data-slot":"scroll-area-scrollbar",orientation:r,className:O("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(tf,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const mx=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Nt(),c=i,{currentDirectory:d}=yt(),u=ai(T=>T.searchFiles),[m,f]=l.useState(!1),[p,h]=l.useState(!1),[y,g]=l.useState(""),w=Xd(y,200),[x,v]=l.useState(new Set),[S,N]=l.useState(new Set),[j,k]=l.useState({}),F=l.useRef(new Set),I=l.useRef(new Set),[M,b]=l.useState([]),[C,A]=l.useState(!1),[P,L]=l.useState(!1),[$,q]=l.useState(!1),[ee,ce]=l.useState(null),_=n??m,z=o??f,D=l.useCallback(T=>T.slice().sort((Y,E)=>Y.type!==E.type?Y.type==="directory"?-1:1:Y.name.localeCompare(E.name)),[]),H=l.useCallback((T,Y)=>D(Y.filter(E=>!E.name.startsWith(".")).map(E=>{const B=E.name,U=!E.isDirectory&&B.includes(".")?B.split(".").pop()?.toLowerCase():void 0;return{name:B,path:E.path||`${T}/${B}`,type:E.isDirectory?"directory":"file",size:0,extension:U}})),[D]),X=l.useCallback(async T=>{L(!0),ce(null);try{const Y=await Le.listLocalDirectory(T),E=H(T,Y.map(B=>({name:B.name,path:B.path,isDirectory:B.isDirectory})));F.current=new Set([T]),I.current=new Set,k({[T]:E}),N(new Set)}catch{ce("Failed to load directory contents"),F.current=new Set([T]),I.current=new Set,k({[T]:[]}),N(new Set)}finally{L(!1)}},[H]),he=l.useCallback(async T=>{const Y=T.trim();if(Y&&!F.current.has(Y)&&!I.current.has(Y)){I.current=new Set(I.current),I.current.add(Y);try{const E=await Le.listLocalDirectory(Y),B=H(Y,E.map(U=>({name:U.name,path:U.path,isDirectory:U.isDirectory})));F.current=new Set(F.current),F.current.add(Y),k(U=>({...U,[Y]:B}))}catch{k(E=>E[Y]?E:{...E,[Y]:[]})}finally{I.current=new Set(I.current),I.current.delete(Y)}}},[H]);l.useEffect(()=>{(_||p)&&d&&X(d)},[_,p,d,X]),l.useEffect(()=>{if(!(_||p)||!d){b([]),A(!1);return}const T=w.trim();if(!T){b([]),A(!1);return}let Y=!1;return A(!0),u(d,T,150).then(E=>{if(Y)return;const B=E.map(U=>({name:U.name,path:U.path,type:"file",extension:U.extension,relativePath:U.relativePath,size:0}));b(B)}).catch(()=>{Y||b([])}).finally(()=>{Y||A(!1)}),()=>{Y=!0}},[_,p,d,w,u]),l.useEffect(()=>{!_&&!p&&(v(new Set),g(""),b([]),A(!1))},[_,p]);const ae=T=>{if(T.type==="directory")return S.has(T.path)?e.jsx(ms,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(ms,{className:"h-3.5 w-3.5 text-primary/60"});switch(T.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(Na,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(rr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Na,{className:"h-3.5 w-3.5 text-muted-foreground"})}},fe=async T=>{S.has(T)?N(E=>{const B=new Set(E);return B.delete(T),B}):(N(E=>{const B=new Set(E);return B.add(T),B}),await he(T))},je=T=>{v(r?Y=>{const E=new Set(Y);return E.has(T)?E.delete(T):E.add(T),E}:new Set([T]))},W=async()=>{const T=new Map;Object.values(j).forEach(B=>{B.forEach(U=>{U.type==="file"&&T.set(U.path,U)})});const Y=new Map(M.map(B=>[B.path,B])),E=Array.from(x).map(B=>T.get(B)??Y.get(B)).filter(B=>!!B);q(!0);try{await s(E),v(new Set),z(!1),h(!1)}finally{q(!1)}},te=l.useMemo(()=>d?j[d]??[]:[],[j,d]),oe=y.trim().length>0,V=T=>j[T]??[],ue=T=>{if(d&&T.startsWith(d)){const Y=T.substring(d.length);return Y.startsWith("/")?Y.substring(1):Y}return T.split("/").pop()||T},ge=(T,Y)=>{const E=oe?T.relativePath||ue(T.path):T.name,B=oe&&E.includes("/")&&E.length>45,U=B?sd(E,{maxLength:c?42:48}):E,be=e.jsxs("div",{className:O("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",T.type==="file"&&x.has(T.path)&&"bg-primary/10"),style:{paddingLeft:`${Y*12}px`},onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),T.type==="file"&&je(T.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ae(T)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":E,children:U})]}),T.type==="file"&&x.has(T.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return B?e.jsxs(Qe,{delayDuration:120,children:[e.jsx(Je,{asChild:!0,children:be}),e.jsx(Xe,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:E})})]},T.path):l.cloneElement(be,{key:T.path})},ie=(T,Y)=>{const E=T.type==="directory",B=E?V(T.path):[],U=S.has(T.path),be=E&&U&&I.current.has(T.path)&&B.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:O("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!E&&x.has(T.path)&&"bg-primary/10"),style:{paddingLeft:`${Y*12}px`},onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),E?fe(T.path):je(T.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ae(T)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:T.name}),!E&&x.has(T.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),E&&U&&B.length>0&&e.jsx("div",{children:B.map(Q=>ie(Q,Y+1))}),E&&U&&be&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(Y+1)*12}px`},children:"Loading…"})]},T.path)},De=x.size>0?`${x.size} file${x.size!==1?"s":""} selected`:"No files selected",Ce=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:De}),e.jsx(ve,{size:"sm",onClick:W,disabled:x.size===0||$,className:"h-6 typography-meta",children:$?"Attaching...":"Attach Files"})]}),Ie=c?"flex-1 min-h-[240px]":"h-[300px]",K=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(vr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{value:y,onChange:T=>g(T.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:T=>T.stopPropagation()}),y&&e.jsx("button",{onClick:T=>{T.stopPropagation(),g("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(zt,{className:"h-3 w-3"})})]})}),e.jsxs(dx,{className:Ie,children:[P&&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..."})}),ee&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:ee})}),!P&&!ee&&e.jsxs("div",{className:"py-1 px-2",children:[oe?C?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):M.map(T=>ge(T,0)):te.map(T=>ie(T,0)),!oe&&te.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),oe&&!C&&M.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),G=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:T=>{T.preventDefault(),T.stopPropagation(),h(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:T=>{T.preventDefault(),T.stopPropagation(),z(!0)},children:t}):null,e.jsx(cs,{open:_,onClose:()=>z(!1),title:"Select Project Files",footer:Ce,children:e.jsx("div",{className:"flex flex-col gap-0",children:K})})]}):c?e.jsxs(e.Fragment,{children:[G,e.jsx(cs,{open:p,onClose:()=>h(!1),title:"Select Project Files",footer:Ce,children:e.jsx("div",{className:"flex flex-col gap-0",children:K})})]}):e.jsxs(Gt,{open:_,onOpenChange:z,children:[e.jsx(Kt,{asChild:!0,children:t}),e.jsxs(Yt,{className:O("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[K,e.jsx(Os,{}),Ce]})]})},On=[{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 On[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)%(On.length-1);return On[t]}const fx=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),Zd=s=>fx(s),px=s=>s?typeof s=="string"?s==="ask":Zd(s)?Object.values(s).some(r=>r==="ask"):!1:!1,hx=s=>s?typeof s=="string"?s==="deny":Zd(s)?Object.values(s).some(r=>r==="deny"):!1:!1,eu=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=px(t),o=hx(t),a=!n&&!o,i=r==="allow",c=r!=="deny",d=s==="allow"||s==="full",u=s==="ask";let m=s;d&&i&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:s!=="deny"&&c&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:c}},$n=s=>s==="primary"||s==="all"||s===void 0||s===null,gx=[{key:"tool_call",icon:Co,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:Yr,label:"Reasoning",isActive:s=>s?.reasoning===!0}],xx={text:{icon:Wc,label:"Text"},image:{icon:rr,label:"Image"},video:{icon:rf,label:"Video"},audio:{icon:sf,label:"Audio"},pdf:{icon:No,label:"PDF"}},yx=s=>s.trim().toLowerCase(),an=(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=>yx(o)))).map(o=>{const a=xx[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},bx=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),wx=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),ys=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=bx.format(s);return r.endsWith(".0")?r.slice(0,-2):r},_n=s=>typeof s!="number"||!Number.isFinite(s)?"—":wx.format(s),na=s=>gx.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Rl=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},Ll=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)},Ol=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentAgentName:o,setProvider:a,setModel:i,setAgent:c,getCurrentProvider:d,getModelMetadata:u,getCurrentAgent:m,getVisibleAgents:f}=lt(),p=f(),{currentSessionId:h,messages:y,saveSessionAgentSelection:g,getSessionAgentSelection:w,saveAgentModelForSession:x,getAgentModelForSession:v,analyzeAndSaveExternalSessionChoices:S,getSessionAgentEditMode:N,setSessionAgentEditMode:j}=ye(),k=gt(R=>R.hasHydrated),{toggleFavoriteModel:F,isFavoriteModel:I,addRecentModel:M,isModelSelectorOpen:b,setModelSelectorOpen:C}=Fe(),{favoriteModelsList:A,recentModelsList:P}=bi(),{isMobile:L}=Nt(),$=tg(),q=Ad(),ee=L,[ce,_]=l.useState(null),[z,D]=l.useState(null),[H,X]=l.useState(""),he=l.useCallback(()=>_(null),[]),ae=l.useCallback(()=>D(null),[]),fe=l.useRef(void 0),[je,W]=l.useState(()=>{const R=new Set;return t&&R.add(t),R}),[te,oe]=l.useState(!1),V=b,ue=C,[ge,ie]=l.useState(!1),De=l.useId(),[Ce,Ie]=l.useState(""),[K,G]=l.useState(0),T=l.useRef([]);l.useEffect(()=>{ce==="model"&&W(()=>{const R=new Set;return t&&R.add(t),R})},[ce,t]),l.useEffect(()=>{ce!=="agent"&&oe(!1),ce!=="model"&&X("")},[ce]);const Y=l.useRef(V);l.useEffect(()=>{const R=Y.current;Y.current=V,V||(ie(!1),Ie(""),G(0),R&&!ee&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[V,ee]),l.useEffect(()=>{G(0)},[Ce]);const E=m?.(),B=E?.permission?.edit;let U="ask";(B==="allow"||B==="ask"||B==="deny"||B==="full")&&(U=B);const be=E?E.tools?.edit!==!1:!1;(!E||!be)&&(U="deny");const Q=E?.permission?.webfetch,xe=E?.permission?.bash,He=l.useMemo(()=>eu({agentDefaultEditMode:U,webfetchPermission:Q,bashPermission:xe}),[U,Q,xe]),{cascadeDefaultMode:Ke,modeAvailability:ze,autoApproveAvailable:st}=He,it=!!(h&&o),at=it&&h&&o?N(h,o,Ke):Ke,ct={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},ut=l.useCallback(R=>!ze[R],[ze]),pt=l.useMemo(()=>!it||ut(at)&&at!==Ke?Ke:at,[Ke,ut,it,at]),vt=[{mode:"ask",label:ct.ask,disabled:ut("ask")},{mode:"allow",label:ct.allow,disabled:ut("allow")},{mode:"full",label:ct.full,disabled:ut("full")}],xt=l.useMemo(()=>cn(pt),[pt]),mt=!it||!st;l.useEffect(()=>{mt&&(oe(!1),ie(!1))},[mt]);const J=L?"mobile":q?"vscode":"default",ke=J==="mobile"?"h-9":J==="vscode"?"h-6":"h-8",re=J==="mobile"?"h-5 w-5":"h-4 w-4",le=J==="mobile"?"h-5 w-5":"h-4 w-4",Ae=ee?"typography-micro":"typography-meta",$e=J==="mobile"?"gap-x-2":J==="vscode"?"gap-x-1":"gap-x-3",Ue=ct[pt],We=l.useCallback((R,Z=re)=>{const ne=O(Z,"flex-shrink-0"),Ne=cn(R),Re={color:Ne?Ne.text:"var(--foreground)"};return R==="full"?e.jsx(Ws,{className:ne,style:Re}):R==="allow"?e.jsx(Vn,{className:ne,style:Re}):R==="deny"?e.jsx(Vr,{className:ne,style:Re}):e.jsx(Ur,{className:ne,style:Re})},[re]),Ze=l.useCallback(R=>{mt||!h||!o||ut(R)||(j(h,o,R,Ke),ue(!1),oe(!1),ie(!1))},[Ke,mt,h,o,j,ue,ie,ut]),me=d(),de=Array.isArray(me?.models)?me.models:[],we=t&&n?u(t,n):void 0,Me=na(we),Pe=an(we,"input"),qe=an(we,"output"),bt=[{label:"Input",value:_n(we?.cost?.input)},{label:"Output",value:_n(we?.cost?.output)},{label:"Cache read",value:_n(we?.cost?.cache_read)},{label:"Cache write",value:_n(we?.cost?.cache_write)}],Et=[{label:"Context",value:ys(we?.limit?.context)},{label:"Output",value:ys(we?.limit?.output)}],Ct=l.useRef(void 0),ft=h?y.get(h)?.length??-1:-1,Ye=l.useRef(null),wt=l.useCallback((R,Z,ne)=>{if(!R||!Z)return"model-missing";const Ne=r.find(pe=>pe.id===R);return Ne?(Array.isArray(Ne.models)?Ne.models:[]).find(pe=>pe.id===Z)?(a(R),i(Z),h&&ne&&x(h,ne,R,Z),"applied"):"model-missing":"provider-missing"},[r,a,i,h,x]);l.useEffect(()=>{if(!h){Ye.current=null;return}if(!k||r.length===0||p.length===0)return;(!Ye.current||Ye.current.sessionId!==h)&&(Ye.current={sessionId:h,resolved:!1,inFlight:!1});const R=Ye.current;if(!R||R.resolved||R.inFlight)return;let Z=!1;const ne=()=>{if(Z)return;const pe=Ye.current;pe&&pe.sessionId===h&&(pe.resolved=!0,pe.inFlight=!1)},Ne=()=>{const pe=w(h);if(pe){o!==pe&&c(pe);const Be=v(h,pe);if(Be){const Te=wt(Be.providerId,Be.modelId,pe);if(Te==="applied")return"resolved";if(Te==="provider-missing")return"waiting"}else return"resolved"}for(const Be of p){const Te=v(h,Be.name);if(!Te)continue;o!==Be.name&&c(Be.name),g(h,Be.name);const Ge=wt(Te.providerId,Te.modelId,Be.name);if(Ge==="applied")return"resolved";if(Ge==="provider-missing")return"waiting"}return"continue"},Oe=()=>{if(p.length===0)return;const pe=p.filter(Te=>$n(Te.mode)),Be=p.find(Te=>Te.name==="build")||pe[0]||p[0];Be&&(g(h,Be.name),o!==Be.name&&c(Be.name),Be.model?.providerID&&Be.model?.modelID&&wt(Be.model.providerID,Be.model.modelID,Be.name))};return(async()=>{try{const pe=Ne();if(pe==="resolved"){ne();return}if(pe==="waiting"||ft===-1)return;if(ft>0){R.inFlight=!0;try{const Be=await S(h,p);if(Z)return;if(Be.size>0){let Te=null,Ge=-1/0;for(const[nt,ht]of Be)ht.timestamp>Ge&&(Ge=ht.timestamp,Te=nt);if(Te){g(h,Te),o!==Te&&c(Te);const nt=Be.get(Te);if(nt){const ht=wt(nt.providerId,nt.modelId,Te);if(ht==="applied"){ne();return}if(ht==="provider-missing")return}else{ne();return}}}}catch(Be){Z||console.error("[ModelControls] Error resolving session from messages:",Be)}finally{const Be=Ye.current;!Z&&Be&&Be.sessionId===h&&(Be.inFlight=!1)}}Oe(),ne()}catch(pe){Z||console.error("[ModelControls] Error in session switch:",pe)}})(),()=>{Z=!0}},[h,ft,p,o,w,v,c,wt,S,g,k,r]),l.useEffect(()=>{if(!k||!h||r.length===0||p.length===0)return;const Z=w(h)||o;if(!Z)return;const ne=v(h,Z);if(!ne)return;const Ne=r.find(Be=>Be.id===ne.providerId);if(!Ne||!(Array.isArray(Ne.models)?Ne.models.some(Be=>Be.id===ne.modelId):!1))return;const Re=t===ne.providerId,pe=n===ne.modelId;Re&&pe||(Z!==o&&c(Z),wt(ne.providerId,ne.modelId,Z))},[k,h,o,t,n,r,p,w,v,wt,c]),l.useEffect(()=>{if(!k)return;(async()=>{try{if(o!==Ct.current&&(Ct.current=o,o&&h)){await new Promise(Ne=>setTimeout(Ne,50));const Z=v(h,o);if(Z){const Ne=wt(Z.providerId,Z.modelId,o);if(Ne==="applied"||Ne==="provider-missing")return}const ne=p.find(Ne=>Ne.name===o);if(ne?.model?.providerID&&ne?.model?.modelID&&wt(ne.model.providerID,ne.model.modelID,o)==="provider-missing")return}}catch(Z){console.error("[ModelControls] Agent change error:",Z)}})()},[o,h,v,wt,p,k]);const Ee=R=>{try{c(R),ue(!1),h&&g(h,R),ee&&he()}catch(Z){console.error("[ModelControls] Handle agent change error:",Z)}},_e=(R,Z)=>{try{const ne=wt(R,Z,o||void 0);if(ne!=="applied"){ne==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",R):ne==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:R,modelId:Z});return}M(R,Z),ue(!1),ee&&he(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(ne){console.error("[ModelControls] Handle model change error:",ne)}},Ve=R=>{const Z=typeof R?.name=="string"?R.name:typeof R?.id=="string"?R.id:"";return Z.length>40?Z.substring(0,37)+"...":Z},rt=()=>r.find(Z=>Z.id===t)?.name||t,jt=()=>{if(!t||!n||de.length===0)return"Not selected";const R=de.find(Z=>Z.id===n);return Ve(R)},Rt=()=>{if(!o){const Z=p.filter(Oe=>$n(Oe.mode)),Ne=Z.find(Oe=>Oe.name==="build")||Z[0];return Ne?Tt(Ne.name):"Select Agent"}const R=p.find(Z=>Z.name===o);return Tt(R?R.name:o)},Tt=R=>R.charAt(0).toUpperCase()+R.slice(1),Qt=(R,Z,ne)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:Z,"aria-label":Z,role:"img",children:e.jsx(R,{className:"h-3.5 w-3.5"})},ne),Ar=l.useCallback(R=>{W(Z=>{const ne=new Set(Z);return ne.has(R)?ne.delete(R):ne.add(R),ne})},[]),Er=l.useCallback(R=>{fe.current&&clearTimeout(fe.current),fe.current=setTimeout(()=>{D(R)},500)},[]),Xs=l.useCallback(()=>{fe.current&&clearTimeout(fe.current)},[]);l.useEffect(()=>()=>{fe.current&&clearTimeout(fe.current)},[]);const To=()=>!ee||z!=="model"?null:e.jsx(cs,{open:!0,onClose:ae,title:we?.name||jt(),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:rt()})]}),Me.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:Me.map(({key:R,icon:Z,label:ne})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qt(Z,ne,`cap-${R}`),e.jsx("span",{className:"typography-meta text-foreground",children:ne})]},R))})]}),(Pe.length>0||qe.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:[Pe.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:Pe.map(({key:R,icon:Z,label:ne})=>Qt(Z,`${ne} input`,`input-${R}`))})]}),qe.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:qe.map(({key:R,icon:Z,label:ne})=>Qt(Z,`${ne} output`,`output-${R}`))})]})]})]}),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:ys(we?.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:ys(we?.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:Rl(we?.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:Ll(we?.release_date)})]})]})]})]})}),Fo=()=>{if(!ee||z!=="agent"||!E)return null;const R=Object.entries(E.tools||{}).filter(([,pe])=>pe).map(([pe])=>pe).sort(),Z=!!(E.prompt&&E.prompt.trim().length>0),ne=E.model?.providerID&&E.model?.modelID,Ne=E.temperature!==void 0||E.topP!==void 0,Oe=pe=>We(pe==="full"||pe==="allow"||pe==="deny"?pe:"ask","h-3.5 w-3.5"),Re=pe=>pe==="full"?"Full":pe==="allow"?"Allow":pe==="deny"?"Deny":"Ask";return e.jsx(cs,{open:!0,onClose:ae,title:Tt(E.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[E.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:E.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:E.mode==="primary"?"Primary":E.mode==="subagent"?"Subagent":E.mode==="all"?"All":"—"})]}),(ne||Ne)&&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"}),ne&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[E.model.providerID," / ",E.model.modelID]}),Ne&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[E.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:E.temperature})]}),E.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:E.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:"Tools"}),R.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:R.map(pe=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:pe},pe))}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),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:[Oe(E.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Re(E.permission?.edit)})]})]}),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:[Oe(typeof E.permission?.bash=="string"?E.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Re(typeof E.permission?.bash=="string"?E.permission.bash:void 0)})]})]}),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:[Oe(E.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Re(E.permission?.webfetch)})]})]})]})]}),Z&&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(Vn,{className:"h-4 w-4 text-foreground"})]})})]})})},lr=()=>{if(!ee)return null;const R=H.trim().toLowerCase(),Z=r.map(ne=>{const Ne=Array.isArray(ne.models)?ne.models:[],Oe=R.length===0?!0:ne.name.toLowerCase().includes(R)||ne.id.toLowerCase().includes(R),Re=R.length===0?Ne:Ne.filter(pe=>{const Be=Ve(pe).toLowerCase(),Te=typeof pe.id=="string"?pe.id.toLowerCase():"";return Be.includes(R)||Te.includes(R)});return{provider:ne,providerModels:Re,matchesProvider:Oe}}).filter(({matchesProvider:ne,providerModels:Ne})=>ne||Ne.length>0);return e.jsx(cs,{open:ce==="model",onClose:he,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(vr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{value:H,onChange:ne=>X(ne.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),H&&e.jsx("button",{type:"button",onClick:()=>X(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Vr,{className:"h-4 w-4"})})]})}),Z.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."}),!H&&A.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(Vs,{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:A.map(({model:ne,providerID:Ne,modelID:Oe})=>{const Re=Ne===t&&Oe===n,pe=u(Ne,Oe);return e.jsxs("button",{type:"button",onClick:()=>_e(Ne,Oe),className:O("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",Re?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(qt,{providerId:Ne,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ve(ne)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(pe?.limit?.context||pe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[pe?.limit?.context?`${ys(pe?.limit?.context)} ctx`:"",pe?.limit?.context&&pe?.limit?.output?" • ":"",pe?.limit?.output?`${ys(pe?.limit?.output)} out`:""]})})]},`fav-mobile-${Ne}-${Oe}`)})})]}),!H&&P.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(hn,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:P.map(({model:ne,providerID:Ne,modelID:Oe})=>{const Re=Ne===t&&Oe===n,pe=u(Ne,Oe);return e.jsxs("button",{type:"button",onClick:()=>_e(Ne,Oe),className:O("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",Re?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(qt,{providerId:Ne,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ve(ne)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(pe?.limit?.context||pe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[pe?.limit?.context?`${ys(pe?.limit?.context)} ctx`:"",pe?.limit?.context&&pe?.limit?.output?" • ":"",pe?.limit?.output?`${ys(pe?.limit?.output)} out`:""]})})]},`recent-mobile-${Ne}-${Oe}`)})})]}),Z.map(({provider:ne,providerModels:Ne})=>{if(Ne.length===0&&!R.length)return null;const Oe=ne.id===t,Re=je.has(ne.id)||R.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:()=>Ar(ne.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Re,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{providerId:ne.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ne.name}),Oe&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Re?e.jsx(kt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Ss,{className:"h-3 w-3 text-muted-foreground"})]}),Re&&Ne.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Ne.map(pe=>{const Be=Oe&&pe.id===n,Te=u(ne.id,pe.id),Ge=na(Te).slice(0,3),nt=an(Te,"input");return e.jsxs("div",{className:O("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",!Be&&"hover:bg-muted",Be?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>_e(ne.id,pe.id),className:O("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:Ve(pe)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Te?.limit?.context||Te?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Te?.limit?.context?e.jsxs("span",{children:[ys(Te?.limit?.context)," ctx"]}):null,Te?.limit?.context&&Te?.limit?.output?e.jsx("span",{children:"•"}):null,Te?.limit?.output?e.jsxs("span",{children:[ys(Te?.limit?.output)," out"]}):null]}),(Ge.length>0||nt.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Ge,...nt].map(({key:ht,icon:Lt,label:Ut})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Ut,"aria-label":Ut,children:e.jsx(Lt,{className:"h-3 w-3"})},`meta-${ne.id}-${pe.id}-${ht}`))})]})]}),e.jsx("button",{type:"button",onClick:ht=>{ht.preventDefault(),ht.stopPropagation(),F(ne.id,pe.id)},className:O("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",I(ne.id,pe.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":I(ne.id,pe.id)?"Unfavorite":"Favorite",title:I(ne.id,pe.id)?"Remove from favorites":"Add to favorites",children:I(ne.id,pe.id)?e.jsx(Vs,{className:"h-4 w-4"}):e.jsx(_r,{className:"h-4 w-4"})})]},pe.id)})})]},ne.id)})]})})},cr=()=>{if(!ee)return null;const R=p.filter(Z=>$n(Z.mode));return e.jsx(cs,{open:ce==="agent",onClose:he,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[R.map(Z=>{const ne=Z.name===o,Ne=er(Z.name);return e.jsxs("button",{type:"button",className:O("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",Ne.class,ne?"active":"border-border/40"),onClick:()=>Ee(Z.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:O("h-2 w-2 rounded-full",Ne.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:ne?{color:`var(${Ne.var})`}:void 0,children:Tt(Z.name)})]}),Z.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:Z.description})]},Z.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:mt,onClick:()=>{mt||oe(Z=>!Z)},className:O("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:xt?xt.text:"var(--foreground)",mixBlendMode:"normal"},children:Ue})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:O("flex items-center justify-center p-1",!xt&&"text-muted-foreground"),style:xt?{color:xt.text}:void 0,children:We(pt,re)}),e.jsx(kt,{className:O("h-4 w-4 text-muted-foreground transition-transform",te?"rotate-180":"")})]})]}),te&&!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:vt.map(Z=>{const ne=Z.mode===pt,Ne=cn(Z.mode);return e.jsxs("button",{type:"button",disabled:Z.disabled,onClick:()=>Ze(Z.mode),className:O("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",Z.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",ne?"bg-primary/10":void 0),style:ne&&Ne?{backgroundColor:Ne.background??void 0}:void 0,children:[We(Z.mode,re),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:Ne?Ne.text:"var(--foreground)"},children:Z.label})})]},Z.mode)})})})]})]})})},Ii=()=>e.jsx(Xe,{align:"start",sideOffset:8,className:"max-w-[320px]",children:we?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:we.name||jt()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:rt()})]}),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:Me.length>0?Me.map(({key:R,icon:Z,label:ne})=>Qt(Z,ne,`cap-${R}`)):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:Pe.length>0?Pe.map(({key:R,icon:Z,label:ne})=>Qt(Z,`${ne} input`,`input-${R}`)):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:qe.length>0?qe.map(({key:R,icon:Z,label:ne})=>Qt(Z,`${ne} output`,`output-${R}`)):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)"}),bt.map(R=>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:R.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:R.value})]},R.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),Et.map(R=>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:R.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:R.value})]},R.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:Rl(we.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:Ll(we.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Ir=(R,Z,ne,Ne,Oe,Re)=>{const pe=u(Z,ne),Be=na(pe).map(Jt=>({...Jt,id:`cap-${Jt.key}`})),Te=[...an(pe,"input"),...an(pe,"output")],Ge=Array.from(new Map(Te.map(Jt=>[Jt.key,Jt])).values()).map(Jt=>({...Jt,id:`mod-${Jt.key}`})),nt=[...Be,...Ge],ht=ys(pe?.limit?.context),Lt=t===Z&&n===ne,Ut=I(Z,ne);return e.jsxs("div",{ref:Jt=>{T.current[Oe]=Jt},className:O("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Re?"bg-accent":"hover:bg-accent/50"),onClick:()=>_e(Z,ne),onMouseEnter:()=>G(Oe),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:Ve(R)}),pe?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:ht}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[nt.length>0&&e.jsx("div",{className:O("items-center gap-0.5",Re?"flex":"hidden group-hover:flex"),children:nt.map(({id:Jt,icon:Bu,label:Ti})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Ti,role:"img",title:Ti,children:e.jsx(Bu,{className:"h-2.5 w-2.5"})},Jt))}),Lt&&e.jsx(Mt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:Jt=>{Jt.preventDefault(),Jt.stopPropagation(),F(Z,ne)},className:O("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Ut?"text-yellow-500":"text-muted-foreground"),"aria-label":Ut?"Unfavorite":"Favorite",title:Ut?"Remove from favorites":"Add to favorites",children:Ut?e.jsx(Vs,{className:"h-3.5 w-3.5"}):e.jsx(_r,{className:"h-3.5 w-3.5"})})]})]},`${Ne}-${Z}-${ne}`)},tn=(R,Z,ne)=>{if(!ne.trim())return!0;const Ne=ne.toLowerCase();return R.toLowerCase().includes(Ne)||Z.toLowerCase().includes(Ne)},Po=()=>{const R=A.filter(({model:Te,providerID:Ge})=>{const ht=r.find(Ut=>Ut.id===Ge)?.name||Ge,Lt=Ve(Te);return tn(Lt,ht,Ce)}),Z=P.filter(({model:Te,providerID:Ge})=>{const ht=r.find(Ut=>Ut.id===Ge)?.name||Ge,Lt=Ve(Te);return tn(Lt,ht,Ce)}),ne=r.map(Te=>{const nt=(Array.isArray(Te.models)?Te.models:[]).filter(ht=>{const Lt=Ve(ht);return tn(Lt,Te.name||Te.id||"",Ce)});return{...Te,models:nt}}).filter(Te=>Te.models.length>0),Ne=R.length>0||Z.length>0||ne.length>0,Oe=[];R.forEach(({model:Te,providerID:Ge,modelID:nt})=>{Oe.push({model:Te,providerID:Ge,modelID:nt,section:"fav"})}),Z.forEach(({model:Te,providerID:Ge,modelID:nt})=>{Oe.push({model:Te,providerID:Ge,modelID:nt,section:"recent"})}),ne.forEach(Te=>{Te.models.forEach(Ge=>{Oe.push({model:Ge,providerID:Te.id,modelID:Ge.id,section:"provider"})})});const Re=Oe.length,pe=Te=>{if(Te.key==="ArrowDown")Te.preventDefault(),Te.stopPropagation(),G(Ge=>(Ge+1)%Math.max(1,Re)),setTimeout(()=>{const Ge=(K+1)%Math.max(1,Re);T.current[Ge]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Te.key==="ArrowUp")Te.preventDefault(),Te.stopPropagation(),G(Ge=>(Ge-1+Math.max(1,Re))%Math.max(1,Re)),setTimeout(()=>{const Ge=(K-1+Math.max(1,Re))%Math.max(1,Re);T.current[Ge]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Te.key==="Enter"){Te.preventDefault(),Te.stopPropagation();const Ge=Oe[K];Ge&&_e(Ge.providerID,Ge.modelID)}else Te.key==="Escape"&&(Te.preventDefault(),Te.stopPropagation(),ue(!1))};let Be=0;return e.jsxs(Qe,{delayDuration:1e3,children:[ee?e.jsxs("button",{type:"button",onClick:()=>_("model"),onTouchStart:()=>Er("model"),onTouchEnd:Xs,onTouchCancel:Xs,className:O("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",ke),children:[t?e.jsx(qt,{providerId:t,className:O(le,"flex-shrink-0")}):e.jsx(Ws,{className:O(le,"text-muted-foreground")}),e.jsx("span",{className:O("model-controls__model-label typography-micro font-medium truncate min-w-0",!L&&"max-w-[220px]"),children:jt()})]}):e.jsxs(Gt,{open:V,onOpenChange:ue,children:[e.jsx(Je,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:O("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",ke),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(qt,{providerId:t,className:O(le,"flex-shrink-0")}),e.jsx(Ws,{className:O(le,"text-primary/60 hidden")})]}):e.jsx(Ws,{className:O(le,"text-muted-foreground")}),e.jsx("span",{className:O("model-controls__model-label",Ae,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:jt()},`${t}-${n}`)]})})}),e.jsxs(Yt,{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(vr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{type:"text",placeholder:"Search models",value:Ce,onChange:Te=>Ie(Te.target.value),onKeyDown:pe,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(tt,{outerClassName:"max-h-[400px] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Ne&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),R.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(zr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Vs,{className:"h-4 w-4 text-primary"}),"Favorites"]}),R.map(({model:Te,providerID:Ge,modelID:nt})=>{const ht=Be++;return Ir(Te,Ge,nt,"fav",ht,K===ht)})]}),Z.length>0&&e.jsxs(e.Fragment,{children:[R.length>0&&e.jsx(Os,{}),e.jsxs(zr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(hn,{className:"h-4 w-4"}),"Recent"]}),Z.map(({model:Te,providerID:Ge,modelID:nt})=>{const ht=Be++;return Ir(Te,Ge,nt,"recent",ht,K===ht)})]}),(R.length>0||Z.length>0)&&ne.length>0&&e.jsx(Os,{}),ne.map((Te,Ge)=>e.jsxs(l.Fragment,{children:[Ge>0&&e.jsx(Os,{}),e.jsxs(zr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(qt,{providerId:Te.id,className:"h-4 w-4 flex-shrink-0"}),Te.name]}),Te.models.map(nt=>{const ht=Be++;return Ir(nt,Te.id,nt.id,"provider",ht,K===ht)})]},Te.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})]}),Ii()]})},Nn=()=>{if(!E)return e.jsx(Xe,{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 R=Object.entries(E.tools||{}).filter(([,pe])=>pe).map(([pe])=>pe).sort(),Z=!!(E.prompt&&E.prompt.trim().length>0),ne=E.model?.providerID&&E.model?.modelID,Ne=E.temperature!==void 0||E.topP!==void 0,Oe=pe=>We(pe==="full"||pe==="allow"||pe==="deny"?pe:"ask","h-3.5 w-3.5"),Re=pe=>pe==="full"?"Full":pe==="allow"?"Allow":pe==="deny"?"Deny":"Ask";return e.jsx(Xe,{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:Tt(E.name)}),E.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:E.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:E.mode==="primary"?"Primary":E.mode==="subagent"?"Subagent":E.mode==="all"?"All":"—"})]}),(ne||Ne)&&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"}),ne?e.jsxs("span",{className:"typography-meta text-foreground",children:[E.model.providerID," / ",E.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),Ne&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[E.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:E.temperature})]}),E.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:E.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:"Tools"}),R.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:R.map(pe=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:pe},pe))}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),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:[Oe(E.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Re(E.permission?.edit)})]})]}),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:[Oe(typeof E.permission?.bash=="string"?E.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Re(typeof E.permission?.bash=="string"?E.permission.bash:void 0)})]})]}),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:[Oe(E.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Re(E.permission?.webfetch)})]})]})]}),Z&&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(Vn,{className:"h-4 w-4 text-foreground"})]})]})})},Ro=()=>ee?e.jsxs("button",{type:"button",onClick:()=>_("agent"),onTouchStart:()=>Er("agent"),onTouchEnd:Xs,onTouchCancel:Xs,className:O("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",ke,"cursor-pointer hover:opacity-70",ee&&"ml-1"),children:[e.jsx(gn,{className:O(le,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${er(o).var})`}:void 0}),e.jsx("span",{className:O("model-controls__agent-label",Ae,"font-medium truncate min-w-0"),style:o?{color:`var(${er(o).var})`}:void 0,children:Rt()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(Qe,{delayDuration:1e3,children:[e.jsxs(Gt,{children:[e.jsx(Je,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:O("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",ke),children:[e.jsx(gn,{className:O(le,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${er(o).var})`}:void 0}),e.jsx("span",{className:O("model-controls__agent-label",Ae,"font-medium min-w-0 truncate",$?"max-w-[220px]":void 0),style:o?{color:`var(${er(o).var})`}:void 0,children:Rt()})]})})}),e.jsxs(Yt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[p.filter(R=>$n(R.mode)).map(R=>e.jsx(St,{className:"typography-meta",onSelect:()=>Ee(R.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:O("h-1 w-1 rounded-full agent-dot",er(R.name).class)}),e.jsx("span",{className:"font-medium",children:Tt(R.name)})]}),R.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:R.description})]})},R.name)),e.jsx(Os,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:mt,onClick:()=>{mt||ie(R=>!R)},className:O("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":ge,"aria-controls":De,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:xt?xt.text:"var(--foreground)"},children:Ue})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:O("flex items-center justify-center p-1",!xt&&"text-muted-foreground"),style:xt?{color:xt.text}:void 0,children:We(pt)}),e.jsx(kt,{className:O("h-3.5 w-3.5 transition-transform text-muted-foreground",ge?"rotate-180":"")})]})]}),ge&&!mt&&e.jsx("div",{id:De,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:vt.map(R=>{const Z=R.mode===pt,ne=cn(R.mode);return e.jsxs("button",{type:"button",disabled:R.disabled,onClick:()=>Ze(R.mode),className:O("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",R.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",Z?"bg-primary/10":void 0),style:Z&&ne?{backgroundColor:ne.background??void 0}:void 0,children:[We(R.mode,re),e.jsx("span",{className:"typography-meta font-medium",style:{color:ne?ne.text:"var(--foreground)"},children:R.label})]},R.mode)})})]})]})]}),Nn()]})}),Lo=O("@container/model-controls flex items-center min-w-0",$e,L&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Lo,children:[e.jsx("div",{className:O("flex items-center min-w-0 flex-1 justify-end",L&&"overflow-hidden"),children:Po()}),e.jsx("div",{className:O("flex items-center min-w-0",$e,L&&"flex-shrink-0"),children:Ro()})]}),lr(),cr(),To(),Fo()]})},vx=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,$l=(s,r)=>{if(typeof s!="string"||s.length===0)return{sanitizedText:s,mention:null};const t=r.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!s.includes("#"))return{sanitizedText:s,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(s))!==null;){const c=i.index,d=c+i[0].length,u=c>0?s[c-1]:null;if(!vx(u))continue;const m={name:o.name,source:{value:i[0],start:c,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},tu=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),_a=It()(Pt((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const o=(await Le.getSessionTodos(t)).map(tu);s(a=>{const i=new Map(a.sessionTodos);return i.set(t,o),{sessionTodos:i,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"})),jx=(s,r)=>{const t=r.map(tu);_a.getState().updateTodos(s,t)},_l=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(Rr.span,{...t,className:O("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)=>Se.createElement(Rr.span,{...t,key:n+String(o),className:O("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:O("invisible",r),children:s}),e.jsx("span",{...t,className:O("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:O("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",r),children:s})]})},{variant:"hover-enter",component:({children:s,className:r,...t})=>{if(typeof s!="string")return null;const n=.25,o=.025,a=s.split("").map(i=>i===" "?" ":i);return e.jsxs(Rr.span,{...t,className:O("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((i,c)=>e.jsx(Rr.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))}),e.jsx("div",{className:O("absolute inset-0"),children:a.map((i,c)=>e.jsx(Rr.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:O("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:O("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:O("text-primary-muted",r),children:s})})}];function oa({variant:s="shine",className:r,...t}){const a=_l.find(i=>i.variant===s)?.component||_l[0].component;return e.jsx(zc,{children:e.jsx(a,{...t,className:r})})}const Bl=1500,Sx=2e3;function kx({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:i}){const[c,d]=Se.useState("idle"),[u,m]=Se.useState(null),[f,p]=Se.useState(!1),h=Se.useRef(0),y=Se.useRef(null),g=Se.useRef(null),w=Se.useRef(null),x=Se.useRef(null),v=Se.useRef(!1),S=Se.useRef(!1),N=Se.useRef(!1),j=Se.useCallback(()=>{g.current&&(clearTimeout(g.current),g.current=null),w.current&&(clearTimeout(w.current),w.current=null)},[]),k=Se.useCallback((P,L)=>{j(),y.current=null,m(P),p(L),d("showing"),h.current=Date.now(),v.current=!0},[j]),F=Se.useCallback(()=>{if(g.current)return;const P=Date.now()-h.current,L=Math.max(0,Bl-P);g.current=setTimeout(()=>{g.current=null;const $=y.current;$&&k($.text,$.permission)},L)},[k]),I=Se.useCallback(P=>{if(j(),y.current=null,!v.current){d("idle"),m(null),i?.(!1);return}if(P==="done"&&o&&x.current===o){d("idle"),m(null),v.current=!1,i?.(!1);return}P==="done"&&o&&(x.current=o),d(P),m(null),i?.(!0),w.current=setTimeout(()=>{w.current=null,d("idle"),v.current=!1,i?.(!1)},Sx)},[j,o,i]);if(Se.useEffect(()=>{if(n&&!N.current){N.current=!0,I("aborted");return}if(N.current=!!n,a&&!S.current){S.current=!0,I("done");return}if(!a&&S.current&&(S.current=!1),!(c==="done"||c==="aborted")&&s){const L=Date.now()-h.current;if(c==="idle"||!u)k(s,!!t);else if(s!==u||!!t!==f){if(r)return;L>=Bl?k(s,!!t):(y.current={text:s,permission:!!t},F())}}},[s,t,n,a,c,u,f,k,I,F,r]),Se.useEffect(()=>()=>j(),[j]),Se.useEffect(()=>{const P=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(j(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",P),()=>document.removeEventListener("visibilitychange",P)},[c,j]),c==="idle"&&!u)return null;let M,b=!0;c==="done"?(M="Done",b=!1):c==="aborted"?(M="Aborted",b=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const C=b?`${M}...`:M,A=c!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${A?"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(oa,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(oa,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(oa,{variant:"shine",className:"typography-ui-header",children:C})})})}const zl={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Nx=({todo:s})=>{const r=zl[s.status]||zl.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:O("flex-1 typography-ui-label",r.textClassName),children:s.content})})},Hl=[],Cx=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:i,isComplete:c,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=l.useState(!1),h=ye(L=>L.currentSessionId),y=_a(L=>h?L.sessionTodos.get(h)??Hl:Hl),g=_a(L=>L.loadTodos),{isMobile:w}=Fe(),x=w||Dt();l.useEffect(()=>{h&&g(h)},[h,g]);const v=l.useMemo(()=>{const L={in_progress:0,pending:1,completed:2,cancelled:3};return[...y].filter($=>$.status!=="cancelled").sort(($,q)=>L[$.status]-L[q.status])},[y]),S=l.useMemo(()=>v.find(L=>L.status==="in_progress")||v.find(L=>L.status==="pending")||null,[v]),N=l.useMemo(()=>{const L=y.filter(q=>q.status!=="cancelled").length;return{completed:y.filter(q=>q.status==="completed").length,total:L}},[y]),j=v.length>0,k=!m&&(o||!a),[F,I]=l.useState(!1),M=s||c||o||F||j||m,b=l.useRef(null);if(l.useEffect(()=>{if(!f)return;const L=$=>{b.current&&!b.current.contains($.target)&&p(!1)};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[f]),!M)return null;const C=()=>p(L=>!L),A=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(Vr,{size:18,"aria-hidden":"true"})}):null,P=j?e.jsxs("button",{type:"button",onClick:C,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!x&&S?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:S.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[N.completed,"/",N.total]}),f?e.jsx(ko,{className:"h-3.5 w-3.5"}):e.jsx(kt,{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(Vr,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(kx,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:i??null,isComplete:c,onResultVisibilityChange:I},h??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:b,children:[A,P,f&&j&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:O("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:v.map(L=>e.jsx(Nx,{todo:L},L.id))})]})]})]})})},Ba=s=>!s||typeof s!="object"?!1:!!s.synthetic,Ul=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>Ba(r)),Mx=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!Ba(t))?s.filter(t=>!Ba(t)):s,Dx={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Ax(s){const r=ye(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return l.useMemo(()=>{if(r==="idle")return Dx;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function wi(){const s=ye(r=>r.currentSessionId);return Ax(s)}const Ex={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},Wl=s=>s.role==="assistant",Ix=s=>s.type==="reasoning",su=s=>s.type==="text",Vl=s=>{if(su(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},ql=s=>(su(s)||Ix(s),s.time),Tx=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function ru(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=ye(Ja(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=wi(),c=l.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=l.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const h=c.filter(M=>Wl(M.info)&&!Ul(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const y=[...h].sort((M,b)=>{const C=typeof M.info.time?.created=="number"?M.info.time.created:null,A=typeof b.info.time?.created=="number"?b.info.time.created:null;return C!==null&&A!==null&&C!==A?C-A:M.info.id.localeCompare(b.info.id)}),g=y[y.length-1];let w,x;const v=new Set(["edit","write"]);for(let M=(g.parts??[]).length-1;M>=0;M-=1){const b=g.parts?.[M];if(b)switch(b.type){case"reasoning":{const C=b.time??ql(b);(!C||typeof C.end>"u")&&!w&&(w="reasoning");break}case"tool":{const C=b.state?.status;if((C==="running"||C==="pending")&&!w){const A=Tx(b);v.has(A)?w="editing":(w="tool",x=A)}break}case"text":{const C=Vl(b)??"";if(typeof C=="string"&&C.trim().length>0){const A=ql(b);(!A||typeof A.end>"u")&&!w&&(w="text")}break}}}const S={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"},N=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],j=M=>S[M]??`using ${M}`,k=()=>N[Math.floor(Math.random()*N.length)],F=w===void 0,I=w==="editing"?"editing file":w==="tool"&&x?j(x):w==="reasoning"?"thinking":w==="text"?"composing":k();return{activePartType:w,activeToolName:x,statusText:I,isGenericStatus:F}},[c]),u=l.useMemo(()=>{const h=s,y=h?n?.get(h)??null:null,g=!!(y&&!y.acknowledged);return{wasAborted:g,abortActive:g}},[s,n]),m=l.useMemo(()=>{if(u.wasAborted)return{...Ex,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=i;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,i,d,u]),f=l.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const y=c.filter(x=>Wl(x.info)&&!Ul(x.parts));if(y.length===0)return{isActive:h,characterCount:0};const g=y[y.length-1];let w=0;return(g.parts??[]).forEach(x=>{if(x.type!=="text")return;const v=Vl(x)??"";typeof v=="string"&&v.trim().length>0&&(w+=v.length)}),{isActive:h,characterCount:w}},[c,a,d.activePartType]),p=l.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 Fx=8,Gl=[],Px=s=>s==="primary"||s==="all"||s===void 0||s===null,Bn=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=l.useState(""),[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(""),[m,f]=l.useState(!1),[p,h]=l.useState(""),[y,g]=l.useState(!1),[w,x]=l.useState(""),[v,S]=l.useState(null),N=l.useRef(null),j=l.useRef(null),k=l.useRef(null),F=l.useRef(null),I=l.useRef(null),M=ye(R=>R.sendMessage),b=ye(R=>R.currentSessionId),C=ye(R=>R.newSessionDraft?.open),A=ye(R=>R.abortCurrentOperation),P=ye(R=>R.acknowledgeSessionAbort),L=ye(R=>R.abortPromptSessionId),$=ye(R=>R.abortPromptExpiresAt),q=ye(R=>R.clearAbortPrompt),ee=ye(R=>R.sessionAbortFlags),ce=ye(R=>R.attachedFiles),_=ye(R=>R.addAttachedFile),z=ye(R=>R.addServerFile),D=ye(R=>R.clearAttachedFiles),H=ye(R=>R.saveSessionAgentSelection),X=ye(R=>R.consumePendingInputText),he=ye(R=>R.pendingInputText),{currentProviderId:ae,currentModelId:fe,currentAgentName:je,setAgent:W,getVisibleAgents:te}=lt(),oe=te(),{isMobile:V,inputBarOffset:ue,isKeyboardOpen:ge}=Fe(),{working:ie}=ru(),[De,Ce]=l.useState(!1),Ie=l.useRef(null),K=l.useRef(!1),G=l.useRef(!1),T=Rs(R=>R.queueModeEnabled),Y=Rs(l.useCallback(R=>b?R.queuedMessages[b]??Gl:Gl,[b])),E=Rs(R=>R.addToQueue),B=Rs(R=>R.clearQueue),{phase:U}=wi(),be=l.useRef(U),Q=l.useRef(!1),xe=l.useCallback(R=>{if(!V||R.pointerType!=="touch")return;const Z=N.current;if(!Z||document.activeElement===Z)return;R.preventDefault(),R.stopPropagation();const ne=document.scrollingElement;ne&&ne.scrollTop!==0&&(ne.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Z.focus({preventScroll:!0})}catch{Z.focus()}const Ne=Z.value.length;try{Z.setSelectionRange(Ne,Ne)}catch{}},[V]);l.useEffect(()=>{if(he!==null){const R=X();R&&(n(R),setTimeout(()=>{N.current?.focus()},0))}},[he,X]);const He=l.useMemo(()=>{if(je)return oe.find(R=>R.name===je)},[oe,je]),Ke=l.useMemo(()=>{const R=He?.permission?.edit;let Z="ask";(R==="allow"||R==="ask"||R==="deny"||R==="full")&&(Z=R);const ne=He?He.tools?.edit!==!1:!1;return(!He||!ne)&&(Z="deny"),Z},[He]),ze=ye(l.useCallback(R=>!b||!je?void 0:R.sessionAgentEditModes.get(b)?.get(je),[b,je])),st=He?.permission?.webfetch,it=He?.permission?.bash,at=l.useMemo(()=>eu({agentDefaultEditMode:Ke,webfetchPermission:st,bashPermission:it}),[Ke,st,it]),ct=!!(b&&je),ut=l.useMemo(()=>ct&&ze&&at.modeAvailability[ze]?ze:at.cascadeDefaultMode,[at,ct,ze]),pt=l.useMemo(()=>cn(ut),[ut]),vt=l.useCallback(R=>Dt()?`color-mix(in srgb, ${R} 55%, transparent)`:R,[]),xt=l.useMemo(()=>{const R=Dt()?1:2;if(!pt)return{borderWidth:R};const Z=pt.border??pt.text;return{borderColor:vt(Z),borderWidth:R}},[pt,vt]),mt=t.trim()||ce.length>0,J=Y.length>0,ke=mt||J,re=ie.isWorking,le=l.useMemo(()=>b?L===b&&!!$:!1,[L,$,b]),Ae=l.useCallback(()=>{if(!mt||!b)return;const R=t.replace(/^\n+|\n+$/g,""),Z=ce.map(ne=>({...ne}));E(b,{content:R,attachments:Z.length>0?Z:void 0}),n(""),Z.length>0&&D(),V||N.current?.focus()},[mt,b,t,ce,E,D,V]),$e=async R=>{if(R?.preventDefault(),!ke||!b&&!C)return;if(r?.({instant:!0,force:!0}),!ae||!fe){console.warn("Cannot send message: provider or model not selected");return}let Z="",ne=[],Ne;const Oe=[];for(let Be=0;Be<Y.length;Be++){const Te=Y[Be],{sanitizedText:Ge,mention:nt}=$l(Te.content,oe);!Ne&&nt?.name&&(Ne=nt.name),Be===0?(Z=Ge,ne=Te.attachments??[]):Oe.push({text:Ge,attachments:Te.attachments})}if(mt){const Be=t.replace(/^\n+|\n+$/g,""),{sanitizedText:Te,mention:Ge}=$l(Be,oe),nt=ce.map(ht=>({...ht}));!Ne&&Ge?.name&&(Ne=Ge.name),Y.length===0?(Z=Te,ne=nt):Oe.push({text:Te,attachments:nt.length>0?nt:void 0})}if(!Z&&Oe.length===0)return;b&&J&&B(b),n(""),ce.length>0&&D(),V&&N.current?.blur();const Re=Z.trimStart();Re.startsWith("/")&&Re.slice(1).trim().split(/\s+/)[0]?.toLowerCase()==="summarize"&&r?.({instant:!0,force:!0});const pe=[...ne,...Oe.flatMap(Be=>Be.attachments??[])];await M(Z,ae,fe,je,ne,Ne,Oe.length>0?Oe:void 0).catch(Be=>{const Te=Be instanceof Error?Be.message:typeof Be=="string"?Be:String(Be??""),Ge=Te.toLowerCase();console.error("Message send failed:",Te||Be),!(Ge.includes("timeout")||Ge.includes("timed out")||Ge.includes("may still be processing")||Ge.includes("being processed")||Ge.includes("failed to fetch")||Ge.includes("networkerror")||Ge.includes("network error")||Ge.includes("gateway timeout")||Ge==="failed to send message")&&(pe.length>0&&Ls.setState({attachedFiles:pe}),se.error(Te||"Message failed to send. Attachments restored."))}),V||N.current?.focus()},Ue=l.useRef($e);Ue.current=$e,l.useEffect(()=>{const R=be.current==="busy"||be.current==="cooldown",Z=U==="idle",ne=b&&ee.has(b)&&(()=>{const Ne=ee.get(b);return Ne?Date.now()-Ne.timestamp<2e3:!1})();R&&Z&&Y.length>0&&!Q.current&&!ne&&(Q.current=!0,setTimeout(()=>{b&&ae&&fe&&Ue.current(),Q.current=!1},100)),be.current=U},[U,Y.length,b,ae,fe,ee]);const We=R=>{if(m&&F.current&&(R.key==="Enter"||R.key==="ArrowUp"||R.key==="ArrowDown"||R.key==="Escape"||R.key==="Tab")){R.preventDefault(),F.current.handleKeyDown(R.key);return}if(y&&I.current&&(R.key==="Enter"||R.key==="ArrowUp"||R.key==="ArrowDown"||R.key==="Escape"||R.key==="Tab")){R.preventDefault(),I.current.handleKeyDown(R.key);return}if(i&&k.current&&(R.key==="Enter"||R.key==="ArrowUp"||R.key==="ArrowDown"||R.key==="Escape"||R.key==="Tab")){R.preventDefault(),k.current.handleKeyDown(R.key);return}if(R.key==="Tab"&&!m&&!i){R.preventDefault(),de();return}if(R.key==="Enter"&&!R.shiftKey&&!V){R.preventDefault();const Z=R.ctrlKey||R.metaKey,ne=mt&&b&&U!=="idle";T?Z||!ne?$e():Ae():Z&&ne?Ae():$e()}},Ze=l.useCallback(()=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null),Ce(!0),Ie.current=setTimeout(()=>{Ce(!1),Ie.current=null},1800)},[]),me=l.useCallback(()=>{q(),Ze(),A()},[A,q,Ze]),de=()=>{const R=oe.filter(Oe=>Px(Oe.mode));if(R.length<=1)return;const ne=(R.findIndex(Oe=>Oe.name===je)+1)%R.length,Ne=R[ne];W(Ne.name),b&&H(b,Ne.name)},we=l.useCallback(()=>{const R=N.current;if(!R)return;R.style.height="auto";const Z=R.ownerDocument?.defaultView,ne=Z?Z.getComputedStyle(R):null,Ne=ne?parseFloat(ne.lineHeight):NaN,Oe=ne?parseFloat(ne.paddingTop):NaN,Re=ne?parseFloat(ne.paddingBottom):NaN,pe=22,Te=Number.isNaN(Oe)||Number.isNaN(Re)?16:Oe+Re,nt=(Number.isNaN(Ne)?pe:Ne)*Fx+Te,ht=R.scrollHeight||R.offsetHeight,Lt=Math.min(ht,nt);R.style.height=`${Lt}px`,R.style.maxHeight=`${nt}px`,S(Ut=>Ut&&Ut.height===Lt&&Ut.maxHeight===nt?Ut:{height:Lt,maxHeight:nt})},[]);l.useLayoutEffect(()=>{we()},[we,t,V]);const Me=l.useCallback((R,Z)=>{if(R.startsWith("/")){const Re=R.indexOf(" "),pe=R.indexOf(`
64
- `),Be=Math.min(Re===-1?R.length:Re,pe===-1?R.length:pe);if(Z<=Be&&Re===-1){const Te=R.substring(1,Be);h(Te),f(!0),c(!1),g(!1)}else f(!1);return}f(!1);const ne=R.substring(0,Z),Ne=ne.lastIndexOf("#");if(Ne!==-1){const Re=Ne>0?ne[Ne-1]:null,pe=ne.substring(Ne+1),Be=pe.includes(" ")||pe.includes(`
65
- `);if((!Re||/\s/.test(Re))&&!Be){x(pe),g(!0),c(!1);return}}g(!1),x("");const Oe=ne.lastIndexOf("@");if(Oe!==-1){const Re=ne.substring(Oe+1);!Re.includes(" ")&&!Re.includes(`
66
- `)?(u(Re),c(!0)):c(!1)}else c(!1)},[x,h,u,g,f,c]),Pe=l.useCallback(R=>{if(!R)return;const Z=N.current;if(!Z){const pe=t+R;n(pe),Me(pe,pe.length),requestAnimationFrame(()=>we());return}const ne=Z.selectionStart??t.length,Ne=Z.selectionEnd??t.length,Oe=`${t.substring(0,ne)}${R}${t.substring(Ne)}`;n(Oe);const Re=ne+R.length;requestAnimationFrame(()=>{const pe=N.current;pe&&(pe.selectionStart=Re,pe.selectionEnd=Re),we()}),Me(Oe,Re)},[we,t,Me]),qe=R=>{const Z=R.target.value,ne=R.target.selectionStart??Z.length;n(Z),we(),Me(Z,ne)},bt=l.useCallback(async R=>{const Z=new Map;Array.from(R.clipboardData.files||[]).forEach(Re=>{Re.type.startsWith("image/")&&Z.set(`${Re.name}-${Re.size}`,Re)}),Array.from(R.clipboardData.items||[]).forEach(Re=>{if(Re.kind==="file"&&Re.type.startsWith("image/")){const pe=Re.getAsFile();pe&&Z.set(`${pe.name}-${pe.size}`,pe)}});const ne=Array.from(Z.values());if(ne.length===0||!b&&!C)return;R.preventDefault();const Ne=R.clipboardData.getData("text");Ne&&Pe(Ne);let Oe=0;for(const Re of ne){const pe=ye.getState().attachedFiles.length;try{await _(Re),ye.getState().attachedFiles.length>pe&&(Oe+=1)}catch(Be){console.error("Clipboard image attach failed",Be),se.error(Be instanceof Error?Be.message:"Failed to attach image from clipboard")}}Oe>0&&se.success(`Attached ${Oe} image${Oe>1?"s":""} from clipboard`)},[_,b,C,Pe]),Et=R=>{const Z=N.current?.selectionStart||0,Ne=t.substring(0,Z).lastIndexOf("@");if(Ne!==-1){const Oe=t.substring(0,Ne)+R.name+t.substring(Z);n(Oe)}c(!1),u(""),N.current?.focus()},Ct=R=>{const ne=N.current?.selectionStart??t.length,Oe=t.substring(0,ne).lastIndexOf("#");if(Oe!==-1){const Re=t.substring(0,Oe)+`#${R} `+t.substring(ne);n(Re);const pe=Oe+R.length+2;requestAnimationFrame(()=>{N.current&&(N.current.selectionStart=pe,N.current.selectionEnd=pe),we(),Me(Re,pe)})}g(!1),x(""),N.current?.focus()},ft=R=>{n(`/${R.name} `);const Z=N.current;Z&&(Z._commandMetadata=R),f(!1),h(""),setTimeout(()=>{N.current&&(N.current.focus(),N.current.setSelectionRange(N.current.value.length,N.current.value.length))},0)};l.useEffect(()=>{b&&N.current&&!V&&N.current.focus()},[b,V]),l.useEffect(()=>{L&&L!==b&&q()},[L,b,q]);const Ye=R=>{R.preventDefault(),R.stopPropagation(),(b||C)&&!o&&a(!0)},wt=R=>{R.preventDefault(),R.stopPropagation(),R.currentTarget===R.target&&a(!1)},Ee=async R=>{if(R.preventDefault(),R.stopPropagation(),a(!1),!b&&!C)return;const Z=Array.from(R.dataTransfer.files);let ne=0;for(const Ne of Z){const Oe=ye.getState().attachedFiles.length;try{await _(Ne),ye.getState().attachedFiles.length>Oe&&(ne+=1)}catch(Re){console.error("File attach failed",Re),se.error(Re instanceof Error?Re.message:"Failed to attach file")}}ne>0&&se.success(`Attached ${ne} file${ne>1?"s":""}`)},_e=l.useCallback(async R=>{let Z=0;for(const ne of R){const Ne=ye.getState().attachedFiles.length;try{await z(ne.path,ne.name),ye.getState().attachedFiles.length>Ne&&(Z+=1)}catch(Oe){console.error("Server file attach failed",Oe),se.error(Oe instanceof Error?Oe.message:"Failed to attach file")}}Z>0&&se.success(`Attached ${Z} file${Z>1?"s":""}`)},[z]),Ve=l.useRef(null),[rt,jt]=l.useState(!1),Rt=l.useCallback(async R=>{let Z=0;const ne=Array.isArray(R)?R:Array.from(R);for(const Ne of ne){const Oe=ye.getState().attachedFiles.length;try{await _(Ne),ye.getState().attachedFiles.length>Oe&&(Z+=1)}catch(Re){console.error("File attach failed",Re),se.error(Re instanceof Error?Re.message:"Failed to attach file")}}Z>0&&se.success(`Attached ${Z} file${Z>1?"s":""}`)},[_]),Tt=l.useCallback(async()=>{try{const Z=await(await fetch("/api/vscode/pick-files")).json(),ne=Array.isArray(Z?.files)?Z.files:[],Ne=Array.isArray(Z?.skipped)?Z.skipped:[];if(Ne.length>0){const Re=Ne.map(pe=>`${pe?.name||"file"}: ${pe?.reason||"skipped"}`).join(`
67
- `);se.error(`Some files were skipped:
68
- ${Re}`)}const Oe=ne.map(Re=>{if(!Re?.dataUrl)return null;try{const[pe,Be]=Re.dataUrl.split(","),Te=Re.mimeType||pe?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Be)return null;const Ge=atob(Be),nt=new Uint8Array(Ge.length);for(let Lt=0;Lt<Ge.length;Lt++)nt[Lt]=Ge.charCodeAt(Lt);const ht=new Blob([nt],{type:Te});return new File([ht],Re.name||"file",{type:Te})}catch(pe){return console.error("Failed to decode VS Code picked file",pe),null}}).filter(Boolean);Oe.length>0&&await Rt(Oe)}catch(R){console.error("VS Code file pick failed",R),se.error(R instanceof Error?R.message:"Failed to pick files in VS Code")}},[Rt]),Qt=l.useCallback(()=>{if(Dt()){Tt();return}Ve.current?.click()},[Tt]),Ar=l.useCallback(async R=>{const Z=R.target.files;Z&&(await Rt(Z),R.target.value="")},[Rt]),Er="gap-x-1.5 gap-y-0",Xs=Dt(),To=V?"px-1.5 py-1.5":Xs?"px-1.5 py-1":"px-2.5 py-1.5",Fo=V?"h-9 w-9":Xs?"h-[22px] w-[22px]":"h-7 w-7",lr=V?"h-5 w-5":Xs?"h-4 w-4":"h-[18px] w-[18px]",cr=O(Fo,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Ir=!V&&le&&re?e.jsx("button",{type:"button",onClick:me,className:O(cr,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Vr,{className:O(lr)})}):e.jsx("button",{type:V?"button":"submit",disabled:!ke||!b&&!C,onPointerDownCapture:R=>{!V||R.pointerType!=="touch"||!ke||!b&&!C||(G.current=!0,R.preventDefault(),R.stopPropagation(),$e())},onClick:R=>{if(V){if(G.current){G.current=!1;return}R.preventDefault(),$e()}},className:O(cr,ke&&(b||C)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(nf,{className:O(lr)})}),tn=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Ve,type:"file",multiple:!0,className:"hidden",onChange:Ar,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(mx,{onFilesSelected:_e,multiSelect:!0,presentation:V?"modal":"dropdown",open:rt,onOpenChange:jt,children:V?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:cr,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(of,{className:O(lr,"text-current")})})}),e.jsxs(Yt,{align:"start",children:[e.jsxs(St,{onSelect:()=>{requestAnimationFrame(()=>Qt())},children:[e.jsx(so,{}),"Attach files"]}),e.jsxs(St,{onSelect:()=>{requestAnimationFrame(()=>{jt(!0)})},children:[e.jsx(af,{}),"Attach from project"]})]})]})]})]}),Po=s?e.jsx("button",{type:"button",onClick:s,className:cr,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(gn,{className:O(lr,"text-current")})}):null,Nn=e.jsxs(e.Fragment,{children:[tn,Po]}),Ro=ie.statusText;l.useEffect(()=>{const R=!!ie.wasAborted;!K.current&&R&&!De&&(Ze(),b&&P(b)),K.current=R},[P,b,De,Ze,ie.wasAborted]),l.useEffect(()=>()=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null)},[]);const Lo=V&&re;return e.jsxs("form",{onSubmit:$e,className:"pt-0 pb-2 md:pb-4 bottom-safe-area","data-keyboard-avoid":"true",style:V&&ue>0&&!ge?{marginBottom:`${ue}px`}:void 0,children:[e.jsx(Cx,{isWorking:ie.isWorking,statusText:Ro,isGenericStatus:ie.isGenericStatus,isWaitingForPermission:ie.isWaitingForPermission,wasAborted:ie.wasAborted,abortActive:ie.abortActive,completionId:ie.lastCompletionId,isComplete:ie.isComplete,showAbort:Lo,onAbort:me,showAbortStatus:De}),e.jsxs("div",{ref:j,className:O("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Ye,onDragLeave:wt,onDrop:Ee,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:cr,onClick:()=>Qt(),title:"Attach files","aria-label":"Attach files",children:e.jsx(so,{className:O(lr,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(ix,{}),e.jsx(Yd,{onEditMessage:R=>{n(R),setTimeout(()=>{N.current?.focus()},0)}}),e.jsxs("div",{className:O("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:xt,children:[m&&e.jsx(Qd,{ref:F,searchQuery:p,onCommandSelect:ft,onClose:()=>f(!1)}),y&&e.jsx(Jd,{ref:I,searchQuery:w,onAgentSelect:Ct,onClose:()=>g(!1)}),i&&e.jsx(lx,{ref:k,searchQuery:d,onFileSelect:Et,onClose:()=>c(!1)}),e.jsx(Cs,{ref:N,"data-chat-input":"true",value:t,onChange:qe,onKeyDown:We,onPaste:bt,onPointerDownCapture:xe,placeholder:b||C?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!b&&!C,className:O("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",V?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:v?`${v.height}px`:void 0,maxHeight:v?`${v.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:O("rounded-b-xl bg-transparent",To,V?"flex items-center gap-x-1.5":O("flex items-center justify-between",Er)),"data-chat-input-footer":"true",children:V?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:Nn}),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(Ol,{className:O("w-full flex items-center justify-end min-w-0")})}),Ir]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:O("flex items-center flex-shrink-0",Er),children:Nn}),e.jsxs("div",{className:O("flex items-center flex-1 justify-end",Er,"md:gap-x-3"),children:[e.jsx(Ol,{className:O("flex-1 min-w-0 justify-end")}),Ir]})]})})]})]})]})};function aa({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:O("bg-accent animate-pulse rounded-xl",s),...r})}const Kl=(s,r,t,n,o=4)=>{const a=[];for(let i=0;i<o;i++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,m=i/o,f=(i+1)/o,p=(v,S,N)=>v+(S-v)*N,h=(v,S,N,j,k,F)=>{const I=p(v,S,k),M=p(j,N,k);return p(I,M,F)},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)},x={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${x.x} ${x.y} Z`,row:i,col:c})}return a},vi=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=Eo();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const i=a?"white":"black",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},x={x:50,y:h},v={x:50-m*f,y:h+m*p},S={x:50+m*f,y:h+m*p},N={x:50,y:h+m},k=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(y.y+g.y+x.y+w.y)/4})`,F=Kl(g,x,N,v),I=Kl(x,w,S,N),M=Se.useMemo(()=>{const b=[];for(let C=0;C<32;C++)b.push(.1+Math.random()*.5);return b},[]);return e.jsxs("svg",{width:r,height:t,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:s,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${x.x} ${x.y} L${g.x} ${g.y} L${v.x} ${v.y} L${N.x} ${N.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),F.map((b,C)=>e.jsx("path",{d:b.path,fill:u,opacity:M[C]},`left-${C}`)),e.jsx("path",{d:`M${x.x} ${x.y} L${w.x} ${w.y} L${S.x} ${S.y} L${N.x} ${N.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),I.map((b,C)=>e.jsx("path",{d:b.path,fill:u,opacity:M[C+16]},`right-${C}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${g.x} ${g.y} L${x.x} ${x.y} L${w.x} ${w.y} Z`,fill:"none",stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${k} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function Rx({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:i=!0,mode:c="popLayout"}){const[d,u]=Se.useState(0),m=Se.Children.toArray(s);Se.useEffect(()=>{if(!i)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,i]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:O("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(lf,{mode:c,initial:!1,children:e.jsx(Rr.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Lx=["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"],Ox=()=>{const s=Eo();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(vi,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Rx,{className:"text-body-md",interval:4,transition:{duration:.5},children:Lx.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},ia=l.memo(Ox),$x={'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"}},_x={'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 nu(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 Zt=({children:s,className:r})=>{const[t,n]=l.useState(!1);return l.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:O("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},Bx=({isUser:s,providerID:r,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=Vd(r);return e.jsx(Zt,{children:e.jsx("div",{className:O("pl-3","mb-2"),children:e.jsx("div",{className:O("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(hs,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:c&&a?e.jsx("img",{src:a,alt:`${r} logo`,className:"h-4 w-4",style:{filter:o?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:i}):e.jsx(Yr,{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:O("font-bold typography-ui-header tracking-tight leading-none",s?"text-primary":"text-foreground"),children:s?"You":n||"Assistant"}),!s&&t&&e.jsx("div",{className:O("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",er(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},zx=l.memo(Bx),Yl=(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},Xl=()=>{if(!Dt()||typeof window>"u")return gl;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=Yl({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=Yl({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return gl},ou=()=>{const[s,r]=l.useState(Xl);return l.useEffect(()=>{if(!Dt()||typeof window>"u")return;const t=n=>{r(Xl())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},au=s=>{const r=[],t=[],n=s.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>r.push(i.innerText.trim()));const o=s.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const c=i.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},iu=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
69
- `)?`"${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(`
70
- `)},Hx=({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(`
71
- `)},Ux=({headers:s,rows:r})=>{if(s.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${s.map(t).join(" | ")} |`),n.push(`| ${s.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=s.map((i,c)=>t(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
72
- `)},Wx=(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)},Vx=({tableRef:s})=>{const[r,t]=l.useState(!1),[n,o]=l.useState(!1),a=l.useRef(null);l.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const i=async c=>{const d=s.current?.querySelector("table");if(d)try{const u=au(d),m=c==="csv"?iu(u):Hx(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(Mt,{className:"size-3.5"}):e.jsx(zs,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("tsv"),children:"TSV"})]})]})},qx=({tableRef:s})=>{const[r,t]=l.useState(!1),n=l.useRef(null);l.useEffect(()=>{const a=i=>{n.current&&!n.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=s.current?.querySelector("table");if(i)try{const c=au(i),d=a==="csv"?iu(c):Ux(c);Wx(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(Wr,{className:"size-3.5"})}),r&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("markdown"),children:"Markdown"})]})]})},Gx=({children:s,className:r})=>{const t=l.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(Vx,{tableRef:t}),e.jsx(qx,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:O("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},Kx=({children:s,className:r,style:t,...n})=>{const[o,a]=l.useState(!1),i=l.useRef(null),c=l.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),x={};for(const v of w){const S=v.indexOf(":");if(S===-1)continue;const N=v.slice(0,S).trim(),j=v.slice(S+1).trim();!N.startsWith("--")||j.length===0||(x[N]=j)}return{value:g,vars:x}},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=()=>i.current&&i.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:O(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(Mt,{className:"size-3.5"}):e.jsx(zs,{className:"size-3.5"})})})]})},lu={pre:Kx,table:Gx},Yx=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const c=ou(),d=l.useMemo(()=>`markdown-${r?.id?`part-${r.id}`:`message-${t}`}`,[t,r?.id]),u=i==="tool"?"streamdown-content streamdown-tool":"streamdown-content",m=e.jsx("div",{className:O("break-words",o),children:e.jsx(qc,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:lu,children:s})});return n?e.jsx(Zt,{children:m},d):m},br=({content:s,className:r,variant:t="assistant"})=>{const n=ou(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:O("break-words",r),children:e.jsx(qc,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:lu,children:s})})},Xx={thinking:{label:"Thinking",Icon:Yr},justification:{label:"Justification",Icon:Ya}},cu=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
73
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
74
- `).trim(),Qx=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
75
- `),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},ji=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>Qx(s),[s]),{label:c,Icon:d}=Xx[r];return l.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:O("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:O("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:O("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(kt,{className:"h-3.5 w-3.5"}):e.jsx(Ss,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className:O("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(tt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},du=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=l.useMemo(()=>cu(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(ji,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},Jx=s=>cu(s),Zx=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=s,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",u=l.useMemo(()=>a?Jx(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=l.useRef(m);if(m||f)return p.current=!0,null;const h=i.time;return!(h&&typeof h.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(ji,{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(Yx,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},ey=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,ty=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,c]=l.useState(!1),[d,u]=l.useState(!1),m=l.useRef(null);l.useEffect(()=>{const h=m.current;if(!h||i)return;const y=()=>{u(h.scrollHeight>h.clientHeight)};y();const g=new ResizeObserver(y);return g.observe(h),()=>g.disconnect()},[a,i]);const f=l.useCallback(()=>{(d||i)&&c(h=>!h)},[d,i]);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:ey(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:O("break-words whitespace-pre-wrap font-sans typography-markdown",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:m,onClick:f,children:p()},s.id||`${r}-user-text`)},sy=l.memo(ty),ry=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},uu=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,ny=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Ql=(s,r)=>!s||typeof s!="object"?String(s):eg(s,r||""),la=(s,r,t)=>{let n=ry(s);if((r==="edit"||r==="multiedit")&&uu(n)&&(n=ny(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},oy=(s,r)=>{try{const t=s.trim().split(`
76
- `).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,c]=a,d=Math.floor(i.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:O("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:qs.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}},ay=(s,r,t)=>{try{const n=s.trim().split(`
77
- `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,c,d,u]=i,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:O("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:qs.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:O("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:O("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}},iy=(s,r,t)=>{try{const n=s.trim().split(`
78
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",u=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:O("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:qs.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:O("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:O("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:O("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))})]},i))]})}catch{return null}},ly=(s,r)=>{try{const t=JSON.parse(s);if(!Array.isArray(t))return null;const n={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const i="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:i,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:i,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:O("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:qs.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mt,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Mt,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||i))})]})]})}catch{return null}},cy=(s,r,t)=>{try{return e.jsx("div",{className:O("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:qs.tool.popup,children:e.jsx(br,{content:s,variant:"tool"})})}catch{return null}},mu=s=>{const r=s.split(`
79
- `);let t="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let m=d,f=o+1;for(;f<r.length&&!r[f].startsWith("@@")&&!r[f].startsWith("Index:");){const p=r[f];p.startsWith("+")?(u.push({type:"added",lineNumber:m,content:p.substring(1)}),m++):p.startsWith("-")?u.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(u.push({type:"context",lineNumber:m,content:p.substring(1)}),m++),f++}n.push({file:t,oldStart:c,newStart:d,lines:u}),o=f;continue}o++}return n},za=(s,r,t)=>Qh(r,s,t),fu=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(cf,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Gc,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(Na,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(ar,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(ms,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(df,{className:r}):t==="glob"?e.jsx(uf,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(Ca,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(Ca,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(mf,{className:r}):t==="skill"?e.jsx(Kc,{className:r}):t.startsWith("git")?e.jsx(ns,{className:r}):e.jsx(Co,{className:r})},dy=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},uy=({start:s,end:r,active:t})=>{const[n,o]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:dy(s,r,n)})},my=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
80
- `);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}},Ha=(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},fy=(s,r,t,n)=>{const o=r,a=o.metadata,i=o.input;if((s.tool==="edit"||s.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return Ha(d,n,t)}if((s.tool==="read"||s.tool==="write")&&i){const d=i?.filePath||i?.file_path||i?.path;if(typeof d=="string")return Ha(d,n,t)}if(s.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
81
- `)[0];return t?d.substring(0,50):d.substring(0,100)}if(s.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);if(s.tool==="skill"&&i?.name&&typeof i.name=="string")return i.name;const c=i?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},Ua=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(tt,{outerClassName:O("w-full min-w-0 flex-none overflow-hidden",r,n),className:O("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})}),py=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"},hy=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),gy=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o})=>{const a=l.useMemo(()=>s.filter(p=>p.state?.status==="completed"),[s]),i=typeof o=="string"?hy(o):"",c=i.length>0,[d,u]=l.useState(!1);if(a.length===0&&!c)return null;const m=r?a:a.slice(-6),f=Math.max(0,a.length-m.length);return e.jsxs("div",{className:O("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:[a.length>0?e.jsx(Ua,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[f>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",f," more…"]}):null,m.map((p,h)=>{const y=typeof p.tool=="string"&&p.tool.trim().length>0?p.tool:"tool",g=py(p),w=di(y).displayName;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:fu(y)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:w}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:g})]},p.id??`${y}-${h}`)})]})}):null,c?e.jsxs("div",{className:O("space-y-1",a.length>0&&"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:p=>p.stopPropagation(),onClick:p=>{p.stopPropagation(),u(h=>!h)},children:[d?e.jsx(kt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Ss,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),d?e.jsx(Ua,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(br,{content:i,variant:"tool"})})}):null]}):null]})},xy=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:mu(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:O("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(Ps,{style:r,language:Cr(typeof t?.file_path=="string"?t.file_path:typeof t?.filePath=="string"?t.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),yy=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
82
- `),a=Cr(t??"")||za(s,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),c=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${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(Ps,{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))})]})},by=({content:s,filePath:r,displayPath:t})=>{const n=Zh(r),o=r.toLowerCase().endsWith(".svg"),a=l.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"}})})]})},wy=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{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,x=y?Md(y):!1,v=w?y?Ha(y,o,n):"New file":null,S=l.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?Ql(u,s.tool):typeof u.content=="string"?u.content??"":Ql(u,s.tool),[u,s.tool]),N=S.trim().length>0,j=(F,I)=>e.jsx(Ua,{maxHeightClass:I?.maxHeightClass,className:I?.className,disableHorizontal:I?.disableHorizontal,outerClassName:I?.outerClassName,children:F}),k=()=>{if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const F=ly(p,{unstyled:!0});return j(F??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 F=oy(p,{unstyled:!0});return j(F??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 F=ay(p,n,{unstyled:!0});return j(F??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 F=iy(p,n,{unstyled:!0});return j(F??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 j(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(br,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const F=cy(p,t,{unstyled:!0});return j(F??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 j(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(br,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return j(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(br,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&(!f&&h||p.trim().length===0||uu(p))&&h)return j(e.jsx(xy,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const F=la(p,s.tool,d),I=F.split(`
83
- `),M=typeof u?.offset=="number"?u.offset:0,b=typeof u?.limit=="number"?u.limit:void 0,C=A=>A.trim().startsWith("(");return j(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:I.map((A,P)=>{const L=C(A),$=M+P+1,q=!L&&(b===void 0||P<b);return e.jsxs("div",{className:O("typography-code font-mono flex w-full min-w-0",L&&"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:q?$:""}),e.jsx("div",{className:"flex-1 min-w-0",children:L?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:A}):e.jsx(Ps,{style:t,language:za(F,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:A})})]},P)})}),{className:"p-1"})}return j(e.jsx(Ps,{style:t,language:za(la(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...qn.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:la(p,s.tool,d)}),{className:"p-1"})}return j(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:O("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:s.tool==="todowrite"||s.tool==="todoread"?k():e.jsxs(e.Fragment,{children:[w&&x?e.jsx("div",{className:"my-1",children:j(e.jsx(by,{content:g,filePath:y,displayPath:v??"New file"}))}):w?e.jsx("div",{className:"my-1",children:j(e.jsx(yy,{content:g,syntaxTheme:t,filePath:y,displayPath:v??"New file"}))}):N?e.jsx("div",{className:"my-1",children:j(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:S}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,s.tool!=="write"&&r.status==="completed"&&"output"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),k()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})},Jn=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=s.state,u=yt(L=>L.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=l.useRef(r);l.useEffect(()=>{!f&&!m||y.current!==r&&(y.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const g=d,w=g.metadata,x=g.input,v=g.time,S=l.useRef({}),N=l.useRef(s.id);if(N.current!==s.id&&(N.current=s.id,S.current={}),m){if(typeof v?.start=="number"){const L=S.current.start;(typeof L!="number"||v.start<L)&&(S.current.start=v.start)}typeof v?.end=="number"&&(S.current.end=v.end)}const j=m?S.current.start??v?.start:v?.start,k=m?S.current.end??v?.end:v?.end,F=l.useMemo(()=>{if(!m)return[];const L=w?.summary;return Array.isArray(L)?L.filter($=>typeof $=="object"&&$!==null):[]},[m,w]),I=l.useRef(F.length);l.useEffect(()=>{m&&I.current!==F.length&&(I.current=F.length,a?.("structural"))},[m,a,F.length]);const M=s.tool==="edit"||s.tool==="multiedit"?my(w):null,b=fy(s,d,o,u),C=di(s.tool).displayName,A=l.useContext(ui),P=L=>{if(m||!A?.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))&&($=x?.filePath||x?.file_path||x?.path||w?.filePath||w?.file_path||w?.path),typeof $=="string"){L.stopPropagation();let q=$;$.startsWith("/")||(q=u.endsWith("/")?u+$:u+"/"+$),A.editor.openFile(q)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:O("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:P,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:L=>{L.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:O("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&h?{color:"var(--status-error)"}:{},children:fu(s.tool)}),e.jsx("div",{className:O("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(kt,{className:"h-3.5 w-3.5"}):e.jsx(Ss,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&h?{color:"var(--status-error)"}:{},children:C})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[b&&e.jsx("span",{className:O("truncate",o&&"max-w-[120px]"),children:b}),M&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",M.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",M.removed]})]}),typeof j=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(uy,{start:j,end:typeof k=="number"?k:void 0,active:!!(m&&p&&typeof k!="number")})})]})]}),m&&(F.length>0||p||f)?e.jsx(gy,{entries:F,isExpanded:r,hasPrevTool:i,hasNextTool:c,output:typeof g.output=="string"?g.output:void 0}):null,!m&&r?e.jsx(wy,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c}):null]})},vy=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
84
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
85
- `).trim(),jy=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=l.useMemo(()=>vy(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(ji,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},Sy=l.memo(jy),ky=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(", ")},Jl=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}),Ny=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},Cy=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=l.useRef(r),[p,h]=l.useState(0);l.useEffect(()=>{if(f.current===r)return;const x=f.current===!1;f.current=r,c?.("structural"),r&&x&&h(v=>v+1)},[r,c]);const y=l.useMemo(()=>Jl(d?s.filter(x=>x.part.id&&u.has(x.id)):s),[s,d,u]),g=ky(y),w=Ny(y);return y.length===0?null:e.jsx(Zt,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:O("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:O("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(xn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:O("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(kt,{className:"h-3.5 w-3.5"}):e.jsx(Ss,{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:O("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((x,v)=>{const S=x.part.id||`group-part-${v}`,N=w[S],j=`${S}-exp${p}`;switch(x.kind){case"tool":return e.jsx(Zt,{children:e.jsx(Jn,{part:x.part,isExpanded:a.has(S),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},j);case"reasoning":return e.jsx(Zt,{children:e.jsx(du,{part:x.part,messageId:x.messageId,onContentChange:c})},j);case"justification":return e.jsx(Zt,{children:e.jsx(Sy,{part:x.part,messageId:x.messageId,onContentChange:c})},j);default:return null}})})]})})},My=l.memo(Cy),Dy=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:O("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),ca=l.memo(Dy),pu=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},hu=s=>{if(s.type!=="text")return!1;const r=pu(s);return!r||r.trim().length===0},Ay=(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"))},Ey=(s,r)=>{const t=l.useRef(null),n=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(s);i.current=s;const c=l.useRef(r);c.current=r;const d=l.useRef(!1),u=r.size>0;return l.useEffect(()=>{s&&s.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const m=i.current;if(!m)return;const f=Array.from(c.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),l.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]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},Iy=new Set(["task"]),Pr=s=>typeof s=="string"&&Iy.has(s.toLowerCase()),Ty=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d,onRevert:u})=>{const[m,f]=l.useState(!1),p=l.useRef(null),h=l.useMemo(()=>r.filter(F=>F.type!=="text"?!1:!hu(F)),[r]),y=d?.token;let g=!1;const w=!!a,x=!!i,v=!!(n??t),S=!!o,N=l.useCallback(()=>{p.current!==null&&typeof window<"u"&&(window.clearTimeout(p.current),p.current=null)},[]),j=l.useCallback(()=>{!v||!w||!S||typeof window>"u"||(N(),f(!0),p.current=window.setTimeout(()=>{f(!1),p.current=null},1800))},[w,N,S,v]);l.useEffect(()=>{S||(f(!1),N())},[N,S]);const k=l.useCallback(F=>{!a||!S||(F.stopPropagation(),F.preventDefault(),a(),v&&j())},[S,v,a,j]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:v&&w&&S?j:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:h.map((F,I)=>{let M;return d&&y&&!g&&pu(F).includes(y)&&(M=d,g=!0),e.jsx(Zt,{children:e.jsx(sy,{part:F,messageId:s,isMobile:t,agentMention:M})},`user-text-${I}`)})}),e.jsx(Gd,{files:r,onShowPopup:c}),w&&S||u?e.jsxs("div",{className:O("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",m&&"opacity-100 pointer-events-auto"),children:[u&&e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Revert to this message",onPointerDown:F=>F.stopPropagation(),onClick:F=>{F.stopPropagation(),u()},children:e.jsx(Yc,{className:"h-3.5 w-3.5"})})}),e.jsx(Xe,{sideOffset:6,children:"Revert from here"})]}),w&&S&&e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":m||x?"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:F=>F.stopPropagation(),onClick:k,onFocus:()=>f(!0),onBlur:()=>{x||f(!1)},children:x?e.jsx(Mt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(zs,{className:"h-3.5 w-3.5"})})}),e.jsx(Xe,{sideOffset:6,children:"Copy message"})]})]}):null]})},Fy=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,syntaxTheme:o,isMobile:a,hasTouchInput:i,expandedTools:c,onToggleTool:d,onShowPopup:u,streamPhase:m,allowAnimation:f,onContentChange:p,hasTextContent:h=!1,onCopyMessage:y,copiedMessage:g=!1,onAuxiliaryContentComplete:w,showReasoningTraces:x=!1,turnGroupingContext:v,errorMessage:S})=>{const[N,j]=l.useState(!1),k=l.useRef(null),F=!!y,I=!!g,M=!!(i??a),b=!t,C=l.useMemo(()=>r.filter(de=>!hu(de)).filter(de=>de.type!=="compaction"),[r]),A=l.useMemo(()=>C.filter(de=>de.type==="tool"),[C]),P=l.useMemo(()=>C.filter(de=>de.type==="text"),[C]),L=ye(de=>de.createSessionFromAssistantMessage),$=Fe(de=>de.openMultiRunLauncherWithPrompt),q=v?.isLastAssistantInTurn??!1,ee=n==="stop",ce=A.length>0,_=l.useMemo(()=>A.some(de=>{const Me=(de.state??{})?.status;return Me==="pending"||Me==="running"||Me==="started"}),[A]),z=l.useCallback(de=>{const we=de.state??{},Me=we?.status;if(Me==="pending"||Me==="running"||Me==="started")return!1;const Pe=we?.time??{},qe=typeof Pe?.end=="number"?Pe.end:void 0,bt=typeof Pe?.start=="number"?Pe.start:void 0;return!(typeof qe!="number"||typeof bt=="number"&&qe<bt)},[]),D=l.useMemo(()=>A.length===0?!0:_?!1:A.every(de=>z(de)),[A,_,z]),H=l.useMemo(()=>P.length===0?!0:P.every(de=>typeof de.time?.end=="number"),[P]),X=l.useMemo(()=>C.filter(de=>de.type==="reasoning"),[C]),he=l.useMemo(()=>X.length===0?!0:X.every(de=>typeof de.time?.end=="number"),[X]),ae=typeof n!="string",fe=X.length>0&&ce&&(_||ae||!D),je=l.useMemo(()=>ce?P.length===0?ae||_||!D:!0:P.length>0?fe:!1,[P.length,ae,_,ce,fe,D]),W=b||je&&(!H||!D||_||ae)||fe,te=b||ce&&(_||ae||!D),oe=b||fe,V=ce||X.length>0,ue=P.length===0,ge=V&&ue&&!te&&!oe&&D&&he,ie=l.useRef(!1),De=l.useRef(!1);l.useEffect(()=>{De.current=!1},[s]),l.useEffect(()=>{if(!ge){ie.current=!1;return}ie.current||(ie.current=!0,w?.())},[ge,w]),l.useEffect(()=>{if(b){De.current=!1;return}if(ce){De.current=!1;return}X.length!==0&&(oe||!he||De.current||(De.current=!0,p?.("structural")))},[b,ce,p,he,X.length,oe]);const Ce=!!h&&!b,Ie=l.useCallback(()=>{k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null)},[]),K=l.useCallback(()=>{!M||!F||!Ce||typeof window>"u"||(Ie(),j(!0),k.current=window.setTimeout(()=>{j(!1),k.current=null},1800))},[F,Ie,Ce,M]);l.useEffect(()=>{Ce||(j(!1),Ie())},[Ie,Ce]);const G=l.useCallback(de=>{!y||!Ce||(de.stopPropagation(),de.preventDefault(),y(),M&&K())},[Ce,M,y,K]),T=l.useCallback(de=>{de.stopPropagation(),de.preventDefault(),L&&L(s)},[L,s]),Y=l.useCallback(de=>{de.stopPropagation(),de.preventDefault();const we=li(P);if(!we.trim())return;const Me=`${ph}
86
-
87
- ${we}`;$(Me)},[P,$]);l.useEffect(()=>()=>{Ie()},[Ie]);const E=l.useMemo(()=>{const de={},we=A.filter(Me=>Pr(Me.tool)||te?!1:z(Me));return we.forEach((Me,Pe)=>{de[Me.id]={hasPrev:Pe>0,hasNext:Pe<we.length-1}}),de},[A,te,z]),B=l.useMemo(()=>v?.activityParts??[],[v]),U=l.useMemo(()=>v?B.filter(de=>de.messageId===s):[],[B,s,v]),be=l.useMemo(()=>v?v.activityGroupSegments.filter(de=>de.anchorMessageId===s):[],[s,v]),Q=l.useMemo(()=>{const de=new Map;return U.forEach(we=>{de.set(we.part,we)}),de},[U]),xe=l.useMemo(()=>v?(x?B:B.filter(we=>we.kind==="tool")).filter(we=>{if(we.kind!=="tool")return!0;const Me=we.part.tool;return!Pr(Me)}):[],[B,x,v]),[He,Ke]=l.useState(!1);l.useEffect(()=>{if(!v)return;const de=v.activityGroupSegments.some(we=>we.afterToolPartId!==null);(xe.length>1||de&&xe.length>0)&&Ke(!0)},[v,xe.length]);const ze=!!(v&&He),st=l.useMemo(()=>{if(!v)return[];if(!ze)return[];if(!v.isWorking)return[];const de=[];return U.forEach(we=>{if(v.previewedPartIds.has(we.id)||!x&&we.kind!=="tool")return;const Me=we.part;if(we.kind==="tool"){const Pe=Me;if(Pr(Pe.tool)||te||!z(Pe))return}else if(we.kind==="reasoning"){if(!x||oe||typeof Me.time?.end!="number")return}else if(we.kind==="justification"&&(!x||W||typeof Me.time?.end!="number"))return;de.push(we)}),de},[U,z,W,oe,te,x,ze,v]),it=l.useMemo(()=>{const de=new Set;return st.forEach(we=>{de.add(we.id)}),de},[st]),{isAnimating:at}=Ey(v,it),ct=!!(v&&ze&&xe.length>0&&be.length>0),ut=l.useMemo(()=>A.filter(de=>Pr(de.tool)),[A]),pt=l.useMemo(()=>{const de=[],we=Pe=>{!v||!ct||be.filter(qe=>(qe.afterToolPartId??null)===Pe).forEach(qe=>{const bt=x?qe.parts:qe.parts.filter(Et=>Et.kind==="tool");bt.length!==0&&de.push(e.jsx(My,{parts:bt,isExpanded:v.isGroupExpanded,onToggle:v.toggleGroup,syntaxTheme:o,isMobile:a,expandedTools:c,onToggleTool:d,onShowPopup:u,onContentChange:p,isWorking:v.isWorking,previewedPartIds:v.previewedPartIds,diffStats:v.diffStats},`progressive-group-${qe.id}`))})};we(null),ut.forEach(Pe=>{de.push(e.jsx(Zt,{children:e.jsx(Jn,{part:Pe,isExpanded:c.has(Pe.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Pe.id}`)),we(Pe.id)});const Me=[];return C.forEach((Pe,qe)=>{const bt=Q.get(Pe);if(!bt||!v)return;let Et=null,Ct=null;if(!ze){if(bt.kind==="tool"){const Ye=Pe;if(Pr(Ye.tool))return;const Ee=Ye.state?.time,_e=z(Ye);if(!(!te&&_e))return;const rt=E[Ye.id];Ct=e.jsx(Zt,{children:e.jsx(Jn,{part:Ye,isExpanded:c.has(Ye.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:rt?.hasPrev??!1,hasNextTool:rt?.hasNext??!1})},`tool-${Ye.id}`),Et=_e&&typeof Ee?.end=="number"?Ee.end:null}Ct&&Me.push({part:Pe,index:qe,endTime:Et,element:Ct});return}if(!v.isWorking||v.isGroupExpanded||v.previewedPartIds.has(bt.id)||!x&&bt.kind!=="tool")return;const ft=it.has(bt.id);switch(bt.kind){case"tool":{const Ye=Pe;if(Pr(Ye.tool))break;const Ee=Ye.state?.time,_e=z(Ye);if(!(!te&&_e))break;const rt=E[Ye.id],jt=e.jsx(Zt,{children:e.jsx(Jn,{part:Ye,isExpanded:c.has(Ye.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:rt?.hasPrev??!1,hasNextTool:rt?.hasNext??!1})},`tool-${Ye.id}`);Ct=ft?e.jsx(ca,{isMigrating:at,children:jt},`migrating-tool-${Ye.id}`):jt,Et=_e&&typeof Ee?.end=="number"?Ee.end:null;break}case"reasoning":{if(!x)break;const Ye=Pe.time,wt=typeof Ye?.end=="number";if(!(wt&&!oe))break;const _e=e.jsx(Zt,{children:e.jsx(du,{part:Pe,messageId:s,onContentChange:p})},`reasoning-${qe}`);Ct=ft?e.jsx(ca,{isMigrating:at,children:_e},`migrating-reasoning-${qe}`):_e,Et=wt?Ye?.end??null:null;break}case"justification":{if(!x)break;const Ye=Pe.time,wt=typeof Ye?.end=="number";if(!(wt&&!W))break;const _e=e.jsx(Zt,{children:e.jsx(Zx,{part:Pe,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:p,renderAsReasoning:!0})},`assistant-text-${qe}`);Ct=ft?e.jsx(ca,{isMigrating:at,children:_e},`migrating-text-${qe}`):_e,Et=wt?Ye?.end??null:null;break}}Ct&&Me.push({part:Pe,index:qe,endTime:Et,element:Ct})}),Me.sort((Pe,qe)=>Pe.endTime===null&&qe.endTime===null?Pe.index-qe.index:Pe.endTime===null?1:qe.endTime===null?-1:Pe.endTime-qe.endTime),Me.forEach(({element:Pe})=>{de.push(Pe)}),de},[Q,be,c,at,a,z,s,p,u,d,it,W,oe,te,ze,x,o,E,v,C,ut,ct]),vt=v?.turnId,xt=ye(de=>de.currentSessionId),mt=ot(de=>{if(!vt||!xt)return;const we=de.messages.get(xt);if(!we)return;const Me=we.find(bt=>bt.info?.id===vt);if(!Me)return;const qe=Me.info.summary?.body;return typeof qe=="string"&&qe.trim().length>0?qe:void 0}),J=typeof v?.summaryBody=="string"&&v.summaryBody.trim().length>0?v.summaryBody:mt,ke=l.useRef(void 0);J&&J.trim().length>0&&(ke.current=J);const re=l.useRef(vt);re.current!==vt&&(re.current=vt,ke.current=void 0);const le=ke.current,Ae=v?.isLastAssistantInTurn&&le&&le.trim().length>0,$e=!!S,Ue=q&&h&&(ee||!!S),[We,Ze]=l.useState(!1),me=e.jsxs(e.Fragment,{children:[e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:de=>de.stopPropagation(),onClick:T,children:e.jsx(ff,{className:"h-4 w-4"})})}),e.jsx(Xe,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:de=>de.stopPropagation(),onClick:Y,children:e.jsx(zd,{className:"h-4 w-4"})})}),e.jsx(Xe,{sideOffset:6,children:"Start new multi-run from this answer"})]}),y&&e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{type:"button",variant:"ghost",size:"icon","data-visible":N||I?"true":void 0,className:O("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",!Ce&&"opacity-50"),disabled:!Ce,"aria-label":"Copy message text","aria-hidden":!Ce,onPointerDown:de=>de.stopPropagation(),onClick:G,onFocus:()=>{Ce&&j(!0)},onBlur:()=>{I||j(!1)},children:I?e.jsx(Mt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(zs,{className:"h-3.5 w-3.5"})})}),e.jsx(Xe,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:O("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:M&&F&&Ce?K: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:[pt,$e&&e.jsx(Zt,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(br,{content:S??""})})},"assistant-error"),Ae&&e.jsx(Zt,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ze(!0),onMouseLeave:()=>Ze(!1),children:[e.jsx(br,{content:le}),Ue&&e.jsx("div",{className:O("mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",We&&"opacity-100 pointer-events-auto"),children:me})]})},"summary-body")]}),e.jsx(Gd,{files:r,onShowPopup:u}),!Ae&&Ue&&e.jsx("div",{className:"mt-2 mb-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",children:me})]})})},Py=({isUser:s,...r})=>s?e.jsx(Ty,{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}):e.jsx(Fy,{...r}),Zl=l.memo(Py),da=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}},Ry=l.lazy(()=>Ks(()=>import("./ToolOutputDialog-CBMeCbbW.js"),__vite__mapDeps([2,0,1,3,4]))),Ly=new Set(["task","edit","multiedit","write","bash"]),ec=s=>typeof s=="string"&&Ly.has(s.toLowerCase());function ua(s){const r=l.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 Hs=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},Oy=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=Nt(),{currentTheme:u}=Dr(),m=l.useRef(null),f=ye(Ja(Ee=>({lifecyclePhase:Ee.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const _e=s.info.sessionID??Ee.currentSessionId??null;return _e?(Ee.streamingMessageIds.get(_e)??null)===s.info.id:!1})(),currentSessionId:Ee.currentSessionId,getCurrentAgent:Ee.getCurrentAgent,getSessionAgentSelection:Ee.getSessionAgentSelection,getAgentModelForSession:Ee.getAgentModelForSession,getSessionModelSelection:Ee.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:y,getCurrentAgent:g,getSessionAgentSelection:w,getAgentModelForSession:x,getSessionModelSelection:v}=f,S=lt(Ee=>Ee.providers),N=Fe(Ee=>Ee.showReasoningTraces),j=Fe(Ee=>Ee.toolCallExpansion);l.useEffect(()=>{y&&tr.getInstance().recordSessionStart(y)},[y]);const[k,F]=l.useState(null),[I,M]=l.useState(!1),[b,C]=l.useState(new Set),[A,P]=l.useState({open:!1,title:"",content:""});l.useEffect(()=>{C(new Set)},[s.info.id,j]);const $=l.useMemo(()=>da(s.info),[s.info]).isUser,q=l.useMemo(()=>$?s.parts.map(Ee=>Ee.type==="compaction"?{type:"text",text:"/summarize"}:Ee):s.parts,[$,s.parts]),ee=l.useMemo(()=>{if($||!r)return null;const Ee=Hs(r.info,"clientRole"),_e=Hs(r.info,"role");if((typeof Ee=="string"?Ee:typeof _e=="string"?_e:void 0)!=="user")return null;const rt=Hs(r.info,"mode"),jt=Hs(r.info,"providerID"),Rt=Hs(r.info,"modelID"),Tt=typeof rt=="string"&&rt.trim().length>0?rt:void 0,Qt=typeof jt=="string"&&jt.trim().length>0?jt:void 0,Ar=typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0;return!Tt&&!Qt&&!Ar?null:{agentName:Tt,providerId:Qt,modelId:Ar}},[$,r]),ce=l.useMemo(()=>{if($)return;const Ee=Hs(s.info,"mode");if(typeof Ee=="string"&&Ee.trim().length>0)return Ee;if(ee?.agentName)return ee.agentName;const _e=s.info.sessionID;if(!_e)return;const Ve=g(_e);return Ve||(w(_e)??void 0)},[$,s.info,ee,g,w]),_=s.info.sessionID,z=$?null:Hs(s.info,"providerID"),D=$?null:Hs(s.info,"modelID"),H=l.useMemo(()=>{if($||!_)return null;if(ee?.providerId&&ee?.modelId)return{providerId:ee.providerId,modelId:ee.modelId};if(ce){const _e=x(_,ce);if(_e?.providerId&&_e?.modelId)return _e}const Ee=v(_);return Ee?.providerId&&Ee?.modelId?Ee:null},[$,_,ce,ee,x,v]),X=l.useMemo(()=>$?null:typeof z=="string"&&z.trim().length>0?z:H?.providerId??null,[$,z,H]),he=l.useMemo(()=>$?null:typeof D=="string"&&D.trim().length>0?D:H?.modelId??null,[$,D,H]),ae=l.useMemo(()=>{if(!$&&X&&he&&S.length>0){const Ee=S.find(_e=>_e.id===X);if(Ee?.models&&Array.isArray(Ee.models)){const rt=Ee.models.find(jt=>jt.id===he)?.name;return typeof rt=="string"?rt:void 0}}},[$,X,he,S]),fe=ua(ce),je=ua(X??void 0),W=ua(ae),te=fe??void 0,oe=je??null,V=W??void 0,ue=l.useMemo(()=>{const Ee=s.info.time;return typeof Ee?.completed=="number"?Ee.completed:null},[s.info.time]),ge=l.useMemo(()=>$?!0:!!(ue&&ue>0),[$,ue]),ie=l.useMemo(()=>{const Ee=s.info.finish;return typeof Ee=="string"?Ee:void 0},[s.info]),De=l.useMemo(()=>Ay(q,{includeReasoning:N}),[q,N]),Ce=l.useMemo(()=>$||ge?De:[],[$,ge,De]),Ie=l.useMemo(()=>$?[]:De.filter(Ee=>Ee.type==="text"),[$,De]),K=l.useMemo(()=>$?[]:De.filter(_e=>_e.type==="tool"),[$,De]),G=l.useMemo(()=>{if(j==="collapsed"||j==="activity")return b;const Ee=new Set;for(const Ve of K){const rt=Ve.tool;Ve.id&&ec(rt)&&Ee.add(Ve.id)}if(i?.isFirstAssistantInTurn)for(const Ve of i.activityParts){if(Ve.kind!=="tool")continue;const rt=Ve.part;rt.id&&ec(rt.tool)&&Ee.add(rt.id)}const _e=new Set(Ee);for(const Ve of b)_e.has(Ve)?_e.delete(Ve):_e.add(Ve);return _e},[b,j,K,i]),T=l.useMemo(()=>{if(!$)return;const Ee=s.parts.find(jt=>jt.type==="agent");if(!Ee)return;const _e=Ee,Ve=typeof _e.name=="string"?_e.name:void 0;if(!Ve)return;const rt=_e.source&&typeof _e.source.value=="string"&&_e.source.value.trim().length>0?_e.source.value:`#${Ve}`;return{name:Ve,token:rt}},[$,s.parts]),Y=typeof ie!="string",E=l.useMemo(()=>$?!1:Ie.length===0||K.length===0?Y:!0,[Ie.length,K.length,Y,$]),B=u?.metadata.variant,U=l.useMemo(()=>B?B==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[B]),be=l.useMemo(()=>u?nu(u):U?$x:_x,[u,U]),Q=l.useMemo(()=>$?!1:tr.getInstance().shouldAnimateMessage(s.info,y||s.info.sessionID),[s.info,y,$]),xe=l.useRef(!1),He=l.useMemo(()=>r?da(r.info):null,[r]),Ke=l.useMemo(()=>t?da(t.info):null,[t]),ze=l.useMemo(()=>$||!Ke?!1:!Ke.isUser&&Ke.role==="assistant",[$,Ke]),st=l.useMemo(()=>ge?"completed":p||(h?"streaming":"completed"),[ge,p,h]),it=l.useMemo(()=>{if($)return!0;const Ee=i?.headerMessageId;if(Ee){if(s.info.id===Ee){if(st==="completed")return!0;const Ve=st==="streaming"||st==="cooldown",rt=xe.current;return Ve&&!rt&&(xe.current=!0),rt||Ve}return!1}return He?He.isUser:!0},[$,He,i,st,s.info]),at=l.useCallback(Ee=>{navigator.clipboard.writeText(Ee),F(Ee),setTimeout(()=>F(null),2e3)},[]),ct=i?.turnId,ut=ot(Ee=>{if(!ct)return;const _e=s.info.sessionID;if(!_e)return;const Ve=Ee.messages.get(_e);if(!Ve)return;const rt=Ve.find(Tt=>Tt.info?.id===ct);if(!rt)return;const Rt=rt.info.summary?.body;return typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0}),pt=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:ut,vt=l.useRef(void 0);pt&&pt.trim().length>0&&(vt.current=pt);const xt=l.useRef(ct);xt.current!==ct&&(xt.current=ct,vt.current=void 0);const mt=vt.current,J=l.useMemo(()=>{if($)return;const Ee=s.info?.error;if(!Ee)return;const _e=typeof Ee.data?.message=="string"?Ee.data.message:void 0,Ve=typeof Ee.message=="string"?Ee.message:void 0,rt=typeof Ee.name=="string"?Ee.name:void 0,jt=_e||Ve||rt;if(jt)return`Opencode failed to send message with error:
88
- \`${jt}\``},[$,s.info]),ke=l.useMemo(()=>$?Ce.filter(Ve=>Ve.type==="text").map(Ve=>(Ve.text||Ve.content||"").trim()).filter(Ve=>Ve.length>0).join(`
89
- `).replace(/\n\s*\n+/g,`
90
- `):J&&J.trim().length>0?J:mt&&mt.trim().length>0?mt:li(Ce),[J,mt,Ce,$]),re=ke.length>0,le=l.useCallback(()=>{navigator.clipboard.writeText(ke),M(!0),setTimeout(()=>M(!1),2e3)},[ke]),Ae=ye(Ee=>Ee.revertToMessage),$e=l.useCallback(()=>{!_||!s.info.id||Ae(_,s.info.id)},[_,s.info.id,Ae]),Ue=l.useCallback(Ee=>{C(_e=>{const Ve=new Set(_e);return Ve.has(Ee)?Ve.delete(Ee):Ve.add(Ee),Ve})},[]),We=o??null,Ze=l.useRef(!1),me=l.useRef(!1),de=l.useRef(!1),we=l.useRef(!1),Me=l.useRef(!1);l.useEffect(()=>{me.current=!1,de.current=!1,we.current=!1,Me.current=!1,Ze.current=!1},[s.info.id]);const Pe=l.useCallback(()=>{$||Ze.current||(Ze.current=!0,n?.("structural"))},[$,n]),qe=l.useCallback(Ee=>{Ee.image&&P(Ee)},[]),bt=l.useCallback(Ee=>{P(_e=>({..._e,open:Ee}))},[]),Et=!!Hs(s.info,"animationSettled"),Ct=st==="streaming",ft=l.useMemo(()=>$?!1:De.some(Ee=>Ee.type==="reasoning"),[$,De]),Ye=Q&&!Et&&!Ct,wt=!$&&Q&&Ie.length>0&&!E;return l.useEffect(()=>{if(We?.onStreamingCandidate){if(!wt){de.current&&(ft&&We?.onReasoningBlock?We.onReasoningBlock():We?.onReservationCancelled&&We.onReservationCancelled(),de.current=!1);return}Me.current||(Me.current=!0,We.onStreamingCandidate(),de.current=!0)}},[We,wt,ft]),l.useEffect(()=>{We?.onAnimationStart&&Ye&&(we.current||(We.onAnimationStart(),we.current=!0))},[We,Ye]),l.useEffect(()=>{if($)return;const Ee=We?.onAnimatedHeightChange;if(!Ee||!(Ye||wt))return;const Ve=m.current;if(!Ve)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Ee(Ve.getBoundingClientRect().height);return}let rt=null;const jt=Tt=>{if(typeof window>"u"){Ee(Tt);return}rt!==null&&window.cancelAnimationFrame(rt),rt=window.requestAnimationFrame(()=>{Ee(Tt)})},Rt=new ResizeObserver(Tt=>{const Qt=Tt[0];Qt&&jt(Qt.contentRect.height)});return Rt.observe(Ve),jt(Ve.getBoundingClientRect().height),()=>{rt!==null&&(window.cancelAnimationFrame(rt),rt=null),Rt.disconnect()}},[Ye,$,We,wt]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:O("group w-full",it?"pt-2":"pt-0",$?"pb-2":ze?"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:$?e.jsx(Zt,{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(Zl,{messageId:s.info.id,parts:De,isUser:$,isMessageCompleted:ge,messageFinish:ie,syntaxTheme:be,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:at,expandedTools:b,onToggleTool:Ue,onShowPopup:qe,streamPhase:st,allowAnimation:Ye,onContentChange:n,shouldShowHeader:!1,hasTextContent:re,onCopyMessage:le,copiedMessage:I,showReasoningTraces:N,onAuxiliaryContentComplete:Pe,agentMention:T,onRevert:$e,errorMessage:J})})})}):e.jsxs("div",{children:[it&&e.jsx(zx,{isUser:$,providerID:oe,agentName:te,modelName:V,isDarkTheme:U}),e.jsx(Zl,{messageId:s.info.id,parts:De,isUser:$,isMessageCompleted:ge,messageFinish:ie,syntaxTheme:be,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:at,expandedTools:G,onToggleTool:Ue,onShowPopup:qe,streamPhase:st,allowAnimation:Ye,onContentChange:n,shouldShowHeader:it,hasTextContent:re,onCopyMessage:le,copiedMessage:I,onAuxiliaryContentComplete:Pe,showReasoningTraces:N,agentMention:T,turnGroupingContext:i,errorMessage:J})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(Ry,{popup:A,onOpenChange:bt,syntaxTheme:be,isMobile:c})})]})},$y=l.memo(Oy),_y=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:mu(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file||t?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:O("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(Ps,{style:r,language:Cr(t||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),By=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
91
- `),o=Cr(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(n.length,1),c=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${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(Ps,{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))})]})},zy=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(Ws,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Gc,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(ar,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(Ca,{className:r}):e.jsx(Co,{className:r})},Hy=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},Uy=({permission:s,onResponse:r})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=ye(),{currentTheme:c}=Dr(),d=l.useMemo(()=>nu(c),[c]),u=async x=>{n(!0);try{await i(s.sessionID,s.id,x),a(!0),r?.(x)}catch{}finally{n(!1)}};if(o)return null;const m=s.type||"Unknown Tool",f=m.toLowerCase(),p=(x,v="")=>{const S=s.metadata[x];return typeof S=="string"?S:typeof S=="number"?String(S):v},h=x=>{const v=s.metadata[x];return typeof v=="number"?v:void 0},y=x=>!!s.metadata[x],g=Hy(m),w=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const S=p("command")||p("cmd")||p("script"),N=p("description"),j=p("cwd")||p("working_directory")||p("directory")||p("path"),k=h("timeout"),F=s.title===S;return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),j&&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:j})]}),k&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",k,"ms"]}),S&&!F&&e.jsx("div",{children:e.jsx(Ps,{language:"bash",style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:S})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("changes")||p("diff"),j=y("replace_all")||y("replaceAll");return e.jsxs(e.Fragment,{children:[j&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),N&&e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(_y,{diff:N,syntaxTheme:d,filePath:S})})]})}if(f==="write"||f==="create"||f==="file_write"){const S=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(By,{content:N,syntaxTheme:d,filePath:S})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const S=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",j=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,k=p("body")||p("data")||p("payload"),F=h("timeout"),I=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[S&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:N}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:S})]})]}),j&&Object.keys(j).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(tt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Ps,{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(j,null,2)})})]}),k&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(tt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Ps,{language:typeof k=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof k=="object"?JSON.stringify(k,null,2):String(k)})})]}),(F||I)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[F&&e.jsxs("span",{children:["Timeout: ",F,"ms"]}),F&&I&&e.jsx("span",{children:" • "}),I&&e.jsxs("span",{children:["Response format: ",I]})]})]})}const x=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}),x&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(tt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(x)})})]}),Object.keys(s.metadata).length>0&&!x&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(tt,{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(Ur,{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:[zy(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:g})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[(()=>{let x="",v="text",S=!1;f==="bash"||f==="shell"||f==="shell_command"?(x=p("command")||p("cmd")||p("script"),v="bash",S=!0):f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"||f==="write"||f==="create"||f==="file_write"?(x=p("path")||p("file_path")||p("filename")||p("filePath"),S=!1):(f==="webfetch"||f==="fetch")&&(x=p("url")||p("uri")||p("endpoint"),S=!1);const N=s.title===x;return N&&x&&S?e.jsx("div",{className:"mb-3",children:e.jsx(Ps,{language:v,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:x})}):N&&x&&!S?e.jsx("div",{className:"mb-3",children:e.jsx("code",{className:"typography-ui-label px-2 py-1 bg-muted/30 rounded block break-all",children:x})}):s.title?e.jsx("div",{className:O("typography-ui-label text-foreground mb-3",(S||x)&&"font-mono"),children:s.title}):null})(),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:O("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Mt,{className:"h-3 w-3"}),"Allow Once"]}),e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:O("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(hn,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:O("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(zt,{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"})})]})]})})})},Wy=new Set(["task"]),tc=s=>typeof s=="string"&&Wy.has(s.toLowerCase()),Vy=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},qy=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}}},Gy=s=>{const r=qy(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let x=0,v=0,S=0;o.forEach(N=>{if(!N)return;const j=typeof N.additions=="number"?N.additions:0,k=typeof N.deletions=="number"?N.deletions:0;(j!==0||k!==0)&&(S+=1),x+=j,v+=k}),S>0&&(t={additions:x,deletions:v,files:S})}let a=!1,i=!1;s.assistantMessages.forEach(x=>{x.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(i=!0)})});const c=[];let d=0;s.assistantMessages.forEach(x=>{const v=x.info.id;x.info.finish,x.parts.forEach(S=>{const N=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-activity-${d++}`;if(S.type==="tool"){const k=S.state?.time,F=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:s.turnId,messageId:v,kind:"tool",part:S,endedAt:F});return}if(S.type==="reasoning"){const j=S.text??S.content;if(typeof j!="string"||j.trim().length===0)return;const k=S.time,F=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:s.turnId,messageId:v,kind:"reasoning",part:S,endedAt:F});return}})});const u=[],m=new WeakMap;c.forEach(x=>{m.set(x.part,x)});const f=new Map,p=[],h=new Map;let y=null;s.assistantMessages.forEach(x=>{const v=x.info.id;x.parts.forEach(S=>{if(S.type==="tool"){const k=S.tool;if(tc(k)){const F=typeof S.id=="string"&&S.id.trim().length>0?S.id:`${v}-task-${p.length+1}`;f.has(F)||(f.set(F,v),p.push(F)),y=F;return}}const N=m.get(S);if(!N)return;if(N.kind==="tool"){const k=N.part.tool;if(tc(k))return}const j=h.get(y)??[];j.push(N),h.set(y,j)})});const g=x=>{if(x.length===0)return;const v=new Map;x.forEach(j=>{v.set(j.messageId,(v.get(j.messageId)??0)+1)});let S,N=0;for(const j of s.assistantMessages){const k=v.get(j.info.id)??0;if(k>0&&!S&&(S=j.info.id),N+=k,N>=2)return j.info.id}return S};return[null,...p].forEach(x=>{const v=h.get(x)??[];if(v.length===0)return;const S=x===null?g(v):f.get(x);S&&u.push({id:`${s.turnId}:${S}:${x??"start"}`,anchorMessageId:S,afterToolPartId:x,parts:v})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:i,summaryBody:r,diffStats:t}},Ky=s=>{const{isWorking:r}=wi(),t=l.useMemo(()=>Vy(s),[s]),n=l.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=l.useMemo(()=>{const g=new Map;return t.forEach(w=>{g.set(w.userMessage.info.id,w),w.assistantMessages.forEach(x=>{g.set(x.info.id,w)})}),g},[t]),a=l.useMemo(()=>{const g=new Map;return t.forEach(w=>{g.set(w.turnId,Gy(w))}),g},[t]),[i,c]=l.useState(()=>new Map),d=Fe(g=>g.toolCallExpansion),u=d==="activity"||d==="detailed";l.useEffect(()=>{c(new Map)},[d]);const m=l.useCallback(g=>{const w=i.get(g);return w||{isExpanded:u,previewedPartIds:new Set}},[i,u]),f=l.useCallback(g=>{c(w=>{const x=new Map(w),v=x.get(g)??{isExpanded:u,previewedPartIds:new Set};return x.set(g,{...v,isExpanded:!v.isExpanded}),x})},[u]),p=l.useCallback((g,w)=>{w.length!==0&&c(x=>{const v=new Map(x),S=v.get(g)??{isExpanded:u,previewedPartIds:new Set},N=new Set(S.previewedPartIds);return w.forEach(j=>{j&&j.trim().length>0&&N.add(j)}),v.set(g,{...S,previewedPartIds:N}),v})},[u]),h=l.useCallback(g=>o.get(g),[o]),y=l.useCallback(g=>{const w=o.get(g);if(!w||!w.assistantMessages.some(q=>q.info.id===g))return;const v=a.get(w.turnId),S=v?.activityParts??[],N=v?.activityGroupSegments??[],j=!!v?.hasTools,k=!!v?.hasReasoning,F=v?.summaryBody,I=v?.diffStats,M=w.assistantMessages[0]?.info.id,b=g===M,C=w.assistantMessages[w.assistantMessages.length-1]?.info.id,A=g===C,P=M,L=m(w.turnId),$=r&&n===w.turnId;return{turnId:w.turnId,isFirstAssistantInTurn:b,isLastAssistantInTurn:A,summaryBody:F,activityParts:S,activityGroupSegments:N,headerMessageId:P,hasTools:j,hasReasoning:k,diffStats:I,isWorking:$,isGroupExpanded:L.isExpanded,previewedPartIds:L.previewedPartIds,toggleGroup:()=>f(w.turnId),markPartsPreviewed:q=>p(w.turnId,q)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:y}},Yy=({messages:s,permissions:r,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:c,pendingAnchorId:d})=>{l.useEffect(()=>{r.length!==0&&t("permission")},[r,t]);const u=l.useMemo(()=>{const f=new Set;return s.filter(p=>{const h=p.info?.id;if(typeof h=="string"){if(f.has(h))return!1;f.add(h)}return!0}).map(p=>({...p,parts:Mx(p.parts)}))},[s]),{getContextForMessage:m}=Ky(u);return e.jsxs("div",{children:[o&&e.jsx("div",{className:"flex justify-center py-3",children:a?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:i,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((f,p)=>e.jsx($y,{message:f,previousMessage:p>0?u[p-1]:void 0,nextMessage:p<u.length-1?u[p+1]:void 0,onContentChange:t,animationHandlers:n(f.info.id),scrollToBottom:c,isPendingAnchor:d===f.info.id,turnGroupingContext:m(f.info.id)},f.info.id))}),r.length>0&&e.jsx("div",{children:r.map(f=>e.jsx(Uy,{permission:f},f.id))})]})},Xy=l.memo(Yy);function Qy(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const gu=l.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:c,children:d,...u},m)=>{const f=l.useRef(null),p=l.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const y=l.useMemo(()=>{const v={...i};return v["--scroll-shadow-size"]=`${t}px`,v},[t,i]),g=l.useCallback((v,S,N,j,k)=>{const F=`${j}${k.charAt(0).toUpperCase()}${k.slice(1)}Scroll`;S&&N?(v.dataset[F]="true",v.removeAttribute(`data-${j}-scroll`),v.removeAttribute(`data-${k}-scroll`)):(v.dataset[`${j}Scroll`]=String(S),v.dataset[`${k}Scroll`]=String(N),v.removeAttribute(`data-${j}-${k}-scroll`))},[]),w=l.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(S=>{v.removeAttribute(`data-${S}-scroll`)})},[]),x=l.useCallback(()=>{const v=f.current;if(!v)return;if(!n){w(v);return}const S=s==="vertical"?v.scrollTop>r:v.scrollLeft>r;let N=s==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&s==="vertical"&&(N=!1),g(v,S,N,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const j=S&&N?"both":S?s==="vertical"?"top":"left":N?s==="vertical"?"bottom":"right":"none";j!==p.current&&(p.current=j,a?.(j))},[w,o,n,r,a,s,g]);return l.useEffect(()=>{const v=f.current;if(!v)return;const S=()=>x(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>x()):null,j=typeof MutationObserver<"u"?new MutationObserver(()=>x()):null;return x(),v.addEventListener("scroll",S,{passive:!0}),N?.observe(v),j?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",S),N?.disconnect(),j?.disconnect()}},[x]),e.jsx("div",{...u,ref:Qy(f,m),className:c,"data-orientation":s,"data-scroll-shadow":h??!0,style:y,children:d})});gu.displayName="ScrollShadow";const Jy=160,Zy=({containerRef:s})=>{const[r,t]=l.useState(!0),n=l.useRef(!0),o=l.useRef(!1),a=l.useRef(null),i=l.useRef(null),c=l.useRef(0),d=l.useRef(0),u=l.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),m=l.useCallback(S=>{const N=s.current;if(!N){u();return}i.current===null&&(i.current=S);const j=Math.min(1,(S-i.current)/Jy),k=1-Math.pow(1-j,3),F=c.current,I=d.current,M=F+(I-F)*k;if(N.scrollTop=M,j<1){a.current=window.requestAnimationFrame(m);return}N.scrollTop=I,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=l.useCallback((S,N)=>{const j=s.current;if(!j)return;const k=Math.max(0,S),F=N?.instant??!1;if(o.current=!1,typeof window>"u"||F){u(),j.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}if(u(),Math.abs(k-j.scrollTop)<=.5){j.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}c.current=j.scrollTop,d.current=k,i.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),y=l.useCallback(()=>o.current,[]),g=l.useCallback(()=>s.current?.scrollTop??0,[s]),w=l.useCallback(()=>s.current?.scrollHeight??0,[s]),x=l.useCallback(()=>s.current?.clientHeight??0,[s]),v=l.useCallback(()=>{const S=s.current;if(!S)return;o.current&&a.current!==null&&u();const N=S.scrollTop<=1;n.current!==N&&(n.current=N,t(N))},[u,s]);return l.useEffect(()=>{const S=s.current;if(S)return S.addEventListener("wheel",h,{passive:!0}),S.addEventListener("touchstart",h,{passive:!0}),()=>{S.removeEventListener("wheel",h),S.removeEventListener("touchstart",h)}},[s,h]),l.useEffect(()=>()=>{u()},[u]),l.useMemo(()=>({handleScroll:v,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:y,getScrollTop:g,getScrollHeight:w,getClientHeight:x}),[v,f,p,r,y,g,w,x])},sc=typeof window<"u"?l.useLayoutEffect:l.useEffect,rc=50,nc=40,eb=.2,tb=.1,sb=150,bs=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},rb=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},nb=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:i,sessionActivityPhase:c})=>{const d=l.useRef(null),u=Zy({containerRef:d}),[m,f]=l.useState(null),[p,h]=l.useState(0),[y,g]=l.useState(!1),[w,x]=l.useState(null),v=l.useRef(null),S=l.useRef(null),N=l.useRef(r.length),j=l.useRef(r.length>0?bs(r[0]):null),k=l.useRef(r.length>0?bs(r[r.length-1]):null),F=l.useRef(0),I=l.useRef(0),M=l.useRef(void 0),b=l.useRef(null),C=l.useRef(!1),A=l.useRef(!1),P=l.useRef(null),L=s?c?.get(s)??"idle":"idle",$=l.useCallback(W=>{const te=Math.max(0,W);F.current!==te&&(F.current=te,h(te))},[]),q=l.useCallback(()=>{const W=d.current;W&&(I.current=W.clientHeight)},[]),ee=l.useCallback(()=>{if(!m)return null;const W=d.current;return W?W.querySelector(`[data-message-id="${m}"]`):null},[m]),ce=l.useCallback(()=>{const W=d.current,te=F.current;if(!W||te<=0)return!0;const oe=W.scrollHeight-te;return W.scrollTop+W.clientHeight<oe},[]),_=l.useCallback((W,te)=>{const oe=W.offsetHeight,V=W.offsetTop;if(oe>te*eb){const ge=te*tb;return V+oe-ge}else return V-rc},[]),z=l.useCallback(()=>{const W=d.current;if(!W||!b.current)return;const te=ee();if(!te)return;const oe=W.clientHeight,V=W.scrollHeight,ge=_(te,oe)+oe,ie=F.current,De=V-ie;if(!C.current&&De<ge){const Ce=ge-De;Ce>ie&&($(Ce),s&&b.current&&n(s,b.current,Ce))}},[_,s,ee,n,$]),D=l.useCallback(()=>{const W=d.current;if(!W){g(!1);return}if(w){g(!1);return}if(!(W.scrollHeight>W.clientHeight)){g(!1);return}const oe=W.scrollHeight-W.scrollTop-W.clientHeight,V=F.current;if(V>0){const ue=W.scrollHeight-V,ge=W.scrollTop+W.clientHeight;g(ge<ue)}else g(oe>nc)},[w]),H=l.useCallback(W=>{const te=d.current;if(!te)return;const oe=te.scrollHeight-te.scrollTop-te.clientHeight;if(A.current&&L==="idle"&&!a&&!W?.force&&oe>nc)return;W?.force&&(A.current=!1);const ue=te.scrollHeight-te.clientHeight;u.scrollToPosition(Math.max(0,ue),W)},[L,a,u]),X=l.useCallback(W=>{if(v.current===W)return;v.current=W,x(W);const te=d.current;if(!te){x(null);return}const oe=te.scrollHeight,V=F.current,ue=oe-V,ge=I.current>0?I.current:te.clientHeight,De=ue-rc,Ce=De+ge;let Ie=0;ue<Ce&&(Ie=Ce-ue),Ie!==V&&$(Ie),s&&n(s,W,Ie),C.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(De,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[s,u,n,$]),he=l.useCallback(W=>{const te=d.current;if(!te||!s)return;W?.isTrusted&&(A.current=!0),u.handleScroll(),D(),L==="idle"&&F.current>0&&ce()&&($(0),b.current=null,f(null),n(s,null,0));const{scrollTop:oe,scrollHeight:V,clientHeight:ue}=te,ge=(oe+ue/2)/Math.max(V,1),ie=Math.floor(ge*r.length);t(s,ie)},[s,L,ce,u,r.length,n,D,$,t]);l.useEffect(()=>{const W=d.current;if(W)return W.addEventListener("scroll",he,{passive:!0}),()=>{W.removeEventListener("scroll",he)}},[he]),sc(()=>{if(typeof window>"u")return;q();const W=()=>{M.current!==void 0&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{q()},sb)};return window.addEventListener("resize",W),()=>{window.removeEventListener("resize",W),M.current!==void 0&&window.clearTimeout(M.current)}},[q]),l.useEffect(()=>{if(s&&s!==S.current){S.current=s,tr.getInstance().recordSessionStart(s),N.current=r.length,j.current=r.length>0?bs(r[0]):null,k.current=r.length>0?bs(r[r.length-1]):null;const W=o(s);L!=="idle"&&W&&W.anchorId?(b.current=W.anchorId,v.current=W.anchorId,C.current=!0,f(W.anchorId),F.current=W.spacerHeight,h(W.spacerHeight),window.requestAnimationFrame(()=>{const oe=d.current;if(!oe)return;const V=oe.querySelector(`[data-message-id="${W.anchorId}"]`);if(V){const ue=oe.clientHeight,ge=_(V,ue);u.scrollToPosition(ge,{instant:!0})}})):(v.current=null,b.current=null,C.current=!1,f(null),F.current=0,h(0),window.requestAnimationFrame(()=>{H({instant:!0,force:!0})})),x(null),g(!1),A.current=!1,P.current=null}},[L,s,H,r.length,o]),sc(()=>{if(a){N.current=r.length,j.current=r.length>0?bs(r[0]):null,k.current=r.length>0?bs(r[r.length-1]):null;return}if(S.current!==s)return;const W=N.current,te=r.length;if(te>W&&W>0){const oe=j.current,V=bs(r[0]),ue=bs(r[te-1]),ge=k.current,ie=oe!==null&&V!==oe,De=ge!==null&&ue!==ge,Ce=ie&&!De,Ie=De&&!ie;if(Ce){b.current=null,C.current=!1,f(null),$(0),N.current=te,j.current=V,k.current=ue;return}if(Ie){const G=r.slice(W,te).find(rb);if(G){const T=bs(G);T&&(b.current=T,f(T),X(T))}else z()}}N.current=te,j.current=r.length>0?bs(r[0]):null,k.current=r.length>0?bs(r[r.length-1]):null},[s,a,z,X,r]),l.useEffect(()=>{const W=d.current;if(!W||typeof ResizeObserver>"u")return;const te=new ResizeObserver(()=>{z(),D()});return te.observe(W),()=>{te.disconnect()}},[z,D]),l.useEffect(()=>{if(typeof window>"u"){D();return}const W=window.requestAnimationFrame(()=>{D()});return()=>{window.cancelAnimationFrame(W)}},[s,r.length,D]),l.useEffect(()=>{m&&(z(),D())},[m,z,D]),l.useEffect(()=>{const W=P.current;P.current=L,W!==null&&W!=="idle"&&L==="idle"&&F.current>0&&ce()&&b.current!==null&&($(0),b.current=null,C.current=!1,f(null),s&&n(s,null,0))},[L,s,ce,n,$]),l.useEffect(()=>{D()},[p,D]);const ae=l.useRef(new Map),fe=l.useCallback(()=>{z(),D()},[z,D]),je=l.useCallback(W=>{const te=ae.current.get(W);if(te)return te;const oe={onChunk:()=>{z()},onComplete:()=>{z()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{z()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return ae.current.set(W,oe),oe},[z]);return{scrollRef:d,handleMessageContentChange:fe,getAnimationHandlers:je,showScrollButton:y,scrollToBottom:H,spacerHeight:p,pendingAnchorId:w,hasActiveAnchor:m!==null}},ob=()=>{const{currentSessionId:s,messages:r,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,sessionMemoryState:m,openNewSessionDraft:f,isSyncing:p,messageStreamStates:h,trimToViewportWindow:y,sessionActivityPhase:g,newSessionDraft:w}=ye(),x=l.useMemo(()=>s?n.get(s)??null:null,[s,n]),{isMobile:v}=Nt(),S=!!w?.open;l.useEffect(()=>{!s&&!S&&f()},[s,S,f]);const N=l.useMemo(()=>s?r.get(s)||[]:[],[s,r]),j=l.useMemo(()=>s?t.get(s)||[]:[],[s,t]),{scrollRef:k,handleMessageContentChange:F,getAnimationHandlers:I,showScrollButton:M,scrollToBottom:b,spacerHeight:C,pendingAnchorId:A,hasActiveAnchor:P}=nb({currentSessionId:s,sessionMessages:N,updateViewportAnchor:c,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,isSyncing:p,isMobile:v,sessionActivityPhase:g}),$=!!l.useMemo(()=>s?m.get(s)??null:null,[s,m])?.hasMoreAbove,[q,ee]=l.useState(!1);l.useEffect(()=>{ee(!1)},[s]);const ce=l.useRef(null);l.useLayoutEffect(()=>{if(!(!s||s===ce.current)&&(ce.current=s,!P)){const z=k.current;z&&(z.scrollTop=z.scrollHeight-z.clientHeight)}},[s,k,P]);const _=l.useCallback(async()=>{if(!s||q)return;const z=k.current,D=z?.scrollHeight??null,H=z?.scrollTop??null;ee(!0);try{if(await i(s,"up"),z&&D!==null&&H!==null){const X=z.scrollHeight-D;z.scrollTop=H+X}}finally{ee(!1)}},[s,q,i,k]);return l.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await a(s)}finally{typeof window>"u"?b():window.requestAnimationFrame(()=>{b()})}})()},[s,a,r,b]),!s&&!S?e.jsx("div",{className:"flex flex-col h-full bg-background",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(ia,{})}):!s&&S?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(ia,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Bn,{scrollToBottom:b})})]}):s?o&&N.length===0&&!x&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-column space-y-4",children:[1,2,3].map(D=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(aa,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(aa,{className:"h-4 w-24"}),e.jsx(aa,{className:"h-20 w-full"})]})]},D))})}),e.jsx(Bn,{scrollToBottom:b})]}):N.length===0&&!x?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(ia,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Bn,{scrollToBottom:b})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(gu,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:k,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!A,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(Xy,{messages:N,permissions:j,onMessageContentChange:F,getAnimationHandlers:I,hasMoreAbove:$,isLoadingOlder:q,onLoadOlder:_,scrollToBottom:b,pendingAnchorId:A}),C>0&&P&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:C},"aria-hidden":"true"})]})}),e.jsx(ci,{containerRef:k})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[M&&N.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>b({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(Xr,{className:"h-4 w-4"})})}),e.jsx(Bn,{scrollToBottom:b})]})]}):null};class ab extends l.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(xi,{className:"w-full max-w-md",children:[e.jsx(Fd,{className:"text-center",children:e.jsxs(Pd,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(pf,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Rd,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data."}),this.props.sessionId&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Session: ",this.props.sessionId]}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(fs,{className:"h-4 w-4 mr-2"}),"Reset Chat"]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:"If the problem persists, try refreshing the page."})]})]})}):this.props.children}}const Wa=()=>{const s=ye(r=>r.currentSessionId);return e.jsx(ab,{sessionId:s||void 0,children:e.jsx(ob,{})})},oc=12,ib=[{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"}],lb=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=ib,onComplete:a})=>{const i=Se.useRef(!1);Se.useEffect(()=>{!s&&i.current&&a?.(),s&&(i.current=!0)},[s,a]);const c=Se.useMemo(()=>Array.from({length:oc},(d,u)=>{const m=Math.PI*2*u/oc;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:O("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},cb=({durationMs:s=3400}={})=>{const[r,t]=Se.useState({isActive:!1,cycle:0}),n=Se.useRef(null),o=Se.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Se.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=Se.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 Se.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:i,dismissFireworks:a}},xu=l.createContext(void 0),ac=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=cb(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(xu.Provider,{value:a,children:[s,e.jsx(lb,{isActive:r,burstKey:t})]})},db=()=>{const s=l.useContext(xu);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},Io=It()(Pt(gs((s,r)=>({selectedProfileId:null,profiles:[],globalIdentity:null,isLoading:!1,setSelectedProfile:t=>{s({selectedProfileId:t})},loadProfiles:async()=>{s({isLoading:!0});const t=r().profiles;try{const n=await Bp();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 Wp("");if(t&&t.userName&&t.userEmail){const n={id:"global",name:"Global Identity",userName:t.userName,userEmail:t.userEmail,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}},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 zp(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(t,n)=>{try{const o=r().profiles.find(i=>i.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Hp(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 Up(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)}}),{name:"git-identities-store",storage:xs(()=>rs()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Io);const ub=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),mb=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:i=!1})=>{const[c,d]=l.useState(!1),[u,m]=l.useState(""),[f,p]=l.useState(!1),[h,y]=l.useState(""),[g,w]=l.useState(!1),x=l.useRef(null),v=l.useMemo(()=>ub(h),[h]),S=l.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(b=>b.toLowerCase().includes(M)):r},[u,r]),N=l.useMemo(()=>{const M=u.toLowerCase();return M?t.filter(b=>b.toLowerCase().includes(M)):t},[u,t]),j=M=>{if(M===s){d(!1);return}o(M),d(!1),m("")},k=()=>{p(!0),setTimeout(()=>x.current?.focus(),50)},F=async()=>{if(!(!v||g)){w(!0);try{await a(v),y(""),p(!1),d(!1)}finally{w(!1)}}},I=()=>{y(""),p(!1)};return l.useEffect(()=>{c||(m(""),p(!1),y(""))},[c]),e.jsxs(Gt,{open:c,onOpenChange:d,children:[e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx(ns,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(kt,{className:"size-4 opacity-60"})]})})}),e.jsxs(Xe,{sideOffset:8,children:["Switch branch (",r.length," local · ",t.length," remote)"]})]}),e.jsx(Yt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Od,{className:"h-full min-h-0",children:[e.jsx($d,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(_d,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Bd,{children:"No branches found."}),e.jsx(Hr,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:x,placeholder:"New branch name",value:h,onChange:M=>y(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),F()):M.key==="Escape"&&(M.preventDefault(),I())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:F,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(Ht,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:I,disabled:g,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(zt,{className:"size-4"})})]}):e.jsxs($t,{onSelect:k,children:[e.jsx(Ht,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(go,{}),e.jsxs(Hr,{heading:"Local branches",children:[S.map(M=>e.jsxs($t,{onSelect:()=>j(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}`)),S.length===0&&e.jsx($t,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(go,{}),e.jsxs(Hr,{heading:"Remote branches",children:[N.map(M=>e.jsx($t,{onSelect:()=>j(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),N.length===0&&e.jsx($t,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},fb=({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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsxs(ve,{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(kn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(Xe,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsxs(ve,{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(Xr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(Xe,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsxs(ve,{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(jn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(Xe,{sideOffset:8,children:"Push changes"})]})]})},pb={branch:ns,briefcase:ti,house:ei,graduation:Za,code:_s,heart:Xc,user:hs},hb={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 yu(s){return s&&hb[s]||"var(--primary)"}const ic=({icon:s,className:r,colorToken:t})=>{const n=pb[s??"branch"]??hs;return e.jsx(n,{className:r,style:{color:yu(t)}})},gb=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(Gt,{children:[e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs(ve,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:yu(s?.color)},disabled:o,children:[n?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(ic,{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(kt,{className:"size-4 opacity-60"})]})})}),e.jsxs(Xe,{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(Yt,{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(St,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ic,{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))})]})},xb=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:i,onPush:c,onCheckoutBranch:d,onCreateBranch:u,activeIdentityProfile:m,availableIdentities:f,onSelectIdentity:p,isApplyingIdentity:h,isWorktreeMode:y})=>s?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[!y&&e.jsx(mb,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(Qe,{delayDuration:800,children:[e.jsx(Je,{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(jn,{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(Xr,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(Xe,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(fb,{syncAction:o,onFetch:a,onPull:i,onPush:c,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(gb,{activeProfile:m,identities:f,onSelect:p,isApplying:h})]}):null,yb=({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(Ka,{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(ve,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(Xr,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),bu={"?":{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"}},bb=bu.M;function wb(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 vb(s){const r=wb(s);return bu[r]??bb}const jb=l.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:c}){const d=Se.useMemo(()=>vb(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=Se.useCallback(g=>{g.key===" "?(g.preventDefault(),n()):g.key==="Enter"&&(g.preventDefault(),o())},[n,o]),h=Se.useCallback(g=>{g.preventDefault(),g.stopPropagation(),n()},[n]),y=Se.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(Xa,{className:"size-4 text-primary"}):e.jsx(Qa,{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(Qe,{delayDuration:200,children:[e.jsx(Je,{asChild:!0,children:e.jsx("button",{type:"button",onClick:y,disabled:i,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:i?e.jsx(ts,{className:"size-3.5 animate-spin"}):e.jsx(kn,{className:"size-3.5"})})}),e.jsx(Xe,{sideOffset:8,children:"Revert changes"})]})]})})}),Sb=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:i,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(ve,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(ve,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(tt,{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(jb,{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))})})]})},wu=hf,kb=({className:s,...r})=>e.jsx(xf,{className:O("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}),vu=({className:s,...r})=>e.jsx(gf,{className:O("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r});function jr({className:s,variant:r,...t}){return e.jsx(ve,{variant:r,size:"sm",className:O("h-7 px-2 py-0",s),...t})}const ma=38,lc=200,Nb=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=l.useRef(null);return l.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${ma}px`;const i=Math.min(Math.max(a.scrollHeight,ma),lc);a.style.height=`${i}px`},[s]),e.jsx(Cs,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:O("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:ma,maxHeight:lc}})},Cb=({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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(Xr,{className:"size-4"})})}),e.jsx(Xe,{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))})]})},Mb=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f})=>{const p=s>0,h=r.trim()&&p&&m===null;return e.jsxs(wu,{open:p,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex w-full items-center justify-between px-3 py-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:p?`${s} file${s===1?"":"s"} selected`:"No files selected"})]}),e.jsx(vu,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(Cb,{highlights:n,onInsert:o,onClear:a}),e.jsx(Nb,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:c||m!==null||s===0||f,"aria-label":"Generate commit message",children:c?e.jsx(ts,{className:"size-4 animate-spin"}):e.jsx(yf,{className:"size-4 text-primary"})})}),e.jsx(Xe,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(jr,{variant:"outline",onClick:d,disabled:!h||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(Ka,{className:"size-4"}),"Commit"]})}),e.jsx(jr,{variant:"default",onClick:u,disabled:!h||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(jn,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function cc(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 Db(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 Ab=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:O("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:cc(s.date),children:cc(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(Qe,{delayDuration:500,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(s.hash)},children:e.jsx(zs,{className:"size-3"})})}),e.jsx(Xe,{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(i=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:O("font-semibold w-3 text-center",Db(i.changeType)),children:i.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:i.path,children:i.path}),!i.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",i.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",i.deletions]})]}),i.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},i.path))})})]}),Eb=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Ib=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:c,onCopyHash:d})=>{const[u,m]=l.useState(!0);return s?e.jsxs(wu,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(kb,{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(Ms,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Ds,{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(xo,{placeholder:"Commits"})}),e.jsx(As,{children:Eb.map(f=>e.jsx(Ft,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(ko,{className:"size-4 text-muted-foreground"}):e.jsx(kt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(vu,{children:e.jsx(tt,{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(Ab,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:i.get(f.hash)??[],isLoadingFiles:c.has(f.hash),onCopyHash:d},f.hash))})})})]}):null};let ln=null;const Tb=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=ye(),{currentDirectory:n}=yt(),o=s?t.get(s)??void 0:void 0,i=r.find(c=>c.id===s)?.directory;return o?.path??i??n??void 0},Fb=()=>{const{git:s}=Mr(),r=Tb(),{currentSessionId:t,worktreeMetadata:n}=ye(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=Io(),u=Cd(r??null),m=Nd(r??null),f=Wh(r??null),p=Vh(r??null),h=qh(r??null),y=At(re=>re.isLoadingStatus),g=At(re=>re.isLoadingLog),{setActiveDirectory:w,fetchAll:x,fetchStatus:v,fetchBranches:S,fetchLog:N,fetchIdentity:j,setLogMaxCount:k}=At(),F=l.useMemo(()=>!ln||ln.directory!==r?null:ln,[r]),[I,M]=l.useState(F?.commitMessage??""),[b,C]=l.useState(null),[A,P]=l.useState(null),[L,$]=l.useState(25),[q,ee]=l.useState(!1),{triggerFireworks:ce}=db(),[_,z]=l.useState(()=>new Set(F?.selectedPaths??[])),[D,H]=l.useState(!1),[X,he]=l.useState(new Set),[ae,fe]=l.useState(!1),[je,W]=l.useState([]),te=l.useCallback(()=>{W([])},[]),[oe,V]=l.useState(new Set),[ue,ge]=l.useState(new Map),[ie,De]=l.useState(new Set),Ce=l.useCallback(re=>{navigator.clipboard.writeText(re).then(()=>{se.success("Commit hash copied")}).catch(()=>{se.error("Failed to copy")})},[]),Ie=l.useCallback(re=>{V(le=>{const Ae=new Set(le);return Ae.has(re)?Ae.delete(re):Ae.add(re),Ae})},[]);l.useEffect(()=>{if(!r||!s)return;const re=Array.from(oe).filter(le=>!ue.has(le)&&!ie.has(le));re.length!==0&&(De(le=>{const Ae=new Set(le);return re.forEach($e=>Ae.add($e)),Ae}),re.forEach(le=>{s.getCommitFiles(r,le).then(Ae=>{ge($e=>new Map($e).set(le,Ae.files))}).catch(Ae=>{console.error("Failed to fetch commit files:",Ae),ge($e=>new Map($e).set(le,[]))}).finally(()=>{De(Ae=>{const $e=new Set(Ae);return $e.delete(le),$e})})}))},[oe,r,s,ue,ie]),l.useEffect(()=>()=>{if(!r){ln=null;return}ln={directory:r,selectedPaths:Array.from(_),commitMessage:I}},[I,r,_]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{r&&(w(r),At.getState().directories.get(r)?.status||x(r,s,{force:!0}))},[r,w,x,s]);const K=l.useCallback(async(re=!0)=>{if(r)try{await Promise.all([v(r,s),S(r,s)])}catch(le){if(re){const Ae=le instanceof Error?le.message:"Failed to refresh repository state";se.error(Ae)}}},[r,s,v,S]),G=l.useCallback(async()=>{r&&await N(r,s,L)},[r,s,N,L]),T=l.useCallback(async()=>{r&&await j(r,s)},[r,s,j]),Y=l.useMemo(()=>{if(!m)return[];const re=m.files??[],le=new Map;return re.forEach(Ae=>{le.set(Ae.path,Ae)}),Array.from(le.values()).sort((Ae,$e)=>Ae.path.localeCompare($e.path))},[m]);l.useEffect(()=>{if(!m||Y.length===0){z(new Set),H(!1);return}z(re=>{const le=new Set,Ae=re??new Set;return Y.forEach($e=>{Ae.has($e.path)?le.add($e.path):D||le.add($e.path)}),le})},[m,Y,D]);const E=async re=>{if(r){C(re);try{if(re==="fetch")await s.gitFetch(r),se.success("Fetched latest updates");else if(re==="pull"){const le=await s.gitPull(r);se.success(`Pulled ${le.files.length} file${le.files.length===1?"":"s"}`)}else re==="push"&&(await s.gitPush(r),se.success("Pushed to remote"));await K(!1),await G()}catch(le){const Ae=le instanceof Error?le.message:`Failed to ${re==="pull"?"pull":re}`;se.error(Ae)}finally{C(null)}}},B=async(re={})=>{if(!r)return;if(!I.trim()){se.error("Please enter a commit message");return}const le=Array.from(_).sort();if(le.length===0){se.error("Select at least one file to commit");return}const Ae=re.pushAfter?"commitAndPush":"commit";P(Ae);try{await s.createGitCommit(r,I.trim(),{files:le}),se.success("Commit created successfully"),M(""),z(new Set),H(!1),te(),await K(),re.pushAfter?(await s.gitPush(r),se.success("Pushed to remote"),ce(),await K(!1)):await K(!1),await G()}catch($e){const Ue=$e instanceof Error?$e.message:"Failed to create commit";se.error(Ue)}finally{P(null)}},U=l.useCallback(async()=>{if(r){if(_.size===0){se.error("Select at least one file to describe");return}fe(!0);try{const{message:re}=await s.generateCommitMessage(r,Array.from(_)),le=re.subject?.trim()??"",Ae=Array.isArray(re.highlights)?re.highlights:[];le&&M(le),W(Ae),se.success("Commit message generated")}catch(re){const le=re instanceof Error?re.message:"Failed to generate commit message";se.error(le)}finally{fe(!1)}}},[r,_,s]),be=async re=>{if(!r||!m)return;const le=m.current??null;try{await s.createBranch(r,re,le??"HEAD"),se.success(`Created branch ${re}`);let Ae=!1;try{await s.checkoutBranch(r,re),await s.gitPush(r,{remote:"origin",branch:re,options:["--set-upstream"]}),Ae=!0}catch($e){const Ue=$e instanceof Error?$e.message:"Unable to push new branch to origin.";se.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Ue]})})}finally{if(le)try{await s.checkoutBranch(r,le)}catch($e){console.warn("Failed to restore original branch after creation:",$e)}}await K(),await G(),Ae&&se.success(`Upstream set for ${re}`)}catch(Ae){const $e=Ae instanceof Error?Ae.message:"Failed to create branch";throw se.error($e),Ae}},Q=async re=>{if(!r)return;const le=re.replace(/^remotes\//,"");if(m?.current!==le)try{await s.checkoutBranch(r,le),se.success(`Checked out ${le}`),await K(),await G()}catch(Ae){const $e=Ae instanceof Error?Ae.message:`Failed to checkout ${le}`;se.error($e)}},xe=async re=>{if(r){ee(!0);try{await s.setGitIdentity(r,re.id),se.success(`Applied "${re.name}" to repository`),await T()}catch(le){const Ae=le instanceof Error?le.message:"Failed to apply git identity";se.error(Ae)}finally{ee(!1)}}},He=l.useMemo(()=>f?.all?f.all.filter(re=>!re.startsWith("remotes/")).sort():[],[f]),Ke=l.useMemo(()=>f?.all?f.all.filter(re=>re.startsWith("remotes/")).map(re=>re.replace(/^remotes\//,"")).sort():[],[f]),ze=l.useMemo(()=>{const re=new Map;i&&re.set(i.id,i);for(const le of a)re.set(le.id,le);return Array.from(re.values())},[a,i]),st=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const re=a.find(le=>le.userName===h.userName&&le.userEmail===h.userEmail);return re||(i&&i.userName===h.userName&&i.userEmail===h.userEmail?i:{id:"local-config",name:h.userName,userName:h.userName,userEmail:h.userEmail,sshKey:h.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[h,a,i]),it=Y.length,at=_.size,ct=y||b!==null||A!==null,ut=it>0,pt=re=>{z(le=>{const Ae=new Set(le);return Ae.has(re)?Ae.delete(re):Ae.add(re),Ae}),H(!0)},vt=()=>{const re=new Set(Y.map(le=>le.path));z(re),H(!0)},xt=()=>{z(new Set),H(!0)},mt=l.useCallback(async re=>{if(r){he(le=>{const Ae=new Set(le);return Ae.add(re),Ae});try{await s.revertGitFile(r,re),se.success(`Reverted ${re}`),await K(!1)}catch(le){const Ae=le instanceof Error?le.message:"Failed to revert changes";se.error(Ae)}finally{he(le=>{const Ae=new Set(le);return Ae.delete(re),Ae})}}},[r,K,s]),J=l.useCallback(()=>{if(je.length===0)return;const re=je.map(le=>le.trim()).filter(Boolean);if(re.length===0){te();return}M(le=>{const Ae=le.trim(),$e=Ae.length>0?`
92
-
93
- `:"";return`${Ae}${$e}${re.join(`
94
- `)}`.trim()})},[je,te]),ke=l.useCallback(re=>{$(re),r&&(k(r,re),N(r,s,re))},[r,k,N,s]);return r?y&&u===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ts,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):u===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(ns,{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(xb,{status:m,localBranches:He,remoteBranches:Ke,branchInfo:f?.branches,syncAction:b,onFetch:()=>E("fetch"),onPull:()=>E("pull"),onPush:()=>E("push"),onCheckoutBranch:Q,onCreateBranch:be,activeIdentityProfile:st,availableIdentities:ze,onSelectIdentity:xe,isApplyingIdentity:q,isWorktreeMode:!!o}),e.jsx(tt,{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:[ut?e.jsx(Sb,{changeEntries:Y,selectedPaths:_,diffStats:m?.diffStats,revertingPaths:X,onToggleFile:pt,onSelectAll:vt,onClearSelection:xt,onViewDiff:re=>Fe.getState().navigateToDiff(re),onRevertFile:mt}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(yb,{behind:m?.behind??0,onPull:()=>E("pull"),isPulling:b==="pull"})}),Y.length>0&&e.jsx(Mb,{selectedCount:at,commitMessage:I,onCommitMessageChange:M,generatedHighlights:je,onInsertHighlights:J,onClearHighlights:te,onGenerateMessage:U,isGeneratingMessage:ae,onCommit:()=>B({pushAfter:!1}),onCommitAndPush:()=>B({pushAfter:!0}),commitAction:A,isBusy:ct})]}),e.jsx(Ib,{log:p,isLogLoading:g,logMaxCount:L,onLogMaxCountChange:ke,expandedCommitHashes:oe,onToggleCommit:Ie,commitFilesMap:ue,loadingCommitHashes:ie,onCopyHash:Ce})]})})]}):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."})})},Pb=1e6;function fr(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const zn=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),dc=It((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=fr(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=fr(t);s(a=>{const i=new Map(a.sessions),c=i.get(o),u=!c||c.terminalSessionId!==n.sessionId?zn(o):c??zn(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=fr(t);s(a=>{const i=new Map(a.sessions),c=i.get(o)??zn(o);return i.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=fr(t);s(a=>{const i=new Map(a.sessions),c=i.get(o)??zn(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>Pb&&m.length>1;){const h=m.shift();if(!h)break;f-=h.data.length}const p=m.map(h=>h.data).join("");return i.set(o,{...c,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=fr(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i&&a.set(n,{...i,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const n=fr(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i?(a.set(n,{...i,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const n=fr(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),ju=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Rb=[{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'}],Lb=[{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'}],Su=s=>Object.fromEntries(s.map(r=>[r.id,r])),uc=Su(Rb),pr=Su(Lb),Ob="ibm-plex-sans",Zn="ibm-plex-mono";function $b(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 _b(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 fa=null;function Bb(){return fa||(fa=vf.load()),fa}function zb(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 Va=l.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:c,enableTouchScroll:d},u)=>{const m=l.useRef(null),f=l.useRef(null),p=l.useRef(null),h=l.useRef(null),y=l.useRef(t),g=l.useRef(n),w=l.useRef(null),x=l.useRef(""),v=l.useRef(null),S=l.useRef(!1),N=l.useRef(null),j=l.useRef(null),k=l.useRef(null),F=l.useRef(0),I=l.useRef(null),[,M]=l.useReducer(_=>_+1,0),[b,C]=l.useReducer(_=>_+1,0);y.current=t,g.current=n;const A=l.useCallback((_,z)=>{const D=I.current,H=m.current;if(!D||!H)return;const X=H.getBoundingClientRect(),he=X.left+X.width/2,ae=X.top+X.height-12,fe=typeof _=="number"?_:he,je=typeof z=="number"?z:ae,W=8,te=Math.max(W,Math.min(X.width-W,fe-X.left)),oe=Math.max(W,Math.min(X.height-W,je-X.top));D.style.left=`${te}px`,D.style.top=`${oe}px`,D.style.bottom="";try{D.focus({preventScroll:!0})}catch{try{D.focus()}catch{}}},[]),P=l.useCallback(()=>{x.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,S.current=!1,N.current=null},[]),L=l.useCallback(()=>{const _=h.current,z=p.current,D=m.current;if(!_||!z||!D)return;const H=D.getBoundingClientRect();if(!(H.width<24||H.height<24))try{_.fit();const X={cols:z.cols,rows:z.rows},he=w.current;(!he||he.cols!==X.cols||he.rows!==X.rows)&&(w.current=X,g.current(X.cols,X.rows))}catch{}},[]),$=l.useCallback(()=>{if(S.current)return;const _=p.current;if(!_){P();return}if(!x.current)return;const z=x.current;x.current="",S.current=!0,_.write(z,()=>{S.current=!1,x.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,$()}):$())})},[P]),q=l.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,$()}):$())},[$]),ee=l.useCallback(_=>{_&&(x.current+=_,q())},[q]),ce=l.useCallback(()=>{if(j.current?.(),j.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),!d){F.current=0;return}const _=m.current;if(!_)return;const z=p.current;if(!z)return;F.current=0;const D=2.2,H=2.8,X=25,he=.25,ae=8,fe=.05,je=.015,W={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},te=()=>typeof performance<"u"?performance.now():Date.now(),oe=Math.max(12,Math.round(i*1.35));let V=0;const ue=Y=>{if(!Y)return!1;const E=z.getViewportY(),B=V+Y,U=Math.trunc(B/oe);return V=B-U*oe,U!==0&&z.scrollLines(U),z.getViewportY()!==E},ge=()=>{W.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(W.rafId),W.rafId=null},ie={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const Y=Object.assign(W,{pointerId:null,startX:null,startY:null,moved:!1}),E=6,B=xe=>{if(xe.pointerType==="touch"){ge(),Y.pointerId=xe.pointerId,Y.startX=xe.clientX,Y.startY=xe.clientY,Y.moved=!1,Y.lastY=xe.clientY,Y.lastTime=te(),Y.velocity=0;try{_.setPointerCapture(xe.pointerId)}catch{}}},U=xe=>{if(xe.pointerType!=="touch"||Y.pointerId!==xe.pointerId)return;if(Y.startX!==null&&Y.startY!==null&&!Y.moved){const pt=xe.clientX-Y.startX,vt=xe.clientY-Y.startY;Math.hypot(pt,vt)>=E&&(Y.moved=!0)}if(Y.lastY===null){Y.lastY=xe.clientY,Y.lastTime=te();return}const He=Y.lastY,Ke=Y.lastTime??te(),ze=te();Y.lastY=xe.clientY,Y.lastTime=ze;const st=He-xe.clientY;if(Math.abs(st)<1)return;const it=Math.max(ze-Ke,8),at=D+Math.min(H,Math.abs(st)/X),ct=st*at,ut=ct/it;Y.velocity=Y.velocity*(1-he)+ut*he,Y.velocity>ae?Y.velocity=ae:Y.velocity<-ae&&(Y.velocity=-ae),Y.moved&&(xe.cancelable&&xe.preventDefault(),xe.stopPropagation()),ue(ct)},be=xe=>{if(xe.pointerType!=="touch"||Y.pointerId!==xe.pointerId)return;const He=!Y.moved;Y.pointerId=null,Y.startX=null,Y.startY=null,Y.moved=!1,Y.lastY=null,Y.lastTime=null;try{_.releasePointerCapture(xe.pointerId)}catch{}if(He){A(xe.clientX,xe.clientY);return}if(typeof window>"u")return;if(Math.abs(Y.velocity)<fe){Y.velocity=0;return}let Ke=te();const ze=()=>{const st=te(),it=Math.max(st-Ke,8);Ke=st;const at=ue(Y.velocity*it)??!1,ct=Math.sign(Y.velocity),ut=Math.max(0,Math.abs(Y.velocity)-je*it);if(Y.velocity=ut*ct,!at||ut<=fe){ge(),Y.velocity=0;return}Y.rafId=window.requestAnimationFrame(ze)};Y.rafId=window.requestAnimationFrame(ze)};_.addEventListener("pointerdown",B,ie),_.addEventListener("pointermove",U,ie),_.addEventListener("pointerup",be,ie),_.addEventListener("pointercancel",be,ie);const Q=_.style.touchAction;_.style.touchAction="manipulation",j.current=()=>{ge(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),F.current=0,_.removeEventListener("pointerdown",B,ie),_.removeEventListener("pointermove",U,ie),_.removeEventListener("pointerup",be,ie),_.removeEventListener("pointercancel",be,ie),_.style.touchAction=Q};return}const Ce=6,Ie=Y=>{Y.touches.length===1&&(ge(),W.lastY=Y.touches[0].clientY,W.lastTime=te(),W.velocity=0,W.startX=Y.touches[0].clientX,W.startY=Y.touches[0].clientY,W.didMove=!1)},K=Y=>{if(Y.touches.length!==1){W.lastY=null,W.lastTime=null,W.velocity=0,W.startX=null,W.startY=null,W.didMove=!1,ge();return}const E=Y.touches[0].clientX,B=Y.touches[0].clientY;if(W.startX!==null&&W.startY!==null&&!W.didMove){const it=E-W.startX,at=B-W.startY;Math.hypot(it,at)>=Ce&&(W.didMove=!0)}if(W.lastY===null){W.lastY=B,W.lastTime=te();return}const U=W.lastY,be=W.lastTime??te(),Q=te();W.lastY=B,W.lastTime=Q;const xe=U-B;if(Math.abs(xe)<1)return;const He=Math.max(Q-be,8),Ke=D+Math.min(H,Math.abs(xe)/X),ze=xe*Ke,st=ze/He;W.velocity=W.velocity*(1-he)+st*he,W.velocity>ae?W.velocity=ae:W.velocity<-ae&&(W.velocity=-ae),W.didMove&&(Y.preventDefault(),Y.stopPropagation()),ue(ze)},G=Y=>{const E=!W.didMove;W.lastY=null,W.lastTime=null;const B=W.velocity;if(W.startX=null,W.startY=null,W.didMove=!1,E){const Q=Y.changedTouches?.[0];A(Q?.clientX,Q?.clientY);return}if(typeof window>"u")return;if(Math.abs(B)<fe){W.velocity=0;return}let U=te();const be=()=>{const Q=te(),xe=Math.max(Q-U,8);U=Q;const He=ue(W.velocity*xe)??!1,Ke=Math.sign(W.velocity),ze=Math.max(0,Math.abs(W.velocity)-je*xe);if(W.velocity=ze*Ke,!He||ze<=fe){ge(),W.velocity=0;return}W.rafId=window.requestAnimationFrame(be)};W.rafId=window.requestAnimationFrame(be)};_.addEventListener("touchstart",Ie,ie),_.addEventListener("touchmove",K,ie),_.addEventListener("touchend",G,ie),_.addEventListener("touchcancel",G,ie);const T=_.style.touchAction;_.style.touchAction="manipulation",j.current=()=>{ge(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),F.current=0,_.removeEventListener("touchstart",Ie,ie),_.removeEventListener("touchmove",K,ie),_.removeEventListener("touchend",G,ie),_.removeEventListener("touchcancel",G,ie),_.style.touchAction=T}},[d,A,i]);return l.useEffect(()=>{let _=!1,z=null,D=null,H=[];const X=m.current;return X?(X.tabIndex=0,(async()=>{try{const ae=await Bb();if(_)return;const fe=_b(a,i,o,ae),je=new bf(fe),W=new wf;z=je,p.current=je,h.current=W,je.loadAddon(W),je.open(X),C();const te=zb(X);te?(te.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=te,M()):f.current=null,L(),ce(),je.focus(),H=[je.onData(oe=>{y.current(oe)})],D=new ResizeObserver(()=>{L()}),D.observe(X),typeof window<"u"&&window.setTimeout(()=>{L()},0)}catch{}})(),()=>{_=!0,j.current?.(),j.current=null,H.forEach(ae=>ae.dispose()),D?.disconnect(),z?.dispose(),p.current=null,h.current=null,f.current=null,w.current=null,P()}):void 0},[L,a,i,ce,o,P]),l.useEffect(()=>{const _=p.current;_&&(_.reset(),P(),w.current=null,L(),_.focus())},[s,b,L,P]),l.useEffect(()=>(ce(),()=>{j.current?.(),j.current=null}),[ce,s]),l.useEffect(()=>{const _=p.current;if(!_)return;if(r.length===0){N.current!==null&&(_.reset(),P(),L());return}const z=N.current;let D;if(z===null)D=r;else{const H=r.findIndex(X=>X.id===z);D=H>=0?r.slice(H+1):r}D.length>0&&ee(D.map(H=>H.data).join("")),N.current=r[r.length-1].id},[r,b,ee,L,P]),l.useImperativeHandle(u,()=>({focus:()=>{if(d){A();return}p.current?.focus()},clear:()=>{const _=p.current;_&&(_.reset(),P(),L())},fit:()=>{L()}}),[d,A,L,P]),e.jsxs("div",{ref:m,className:O("relative h-full w-full",c),style:{backgroundColor:o.background},onClick:_=>{d?A(_.clientX,_.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:I,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:.001,zIndex:1,background:"transparent",color:"transparent",border:"none",padding:0,margin:0,outline:"none"},onInput:_=>{const z=String(_.currentTarget.value||"");if(!z)return;const D=z.replace(/\r\n|\r|\n/g,"\r");y.current(D),_.currentTarget.value=""},onKeyDown:_=>{_.key==="Backspace"&&(_.currentTarget.value||y.current(""))}}):null,f.current&&!d?e.jsx(ci,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Va.displayName="TerminalViewport";const mc=13,Hb={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Hn={ctrl:"5",cmd:"3"},Ub={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},Wb=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${Hn[r]}A`;case"arrow-down":return`\x1B[1;${Hn[r]}B`;case"arrow-right":return`\x1B[1;${Hn[r]}C`;case"arrow-left":return`\x1B[1;${Hn[r]}D`}return Hb[s]??null},Vb=()=>{const{terminal:s}=Mr(),{currentTheme:r}=Dr(),{monoFont:t}=ju(),{isMobile:n,hasTouchInput:o}=Nt(),{currentSessionId:a,sessions:i,worktreeMetadata:c}=ye(),d=a?c.get(a)??void 0:void 0,u=l.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const E=i.find(U=>U.id===a),B=typeof E?.directory=="string"?E.directory:null;return B&&B.length>0?B:null},[a,i,d]),{currentDirectory:m,homeDirectory:f}=yt(),p=u||m||null,h=l.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),y=dc(),g=y.sessions,w=y.setTerminalSession,x=y.setConnecting,v=y.appendToBuffer,S=y.clearTerminalSession,N=y.removeTerminalSession,j=y.clearBuffer,k=l.useMemo(()=>{if(p)return g.get(p)},[g,p]),F=k?.terminalSessionId??null,I=k?.bufferChunks??[],M=k?.bufferLength??0,b=k?.isConnecting??!1,C=F,[A,P]=l.useState(null),[L,$]=l.useState(!1),[q,ee]=l.useState(null),[ce,_]=l.useState(!1),z=l.useRef(null),D=l.useRef(null),H=l.useRef(C),X=l.useRef(p),he=l.useRef(null),fe=Fe(E=>E.activeMainTab)==="terminal";l.useEffect(()=>{H.current=C},[C]),l.useEffect(()=>{X.current=p},[p]),l.useEffect(()=>{!n&&q!==null&&ee(null)},[n,q,ee]),l.useEffect(()=>{!C&&q!==null&&ee(null)},[C,q,ee]);const je=l.useCallback(()=>{z.current?.(),z.current=null,D.current=null},[]);l.useEffect(()=>()=>{je(),H.current=null},[je]);const W=l.useCallback(E=>{if(D.current===E)return;je();const B=s.connect(E,{onEvent:U=>{const be=X.current;if(be)switch(U.type){case"connected":{(U.runtime||U.ptyBackend)&&console.log(`[Terminal] connected runtime=${U.runtime??"unknown"} pty=${U.ptyBackend??"unknown"}`),x(be,!1),P(null),$(!1),he.current?.focus();break}case"reconnecting":{const Q=U.attempt??0,xe=U.maxAttempts??3;P(`Reconnecting (${Q}/${xe})...`),$(!1);break}case"data":{U.data&&v(be,U.data);break}case"exit":{const Q=typeof U.exitCode=="number"?U.exitCode:null,xe=typeof U.signal=="number"?U.signal:null;v(be,`\r
95
- [Process exited${Q!==null?` with code ${Q}`:""}${xe!==null?` (signal ${xe})`:""}]\r
96
- `),S(be),x(be,!1),P("Terminal session ended"),$(!1),je();break}}},onError:(U,be)=>{const Q=X.current;if(!Q)return;const xe=be?`Connection failed: ${U.message}`:U.message||"Terminal stream connection error";P(xe),$(!!be),be&&(x(Q,!1),je(),N(Q))}},Ub);z.current=()=>{B.close(),D.current=null},D.current=E},[v,S,je,N,x,s,P]);l.useEffect(()=>{let E=!1;if(!p){P(a?"No working directory available for terminal.":"Select a session to open the terminal."),je();return}return(async()=>{const U=p;if(!X.current||X.current!==U)return;let Q=dc.getState().getTerminalSession(U)?.terminalSessionId??null;if(!Q){P(null),$(!1),x(U,!0);try{const xe=await s.createSession({cwd:U});if(E){try{await s.close(xe.sessionId)}catch{}return}w(U,xe),Q=xe.sessionId}catch(xe){E||(P(xe instanceof Error?xe.message:"Failed to start terminal session"),$(!0),x(U,!1));return}}!Q||E||(H.current=Q,W(Q))})(),()=>{E=!0,H.current=null,je()}},[a,p,C,N,x,w,W,je,s]);const te=l.useCallback(async()=>{if(!p||ce)return;_(!0),P(null),$(!1),je();const E=H.current;try{if(s.restartSession&&E){const B=await s.restartSession(E,{cwd:p});w(p,B),H.current=B.sessionId,W(B.sessionId)}else{if(E)try{await s.close(E)}catch{}N(p)}}catch(B){P(B instanceof Error?B.message:"Failed to restart terminal"),$(!0)}finally{_(!1)}},[p,ce,je,s,w,W,N]),oe=l.useCallback(async()=>{if(p&&!ce){_(!0),P(null),$(!1),je();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}N(p),j(p),he.current?.clear(),await new Promise(E=>setTimeout(E,100));try{x(p,!0);const E=await s.createSession({cwd:p});w(p,E),H.current=E.sessionId,W(E.sessionId)}catch(E){P(E instanceof Error?E.message:"Failed to create terminal"),$(!0),x(p,!1)}finally{_(!1)}}},[p,ce,je,s,N,j,x,w,W]),V=l.useCallback(()=>{if(!p)return;j(p),he.current?.clear(),he.current?.focus();const E=H.current;E&&s.sendInput(E,"\f").catch(B=>{P(B instanceof Error?B.message:"Failed to refresh prompt")})},[j,p,P,s]),ue=l.useCallback(E=>{if(!E)return;let B=E,U=!1;if(q&&E.length>0){const Q=E[0];if(Q.length===1&&/[a-zA-Z]/.test(Q)){const xe=Q.toUpperCase();(q==="ctrl"||q==="cmd")&&(B=String.fromCharCode(xe.charCodeAt(0)&31),U=!0)}U||(U=!0)}const be=H.current;be&&(s.sendInput(be,B).catch(Q=>{P(Q instanceof Error?Q.message:"Failed to send input")}),U&&(ee(null),he.current?.focus()))},[q,ee,s]),ge=l.useCallback((E,B)=>{const U=H.current;U&&s.resize({sessionId:U,cols:E,rows:B}).catch(()=>{})},[s]),ie=l.useCallback(E=>{ee(B=>B===E?null:E),he.current?.focus()},[ee]),De=l.useCallback(E=>{const B=Wb(E,q);B&&(ue(B),ee(null),he.current?.focus())},[q,ue,ee]);l.useEffect(()=>{if(!n||!q||!C)return;const E=B=>{if(B.repeat)return;const U=B.key;if(!U||U==="Control"||U==="Meta"||U==="Alt"||U==="Shift")return;const be=U.length===1?U.toLowerCase():U,Q=B.code??"",xe=Q.startsWith("Key")&&Q.length===4?Q.slice(3).toUpperCase():null,He=U.length===1&&/[a-zA-Z]/.test(U)?U.toUpperCase():xe,Ke={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(be in Ke){B.preventDefault(),B.stopPropagation(),De(Ke[be]);return}if(q==="ctrl"&&He&&He.length===1&&He>="A"&&He<="Z"){const ze=String.fromCharCode(He.charCodeAt(0)&31);B.preventDefault(),B.stopPropagation(),ue(ze),ee(null),he.current?.focus()}};return window.addEventListener("keydown",E),()=>{window.removeEventListener("keydown",E)}},[q,De,ue,n,ee,C]);const Ce=l.useMemo(()=>{const E=pr[Zn].stack;if(typeof window>"u")return(pr[t]??pr[Zn]).stack;const U=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return U&&U.trim().length>0?U.trim():(pr[t]??pr[Zn]).stack??E},[t]),Ie=l.useMemo(()=>$b(r),[r]),K=l.useMemo(()=>`${p??"no-dir"}::${C??"pending"}`,[p,C]);l.useEffect(()=>{if(!fe)return;const E=he.current;if(!E)return;const B=()=>{E.fit()};if(typeof window<"u"){const U=window.requestAnimationFrame(()=>{B(),E.focus()}),be=[220,400].map(Q=>window.setTimeout(B,Q));return()=>{window.cancelAnimationFrame(U),be.forEach(Q=>window.clearTimeout(Q))}}B()},[fe,K,C]);const G=A?.includes("Reconnecting"),T=A?G?e.jsx(jf,{size:20,className:"text-amber-400"}):e.jsx(zt,{size:20,className:"text-destructive"}):C&&!b&&!ce?e.jsx(Vn,{size:20,className:"text-emerald-400"}):b||ce?e.jsx(Ri,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Ri,{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:te,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Y=!C||b||ce;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:[T,e.jsxs(ve,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:V,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(Es,{size:16}),"Clear"]}),e.jsxs(ve,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:te,disabled:ce,title:"Restart terminal session",type:"button",children:[e.jsx(fs,{size:16,className:O((b||ce)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>De("esc"),disabled:Y,children:"Esc"}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>De("tab"),disabled:Y,children:[e.jsx(Pi,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:q==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ie("ctrl"),disabled:Y,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:q==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ie("cmd"),disabled:Y,children:[e.jsx(Sr,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>De("arrow-up"),disabled:Y,children:[e.jsx(jn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>De("arrow-left"),disabled:Y,children:[e.jsx(Qc,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>De("arrow-down"),disabled:Y,children:[e.jsx(Xr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>De("arrow-right"),disabled:Y,children:[e.jsx(Pi,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(ve,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>De("enter"),disabled:Y,children:[e.jsx(Yc,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Ie.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:fe?n?e.jsx(Va,{ref:E=>{he.current=E},sessionKey:K,chunks:I,onInput:ue,onResize:ge,theme:Ie,fontFamily:Ce,fontSize:mc,enableTouchScroll:o},K):e.jsx(tt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Va,{ref:E=>{he.current=E},sessionKey:K,chunks:I,onInput:ue,onResize:ge,theme:Ie,fontFamily:Ce,fontSize:mc,enableTouchScroll:o},K)}):null}),A&&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:A}),L&&e.jsx(ve,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:oe,disabled:ce,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},ku=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Ya},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Yr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:Sr},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:Kc},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:xn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:ns},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:wr}],qb={},Gb={},Kb={};ku.forEach(s=>{qb[s.id]=s.label,Gb[s.id]=s.description,Kb[s.id]=s});const Yb=({onItemSelect:s})=>{const[r,t]=l.useState(null),[n,o]=l.useState(""),{selectedAgentName:a,agents:i,setSelectedAgent:c,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=Jr(),{setSidebarOpen:p}=Fe(),{isMobile:h}=Nt(),[y,g]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=l.useMemo(()=>Dt(),[]);l.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{f()},[f]);const x=y?"bg-transparent":w?"bg-background":"bg-sidebar",v=()=>{const A="new-agent";let P=A,L=1;for(;i.some($=>$.name===P);)P=`${A}-${L}`,L++;d({name:P,scope:"user"}),c(P),s?.(),h&&p(!1)},S=async A=>{if(Lr(A)){se.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${A.name}"?`)&&(await m(A.name)?se.success(`Agent "${A.name}" deleted successfully`):se.error("Failed to delete agent"))},N=async A=>{Lr(A)&&window.confirm(`Are you sure you want to reset agent "${A.name}" to its default configuration?`)&&(await m(A.name)?se.success(`Agent "${A.name}" reset to default`):se.error("Failed to reset agent"))},j=A=>{const P=A.name;let L=1,$=`${P}-copy`;for(;i.some(_=>_.name===$);)L++,$=`${P}-copy-${L}`;const q=A,ee=typeof A.model=="string"?A.model:A.model?.providerID&&A.model?.modelID?`${A.model.providerID}/${A.model.modelID}`:void 0,ce=A;d({name:$,scope:q.scope||"user",description:A.description,model:ee,temperature:A.temperature,top_p:A.topP,prompt:A.prompt,mode:A.mode,tools:A.tools,permission:A.permission,disable:ce.disable}),c($),h&&p(!1)},k=A=>{o(A.name),t(A)},F=async()=>{if(!r)return;const A=n.trim().replace(/\s+/g,"-");if(!A){se.error("Agent name is required");return}if(A===r.name){t(null);return}if(i.some(q=>q.name===A)){se.error("An agent with this name already exists");return}const P=typeof r.model=="string"?r.model:r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:void 0,L=r;await u({name:A,description:r.description,model:P,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,tools:r.tools,permission:r.permission,disable:L.disable,scope:L.scope})?await m(r.name)?(se.success(`Agent renamed to "${A}"`),c(A)):se.error("Failed to remove old agent after rename"):se.error("Failed to rename agent"),t(null)},I=A=>{switch(A){case"primary":return e.jsx(gn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Zc,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(Jc,{className:"h-3 w-3 text-primary"});default:return null}},M=i.filter(A=>!od(A)),b=M.filter(Lr),C=M.filter(A=>!Lr(A));return e.jsxs("div",{className:O("flex h-full flex-col",x),children:[e.jsx("div",{className:O("border-b px-3",h?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",M.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Ht,{className:"size-4"})})]})}),e.jsx(tt,{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(ro,{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:[b.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"}),b.map(A=>e.jsx(fc,{agent:A,isSelected:a===A.name,onSelect:()=>{c(A.name),s?.(),h&&p(!1)},onReset:()=>N(A),onDuplicate:()=>j(A),getAgentModeIcon:I},A.name))]}),C.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"}),C.map(A=>e.jsx(fc,{agent:A,isSelected:a===A.name,onSelect:()=>{c(A.name),s?.(),h&&p(!1)},onRename:()=>k(A),onDelete:()=>S(A),onDuplicate:()=>j(A),getAgentModeIcon:I},A.name))]})]})}),e.jsx(os,{open:r!==null,onOpenChange:A=>!A&&t(null),children:e.jsxs(as,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Agent"}),e.jsxs(Is,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(dt,{value:n,onChange:A=>o(A.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:A=>{A.key==="Enter"&&F()}}),e.jsxs(Bs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(jr,{onClick:F,children:"Rename"})]})]})})]})},fc=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i,getAgentModeIcon:c})=>{const d=s;return e.jsx("div",{className:O("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||Lr(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:Lr(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(ve,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(St,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(si,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(St,{onClick:u=>{u.stopPropagation(),i()},children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(St,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(fs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(St,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function ws({className:s,variant:r,...t}){return e.jsx(ve,{variant:r,size:"sm",className:O("h-6 px-2 text-xs",s),...t})}const Xb=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Qb=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=Xb.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Si=({providerId:s,modelId:r,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=lt(),i=Fe(D=>D.isMobile),{toggleFavoriteModel:c,isFavoriteModel:d,addRecentModel:u}=Fe(),{favoriteModelsList:m,recentModelsList:f}=bi(),{isMobile:p}=Nt(),h=i||p,[y,g]=l.useState(!1),[w,x]=l.useState(new Set),[v,S]=l.useState(!1),[N,j]=l.useState(""),[k,F]=l.useState(0),I=l.useRef([]),M=()=>g(!1),b=D=>{x(H=>{const X=new Set(H);return X.has(D)?X.delete(D):X.add(D),X})};l.useEffect(()=>{v||(j(""),F(0))},[v]),l.useEffect(()=>{F(0)},[N]);const C=D=>{const H=D?.name||D?.id||"",X=String(H);return X.length>40?X.substring(0,37)+"...":X},A=(D,H)=>{const X=`${D}/${H}`;return a.get(X)},P=(D,H)=>{t(D,H),D&&H&&u(D,H),S(!1)},L=(D,H)=>{if(!N.trim())return!0;const X=N.toLowerCase();return D.toLowerCase().includes(X)||H.toLowerCase().includes(X)},$=(D,H,X,he,ae,fe)=>{const je=A(H,X),W=Qb(je?.limit?.context),te=s===H&&r===X,oe=d(H,X);return e.jsxs("div",{ref:V=>{I.current[ae]=V},className:O("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",fe?"bg-accent":"hover:bg-accent/50"),onClick:()=>P(H,X),onMouseEnter:()=>F(ae),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:C(D)}),W?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:W}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[te&&e.jsx(Mt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:V=>{V.preventDefault(),V.stopPropagation(),c(H,X)},className:O("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",oe?"text-yellow-500":"text-muted-foreground"),"aria-label":oe?"Unfavorite":"Favorite",title:oe?"Remove from favorites":"Add to favorites",children:oe?e.jsx(Vs,{className:"h-3.5 w-3.5"}):e.jsx(_r,{className:"h-3.5 w-3.5"})})]})]},`${he}-${H}-${X}`)},q=m.filter(({model:D,providerID:H})=>{const he=o.find(fe=>fe.id===H)?.name||H,ae=C(D);return L(ae,he)}),ee=f.filter(({model:D,providerID:H})=>{const he=o.find(fe=>fe.id===H)?.name||H,ae=C(D);return L(ae,he)}),ce=o.map(D=>{const X=(Array.isArray(D.models)?D.models:[]).filter(he=>{const ae=C(he);return L(ae,D.name||D.id||"")});return{...D,models:X}}).filter(D=>D.models.length>0),_=q.length>0||ee.length>0||ce.length>0,z=()=>h?e.jsx(cs,{open:y,onClose:M,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[m.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:m.map(({model:D,providerID:H,modelID:X})=>{const he=H===s&&X===r;return e.jsxs("div",{className:O("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",he?"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:()=>{P(H,X),M()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{providerId:H,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:C(D)})]})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),c(H,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(Vs,{className:"h-4 w-4"})})]},`fav-mobile-${H}-${X}`)})})]}),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:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:D,providerID:H,modelID:X})=>{const he=H===s&&X===r;return e.jsxs("div",{className:O("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",he?"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:()=>{P(H,X),M()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{providerId:H,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:C(D)})]})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),c(H,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(_r,{className:"h-4 w-4"})})]},`recent-mobile-${H}-${X}`)})})]}),o.map(D=>{const H=Array.isArray(D.models)?D.models:[];if(H.length===0)return null;const X=D.id===s,he=w.has(D.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:()=>b(D.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qt,{providerId:D.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:D.name}),X&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),he?e.jsx(kt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Ss,{className:"h-3 w-3 text-muted-foreground"})]}),he&&e.jsx("div",{className:"border-t border-border/20",children:H.map(ae=>{const fe=D.id===s&&ae.id===r;return e.jsxs("div",{className:O("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",fe?"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:()=>{P(D.id,ae.id),M()},children:e.jsx("span",{className:"font-medium truncate",children:C(ae)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:je=>{je.preventDefault(),je.stopPropagation(),c(D.id,ae.id)},className:O("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(D.id,ae.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(D.id,ae.id)?"Unfavorite":"Favorite",children:d(D.id,ae.id)?e.jsx(Vs,{className:"h-4 w-4"}):e.jsx(_r,{className:"h-4 w-4"})}),fe&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},ae.id)})})]},D.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:()=>{P("",""),M()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[h?e.jsxs("button",{type:"button",onClick:()=>g(!0),className:O("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(qt,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(Ws,{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(kt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Gt,{open:v,onOpenChange:S,children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:O("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(qt,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Ws,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Ws,{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(kt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Yt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const D=[];q.forEach(({model:ae,providerID:fe,modelID:je})=>{D.push({model:ae,providerID:fe,modelID:je,section:"fav"})}),ee.forEach(({model:ae,providerID:fe,modelID:je})=>{D.push({model:ae,providerID:fe,modelID:je,section:"recent"})}),ce.forEach(ae=>{ae.models.forEach(fe=>{D.push({model:fe,providerID:ae.id,modelID:fe.id,section:"provider"})})});const H=D.length,X=ae=>{if(ae.key==="ArrowDown"){ae.preventDefault(),ae.stopPropagation();const fe=(k+1)%Math.max(1,H);F(fe),setTimeout(()=>{I.current[fe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ae.key==="ArrowUp"){ae.preventDefault(),ae.stopPropagation();const fe=(k-1+Math.max(1,H))%Math.max(1,H);F(fe),setTimeout(()=>{I.current[fe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(ae.key==="Enter"){ae.preventDefault(),ae.stopPropagation();const fe=D[k];fe&&P(fe.providerID,fe.modelID)}else ae.key==="Escape"&&(ae.preventDefault(),ae.stopPropagation(),S(!1))};let he=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(vr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(dt,{type:"text",placeholder:"Search models",value:N,onChange:ae=>j(ae.target.value),onKeyDown:X,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(tt,{outerClassName:"max-h-[400px] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:O("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>P("",""),children:[e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!s&&!r&&e.jsx(Mt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Os,{}),!_&&N&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),q.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(zr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(Vs,{className:"h-4 w-4 text-primary"}),"Favorites"]}),q.map(({model:ae,providerID:fe,modelID:je})=>{const W=he++;return $(ae,fe,je,"fav",W,k===W)})]}),ee.length>0&&e.jsxs(e.Fragment,{children:[q.length>0&&e.jsx(Os,{}),e.jsxs(zr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(hn,{className:"h-4 w-4"}),"Recent"]}),ee.map(({model:ae,providerID:fe,modelID:je})=>{const W=he++;return $(ae,fe,je,"recent",W,k===W)})]}),(q.length>0||ee.length>0)&&ce.length>0&&e.jsx(Os,{}),ce.map((ae,fe)=>e.jsxs(l.Fragment,{children:[fe>0&&e.jsx(Os,{}),e.jsxs(zr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(qt,{providerId:ae.id,className:"h-4 w-4 flex-shrink-0"}),ae.name]}),ae.models.map(je=>{const W=he++;return $(je,ae.id,je.id,"provider",W,k===W)})]},ae.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()})]}),z()]})},Jb=()=>{const{tools:s}=Mr(),[r,t]=l.useState([]),[n,o]=l.useState(!0),[a,i]=l.useState(null);return l.useEffect(()=>{let c=!1;return(async()=>{o(!0),i(null);try{const u=await s.getAvailableTools();if(c)return;t(u)}catch(u){if(c)return;const m=u instanceof Error?u.message:"Failed to fetch tools";console.error("Failed to fetch available tools:",m),i(m),t([])}finally{c||o(!1)}})(),()=>{c=!0}},[s]),{tools:r,isLoading:n,error:a}},Zb=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:i}=Jr();lt();const{tools:c}=Jb(),d=s?r(s):null,u=!!(a&&a.name===s&&!d),[m,f]=l.useState(""),[p,h]=l.useState("user"),[y,g]=l.useState(""),[w,x]=l.useState("subagent"),[v,S]=l.useState(""),[N,j]=l.useState(void 0),[k,F]=l.useState(void 0),[I,M]=l.useState(""),[b,C]=l.useState({}),[A,P]=l.useState("allow"),[L,$]=l.useState("allow"),[q,ee]=l.useState("allow"),[ce,_]=l.useState("allow"),[z,D]=l.useState("ask"),[H,X]=l.useState("ask"),[he,ae]=l.useState(!1);l.useEffect(()=>{if(u&&a){f(a.name||""),h(a.scope||"user"),g(a.description||""),x(a.mode||"subagent"),S(a.model||""),j(a.temperature),F(a.top_p),M(a.prompt||"");const te=a.tools||{};C(te);const oe=(ie,De,Ce)=>ie==="allow"||ie==="ask"||ie==="deny"?ie:De?"deny":Ce,V=a.permission||{},ue=ie=>{if(ie==="allow"||ie==="ask"||ie==="deny")return ie;if(ie&&typeof ie=="object"&&!Array.isArray(ie)){const De=ie["*"];if(De==="allow"||De==="ask"||De==="deny")return De}},ge=te.edit===!1||te.write===!1||te.patch===!1;P(oe(ue(V.edit),ge,"allow")),ee(oe(ue(V.bash),te.bash===!1,"allow")),$(oe(ue(V.webfetch),te.webfetch===!1,"allow")),_(oe(ue(V.skill),te.skill===!1,"allow")),D(oe(ue(V.doom_loop),!1,"ask")),X(oe(ue(V.external_directory),!1,"ask"))}else if(d){g(d.description||""),x(d.mode||"subagent"),d.model?.providerID&&d.model?.modelID?S(`${d.model.providerID}/${d.model.modelID}`):S(""),j(d.temperature),F(d.topP),M(d.prompt||"");const te=d.tools||{};C(te);const oe=(ie,De,Ce)=>ie==="allow"||ie==="ask"||ie==="deny"?ie:De?"deny":Ce,V=d.permission||{},ue=ie=>{if(ie==="allow"||ie==="ask"||ie==="deny")return ie;if(ie&&typeof ie=="object"&&!Array.isArray(ie)){const De=ie["*"];if(De==="allow"||De==="ask"||De==="deny")return De}},ge=te.edit===!1||te.write===!1||te.patch===!1;P(oe(ue(V.edit),ge,"allow")),ee(oe(ue(V.bash),te.bash===!1,"allow")),$(oe(ue(V.webfetch),te.webfetch===!1,"allow")),_(oe(ue(V.skill),te.skill===!1,"allow")),D(oe(ue(V.doom_loop),!1,"ask")),X(oe(ue(V.external_directory),!1,"ask"))}},[d,u,s,o,a]);const fe=async()=>{const te=u?m.trim().replace(/\s+/g,"-"):s?.trim();if(!te){se.error("Agent name is required");return}if(u&&o.some(oe=>oe.name===te)){se.error("An agent with this name already exists");return}ae(!0);try{const oe=v.trim(),V={name:te,description:y.trim()||void 0,mode:w,model:oe===""?null:oe,temperature:N,top_p:k,prompt:I.trim()||void 0,tools:Object.keys(b).length>0?b:void 0,permission:{edit:A,webfetch:L,bash:q,skill:ce,doom_loop:z,external_directory:H},scope:u?p:void 0};let ue;u?(ue=await t(V),ue&&i(null)):ue=await n(te,V),ue?se.success(u?"Agent created successfully":"Agent updated successfully"):se.error(u?"Failed to create agent":"Failed to update agent")}catch(oe){console.error("Error saving agent:",oe),se.error("An error occurred while saving")}finally{ae(!1)}},je=te=>{C(oe=>({...oe,[te]:!oe[te]}))},W=te=>{const oe={};c.forEach(V=>{oe[V]=te}),C(oe)};return s?e.jsx(tt,{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:u?"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"})]}),u&&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(dt,{value:m,onChange:te=>f(te.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Ms,{value:p,onValueChange:te=>h(te),children:[e.jsxs(Ds,{className:"!h-9 w-auto gap-1.5",children:[p==="user"?e.jsx(hs,{className:"h-4 w-4"}):e.jsx(nr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:p})]}),e.jsxs(As,{align:"end",children:[e.jsx(Ft,{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(hs,{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(Ft,{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(nr,{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(Cs,{value:y,onChange:te=>g(te.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(ws,{variant:w==="primary"?"default":"outline",onClick:()=>x("primary"),className:O("gap-2",w==="primary"?void 0:"text-foreground"),children:[e.jsx(gn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(ws,{variant:w==="subagent"?"default":"outline",onClick:()=>x("subagent"),className:O("gap-2",w==="subagent"?void 0:"text-foreground"),children:[e.jsx(Jc,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(ws,{variant:w==="all"?"default":"outline",onClick:()=>x("all"),className:O("gap-2",w==="all"?void 0:"text-foreground"),children:[e.jsx(Zc,{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(Si,{providerId:v?v.split("/")[0]:"",modelId:v?v.split("/")[1]:"",onChange:(te,oe)=>{S(te&&oe?`${te}/${oe}`:"")}})]}),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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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 oe=Math.max(0,(N!==void 0?N:.7)-.1);j(parseFloat(oe.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(Li,{className:"h-3.5 w-3.5"})}),e.jsx(dt,{type:"text",inputMode:"decimal",value:N!==void 0?N:"",onChange:te=>{const oe=te.target.value;if(oe===""){j(void 0);return}const V=parseFloat(oe);!isNaN(V)&&V>=0&&V<=2&&j(V)},onBlur:te=>{const oe=te.target.value;if(oe!==""){const V=parseFloat(oe);if(!isNaN(V)){const ue=Math.max(0,Math.min(2,V));j(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 oe=Math.min(2,(N!==void 0?N:.7)+.1);j(parseFloat(oe.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(Ht,{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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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 oe=Math.max(0,(k!==void 0?k:.9)-.1);F(parseFloat(oe.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(Li,{className:"h-3.5 w-3.5"})}),e.jsx(dt,{type:"text",inputMode:"decimal",value:k!==void 0?k:"",onChange:te=>{const oe=te.target.value;if(oe===""){F(void 0);return}const V=parseFloat(oe);!isNaN(V)&&V>=0&&V<=1&&F(V)},onBlur:te=>{const oe=te.target.value;if(oe!==""){const V=parseFloat(oe);if(!isNaN(V)){const ue=Math.max(0,Math.min(1,V));F(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 oe=Math.min(1,(k!==void 0?k:.9)+.1);F(parseFloat(oe.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(Ht,{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(Cs,{value:I,onChange:te=>M(te.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),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:"Available Tools"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select tools this agent can access"})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>W(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>W(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:c.map(te=>e.jsx("button",{type:"button",onClick:()=>je(te),className:O("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",b[te]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:te},te))})]}),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:"Configure permission levels for different operations"})]}),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:"Edit Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:A==="allow"?"default":"outline",onClick:()=>P("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:A==="ask"?"default":"outline",onClick:()=>P("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:A==="deny"?"default":"outline",onClick:()=>P("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:"Controls file editing permissions."}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Xe,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Allows file editing without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompts for confirmation before editing"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Blocks all file editing operations"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Bash Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:q==="allow"?"default":"outline",onClick:()=>ee("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:q==="ask"?"default":"outline",onClick:()=>ee("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:q==="deny"?"default":"outline",onClick:()=>ee("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:"Permission for running bash commands"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Xe,{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 bash commands without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before execution"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all bash command execution"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"WebFetch Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:L==="allow"?"default":"outline",onClick:()=>$("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:L==="ask"?"default":"outline",onClick:()=>$("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:L==="deny"?"default":"outline",onClick:()=>$("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:"Permission for fetching web content"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Xe,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Fetch web content without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before fetching"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all web content access"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:ce==="allow"?"default":"outline",onClick:()=>_("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:ce==="ask"?"default":"outline",onClick:()=>_("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:ce==="deny"?"default":"outline",onClick:()=>_("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:"Permission for loading skills"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Xe,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Load skills without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before loading skills"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all skill loading"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Doom Loop Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:z==="allow"?"default":"outline",onClick:()=>D("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:z==="ask"?"default":"outline",onClick:()=>D("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:z==="deny"?"default":"outline",onClick:()=>D("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:"Permission for repeated identical tool calls"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Xe,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Continue without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt when a doom loop is detected"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block repeated tool calls"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"External Directory Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(ve,{size:"sm",variant:H==="allow"?"default":"outline",onClick:()=>X("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(ve,{size:"sm",variant:H==="ask"?"default":"outline",onClick:()=>X("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(ve,{size:"sm",variant:H==="deny"?"default":"outline",onClick:()=>X("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:"Permission for file access outside project"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Xe,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Access external paths without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt before accessing external paths"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block external directory access"]})]})})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ve,{size:"sm",variant:"default",onClick:fe,disabled:he,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Mo,{className:"h-3 w-3"}),he?"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(ro,{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"})]})})},ew=({onItemSelect:s})=>{const[r,t]=l.useState(null),[n,o]=l.useState(""),{selectedCommandName:a,commands:i,setSelectedCommand:c,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=en(),{setSidebarOpen:p}=Fe(),{isMobile:h}=Nt(),[y,g]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=l.useMemo(()=>Dt(),[]);l.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{f()},[f]);const x=y?"bg-transparent":w?"bg-background":"bg-sidebar",v=()=>{const b="new-command";let C=b,A=1;for(;i.some(P=>P.name===C);)C=`${b}-${A}`,A++;d({name:C,scope:"user"}),c(C),s?.(),h&&p(!1)},S=async b=>{if(Or(b)){se.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${b.name}"?`)&&(await m(b.name)?se.success(`Command "${b.name}" deleted successfully`):se.error("Failed to delete command"))},N=async b=>{Or(b)&&window.confirm(`Are you sure you want to reset command "${b.name}" to its default configuration?`)&&(await m(b.name)?se.success(`Command "${b.name}" reset to default`):se.error("Failed to reset command"))},j=b=>{const C=b.name;let A=1,P=`${C}-copy`;for(;i.some(L=>L.name===P);)A++,P=`${C}-copy-${A}`;d({name:P,scope:b.scope||"user",description:b.description,template:b.template,agent:b.agent,model:b.model,subtask:b.subtask}),c(P),h&&p(!1)},k=b=>{o(b.name),t(b)},F=async()=>{if(!r)return;const b=n.trim().replace(/\s+/g,"-");if(!b){se.error("Command name is required");return}if(b===r.name){t(null);return}if(i.some(A=>A.name===b)){se.error("A command with this name already exists");return}await u({name:b,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(se.success(`Command renamed to "${b}"`),c(b)):se.error("Failed to remove old command after rename"):se.error("Failed to rename command"),t(null)},I=i.filter(Or),M=i.filter(b=>!Or(b));return e.jsxs("div",{className:O("flex h-full flex-col",x),children:[e.jsx("div",{className:O("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 ",i.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Ht,{className:"size-4"})})]})}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(ar,{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:[I.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"}),[...I].sort((b,C)=>b.name.localeCompare(C.name)).map(b=>e.jsx(pc,{command:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),h&&p(!1)},onReset:()=>N(b),onDuplicate:()=>j(b)},b.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((b,C)=>b.name.localeCompare(C.name)).map(b=>e.jsx(pc,{command:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),h&&p(!1)},onRename:()=>k(b),onDelete:()=>S(b),onDuplicate:()=>j(b)},b.name))]})]})}),e.jsx(os,{open:r!==null,onOpenChange:b=>!b&&t(null),children:e.jsxs(as,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Command"}),e.jsxs(Is,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(dt,{value:n,onChange:b=>o(b.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:b=>{b.key==="Enter"&&F()}}),e.jsxs(Bs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(jr,{onClick:F,children:"Rename"})]})]})})]})},pc=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i})=>e.jsx("div",{className:O("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||Or(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:Or(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(ve,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(St,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(si,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(St,{onClick:c=>{c.stopPropagation(),i()},children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(St,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(fs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(St,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),Nu=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=Jr(),a=o(),i=Fe(y=>y.isMobile),{isMobile:c}=Nt(),d=i||c,[u,m]=l.useState(!1);l.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=y=>{r(y)},h=()=>d?e.jsx(cs,{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:O("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:O("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(ro,{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(kt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:O("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(ro,{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(kt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Yt,{className:"max-w-[300px]",children:[a.map(y=>e.jsx(St,{className:"typography-meta",onSelect:()=>p(y.name),children:e.jsx("span",{className:"font-medium",children:y.name})},y.name)),e.jsx(St,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},tw=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:i}=en(),c=s?r(s):null,d=!!(a&&a.name===s&&!c),[u,m]=l.useState(""),[f,p]=l.useState("user"),[h,y]=l.useState(""),[g,w]=l.useState(""),[x,v]=l.useState(""),[S,N]=l.useState(""),[j,k]=l.useState(!1),[F,I]=l.useState(!1);l.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),y(a.description||""),w(a.agent||""),v(a.model||""),N(a.template||""),k(a.subtask||!1)):c&&(y(c.description||""),w(c.agent||""),v(c.model||""),N(c.template||""),k(c.subtask||!1))},[c,d,s,o,a]);const M=async()=>{const b=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!b){se.error("Command name is required");return}if(!S.trim()){se.error("Command template is required");return}if(d&&o.some(C=>C.name===b)){se.error("A command with this name already exists");return}I(!0);try{const C=g.trim(),A=x.trim(),P=S.trim(),L={name:b,description:h.trim()||void 0,agent:C===""?null:C,model:A===""?null:A,template:P,subtask:j,scope:d?f:void 0};let $;d?($=await t(L),$&&i(null)):$=await n(b,L),$?se.success(d?"Command created successfully":"Command updated successfully"):se.error(d?"Failed to create command":"Failed to update command")}catch(C){console.error("Error saving command:",C),se.error("An error occurred while saving")}finally{I(!1)}};return s?e.jsx(tt,{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(dt,{value:u,onChange:b=>m(b.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(Ms,{value:f,onValueChange:b=>p(b),children:[e.jsxs(Ds,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(hs,{className:"h-4 w-4"}):e.jsx(nr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(As,{align:"end",children:[e.jsx(Ft,{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(hs,{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(Ft,{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(nr,{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(Cs,{value:h,onChange:b=>y(b.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(Nu,{agentName:g,onChange:b=>w(b)}),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(Si,{providerId:x?x.split("/")[0]:"",modelId:x?x.split("/")[1]:"",onChange:(b,C)=>{v(b&&C?`${b}/${C}`:"")}}),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:j,onChange:b=>k(b.target.checked),className:"sr-only"}),e.jsx("div",{className:O("w-5 h-5 rounded border-2 flex items-center justify-center",j?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:j&&e.jsx(Mt,{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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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(Cs,{value:S,onChange:b=>N(b.target.value),placeholder:`Your command template here...
97
-
98
- Use $ARGUMENTS to reference user input.
99
- Use !\`shell command\` to inject shell output.
100
- 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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{sideOffset:8,className:"max-w-xs",children:["Replaces with the full contents of the specified file.",e.jsx("br",{}),"Example: @package.json includes the package.json content in the prompt"]})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ve,{size:"sm",variant:"default",onClick:M,disabled:F,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Mo,{className:"h-3 w-3"}),F?"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(ar,{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"})]})})},Zs=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},eo="useSkillsStore",sr=It()(Pt(gs((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=Zs(),i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills${i}`);if(!c.ok)throw new Error(`Failed to list skills: ${c.status}`);const u=(await c.json()).skills||[];return s({skills:u,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=Zs(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async t=>{ks("Creating skill...");try{const n={name:t.name,description:t.description};t.instructions&&(n.instructions=t.instructions),t.scope&&(n.scope=t.scope),t.supportingFiles&&(n.supportingFiles=t.supportingFiles);const o=Zs(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),c=await i.json().catch(()=>null);if(!i.ok){const u=c?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&ps("skills",{source:eo}),d}catch{return!1}finally{ss()}},updateSkill:async(t,n)=>{ks("Updating skill...");try{const o={};n.description!==void 0&&(o.description=n.description),n.instructions!==void 0&&(o.instructions=n.instructions),n.supportingFiles!==void 0&&(o.supportingFiles=n.supportingFiles);const a=Zs(),i=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(t)}${i}`,{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&&ps("skills",{source:eo}),u}catch{return!1}finally{ss()}},deleteSkill:async t=>{ks("Deleting skill...");try{const n=Zs(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`,{method:"DELETE"}),i=await a.json().catch(()=>null);if(!a.ok){const d=i?.error||"Failed to delete skill";throw new Error(d)}const c=await r().loadSkills();return c&&ps("skills",{source:eo}),r().selectedSkillName===t&&s({selectedSkillName:null}),c}catch{return!1}finally{ss()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=Zs(),a=o?`&directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return i.ok?(await i.json()).content??null:null}catch{return null}},writeSupportingFile:async(t,n,o)=>{try{const a=Zs(),i=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(t,n)=>{try{const o=Zs(),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:xs(()=>rs()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=sr);let hc=null;hc||(hc=Ao(s=>{if(s.source!==eo&&yn(s,"skills")){const{loadSkills:r}=sr.getState();r()}}));const sw=({onItemSelect:s})=>{const[r,t]=l.useState(null),[n,o]=l.useState(""),{selectedSkillName:a,skills:i,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=sr(),{setSidebarOpen:h}=Fe(),{isMobile:y}=Nt(),[g,w]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=l.useMemo(()=>Dt(),[]);l.useEffect(()=>{typeof window>"u"||w(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{f()},[f]);const v=g?"bg-transparent":x?"bg-background":"bg-sidebar",S=()=>{const b="new-skill";let C=b,A=1;for(;i.some(P=>P.name===C);)C=`${b}-${A}`,A++;d({name:C,scope:"user",description:""}),c(C),s?.(),y&&h(!1)},N=async b=>{window.confirm(`Are you sure you want to delete skill "${b.name}"?`)&&(await m(b.name)?se.success(`Skill "${b.name}" deleted successfully`):se.error("Failed to delete skill"))},j=async b=>{const C=b.name;let A=1,P=`${C}-copy`;for(;i.some($=>$.name===P);)A++,P=`${C}-copy-${A}`;const L=await p(b.name);if(!L){se.error("Failed to load skill details for duplication");return}d({name:P,scope:b.scope||"user",description:(L.sources.md.fields.includes("description"),""),instructions:""}),c(P),y&&h(!1)},k=b=>{o(b.name),t(b)},F=async()=>{if(!r)return;const b=n.trim().replace(/\s+/g,"-").toLowerCase();if(!b){se.error("Skill name is required");return}if(b===r.name){t(null);return}if(i.some(P=>P.name===b)){se.error("A skill with this name already exists");return}if(!await p(r.name)){se.error("Failed to load skill details"),t(null);return}await u({name:b,description:"Renamed skill",scope:r.scope})?await m(r.name)?(se.success(`Skill renamed to "${b}"`),c(b)):se.error("Failed to remove old skill after rename"):se.error("Failed to rename skill"),t(null)},I=i.filter(b=>b.scope==="project"),M=i.filter(b=>b.scope==="user");return e.jsxs("div",{className:O("flex h-full flex-col",v),children:[e.jsx("div",{className:O("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 ",i.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:S,children:e.jsx(Ht,{className:"size-4"})})]})}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(ed,{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:[I.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"}),I.map(b=>e.jsx(gc,{skill:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),y&&h(!1)},onRename:()=>k(b),onDelete:()=>N(b),onDuplicate:()=>j(b)},b.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(b=>e.jsx(gc,{skill:b,isSelected:a===b.name,onSelect:()=>{c(b.name),s?.(),y&&h(!1)},onRename:()=>k(b),onDelete:()=>N(b),onDuplicate:()=>j(b)},b.name))]})]})}),e.jsx(os,{open:r!==null,onOpenChange:b=>!b&&t(null),children:e.jsxs(as,{children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Rename Skill"}),e.jsxs(Is,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(dt,{value:n,onChange:b=>o(b.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:b=>{b.key==="Enter"&&F()}}),e.jsxs(Bs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(jr,{onClick:F,children:"Rename"})]})]})})]})},gc=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:O("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(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(ve,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})}),e.jsxs(Yt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(St,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(si,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(St,{onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(zs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(St,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),pa=()=>{try{const s=window.__zustand_directory_store__;if(s)return s.getState().currentDirectory}catch{}return null},ki=It()(Pt((s,r)=>({sources:[],itemsBySource:{},selectedSourceId:null,isLoadingCatalog:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:t=>s({selectedSourceId:t}),loadCatalog:async t=>{s({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource};let o=null;try{for(let a=0;a<3;a++)try{const i=pa(),c=t?.refresh?"&refresh=true":"",d=i?`?directory=${encodeURIComponent(i)}${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(i){o={kind:"unknown",message:i instanceof Error?i.message:String(i)};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=pa(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!a.ok||!i){const c=i?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:c}),{ok:!1,error:c}}return i.ok?(s({scanResults:i.items||[]}),i):(s({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{s({isScanning:!1})}},installSkills:async t=>{s({isInstalling:!0,lastInstallError:null});try{const n=pa(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/install${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!i){const c={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}if(!a.ok||!i.ok){const c=i.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}return sr.getState().loadSkills(),i}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return s({lastInstallError:o}),{ok:!1,error:o}}finally{s({isInstalling:!1})}}}),{name:"skills-catalog-store"})),rw=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,nw=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},ow=async()=>{try{if(Xt())return await Qr();const s=Nr()?.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}},aw=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=ki(),[a,i]=l.useState(""),[c,d]=l.useState(""),[u,m]=l.useState(""),[f,p]=l.useState([]),[h,y]=l.useState(null),[g,w]=l.useState(!1),[x,v]=l.useState([]),[S,N]=l.useState(null);l.useEffect(()=>{s&&(i(""),d(""),m(""),y(null),w(!1),v([]),N(null),(async()=>{const I=await ow(),M=Array.isArray(I?.skillCatalogs)?I?.skillCatalogs:[];p(M||[])})())},[s]);const j=l.useMemo(()=>{const I=c.trim(),M=u.trim();return f.some(b=>{const C=(b.source||"").trim(),A=(b.subpath||"").trim();return C===I&&A===M})},[f,c,u]),k=async()=>{const I=c.trim();if(!I){se.error("Repository source is required");return}a.trim()||i(nw(I)),w(!1),y(null);const M=await t({source:I,subpath:u.trim()||void 0,gitIdentityId:S||void 0});if(!M.ok){if(M.error?.kind==="authRequired"){if(Dt()){se.error("Private repositories are not supported in VS Code yet");return}const C=M.error.identities||[];v(C),!S&&C.length>0&&N(C[0].id),se.error("Authentication required. Select a Git identity and scan again.");return}se.error(M.error?.message||"Failed to scan repository");return}const b=M.items?.length||0;if(y(b),b===0){se.error("No skills found in this repository"),w(!1);return}v([]),w(!0),se.success(`Found ${b} skill(s)`)},F=async()=>{const I=a.trim(),M=c.trim(),b=u.trim();if(!I){se.error("Catalog name is required");return}if(!M){se.error("Repository source is required");return}if(!g){se.error("Scan the repository before adding this catalog");return}if(j){se.error("This catalog already exists");return}const C={id:rw(),label:I,source:M,...b?{subpath:b}:{},...S?{gitIdentityId:S}:{}},A=[...f,C];try{await es({skillCatalogs:A}),p(A),se.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(P){se.error(P instanceof Error?P.message:"Failed to save catalog")}};return e.jsx(os,{open:s,onOpenChange:r,children:e.jsxs(as,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Add skills catalog"}),e.jsxs(Is,{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(dt,{value:a,onChange:I=>i(I.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(dt,{value:c,onChange:I=>{d(I.target.value),w(!1),y(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(dt,{value:u,onChange:I=>{m(I.target.value),w(!1),y(null)},placeholder:"e.g. skills"})]}),x.length>0&&!Dt()?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(Ms,{value:S||"",onValueChange:I=>N(I),children:[e.jsx(Ds,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x.find(I=>I.id===S)?.name||"Choose identity"})}),e.jsx(As,{align:"start",children:x.map(I=>e.jsx(Ft,{value:I.id,className:"pr-2 [&>span:first-child]:hidden",children:I.name},I.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,h!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",h," skill(s) found"]}):null,j?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Bs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(ve,{variant:"outline",onClick:()=>{k()},disabled:o||!c.trim(),className:"gap-2",children:[e.jsx(Vc,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(ve,{variant:"default",onClick:()=>{F()},disabled:!g||j||!a.trim()||!c.trim(),children:"Add catalog"})]})]})})},iw=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=l.useState({});l.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const i=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},c=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(os,{open:s,onOpenChange:r,children:e.jsxs(as,{className:"max-w-2xl",children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Skills already exist"}),e.jsx(Is,{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(ve,{variant:"outline",size:"sm",onClick:()=>i("skip"),children:"Skip all"}),e.jsx(ve,{variant:"outline",size:"sm",onClick:()=>i("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:t.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label truncate",children:d.skillName}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Installed in ",d.scope," scope"]})]}),e.jsxs(Ms,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Ds,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(As,{align:"end",children:[e.jsx(Ft,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Ft,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Bs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(jr,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},lw=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=ki(),[a,i]=l.useState("user"),[c,d]=l.useState(!1),[u,m]=l.useState([]),[f,p]=l.useState(null);l.useEffect(()=>{s&&(i("user"),d(!1),m([]),p(null))},[s]);const h=async y=>{const g=await n({source:y.source,subpath:y.subpath,gitIdentityId:t?.gitIdentityId,scope:y.scope,selections:[{skillDir:y.skillDir}],conflictPolicy:"prompt",conflictDecisions:y.conflictDecisions});if(g.ok){se.success("Skill installed successfully"),r(!1);return}if(g.error?.kind==="conflicts"){p({source:y.source,subpath:y.subpath,scope:y.scope,skillDir:y.skillDir}),m(g.error.conflicts),d(!0);return}if(g.error?.kind==="authRequired"){se.error(g.error.message||"Authentication required");return}se.error(g.error?.message||"Failed to install skill")};return t?e.jsxs(e.Fragment,{children:[e.jsx(os,{open:s,onOpenChange:r,children:e.jsxs(as,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(ds,{children:[e.jsx(us,{children:"Install skill"}),e.jsxs(Is,{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(Bs,{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(Ms,{value:a,onValueChange:y=>i(y),children:[e.jsx(Ds,{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(hs,{className:"h-4 w-4"}):e.jsx(nr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(As,{align:"start",children:[e.jsx(Ft,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Ft,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nr,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]})})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(ve,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(ve,{className:"w-full sm:w-auto",variant:"default",disabled:o||!t.installable,onClick:()=>{h({source:t.repoSource,subpath:t.repoSubpath,scope:a,skillDir:t.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(iw,{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},cw=async()=>{try{if(Xt())return await Qr();const s=Nr()?.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}},dw=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:i,isLoadingCatalog:c,lastCatalogError:d}=ki(),[u,m]=l.useState(""),[f,p]=l.useState(!1),[h,y]=l.useState(!1),[g,w]=l.useState(null),[x,v]=l.useState(!1);l.useEffect(()=>{i()},[i]);const S=l.useMemo(()=>o?n[o]||[]:[],[n,o]),N=l.useMemo(()=>{const I=u.trim().toLowerCase();return I?S.filter(M=>{const b=M.skillName.toLowerCase(),C=(M.description||"").toLowerCase(),A=(M.frontmatterName||"").toLowerCase();return b.includes(I)||C.includes(I)||A.includes(I)}):S},[S,u]),j=l.useMemo(()=>t.find(I=>I.id===o)||null,[t,o]),k=!!(o&&o.startsWith("custom:")),F=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){v(!0);try{const I=await cw(),b=(Array.isArray(I?.skillCatalogs)?I?.skillCatalogs:[]).filter(C=>C.id!==o);await es({skillCatalogs:b}),await i({refresh:!0})}finally{v(!1)}}};return e.jsx(tt,{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(yi,{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(Ms,{value:o||"",onValueChange:I=>a(I),children:[e.jsx(Ds,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:j?.label||"Select source"})}),e.jsx(As,{align:"start",children:t.map(I=>e.jsx(Ft,{value:I.id,className:"pr-2 [&>span:first-child]:hidden",children:I.label},I.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ve,{type:"button",variant:"outline",onClick:()=>{i({refresh:!0})},disabled:c,className:"gap-2",children:[e.jsx(kn,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(ve,{type:"button",variant:"outline",onClick:()=>{F()},disabled:x,className:"gap-2",children:[e.jsx(Es,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(ve,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Ht,{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(dt,{value:u,onChange:I=>m(I.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:c?"Loading…":`${N.length} skill(s)`})]}),d?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.length===0?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):N.map(I=>{const M=I.installed?.isInstalled,b=I.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:I.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 (",b||"unknown",")"]}):null,I.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"})]}),I.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:I.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),I.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:I.warnings.join(" · ")}):null]}),e.jsx(ve,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!I.installable,onClick:()=>{w(I),y(!0)},children:"Install"})]})},`${I.sourceId}:${I.skillDir}`)})}),e.jsx(aw,{open:f,onOpenChange:p}),e.jsx(lw,{open:h,onOpenChange:y,item:g})]})})},uw=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:i,setSkillDraft:c,setSelectedSkill:d}=sr(),u=s?r(s):null,m=!!(i&&i.name===s&&!u),f=!!(s&&!u&&!i),[p,h]=l.useState("manual");l.useEffect(()=>{!m&&p!=="manual"&&h("manual")},[m,p]),l.useEffect(()=>{f&&d(null)},[f,d]);const y=m?e.jsx(yi,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:h,animate:!1}):null,[g,w]=l.useState(""),[x,v]=l.useState("user"),[S,N]=l.useState(""),[j,k]=l.useState(""),[F,I]=l.useState([]),[M,b]=l.useState([]),[C,A]=l.useState(!1),[P,L]=l.useState(!1),[$,q]=l.useState(""),[ee,ce]=l.useState(""),[_,z]=l.useState(!1),[D,H]=l.useState(""),[X,he]=l.useState(""),[ae,fe]=l.useState(null),[je,W]=l.useState(!1),[te,oe]=l.useState(""),V=m?g.trim()!==""||S.trim()!==""||j.trim()!==""||M.length>0:S!==$||j!==ee,ue=ae?X!==te:D.trim()!=="";l.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&i)w(i.name||""),v(i.scope||"user"),N(i.description||""),k(i.instructions||""),q(""),ce(""),I([]),b(i.pendingFiles||[]);else if(s&&u){L(!0);try{const G=await t(s);if(G){const T=G.sources.md;N(T.description||""),k(T.instructions||""),q(T.description||""),ce(T.instructions||""),I(T.supportingFiles||[])}}catch(G){console.error("Failed to load skill details:",G)}finally{L(!1)}}})()},[u,m,s,a,i,t,p]);const ge=async()=>{const K=m?g.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!K){se.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(K)||K.length>64){se.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!S.trim()){se.error("Description is required");return}if(m&&a.some(G=>G.name===K)){se.error("A skill with this name already exists");return}A(!0);try{const G={name:K,description:S.trim(),instructions:j.trim()||void 0,scope:m?x:void 0,supportingFiles:m&&M.length>0?M:void 0};let T;m?(T=await n(G),T&&(c(null),b([]),d(K))):(T=await o(K,G),T&&(q(S.trim()),ce(j.trim()))),T?se.success(m?"Skill created successfully":"Skill updated successfully"):se.error(m?"Failed to create skill":"Failed to update skill")}catch(G){console.error("Error saving skill:",G),se.error("An error occurred while saving")}finally{A(!1)}},ie=()=>{fe(null),H(""),he(""),oe(""),z(!0)},De=async K=>{if(fe(K),H(K),m){const T=M.find(Y=>Y.path===K)?.content||"";he(T),oe(T),z(!0);return}if(s){W(!0),z(!0);try{const{readSupportingFile:G}=sr.getState(),T=await G(s,K);he(T||""),oe(T||"")}catch{se.error("Failed to load file content"),he(""),oe("")}finally{W(!1)}}},Ce=async()=>{if(!D.trim()){se.error("File name is required");return}const K=D.trim(),G=ae!==null;if(m){if(G)b(E=>E.map(B=>B.path===ae?{path:K,content:X}:B)),se.success(`File "${K}" updated`);else{if(M.some(E=>E.path===K)){se.error("A file with this name already exists");return}b(E=>[...E,{path:K,content:X}]),se.success(`File "${K}" added`)}z(!1),fe(null);return}if(!s){se.error("No skill selected");return}const{writeSupportingFile:T}=sr.getState();if(await T(s,K,X)){se.success(G?`File "${K}" updated`:`File "${K}" created`),z(!1),fe(null);const E=await t(s);E&&I(E.sources.md.supportingFiles||[])}else se.error(G?"Failed to update file":"Failed to create file")},Ie=async K=>{if(m){b(G=>G.filter(T=>T.path!==K)),se.success(`File "${K}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${K}"?`)){const{deleteSupportingFile:G}=sr.getState();if(await G(s,K)){se.success(`File "${K}" deleted`);const Y=await t(s);Y&&I(Y.sources.md.supportingFiles||[])}else se.error("Failed to delete file")}};return m&&p==="external"?e.jsx(dw,{mode:p,onModeChange:h}):!s&&!i||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(ed,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a skill from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})}):P?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skill details..."})})}):e.jsx(tt,{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(dt,{value:g,onChange:K=>w(K.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(Ms,{value:x,onValueChange:K=>v(K),children:[e.jsxs(Ds,{className:"!h-9 w-auto gap-1.5",children:[x==="user"?e.jsx(hs,{className:"h-4 w-4"}):e.jsx(nr,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:x})]}),e.jsxs(As,{align:"end",children:[e.jsx(Ft,{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(hs,{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(Ft,{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(nr,{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(Cs,{value:S,onChange:K=>N(K.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(Cs,{value:j,onChange:K=>k(K.target.value),placeholder:"Step-by-step instructions, guidelines, or reference content...",rows:12,className:"font-mono typography-meta max-h-80 resize-y"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Supporting Files"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Reference documentation, scripts, or templates"})]}),e.jsxs(ve,{variant:"outline",size:"sm",onClick:ie,className:"gap-1.5",children:[e.jsx(Ht,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const K=m?M:F;return K.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:K.map(G=>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:()=>De(G.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:G.path}),m&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"pending"})]}),e.jsx(ve,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:T=>{T.stopPropagation(),Ie(G.path)},children:e.jsx(Es,{className:"h-3.5 w-3.5"})})]},G.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(ve,{size:"sm",variant:"default",onClick:ge,disabled:C||!V,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Mo,{className:"h-3 w-3"}),C?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(os,{open:_,onOpenChange:K=>{z(K),K||fe(null)},children:e.jsxs(as,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(ds,{className:"flex-shrink-0",children:[e.jsx(us,{children:ae?"Edit Supporting File":"Add Supporting File"}),e.jsx(Is,{children:ae?"Modify the file content":"Create a new file in the skill directory"})]}),je?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(dt,{value:D,onChange:K=>H(K.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:ae!==null}),!ae&&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(Cs,{value:X,onChange:K=>he(K.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Bs,{children:[e.jsx(ve,{variant:"ghost",onClick:()=>{z(!1),fe(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(jr,{onClick:Ce,disabled:je||!ue,children:ae?"Save Changes":"Create File"})]})]})})]})})},mw="__add_provider__",fw=({onItemSelect:s})=>{const r=lt(u=>u.providers),t=lt(u=>u.selectedProviderId),n=lt(u=>u.setSelectedProvider),{isMobile:o}=Nt(),[a,i]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=l.useMemo(()=>Dt(),[]);l.useEffect(()=>{typeof window>"u"||i(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:O("flex h-full flex-col",d),children:[e.jsx("div",{className:O("border-b px-3",o?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",r.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(mw),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Ht,{className:"size-4"})})]})}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:r.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(xn,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No providers found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]}):r.map(u=>{const m=Array.isArray(u.models)?u.models.length:0,f=u.id===t;return e.jsx("div",{className:O("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(qt,{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)})})]})},pw=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),xc=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=pw.format(s);return r.endsWith(".0")?r.slice(0,-2):r},yc="__add_provider__",Gr=s=>typeof s=="object"&&s!==null,bc=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()},hw=s=>{if(!Gr(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>Gr(o)));return r},gw=s=>{if(typeof s=="string")return{id:s};if(!Gr(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}},xw=s=>{let r=[];Array.isArray(s)?r=s:Gr(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>gw(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},yw=()=>{const s=lt(V=>V.providers),r=lt(V=>V.selectedProviderId),t=lt(V=>V.setSelectedProvider),n=lt(V=>V.loadProviders),o=lt(V=>V.getModelMetadata),[a,i]=l.useState({}),[c,d]=l.useState(!1),[u,m]=l.useState({}),[f,p]=l.useState(null),[h,y]=l.useState(""),[g,w]=l.useState(null),[x,v]=l.useState({}),[S,N]=l.useState({}),[j,k]=l.useState([]),[F,I]=l.useState(!1),[M,b]=l.useState(null),[C,A]=l.useState(""),[P,L]=l.useState(""),[$,q]=l.useState(!1);l.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),l.useEffect(()=>{let V=!0;return(async()=>{d(!0);try{const ge=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!ge.ok)throw new Error(`Auth methods request failed (${ge.status})`);const ie=await ge.json().catch(()=>({}));if(!V)return;i(hw(ie))}catch(ge){if(!V)return;console.error("Failed to load provider auth methods:",ge),se.error("Failed to load provider authentication methods")}finally{V&&d(!1)}})(),()=>{V=!1}},[]),l.useEffect(()=>{let V=!0;return(async()=>{I(!0),b(null);try{const ge=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!ge.ok)throw new Error(`Provider list request failed (${ge.status})`);const ie=await ge.json().catch(()=>({}));if(!V)return;k(xw(ie))}catch(ge){if(!V)return;console.error("Failed to load available providers:",ge),b("Unable to load provider list")}finally{V&&I(!1)}})(),()=>{V=!1}},[]);const ee=l.useMemo(()=>new Set(s.map(V=>V.id)),[s]),ce=l.useMemo(()=>j.filter(V=>!ee.has(V.id)),[j,ee]);l.useEffect(()=>{if(r===yc){if(!C&&ce.length>0){A(ce[0].id);return}C&&!ce.some(V=>V.id===C)&&A(ce[0]?.id??"")}},[r,C,ce]);const _=s.find(V=>V.id===r),z=async V=>{const ue=u[V]?.trim()??"";if(!ue){se.error("API key is required");return}const ge=`api:${V}`;p(ge);try{const ie=await fetch(`/api/auth/${encodeURIComponent(V)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:ue})}),De=await ie.json().catch(()=>null);if(!ie.ok){const Ce=De?.error||"Failed to save API key";throw new Error(Ce)}se.success("API key saved"),m(Ce=>({...Ce,[V]:""})),await un(),await n(),t(V)}catch(ie){console.error("Failed to save API key:",ie),se.error("Failed to save API key")}finally{p(null)}},D=async(V,ue)=>{const ge=`oauth:${V}:${ue}`;p(ge);try{const ie=await fetch(`/api/provider/${encodeURIComponent(V)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:ue})}),De=await ie.json().catch(()=>null);if(!ie.ok){const E=De?.error||"Failed to start OAuth flow";throw new Error(E)}const Ce=Gr(De)?De:{},Ie=Gr(Ce.data)?Ce.data:Ce,K=typeof Ie.url=="string"&&Ie.url||typeof Ie.verification_uri_complete=="string"&&Ie.verification_uri_complete||typeof Ie.verification_uri=="string"&&Ie.verification_uri||void 0,G=typeof Ie.instructions=="string"&&Ie.instructions||typeof Ie.message=="string"&&Ie.message||void 0,T=typeof Ie.user_code=="string"&&Ie.user_code||typeof Ie.code=="string"&&Ie.code||typeof Ie.userCode=="string"&&Ie.userCode||void 0;if(!K&&!G&&!T)throw new Error("No OAuth details returned");const Y=`${V}:${ue}`;N(E=>({...E,[Y]:{url:K,instructions:G,userCode:T}})),K&&window.open(K,"_blank","noopener,noreferrer"),w({providerId:V,methodIndex:ue}),se.message("Complete the OAuth flow in your browser")}catch(ie){console.error("Failed to start OAuth flow:",ie),se.error("Failed to start OAuth flow")}finally{p(null)}},H=async(V,ue)=>{const ge=`${V}:${ue}`,ie=x[ge]?.trim(),De=`oauth-complete:${V}:${ue}`;p(De);try{const Ce={method:ue};ie&&(Ce.code=ie);const Ie=await fetch(`/api/provider/${encodeURIComponent(V)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ce)}),K=await Ie.json().catch(()=>null);if(!Ie.ok){const G=K?.error||"Failed to complete OAuth flow";throw new Error(G)}se.success("OAuth connection completed"),v(G=>({...G,[ge]:""})),w(null),await un(),await n(),t(V)}catch(Ce){console.error("Failed to complete OAuth flow:",Ce),se.error("Failed to complete OAuth flow")}finally{p(null)}},X=async V=>{try{await navigator.clipboard.writeText(V),se.success("OAuth link copied")}catch(ue){console.error("Failed to copy OAuth link:",ue),se.error("Failed to copy OAuth link")}},he=async V=>{try{await navigator.clipboard.writeText(V),se.success("Device code copied")}catch(ue){console.error("Failed to copy device code:",ue),se.error("Failed to copy device code")}},ae=async V=>{const ue=`disconnect:${V}`;p(ue);try{const ge=await fetch(`/api/provider/${encodeURIComponent(V)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),ie=await ge.json().catch(()=>null);if(!ge.ok){const De=ie?.error||"Failed to disconnect provider";throw new Error(De)}se.success("Provider disconnected"),await un(),await n()}catch(ge){console.error("Failed to disconnect provider:",ge),se.error("Failed to disconnect provider")}finally{p(null)}},fe=r===yc;if(!fe&&s.length===0)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(xn,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"No providers detected"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]})});if(fe)return e.jsx(tt,{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."})]}),F?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M}):ce.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(Gt,{open:$,onOpenChange:V=>{q(V),V||L("")},children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("button",{type:"button",className:O("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:C?"text-foreground":"text-muted-foreground",children:C?ce.find(V=>V.id===C)?.name||C:"Select provider"}),e.jsx(kt,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Yt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:V=>V.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:V=>V.stopPropagation(),children:[e.jsx(vr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:P,onChange:V=>L(V.target.value),onKeyDown:V=>V.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(tt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const V=ce.filter(ue=>{const ge=P.toLowerCase();return(ue.name||ue.id).toLowerCase().includes(ge)||ue.id.toLowerCase().includes(ge)});return V.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):V.map(ue=>e.jsxs(St,{onSelect:()=>{A(ue.id),q(!1),L("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:ue.name||ue.id}),C===ue.id&&e.jsx(Mt,{className:"h-4 w-4 text-primary"})]},ue.id))})()})]})]})]}),C&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{type:"password",value:u[C]??"",onChange:V=>m(ue=>({...ue,[C]:V.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>z(C),disabled:f===`api:${C}`,className:"h-8",children:f===`api:${C}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),(()=>{const ue=(a[C]??[]).filter(ge=>bc(ge)==="oauth");return ue.length===0?null:e.jsx("div",{className:"space-y-3",children:ue.map((ge,ie)=>{const De=ge.label||ge.name||`OAuth method ${ie+1}`,Ce=`${C}:${ie}`,Ie=g?.providerId===C&&g?.methodIndex===ie;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:De}),(ge.description||ge.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(ge.description||ge.help)})]}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>D(C,ie),disabled:f===`oauth:${C}:${ie}`,className:"h-8",children:"Connect"})]}),S[Ce]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:S[Ce]?.instructions}),S[Ce]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[Ce]?.userCode,readOnly:!0}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>he(S[Ce]?.userCode??""),className:"h-8",children:"Copy code"})]}),S[Ce]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[Ce]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ve,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:S[Ce]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>X(S[Ce]?.url??""),className:"h-8",children:"Copy link"})]})]}),Ie&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:x[Ce]??"",onChange:K=>v(G=>({...G,[Ce]:K.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(ve,{size:"sm",onClick:()=>H(C,ie),disabled:f===`oauth-complete:${C}:${ie}`,className:"h-8",children:f===`oauth-complete:${C}:${ie}`?"Saving…":"Complete"})]})]},`${C}-${De}`)})})})()]})]})]})});if(!_)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(xn,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a provider from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Review details and configure auth"})]})});const je=Array.isArray(_.models)?_.models:[],te=(a[_.id]??[]).filter(V=>bc(V)==="oauth"),oe=je.filter(V=>{const ue=typeof V?.name=="string"?V.name:"",ge=typeof V?.id=="string"?V.id:"",ie=h.trim().toLowerCase();return ie?ue.toLowerCase().includes(ie)||ge.toLowerCase().includes(ie):!0});return e.jsx(tt,{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(qt,{providerId:_.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:_.name||_.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",_.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),c?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{type:"password",value:u[_.id]??"",onChange:V=>m(ue=>({...ue,[_.id]:V.target.value})),placeholder:"sk-..."}),e.jsx(ve,{size:"sm",onClick:()=>z(_.id),disabled:f===`api:${_.id}`,className:"h-8",children:f===`api:${_.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(ve,{size:"sm",variant:"outline",onClick:()=>ae(_.id),disabled:f===`disconnect:${_.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:f===`disconnect:${_.id}`?"Disconnecting…":"Disconnect provider"})}),te.length>0&&e.jsx("div",{className:"space-y-3",children:te.map((V,ue)=>{const ge=V.label||V.name||`OAuth method ${ue+1}`,ie=`${_.id}:${ue}`,De=g?.providerId===_.id&&g?.methodIndex===ue;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:ge}),(V.description||V.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(V.description||V.help)})]}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>D(_.id,ue),disabled:f===`oauth:${_.id}:${ue}`,className:"h-8",children:"Connect"})]}),S[ie]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:S[ie]?.instructions}),S[ie]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[ie]?.userCode,readOnly:!0}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>he(S[ie]?.userCode??""),className:"h-8",children:"Copy code"})]}),S[ie]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(dt,{value:S[ie]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ve,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:S[ie]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(ve,{size:"sm",variant:"outline",onClick:()=>X(S[ie]?.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(dt,{value:x[ie]??"",onChange:Ce=>v(Ie=>({...Ie,[ie]:Ce.target.value})),placeholder:"Paste authorization code"}),e.jsx(ve,{size:"sm",onClick:()=>H(_.id,ue),disabled:f===`oauth-complete:${_.id}:${ue}`,className:"h-8",children:f===`oauth-complete:${_.id}:${ue}`?"Saving…":"Complete"})]})]},`${_.id}-${ge}`)})})]})]}),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(dt,{value:h,onChange:V=>y(V.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:oe.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):oe.map(V=>{const ue=typeof V?.id=="string"?V.id:"",ge=typeof V?.name=="string"?V.name:ue,ie=ue?o(_.id,ue):void 0,De=xc(ie?.limit?.context),Ce=xc(ie?.limit?.output),Ie=[];return ie?.tool_call&&Ie.push({key:"tools",icon:Co,label:"Tool calling"}),ie?.reasoning&&Ie.push({key:"reasoning",icon:Yr,label:"Reasoning"}),ie?.attachment&&Ie.push({key:"image",icon:rr,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:ge}),(De||Ce)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[De?`${De} ctx`:"",De&&Ce?" · ":"",Ce?`${Ce} out`:""]}),Ie.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:Ie.map(({key:K,icon:G,label:T})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:T,"aria-label":T,children:e.jsx(G,{className:"h-3 w-3"})},K))})]},ue)})})]})]})})},bw={branch:ns,briefcase:ti,house:ei,graduation:Za,code:_s,heart:Xc},ww={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},vw=({onItemSelect:s})=>{const{selectedProfileId:r,profiles:t,globalIdentity:n,setSelectedProfile:o,deleteProfile:a,loadProfiles:i,loadGlobalIdentity:c}=Io(),{setSidebarOpen:d}=Fe(),{isMobile:u}=Nt(),[m,f]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),p=l.useMemo(()=>Dt(),[]);l.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{i(),c()},[i,c]);const h=m?"bg-transparent":p?"bg-background":"bg-sidebar",y=()=>{o("new"),s?.(),u&&d(!1)},g=async w=>{window.confirm(`Are you sure you want to delete profile "${w.name}"?`)&&(await a(w.id)?se.success(`Profile "${w.name}" deleted successfully`):se.error("Failed to delete profile"))};return e.jsxs("div",{className:O("flex h-full flex-col",h),children:[e.jsx("div",{className:O("border-b px-3",u?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",t.length]}),e.jsx(ve,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:y,children:e.jsx(Ht,{className:"size-4"})})]})}),e.jsxs(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"System Default"}),e.jsx(wc,{profile:n,isSelected:r==="global",onSelect:()=>{o("global"),s?.(),u&&d(!1)},onDelete:void 0,isReadOnly:!0})]}),t.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),t.length===0&&!n?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(ns,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:t.map(w=>e.jsx(wc,{profile:w,isSelected:r===w.id,onSelect:()=>{o(w.id),s?.(),u&&d(!1)},onDelete:()=>g(w)},w.id))})]})]})},wc=({profile:s,isSelected:r,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=bw[s.icon||"branch"]||ns,i=ww[s.color||""];return e.jsx("div",{className:O("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.jsx(a,{className:"w-4 h-4 flex-shrink-0",style:{color:i}}),e.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 text-foreground",children:s.name})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.userEmail})]}),!o&&n&&e.jsxs(Gt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(ve,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Sn,{className:"h-3.5 w-3.5"})})}),e.jsx(Yt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(St,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})},vc=[{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)"}],jw=[{key:"branch",Icon:ns,label:"Branch"},{key:"briefcase",Icon:ti,label:"Work"},{key:"house",Icon:ei,label:"Personal"},{key:"graduation",Icon:Za,label:"School"},{key:"code",Icon:_s,label:"Code"}],Sw=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=Io(),a=l.useMemo(()=>s&&s!=="new"?r(s):null,[s,r]),i=s==="new",c=s==="global",[d,u]=l.useState(""),[m,f]=l.useState(""),[p,h]=l.useState(""),[y,g]=l.useState(""),[w,x]=l.useState("keyword"),[v,S]=l.useState("branch"),[N,j]=l.useState(!1);l.useEffect(()=>{i?(u(""),f(""),h(""),g(""),x("keyword"),S("branch")):a&&(u(a.name),f(a.userName),h(a.userEmail),g(a.sshKey||""),x(a.color||"keyword"),S(a.icon||"branch"))},[a,i,s]);const k=async()=>{if(!m.trim()||!p.trim()){se.error("User name and email are required");return}j(!0);try{const M={name:d.trim()||m.trim(),userName:m.trim(),userEmail:p.trim(),sshKey:y.trim()||null,color:w,icon:v};let b;if(i)b=await t(M);else if(s)b=await n(s,M);else return;b?se.success(i?"Profile created successfully":"Profile updated successfully"):se.error(i?"Failed to create profile":"Failed to update profile")}catch(M){console.error("Error saving profile:",M),se.error("An error occurred while saving")}finally{j(!1)}},F=async()=>{if(!(!s||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(s)?se.success("Profile deleted successfully"):se.error("Failed to delete profile")}catch(M){console.error("Error deleting profile:",M),se.error("An error occurred while deleting")}},I=l.useMemo(()=>vc.find(b=>b.key===w)?.cssVar||"var(--syntax-keyword)",[w]);return s?e.jsx(tt,{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:i?"New Git Profile":c?"Global Identity":d||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:i?"Create a new Git identity profile for your repositories":c?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!c&&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(dt,{value:d,onChange:M=>u(M.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:vc.map(M=>e.jsx("button",{onClick:()=>x(M.key),className:O("w-8 h-8 rounded-lg border-2 transition-all",w===M.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:M.cssVar},title:M.label},M.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:jw.map(M=>{const b=M.Icon;return e.jsx("button",{onClick:()=>S(M.key),className:O("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",v===M.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:M.label,children:e.jsx(b,{className:"w-4 h-4",style:{color:I}})},M.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 ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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(dt,{value:m,onChange:M=>f(M.target.value),placeholder:"John Doe",required:!c,readOnly:c,disabled:c}),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 ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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(dt,{type:"email",value:p,onChange:M=>h(M.target.value),placeholder:"john@example.com",required:!c,readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email 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:["SSH Key Path",e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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 HTTPS and SSH Git operations.",e.jsx("br",{}),"Common paths: ~/.ssh/id_rsa, ~/.ssh/id_ed25519"]})]})]}),e.jsx(dt,{value:y,onChange:M=>g(M.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!c&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(ve,{size:"sm",variant:"destructive",onClick:F,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Es,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:O("flex gap-2",i&&"ml-auto"),children:e.jsxs(ve,{size:"sm",variant:"default",onClick:k,disabled:N,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Mo,{className:"h-3 w-3"}),N?"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(hs,{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 ha(s,r,t){return Math.min(t,Math.max(r,s))}const wo=Se.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=Se.useRef(null);Se.useImperativeHandle(f,()=>p.current);const[h,y]=Se.useState(()=>String(s));Se.useEffect(()=>{document.activeElement!==p.current&&y(String(s))},[s]);const g=Se.useCallback(()=>{p.current?.focus()},[]),w=Se.useCallback(b=>{const C=ha(b,t,n);r(C),y(String(C))},[n,t,r]),x=Se.useCallback(()=>{const b=Number(h);return Number.isFinite(b)?b:s},[h,s]),v=Se.useCallback(()=>{w(x()+o),g()},[w,x,g,o]),S=Se.useCallback(()=>{w(x()-o),g()},[w,x,g,o]),N=b=>{const C=b.target.value;y(C);const A=Number(C);Number.isFinite(A)&&r(ha(A,t,n))},j=b=>{const C=Number(h);if(!Number.isFinite(C))y(String(s));else{const A=ha(C,t,n);A!==C&&r(A),y(String(A))}c?.(b)},k=b=>{if(b.key==="ArrowUp"){b.preventDefault(),v();return}if(b.key==="ArrowDown"){b.preventDefault(),S();return}d?.(b)},F=x(),I=u||F<=t,M=u||F>=n;return e.jsxs("div",{className:O("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",i),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:N,onBlur:j,onKeyDown:k,disabled:u,className:O("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:O("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(ko,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:I,onClick:S,className:O("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(kt,{className:"h-3.5 w-3.5"})})]})]})});wo.displayName="NumberInput";const kw=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],jc=[{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"}],Sc=[{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."}],Ni=({visibleSettings:s})=>{const{isMobile:r}=Nt(),t=Fe(S=>S.showReasoningTraces),n=Fe(S=>S.setShowReasoningTraces),o=Fe(S=>S.toolCallExpansion),a=Fe(S=>S.setToolCallExpansion),i=Fe(S=>S.fontSize),c=Fe(S=>S.setFontSize),d=Fe(S=>S.padding),u=Fe(S=>S.setPadding),m=Fe(S=>S.inputBarOffset),f=Fe(S=>S.setInputBarOffset),p=Fe(S=>S.diffLayoutPreference),h=Fe(S=>S.setDiffLayoutPreference),y=Rs(S=>S.queueModeEnabled),g=Rs(S=>S.setQueueMode),{themeMode:w,setThemeMode:x}=Dr(),v=S=>s?s.includes(S):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[v("theme")&&!Dt()&&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:kw.map(S=>e.jsx(ws,{variant:w===S.value?"default":"outline",className:O(w===S.value?void 0:"text-foreground"),onClick:()=>x(S.value),children:S.label},S.value))})]}),v("fontSize")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Font Size"})}),e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:i,onChange:S=>c(Number(S.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(wo,{value:i,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(ws,{type:"button",variant:"ghost",onClick:()=>c(100),disabled:i===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(fs,{className:"h-3.5 w-3.5"})})]})]}),v("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:S=>u(Number(S.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(ws,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(fs,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:d,onChange:S=>u(Number(S.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(wo,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(ws,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(fs,{className:"h-3.5 w-3.5"})})]})]}),v("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:S=>f(Number(S.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(ws,{type:"button",variant:"ghost",onClick:()=>f(0),disabled:m===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(fs,{className:"h-3.5 w-3.5"})})]})]}),v("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:jc.find(S=>S.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:jc.map(S=>e.jsx(ws,{variant:o===S.value?"default":"outline",className:O(o===S.value?void 0:"text-foreground"),onClick:()=>a(S.value),children:S.label},S.value))})]}),v("diffLayout")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:Sc.map(S=>e.jsx(ws,{variant:p===S.id?"default":"outline",className:O(p===S.id?void 0:"text-foreground"),onClick:()=>h(S.id),children:S.label},S.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Sc.find(S=>S.id===p)?.description})]})]}),v("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:S=>n(S.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),v("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:y,onChange:S=>g(S.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:y?"Enter queues messages, Ctrl+Enter sends immediately.":"Enter sends immediately, Ctrl+Enter queues messages."})]})]})},kc="https://github.com/btriapitsyn/openchamber",Nw=800,Cu=()=>{const[s,r]=l.useState(!1),[t,n]=l.useState(!1),o=Do(),{isMobile:a}=Nt(),i=o.info?.currentVersion||"unknown",c=l.useRef(!1);l.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(t){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(se.success("You are on the latest version"),c.current=!1)},Nw);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:()=>un(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(fs,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",i]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:O("typography-meta text-muted-foreground/60 hover:text-muted-foreground disabled:cursor-default",d&&"animate-pulse [animation-duration:1s]"),children:"Check updates"}),!d&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:"flex items-center gap-1 typography-meta text-primary hover:underline",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),"Update"]})]}),o.error&&e.jsx("p",{className:"typography-micro text-destructive truncate",children:o.error}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("a",{href:kc,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ma,{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(td,{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(Da,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Pa,{open:s,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]}):e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:i})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Wn,{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:O("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Wr,{className:"h-4 w-4"}),"Update to ",o.info?.version]}),!o.checking&&!o.available&&!o.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"})]}),o.error&&e.jsx("p",{className:"typography-meta text-destructive",children:o.error}),e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:o.checking,className:O("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:kc,target:"_blank",rel:"noopener noreferrer",className:O("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ma,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:O("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Pa,{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})]})},Cw=1440*60*1e3,Mu=5,Nc=1440*60*1e3,ga=s=>s.time?.updated??s.time?.created??0,Cc=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=Mu,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*Cw,i=[...s].sort((d,u)=>ga(u)-ga(d)),c=new Set(i.slice(0,n).map(d=>d.id));return i.filter(d=>{if(!d?.id||c.has(d.id)||d.id===r||d.share)return!1;const u=ga(d);return u?u<a:!1}).map(d=>d.id)},Du=s=>{const r=s?.autoRun!==!1,t=ye(g=>g.sessions),n=ye(g=>g.currentSessionId),o=ye(g=>g.isLoading),a=ye(g=>g.deleteSessions),i=Fe(g=>g.autoDeleteEnabled),c=Fe(g=>g.autoDeleteAfterDays),d=Fe(g=>g.autoDeleteLastRunAt),u=Fe(g=>g.setAutoDeleteLastRunAt),[m,f]=l.useState(!1),p=l.useRef(!1),h=l.useMemo(()=>c<=0?[]:Cc({sessions:t,currentSessionId:n,cutoffDays:c}),[c,n,t]),y=l.useCallback(async({force:g=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!i||c<=0)&&!g)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const w=Date.now();if(!g&&d&&w-d<Nc)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const x=Cc({sessions:t,currentSessionId:n,cutoffDays:c,now:w});if(x.length===0)return u(w),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(x,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[c,i,d,n,a,o,t,u]);return l.useEffect(()=>{if(!r||!i||c<=0||o||t.length===0)return;const g=Date.now();d&&g-d<Nc||y()},[c,i,d,r,o,t.length,y]),{candidates:h,isRunning:m,runCleanup:y,keepRecentCount:Mu}},xa=1,ya=365,Au=()=>{const{isMobile:s}=Nt(),r=Fe(p=>p.autoDeleteEnabled),t=Fe(p=>p.autoDeleteAfterDays),n=Fe(p=>p.setAutoDeleteEnabled),o=Fe(p=>p.setAutoDeleteAfterDays),[a,i]=l.useState(String(t));l.useEffect(()=>{i(String(t))},[t]);const{candidates:c,isRunning:d,runCleanup:u}=Du({autoRun:!1}),m=c.length,f=l.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){se.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&se.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&se.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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{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(i(h),h.trim()==="")return;const y=Number(h);if(!Number.isFinite(y))return;const g=Math.min(ya,Math.max(xa,Math.round(y)));o(g)},onBlur:()=>{if(a.trim()===""){i(String(t));return}const p=Number(a);if(!Number.isFinite(p)){i(String(t));return}const h=Math.min(ya,Math.max(xa,Math.round(p)));o(h),i(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(wo,{value:t,onValueChange:o,min:xa,max:ya,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(ws,{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]})]})},Eu=()=>{const s=lt(g=>g.setProvider),r=lt(g=>g.setModel),t=lt(g=>g.setAgent),n=lt(g=>g.setSettingsDefaultModel),o=lt(g=>g.setSettingsDefaultAgent),a=lt(g=>g.providers),[i,c]=l.useState(),[d,u]=l.useState(),[m,f]=l.useState(!0),p=l.useMemo(()=>{if(!i)return{providerId:"",modelId:""};const g=i.split("/");return g.length!==2?{providerId:"",modelId:""}:{providerId:g[0]||"",modelId:g[1]||""}},[i]);l.useEffect(()=>{(async()=>{try{let w=null;if(Xt())w=await Qr();else{const x=Nr()?.settings;if(x)try{const S=(await x.load())?.settings;S&&(w={defaultModel:typeof S.defaultModel=="string"?S.defaultModel:void 0,defaultAgent:typeof S.defaultAgent=="string"?S.defaultAgent:void 0})}catch{}if(!w){const v=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});v.ok&&(w=await v.json())}}w&&(c(w.defaultModel),u(w.defaultAgent))}catch(w){console.warn("Failed to load defaults settings:",w)}finally{f(!1)}})()},[]);const h=l.useCallback(async(g,w)=>{const x=g&&w?`${g}/${w}`:void 0;c(x),n(x),g&&w&&a.find(S=>S.id===g)&&(s(g),r(w));try{await es({defaultModel:x??""})}catch(v){console.warn("Failed to save default model:",v)}},[a,s,r,n]),y=l.useCallback(async g=>{const w=g||void 0;u(w),o(w),g&&t(g);try{await es({defaultAgent:w??""})}catch(x){console.warn("Failed to save default agent:",x)}},[t,o]);return m?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:"Default model & agent"}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(_t,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(Xe,{sideOffset:8,className:"max-w-xs",children:["Set the default model and agent for new sessions.",e.jsx("br",{}),"When not set, uses agent's preferred model or opencode/big-pickle as fallback."]})]})]})}),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(Si,{providerId:p.providerId,modelId:p.modelId,onChange:h})]}),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(Nu,{agentName:d||"",onChange:y})]})]}),(i||d)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",i&&e.jsx("span",{className:"text-foreground",children:i}),i&&d&&" / ",d&&e.jsx("span",{className:"text-foreground",children:d})]})]})},Mw=({section:s})=>{const{isMobile:r}=Nt(),t=r&&ni();if(!s)return e.jsxs(tt,{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(Ni,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Eu,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Au,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Cu,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(Dw,{});case"chat":return e.jsx(Aw,{});case"sessions":return e.jsx(Ew,{});default:return null}};return e.jsx(tt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},Dw=()=>e.jsx(Ni,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),Aw=()=>e.jsx(Ni,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),Ew=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Eu,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Au,{})})]}),Iw=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]}],Tw=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=Nt(),n=t&&ni(),[o,a]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),i=l.useMemo(()=>Dt(),[]);l.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const c=o?"bg-transparent":i?"bg-background":"bg-sidebar";return e.jsxs("div",{className:O("flex h-full flex-col",c),children:[e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:Iw.map(d=>{const u=s===d.id;return e.jsx("div",{className:O("group relative rounded-md px-1.5 py-1 transition-all duration-200",u?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{onClick:()=>r(d.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:d.label}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:d.items.join(" · ")})]})},d.id)})}),n&&e.jsx("div",{className:"border-t px-3 py-4",children:e.jsx(Cu,{})})]})},Fw=(()=>{const s=ku.filter(n=>n.id!=="sessions"),r=s.find(n=>n.id==="settings"),t=s.filter(n=>n.id!=="settings");return r?[r,...t]:s})(),ba=200,wa=500,Pw=264,Rw=700,qa=({onClose:s,forceMobile:r})=>{const t=Nt(),n=r??t.isMobile,[o,a]=l.useState("settings"),[i,c]=l.useState("visual"),[d,u]=l.useState(!1),[m,f]=l.useState(()=>typeof window<"u"?Math.min(wa,Math.max(ba,Math.floor(window.innerWidth*.2))):Pw),[p,h]=l.useState(!1),[y,g]=l.useState(!1),[w,x]=l.useState(0),v=l.useRef(null),S=l.useRef(0),N=l.useRef(m),[j,k]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),F=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),I=l.useMemo(()=>Dt(),[]);l.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),l.useEffect(()=>{const z=v.current;if(!z)return;const D=new ResizeObserver(H=>{for(const X of H)x(X.contentRect.width)});return D.observe(z),x(z.clientWidth),()=>D.disconnect()},[]);const M=w===0||w>=Rw;l.useEffect(()=>{if(typeof window>"u")return;const z=()=>{if(!p){const D=Math.min(wa,Math.max(ba,Math.floor(window.innerWidth*.2)));f(D)}};return window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[p]),l.useEffect(()=>{if(!y)return;const z=H=>{const X=H.clientX-S.current,he=Math.min(wa,Math.max(ba,N.current+X));f(he),h(!0)},D=()=>g(!1);return window.addEventListener("pointermove",z),window.addEventListener("pointerup",D,{once:!0}),()=>{window.removeEventListener("pointermove",z),window.removeEventListener("pointerup",D)}},[y]);const b=z=>{g(!0),S.current=z.clientX,N.current=m,z.preventDefault()},C=l.useCallback(async z=>{if(!z.target.closest("button, a, input, select, textarea")&&z.button===0&&j)try{const{getCurrentWindow:D}=await Ks(async()=>{const{getCurrentWindow:X}=await import("./vendor-.bun-CpaXrlrC.js").then(he=>he.c9);return{getCurrentWindow:X}},__vite__mapDeps([0,1]));await D().startDragging()}catch(D){console.error("Failed to start window dragging:",D)}},[j]),A=l.useCallback(async z=>{if(z.button===0&&j)try{const{getCurrentWindow:D}=await Ks(async()=>{const{getCurrentWindow:X}=await import("./vendor-.bun-CpaXrlrC.js").then(he=>he.c9);return{getCurrentWindow:X}},__vite__mapDeps([0,1]));await D().startDragging()}catch(D){console.error("Failed to start window dragging:",D)}},[j]),P=l.useCallback(z=>{a(z),u(!1)},[]),L=l.useCallback(()=>{n&&u(!0)},[n]),$=()=>{switch(o){case"settings":return e.jsx(Tw,{selectedSection:i,onSelectSection:z=>{c(z),L()}});case"agents":return e.jsx(Yb,{onItemSelect:L});case"commands":return e.jsx(ew,{onItemSelect:L});case"skills":return e.jsx(sw,{onItemSelect:L});case"providers":return e.jsx(fw,{onItemSelect:L});case"git-identities":return e.jsx(vw,{onItemSelect:L});default:return null}},q=()=>{switch(o){case"agents":return e.jsx(Zb,{});case"commands":return e.jsx(tw,{});case"skills":return e.jsx(uw,{});case"providers":return e.jsx(yw,{});case"git-identities":return e.jsx(Sw,{});case"settings":return e.jsx(Mw,{section:i});default:return null}},ee=F?"⌘":"Ctrl",ce=l.useMemo(()=>j&&F?"pl-[5.75rem]":"",[j,F]),_=j&&F;return e.jsxs("div",{ref:v,className:O("flex h-full flex-col overflow-hidden",j?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:C,className:O("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&ce,j?"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(Sf,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:O("flex items-center",n?"gap-1":"h-full"),children:[!n&&_&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),Fw.map(({id:z,label:D,icon:H})=>{const X=o===z,he=H;return n?e.jsxs(Qe,{delayDuration:500,children:[e.jsx(Je,{asChild:!0,children:e.jsx("button",{onClick:()=>P(z),className:O("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",X?"text-foreground":"text-muted-foreground"),"aria-pressed":X,"aria-label":D,children:e.jsx(he,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(Xe,{children:e.jsx("p",{children:D})})]},z):e.jsxs(l.Fragment,{children:[e.jsxs("button",{onClick:()=>P(z),onMouseDown:X?A:void 0,className:O("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",X?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",X?"text-foreground":"text-muted-foreground"),"aria-pressed":X,"aria-label":D,children:[e.jsx(he,{className:"h-4 w-4",weight:"regular"}),M&&e.jsx("span",{children:D})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},z)})]}),s&&e.jsx("div",{className:O("flex items-center",n?"":"pr-3"),children:e.jsxs(Qe,{delayDuration:500,children:[e.jsx(Je,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",className:O("inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",!n&&"app-region-no-drag"),children:e.jsx(zt,{className:"h-5 w-5"})})}),e.jsx(Xe,{children:e.jsxs("p",{children:["Close Settings (",ee,"+,)"]})})]})})]}),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(Bt,{children:q()})}):e.jsx("div",{className:O("flex-1 overflow-hidden",I?"bg-background":"bg-sidebar"),children:e.jsx(Bt,{children:$()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:O("relative overflow-hidden border-r",j?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":I?"bg-background":"bg-sidebar",y?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:O("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:b,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(Bt,{children:$()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(Bt,{children:q()})})]})})]})},Lw=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i,isMultiRunLauncherOpen:c,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=Fe(),{isMobile:m}=Nt(),[f,p]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),ox({enabled:!0});const h=Do(x=>x.checkForUpdates);l.useEffect(()=>{const x=setTimeout(()=>{h()},3e3);return()=>clearTimeout(x)},[h]),l.useEffect(()=>{Fe.getState().isMobile!==m&&t(m)},[m,t]),l.useEffect(()=>{if(typeof window>"u")return;let x;const v=()=>{x!==void 0&&window.clearTimeout(x),x=window.setTimeout(()=>{Fe.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v),x!==void 0&&window.clearTimeout(x)}},[]),l.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const x=document.documentElement;let v=0,S=!1,N=0,j=null;const k=Fe.getState().setKeyboardOpen,F=()=>{j&&(j.style.setProperty("--oc-keyboard-avoid-offset","0px"),j.removeAttribute("data-keyboard-avoid-active"),j=null)},I=L=>{if(!L)return null;const $=L.closest("[data-keyboard-avoid]");if($)return $;if(L.classList.contains("overlay-scrollbar-container")){const q=L.parentElement;if(q instanceof HTMLElement)return q}return L},M=()=>{v=0,S=!0,x.style.setProperty("--oc-keyboard-inset","0px"),k(!1)},b=()=>{const L=window.visualViewport,$=L?Math.round(L.height):window.innerHeight,q=L?Math.max(0,Math.round(L.offsetTop)):0;x.style.setProperty("--oc-visual-viewport-offset-top",`${q}px`);const ee=document.activeElement,ce=ee?.tagName,z=ce==="INPUT"||ce==="TEXTAREA"||ce==="SELECT"||!!ee?.isContentEditable,D=Math.round(x.clientHeight||window.innerHeight),H=$+q,X=Math.max(0,D-H),ae=X>=(z?120:180)?X:0;if(S)ae===0&&(S=!1),v=0;else if(v===0)ae>0&&z&&(v=ae);else{const je=!z&&$>N+6;ae===0?(v=0,k(!1)):je?M():(ae>0&&z||ae>v)&&(v=ae,k(!0))}x.style.setProperty("--oc-keyboard-inset",`${v}px`),N=$;const fe=z?I(ee):null;if(!m||!fe||!ee)F();else{fe!==j&&(F(),j=fe);const je=q+$,te=ee.getBoundingClientRect().bottom-je,oe=8,V=Math.max(v,ae),ue=te>oe&&V>0?Math.min(te,V):0,ge=j;ge&&(ge.style.setProperty("--oc-keyboard-avoid-offset",`${ue}px`),ge.setAttribute("data-keyboard-avoid-active","true"))}if(m&&z){const je=document.scrollingElement;je&&je.scrollTop!==0&&(je.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};b();const C=window.visualViewport;C?.addEventListener("resize",b),C?.addEventListener("scroll",b),window.addEventListener("resize",b),window.addEventListener("orientationchange",b);const A=L=>{const $=L.target;if(!$)return;const q=$.tagName;(q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||$.isContentEditable)&&(S=!1),b()};document.addEventListener("focusin",A,!0);const P=L=>{const $=L.target;if(!$)return;const q=$.tagName;if(q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||$.isContentEditable){const ce=L.relatedTarget,_=ce?.tagName;if(_==="INPUT"||_==="TEXTAREA"||_==="SELECT"||ce?.isContentEditable)return;M()}};return document.addEventListener("focusout",P,!0),()=>{C?.removeEventListener("resize",b),C?.removeEventListener("scroll",b),window.removeEventListener("resize",b),window.removeEventListener("orientationchange",b),document.removeEventListener("focusin",A,!0),document.removeEventListener("focusout",P,!0),F()}},[m]);const y=l.useMemo(()=>{switch(r){case"git":return e.jsx(Fb,{});case"diff":return e.jsx(Ng,{});case"terminal":return e.jsx(Vb,{});default:return null}},[r]),g=r==="chat",w=a&&!m;return e.jsx(Gg,{children:e.jsxs("div",{className:O("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(Pg,{}),e.jsx(Og,{}),e.jsx(Hg,{}),m?e.jsxs(e.Fragment,{children:[!(a||c)&&e.jsx(wl,{}),e.jsx("div",{className:O("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:O("absolute inset-0",!g&&"invisible"),children:e.jsx(Bt,{children:e.jsx(Wa,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Bt,{children:y})})]})}),e.jsx(cs,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Ra,{mobileVariant:!0})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(Bt,{children:e.jsx(Fl,{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(Bt,{children:e.jsx(qa,{onClose:()=>i(!1)})})})]}):e.jsxs(e.Fragment,{children:[!w&&e.jsx(Tg,{isOpen:s,isMobile:m,children:e.jsx(Ra,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:O("absolute inset-0 flex flex-col",(w||c)&&"invisible"),children:[e.jsx(wl,{}),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:O("absolute inset-0",!g&&"invisible"),children:e.jsx(Bt,{children:e.jsx(Wa,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Bt,{children:y})})]})})]}),c&&e.jsx("div",{className:O("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(Bt,{children:e.jsx(Fl,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),w&&e.jsx("div",{className:O("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(Bt,{children:e.jsx(qa,{onClose:()=>i(!1)})})})]}),!w&&e.jsx(Mg,{})]})})},Ow=550,$w=()=>{const[s,r]=l.useState("chat"),[t,n]=l.useState(0),o=l.useRef(null),a=ye(k=>k.currentSessionId),i=ye(k=>k.sessions),c=ye(k=>!!k.newSessionDraft?.open),d=ye(k=>k.openNewSessionDraft),[u,m]=l.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),f=lt(k=>k.isInitialized),p=lt(k=>k.initializeApp),h=ye(k=>k.loadSessions),y=ye(k=>k.loadMessages),g=ye(k=>k.messages),[w,x]=l.useState(()=>f),[v,S]=l.useState(!1);l.useEffect(()=>{a&&r("chat")},[a]),l.useEffect(()=>{!a&&!c&&d()},[a,c,d]);const N=l.useCallback(()=>{r("sessions")},[]);l.useEffect(()=>{const k=F=>{const M=F.detail?.status;(M==="connected"||M==="connecting"||M==="error"||M==="disconnected")&&m(M)};return window.addEventListener("openchamber:connection-status",k),()=>window.removeEventListener("openchamber:connection-status",k)},[]),l.useEffect(()=>{const k=F=>{const M=F.detail?.view;M==="settings"?r("settings"):M==="chat"?r("chat"):M==="sessions"&&r("sessions")};return window.addEventListener("openchamber:navigate",k),()=>window.removeEventListener("openchamber:navigate",k)},[]),l.useEffect(()=>{(async()=>{if(!(v||w||u!=="connected")){S(!0);try{f||await p(),await h(),x(!0)}catch{}finally{S(!1)}}})()},[u,f,w,p,v,h]),l.useEffect(()=>{(async()=>{if(!w||u!=="connected"||s!=="chat"||c||!a)return;if(!(g.has(a)&&(g.get(a)?.length||0)>0))try{await y(a)}catch{}})()},[u,a,s,w,y,g,c]),l.useEffect(()=>{const k=o.current;if(!k)return;const F=new ResizeObserver(I=>{for(const M of I)n(M.contentRect.width)});return F.observe(k),n(k.clientWidth),()=>F.disconnect()},[]);const j=t>0&&t<Ow;return e.jsx("div",{ref:o,className:"h-full w-full bg-background text-foreground flex flex-col",children:s==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Mc,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ra,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>r("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):s==="settings"?e.jsx(qa,{onClose:()=>r("sessions"),forceMobile:j}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Mc,{title:c&&!a?"New session":i.find(k=>k.id===a)?.title||"Chat",showBack:!0,onBack:N,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Bt,{children:e.jsx(Wa,{})})})]})})},Mc=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,showContextUsage:a})=>{const{getCurrentModel:i}=lt(),c=ye(h=>h.getContextUsage),d=i(),u=d?.limit&&typeof d.limit=="object"?d.limit:null,m=typeof u?.context=="number"?u.context:0,f=typeof u?.output=="number"?u.output:0,p=c(m,f);return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border bg-background shrink-0",children:[r&&t&&e.jsx("button",{onClick:t,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(Qc,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1 h-9 w-9 items-center justify-center p-2",title:s,children:s}),n&&e.jsx("button",{onClick:n,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"New session",children:e.jsx(Ht,{className:"h-5 w-5"})}),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(wr,{className:"h-5 w-5"})}),a&&p&&p.totalTokens>0&&e.jsx(Fa,{totalTokens:p.totalTokens,percentage:p.percentage,contextLimit:p.contextLimit,outputLimit:p.outputLimit??0,size:"compact"})]})},Dc=({...s})=>{const{theme:r="system"}=kf();return e.jsx(Nf,{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})},_w=(s=5e3)=>{const[r,t]=Se.useState(null);return Se.useEffect(()=>{if(!Xt())return;let n=!1,o=null;const a=async()=>{const i=await Kf();n||(t(i),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},Bw=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=ye(),c=_w(4e3),d=l.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=l.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(xi,{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(Cf,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(ve,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:s,children:e.jsx(zt,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Messages"}),e.jsx("div",{className:"typography-markdown font-semibold",children:d})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Cached Sessions"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[m," / ",Vt.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:[Vt.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:[Vt.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:[Vt.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(tt,{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(Mf,{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>Vt.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(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsxs(ve,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Es,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(Xe,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(Xe,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(Qe,{delayDuration:1e3,children:[e.jsx(Je,{asChild:!0,children:e.jsx(ve,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:r.map(f=>({id:f.id,title:f.title})),currentSessionId:o,cachedSessions:Array.from(t.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(Xe,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},zw="openchamber-message-cursors",Kr="cursors",Hw=1,Iu="openchamber.messageCursors",Ci=()=>typeof window<"u",Mi=()=>Ci()&&typeof indexedDB<"u",Tu=()=>Mi()?new Promise((s,r)=>{const t=indexedDB.open(zw,Hw);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Kr)||n.createObjectStore(Kr)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),Fu=()=>{if(!Ci())return{};try{const s=window.localStorage.getItem(Iu);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},Uw=s=>{if(Ci())try{window.localStorage.setItem(Iu,JSON.stringify(s))}catch{}},Ww=async(s,r,t)=>{if(!s||!r)return;if(Mi())try{const o=await Tu();await new Promise((a,i)=>{const c=o.transaction(Kr,"readwrite");c.objectStore(Kr).put({messageId:r,completedAt:t},s),c.oncomplete=()=>a(),c.onerror=()=>i(c.error??new Error("Cursor write failed")),c.onabort=()=>i(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=Fu();n[s]={messageId:r,completedAt:t},Uw(n)},Vw=async s=>{if(!s)return null;if(Mi())try{const t=await Tu(),n=await new Promise((o,a)=>{const i=t.transaction(Kr,"readonly"),d=i.objectStore(Kr).get(s);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),i.onerror=()=>a(i.error??new Error("Cursor read failed")),i.onabort=()=>a(i.error??new Error("Cursor read aborted"))});return t.close(),n}catch{}return Fu()[s]??null},qw=50,Gw=750,Ac=new WeakMap,Ec=s=>{if(!s||!Array.isArray(s))return 0;const r=Ac.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 Ac.set(s,t),t},Kw=10,Ic=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<Kw?null:n},Tc=(s,r)=>{const t=Ic(s),n=Ic(r);return!t||!n||t.length!==n.length?!0:t>n},Ga=new Map,Fc=(s,r)=>{const t=`${s}:${r}`,n=Ga.get(t);if(n&&n.sessionId===s)return n.message;const i=(ye.getState().messages.get(s)||[]).find(c=>c.info.id===r)||null;return Ga.set(t,{sessionId:s,message:i}),i},Yw=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:m}=ye(),{checkConnection:f}=lt(),p=yt(G=>G.currentDirectory),h=l.useMemo(()=>{if(!a)return;try{const T=d?.(a);if(T?.path)return T.path}catch(T){console.warn("Failed to inspect worktree metadata for session directory:",T)}const G=c.find(T=>T.id===a);if(G&&typeof G.directory=="string"&&G.directory.trim().length>0)return G.directory.trim()},[a,d,c]),y=l.useMemo(()=>{if(h&&h.length>0)return h;if(typeof p=="string"&&p.trim().length>0)return p.trim()},[h,p]),g=Fe(G=>G.setEventStreamStatus),w=l.useRef(null),x=l.useCallback((G,T)=>{const Y=T??null,E=w.current;if(!(E&&E.status===G&&E.hint===Y)){if(w.current={status:G,hint:Y},Ot()){const U={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[G]??"[INFO]",be=Y?`${U} SSE ${G}: ${Y}`:`${U} SSE ${G}`;console.info(be)}g(G,Y)}},[g]),v=l.useCallback((G,T)=>{if(!G)return Promise.resolve();const Y=Date.now();if(A.current)return A.current;if(Y-P.current<Gw)return Promise.resolve();const E=u(G).catch(B=>{console.warn(`[useEventStream] Failed to resync messages (${T}):`,B)}).finally(()=>{A.current=null,P.current=Date.now()});return A.current=E,E},[u]),S=l.useCallback(async G=>{Ot()&&console.info("[useEventStream] Bootstrapping state:",G);try{await Promise.all([m(),a?v(a,G):Promise.resolve()])}catch(T){console.warn("[useEventStream] Bootstrap failed:",G,T)}},[a,m,v]),N=l.useCallback((G,T,Y)=>{Ot()&&console.debug(`[MessageTracker] ${G}: ${T}`,Y)},[]),j=l.useCallback(G=>{Ot()&&console.debug(`[MessageTracker] ${G}: reported`)},[]),k=l.useRef(null),F=l.useRef(null),I=l.useRef(0);l.useRef(new Set);const M=l.useRef(new Map),b=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),P=l.useRef(0),L=l.useCallback(()=>{if(typeof document>"u")return"visible";const G=document.visibilityState;return G==="hidden"&&document.hasFocus()?"visible":G},[]),$=l.useRef(L()),q=l.useRef(typeof navigator>"u"?!0:navigator.onLine),ee=l.useRef(!1),ce=l.useRef(null),_=l.useRef(null),z=l.useRef(Date.now()),D=l.useRef(!1),H=l.useCallback(G=>{const T=Date.now();T-z.current>25e3&&(S(G),z.current=T)},[S]);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(D.current=!0)},[]);const X=l.useRef(new Map),he=l.useRef(new Map),ae=l.useRef(0),fe=l.useRef(null),je=l.useRef(a);l.useEffect(()=>{je.current=a},[a]);const W=l.useCallback(G=>{if(!G)return;const T=Date.now(),Y=M.current,E=Y.get(G);E&&T-E<3e3||(Y.set(G,T),setTimeout(async()=>{try{const B=await Le.getSession(G);if(B){const U={};typeof B.title=="string"&&B.title.length>0&&(U.title=B.title),B.summary!==void 0&&(U.summary=B.summary),Object.keys(U).length>0&&i(G,U)}}catch(B){console.warn("Failed to refresh session metadata:",B)}},100))},[i]),te=l.useCallback(()=>{b.current||(b.current=setTimeout(()=>{b.current=null;try{m()}catch(G){console.warn("Failed to refresh sessions after stream completion:",G)}},500))},[m]),oe=l.useCallback((G,T)=>{if(ye.getState().sessionActivityPhase?.get(G)===T){he.current=new Map(ye.getState().sessionActivityPhase??new Map);return}const E=X.current.get(G);E&&(clearTimeout(E),X.current.delete(G));const B=new Map(ye.getState().sessionActivityPhase??new Map);if(B.set(G,T),he.current=B,ye.setState({sessionActivityPhase:B}),T==="cooldown"){const U=setTimeout(()=>{if(X.current.delete(G),ye.getState().sessionActivityPhase?.get(G)==="cooldown"){const Q=new Map(ye.getState().sessionActivityPhase??new Map);Q.set(G,"idle"),he.current=Q,ye.setState({sessionActivityPhase:Q})}},2e3);X.current.set(G,U)}},[]),V=l.useCallback(async()=>{const G=Date.now();if(fe.current)return fe.current;if(G-ae.current<1500)return;ae.current=G;const T=U=>{if(typeof U!="string")return null;const be=U.trim();if(!be)return null;const Q=be.replace(/\\/g,"/");return Q.length>1?Q.replace(/\/+$/,""):Q},Y=U=>{try{const xe=d?.(U),He=T(xe?.path??null);if(He)return He}catch{}const be=c.find(xe=>xe.id===U);return T(be?.directory??null)},E=U=>{Object.entries(U).forEach(([be,Q])=>{if(!be||!Q)return;const xe=Q.type==="busy"||Q.type==="retry"?"busy":"idle";oe(be,xe)})},B=(async()=>{try{const U=await Le.getGlobalSessionStatus();if(U&&Object.keys(U).length>0){E(U);return}const be=new Set;c.forEach(ze=>{const st=Y(ze.id);st&&be.add(st)});const Q=T(y??null);Q&&be.add(Q);const xe=Array.from(be);if(xe.length===0){const ze=await Le.getSessionStatus();ze&&E(ze);return}const He=await Promise.allSettled(xe.map(ze=>Le.getSessionStatusForDirectory(ze))),Ke={};He.forEach(ze=>{ze.status!=="fulfilled"||!ze.value||Object.assign(Ke,ze.value)}),E(Ke)}catch{}})().finally(()=>{fe.current=null});return fe.current=B,B},[y,d,c,oe]),ue=l.useCallback(G=>{if(z.current=Date.now(),Ot()&&console.debug("[useEventStream] Received event:",G.type,G.properties),!G.properties)return;const T=G.properties;if(!new Set(["session.abort","session.error"]).has(G.type)){const E=(typeof T.session=="object"&&T.session!==null?T.session:null)||(typeof T.sessionInfo=="object"&&T.sessionInfo!==null?T.sessionInfo:null);if(E){const B=E,U=typeof B.id=="string"&&B.id.length>0?B.id:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:typeof T.id=="string"&&T.id.length>0?T.id:void 0;if(U){const be=typeof B.title=="string"?B.title:typeof T.title=="string"?T.title:void 0,Q=typeof B.summary=="object"&&B.summary!==null?B.summary:typeof T.summary=="object"&&T.summary!==null?T.summary:void 0;if(be!==void 0||Q!==void 0){const xe={};be!==void 0&&(xe.title=be),Q!==void 0&&(xe.summary=Q),i(U,xe)}}}}switch(G.type){case"server.connected":f();break;case"global.disposed":case"server.instance.disposed":{S("server_disposed_event");break}case"openchamber:session-activity":{const E=typeof T.sessionId=="string"?T.sessionId:null,B=typeof T.phase=="string"?T.phase:null;E&&(B==="idle"||B==="busy"||B==="cooldown")&&(oe(E,B),te());break}case"session.status":if(D.current)break;{const E=typeof T.sessionID=="string"?T.sessionID:null,B=typeof T.status=="object"&&T.status!==null?T.status:null,U=typeof B?.type=="string"?B.type:null;E&&U&&(oe(E,U==="busy"||U==="retry"?"busy":"idle"),te())}break;case"message.part.updated":{const E=typeof T.part=="object"&&T.part!==null?T.part:null;if(!E)break;const B=E,U=typeof T.info=="object"&&T.info!==null?T.info:T,be=typeof U.sessionID=="string"?U.sessionID:null,Q=typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof be=="string"&&be.length>0?be:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:null,xe=typeof U.id=="string"?U.id:null,He=typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:typeof xe=="string"&&xe.length>0?xe:typeof T.messageID=="string"&&T.messageID.length>0?T.messageID:null;if(!Q||!He){Ot()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:B.sessionID??be??T.sessionID,messageID:B.messageID??xe??T.messageID});break}const Ke=Q,ze=He,st=ye.getState().sessionMemoryState.get(Ke)?.trimmedHeadMaxId;if(st&&!Tc(ze,st)){Ot()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:Ke,messageId:ze,trimmedHeadMaxId:st});break}let it="assistant";if(U&&typeof U.role=="string")it=U.role;else{const ct=Fc(Ke,ze);if(ct){const ut=ct.info.role;typeof ut=="string"&&(it=ut)}}if(N(ze,"part_received",{role:it}),it==="user"&&B.synthetic===!0){N(ze,"skipped_synthetic_user_part");break}const at={...E,type:E.type||"text"};N(ze,"addStreamingPart_called"),s(Ke,ze,at,it);break}case"message.updated":{const E=typeof T.info=="object"&&T.info!==null?T.info:T,B=E,U=typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:null,be=typeof B.id=="string"&&B.id.length>0?B.id:typeof T.messageID=="string"&&T.messageID.length>0?T.messageID:null;if(!U||!be){Ot()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:B.sessionID??T.sessionID,messageID:B.id??T.messageID});break}const Q=U,xe=be,He=ye.getState().sessionMemoryState.get(Q)?.trimmedHeadMaxId;if(He&&!Tc(xe,He)){Ot()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Q,messageId:xe,trimmedHeadMaxId:He});break}if(D.current&&Ot())try{const $e=T.parts||B.parts||[],We=(Array.isArray($e)?$e.filter(Ze=>Ze?.type==="text"):[]).map(Ze=>{const me=Ze;return typeof me?.text=="string"?me.text:typeof me?.content=="string"?me.content:""}).join(`
101
- `);console.info("[STREAM-TRACE] message.updated",{messageId:xe,role:B.role,status:B.status,textLen:We.length,textPreview:We.slice(0,120),partsCount:Array.isArray($e)?$e.length:0})}catch{}if(N(xe,"message_updated",{role:B.role}),B.role==="user"){const $e=T.parts||B.parts,Ue=Array.isArray($e)?$e:[],We={...E,userMessageMarker:!0,clientRole:"user"};if(t(Q,xe,We),Ue.length>0)for(let Ze=0;Ze<Ue.length;Ze++){const me=Ue[Ze];if(me.synthetic===!0)continue;const de={...me,type:me?.type||"text",sessionID:me?.sessionID||Q,messageID:me?.messageID||xe};s(Q,xe,de,"user")}N(xe,"user_message_created_from_event",{partsCount:Ue.length});break}const Ke=Fc(Q,xe),ze=Ec(Ke?.parts||[]),st=Ke?.info?.finish==="stop",it=T.parts||B.parts,at=Array.isArray(it)?it:[],ct=at.length>0,pt=typeof(B.time||{})?.completed=="number";if(!ct&&!pt)break;const vt=E.finish,xt=typeof vt=="string"?vt:null,mt=xt==="stop";if(B.role==="assistant"&&ct){const $e=Ec(at);if(ze>0&&$e+qw<ze&&!mt){N(xe,"skipped_shrinking_update",{incomingLen:$e,existingLen:ze});break}if(D.current){const We=ze>0&&$e<ze,Ze=at.some(de=>{if(!de||de.type!=="text")return!1;const we=de;return typeof we.text=="string"&&we.text.length>0});if(We&&!(mt&&Ze)){N(xe,"desktop_shrinking_update_suppressed",{incomingLen:$e,existingLen:ze});break}}}if(t(Q,xe,E),ct&&B.role!=="user"){const We=(ye.getState().messages.get(Q)||[]).find(de=>de.info.id===xe),Ze=!We||We.parts.length===0;N(xe,Ze?"server_parts_injected":"server_parts_refreshed",{count:at.length});const me=D.current&&B.role==="assistant"?at.filter(de=>de?.type!=="text"):at;for(let de=0;de<me.length;de++){const we=me[de],Me={...we,type:we?.type||"text",sessionID:we?.sessionID||Q,messageID:we?.messageID||xe};s(Q,xe,Me,B.role),N(xe,`server_part_${de}`)}}const J=E.time,ke=J?.completed,re=typeof ke=="number"&&Number.isFinite(ke),le=xt==="stop"||st;if(E.role==="assistant"&&(re||le)&&E.role==="assistant"){const Ue=ye.getState().messages.get(Q)||[];let We=null,Ze="";for(let Pe=0;Pe<Ue.length;Pe++){const qe=Ue[Pe];qe.info.role==="assistant"&&qe.info.id>Ze&&(Ze=qe.info.id,We=qe.info.id)}if(xe!==We)break;if(!le&&D.current){N(xe,"desktop_completion_without_stop");break}const me=re?ke:Date.now();re||t(Q,xe,{...E,time:{...J??{},completed:me}}),N(xe,"completed",{timeCompleted:me}),j(xe),Ww(Q,xe,me),r(Q,xe),D.current||xt==="stop"&&ye.getState().sessionActivityPhase?.get(Q)==="busy"&&oe(Q,"cooldown");const de=E.sessionID,we=typeof de=="string"&&de.length>0?de:Q;W(we),E.summary&&typeof we=="string"&&n(we,null)}break}case"session.updated":{const E=typeof T.info=="object"&&T.info!==null?T.info:typeof T.sessionInfo=="object"&&T.sessionInfo!==null?T.sessionInfo:typeof T.session=="object"&&T.session!==null?T.session:T,B=typeof E.id=="string"&&E.id.length>0?E.id:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:typeof T.id=="string"&&T.id.length>0?T.id:void 0;if(B){const U=typeof E.time=="object"&&E.time!==null?E.time:typeof T.time=="object"&&T.time!==null?T.time:null,be=U&&typeof U.compacting=="number"?U.compacting:null;n(B,be)}break}case"session.abort":{const E=typeof T.sessionID=="string"&&T.sessionID.length>0?T.sessionID:null,B=typeof T.messageID=="string"&&T.messageID.length>0?T.messageID:null;E&&B&&r(E,B);break}case"permission.updated":a===T.sessionID&&o(T);break;case"permission.replied":break;case"todo.updated":{const E=typeof T.sessionID=="string"?T.sessionID:null,B=Array.isArray(T.todos)?T.todos:[];E&&B.length>0&&jx(E,B);break}}},[a,s,r,t,o,f,W,te,n,i,N,j,oe,S]),ge=l.useCallback(()=>{const G=L();return $.current=G,G==="visible"&&q.current},[L]),ie=l.useCallback(()=>{Ot()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:D.current,hasUnsubscribe:!!k.current,currentSessionId:je.current,effectiveDirectory:y,onlineStatus:q.current,visibilityState:$.current,lastEventTimestamp:z.current,reconnectAttempts:I.current})},[y]),De=l.useCallback(async()=>!0,[]),Ce=l.useCallback(()=>{if(C.current){Ot()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(C.current=!0,F.current&&(clearTimeout(F.current),F.current=null),k.current){const G=k.current;k.current=null;try{G()}catch(T){console.warn("[useEventStream] Error during unsubscribe:",T)}}C.current=!1},[]),Ie=l.useCallback(async G=>{if(ie(),!ge()){ee.current=!0,q.current?x("paused","Paused while hidden"):x("offline","Waiting for network");return}D.current&&(await De()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),G?.resetAttempts&&(I.current=0),Ce(),z.current=Date.now(),x("connecting",null),Ot()&&console.info("[useEventStream] Starting event stream...");const T=E=>{console.warn("Event stream error:",E)},Y=()=>{const E=ee.current;if(I.current=0,ee.current=!1,z.current=Date.now(),x("connected",null),f(),Array.from(ye.getState().sessionActivityPhase?.values?.()??[]).some(U=>U==="busy")&&V(),E)S("sse_reconnected");else{const U=je.current;U&&setTimeout(()=>{v(U,"sse_reconnected").then(()=>W(U)).catch(be=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",be)})},0)}};if(Ot()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:y,isCleaningUp:C.current}),C.current){Ot()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const E=Le.subscribeToEvents(ue,T,Y,y),B=()=>{try{E()}catch(U){console.warn("[useEventStream] Error during unsubscribe:",U)}};C.current?B():k.current=B}catch(E){console.error("[useEventStream] Error during subscription:",E),T(E)}},[ge,Ce,x,f,v,W,ue,y,V,De,ie,S]),K=l.useCallback(G=>{if(!ge()){ee.current=!0,Ce(),q.current?x("paused","Paused while hidden"):x("offline","Waiting for network");return}const T=I.current+1;I.current=T;const Y=G??`Retrying (${T})`;x("reconnecting",Y);const E=T<=3?Math.min(1e3*Math.pow(2,T-1),8e3):Math.min(2e3*Math.pow(2,T-3),32e3),B=Math.floor(Math.random()*250),U=E+B;F.current&&clearTimeout(F.current),F.current=setTimeout(()=>{Ie({resetAttempts:!1})},U)},[ge,Ce,x,Ie]);l.useEffect(()=>{const G=X.current;typeof window<"u"&&(window.__messageTracker=N);let T=null;D.current&&typeof window<"u"&&(T=He=>{const Ke=typeof He.detail?.sessionId=="string"?He.detail.sessionId:null,ze=typeof He.detail?.phase=="string"?He.detail.phase:null;Ke&&(ze==="idle"||ze==="busy"||ze==="cooldown")&&(oe(Ke,ze),te())},window.addEventListener("openchamber:session-activity",T));const Y=()=>{ce.current&&(clearTimeout(ce.current),ce.current=null)},E=()=>{ce.current||(ce.current=setTimeout(()=>{const He=L();$.current=He,He!=="visible"?(Ce(),ee.current=!0,x("paused","Paused while hidden")):Y()},5e3))},B=()=>{if($.current=L(),$.current==="visible"){if(Y(),H("visibility_restore"),ee.current||!k.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const He=je.current;He&&(v(He,"visibility_restore").catch(()=>{}),W(He)),m(),V(),x("connecting","Resuming stream"),Ie({resetAttempts:!0})}}else x("paused","Paused while hidden"),E()},U=()=>{if($.current=L(),$.current==="visible"&&(Y(),H("window_focus"),ee.current||!k.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const He=je.current;He&&(W(He),v(He,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(Ke=>console.warn("[useEventStream] Failed to refresh messages:",Ke))),m(),V(),x("connecting","Resuming stream"),Ie({resetAttempts:!0})}},be=()=>{q.current=!0,H("network_restored"),(ee.current||!k.current)&&(x("connecting","Network restored"),Ie({resetAttempts:!0}))},Q=()=>{q.current=!1,ee.current=!0,x("offline","Waiting for network"),Ce()};typeof document<"u"&&document.addEventListener("visibilitychange",B),typeof window<"u"&&(window.addEventListener("online",be),window.addEventListener("offline",Q),window.addEventListener("focus",U));const xe=setTimeout(()=>{Ie({resetAttempts:!0})},100);return _.current&&clearInterval(_.current),_.current=setInterval(()=>{if(!ge())return;const He=Date.now();Array.from(ye.getState().sessionActivityPhase?.values?.()??[]).some(ze=>ze==="busy")&&V(),He-z.current>25e3&&Promise.resolve().then(async()=>{try{await Le.checkHealth()?z.current=Date.now():K("Refreshing stalled stream")}catch(ze){console.warn("Health check after stale stream failed:",ze),K("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(xe),T&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",T),typeof document<"u"&&document.removeEventListener("visibilitychange",B),typeof window<"u"&&(window.removeEventListener("online",be),window.removeEventListener("offline",Q),window.removeEventListener("focus",U)),Y(),_.current&&(clearInterval(_.current),_.current=null),G.forEach(He=>clearTimeout(He)),G.clear(),Ga.clear(),ee.current=!1,$.current=L(),q.current=typeof navigator>"u"?!0:navigator.onLine,Ce(),b.current&&(clearTimeout(b.current),b.current=null),x("idle",null)}},[y,N,L,Ce,x,Ie,K,u,W,te,oe,V,ge,m,H,v])},Xw=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=ye(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:c,setSessionSwitcherOpen:d,setSessionCreateDialogOpen:u,setActiveMainTab:m,setSettingsDialogOpen:f,setModelSelectorOpen:p}=Fe(),{themeMode:h,setThemeMode:y}=Dr(),{working:g}=ru(),w=l.useRef(null),x=l.useRef(null),v=l.useRef(!1),S=l.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null),w.current=null,n()},[n]);l.useEffect(()=>{const N=j=>{if(j.ctrlKey&&j.key==="x"&&(j.preventDefault(),a()),j.ctrlKey&&j.shiftKey&&j.key.toLowerCase()==="l"){const F=Nr()?.diagnostics;if(!F||(j.preventDefault(),v.current))return;v.current=!0,F.downloadLogs().then(({fileName:I,content:M})=>{const b=I||"openchamber.log",C=new Blob([M],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(C),P=document.createElement("a");P.href=A,P.download=b,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(A)}).finally(()=>{v.current=!1});return}if(j.ctrlKey&&j.key==="h"&&(j.preventDefault(),i()),j.ctrlKey&&!j.metaKey&&j.key.toLowerCase()==="n"){if(j.preventDefault(),j.shiftKey){u(!0);return}m("chat"),d(!1),s()}if((j.metaKey||j.ctrlKey)&&j.key==="/"){j.preventDefault();const k=["light","dark","system"],I=(k.indexOf(h)+1)%k.length;y(k[I])}if(j.ctrlKey&&!j.metaKey&&!j.shiftKey&&j.key.toLowerCase()==="g"){j.preventDefault();const{activeMainTab:k}=Fe.getState();m(k==="git"?"chat":"git");return}if(j.ctrlKey&&!j.metaKey&&!j.shiftKey&&j.key.toLowerCase()==="e"){j.preventDefault();const{activeMainTab:k}=Fe.getState();m(k==="diff"?"chat":"diff");return}if(j.ctrlKey&&!j.metaKey&&!j.shiftKey&&j.key.toLowerCase()==="t"){j.preventDefault();const{activeMainTab:k}=Fe.getState();m(k==="terminal"?"chat":"terminal");return}if((j.ctrlKey||j.metaKey)&&!j.shiftKey&&j.key===","){j.preventDefault();const{isSettingsDialogOpen:k}=Fe.getState();f(!k);return}if(j.ctrlKey&&!j.metaKey&&!j.shiftKey&&j.key.toLowerCase()==="l"){j.preventDefault();const{isMobile:k,isSessionSwitcherOpen:F}=Fe.getState();k?d(!F):c();return}if(j.ctrlKey&&!j.metaKey&&!j.shiftKey&&j.key.toLowerCase()==="i"){j.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(j.ctrlKey&&!j.metaKey&&!j.shiftKey&&j.key.toLowerCase()==="m"){const{isSettingsDialogOpen:k,isCommandPaletteOpen:F,isHelpDialogOpen:I,isSessionSwitcherOpen:M,isSessionCreateDialogOpen:b,isAboutDialogOpen:C,activeMainTab:A,isModelSelectorOpen:P}=Fe.getState();if(k||F||I||M||b||C||!(A==="chat"))return;j.preventDefault(),p(!P);return}if(j.key==="Escape"){const{isSettingsDialogOpen:k,isCommandPaletteOpen:F,isHelpDialogOpen:I,isSessionSwitcherOpen:M,isSessionCreateDialogOpen:b,isAboutDialogOpen:C,activeMainTab:A}=Fe.getState();if(k){j.preventDefault(),f(!1),S();return}if(F||I||M||b||C||!(A==="chat")){S();return}const $=o;if(!(g.canAbort&&!!$)){S();return}const ee=Date.now(),ce=w.current;if(ce&&ee<ce){j.preventDefault(),S(),r();return}j.preventDefault();const _=t(3e3)??ee+3e3;w.current=_,x.current&&clearTimeout(x.current);const z=Math.max(_-ee,0);x.current=setTimeout(()=>{w.current&&Date.now()>=w.current&&S()},z||0);return}};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[s,r,a,i,c,d,u,m,f,p,y,h,g,t,S,o]),l.useEffect(()=>()=>{S()},[S])},Pc="openchamber:menu-action",Qw=s=>{const{openNewSessionDraft:r}=ye(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setSessionCreateDialogOpen:i,setActiveMainTab:c,setSettingsDialogOpen:d,setAboutDialogOpen:u}=Fe(),{setDirectory:m}=yt(),{setThemeMode:f}=Dr(),p=l.useRef(!1),h=l.useCallback(()=>{Xt()&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(y=>{y.success&&y.path?m(y.path,{showOverlay:!0}):y.error&&y.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:y.error})}).catch(y=>{console.error("Desktop: Error selecting directory:",y),se.error("Failed to select directory")}):hr.requestDirectoryDialog()},[m]);l.useEffect(()=>{const y=g=>{switch(g.detail){case"about":u(!0);break;case"settings":d(!0);break;case"command-palette":t();break;case"new-session":c("chat"),a(!1),r();break;case"worktree-creator":i(!0);break;case"change-workspace":h();break;case"open-git-tab":{const{activeMainTab:x}=Fe.getState();c(x==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:x}=Fe.getState();c(x==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:x}=Fe.getState();c(x==="terminal"?"chat":"terminal");break}case"theme-light":f("light");break;case"theme-dark":f("dark");break;case"theme-system":f("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":s?.();break;case"help-dialog":n();break;case"download-logs":{const v=Nr()?.diagnostics;if(!v||p.current)break;p.current=!0,v.downloadLogs().then(({fileName:S,content:N})=>{const j=S||"openchamber.log",k=new Blob([N],{type:"text/plain;charset=utf-8"}),F=URL.createObjectURL(k),I=document.createElement("a");I.href=F,I.download=j,document.body.appendChild(I),I.click(),document.body.removeChild(I),URL.revokeObjectURL(F),se.success("Logs saved",{description:`Downloaded to ~/Downloads/${j}`})}).catch(()=>{se.error("Failed to download logs")}).finally(()=>{p.current=!1});break}}};return window.addEventListener(Pc,y),()=>window.removeEventListener(Pc,y)},[r,t,n,o,a,i,c,d,u,f,s,h])},Jw=s=>s.role==="assistant",Rc=s=>{const r=s.info;if(!Jw(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},to=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},Lc=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>fn(n)).join(" ").replace(/\s+/g," ").trim(),Zw=(s,r)=>{if(!s||!to(s.info))return-1;const t=Lc(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((i,c)=>{if(!to(i.info))return;const d=Lc(i),u=!!(t&&d&&d===t),m=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=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(i=>{if(!to(i.info))return!1;const c=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},ev=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=ye(),n=l.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=l.useRef(void 0),a=l.useRef(0),i=l.useCallback(async()=>{if(!s||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(s)||[],u=await Le.getSessionMessages(s),m=await Vw(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(g=>g.info.id===f.info.id),y=p===-1?Zw(f,u):p;if(y!==-1)if(y<u.length-1){const g=u.slice(y+1);console.log(`[SYNC] Found ${g.length} new messages to append`);const w=[...d,...g],{syncMessages:x}=ye.getState();x(s,w)}else{const g=u[y],w=d[d.length-1],x=Rc(g),v=Rc(w);if(x&&!v){console.log("[SYNC] Last message completed on server");const S=[...d.slice(0,-1),g],{syncMessages:N}=ye.getState();N(s,S)}}else if(to(f.info)){const g=u.slice(-Vt.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:w}=ye.getState();w(s,g)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(m){const p=u.findIndex(h=>h.info.id===m.messageId);if(p!==-1){if(p<u.length-1){const y=u.slice(p+1).slice(-Vt.VIEWPORT_MESSAGES);if(y.length>0){console.log(`[SYNC] Restoring ${y.length} messages after cursor`);const{syncMessages:g}=ye.getState();g(s,y)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-Vt.VIEWPORT_MESSAGES),{syncMessages:y}=ye.getState();y(s,h)}}else if(u.length>0){const p=u.slice(-Vt.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:h}=ye.getState();h(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);l.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[i]),l.useEffect(()=>{if(!s||n)return;const c=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,i]),l.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[i])},tv=()=>{l.useEffect(()=>{let s=!1;return(async()=>{try{const t=await Le.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,c=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&ye.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function sv(){const{git:s}=Mr(),r=yt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=ye(),{setActiveDirectory:a,startPolling:i,stopPolling:c,fetchAll:d}=At(),u=l.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]);l.useEffect(()=>{if(!u||!s){c();return}return a(u),d(u,s),i(s),()=>{c()}},[u,s,a,i,c,d])}function rv({children:s}){return sv(),e.jsx(e.Fragment,{children:s})}const nv=()=>{const[{isUpdating:s,message:r},t]=l.useState(()=>up());return l.useEffect(()=>dp(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(vi,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},ov=({open:s,onOpenChange:r})=>{const[t,n]=l.useState(null);l.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:c}=await Ks(async()=>{const{getVersion:u}=await import("./vendor-.bun-CpaXrlrC.js").then(m=>m.ca);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();n(d)}catch{n("1.4.1")}})():n("1.4.1")},[s]);const o=t;return e.jsx(os,{open:s,onOpenChange:r,children:e.jsx(as,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(vi,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),o&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",o]})]}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["A fan-made interface for"," ",e.jsx("a",{href:"https://opencode.ai/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground transition-colors",children:"OpenCode"})," ","agent"]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ma,{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(td,{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(Da,{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 Oc({apis:s,children:r}){return e.jsx(ui.Provider,{value:s,children:r})}const av="curl -fsSL https://opencode.ai/install | bash",iv=3e3;function lv({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(zs,{className:"h-4 w-4"})})]})}const cv=3e4;function dv({onCliAvailable:s}){const[r,t]=l.useState(!1),[n,o]=l.useState(!1),[a,i]=l.useState(!1);l.useEffect(()=>{const m=setTimeout(()=>o(!0),cv);return()=>clearTimeout(m)},[]),l.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const c=l.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await Ks(async()=>{const{getCurrentWindow:h}=await import("./vendor-.bun-CpaXrlrC.js").then(y=>y.c9);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=l.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=l.useCallback(async()=>{try{await navigator.clipboard.writeText(av),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return l.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,iv);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(ka,{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(Mt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(lv,{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(ka,{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 uv=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=Fe();return e.jsx(ov,{open:s,onOpenChange:r})};function mv({apis:s}){const{initializeApp:r,isInitialized:t}=lt(),{error:n,clearError:o,loadSessions:a}=ye(),i=yt(N=>N.currentDirectory),c=yt(N=>N.isSwitchingDirectory),[d,u]=l.useState(!1),{uiFont:m,monoFont:f}=ju(),[p,h]=l.useState(()=>s.runtime.isDesktop),[y,g]=l.useState(()=>s.runtime.isVSCode),[w,x]=l.useState(()=>s.runtime.isDesktop?Yf():!0);l.useEffect(()=>{h(s.runtime.isDesktop),g(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),l.useEffect(()=>(Ui(s),()=>Ui(null)),[s]),l.useEffect(()=>{if(typeof document>"u")return;const N=document.documentElement,j=uc[m]?.stack??uc[Ob].stack,k=pr[f]?.stack??pr[Zn].stack;N.style.setProperty("--font-sans",j),N.style.setProperty("--font-heading",j),N.style.setProperty("--font-family-sans",j),N.style.setProperty("--font-mono",k),N.style.setProperty("--font-family-mono",k),N.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=j)},[m,f]),l.useEffect(()=>{if(t){const j=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},150);return()=>clearTimeout(j)}},[t]),l.useEffect(()=>{const N=setTimeout(()=>{const j=document.getElementById("initial-loading");j&&!t&&(j.classList.add("fade-out"),setTimeout(()=>{j.remove()},300))},5e3);return()=>clearTimeout(N)},[t]),l.useEffect(()=>{(async()=>await r())()},[r]),l.useEffect(()=>{if(c)return;(async()=>(Le.setDirectory(i),await a()))()},[i,c,a]),Yw(),Xw();const v=l.useCallback(()=>{u(N=>!N)},[]);Qw(v),ev(),tv(),Du(),l.useEffect(()=>{const N=j=>{(j.metaKey||j.ctrlKey)&&j.shiftKey&&j.key==="M"&&(j.preventDefault(),u(k=>!k))};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[]),l.useEffect(()=>{n&&setTimeout(()=>o(),5e3)},[n,o]);const S=l.useCallback(()=>{x(!0),window.location.reload()},[]);return p&&!w?e.jsx(Bt,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(dv,{onCliAvailable:S})})}):y?e.jsx(Bt,{children:e.jsx(Oc,{apis:s,children:e.jsx(ac,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx($w,{}),e.jsx(Dc,{})]})})})}):e.jsx(Bt,{children:e.jsx(Oc,{apis:s,children:e.jsx(rv,{children:e.jsx(ac,{children:e.jsxs("div",{className:`h-full text-foreground ${p?"bg-transparent":"bg-background"}`,children:[e.jsx(Lw,{}),e.jsx(Dc,{}),e.jsx(nv,{}),e.jsx(uv,{}),d&&e.jsx(Bw,{onClose:()=>u(!1)})]})})})})})}const Pu=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&&t.setDirectory(r,{showOverlay:!1})},Ru="/auth/session",fv=async()=>fetch(Ru,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),pv=async s=>fetch(Ru,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Di=({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})]}),hv=({message:s="Preparing workspace…"})=>e.jsx(Di,{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})})}),gv=({onRetry:s})=>e.jsx(Di,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:"Unable to reach server"}),e.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:"We couldn't verify the UI session. Check that the service is running and try again."})]}),e.jsx(ve,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),xv=({children:s})=>{const r=l.useMemo(()=>Xt(),[]),t=l.useMemo(()=>Dt(),[]),n=r||t,[o,a]=l.useState(()=>n?"authenticated":"pending"),[i,c]=l.useState(""),[d,u]=l.useState(!1),[m,f]=l.useState(""),p=l.useRef(null),h=l.useRef(n),y=l.useCallback(async()=>{if(n){a("authenticated");return}a(w=>w==="authenticated"?w:"pending");try{const w=await fv();if(w.ok){a("authenticated"),f("");return}if(w.status===401){a("locked");return}a("error")}catch(w){console.warn("Failed to check session status:",w),a("error")}},[n]);l.useEffect(()=>{n||y()},[y,n]),l.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),l.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),l.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await dd(),await ud(),await Pu()))())},[n,o]);const g=async w=>{if(w.preventDefault(),!(!i||d)){u(!0),f("");try{const x=await pv(i);if(x.ok){c(""),a("authenticated");return}if(x.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(x){console.warn("Failed to submit UI password:",x),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(hv,{}):o==="error"?e.jsx(gv,{onRetry:()=>{y()}}):o==="locked"?e.jsx(Di,{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:g,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(Df,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(dt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:w=>{c(w.target.value),m&&f("")},className:"pl-10","aria-invalid":!!m||void 0,"aria-describedby":m?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(ve,{type:"submit",size:"icon",disabled:!i||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(ts,{className:"h-4 w-4 animate-spin"}):e.jsx(Af,{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})},va=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,i=n&255;return`${o} ${a} ${i}`};class yv{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(`
102
- `)}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=va(r.colors.surface.muted),o=va(r.colors.surface.subtle),a=va(r.colors.interactive.border);t.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const i=r.metadata.variant==="dark",c=i?.8:.95,d=i?.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 {
103
- ${t}
104
- }
105
-
106
- .dark {
107
- ${t}
108
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
109
- ${t}
110
- }
111
-
112
- :root:not(.dark) {
113
- ${t}
114
- }`,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=Dt()?Gf:ri;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${t.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${t.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${t.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${t.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${t.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${t.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,t){return r.startsWith("#")?`${r}${Math.round(t*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,t){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),i=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${i}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${i}, ${t})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}darken(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,i=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i: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,i=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i: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 Ai={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"}}},Ei={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"}}},vn=[Ai,Ei];function vo(s){return vn.find(r=>r.metadata.id===s)}const Lu=Ai.metadata.id,Ou=Ei.metadata.id,bv=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,$u=s=>s==="dark"?Ei:Ai,wv=s=>(vn.find(t=>t.metadata.variant===s)??$u(s)).metadata.id,Un=(s,r)=>{const t=vo(s);return t&&t.metadata.variant===r?t:vn.find(o=>o.metadata.variant===r)??$u(r)},vv=typeof window<"u"?l.useLayoutEffect:l.useEffect,jo=(s,r)=>{if(!s)return r==="light"?Lu:Ou;const t=vo(s);return t&&t.metadata.variant===r?t.metadata.id:wv(r)},jv=s=>{let r=Lu,t=Ou,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=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=vo(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=jo(a,"light"),t=jo(i,"dark")}if(s){const o=vo(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function Sv({children:s,defaultThemeId:r}){const t=Se.useMemo(()=>new yv,[]),[n,o]=Se.useState(()=>jv(r)),[a,i]=Se.useState(()=>bv()),[c,d]=Se.useState(()=>typeof window>"u"||!Dt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Se.useMemo(()=>Dt(),[]),m=Se.useMemo(()=>u&&c?c:n.themeMode==="light"?Un(n.lightThemeId,"light"):n.themeMode==="dark"||a?Un(n.darkThemeId,"dark"):Un(n.lightThemeId,"light"),[u,n,a,c]),f=Se.useMemo(()=>u&&c?[c,...vn]:vn,[u,c]);Se.useEffect(()=>{if(!u)return;const N=F=>{d(F);const I=F.metadata.variant==="dark"?"dark":"light",M=Fe.getState();M.theme!==I&&M.setTheme(I)},j=F=>{const I=F.detail;I?.theme&&N(I.theme)},k=window.__OPENCHAMBER_VSCODE_THEME__;return k&&N(k),window.addEventListener("openchamber:vscode-theme",j),()=>window.removeEventListener("openchamber:vscode-theme",j)},[u]);const p=Se.useCallback(N=>{if(typeof document>"u")return;const j=N.colors.surface.background;Xt()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=j;let k=document.querySelector('meta[name="theme-color"]');k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),document.head.appendChild(k)),k.setAttribute("content",j);const F=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let I=document.querySelector(`meta[name="theme-color"][media="${F}"]`);I||(I=document.createElement("meta"),I.setAttribute("name","theme-color"),I.setAttribute("media",F),document.head.appendChild(I)),I.setAttribute("content",j)},[]),h=Se.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);vv(()=>{if(typeof window>"u")return;t.apply(m),h(u),p(m);const N=document.documentElement;N.classList.remove("light","dark"),N.classList.add(m.metadata.variant)},[h,t,m,u,p]),Se.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),j=k=>{i(k.matches)};return i(N.matches),N.addEventListener("change",j),()=>N.removeEventListener("change",j)},[n.themeMode]),Se.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]),Se.useEffect(()=>{es({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]),Se.useEffect(()=>{if(typeof window>"u")return;const N=j=>{const k=j.detail;k&&o(F=>{let I=F.themeMode;k.useSystemTheme===!0?I="system":k.useSystemTheme===!1&&(k.themeVariant==="dark"||k.themeVariant==="light")&&(I=k.themeVariant);let M=F.lightThemeId;typeof k.lightThemeId=="string"&&k.lightThemeId.length>0&&(M=jo(k.lightThemeId,"light"));let b=F.darkThemeId;return typeof k.darkThemeId=="string"&&k.darkThemeId.length>0&&(b=jo(k.darkThemeId,"dark")),I===F.themeMode&&M===F.lightThemeId&&b===F.darkThemeId?F:{themeMode:I,lightThemeId:M,darkThemeId:b}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const y=Se.useCallback(N=>{const j=f.find(k=>k.metadata.id===N);j&&o(k=>j.metadata.variant==="dark"?k.darkThemeId===j.metadata.id&&k.themeMode==="dark"?k:{...k,darkThemeId:j.metadata.id,themeMode:"dark"}:k.lightThemeId===j.metadata.id&&k.themeMode==="light"?k:{...k,lightThemeId:j.metadata.id,themeMode:"light"})},[f]),g=Se.useCallback(N=>{o(j=>j.themeMode===N?j:{...j,themeMode:N})},[]),w=Se.useCallback(N=>{if(N){o(k=>k.themeMode==="system"?k:{...k,themeMode:"system"});return}const j=m.metadata.variant==="dark"?"dark":"light";o(k=>k.themeMode===j?k:{...k,themeMode:j})},[m.metadata.variant]),x=Se.useCallback(N=>{const j=f.find(k=>k.metadata.id===N&&k.metadata.variant==="light");j&&o(k=>k.lightThemeId===j.metadata.id?k:{...k,lightThemeId:j.metadata.id})},[f]),v=Se.useCallback(N=>{const j=f.find(k=>k.metadata.id===N&&k.metadata.variant==="dark");j&&o(k=>k.darkThemeId===j.metadata.id?k:{...k,darkThemeId:j.metadata.id})},[f]),S={currentTheme:m,availableThemes:f,setTheme:y,isSystemPreference:n.themeMode==="system",setSystemPreference:w,themeMode:n.themeMode,setThemeMode:g,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:x,setDarkThemePreference:v};return e.jsx(mi.Provider,{value:S,children:s})}const kv=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=Fe();return l.useLayoutEffect(()=>{t(),o(),i()},[r,t,n,o,a,i]),l.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})},Nv={getLastAssistantMessage(){const s=ye.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}),i=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=!i&&!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:i,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!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&&!i&&!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=ye.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=ye.getState(),t=s.currentDirectory||null,n=Le.getDirectory()??null,o=r.sessions||[],a=new Set,i={};o.forEach(k=>{const F=k.directory;typeof F=="string"&&F.trim().length>0?(a.add(F),i[F]=(i[F]??0)+1):i["(none)"]=(i["(none)"]??0)+1});const c=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(k){return{available:!1,error:k instanceof Error?k.message:String(k)}}})(),d=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,u=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,m=!!(d?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),f=async k=>{try{return await k.json()}catch{return null}},p=async k=>{try{return await k.text()}catch{return null}},h=async k=>{try{const F=await fetch(k);return F.ok?await f(F):{status:F.status}}catch(F){return{error:F instanceof Error?F.message:String(F)}}};let y=null,g=null,w=null,x=null;const v=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";y=await h(v);const S=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";g=await h(S),w=await h("/api/config/settings");try{const k=await fetch("/api/health"),F=k.headers.get("content-type")||"",I=await p(k);x={status:k.status,ok:k.ok,contentType:F,type:F.includes("application/json")?"json":"html",preview:I?I.slice(0,120):null}}catch(k){x={error:k instanceof Error?k.message:String(k)}}let N={isGitRepo:null};if(t)try{N.isGitRepo=await Zr(t)}catch(k){N={isGitRepo:null,error:k instanceof Error?k.message:String(k)}}const j={runtime:{isDesktop:m,hasRuntimeApis:!!d,desktopServerOrigin:u?.origin??null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:t,opencodeDirectory:y?.directory||y?.worktree||n,homeDirectory:s.homeDirectory||null,isHomeReady:s.isHomeReady,hasPersistedDirectory:s.hasPersistedDirectory,isSwitchingDirectory:s.isSwitchingDirectory},sessions:{total:o.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:a.size,directorySamples:Array.from(a).slice(0,5),directoryCounts:i},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:N,localStorage:c,opencode:{pathInfo:y,projectInfo:g,health:x},openchamber:{settingsInfo:w}};return console.log("[DEBUG] App status snapshot:",j),j},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=ye.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=ye.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(s.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!i&&!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:
115
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
116
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
117
- `),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)
118
- `),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=ye.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],c=r?i:i.filter(p=>p.info.role==="assistant"),d={totalMessages:i.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??{},x=u(w.completed),v=x!==null,S=g.filter(A=>A.type==="tool"),N=g.filter(A=>A.type==="reasoning"),j=m(S.map(A=>u(A.state?.time?.end??A.state?.time?.start))),k=m(N.map(A=>u(A.time?.end??A.time?.start))),F=m([j,k].filter(A=>A!==null)),I=S.some(A=>["pending","running","started"].includes(A.state?.status)),M=N.some(A=>typeof A.time?.end!="number");S.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const b=!!(v&&typeof j=="number"&&x<j);b&&(d.completedBeforeTool+=1);const C=!!(v&&typeof k=="number"&&x<k);return C&&(d.completedBeforeReasoning+=1),v&&I&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:y.id,role:y.role,completedAt:x,latestToolTimestamp:j,latestReasoningTimestamp:k,latestPartTimestamp:F,completed_missing:!v,completed_before_tool:b,completed_before_reasoning:C,running_tools_when_completed:!!(v&&I),reasoning_open_when_completed:!!(v&&M),has_tools:S.length>0,has_reasoning:N.length>0}});return t&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const s=ye.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"),i=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&i),p=s.messageStreamStates,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:",i),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:i,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Nv,Ot()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",s=>{try{const r=s.message||"",t=s.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&s.preventDefault()}catch{}}));let $c=!1;const Cv=()=>{if($c||typeof window>"u")return;$c=!0;let s={showReasoningTraces:Fe.getState().showReasoningTraces,autoDeleteEnabled:Fe.getState().autoDeleteEnabled,autoDeleteAfterDays:Fe.getState().autoDeleteAfterDays},r=null,t=null;const n=()=>{const a=r;r=null,t=null,a&&Object.keys(a).length>0&&es(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};Fe.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};i.showReasoningTraces!==s.showReasoningTraces&&(c.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==s.autoDeleteEnabled&&(c.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(c.autoDeleteAfterDays=i.autoDeleteAfterDays),s=i,Object.keys(c).length>0&&o(c)})};let _c=!1;const Bc="openchamber-typography-base",Mv=()=>{if(typeof document>"u")return;const r=`:root {
119
- ${Object.entries(ri).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
120
- `)}
121
- }
122
- `,t=document.getElementById(Bc);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=Bc,n.textContent=r,document.head.appendChild(n)},Dv=()=>{_c||typeof window>"u"||(_c=!0,Mv())},Av=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await dd();await ud();Cv();Dv();await Pu();typeof window<"u"&&(window.debugContextTokens=()=>{const s=window.__zustand_session_store__;if(!s)return;const r=s.getState(),t=r.currentSessionId;if(!t)return;const o=(r.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const i=o[o.length-1].info.tokens;i&&typeof i=="object"&&console.debug("Token breakdown:",{base:(i.input||0)+(i.output||0)+(i.reasoning||0),cache:i.cache?(i.cache.read||0)+(i.cache.write||0):0}),r.sessionContextUsage.get(t);const 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 _u=document.getElementById("root");if(!_u)throw new Error("Root element not found");Ef.createRoot(_u).render(e.jsx(Se.StrictMode,{children:e.jsx(Sv,{children:e.jsx(kv,{children:e.jsx(xv,{children:e.jsx(mv,{apis:Av})})})})}));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 Tv=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{os as D,br as S,as as a,rg as b,O as c,oy as d,ay as e,Ql as f,Cr as g,iy as h,cy as i,Tv as m,mu as p,ly as r,qn as t};