@openchamber/web 1.4.7 → 1.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,128 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-C07YQe9X.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-oDE1UvDN.js","assets/index-BqCwlsig.js","assets/index-CFHNKWvn.css"])))=>i.map(i=>d[i]);
2
- import{t as Cf,c as Mf,F as Df,j as e,R as Af,T as Ef,P as If,C as Pf,A as Tf,a as Ff,b as zt,d as Kt,p as As,e as Es,f as Rf,_ as rs,g as c,r as _f,i as Wt,I as Of,k as $f,l as Lf,m as Bf,n as zf,o as Wf,q as Hf,s as Uf,u as Tt,v as Vf,S as Gf,L as qf,w as tu,x as Kf,y as Yf,z as Qf,B as Ce,D as Rl,E as hi,G as Xf,H as Et,K as Hi,J as Jf,U as cs,M as su,N as Zf,O as Dr,Z as ep,Y as nr,Q as Er,W as $t,V as aa,X as tp,$ as qr,a0 as Zr,a1 as Kr,a2 as gi,a3 as Ps,a4 as ru,a5 as sp,a6 as rp,a7 as np,a8 as op,a9 as ap,aa as ip,ab as lp,ac as Do,ad as cp,ae as dp,af as Ho,ag as Yr,ah as ne,ai as ls,aj as yr,ak as en,al as so,am as qt,an as or,ao as up,ap as mp,aq as nu,ar as Ui,as as Qr,at as ou,au as ar,av as au,aw as jn,ax as fp,ay as ia,az as Us,aA as Ca,aB as pp,aC as Ir,aD as mr,aE as Gs,aF as hp,aG as qs,aH as gp,aI as _l,aJ as xp,aK as yp,aL as bp,aM as wp,aN as vp,aO as jp,aP as Sp,aQ as kp,aR as Np,aS as Cp,aT as ur,aU as Ma,aV as Mp,aW as ir,aX as Vi,aY as Gi,aZ as Dp,a_ as Ap,a$ as Ep,b0 as Ip,b1 as Pp,b2 as Tp,b3 as Fp,b4 as Rp,b5 as _p,b6 as Op,b7 as $p,b8 as Lp,b9 as Bp,ba as zp,bb as Wp,bc as Hp,bd as Up,be as Vp,bf as Gp,bg as fr,bh as Uo,bi as br,bj as tr,bk as qp,bl as Kp,bm as la,bn as Yp,bo as qi,bp as Qp,bq as Xp,br as Jp,bs as Kn,bt as Zp,bu as eh,bv as th,bw as sh,bx as rh,by as xi,bz as Ao,bA as ca,bB as nh,bC as oh,bD as xn,bE as fn,bF as iu,bG as lu,bH as ah,bI as ih,bJ as Fs,bK as cu,bL as lh,bM as du,bN as ch,bO as dh,bP as yi,bQ as uu,bR as mu,bS as uh,bT as hr,bU as Yn,bV as mh,bW as fh,bX as bi,bY as ro,bZ as An,b_ as ph,b$ as fu,c0 as Ki,c1 as Yi,c2 as Qi,c3 as hh,c4 as gh,c5 as xh,c6 as Ol,c7 as pu,c8 as yh,c9 as Qn,ca as hu,cb as gu,cc as Da,cd as da,ce as xu,cf as bh,cg as wi,ch as yu,ci as vi,cj as wh,ck as vh,cl as jh,cm as Sh,cn as kh,co as Nh,cp as Ch,cq as Mh,cr as Dh}from"./vendor-.bun-C07YQe9X.js";import{c as Ah,l as Eh,g as Ih,r as Ph,d as Th,a as Fh,b as Rh,e as _h,u as Oh,f as $h,h as Lh,i as Bh,j as zh,k as Wh}from"./index-BqCwlsig.js";const as=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Ht=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Xi=()=>typeof window>"u"?!1:!as()&&!Ht(),Pr=()=>as()?window.opencodeDesktop??null:null,bu=()=>{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},wu=async()=>{const s=Pr();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},Hh=async()=>{const s=Pr();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Uh=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,En=async()=>{const s=bu();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Vh=async s=>{const r=bu();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},Gh=async s=>{const r=Pr();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)}}},qh=async s=>{const r=Pr();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)}}},Kh=async s=>{const r=Pr();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)}}},Yh=async()=>{const s=Pr();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},Qh=async s=>{const r=Pr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},Xh=async()=>{const s=Pr();if(!s||!s.restartToUpdate)return!1;try{return await s.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function T(...s){return Cf(Mf(s))}const vu=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Cs=s=>vu()&&as()?s.metaKey:s.ctrlKey,Zt=()=>vu()&&as()?"⌘":"Ctrl",ju=(s,r)=>{const t=s??"",n=Math.max(16,r?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let l="";for(const d of o){if(!d)continue;const u=l?`${l}/${d}`:d;if(u.length>i)break;l=u}if(!l){const d=o[0]??"";l=d?d.slice(0,i):""}return l?`${l}…/${a}`:`…/${a}`},Vo=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Hr(s,r){if(!s)return"";const t=Vo(s);if(t==="/")return"/";const n=r?Vo(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 $l(s,r){if(!s)return"/";const t=Vo(s);if(!t||t==="/")return"/";const n=r?Vo(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Is(s,r){return r?s?s.toLowerCase().includes(r.toLowerCase())?!0:new Df([s],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function Jh({delayDuration:s=0,...r}){return e.jsx(Ff,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function nt({delayDuration:s=0,...r}){return e.jsx(Jh,{delayDuration:s,children:e.jsx(Af,{"data-slot":"tooltip",...r})})}function ot({...s}){return e.jsx(Ef,{"data-slot":"tooltip-trigger",...s})}function rt({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(If,{children:e.jsxs(Pf,{"data-slot":"tooltip-content",sideOffset:r,className:T("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(Tf,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Aa=null;const Ll=()=>{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}}},Zh=()=>{if(typeof window>"u"||!window.localStorage)return Ll();const s=window.localStorage,r=Ll();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const m=s.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(t)try{s.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(t)try{s.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(t)try{s.clear()}catch{n()}r.clear()},key:u=>{if(t)try{return s.key(u)}catch{n()}return r.key(u)},get length(){if(t)try{return s.length+r.length}catch{n()}return r.length}}},ds=()=>(Aa||(Aa=Zh()),Aa),Ji={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},eg={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Bl(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const pr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Eo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...pr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Eo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...pr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Eo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...pr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Eo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...pr.tool.inline})},$e=zt()(Kt(As((s,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,toolCallExpansion:"collapsed",fontSize:100,padding:100,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,isTimelineDialogOpen:!1,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(Ji);if(o===1){for(const[i]of a)n.style.removeProperty(Bl(i));return}for(const[i,l]of a){const d=parseFloat(l);Number.isFinite(d)&&n.style.setProperty(Bl(i),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=r(),n=document.documentElement,o=t/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(i=>i.providerID===t&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===t&&i.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{s(o=>{const a=o.recentModels.filter(i=>!(i.providerID===t&&i.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||s(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)},setMultiRunLauncherOpen:t=>{s(n=>({isMultiRunLauncherOpen:t,multiRunLauncherPrefillPrompt:t?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:t=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:t,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:t=>{s({isTimelineDialogOpen:t})}}),{name:"ui-store",storage:Es(()=>ds()),partialize:s=>({theme:s.theme,isSidebarOpen:s.isSidebarOpen,sidebarWidth:s.sidebarWidth,isSessionSwitcherOpen:s.isSessionSwitcherOpen,activeMainTab:s.activeMainTab,sidebarSection:s.sidebarSection,isSessionCreateDialogOpen:s.isSessionCreateDialogOpen,isSettingsDialogOpen:s.isSettingsDialogOpen,showReasoningTraces:s.showReasoningTraces,autoDeleteEnabled:s.autoDeleteEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,autoDeleteLastRunAt:s.autoDeleteLastRunAt,toolCallExpansion:s.toolCallExpansion,fontSize:s.fontSize,padding:s.padding,favoriteModels:s.favoriteModels,recentModels:s.recentModels,diffLayoutPreference:s.diffLayoutPreference,diffWrapLines:s.diffWrapLines})}),{name:"ui-store"}));async function tg(){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 sg(){return as()?"desktop":Xi()?"web":null}const zl={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},ua=zt()((s,r)=>({...zl,checkForUpdates:async()=>{const t=sg();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await Yh():t==="web"&&(n=await tg()),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 Qh(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 Xh()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(zl)}})),rg="/api",ng=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,og=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(ng.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}},ag=()=>{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},io=s=>s.replace(/\\/g,"/"),Ea=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class ig{client;baseUrl;sseAbortControllers=new Map;currentDirectory=void 0;globalSseAbortController=null;globalSseTask=null;globalSseLastEventId;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;constructor(r=rg){const n=ag()||r;this.baseUrl=og(n),this.client=Rf({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const t=r.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const t=r.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],l=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,t){if(r==null)return t();const n=this.currentDirectory;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&r.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const t=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(r){const t=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,t){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:t});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const t=r.toLowerCase();return t.startsWith("text/")&&t!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async convertHeicToJpeg(r){try{const t=(await rs(async()=>{const{default:f}=await import("./vendor-.bun-C07YQe9X.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),i=new Uint8Array(a.length);for(let f=0;f<a.length;f++)i[f]=a.charCodeAt(f);const l=new Blob([i],{type:r.mime}),d=await t({blob:l,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const g=new FileReader;g.onload=()=>f(g.result),g.onerror=p,g.readAsDataURL(d)});let m=r.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(t){return console.warn("Failed to convert HEIC to JPEG:",t),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(!this.shouldNormalizeToTextPlain(r.mime))return r;let t=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),a=r.url.substring(n);t=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:t}}async sendMessage(r){const t=Date.now(),n=r.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const i=await this.normalizeFilePart(a),l={type:"file",mime:i.mime,filename:i.filename,url:i.url};o.push(l)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text}),a.files&&a.files.length>0)for(const i of a.files){const l=await this.normalizeFilePart(i),d={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,t,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const t=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Failed to unrevert session");return t.data}async forkSession(r,t){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const i=await a.json().catch(()=>null);return!i||typeof i!="object"?{}:i}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async listToolIds(r){try{const t=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,t,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:t,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async replyToQuestion(r,t){const n=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];return(await this.client.question.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:n})).data||!1}async rejectQuestion(r){return(await this.client.question.reject({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(r){const t=[],n=async d=>{try{const u=typeof d=="string"?d.trim():"";return(await this.client.question.list(u?{directory:u}:void 0)).data||[]}catch{return[]}};t.push(n(null));const o=new Set;for(const d of r?.directories??[]){const u=this.normalizeCandidatePath(d??null);u&&o.add(u)}for(const d of o)t.push(n(d));const a=await Promise.all(t),i=[],l=new Set;for(const d of a)for(const u of d){if(!u||typeof u!="object")continue;const m=u.id;typeof m!="string"||m.length===0||l.has(m)||(l.add(m),i.push(u))}return i}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(r){const t=await this.getConfig(),n=r(t);return await this.updateConfig(n)}async getProviders(){const r=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!r.data)throw new Error("Failed to get providers");return r.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(r){if(!r)return null;const t=r.split(`
3
- `),n=[];let o;for(const i of t)if(i.startsWith("data:"))n.push(i.slice(5).replace(/^\s/,""));else if(i.startsWith("id:")){const l=i.slice(3).trim();l&&(o=l)}if(n.length===0)return null;const a=n.join(`
4
- `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const t=r,n=typeof t.directory=="string"?t.directory:typeof t.properties=="object"&&t.properties!==null?t.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof t.type=="string")return{directory:o&&o.length>0?o:"global",payload:t};const a=t.payload;if(a&&typeof a=="object"){const i=a;if(typeof i.type=="string")return{directory:o&&o.length>0?o:"global",payload:i}}return null}emitGlobalSseEvent(r){for(const t of this.globalSseListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(t){console.warn("[OpencodeClient] Global SSE open handler error:",t)}}notifyGlobalSseError(r){for(const t of this.globalSseErrorListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const r=new AbortController;this.globalSseAbortController=r,this.globalSseTask=this.runGlobalSseLoop(r).catch(t=>{t?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",t)}).finally(()=>{this.globalSseAbortController===r&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null)}async runGlobalSseLoop(r){const t=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!r.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const i=await fetch(t,{method:"GET",headers:a,signal:r.signal});if(!i.ok||!i.body)throw new Error(`Global SSE connect failed with status ${i.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const l=i.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await l.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
5
- `);const g=u.split(`
6
-
7
- `);u=g.pop()??"";for(const b of g){const h=this.parseSseBlock(b);if(!h)continue;h.id&&(this.globalSseLastEventId=h.id);const j=this.normalizeRoutedSsePayload(h.data);j&&this.emitGlobalSseEvent(j)}}const m=u.trim();if(m&&!r.signal.aborted){const f=this.parseSseBlock(m);f?.id&&(this.globalSseLastEventId=f.id);const p=f?this.normalizeRoutedSsePayload(f.data):null;p&&this.emitGlobalSseEvent(p)}this.globalSseIsConnected=!1}catch(a){if(this.globalSseIsConnected=!1,a?.name==="AbortError"||r.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",a),this.notifyGlobalSseError(a)}if(r.signal.aborted)break;n+=1;const o=Math.min(3e3*Math.pow(2,n),3e4);await new Promise(a=>setTimeout(a,o))}}subscribeToGlobalEvents(r,t,n,o){const a=this.normalizeCandidatePath(o?.directory??null),i=l=>{a&&l.directory!==a||r(l)};return this.globalSseListeners.add(i),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),t&&this.globalSseErrorListeners.add(t),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(i),n&&this.globalSseOpenListeners.delete(n),t&&this.globalSseErrorListeners.delete(t),this.maybeStopGlobalSse()}}subscribeToEvents(r,t,n,o,a){const i=a?.key??"default",l=a?.scope??"directory",d=this.sseAbortControllers.get(i);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(i,u);let m;if(l==="global"){let p=null;const g=h=>{if(h.directory==="global")return h.payload;const j=h.payload,y=typeof j.properties=="object"&&j.properties!==null?j.properties:{};return y.directory===h.directory?h.payload:{...j,properties:{...y,directory:h.directory}}},b=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)};return u.signal.addEventListener("abort",b,{once:!0}),p=this.subscribeToGlobalEvents(h=>{u.signal.aborted||r(g(h))},t?h=>{u.signal.aborted||t(h)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{b(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const g=p;if(typeof g.type=="string")return g;const b=g.payload;if(b&&typeof b=="object"){const h=b;if(typeof h.type=="string"){if(typeof g.directory=="string"&&g.directory.length>0){const y={...(typeof h.properties=="object"&&h.properties!==null?h.properties:null)??{},directory:g.directory};return{...h,properties:y}}return h}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const p=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",p??"default");const g=async b=>{try{const h=p?{directory:p}:void 0,j={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:x=>{x instanceof Error&&x.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",x),t&&!u.signal.aborted&&t(x))},onSseEvent:x=>{if(u.signal.aborted)return;x.id&&typeof x.id=="string"&&(m=x.id);const v=x.data,N=f(v);N&&r(N)}};m&&(j.headers={...j.headers||{},"Last-Event-ID":m});const y=await this.client.event.subscribe(h,j);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const x of y.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(h){if(h?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",h),t&&t(h);const j=Math.min(3e3*Math.pow(2,b),3e4);await new Promise(y=>setTimeout(y,j)),u.signal.aborted||await g(b+1);return}if(!u.signal.aborted){const h=Math.min(3e3*Math.pow(2,b),3e4);await new Promise(j=>setTimeout(j,h)),await g(b+1)}};try{await g(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)}})(),()=>{this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i),u.abort()}}async readFile(r){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${r}
8
- // This would be loaded from the server`}}async listFiles(r){try{const t=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model,template:t.template,subtask:t.subtask}))}catch{return[]}}async getCommandDetails(r){try{const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(t.data){const n=t.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;t==="/api"?r="/health":t.endsWith("/api")?r=`${t.slice(0,-4)}/health`:r=`${t}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const t=Ea();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=Ea();if(t)try{const n=await t.listDirectory(r||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:io(o.path),isDirectory:!!o.isDirectory,isFile:!o.isDirectory,isSymbolicLink:!1}))}catch(n){throw console.error("Failed to list directory contents:",n),n}try{const n=new URLSearchParams;r&&r.trim().length>0&&n.set("path",r);const o=n.toString(),a=await fetch(`${this.baseUrl}/fs/list${o?`?${o}`:""}`);if(!a.ok){const l=await a.json().catch(()=>({})),d=typeof l.error=="string"?l.error:"Failed to list directory";throw new Error(d)}const i=await a.json();return!i||!Array.isArray(i.entries)?[]:i.entries}catch(n){throw console.error("Failed to list directory contents:",n),n}}async searchFiles(r,t){const n=Ea(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?io(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=io(f.path),g=p.split("/").filter(Boolean).pop()||p,b=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?io(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||g;return{name:g,path:p,relativePath:b,extension:g.includes(".")?g.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const i=new URLSearchParams;o&&o.length>0&&i.set("directory",o),typeof r=="string"&&i.set("q",r),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&i.set("limit",String(t.limit));const l=`${this.baseUrl}/fs/search${i.toString()?`?${i.toString()}`:""}`,d=await fetch(l,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await wu();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 ke=new ig,lg=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:ke},Symbol.toStringTag,{value:"Module"})),ji=new Set;function ma(s){return ji.add(s),()=>{ji.delete(s)}}function sr(s,r){const t=Array.isArray(s)?s:[s],n=Array.from(new Set(t));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const a of ji)try{const i=a(o);i instanceof Promise&&i.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function Xn(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const Zi="Updating OpenCode configuration...";let rr=0,Ar=Zi;const Si=new Set;function Go(){const s={isUpdating:rr>0,message:Ar};Si.forEach(r=>r(s))}function Vs(s){rr+=1,rr===1?(Ar=s||Zi,Go()):s&&(Ar=s,Go())}function Ds(){rr!==0&&(rr-=1,rr===0&&(Ar=Zi,Go()))}function gr(s){Ar===s&&rr>0||(Ar=s,rr>0&&Go())}function cg(s){return Si.add(s),s({isUpdating:rr>0,message:Ar}),()=>{Si.delete(s)}}function dg(){return{isUpdating:rr>0,message:Ar}}const Zs=zt()(Kt(As((s,r)=>({queuedMessages:{},queueModeEnabled:!1,addToQueue:(t,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};s(i=>{const l=i.queuedMessages[t]??[];return{queuedMessages:{...i.queuedMessages,[t]:[...l,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const i=(o.queuedMessages[t]??[]).filter(l=>l.id!==n);if(i.length===0){const{[t]:l,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:i}}})},popToInput:(t,n)=>{const i=(r().queuedMessages[t]??[]).find(l=>l.id===n);return i?(s(l=>{const u=(l.queuedMessages[t]??[]).filter(m=>m.id!==n);if(u.length===0){const{[t]:m,...f}=l.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...l.queuedMessages,[t]:u}}}),i):null},clearQueue:t=>{s(n=>{const{[t]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{s({queuedMessages:{}})},setQueueMode:t=>{s({queueModeEnabled:t}),os({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:Es(()=>ds()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),Wl=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},ug=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},mg=s=>{const r=$e.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},fg=async()=>{if(typeof window>"u")return null;if(as()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return Wl(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=ug(r);return Wl(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Su=null;const Hl=s=>{Su=s},tn=()=>Su,Io=s=>{typeof window>"u"||(s.themeId&&localStorage.setItem("selectedThemeId",s.themeId),s.themeVariant&&localStorage.setItem("selectedThemeVariant",s.themeVariant),s.lightThemeId&&localStorage.setItem("lightThemeId",s.lightThemeId),s.darkThemeId&&localStorage.setItem("darkThemeId",s.darkThemeId),typeof s.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(s.useSystemTheme)),s.lastDirectory&&localStorage.setItem("lastDirectory",s.lastDirectory),s.homeDirectory&&(localStorage.setItem("homeDirectory",s.homeDirectory),window.__OPENCHAMBER_HOME__=s.homeDirectory),Array.isArray(s.projects)&&s.projects.length>0?localStorage.setItem("projects",JSON.stringify(s.projects)):localStorage.removeItem("projects"),s.activeProjectId?localStorage.setItem("activeProjectId",s.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(s.pinnedDirectories)&&s.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(s.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},pg=s=>{if(!Array.isArray(s))return;const r=[],t=new Set;for(const n of s){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",l=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!i||!l||t.has(a)||(t.add(a),r.push({id:a,label:i,source:l,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},hg=s=>{if(!Array.isArray(s))return;const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=l==="/"?l:l.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&m.branchPrefix.trim()&&(f.branchPrefix=m.branchPrefix.trim()),typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},ku=()=>{const s=$e.persist;if(s&&typeof s=="object")return s},Nu=()=>tn()?.settings??null,Po=s=>{const r=$e.getState(),t=Zs.getState();if(typeof s.showReasoningTraces=="boolean"&&s.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(s.showReasoningTraces),typeof s.autoDeleteEnabled=="boolean"&&s.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(s.autoDeleteEnabled),typeof s.autoDeleteAfterDays=="number"&&Number.isFinite(s.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,s.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof s.queueModeEnabled=="boolean"&&s.queueModeEnabled!==t.queueModeEnabled&&t.setQueueMode(s.queueModeEnabled)},Ul=s=>{if(!s||typeof s!="object")return null;const r=s,t={};typeof r.themeId=="string"&&r.themeId.length>0&&(t.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(t.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(t.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(t.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(t.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(t.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(t.homeDirectory=r.homeDirectory);const n=hg(r.projects);n&&(t.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(t.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(t.approvedDirectories=r.approvedDirectories.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.securityScopedBookmarks)&&(t.securityScopedBookmarks=r.securityScopedBookmarks.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(a=>typeof a=="string"&&a.length>0)))),typeof r.showReasoningTraces=="boolean"&&(t.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(t.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(t.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(t.defaultModel=r.defaultModel),typeof r.defaultVariant=="string"&&r.defaultVariant.length>0&&(t.defaultVariant=r.defaultVariant),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(t.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(t.autoCreateWorktree=r.autoCreateWorktree),typeof r.queueModeEnabled=="boolean"&&(t.queueModeEnabled=r.queueModeEnabled);const o=pg(r.skillCatalogs);return o&&(t.skillCatalogs=o),t},gg=async()=>{const s=Nu();if(s)try{const r=await s.load();return Ul(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 Ul(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},Cu=async()=>{if(typeof window>"u")return;const s=ku(),r=t=>{Io(t);const n=()=>Po(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=as()?await En():await gg();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},os=async s=>{if(typeof window>"u")return;if(as()){try{const t=await Vh(s);t&&(Io(t),Po(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=Nu();if(r)try{const t=await r.save(s);t&&(Io(t),Po(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&&(Io(n),Po(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Mu=async()=>{if(typeof window>"u")return;const s=ku();try{const r=await fg();if(!r)return;const t=()=>mg(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)}},xg=3e4,yg=40,bg=60,wg=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},el=zt()(Kt((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=bg){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",l=wg(a,i,o),d=Date.now(),u=r().cache[l];if(u&&d-u.timestamp<xg)return u.files;const m=r().inFlight[l];if(m)return m;const f=ke.searchFiles(i,{directory:a,limit:o}).then(p=>(s(g=>{const b={...g.cache,[l]:{files:p,timestamp:Date.now()}},h=g.cacheKeys.filter(j=>j!==l);for(h.push(l);h.length>yg;){const j=h.shift();j&&delete b[j]}return{cache:b,cacheKeys:h}}),p)).finally(()=>{s(p=>{const g={...p.inFlight};return delete g[l],{inFlight:g}})});return s(p=>({inFlight:{...p.inFlight,[l]:f}})),f},invalidateDirectory(t){if(!t||t.trim().length===0){s({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;s(a=>{const i={...a.cache},l=a.cacheKeys.filter(m=>m.startsWith(o)?(delete i[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:l,inFlight:u}})}}),{name:"file-search-store"})),Qt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var vg={};let Ws=null;const zs=ds(),Vl=zs.getItem("lastDirectory"),jg=typeof Vl=="string"&&Vl.length>0,lo=s=>{try{el.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Sg=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},kg=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},To=(s,r)=>{const t=kg(s,r);return Sg(t)},qo=()=>{if(typeof window<"u"){const r=zs.getItem("homeDirectory")||Ws||null,t=zs.getItem("lastDirectory");if(t)return To(t,r);if(Ws)return Ws;const n=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:window.opencodeDesktop&&typeof window.opencodeDesktop.homeDirectory=="string"?window.opencodeDesktop.homeDirectory:null;if(n&&n.length>0)return Ws=n,zs.setItem("homeDirectory",n),n;if(r)return Ws=r,r}const s=typeof process<"u"&&vg?.HOME;return s||process?.cwd?.()||"/"},Ng=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},Cg=s=>(Ws=s,typeof window<"u"&&zs.setItem("homeDirectory",s),os({homeDirectory:s}),s),Du=async()=>{const s=n=>{const o=Ng(n);return o?Cg(o):null};try{const n=await ke.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await ke.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 wu(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=qo(),t=s(r);return t||r},Ur=qo();Ur&&ke.setDirectory(Ur);const Mg=!!(Ur&&Ur!=="/"),dt=zt()(Kt((s,r)=>({currentDirectory:Ur,directoryHistory:[Ur],historyIndex:0,homeDirectory:Ur,hasPersistedDirectory:jg,isHomeReady:Mg,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=Ws||r().homeDirectory||zs.getItem("homeDirectory"),a=To(t,o);Qt()&&console.log("[DirectoryStore] setDirectory called with path:",a),ke.setDirectory(a),lo(),s(i=>{const l=[...i.directoryHistory.slice(0,i.historyIndex+1),a];return zs.setItem("lastDirectory",a),os({lastDirectory:a}),{currentDirectory:a,directoryHistory:l,historyIndex:l.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const t=r();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];ke.setDirectory(o),lo(),zs.setItem("lastDirectory",o),os({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const t=r();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];ke.setDirectory(o),lo(),zs.setItem("lastDirectory",o),os({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=Ws||r().homeDirectory||qo();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const l=Ws||qo();n(l)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=Ws||r().homeDirectory||await Du();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;Ws=o;const a=n.homeDirectory!==o,i=zs.getItem("lastDirectory"),l=typeof i=="string"&&i.length>0,d=!l&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||s({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?To(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(h=>To(h,o)),p=f.some((h,j)=>h!==n.directoryHistory[j]),g=!!(m&&m!==n.currentDirectory),b={homeDirectory:o,hasPersistedDirectory:l,isHomeReady:u};if(d?(b.currentDirectory=o,b.directoryHistory=[o],b.historyIndex=0,b.isSwitchingDirectory=!1):(g||p)&&(b.currentDirectory=m,b.directoryHistory=f,b.historyIndex=Math.min(n.historyIndex,f.length-1),b.isSwitchingDirectory=!1),s(()=>b),(d||g)&&u){const h=d?o:m;ke.setDirectory(h),lo(),zs.setItem("lastDirectory",h),os({lastDirectory:h})}os({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Du().then(s=>{dt.getState().synchronizeHomeDirectory(s)});const yn=ds(),Au="projects",ki="activeProjectId",Dg=(s,r)=>{const t=s.trim();return!t.startsWith("~")||!r?t:t==="~"?r:t.startsWith("~/")||t.startsWith("~\\")?`${r}${t.slice(1)}`:t},fa=s=>{const r=s.trim();if(!r)return"";const t=yn.getItem("homeDirectory")||dt.getState().homeDirectory||"",o=Dg(r,t).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Eu=s=>{const r=fa(s);if(!r||r==="/")return"Root";const t=r.split("/").filter(Boolean);return t[t.length-1]||r},Ag=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Iu=s=>{if(!Array.isArray(s))return[];const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=fa(l);if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&(f.branchPrefix=m.branchPrefix),typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},Eg=()=>{try{const s=yn.getItem(Au);return s?Iu(JSON.parse(s)):[]}catch{return[]}},Ig=()=>{try{const s=yn.getItem(ki);if(typeof s=="string"&&s.trim().length>0)return s.trim()}catch{return null}return null},tl=(s,r)=>{try{yn.setItem(Au,JSON.stringify(s))}catch{}try{r?yn.setItem(ki,r):yn.removeItem(ki)}catch{}},an=(s,r)=>{tl(s,r),os({projects:s,activeProjectId:r??void 0})},Pg=Eg(),Tg=()=>{if(typeof window>"u"||!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode)return null;const r=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof r!="string"||r.trim().length===0)return null;const t=fa(r);if(!t)return null;const n=`vscode:${t}`,o={id:n,path:t,label:Eu(t),addedAt:Date.now(),lastOpenedAt:Date.now()};return Qt()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},Ls=Tg(),sl=Ls?.projects??Pg,Pu=Ls?.activeProjectId??Ig()??sl[0]?.id??null;Ls&&tl(sl,Pu);const Ft=zt()(Kt((s,r)=>({projects:sl,activeProjectId:Pu,validateProjectPath:t=>{if(typeof t!="string"||t.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=fa(t);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(t,n)=>{if(Ls)return null;const{validateProjectPath:o}=r(),a=o(t);if(!a.ok||!a.normalizedPath)return null;const i=a.normalizedPath,l=r().projects.find(b=>b.path===i);if(l)return r().setActiveProject(l.id),l;const d=Date.now(),u=n?.label?.trim()||Eu(i),m=n?.id?.trim(),p={id:m&&!r().projects.some(b=>b.id===m)?m:Ag(),path:i,label:u,addedAt:d,lastOpenedAt:d},g=[...r().projects,p];return s({projects:g}),Qt()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:t=>{if(Ls)return;const n=r(),o=n.projects.filter(i=>i.id!==t);let a=n.activeProjectId;if(n.activeProjectId===t&&(a=o[0]?.id??null),s({projects:o,activeProjectId:a}),an(o,a),a){const i=o.find(l=>l.id===a);i&&(ke.setDirectory(i.path),dt.getState().setDirectory(i.path,{showOverlay:!1}))}else dt.getState().goHome()},setActiveProject:t=>{if(Ls)return;const{projects:n,activeProjectId:o}=r();if(o===t)return;const a=n.find(d=>d.id===t);if(!a)return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),an(l,t),ke.setDirectory(a.path),dt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:t=>{if(Ls)return;const{projects:n,activeProjectId:o}=r();if(o===t||!n.find(d=>d.id===t))return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),an(l,t)},renameProject:(t,n)=>{if(Ls)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:i}=r(),l=a.map(d=>d.id===t?{...d,label:o}:d);s({projects:l}),an(l,i)},reorderProjects:(t,n)=>{if(Ls)return;const{projects:o,activeProjectId:a}=r();if(t<0||t>=o.length||n<0||n>=o.length||t===n)return;const i=[...o],[l]=i.splice(t,1);i.splice(n,0,l),s({projects:i}),an(i,a)},synchronizeFromSettings:t=>{if(Ls)return;const n=Iu(t.projects??[]),o=typeof t.activeProjectId=="string"&&t.activeProjectId.trim()?t.activeProjectId.trim():null,a=r(),i=JSON.stringify(a.projects)!==JSON.stringify(n),l=a.activeProjectId!==o;if(!(!i&&!l)&&(s({projects:n,activeProjectId:o}),tl(n,o),o)){const d=n.find(u=>u.id===o);d&&(ke.setDirectory(d.path),dt.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:t,activeProjectId:n}=r();return n?t.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(t,n)=>{if(Ls)return;const{projects:o,activeProjectId:a}=r(),i=o.find(u=>u.id===t);if(!i)return;const l={...i.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?l.branchPrefix=n.branchPrefix.trim():delete l.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?l.baseBranch=n.baseBranch.trim():delete l.baseBranch),n.autoCreateWorktree!==void 0&&(l.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===t?{...u,worktreeDefaults:Object.keys(l).length>0?l:void 0}:u);s({projects:d}),an(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",s=>{const r=s.detail;r&&typeof r=="object"&&Ft.getState().synchronizeFromSettings(r)});const Fg=new Set(["init","review"]),pn=s=>Fg.has(s.name),Wn="useCommandsStore",Ni=s=>new Promise(r=>setTimeout(r,s)),co=()=>{try{const r=Ft.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=ke.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[CommandsStore] Error resolving config directory:",s)}return null},Rg=2e4,Gl=300,ql=4,_g=800,Og=200,$g=2e3,Tr=zt()(Kt(As((s,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:t=>{s({selectedCommandName:t})},setCommandDraft:t=>{s({commandDraft:t})},loadCommands:async()=>{s({isLoading:!0});const t=r().commands;let n=null;for(let o=0;o<3;o++)try{const a=co(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await ke.withDirectory(a,()=>ke.listCommandsWithDetails()),d=await Promise.all(l.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${i}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const g=f.sources;p=(g.md?.exists?g.md.scope:void 0)??(g.json?.exists?g.json.scope:void 0)??g.md?.scope??g.json?.scope}return p==="project"||p==="user"?{...u,scope:p}:{...u,scope:void 0}}}catch(m){console.warn(`[CommandsStore] Failed to fetch config for command ${u.name}:`,m)}return u}));return JSON.stringify(t)!==JSON.stringify(d)?s({commands:d,isLoading:!1}):s({isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{Vs("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),t.scope&&(o.scope=t.scope),console.log("[CommandsStore] Command config to save:",o);const a=co(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await Ia({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&sr("commands",{source:Wn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Ds()}},updateCommand:async(t,n)=>{Vs("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=co(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await Ia({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&sr("commands",{source:Wn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Ds()}},deleteCommand:async t=>{Vs("Deleting command configuration…");let n=!1;try{const o=co(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),l?.requiresReload??!0)return n=!0,await Ia({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&sr("commands",{source:Wn}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Ds()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:Es(()=>ds()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Tr);async function Lg(s){const r=typeof s=="number"&&s>0?Math.min(s,Gl):0;r>0&&await Ni(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Rg;){n+=1,gr(`Waiting for OpenCode… (attempt ${n})`);try{if(await ke.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=ql&&a<1200?Gl:Math.min(_g+Math.max(0,n-ql)*Og,$g);await Ni(i)}throw o||new Error("OpenCode did not become ready in time")}async function Ia(s={}){const{message:r,delayMs:t}=s;try{gr(r||"Refreshing commands…")}catch{}try{await Lg(t),gr("Refreshing commands…"),await Tr.getState().loadCommands(),sr("commands",{source:Wn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),gr("OpenCode refresh failed. Please retry refreshing configuration manually."),await Ni(1500)}finally{Ds()}}let Kl=null;Kl||(Kl=ma(s=>{if(s.source!==Wn&&Xn(s,"commands")){const{loadCommands:r}=Tr.getState();r()}}));const jr=()=>{const s=ke.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Fo="useSkillsStore",Hs=zt()(Kt(As((s,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:t=>{s({selectedSkillName:t})},setSkillDraft:t=>{s({skillDraft:t})},loadSkills:async()=>{s({isLoading:!0});const t=r().skills;let n=null;for(let o=0;o<3;o++)try{const a=jr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills${i}`);if(!l.ok)throw new Error(`Failed to list skills: ${l.status}`);const m=((await l.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return s({skills:m,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=jr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async t=>{Vs("Creating skill...");try{const n={name:t.name,description:t.description};t.instructions&&(n.instructions=t.instructions),t.scope&&(n.scope=t.scope),t.supportingFiles&&(n.supportingFiles=t.supportingFiles);const o=jr(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&sr("skills",{source:Fo}),d}catch{return!1}finally{Ds()}},updateSkill:async(t,n)=>{Vs("Updating skill...");try{const o={};n.description!==void 0&&(o.description=n.description),n.instructions!==void 0&&(o.instructions=n.instructions),n.supportingFiles!==void 0&&(o.supportingFiles=n.supportingFiles);const a=jr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t)}${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&sr("skills",{source:Fo}),u}catch{return!1}finally{Ds()}},deleteSkill:async t=>{Vs("Deleting skill...");try{const n=jr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`,{method:"DELETE"}),i=await a.json().catch(()=>null);if(!a.ok){const d=i?.error||"Failed to delete skill";throw new Error(d)}const l=await r().loadSkills();return l&&sr("skills",{source:Fo}),r().selectedSkillName===t&&s({selectedSkillName:null}),l}catch{return!1}finally{Ds()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=jr(),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=jr(),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=jr(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Es(()=>ds()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=Hs);let Yl=null;Yl||(Yl=ma(s=>{if(s.source!==Fo&&Xn(s,"skills")){const{loadSkills:r}=Hs.getState();r()}}));const Pa=()=>{const s=ke.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},no=zt()(Kt((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(),l=t?.refresh?"&refresh=true":"",d=i?`?directory=${encodeURIComponent(i)}${l}`:l?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const h=200*(a+1);await new Promise(j=>setTimeout(j,h));continue}const f=m.sources||[],p=m.itemsBySource||{},g=r().selectedSourceId,b=g&&f.some(h=>h.id===g)?g:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:b}),!0}catch(i){o={kind:"unknown",message:i instanceof Error?i.message:String(i)};const l=200*(a+1);await new Promise(d=>setTimeout(d,l))}return s({sources:n.sources,itemsBySource:n.itemsBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{s({isLoadingCatalog:!1})}},scanRepo:async t=>{s({isScanning:!0,lastScanError:null,scanResults:null});try{const n=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 l=i?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:l}),{ok:!1,error:l}}return i.ok?(s({scanResults:i.items||[]}),i):(s({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{s({isScanning:!1})}},installSkills:async t=>{s({isInstalling:!0,lastInstallError:null});try{const n=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 l={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}if(!a.ok||!i.ok){const l=i.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}return Hs.getState().loadSkills(),i}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return s({lastInstallError:o}),{ok:!1,error:o}}finally{s({isInstalling:!1})}}}),{name:"skills-catalog-store"})),Bg=()=>{const s=ke.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},uo=()=>{try{const r=Ft.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=ke.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[AgentsStore] Error resolving config directory:",s)}return null},zr=s=>{const r=s;return r.native===!0||r.builtIn===!0},Tu=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},Fu=s=>s.filter(r=>!Tu(r)),Ro="useAgentsStore",Ko=s=>new Promise(r=>setTimeout(r,s)),zg=2e4,Ql=300,Xl=4,Wg=800,Hg=200,Ug=2e3,Fr=zt()(Kt(As((s,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:t=>{s({selectedAgentName:t})},setAgentDraft:t=>{s({agentDraft:t})},loadAgents:async()=>{s({isLoading:!0});const t=r().agents;for(let n=0;n<3;n++)try{const o=uo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await ke.withDirectory(o,()=>ke.listAgents()),l=await Promise.all(i.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(t)!==JSON.stringify(l)?s({agents:l,isLoading:!1}):s({isLoading:!1}),!0}catch{}return s({isLoading:!1}),!1},createAgent:async t=>{Vs("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),t.scope&&(o.scope=t.scope),console.log("[AgentsStore] Agent config to save:",o);const a=uo(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Hn({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&sr("agents",{source:Ro}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Ds()}},updateAgent:async(t,n)=>{Vs("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const i=uo(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await Hn({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&sr("agents",{source:Ro}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Ds()}},deleteAgent:async t=>{Vs("Deleting agent configuration…");let n=!1;try{const o=uo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete agent";throw new Error(m)}if(l?.requiresReload??!0)return n=!0,await Hn({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&sr("agents",{source:Ro}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||Ds()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return Fu(t)}}),{name:"agents-store",storage:Es(()=>ds()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Fr);async function Vg(s){const r=typeof s=="number"&&s>0?Math.min(s,Ql):0;r>0&&await Ko(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<zg;){n+=1,gr(`Waiting for OpenCode… (attempt ${n})`);try{if(await ke.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=Xl&&a<1200?Ql:Math.min(Wg+Math.max(0,n-Xl)*Hg,Ug);await Ko(i)}throw o||new Error("OpenCode did not become ready in time")}const Gg=s=>{if(!s||s.length===0)return["all"];const r=Array.from(new Set(s));return r.includes("all")?["all"]:r};async function qg(s={}){const{message:r,delayMs:t}=s,n=Gg(s.scopes),o=s.mode??(n.includes("all")?"projects":"active");try{gr(r||"Refreshing configuration…")}catch{}try{await Vg(t);const a=st.getState(),i=Fr.getState(),l=Tr.getState(),d=Hs.getState(),u=no.getState(),m=n.includes("all")||n.includes("providers"),f=n.includes("all")||n.includes("agents"),p=n.includes("all")||n.includes("agents"),g=n.includes("all")||n.includes("commands"),b=n.includes("all")||n.includes("skills"),h=Bg(),j=o==="projects"?Ft.getState().projects:[],y=Array.from(new Set([...h?[h]:[],...j.map(N=>N.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&st.setState({directoryScoped:{}});const x=[];for(const N of y)m&&x.push(a.loadProviders({directory:N}).then(()=>{})),f&&x.push(a.loadAgents({directory:N}).then(()=>{}));const v=[];p&&v.push(i.loadAgents().then(()=>{})),g&&v.push(l.loadCommands().then(()=>{})),b&&(v.push(d.loadSkills().then(()=>{})),v.push(u.loadCatalog().then(()=>{}))),gr("Refreshing configuration…"),await Promise.all([...x,...v])}catch{gr("OpenCode refresh failed. Please retry."),await Ko(1500)}finally{Ds()}}async function Hn(s){await qg(s)}async function Un(s){Vs(s?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await r.json().catch(()=>null);if(!r.ok){const o=t?.error||"Failed to reload configuration";throw new Error(o)}const n={...s,scopes:s?.scopes??["all"],mode:s?.mode??"projects"};t?.requiresReload?await Hn({...n,message:t.message,delayMs:t.reloadDelayMs}):await Hn(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),gr("Failed to reload configuration. Please try again."),await Ko(2e3),Ds(),r}}let Jl=null;Jl||(Jl=ma(s=>{if(s.source!==Ro&&Xn(s,"agents")){const{loadAgents:r}=Fr.getState();r()}}));const Kg="https://models.dev/api.json",Yg="/api/openchamber/models-metadata",Zl="opencode",ec="big-pickle",Qg=async()=>{try{if(as()){const i=await En();return{defaultModel:i?.defaultModel,defaultVariant:i?.defaultVariant,defaultAgent:i?.defaultAgent,autoCreateWorktree:i?.autoCreateWorktree}}const s=tn()?.settings;if(s)try{const l=(await s.load())?.settings;if(l){const d=typeof l?.defaultModel=="string"?l.defaultModel.trim():"",u=typeof l?.defaultVariant=="string"?l.defaultVariant.trim():"",m=typeof l?.defaultAgent=="string"?l.defaultAgent.trim():"";return{defaultModel:d.length>0?d:void 0,defaultVariant:u.length>0?u:void 0,defaultAgent:m.length>0?m:void 0,autoCreateWorktree:typeof l?.autoCreateWorktree=="boolean"?l.autoCreateWorktree:void 0}}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const t=await r.json(),n=typeof t?.defaultModel=="string"?t.defaultModel.trim():"",o=typeof t?.defaultVariant=="string"?t.defaultVariant.trim():"",a=typeof t?.defaultAgent=="string"?t.defaultAgent.trim():"";return{defaultModel:n.length>0?n:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:a.length>0?a:void 0,autoCreateWorktree:typeof t?.autoCreateWorktree=="boolean"?t.autoCreateWorktree:void 0}}catch{return{}}},tc=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]}},Xg=s=>s?.toLowerCase?.()??"",Jg=s=>s==="primary"||s==="all"||s===void 0||s===null,Jn=s=>typeof s=="object"&&s!==null,Yo=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),Zg=s=>{if(!Jn(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!Yo(t)||n&&!Yo(n))return!1}return!0},ex=s=>{if(!Jn(s))return!1;const r=s;return r.models===void 0||Jn(r.models)},Ru=(s,r)=>{const t=Xg(s);return!t||!r?"":`${t}/${r}`},tx=s=>{const r=new Map;if(!Jn(s))return r;for(const[t,n]of Object.entries(s)){if(!ex(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!Jn(a)))for(const[i,l]of Object.entries(a)){if(!Zg(l))continue;const d=typeof i=="string"&&i.length>0?i:l.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof l.id=="string"&&l.id.length>0?l.id:d,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:Yo(l.modalities.input)?l.modalities.input:void 0,output:Yo(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},m=Ru(o,d);m&&r.set(m,u)}}return r},sx=async()=>{if(typeof fetch!="function")return new Map;const s=[Yg,Kg];for(const r of s){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(r,a);if(!i.ok)throw new Error(`Metadata request to ${r} returned status ${i.status}`);const l=await i.json();return tx(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let Ta=null;const rx=(s,r)=>{s().size>0||Ta||(Ta=sx().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{Ta=null}))},nx=s=>new Promise(r=>setTimeout(r,s)),rl="__global__",bn=s=>{const r=typeof s=="string"?s.trim():"";return r.length>0?r:rl},ln=s=>s===rl?null:s,ox=()=>{if(typeof window>"u")return rl;const s=ke.getDirectory()??dt.getState().currentDirectory;return bn(s)},st=zt()(Kt(As((s,r)=>({activeDirectoryKey:ox(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,activateDirectory:async t=>{const n=bn(t);s(o=>{const a=o.directoryScoped[n];return a?{activeDirectoryKey:n,providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders}:{activeDirectoryKey:n,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),r().isConnected&&(await r().loadProviders({directory:ln(n)}),await r().loadAgents({directory:ln(n)}))},loadProviders:async t=>{const n=bn(t?.directory??ln(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),i=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let l=null;for(let d=0;d<3;d++)try{rx(()=>r().modelsMetadata,g=>s({modelsMetadata:g}));const u=await ke.withDirectory(ln(n),()=>ke.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(g=>{const b=g.models??{},h=Object.keys(b).map(j=>b[j]);return{...g,models:h}});s(g=>{const h={...g.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},j={directoryScoped:{...g.directoryScoped,[n]:h}};return g.activeDirectoryKey===n&&(j.providers=p,j.defaultProviders=f),j});return}catch(u){l=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",l),s(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:i},f={directoryScoped:{...d.directoryScoped,[n]:m}};return d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=i),f})},setProvider:t=>{const{providers:n}=r(),o=n.find(l=>l.id===t);if(!o)return;const i=o.models[0]?.id||"";s(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:t,currentModelId:i,selectedProviderId:t};return{currentProviderId:t,currentModelId:i,selectedProviderId:t,directoryScoped:{...l.directoryScoped,[d]:m}}})},setModel:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:t};return{currentModelId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},setCurrentVariant:t=>{s(n=>{if(n.currentVariant===t)return n;const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:t};return{currentVariant:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const t=r().getCurrentModelVariants();if(t.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(t[0]);return}const o=t.indexOf(n);if(o===-1||o===t.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(t[o+1])},setSelectedProvider:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:t};return{selectedProviderId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},saveAgentModelSelection:(t,n,o)=>{s(a=>{const i=a.activeDirectoryKey,l={...a.agentModelSelections,[t]:{providerId:n,modelId:o}},u={...a.directoryScoped[i]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:l};return{agentModelSelections:l,directoryScoped:{...a.directoryScoped,[i]:u}}})},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async t=>{const n=bn(t?.directory??ln(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let i=null;for(let l=0;l<3;l++)try{const[d,u]=await Promise.all([ke.withDirectory(ln(n),()=>ke.listAgents()),Qg()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(s(w=>{const D={...w.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},M={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,directoryScoped:{...w.directoryScoped,[n]:D}};return w.activeDirectoryKey===n&&(M.agents=m),M}),m.length===0)return s(w=>{const D={...w.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},M={directoryScoped:{...w.directoryScoped,[n]:D}};return w.activeDirectoryKey===n&&(M.currentAgentName=void 0),M}),!0;const p=(w,k)=>{const D=f.find(M=>M.id===w);return D?D.models.some(M=>M.id===k):!1},g=m.filter(w=>Jg(w.mode));let j=g.find(w=>w.name==="build")||g[0]||m[0];const y={};if(u.defaultAgent){const w=m.find(k=>k.name===u.defaultAgent);w?j=w:y.defaultAgent=""}let x,v,N;if(u.defaultModel){const w=tc(u.defaultModel);if(w&&p(w.providerId,w.modelId)){if(x=w.providerId,v=w.modelId,u.defaultVariant){const M=f.find(C=>C.id===w.providerId)?.models.find(C=>C.id===w.modelId)?.variants;M&&Object.prototype.hasOwnProperty.call(M,u.defaultVariant)?N=u.defaultVariant:y.defaultVariant=""}}else y.defaultModel=""}if(!x&&j?.model?.providerID&&j?.model?.modelID&&p(j.model.providerID,j.model.modelID)&&(x=j.model.providerID,v=j.model.modelID),!x)if(p(Zl,ec))x=Zl,v=ec;else{const w=f[0];w&&w.models[0]&&(x=w.id,v=w.models[0].id)}return s(w=>{const k=w.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},D={...k,providers:f,agents:m,currentAgentName:j.name,currentProviderId:x??k.currentProviderId,currentModelId:v??k.currentModelId,currentVariant:N},M={directoryScoped:{...w.directoryScoped,[n]:D}};return w.activeDirectoryKey===n&&(M.currentAgentName=j.name,x&&v&&(M.currentProviderId=x,M.currentModelId=v,M.currentVariant=N)),M}),Object.keys(y).length>0&&(s({settingsDefaultModel:y.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:y.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:y.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),os(y).catch(()=>{})),!0}catch(d){i=d;const u=200*(l+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",i),s(l=>{const d=l.activeDirectoryKey===n?l.providers:l.directoryScoped[n]?.providers??[],m={...l.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...l.directoryScoped,[n]:m}};return l.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:i}=r();if(s(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentAgentName:t};return{currentAgentName:t,directoryScoped:{...l.directoryScoped,[d]:m}}}),t&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const d=l.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&l.setState(g=>{const b=new Map(g.currentAgentContext);return b.set(u,t),{currentAgentContext:b}}),u&&m(u)&&(p(u,t)||f(u,n))}}if(t&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const{currentSessionId:u,getAgentModelForSession:m}=l.getState();if(u&&m(u,t))return}if(a){const u=tc(a);if(u&&o.find(f=>f.id===u.providerId)?.models.some(f=>f.id===u.modelId)){s(f=>{const p=f.activeDirectoryKey,g=f.directoryScoped[p]??{providers:f.providers,agents:f.agents,currentProviderId:f.currentProviderId,currentModelId:f.currentModelId,currentVariant:f.currentVariant,currentAgentName:f.currentAgentName,selectedProviderId:f.selectedProviderId,agentModelSelections:f.agentModelSelections,defaultProviders:f.defaultProviders};let b;if(i){const x=o.find(v=>v.id===u.providerId)?.models.find(v=>v.id===u.modelId)?.variants;x&&Object.prototype.hasOwnProperty.call(x,i)&&(b=i)}const h={...g,currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:b};return{currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:b,directoryScoped:{...f.directoryScoped,[p]:h}}});return}}const d=n.find(u=>u.name===t);if(d?.model?.providerID&&d?.model?.modelID){const u=o.find(m=>m.id===d.model.providerID);u&&u.models.find(f=>f.id===d.model.modelID)&&s(f=>{const p=f.activeDirectoryKey,b={...f.directoryScoped[p]??{providers:f.providers,agents:f.agents,currentProviderId:f.currentProviderId,currentModelId:f.currentModelId,currentAgentName:f.currentAgentName,selectedProviderId:f.selectedProviderId,agentModelSelections:f.agentModelSelections,defaultProviders:f.defaultProviders},currentProviderId:d.model.providerID,currentModelId:d.model.modelID,selectedProviderId:d.model.providerID};return{currentProviderId:d.model.providerID,currentModelId:d.model.modelID,selectedProviderId:d.model.providerID,directoryScoped:{...f.directoryScoped,[p]:b}}})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultVariant:t=>{s({settingsDefaultVariant:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},setSettingsAutoCreateWorktree:t=>{s({settingsAutoCreateWorktree:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await ke.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await nx(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{const t=Qt();t&&console.log("Starting app initialization...");const n=await r().checkConnection();if(t&&console.log("Connection check result:",n),!n){t&&console.log("Server not connected"),s({isConnected:!1});return}t&&console.log("Initializing app..."),await ke.initApp(),t&&console.log("Loading providers..."),await r().loadProviders(),t&&console.log("Loading agents..."),await r().loadAgents(),s({isInitialized:!0,isConnected:!0}),t&&console.log("App initialized successfully")}catch(t){console.error("Failed to initialize app:",t),s({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:t,currentProviderId:n}=r();return t.find(o=>o.id===n)},getCurrentModel:()=>{const t=r().getCurrentProvider(),{currentModelId:n}=r();if(t)return t.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:t,currentAgentName:n}=r();if(n)return t.find(o=>o.name===n)},getModelMetadata:(t,n)=>{const o=Ru(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return Fu(t)}}),{name:"config-store",storage:Es(()=>ds()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=st);let sc=null;sc||(sc=ma(async s=>{const r=[];if(Xn(s,"agents")){const{loadAgents:t}=st.getState();r.push(t().then(()=>{}))}if(Xn(s,"providers")){const{loadProviders:t}=st.getState();r.push(t())}r.length>0&&await Promise.all(r)}));let rc=null;typeof window<"u"&&!rc&&(rc=dt.subscribe((s,r)=>{const t=bn(s.currentDirectory),n=bn(r.currentDirectory);t!==n&&st.getState().activateDirectory(s.currentDirectory)}));const us={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},ax=180,ks=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function sn(s){const r=ks();return r?r.checkIsGitRepository(s):Ah(s)}async function ix(s){const r=ks();return r?r.getGitStatus(s):Ih(s)}async function nl(s){const r=ks();return r?r.getGitBranches(s):Wh(s)}async function lx(s,r){const t=ks();return t?t.deleteGitBranch(s,r):Th(s,r)}async function cx(s,r){const t=ks();return t?t.deleteRemoteBranch(s,r):Fh(s,r)}async function dx(s){const r=ks();return r?r.listGitWorktrees(s):Eh(s)}async function ux(s,r){const t=ks();return t?t.addGitWorktree(s,r):Rh(s,r)}async function _u(s,r){const t=ks();return t?t.removeGitWorktree(s,r):Ph(s,r)}async function mx(s){const r=ks();return r?r.ensureOpenChamberIgnored(s):zh(s)}async function fx(){const s=ks();return s?s.getGitIdentities():Bh()}async function px(s){const r=ks();return r?r.createGitIdentity(s):$h(s)}async function hx(s,r){const t=ks();return t?t.updateGitIdentity(s,r):Oh(s,r)}async function gx(s){const r=ks();return r?r.deleteGitIdentity(s):_h(s)}async function xx(s){const r=ks();return r?r.getCurrentGitIdentity(s):Lh(s)}const yx="openchamber.json",Ou=".openchamber";function $u(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const bx=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ci=(s,r)=>{const t=bx(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Lu=s=>Ci(Ci(s,Ou),yx);async function Bu(s){const r=Lu(s);try{const t=$u();if(t?.readFile)try{const i=await t.readFile(r);if(!i.content.trim())return null;const l=JSON.parse(i.content);return!l||typeof l!="object"?null:l}catch{return null}const n=await fetch(`${Wu()}/fs/read?path=${encodeURIComponent(r)}`);if(!n.ok)return n.status===404,null;const o=await n.text();if(!o.trim())return null;const a=JSON.parse(o);return!a||typeof a!="object"?null:a}catch{return null}}async function wx(s,r){const t=Lu(s),n=Ci(s,Ou);try{await ke.createDirectory(n);const o=$u();if(o?.writeFile)try{return(await o.writeFile(t,JSON.stringify(r,null,2))).success}catch(i){return console.error("Failed to write openchamber config via runtime API:",i),!1}return(await fetch(`${Wu()}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,content:JSON.stringify(r,null,2)})})).ok}catch(o){return console.error("Failed to write openchamber config:",o),!1}}async function vx(s,r){const n={...await Bu(s)||{},...r};return wx(s,n)}async function oo(s){return(await Bu(s))?.["setup-worktree"]??[]}async function zu(s,r){const t=r.filter(n=>n.trim().length>0);return vx(s,{"setup-worktree":t})}function jx(s,r){return s.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function Wu(){const s="/api";return s.startsWith("/"),s}const Sx=".openchamber",nc="/api";function kx(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const wr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},oc=(s,r)=>{const t=wr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Hu=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",Nx=async s=>{try{await ke.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function Cx(s,r){const t=wr(s),n=oc(t,Sx);return await Nx(n),oc(n,r)}async function Uu(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,i=wr(r),l=await Cx(i,t),d={path:l,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await ux(i,d),{path:l,branch:n,label:Hu(n),projectDirectory:i,relativePath:l.startsWith(`${i}/`)?l.slice(i.length+1):l}}async function Mx(s){const{projectDirectory:r,path:t,force:n}=s,o=wr(r);await _u(o,{path:t,force:n})}async function Vu(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:i}=s,l=wr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await _u(l,{path:t,force:o}),d&&(await lx(l,{branch:d,force:!0}),a))try{await cx(l,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Sn(s){const r=wr(s);return dx(r)}async function ol(s){const r=wr(s),t=await ix(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function kn(s,r){const t=wr(s),n=wr(r.worktree);return{path:n,branch:r.branch??"",label:Hu(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}async function Gu(s,r,t){const n=t??await oo(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>jx(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:s,projectDirectory:r,commands:o});try{const a=kx();if(a?.execCommands){console.log("[worktreeService] Using runtime API for exec");try{const d=await a.execCommands(o,s);return console.log("[worktreeService] Runtime exec result:",d),d}catch(d){return console.error("[worktreeService] Runtime exec error:",d),{success:!1,results:o.map(u=>({command:u,success:!1,error:d instanceof Error?d.message:"Unknown error"}))}}}console.log("[worktreeService] Using web API for exec");const i=await fetch(`${nc}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:s,background:!0})}),l=await i.json().catch(()=>null);if(i.status===202&&l&&typeof l.jobId=="string"){const d=l.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(h=>setTimeout(h,u));const p=await fetch(`${nc}/fs/exec/${d}`,{method:"GET"}),g=await p.json().catch(()=>null);if(!p.ok)return{success:!1,results:o.map(h=>({command:h,success:!1,error:g&&g.error||"Failed to poll exec job"}))};if(g?.status==="done"){const h=Array.isArray(g?.results)?g.results:[];return{success:g?.success===!0,results:h}}}return{success:!1,results:o.map(p=>({command:p,success:!1,error:"Setup commands timed out"}))}}if(!i.ok){const d=l&&l.error||"Request failed";return console.error("[worktreeService] Web exec failed:",l),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",l),l}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(i=>({command:i,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const qu=ds(),Ku="oc.sessionSelectionByDirectory",Fa=".openchamber",Dx=()=>{try{const s=qu.getItem(Ku);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 _o=null;const al=()=>(_o||(_o=Dx()),_o),Yu=s=>{_o=s;try{qu.setItem(Ku,JSON.stringify(s))}catch{}},Qu=s=>{if(!s)return null;const t=al()[s];return typeof t=="string"?t:null},cr=(s,r)=>{if(!s)return;const t={...al()};r?t[s]=r:delete t[s],Yu(t)},Ax=(s,r)=>{if(!s)return;const t=Qu(s);if(!t)return;if(!new Set(r).has(t)){const o={...al()};delete o[s],Yu(o)}},ac=async(s,r)=>{const t=s.status??await ol(s.path).catch(()=>{});await Vu({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},yt=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},ic=()=>{if(typeof window>"u")return null;const s=window.__VSCODE_CONFIG__,r=typeof s?.workspaceFolder=="string"?s.workspaceFolder:null;return yt(r)},Ex=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,mo=(...s)=>{Qt()&&Ex()&&console.log("[OpenChamber][VSCode][sessions]",...s)},Sr=s=>{const r=new Map;return s.forEach(t=>{if(!t||typeof t.id!="string"||t.id.length===0)return;const n=r.get(t.id);if(!n){r.set(t.id,t);return}const o=n.time?.updated??0;(t.time?.updated??0)>o&&r.set(t.id,t)}),Array.from(r.values())},_s=s=>{const r=new Map;s.forEach(t=>{const n=yt(t.directory??null);if(!n)return;const o=r.get(n);o?o.push(t):r.set(n,[t])});for(const[t,n]of r.entries())r.set(t,Sr(n));return r},cn=(s,r)=>{const t=s.find(n=>n.id===r);return t?yt(t.directory??null):null},Ix=async(s,r,t)=>{const n=yt(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:yt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Sn(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=kn(n,u),f=yt(m.path)??m.path;f!==n&&i.set(f,m)});let l=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=i.get(m);if(!f){d.delete(u)&&(l=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),l=!0)}),l?d:null},lt=zt()(Kt(As((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,loadSessions:async()=>{s({isLoading:!0,error:null});try{const t=dt.getState(),n=Ft.getState(),o=ke.getApiClient(),a=ic(),i=!!a;mo("loadSessions:start",{workspace:a,currentDirectory:t.currentDirectory,clientDirectory:ke.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const l=new Map,d=async O=>{const J=yt(O)??O,K=J,L=l.get(K);if(L)return L;try{const G=await o.path.get({directory:O}),H=yt(G.data?.directory??null)??J;return l.set(K,H),H}catch{return l.set(K,J),J}},u=(O,J,K)=>{const L=yt(J);if(!L)return O;const B=K?.includeDescendants===!0?`${L}/`:null,H=K?.includeMissingDirectory===!0;return O.filter(V=>{const oe=yt(V.directory??null);return oe?!!(oe===L||B&&oe.startsWith(B)):H})},m=(O,J,K)=>{const L=yt(J);if(!L)return O;const G=yt(K??null);if(!G||G===L)return O.map(V=>yt(V.directory??null)?V:{...V,directory:L});const B=G==="/"?"/":`${G}/`,H=L==="/"?"/":`${L}/`;return O.map(V=>{const oe=yt(V.directory??null);if(!oe)return{...V,directory:L};if(oe===G)return{...V,directory:L};if(B!=="/"&&oe.startsWith(B)){const se=oe.slice(B.length);return{...V,directory:`${H}${se}`}}return V})},f=async O=>{const J=yt(O);if(!J)try{const oe=await o.session.list(void 0);return Array.isArray(oe.data)?oe.data:[]}catch(oe){throw console.debug("Failed to list sessions (global):",oe),oe}const K=await d(J),L=async()=>{const oe=await o.session.list({directory:J});return Array.isArray(oe.data)?oe.data:[]};let G=[],B=null,H=!1;try{G=await L()}catch(oe){console.debug("Failed to list sessions for directory:",J,oe),B=oe,G=[]}if(G.length===0){H=!0;try{const oe=await o.session.list(void 0),se=Array.isArray(oe.data)?oe.data:[];G=u(se,K,{includeDescendants:i,includeMissingDirectory:!1})}catch(oe){throw console.debug("Failed to list sessions (global fallback):",oe),B||oe}}const V=u(G,K,{includeDescendants:i,includeMissingDirectory:!H});return mo("fetchSessionsForDirectory",{requestedDirectory:J,canonicalDirectory:K,fetched:G.length,filtered:V.length}),m(V,J,K)},p=yt(t.currentDirectory??ke.getDirectory()??null),g=n.projects.find(O=>O.id===n.activeProjectId)??null,b=yt(g?.path??null),h=b??p??null,j=n.projects.length>0?n.projects:h?[{id:"legacy",path:h}]:[];if(j.length===0){s({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const y=await Promise.all(j.map(async O=>{const J=yt(O.path);if(!J)return{projectId:O.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const K=await sn(J).catch(()=>!1),L=await f(J||null);mo("projectSessions",{projectId:O.id,projectPath:J,isGitRepo:K,parentSessions:L.length});const G=[];let B=[];const H=new Set;if(H.add(J),K){const oe=`${J}/${Fa}`;try{const se=new Set;(await ke.listLocalDirectory(J)).some(W=>W.isDirectory&&W.name===Fa)&&(await ke.listLocalDirectory(oe)).filter(F=>F.isDirectory).forEach(F=>{const z=/^([A-Za-z]:)?\//.test(F.path)?F.path:`${oe}/${F.name}`,X=yt(z)??z;se.add(X)});const I=await Sn(J);Array.isArray(I)&&(B=I.map(W=>kn(J,W)).filter(W=>W.path.includes(`/${Fa}/`)),B.forEach(W=>se.add(W.path))),se.forEach(W=>{const F=yt(W)??W;H.add(F)}),se.size>0&&(await Promise.allSettled(Array.from(se).map(F=>f(F)))).forEach(F=>{F.status==="fulfilled"&&Array.isArray(F.value)&&G.push(...F.value)})}catch{B=[]}}const V=Sr([...L,...G]);return{projectId:O.id,projectPath:J,sessions:V,discoveredWorktrees:B,validPaths:H}})),x=new Map;y.forEach(O=>{O.projectPath&&O.validPaths.forEach(J=>{const K=yt(J)??J,L=O.sessions.filter(G=>(yt(G.directory??null)??K)===K);x.set(K,Sr(L))})});const v=Sr(Array.from(x.values()).flat()),N=r();let w=N.worktreeMetadata;for(const O of y)if(O.projectPath)try{const J=await Ix(O.sessions,O.projectPath,w);J&&(w=J)}catch(J){console.debug("Failed to refresh worktree metadata during session load:",J)}const k=new Map;y.forEach(O=>{O.projectPath&&k.set(O.projectPath,O.discoveredWorktrees)});const D=new Set;y.forEach(O=>{O.validPaths.forEach(J=>{const K=yt(J)??J;K&&D.add(K)})});const M=p??b??null,C=M&&D.has(M)?M:b??M,S=C?x.get(C)??[]:v,A=new Set(v.map(O=>O.id));for(const[O,J]of x.entries())Ax(O,J.map(K=>K.id));const E=(C??null)!==(N.lastLoadedDirectory??null);let R=N.currentSessionId;if((!R||!A.has(R)||E)&&(R=S[0]?.id??v[0]?.id??null),C){const O=Qu(C);O&&A.has(O)&&(R=O)}const _=(()=>{if(!R)return C??null;const O=w.get(R)?.path;if(O)return yt(O)??O;const J=cn(v,R);return J||(C??null)})();try{ke.setDirectory(_??void 0)}catch(O){console.warn("Failed to sync OpenCode directory after session load:",O)}const P=b?y.find(O=>O.projectPath===b)?.discoveredWorktrees??[]:[];s({sessions:v,sessionsByDirectory:x,currentSessionId:R,lastLoadedDirectory:C??null,isLoading:!1,worktreeMetadata:w,availableWorktrees:P,availableWorktreesByProject:k}),C&&cr(C,R),_&&_!==C&&cr(_,R)}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=dt.getState(),i=yt(a.currentDirectory),l=ic(),d=l??yt(n??ke.getDirectory()??i);mo("createSession:start",{title:t,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:l});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(h=>h.id)),p={id:u,title:t||"New session",parentID:o??void 0,directory:d??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(s(h=>{const j=[p,...h.sessions],y=new Map(h.sessionsByDirectory);if(d){const x=y.get(d)??[];y.set(d,Sr([p,...x]))}return{sessions:j,sessionsByDirectory:y,currentSessionId:u,webUICreatedSessions:new Set([...h.webUICreatedSessions,u]),isLoading:!1}}),d)try{ke.setDirectory(d)}catch(h){console.warn("Failed to sync OpenCode directory after session creation:",h)}const g=h=>{const j=d??null,y=j?{...h,directory:j}:h;s(x=>{const v=x.sessions.map(w=>w.id===u?y:w),N=new Map(x.sessionsByDirectory);if(d){const k=(N.get(d)??[]).map(D=>D.id===u?y:D);N.set(d,Sr(k))}return{sessions:v,sessionsByDirectory:_s(v),currentSessionId:y.id,webUICreatedSessions:new Set([...Array.from(x.webUICreatedSessions).filter(w=>w!==u),y.id])}}),cr(d??null,y.id)},b=async()=>{const h=ke.getApiClient(),j=20;for(let y=0;y<j;y+=1){try{const x=await h.session.list(d?{directory:d}:void 0),N=(Array.isArray(x.data)?x.data:[]).find(w=>!(f.has(w.id)||t&&w.title&&w.title!==t));if(N)return N}catch(x){console.debug("Session poll attempt failed:",x)}await new Promise(x=>setTimeout(x,2e3))}return null};try{const h=()=>ke.createSession({title:t,parentID:o??void 0});let j=null;try{j=d?await ke.withDirectory(d,h):await h()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return j||(j=await b()),j?(g(j),j):(s(y=>({sessions:y.sessions.filter(x=>x.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(x=>x!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(h){return s(j=>({sessions:j.sessions.filter(y=>y.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(j.webUICreatedSessions).filter(y=>y!==u)),isLoading:!1,error:h instanceof Error?h.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{s({isLoading:!0,error:null});const o=r().worktreeMetadata.get(t),a=cn(r().sessions,t),i=o?.path??a;let l=null;try{o&&n?.archiveWorktree&&(await ac(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),l=o);const d=()=>ke.deleteSession(t);if(!(i?await ke.withDirectory(i,d):await d()))return s(p=>{const g={isLoading:!1,error:"Failed to delete session"};if(l){const b=new Map(p.worktreeMetadata);b.delete(t),g.worktreeMetadata=b}return g}),!1;let m=null;s(p=>{const g=p.sessions.filter(y=>y.id!==t);m=p.currentSessionId===t?null:p.currentSessionId;const b=new Map(p.worktreeMetadata);b.delete(t);const h=n?.archiveWorktree&&o?p.availableWorktrees.filter(y=>yt(y.path)!==yt(o.path)):p.availableWorktrees,j=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const y=yt(o.projectDirectory)??o.projectDirectory,x=j.get(y)??[];j.set(y,x.filter(v=>yt(v.path)!==yt(o.path)))}return{sessions:g,sessionsByDirectory:_s(g),currentSessionId:m,isLoading:!1,worktreeMetadata:b,availableWorktrees:h,availableWorktreesByProject:j}});const f=i??ke.getDirectory()??null;return cr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return s(l?m=>{const f=new Map(m.worktreeMetadata);return f.delete(t),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(j=>typeof j=="string"&&j.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||s({isLoading:!0,error:null});const i=[],l=[],d=new Set,u=[],m=new Set;for(const j of o)try{const y=r().worktreeMetadata.get(j),x=cn(r().sessions,j),v=y?.path??x;y&&n?.archiveWorktree&&!m.has(y.path)&&(await ac(y,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(j),u.push({path:y.path,projectDirectory:y.projectDirectory}),m.add(y.path));const N=()=>ke.deleteSession(j);(v?await ke.withDirectory(v,N):await N())?(i.push(j),y?.path&&!u.some(k=>k.path===y.path)&&u.push({path:y.path,projectDirectory:y.projectDirectory})):l.push(j)}catch{l.push(j)}const f=dt.getState();u.forEach(({path:j,projectDirectory:y})=>{f.currentDirectory===j&&f.setDirectory(y,{showOverlay:!1})});const p=new Set(i),g=l.length>0?l.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let b=null;s(j=>{const y=j.sessions.filter(k=>!p.has(k.id));j.currentSessionId&&p.has(j.currentSessionId)?b=null:b=j.currentSessionId;const x=new Map(j.worktreeMetadata);for(const k of p)x.delete(k);for(const k of d)x.delete(k);const v=new Set(u.map(k=>yt(k.path)).filter(k=>!!k)),N=v.size>0?j.availableWorktrees.filter(k=>!v.has(yt(k.path)??k.path)):j.availableWorktrees,w=new Map(j.availableWorktreesByProject);return u.length>0&&u.reduce((D,M)=>{const C=yt(M.projectDirectory)??M.projectDirectory,S=yt(M.path)??M.path;return D.has(C)||D.set(C,new Set),D.get(C)?.add(S),D},new Map).forEach((D,M)=>{const S=(w.get(M)??[]).filter(A=>!D.has(yt(A.path)??A.path));w.set(M,S)}),{sessions:y,sessionsByDirectory:_s(y),currentSessionId:b,...a?{}:{isLoading:!1,error:g},worktreeMetadata:x,availableWorktrees:N,availableWorktreesByProject:w}});const h=ke.getDirectory()??null;return cr(h,b),{deletedIds:i,failedIds:l}},updateSessionTitle:async(t,n)=>{try{const o=cn(r().sessions,t),a=r().worktreeMetadata.get(t),i=()=>ke.updateSession(t,n),l=a?.path??o,d=l?await ke.withDirectory(l,i):await i();s(u=>{const m=u.sessions.map(f=>f.id===t?d:f);return{sessions:m,sessionsByDirectory:_s(m)}})}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=cn(r().sessions,t),o=ke.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??ke.getDirectory();return o.session.share({sessionID:t,...u?{directory:u}:{}})},d=i?await ke.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:_s(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=cn(r().sessions,t),o=ke.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??ke.getDirectory();return o.session.unshare({sessionID:t,...u?{directory:u}:{}})},d=i?await ke.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:_s(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{s({currentSessionId:t,error:null});const n=ke.getDirectory()??null;cr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:t=>{const n=yt(t)??t,{sessionsByDirectory:o,sessions:a}=r(),i=o.get(n);return i||a.filter(l=>(yt(l.directory??null)??n)===n)},getDirectoryForSession:t=>{if(!t)return null;const n=r().worktreeMetadata.get(t);if(n?.path)return yt(n.path)??n.path;const o=r().sessions.find(i=>i.id===t);return yt(o?.directory??null)},applySessionMetadata:(t,n)=>{!t||!n||s(o=>{const a=o.sessions.findIndex(g=>g.id===t);if(a===-1)return o;const i=o.sessions[a],l=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,m={...i,...n,time:l,summary:d,share:u},f=m.title!==i.title||m.parentID!==i.parentID||m.directory!==i.directory||m.version!==i.version||m.projectID!==i.projectID||JSON.stringify(m.time)!==JSON.stringify(i.time)||JSON.stringify(m.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(i.share??null),p=[...o.sessions];return p[a]=f?m:i,{sessions:p,sessionsByDirectory:_s(p)}})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=r();return n.has(t)},markSessionAsOpenChamberCreated:t=>{s(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=r();n(t)},setWorktreeMetadata:(t,n)=>{t&&s(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return r().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=r().sessions,a=o.findIndex(u=>u.id===t);if(a===-1)return;const l=o[a].directory??null,d=n??void 0;l!==(d??null)&&(s(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:_s(m)}}),l&&cr(l,null),n&&cr(n,t))},updateSession:t=>{s(n=>{const a=n.sessions.findIndex(l=>l.id===t.id)===-1?[t,...n.sessions]:n.sessions.map(l=>l.id===t.id?t:l),i=Sr(a);return{sessions:i,sessionsByDirectory:_s(i)}})},removeSessionFromStore:t=>{t&&s(n=>{const o=n.sessions.find(u=>u.id===t),a=yt(o?.directory??null),i=n.sessions.filter(u=>u.id!==t);if(i.length===n.sessions.length)return n;const l=new Map(n.worktreeMetadata);l.delete(t);const d=n.currentSessionId===t?null:n.currentSessionId;return a&&cr(a,null),{sessions:i,sessionsByDirectory:_s(i),currentSessionId:d,worktreeMetadata:l}})}}),{name:"session-store",storage:Es(()=>ds()),partialize:s=>({currentSessionId:s.currentSessionId,sessions:s.sessions,lastLoadedDirectory:s.lastLoadedDirectory,webUICreatedSessions:Array.from(s.webUICreatedSessions),worktreeMetadata:Array.from(s.worktreeMetadata.entries()),availableWorktrees:s.availableWorktrees,availableWorktreesByProject:Array.from(s.availableWorktreesByProject.entries())}),merge:(s,r)=>{if(!(p=>typeof p=="object"&&p!==null)(s))return r;const n=Array.isArray(s.sessions)?s.sessions:r.sessions,o=typeof s.currentSessionId=="string"||s.currentSessionId===null?s.currentSessionId:r.currentSessionId,a=Array.isArray(s.webUICreatedSessions)?s.webUICreatedSessions:[],i=Array.isArray(s.worktreeMetadata)?s.worktreeMetadata:[],l=Array.isArray(s.availableWorktrees)?s.availableWorktrees:r.availableWorktrees,d=Array.isArray(s.availableWorktreesByProject)?s.availableWorktreesByProject:[],u=new Map(d),m=typeof s.lastLoadedDirectory=="string"?s.lastLoadedDirectory:r.lastLoadedDirectory??null,f=Sr(n);return{...r,...s,sessions:f,sessionsByDirectory:_s(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:l,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),Xu="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.",Px="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: ",Ra=s=>typeof s=="string"&&s.trim()===Xu.trim(),_a=(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},Fn=(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},lc=new Map,Ju=s=>{const r=lc.get(s);r&&(clearTimeout(r),lc.delete(s))},Or=s=>{for(const r of s)Ju(r)},Zn=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>Zn(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>Zn(r)).join("")}return""},Vn=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:Vn(n)).join("");const t=Zn(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||Zn(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=Zn(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},cc=10*1024*1024,Tx=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"}},Fx=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"}},Rx=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},_x=s=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<s.length;n+=3){const o=s[n]??0,a=s[n+1],i=s[n+2],l=o<<16|(a??0)<<8|(i??0);t+=r[l>>18&63],t+=r[l>>12&63],t+=typeof a=="number"?r[l>>6&63]:"=",t+=typeof i=="number"?r[l&63]:"="}return t},er=zt()(Kt(As((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(b=>b.filename===t.name&&b.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=cc;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 10MB.`);const i=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],l=Fx(t);!i.some(b=>l.startsWith(b)||l===b||l==="")&&l!==""&&console.warn(`File type "${l}" might not be supported`);const u=new FileReader,m=await new Promise((b,h)=>{u.onload=()=>b(u.result),u.onerror=h,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${l}`):m,p=b=>{const h=b.replace(/\\/g,"/").split("/");return h[h.length-1]||b},g={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:f,mimeType:l,filename:p(t.name),size:t.size,source:"local"};s(b=>({attachedFiles:[...b.attachedFiles,g]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=r();if(a.some(y=>y.serverPath===t&&y.source==="server")){console.log(`Server file "${n}" is already attached`);return}let l=o,d,u;if(!l)try{const y=ke.getApiClient(),x=t.lastIndexOf("/"),v=x>0?t.substring(0,x):"/",N=x>0?t.substring(x+1):t,w=await y.file.read({path:N,directory:v});w.data&&"content"in w.data?(l=w.data.content,d=w.data.encoding??void 0,u=w.data.mimeType??void 0):l=""}catch(y){console.error("Failed to read server file:",y),l=`[File: ${n}]`}const m=u||Tx(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return l||"";const x=new TextEncoder().encode(l||"");return _x(x)})(),g=d==="base64"?Rx(p):new TextEncoder().encode(l||"").length;if(g>cc)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const b=new File([],n,{type:f}),h=`data:${f};base64,${p}`,j={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:b,dataUrl:h,mimeType:f,filename:n,size:g,source:"server",serverPath:t};s(y=>({attachedFiles:[...y.attachedFiles,j]}))},removeAttachedFile:t=>{s(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{s({attachedFiles:[]})}}),{name:"file-store",storage:Es(()=>ds()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),Ox=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),$x=s=>s?Ox.has(s.toLowerCase()):!1,Lx=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Bx=s=>{if(s)try{const r=Lx();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},zx=(s,r)=>{if(!s||s.length===0)return"ask";for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission===r&&n.pattern==="*")return n.action}for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},Oo=s=>{const r=Bx(s);return r?zx(r.permission,"edit"):"ask"},dc=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},Oa=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return dc(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:dc(t.tokens)},$a=(s,r,t)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),l=Math.min(i,n),d=n>0?Math.max(n-l,1):0,u=d>0?s/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:l}},_n=["ask","allow","full"],bt=zt()(Kt(As((s,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{s(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=r();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{s(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=r();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{s(i=>{const l=new Map(i.sessionAgentModelSelections);let d=l.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),l.set(t,d),{sessionAgentModelSelections:l}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(t);return a&&a.get(n)||null},saveAgentModelVariantForSession:(t,n,o,a,i)=>{s(l=>{const d=new Map(l.sessionAgentModelVariantSelections);let u=d.get(t);u?u=new Map(u):u=new Map;let m=u.get(n);m?m=new Map(m):m=new Map;const f=`${o}/${a}`;return i===void 0?(m.delete(f),m.size===0?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,m),d.set(t,u))):(m.set(f,i),u.set(n,m),d.set(t,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(t,n,o,a)=>{const{sessionAgentModelVariantSelections:i}=r(),l=i.get(t);if(!l)return;const d=l.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:i}=r(),l=new Map,d=(p,g)=>{if("mode"in p&&p.mode&&typeof p.mode=="string"&&n.find(y=>y.name===p.mode))return p.mode;if(p.providerID&&p.modelID){const j=n.find(y=>y.model?.providerID===p.providerID&&y.model?.modelID===p.modelID);if(j)return j.name}const{currentAgentContext:b}=r(),h=b.get(t);if(h&&n.find(j=>j.name===h))return h;if(g>0&&p.providerID&&p.modelID){const y=(o.get(t)||[]).filter(x=>x.info.role==="assistant").sort((x,v)=>x.info.time.created-v.info.time.created);for(let x=g-1;x>=0;x--){const N=y[x].info;if(N.providerID===p.providerID&&N.modelID===p.modelID){if(N.mode&&typeof N.mode=="string"&&n.find(D=>D.name===N.mode))return N.mode;const w=n.find(k=>k.model?.providerID===N.providerID&&k.model?.modelID===N.modelID);if(w)return w.name}}}return p.providerID&&p.modelID&&n.find(y=>y.name==="build")?"build":null},u=o.get(t)||[],m=u.filter(p=>p.info.role==="assistant"||p.info.role==="user").sort((p,g)=>p.info.time.created-g.info.time.created),f=u.filter(p=>p.info.role==="assistant").sort((p,g)=>p.info.time.created-g.info.time.created);for(let p=0;p<m.length;p++){const g=m[p],{info:b}=g,h=b;if(h.providerID&&h.modelID){const j=d(h,f.indexOf(g));if(j&&n.find(y=>y.name===j)){const y=typeof h.variant=="string"&&h.variant.trim().length>0?h.variant:void 0;y&&i(t,j,h.providerID,h.modelID,y);const x={providerId:h.providerID,modelId:h.modelID,timestamp:b.time.created},v=l.get(j);(!v||x.timestamp>v.timestamp)&&l.set(j,x)}}}for(const[p,g]of l)a(t,p,g.providerId,g.modelId);return l},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=$a(0,n,o),l=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(l===0||u===0)return null;const f=(a.get(t)||[]).filter(v=>v.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],g=p.info.id,b=v=>{const N=()=>{s(w=>{const k=w.sessionContextUsage.get(t);if(k&&k.totalTokens===v.totalTokens&&k.percentage===v.percentage&&k.contextLimit===v.contextLimit&&(k.outputLimit??0)===(v.outputLimit??0)&&(k.normalizedOutput??0)===(v.normalizedOutput??0)&&k.thresholdLimit===v.thresholdLimit&&k.lastMessageId===v.lastMessageId)return w;const D=new Map(w.sessionContextUsage);return D.set(t,v),{sessionContextUsage:D}})};typeof queueMicrotask=="function"?queueMicrotask(N):typeof window<"u"?window.setTimeout(N,0):setTimeout(N,0)},h=r().sessionContextUsage.get(t);if(h&&h.lastMessageId===g){const v=h.normalizedOutput??h.outputLimit??0,N=h.contextLimit!==l||v!==d||h.thresholdLimit!==u;if(N&&h.totalTokens>0){const w=h.totalTokens/u*100,k={totalTokens:h.totalTokens,percentage:Math.min(w,100),contextLimit:l,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:g};return b(k),k}if(!N&&h.totalTokens>0)return h}const j=Oa(p);if(j===0)return h||null;const y=$a(j,n,o),x={totalTokens:j,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit,normalizedOutput:y.normalizedOutput,thresholdLimit:y.thresholdLimit,lastMessageId:g};return b(x),x},updateSessionContextUsage:(t,n,o,a)=>{const l=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(l.length===0)return;const d=l[l.length-1],u=Oa(d);if(u===0)return;const m=$a(u,n,o);s(f=>{const p=new Map(f.sessionContextUsage);return p.set(t,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(t,n,o,a)=>{const l=r().sessionContextUsage.get(t);(!l||l.totalTokens===0)&&r().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const l=()=>{i++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&Oa(u)>0){r().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(l,1e3)};setTimeout(l,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=Oo(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Oo(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||_n.includes(o)&&s(l=>{const d=new Map(l.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Oo(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=r().getSessionAgentEditMode(t,n,a),l=_n.indexOf(i),d=_n.indexOf(a),m=((l>=0?l:d>=0?d:0)+1)%_n.length,f=_n[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:Es(()=>ds()),partialize:s=>({sessionModelSelections:Array.from(s.sessionModelSelections.entries()),sessionAgentSelections:Array.from(s.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(s.sessionAgentModelSelections.entries()).map(([r,t])=>[r,Array.from(t.entries())]),sessionAgentModelVariantSelections:Array.from(s.sessionAgentModelVariantSelections.entries()).map(([r,t])=>[r,Array.from(t.entries()).map(([n,o])=>[n,Array.from(o.entries())])]),currentAgentContext:Array.from(s.currentAgentContext.entries()),sessionContextUsage:Array.from(s.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(s.sessionAgentEditModes.entries()).map(([r,t])=>[r,Array.from(t.entries())])}),merge:(s,r)=>{const t=new Map;s?.sessionAgentModelSelections&&s.sessionAgentModelSelections.forEach(([a,i])=>{t.set(a,new Map(i))});const n=new Map;s?.sessionAgentModelVariantSelections&&s.sessionAgentModelVariantSelections.forEach(([a,i])=>{const l=new Map;i.forEach(([d,u])=>{l.set(d,new Map(u))}),n.set(a,l)});const o=new Map;return s?.sessionAgentEditModes&&s.sessionAgentEditModes.forEach(([a,i])=>{o.set(a,new Map(i))}),{...r,...s,sessionModelSelections:new Map(s?.sessionModelSelections||[]),sessionAgentSelections:new Map(s?.sessionAgentSelections||[]),sessionAgentModelSelections:t,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(s?.currentAgentContext||[]),sessionContextUsage:new Map(s?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),uc=(s,r)=>{const t=new Map(s);return t.delete(r),t};let La=[],Ba=null;const Wx=50,Hx=3e4,$r=new Map,fo=new Map,dn=new Map,Ux=10,Qo=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<Ux?null:n},po=(s,r)=>{const t=Qo(s),n=Qo(r);return!t||!n||t.length!==n.length?!0:t>n},Vx=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},hn=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),Xo=s=>s?.finish==="stop",mc=s=>{if(s){if(typeof s.id=="string"&&s.id.length>0)return s.id;if(s.type){const r=s.reason,t=s.callID;return`${s.type}-${r??""}-${t??""}`}}},fc=new Set,Jo=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(mc).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=mc(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},Gx=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=hn(t),a=hn(n),i=Xo(s.info),l=Xo(r.info);let d=n;return i&&o>=a?d=Jo(t,n):l&&a>=o?d=Jo(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},za=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]=Gx(r[a],n)}return r},qx=(s,r)=>{let t=r,n=r?Qo(r):null;for(const o of s){const a=o?.info?.id,i=Qo(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Ys=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return t?o.set(r,t):o.delete(r),o},un=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},ho=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},Kx=(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},pc=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),Yx=async s=>{if(s)try{return lt.getState().getDirectoryForSession(s)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},hc=s=>{if(!s)return null;try{return lt.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},gc=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},Wa=async(s,r)=>{const t=await Yx(s);return t?ke.withDirectory(t,r):r()},pt=zt()(Kt(As((s,r)=>({messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,pendingAssistantHeaderSessions:new Set,pendingUserMessageMetaBySession:new Map,loadMessages:async(t,n=us.VIEWPORT_MESSAGES)=>{const o=await Wa(t,()=>ke.getSessionMessages(t)),a=hc(t),i=gc(o,a),l=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(l?i.filter(m=>{const f=m?.info?.id;return f?po(f,l):!0}):i).slice(-n);s(m=>{const f=new Map(m.messages),p=m.messages.get(t)||[],g=new Map(p.filter(C=>typeof C.info?.id=="string").map(C=>[C.info.id,C])),b=u.map(C=>{const S={...C.info,clientRole:C.info?.clientRole??C.info.role,userMessageMarker:C.info.role==="user"?!0:C.info?.userMessageMarker},A=(Array.isArray(C.parts)?C.parts:[]).map(R=>{if(R?.type==="text"){const _=R.text??R.content??"";if(Ra(_))return{...R,synthetic:!0}}return R}),E=S?.id?g.get(S.id):void 0;if(E&&E.info.role==="assistant"){const R=Array.isArray(E.parts)?E.parts:[],_=hn(R),P=hn(A);if(Xo(E.info)&&_>P){const J=Jo(R,A);return{...C,info:S,parts:J}}}return{...C,info:S,parts:A}}),h=za(b),j=new Set(p.map(C=>C.info.id)),y=new Set(h.map(C=>C.info.id)),x=[];j.forEach(C=>{y.has(C)||x.push(C)}),f.set(t,h);const v=new Map(m.sessionMemoryState),N=m.sessionMemoryState.get(t);v.set(t,{...N,viewportAnchor:h.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:N?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const w={messages:f,sessionMemoryState:v};Or(x);const k=Fn(m.messageStreamStates,x);if(k!==m.messageStreamStates&&(w.messageStreamStates=k),x.length>0){const C=m.streamingMessageIds.get(t);C&&x.includes(C)&&(w.streamingMessageIds=Ys(w.streamingMessageIds??m.streamingMessageIds,t,null))}if(x.length>0){const C=ho(w.messageSessionIndex??m.messageSessionIndex,x);C!==(w.messageSessionIndex??m.messageSessionIndex)&&(w.messageSessionIndex=C)}if(x.length>0){const C=new Map(m.pendingAssistantParts);let S=!1;x.forEach(A=>{C.delete(A)&&(S=!0)}),S&&(w.pendingAssistantParts=C)}const D=w.messageSessionIndex??m.messageSessionIndex;let M=D;return h.forEach(C=>{const S=C?.info?.id;typeof S=="string"&&S.length>0&&(M=un(M,S,t))}),M!==D&&(w.messageSessionIndex=M),w})},sendMessage:async(t,n,o,a,i,l,d,u,m)=>{if(!i)throw new Error("No session selected");const f=i;r().sessionAbortFlags.has(f)&&s(p=>{const g=new Map(p.sessionAbortFlags);return g.delete(f),{sessionAbortFlags:g}}),await Wa(f,async()=>{try{let p=t;if(t.startsWith("/")){const b=t.indexOf(" "),h=b===-1?t.substring(1):t.substring(1,b),j=b===-1?"":t.substring(b+1).trim(),y=ke.getApiClient(),x=ke.getDirectory();if(h==="init"){const v=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({sessionID:f,...x?{directory:x}:{},messageID:v,providerID:n,modelID:o});return}if(h==="summarize"){await y.session.summarize({sessionID:f,...x?{directory:x}:{},providerID:n,modelID:o});return}try{const v=await ke.getCommandDetails(h);v?.template?p=v.template.replace(/\$ARGUMENTS/g,j):p=t}catch(v){console.error("Command template resolution failed:",v),p=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(b=>{const h=b.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},j=dn.get(f);j&&(clearTimeout(j),dn.delete(f));const y=new Map(b.sessionMemoryState);return y.set(f,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:y}});try{const b=new AbortController;s(y=>{const x=new Map(y.abortControllers);return x.set(f,b),{abortControllers:x}});const h=(l??[]).map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}));s(y=>{const x=new Set(y.pendingAssistantHeaderSessions);x.add(f);const v=new Map(y.pendingUserMessageMetaBySession);return v.set(f,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o,variant:typeof m=="string"&&m.trim().length>0?m:void 0}),{pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}});const j=u?.map(y=>({text:y.text,files:y.attachments?.map(x=>({type:"file",mime:x.mimeType,filename:x.filename,url:x.dataUrl}))}));if(await ke.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:h.length>0?h:void 0,additionalParts:j,agentMentions:d?[{name:d}]:void 0}),h.length>0)try{er.getState().clearAttachedFiles()}catch(y){console.error("Failed to clear attached files after send",y)}s(y=>{const x=new Map(y.abortControllers);return x.delete(f),{abortControllers:x}})}catch(b){let h="Network error while sending message. The message may still be processing.";if(b.name==="AbortError")h="Request timed out. The message may still be processing.";else if(b.message?.includes("504")||b.message?.includes("Gateway")){h="Gateway timeout - your message is being processed. Please wait for response.",s(j=>{const y=new Map(j.abortControllers);return y.delete(f),{abortControllers:y}});return}else b.message&&(h=b.message);throw s(j=>{const y=new Map(j.abortControllers);y.delete(f);const x=new Set(j.pendingAssistantHeaderSessions);x.delete(f);const v=new Map(j.pendingUserMessageMetaBySession);return v.delete(f),{abortControllers:y,pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}}),new Error(h)}}catch(p){let g="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?g="Request timed out. The message may still be processing.":p.response?.status===401?g="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?g="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?g="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(g=p.message),s(b=>{const h=new Map(b.abortControllers);h.delete(f);const j=new Set(b.pendingAssistantHeaderSessions);j.delete(f);const y=new Map(b.pendingUserMessageMetaBySession);return y.delete(f),{abortControllers:h,pendingAssistantHeaderSessions:j,pendingUserMessageMetaBySession:y}}),new Error(g)}})},abortCurrentOperation:async t=>{if(!t)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const l=Kx(n,t);if(l.size===0){const u=t?a.get(t)??[]:[];let m=null;for(let f=u.length-1;f>=0;f-=1){const p=u[f];if(!p||p.info.role!=="assistant")continue;if(m||(m=p.info.id),(p.parts??[]).some(b=>b.type==="reasoning"||b.type==="tool"||b.type==="step-start")){l.add(p.info.id);break}}l.size===0&&m&&l.add(m)}for(const u of l){const m=$r.get(u);m&&(clearTimeout(m),$r.delete(u),fo.delete(u))}l.size>0&&Or(l);const d=Date.now();s(u=>{const m=Fn(u.messageStreamStates,l),f=u.messages.get(t)??[];let p=!1,g=u.messages;if(f.length>0&&l.size>0){const y=f.map(x=>{if(!l.has(x.info.id)&&l.size>0)return x;const v=(x.parts??[]).map(N=>{if(N.type==="reasoning"){const w=N,k={...w.time??{}};return typeof k.end!="number"&&(k.end=d),{...w,time:k}}if(N.type==="tool"){const w=N,k={...w.state??{}};return(k.status==="running"||k.status==="pending")&&(k.status="aborted"),{...w,state:k}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...x,info:{...x.info,abortedAt:d,streaming:!1,status:"aborted"},parts:v}});p&&(g=new Map(u.messages),g.set(t,y))}const b=u.sessionMemoryState.get(t);let h=u.sessionMemoryState;if(b){const y=new Map(u.sessionMemoryState);y.set(t,{...b,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),h=y}const j=new Map(u.sessionAbortFlags);return j.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:h,sessionAbortFlags:j,abortControllers:(()=>{const y=new Map(u.abortControllers);return y.delete(t),y})(),streamingMessageIds:Ys(u.streamingMessageIds,t,null),...p?{messages:g}:{}}}),ke.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const l=r();if(fc.has(n))return;const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!po(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=l.messages.get(t)||[],m=u.find(g=>g.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=r().sessionMemoryState.get(t);if(p?.streamStartTime&&Date.now()-p.streamStartTime>us.ZOMBIE_TIMEOUT){p.isZombie||s(b=>{const h=new Map(b.sessionMemoryState);return h.set(t,{...p,isZombie:!0}),{sessionMemoryState:h}}),setTimeout(()=>{r().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}s(g=>{const h=[...g.messages.get(t)||[]],j={},y=un(g.messageSessionIndex,n,t);y!==g.messageSessionIndex&&(j.messageSessionIndex=y);const x=C=>{if(!((f==="assistant"||f==="user")&&g.sessionAbortFlags.has(t)))return C;const A=new Map(g.sessionAbortFlags);return A.delete(t),{...C,sessionAbortFlags:A}},v=C=>{const S=C||"",A=fo.get(n);if(S&&A===S){const _=r();if(pc(_,t,n)){const P=$r.get(n);P&&(clearTimeout(P),$r.delete(n)),setTimeout(()=>{const O=r();typeof O.forceCompleteMessage=="function"&&O.forceCompleteMessage(t,n,"timeout"),O.completeStreamingMessage(t,n)},100)}}fo.set(n,S);const E=$r.get(n);E&&clearTimeout(E);const R=setTimeout(()=>{const _=r();typeof _.forceCompleteMessage=="function"&&_.forceCompleteMessage(t,n,"timeout"),pc(_,t,n)&&_.completeStreamingMessage(t,n),$r.delete(n),fo.delete(n)},8e3);$r.set(n,R)},N=t!==i,w=g.sessionMemoryState.get(t);if(N&&w?.isStreaming){h.length>=us.BACKGROUND_STREAMING_BUFFER&&h.shift();const C=new Map(g.sessionMemoryState);C.set(t,{...w,backgroundMessageCount:(w.backgroundMessageCount||0)+1}),g.sessionMemoryState=C}if(f==="assistant"){const C=g.sessionMemoryState.get(t);if(C){const S=Date.now(),A=new Map(g.sessionMemoryState);A.set(t,{...C,isStreaming:!0,streamStartTime:C.streamStartTime??S,lastAccessedAt:S,isZombie:!1}),g.sessionMemoryState=A}}const k=Vn(o);if(Ra(k)&&(o.synthetic=!0),Vx()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:k.length,snapshotParts:u.length})}catch{}const D=j.streamingMessageIds??g.streamingMessageIds;if(f==="assistant"){const C=Ys(D,t,n);C!==D&&(j.streamingMessageIds=C,window.__messageTracker?.(n,"streamingId_set_latest"))}const M=h.findIndex(C=>C.info.id===n);if(M!==-1&&f==="user"){const C=h[M],S=C.parts.findIndex(P=>P.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),g;const A=Rn(o,S!==-1?C.parts[S]:void 0);window.__messageTracker?.(n,`user_part_type:${A.type||"unknown"}`);const E={...C};S!==-1?E.parts=E.parts.map((P,O)=>O===S?A:P):E.parts=[...E.parts,A];const R=[...h];R[M]=E;const _=new Map(g.messages);return _.set(t,R),x({messages:_})}if(f==="assistant"&&M!==-1){const C=h[M],S=C.parts.findIndex(O=>O.id===o.id),A=Rn(o,S!==-1?C.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const E={...C};S!==-1?E.parts=E.parts.map((O,J)=>J===S?A:O):E.parts=[...E.parts,A];const R=[...h];R[M]=E;const _=new Map(g.messages);_.set(t,R),j.messageStreamStates=_a(g.messageStreamStates,n);const P=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);return P!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set")),A.type==="text"?v(A.text||""):v(""),x({messages:_,...j})}if(M===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),g;const Y=Rn(o);window.__messageTracker?.(n,`new_user_part_type:${Y.type||"unknown"}`);const le=g.pendingUserMessageMetaBySession.get(t),I=bt.getState(),W=le?.mode??I.getSessionAgentSelection(t)??I.getCurrentAgent(t),F=typeof W=="string"&&W.trim().length>0?W.trim():void 0,$=le?.providerID??(g.lastUsedProvider?.providerID||void 0),z=le?.modelID??(g.lastUsedProvider?.modelID||void 0);le&&(j.pendingUserMessageMetaBySession=uc(g.pendingUserMessageMetaBySession,t));const X={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...F?{mode:F}:{},...$?{providerID:$}:{},...z?{modelID:z}:{},time:{created:Date.now()}},parts:[Y]},fe=[...h,X];fe.sort((ge,Re)=>{const be=ge.info?.time?.created||0,Ie=Re.info?.time?.created||0;return be-Ie});const ve=new Map(g.messages);return ve.set(t,fe),x({messages:ve})}if(o?.type==="text"){const Y=Vn(o).trim();if(Y.length>0){const le=[...h].reverse().find(I=>I.info.role==="user");if(le){const I=le.parts.map(W=>Vn(W)).join("").trim();if(I.length>0&&I===Y)return fc.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),g}}}const C=Rn(o);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`),C.type==="text"?v(C.text||""):v("");const S=g.pendingAssistantParts.get(n),A=S?[...S.parts]:[],E=A.findIndex(Y=>Y.id===C.id);E!==-1?A[E]=C:A.push(C);const R=new Map(g.pendingAssistantParts);R.set(n,{sessionId:t,parts:A});const _=g.lastUsedProvider?.providerID||"",P=g.lastUsedProvider?.modelID||"",O=Date.now(),J=ke.getDirectory()??"/",K=bt.getState(),L=K.getSessionAgentSelection(t)??K.getCurrentAgent(t),G=typeof L=="string"&&L.trim().length>0?L.trim():void 0,B=g.pendingAssistantHeaderSessions.has(t);if(B){const Y=new Set(g.pendingAssistantHeaderSessions);Y.delete(t),j.pendingAssistantHeaderSessions=Y}const V={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:O},agent:G||"default",model:{providerID:_,modelID:P},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:O},parentID:n,modelID:P,providerID:_,mode:G||"default",...B?{openchamberHeaderAnchor:!0}:{},path:{cwd:J,root:J},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:A},oe=[...h,V],se=new Map(g.messages);if(se.set(t,oe),f==="assistant"){j.messageStreamStates=_a(g.messageStreamStates,n);const Y=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);Y!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=Y,window.__messageTracker?.(n,"streamingId_set"))}return x({messages:se,pendingAssistantParts:R,...j})}else{const C=h[M],S=C.parts.findIndex(P=>P.id===o.id),A=Rn(o,S!==-1?C.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const E={...C};S!==-1?E.parts=E.parts.map((P,O)=>O===S?A:P):E.parts=[...E.parts,A];const R=[...h];R[M]=E;const _=new Map(g.messages);if(_.set(t,R),E.info.role==="assistant"){j.messageStreamStates=_a(g.messageStreamStates,n);const P=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);P!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set"))}return A.type==="text"?v(A.text||""):v(""),x({messages:_,...j})}})},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,i);return}La.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),Ba||(Ba=setTimeout(()=>{const l=[...La];La=[],Ba=null;const d=r();for(const u of l)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Wx))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[l,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return l;return null};s(i=>{const l=a(i);if(!l)return i;const d=i.messages.get(l)??[],u=d.findIndex(w=>w.info.id===n);if(u===-1)return i;const m=d[u];if(!m)return i;const f=Date.now(),p=m.info,g=typeof p?.time?.completed=="number"&&p.time.completed>0;let b=!1;const h={...p};g||(h.time={...p.time??{},completed:f},b=!0),h.status!=="completed"&&(h.status="completed",b=!0),h.streaming&&(h.streaming=!1,b=!0);let j=!1;const y=m.parts.map(w=>{if(!w)return w;if(w.type==="tool"){const k=w.state;if(!k)return w;const D=k.status,M=D==="running"||D==="pending"||D==="started",C=!k.time||typeof k.time?.end!="number";if(M||C){const S={...k};return M&&(S.status="completed"),C&&(S.time={...k.time??{},end:f}),j=!0,{...w,state:S}}return w}if(w.type==="reasoning"){const k=w.time;return!k||typeof k.end!="number"?(j=!0,{...w,time:{...k??{},end:f}}):w}if(w.type==="text"){const k=w.time;return k&&typeof k.end!="number"?(j=!0,{...w,time:{...k,end:f}}):w}return w});if(!b&&!j)return i;window.__messageTracker?.(n,`force_complete:${o}`);const x={...m,info:h,parts:j?y:m.parts},v=[...d];v[u]=x;const N=new Map(i.messages);return N.set(l,v),{messages:N}})},markMessageStreamSettled:t=>{s(n=>{Ju(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,u)=>{if(i)return;const m=d.findIndex(h=>h.info.id===t);if(m===-1)return;const f=d[m];if(f.info?.animationSettled)return;const p={...f,info:{...f.info,animationSettled:!0}},g=[...d];g[m]=p;const b=new Map(n.messages);b.set(u,g),a=b,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),Or([t])},updateMessageInfo:(t,n,o)=>{s(l=>{const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!po(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),l;const m=[...l.messages.get(t)??[]],f=m.findIndex(M=>M.info.id===n),p=l.pendingAssistantParts.get(n),g=(M=[],C=[])=>{if(!C.length)return M;const S=[...M];return C.forEach(A=>{const E=S.findIndex(R=>R.id===A.id);E===-1?S.push(A):S[E]=A}),S},b=M=>{if(!M)return M;const C=M.clientRole??M.role,S=C==="user"?!0:M.userMessageMarker;return{...M,clientRole:C,...S?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:t,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const J=m[0]?.info,K=typeof J?.time?.created=="number"?J.time.created:null,L=typeof J?.id=="string"?J.id:null,G=o,B=typeof G?.time?.created=="number"?G.time.created:null,H=typeof G?.id=="string"?G.id:n;let V=!1;if(B!==null&&K!==null&&(V=B<K),!V&&H&&L&&(V=H.localeCompare(L)<0),V)return window.__messageTracker?.(n,"skipped_evicted_message_update"),l}const M=b(o);if(M&&M.role==="user"){const O=p?.parts??[],J=l.pendingUserMessageMetaBySession.get(t),K={info:{...M,userMessageMarker:!0,clientRole:"user",...J?.mode?{mode:J.mode}:{},...J?.providerID?{providerID:J.providerID}:{},...J?.modelID?{modelID:J.modelID}:{}},parts:O.length>0?[...O]:[]},L=new Map(l.messages),G=[...m,K];G.sort((V,oe)=>{const se=V.info?.time?.created||0,Y=oe.info?.time?.created||0;return se-Y}),L.set(t,G);const B={messages:L,...J?{pendingUserMessageMetaBySession:uc(l.pendingUserMessageMetaBySession,t)}:{}},H=un(B.messageSessionIndex??l.messageSessionIndex,n,t);if(H!==(B.messageSessionIndex??l.messageSessionIndex)&&(B.messageSessionIndex=H),p){const V=new Map(l.pendingAssistantParts);V.delete(n),B.pendingAssistantParts=V}return B}if(!M||M.role!=="assistant")return l;const C=p?.parts??[],S=l.pendingAssistantHeaderSessions.has(t),A={info:{...M,animationSettled:M?.animationSettled??!1,...S?{openchamberHeaderAnchor:!0}:{}},parts:C.length>0?[...C]:[]},E=new Map(l.messages),R=[...m,A];E.set(t,R);const _={messages:E,...S?{pendingAssistantHeaderSessions:(()=>{const O=new Set(l.pendingAssistantHeaderSessions);return O.delete(t),O})()}:{}},P=un(_.messageSessionIndex??l.messageSessionIndex,n,t);if(P!==(_.messageSessionIndex??l.messageSessionIndex)&&(_.messageSessionIndex=P),p){const O=new Map(l.pendingAssistantParts);O.delete(n),_.pendingAssistantParts=O}return _}const h=m[f],j=h.info;if(j.userMessageMarker===!0||j.clientRole==="user"||j.role==="user"){const M={...h.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:j.providerID||void 0,modelID:j.modelID||void 0},C=l.pendingUserMessageMetaBySession.get(t);C&&!M.mode&&C.mode&&(M.mode=C.mode);const S={...h,info:M},A=new Map(l.messages),E=[...m];if(E[f]=S,A.set(t,E),C){const R=new Map(l.pendingUserMessageMetaBySession);return R.delete(t),{messages:A,pendingUserMessageMetaBySession:R}}return{messages:A}}const x={...h.info,...o};o.role&&o.role!==h.info.role&&(x.role=h.info.role),x.clientRole=x.clientRole??h.info.clientRole??h.info.role,x.clientRole==="user"&&(x.userMessageMarker=!0);const v=p?.parts?g(h.parts,p.parts):h.parts,N={...h,info:x,parts:v},w=new Map(l.messages),k=[...m];k[f]=N,w.set(t,k);const D={messages:w};if(p){const M=new Map(l.pendingAssistantParts);M.delete(n),D.pendingAssistantParts=M}return D});const a=o?.finish,i=o?.role;typeof a=="string"&&i!=="user"&&setTimeout(()=>{r().completeStreamingMessage(t,n)},0)},completeStreamingMessage:(t,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(a&&(i.streamingMessageIds=Ys(o.streamingMessageIds,t,null),i.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),i.messageStreamStates=d}Object.keys(i).length>0&&s(i),o.pendingAssistantParts.has(n)&&s(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),Or([n]);let l=!1;if(s(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const m=new Map(d.sessionMemoryState),f=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return m.set(t,p),l=!0,{sessionMemoryState:m}}),l){const d=dn.get(t);d&&(clearTimeout(d),dn.delete(t));const u=setTimeout(()=>{s(m=>{const f=m.sessionMemoryState.get(t);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:g,...b}=f;return p.set(t,b),{sessionMemoryState:p}}),dn.delete(t)},2e3);dn.set(t,u)}},syncMessages:(t,n)=>{const o=hc(t),a=gc(n,o),i=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,l=i?a.filter(d=>{const u=d?.info?.id;return u?po(u,i):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(w=>typeof w.info?.id=="string").map(w=>[w.info.id,w])),p=l.map(w=>{const k={...w.info,clientRole:w.info?.clientRole??w.info.role,userMessageMarker:w.info.role==="user"?!0:w.info?.userMessageMarker,animationSettled:w.info.role==="assistant"?w.info?.animationSettled??!0:w.info?.animationSettled},D=(Array.isArray(w.parts)?w.parts:[]).map(S=>{if(S?.type==="text"){const A=S.text??S.content??"";if(Ra(A))return{...S,synthetic:!0}}return S}),M=typeof k?.id=="string"?k.id:void 0,C=M?f.get(M):void 0;if(C&&C.info.role==="assistant"){const S=Array.isArray(C.parts)?C.parts:[],A=hn(S),E=hn(D);if(Xo(C.info)&&A>E){const _=Jo(S,D);return{...w,info:k,parts:_}}}return{...w,info:k,parts:D}}),g=za(p),b=new Set(m.map(w=>w.info.id)),h=new Set(g.map(w=>w.info.id)),j=[];b.forEach(w=>{h.has(w)||j.push(w)}),u.set(t,g);const y={messages:u,isSyncing:!0};Or(j);const x=Fn(d.messageStreamStates,j);if(x!==d.messageStreamStates&&(y.messageStreamStates=x),j.length>0){const w=d.streamingMessageIds.get(t);w&&j.includes(w)&&(y.streamingMessageIds=Ys(y.streamingMessageIds??d.streamingMessageIds,t,null))}if(j.length>0){const w=ho(y.messageSessionIndex??d.messageSessionIndex,j);w!==(y.messageSessionIndex??d.messageSessionIndex)&&(y.messageSessionIndex=w)}if(j.length>0){const w=new Map(d.pendingAssistantParts);let k=!1;j.forEach(D=>{w.delete(D)&&(k=!0)}),k&&(y.pendingAssistantParts=w)}const v=y.messageSessionIndex??d.messageSessionIndex;let N=v;return g.forEach(w=>{const k=w?.info?.id;typeof k=="string"&&k.length>0&&(N=un(N,k,t))}),N!==v&&(y.messageSessionIndex=N),y}),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+Hx;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&s(n=>{const o=n.sessionAbortFlags.get(t);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,n)=>{s(o=>{const a=o.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},i=new Map(o.sessionMemoryState);return i.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:i}})},updateActiveTurnAnchor:(t,n,o)=>{s(a=>{const i=a.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(a.sessionMemoryState);return l.set(t,{...i,activeTurnAnchorId:n??void 0,activeTurnSpacerHeight:o}),{sessionMemoryState:l}})},getActiveTurnAnchor:t=>{const n=r().sessionMemoryState.get(t);return n?{anchorId:n.activeTurnAnchorId??null,spacerHeight:n.activeTurnSpacerHeight??0}:null},trimToViewportWindow:(t,n=us.VIEWPORT_MESSAGES,o)=>{const a=r(),i=a.messages.get(t);if(!i||i.length<=n)return;const l=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(l.isStreaming&&t===o)return;const d=l.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const m=Math.min(i.length,u+n);m===i.length&&m-u<n&&(u=Math.max(0,m-n));const f=i.slice(u,m),p=i.slice(0,u),g=new Set(f.map(h=>h.info.id)),b=i.filter(h=>!g.has(h.info.id)).map(h=>h.info.id);s(h=>{const j=new Map(h.messages);j.set(t,f);const y=new Map(h.sessionMemoryState),x={...l,viewportAnchor:d-u,trimmedHeadMaxId:qx(p,l.trimmedHeadMaxId)};y.set(t,x);const v={messages:j,sessionMemoryState:y};Or(b);const N=Fn(h.messageStreamStates,b);if(N!==h.messageStreamStates&&(v.messageStreamStates=N),b.length>0){const D=h.streamingMessageIds.get(t);D&&b.includes(D)&&(v.streamingMessageIds=Ys(v.streamingMessageIds??h.streamingMessageIds,t,null))}if(b.length>0){const D=ho(v.messageSessionIndex??h.messageSessionIndex,b);D!==(v.messageSessionIndex??h.messageSessionIndex)&&(v.messageSessionIndex=D)}const w=v.messageSessionIndex??h.messageSessionIndex;let k=w;return f.forEach(D=>{const M=D?.info?.id;typeof M=="string"&&M.length>0&&(k=un(k,M,t))}),k!==w&&(v.messageSessionIndex=k),v})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=us.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const l=i[0][0];s(d=>{const m=(d.messages.get(l)||[]).map(N=>N.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(l),p.delete(l);const g={messages:f,sessionMemoryState:p},b=new Map(d.pendingAssistantParts);let h=!1;b.forEach((N,w)=>{N.sessionId===l&&(b.delete(w),h=!0)}),h&&(g.pendingAssistantParts=b);const j=new Map(d.sessionCompactionUntil);j.delete(l)&&(g.sessionCompactionUntil=j),Or(m);const y=Fn(d.messageStreamStates,m);y!==d.messageStreamStates&&(g.messageStreamStates=y);const x=ho(g.messageSessionIndex??d.messageSessionIndex,m);x!==(g.messageSessionIndex??d.messageSessionIndex)&&(g.messageSessionIndex=x);const v=Ys(d.streamingMessageIds,l,null);if(v!==d.streamingMessageIds&&(g.streamingMessageIds=v),d.abortControllers.has(l)){const N=new Map(d.abortControllers);N.delete(l),g.abortControllers=N}return g})},loadMoreMessages:async(t,n="up")=>{const o=r(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const l=await Wa(t,()=>ke.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=l.findIndex(m=>m.info.id===d.info.id);if(u>0){const m=Math.min(us.VIEWPORT_MESSAGES,u),f=l.slice(u-m,u);s(p=>{const g=[...f,...a],b=za(g),h=new Map(p.messages);h.set(t,b);const j=Math.max(0,b.length-a.length),y=new Map(p.sessionMemoryState);return y.set(t,{...i,viewportAnchor:i.viewportAnchor+j,hasMoreAbove:u-m>0,totalAvailableMessages:l.length}),{messages:h,sessionMemoryState:y}})}else u===0&&s(m=>{const f=new Map(m.sessionMemoryState);return f.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:f}})}},getLastMessageModel:t=>{const{messages:n}=r(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:Es(()=>ds()),partialize:s=>({lastUsedProvider:s.lastUsedProvider,sessionMemoryState:Array.from(s.sessionMemoryState.entries()).map(([r,t])=>[r,{viewportAnchor:t.viewportAnchor,isStreaming:t.isStreaming,lastAccessedAt:t.lastAccessedAt,backgroundMessageCount:t.backgroundMessageCount,totalAvailableMessages:t.totalAvailableMessages,hasMoreAbove:t.hasMoreAbove,trimmedHeadMaxId:t.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(s.sessionAbortFlags.entries()).map(([r,t])=>[r,{timestamp:t.timestamp,acknowledged:t.acknowledged}])}),merge:(s,r)=>{if(!s)return r;let t=r.sessionMemoryState;Array.isArray(s.sessionMemoryState)&&(t=new Map(s.sessionMemoryState.map(o=>o)));let n=r.sessionAbortFlags;return Array.isArray(s.sessionAbortFlags)&&(n=new Map(s.sessionAbortFlags)),{...r,lastUsedProvider:s.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:t,sessionAbortFlags:n}}}),{name:"message-store"})),Qx=s=>typeof s=="object"&&s!==null,Xx=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},Jx=async(s,r)=>{try{const n=lt.getState().getDirectoryForSession(s);if(n)return ke.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},eo=zt()(Kt(As((s,r)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===t.id))return;const i=t.permission?.toLowerCase?.()??null;let l=n?.currentAgentContext?.get(o);if(l||(l=n?.sessionAgentSelections?.get(o)??void 0),!l&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(l=f.getState().currentAgentName??void 0)}const d=Oo(l),u=n?.getSessionAgentEditMode?.(o,l)??d;if(u==="full"||u==="allow"&&$x(i)){r().respondToPermission(o,t.id,"once").catch(()=>{});return}s(f=>{const p=f.permissions.get(o)||[],g=new Map(f.permissions);return g.set(o,[...p,t]),{permissions:g}})},respondToPermission:async(t,n,o)=>{await Jx(t,()=>ke.replyToPermission(n,o)),o==="reject"&&await pt.getState().abortCurrentOperation(t),s(a=>{const l=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,l),{permissions:d}})}}),{name:"permission-store",storage:Es(()=>ds()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!Qx(s))return r;const t=Xx(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),Zx=s=>typeof s=="object"&&s!==null,ey=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},xc=async(s,r)=>{try{const n=lt.getState().getDirectoryForSession(s);if(n)return ke.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for question handling:",t)}return r()},gn=zt()(Kt(As((s,r)=>({questions:new Map,addQuestion:t=>{const n=t.sessionID;!n||r().questions.get(n)?.some(a=>a.id===t.id)||s(a=>{const i=a.questions.get(n)||[],l=new Map(a.questions);return l.set(n,[...i,t]),{questions:l}})},dismissQuestion:(t,n)=>{!t||!n||s(o=>{const i=(o.questions.get(t)||[]).filter(d=>d.id!==n),l=new Map(o.questions);return l.set(t,i),{questions:l}})},respondToQuestion:async(t,n,o)=>{await xc(t,()=>ke.replyToQuestion(n,o)),r().dismissQuestion(t,n)},rejectQuestion:async(t,n)=>{await xc(t,()=>ke.rejectQuestion(n)),r().dismissQuestion(t,n)}}),{name:"question-store",storage:Es(()=>ds()),partialize:s=>({questions:Array.from(s.questions.entries())}),merge:(s,r)=>{if(!Zx(s))return r;const t=ey(s.questions);return{...r,questions:new Map(t)}}}),{name:"question-store"})),il=s=>s.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
9
- `).replace(/\n\s*\n+/g,`
10
- `),Gn=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},yc=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return Gn(n);const o=s.find(a=>a.id===r);return o?Gn(o.directory??null):null},ue=zt()(Kt((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,questions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,pendingInputText:null,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},getSessionAgentEditMode:(t,n,o)=>bt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>bt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>bt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>lt.getState().loadSessions(),openNewSessionDraft:t=>{let n=null;t?.directoryOverride!==void 0?n=t.directoryOverride:n=Ft.getState().getActiveProject()?.path??null,s({newSessionDraft:{open:!0,directoryOverride:n,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const o=st.getState(),a=o.getVisibleAgents();let i;if(o.settingsDefaultAgent){const l=a.find(d=>d.name===o.settingsDefaultAgent);l&&(i=l.name)}i||(i=a.find(l=>l.name==="build")?.name||a[0]?.name),i&&o.setAgent(i)}catch{}},closeNewSessionDraft:()=>{const t=lt.getState().currentSessionId;s({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:t})},createSession:async(t,n,o)=>{r().closeNewSessionDraft();const a=await lt.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=pt.getState(),{messages:o,lastUsedProvider:a}=n;let i,l;if(o.forEach((y,x)=>{const v=y.find(N=>N.info?.id===t);v&&!i&&(i=v,l=x)}),!i||i.info.role!=="assistant")return;const d=il(i.parts);if(!d.trim())return;const u=lt.getState(),m=yc(u.sessions,l??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:g,currentAgentName:b}=st.getState(),h=p||a?.providerID,j=g||a?.modelID;!h||!j||await ke.sendMessage({id:f.id,providerID:h,modelID:j,text:d,prefaceText:Xu,agent:b??void 0})},deleteSession:(t,n)=>lt.getState().deleteSession(t,n),deleteSessions:(t,n)=>lt.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>lt.getState().updateSessionTitle(t,n),shareSession:t=>lt.getState().shareSession(t),unshareSession:t=>lt.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=lt.getState().currentSessionId,o=yc(lt.getState().sessions,t,lt.getState().getWorktreeMetadata),a=ke.getDirectory()??dt.getState().currentDirectory??null,i=o??a;try{ke.setDirectory(i??void 0)}catch(l){console.warn("Failed to set OpenCode directory for session switch:",l)}if(n&&n!==t&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,us.VIEWPORT_MESSAGES)}lt.getState().setCurrentSession(t),t&&(r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,ax)),r().evictLeastRecentlyUsed()},loadMessages:t=>pt.getState().loadMessages(t),sendMessage:async(t,n,o,a,i,l,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=x=>{s(v=>{const N=new Map(v.sessionActivityPhase??new Map);return N.set(x,"busy"),{sessionActivityPhase:N}})},g=x=>{s(v=>{const N=new Map(v.sessionActivityPhase??new Map);return N.set(x,"idle"),{sessionActivityPhase:N}})};if(m?.open){const x=await lt.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!x?.id)throw new Error("Failed to create session");const v=st.getState(),N=v.currentAgentName,w=f??N,k=v.currentProviderId,D=v.currentModelId;if(k&&D)try{bt.getState().saveSessionModelSelection(x.id,k,D)}catch{}if(w){try{bt.getState().saveSessionAgentSelection(x.id,w)}catch{}if(k&&D){try{bt.getState().saveAgentModelForSession(x.id,w,k,D)}catch{}if(u!==void 0)try{bt.getState().saveAgentModelVariantForSession(x.id,w,k,D,u)}catch{}}}try{lt.getState().initializeNewOpenChamberSession(x.id,v.agents)}catch{}r().closeNewSessionDraft(),p(x.id);try{return await pt.getState().sendMessage(t,n,o,w,x.id,i,l,d,u)}catch(M){throw g(x.id),M}}const b=lt.getState().currentSessionId,h=b?bt.getState().getSessionAgentSelection(b):null,j=st.getState().currentAgentName,y=f||h||j||void 0;if(b&&y){try{bt.getState().saveSessionAgentSelection(b,y)}catch{}if(u!==void 0)try{bt.getState().saveAgentModelVariantForSession(b,y,n,o,u)}catch{}}b&&p(b);try{return await pt.getState().sendMessage(t,n,o,y,b||void 0,i,l,d,u)}catch(x){throw b&&g(b),x}},abortCurrentOperation:()=>{const t=lt.getState().currentSessionId;return pt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=lt.getState().currentSessionId;if(!n)return null;const o=Date.now()+t;return s({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{s({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&&pt.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const l=lt.getState().currentSessionId||t;return pt.getState().addStreamingPart(t,n,o,a,l)},completeStreamingMessage:(t,n)=>pt.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>pt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>pt.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>pt.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:bt.getState().currentAgentContext,sessionAgentSelections:bt.getState().sessionAgentSelections,getSessionAgentEditMode:bt.getState().getSessionAgentEditMode};return eo.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>eo.getState().respondToPermission(t,n,o),addQuestion:t=>gn.getState().addQuestion(t),dismissQuestion:(t,n)=>gn.getState().dismissQuestion(t,n),respondToQuestion:(t,n,o)=>gn.getState().respondToQuestion(t,n,o),rejectQuestion:(t,n)=>gn.getState().rejectQuestion(t,n),clearError:()=>lt.getState().clearError(),getSessionsByDirectory:t=>lt.getState().getSessionsByDirectory(t),getDirectoryForSession:t=>lt.getState().getDirectoryForSession(t),getLastMessageModel:t=>pt.getState().getLastMessageModel(t),getCurrentAgent:t=>bt.getState().getCurrentAgent(t),syncMessages:(t,n)=>pt.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>lt.getState().applySessionMetadata(t,n),addAttachedFile:t=>er.getState().addAttachedFile(t),addServerFile:(t,n,o)=>er.getState().addServerFile(t,n,o),removeAttachedFile:t=>er.getState().removeAttachedFile(t),clearAttachedFiles:()=>er.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>pt.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>pt.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>pt.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=lt.getState().currentSessionId;return pt.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=lt.getState().currentSessionId;return pt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>pt.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>bt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>bt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>bt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>bt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>bt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>bt.getState().getAgentModelForSession(t,n),saveAgentModelVariantForSession:(t,n,o,a,i)=>bt.getState().saveAgentModelVariantForSession(t,n,o,a,i),getAgentModelVariantForSession:(t,n,o,a)=>bt.getState().getAgentModelVariantForSession(t,n,o,a),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=pt.getState().messages;return bt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>lt.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>lt.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>lt.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>lt.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>lt.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>lt.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=lt.getState().currentSessionId;if(!o)return null;const a=pt.getState().messages;return bt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=pt.getState().messages;return bt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=pt.getState().messages;return bt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=pt.getState().messages.get(t)||[],o=lt.getState().sessions.find(a=>a.id===t);console.log(`Debug session ${t}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(t,n,o)=>{const a=pt.getState().messages;return bt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>lt.getState().updateSession(t),removeSessionFromStore:t=>lt.getState().removeSessionFromStore(t),revertToMessage:async(t,n)=>{const a=(pt.getState().messages.get(t)||[]).find(m=>m.info.id===n);let i="";a&&a.info.role==="user"&&(i=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
- `).trim());const l=await ke.revertSession(t,n);lt.getState().updateSession(l);const d=pt.getState().messages.get(t)||[],u=l.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);pt.getState().syncMessages(t,f)}}i&&s({pendingInputText:i})},handleSlashUndo:async t=>{const o=(r().messages.get(t)||[]).filter(p=>p.info.role==="user"),i=r().sessions.find(p=>p.id===t);if(o.length===0)return;const l=i?.revert?.messageID;let d;if(l){const p=o.findIndex(g=>g.info.id===l);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,d.info.id);const{toast:f}=await rs(async()=>{const{toast:p}=await import("./vendor-.bun-C07YQe9X.js").then(g=>g.cs);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async t=>{const a=r().sessions.find(m=>m.id===t)?.revert?.messageID;if(!a)return;const l=(r().messages.get(t)||[]).filter(m=>m.info.role==="user"),d=l.findIndex(m=>m.info.id===a),u=l[d-1];if(u){const m=u.parts.find(g=>g.type==="text"),f=typeof m=="object"&&m&&"text"in m?String(m.text).slice(0,50)+(String(m.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,u.info.id);const{toast:p}=await rs(async()=>{const{toast:g}=await import("./vendor-.bun-C07YQe9X.js").then(b=>b.cs);return{toast:g}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await ke.unrevertSession(t);await lt.getState().updateSession(m),await r().loadMessages(t);const{toast:f}=await rs(async()=>{const{toast:p}=await import("./vendor-.bun-C07YQe9X.js").then(g=>g.cs);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(t,n)=>{const a=r().sessions.find(i=>i.id===t);if(a)try{const i=await ke.forkSession(t,n);if(!i||!i.id){const{toast:f}=await rs(async()=>{const{toast:p}=await import("./vendor-.bun-C07YQe9X.js").then(g=>g.cs);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(r().messages.get(t)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await rs(async()=>{const{toast:p}=await import("./vendor-.bun-C07YQe9X.js").then(g=>g.cs);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(i.id),u&&s({pendingInputText:u}),await r().loadMessages(i.id);const{toast:m}=await rs(async()=>{const{toast:f}=await import("./vendor-.bun-C07YQe9X.js").then(p=>p.cs);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(i){console.error("Failed to fork session:",i);const{toast:l}=await rs(async()=>{const{toast:d}=await import("./vendor-.bun-C07YQe9X.js").then(u=>u.cs);return{toast:d}},__vite__mapDeps([0,1]));l.error("Failed to fork session")}},setPendingInputText:t=>{s({pendingInputText:t})},consumePendingInputText:()=>{const t=r().pendingInputText;return t!==null&&s({pendingInputText:null}),t}}),{name:"composed-session-store"}));lt.subscribe((s,r)=>{if(s.sessions===r.sessions&&s.sessionsByDirectory===r.sessionsByDirectory&&s.currentSessionId===r.currentSessionId&&s.lastLoadedDirectory===r.lastLoadedDirectory&&s.isLoading===r.isLoading&&s.error===r.error&&s.webUICreatedSessions===r.webUICreatedSessions&&s.worktreeMetadata===r.worktreeMetadata&&s.availableWorktrees===r.availableWorktrees&&s.availableWorktreesByProject===r.availableWorktreesByProject)return;const t=ue.getState().newSessionDraft?.open;ue.setState({sessions:s.sessions,sessionsByDirectory:s.sessionsByDirectory,currentSessionId:t?null:s.currentSessionId,lastLoadedDirectory:s.lastLoadedDirectory,isLoading:s.isLoading,error:s.error,webUICreatedSessions:s.webUICreatedSessions,worktreeMetadata:s.worktreeMetadata,availableWorktrees:s.availableWorktrees,availableWorktreesByProject:s.availableWorktreesByProject})});pt.subscribe((s,r)=>{if(s.messages===r.messages&&s.sessionMemoryState===r.sessionMemoryState&&s.messageStreamStates===r.messageStreamStates&&s.sessionCompactionUntil===r.sessionCompactionUntil&&s.sessionAbortFlags===r.sessionAbortFlags&&s.streamingMessageIds===r.streamingMessageIds&&s.abortControllers===r.abortControllers&&s.lastUsedProvider===r.lastUsedProvider&&s.isSyncing===r.isSyncing)return;const t=new Map;s.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const l=i.info;if(l.role==="user"){const d=l.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=l.time&&typeof l.time.created=="number"?l.time.created:null;t.set(o,{title:u,createdAt:m});break}}}}}),ue.setState({messages:s.messages,sessionMemoryState:s.sessionMemoryState,messageStreamStates:s.messageStreamStates,sessionCompactionUntil:s.sessionCompactionUntil,sessionAbortFlags:s.sessionAbortFlags,streamingMessageIds:s.streamingMessageIds,abortControllers:s.abortControllers,lastUsedProvider:s.lastUsedProvider,isSyncing:s.isSyncing,userSummaryTitles:t})});er.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&ue.setState({attachedFiles:s.attachedFiles})});bt.subscribe((s,r)=>{s.sessionModelSelections===r.sessionModelSelections&&s.sessionAgentSelections===r.sessionAgentSelections&&s.sessionAgentModelSelections===r.sessionAgentModelSelections&&s.currentAgentContext===r.currentAgentContext&&s.sessionContextUsage===r.sessionContextUsage&&s.sessionAgentEditModes===r.sessionAgentEditModes||ue.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});eo.subscribe((s,r)=>{s.permissions!==r.permissions&&ue.setState({permissions:s.permissions})});gn.subscribe((s,r)=>{s.questions!==r.questions&&ue.setState({questions:s.questions})});dt.subscribe((s,r)=>{const t=Gn(s.currentDirectory??null),n=Gn(r.currentDirectory??null);if(t===n)return;const o=ue.getState().newSessionDraft;if(!o?.open)return;const a=Gn(o.directoryOverride);a&&a!==n||ue.setState(i=>({newSessionDraft:{...i.newSessionDraft,directoryOverride:t,parentID:null}}))});const ty=ue.getState().newSessionDraft?.open;ue.setState({sessions:lt.getState().sessions,currentSessionId:ty?null:lt.getState().currentSessionId,lastLoadedDirectory:lt.getState().lastLoadedDirectory,isLoading:lt.getState().isLoading,error:lt.getState().error,webUICreatedSessions:lt.getState().webUICreatedSessions,worktreeMetadata:lt.getState().worktreeMetadata,availableWorktrees:lt.getState().availableWorktrees,availableWorktreesByProject:lt.getState().availableWorktreesByProject,messages:pt.getState().messages,sessionMemoryState:pt.getState().sessionMemoryState,messageStreamStates:pt.getState().messageStreamStates,sessionCompactionUntil:pt.getState().sessionCompactionUntil,sessionAbortFlags:pt.getState().sessionAbortFlags,streamingMessageIds:pt.getState().streamingMessageIds,abortControllers:pt.getState().abortControllers,lastUsedProvider:pt.getState().lastUsedProvider,isSyncing:pt.getState().isSyncing,permissions:eo.getState().permissions,questions:gn.getState().questions,attachedFiles:er.getState().attachedFiles,sessionModelSelections:bt.getState().sessionModelSelections,sessionAgentSelections:bt.getState().sessionAgentSelections,sessionAgentModelSelections:bt.getState().sessionAgentModelSelections,currentAgentContext:bt.getState().currentAgentContext,sessionContextUsage:bt.getState().sessionContextUsage,sessionAgentEditModes:bt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=ue);const ll=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=c.useState(!1),[l,d]=c.useState({length:0,offset:0}),[u,m]=c.useState({length:0,offset:0}),f=c.useRef(null),p=c.useRef(null),g=c.useRef(!1),b=c.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),h=c.useRef(null),j=c.useCallback(()=>{const C=s.current;if(!C)return;const{scrollHeight:S,clientHeight:A,scrollTop:E,scrollWidth:R,clientWidth:_,scrollLeft:P}=C,O=8;if(S>A){const J=Math.max(A-O*2,0),K=A/S*J,L=Math.max(r,Math.min(J,K)),G=Math.max(J-L,0),B=Math.max(S-A,1),H=E/B*G;d({length:L,offset:H})}else d({length:0,offset:0});if(!o&&R>_){const J=Math.max(_-O*2,0),K=_/R*J,L=Math.max(r,Math.min(J,K)),G=Math.max(J-L,0),B=Math.max(R-_,1),H=P/B*G;m({length:L,offset:H})}else m({length:0,offset:0})},[s,r,o]),y=c.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),x=c.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{j(),i(!0),y()})},[y,j]);c.useEffect(()=>{const C=s.current;if(!C)return;j(),i(!0),y(),C.addEventListener("scroll",x,{passive:!0});const S=typeof ResizeObserver<"u"?new ResizeObserver(()=>j()):null;S?.observe(C);const A=typeof MutationObserver<"u"?new MutationObserver(()=>j()):null;return A?.observe(C,{childList:!0,subtree:!0,characterData:!0}),()=>{C.removeEventListener("scroll",x),S?.disconnect(),A?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,x,y,j]);const v=(C,S)=>{const A=s.current;A&&(g.current=!0,b.current={pointerX:C.clientX,pointerY:C.clientY,scrollTop:A.scrollTop,scrollLeft:A.scrollLeft},h.current=S,i(!0),f.current&&clearTimeout(f.current),C.currentTarget.setPointerCapture(C.pointerId))},N=C=>{if(!g.current)return;const S=s.current;if(!S)return;const A=h.current;if(A==="vertical"){const{pointerY:E,scrollTop:R}=b.current,_=C.clientY-E,P=S.clientHeight,O=Math.max(P-l.length,1),J=Math.max(S.scrollHeight-S.clientHeight,1),K=_/O*J;S.scrollTop=R+K}else if(A==="horizontal"){const{pointerX:E,scrollLeft:R}=b.current,_=C.clientX-E,P=S.clientWidth,O=Math.max(P-u.length,1),J=Math.max(S.scrollWidth-S.clientWidth,1),K=_/O*J;S.scrollLeft=R+K}},w=C=>{g.current&&(g.current=!1,C.currentTarget.releasePointerCapture(C.pointerId),y())},k=l.length>0,D=u.length>0;if(!k&&!D)return null;const M=8;return e.jsxs("div",{className:T("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[k&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${l.length}px`,top:`${M+l.offset}px`,right:`${M/2}px`},onPointerDown:C=>v(C,"vertical"),onPointerMove:N,onPointerUp:w,onPointerCancel:w}),D&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${M+u.offset}px`,bottom:`${M/2}px`},onPointerDown:C=>v(C,"horizontal"),onPointerMove:N,onPointerUp:w,onPointerCancel:w})]})},mt=c.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:l,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const g=c.useRef(null);return c.useImperativeHandle(p,()=>g.current,[]),e.jsxs("div",{className:T("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(i,{ref:g,className:T("overlay-scrollbar-target overlay-scrollbar-container overscroll-none",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",s),style:n,...f,children:t}),e.jsx(ll,{containerRef:g,minThumbSize:o,hideDelayMs:a,className:l,disableHorizontal:d})]})});mt.displayName="ScrollableOverlay";const bc="mobile-overlay-root",sy=()=>{if(typeof document>"u")return null;let s=document.getElementById(bc);return s||(s=document.createElement("div"),s.id=bc,document.body.appendChild(s)),s},ws=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:l})=>{const d=c.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=sy()),c.useEffect(()=>{if(!s)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=g=>{g.key==="Escape"&&t()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[s,t]),!s||!d.current)return null;const u=i??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:T("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(Wt,{className:"h-4 w-4"})});return l?l(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(mt,{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 _f.createPortal(m,d.current)},Mi=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,l]=c.useState(!1),d=c.useRef(void 0),u=j=>j>=1e6?`${(j/1e6).toFixed(1)}M`:j>=1e3?`${(j/1e3).toFixed(1)}K`:j.toFixed(1).replace(/\.0$/,""),m=j=>j>=90?"text-status-error":j>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(s)}`,`Context limit: ${u(t)}`,`Output limit: ${u(f)}`],g=c.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{l(!0)},500)},[]),b=c.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);c.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const h=e.jsxs("div",{className:T("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",onTouchStart:a?g:void 0,onTouchEnd:a?b:void 0,children:[e.jsx(Of,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:T(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[h,e.jsx(ws,{open:i,onClose:()=>l(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(s)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:T("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:h}),e.jsx(rt,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(j=>e.jsx("p",{className:"typography-micro leading-tight",children:j},j))})})]})},On={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Zu=(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 Ha(){const s=window.innerWidth,r=typeof window.matchMedia=="function",t=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,l=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=s>On.md&&s<=On.lg,m=s<=On.md;let f=d&&m,p=d&&!f&&u,g=!d||s>On.lg,b="desktop";l?(f=!1,p=!1,g=!0,b="desktop"):f?b="mobile":p?b="tablet":(g=!0,b="desktop"),Zu(l,b,d);let h="xs";for(const[j,y]of Object.entries(On))s>=y&&(h=j);return{isMobile:f,isTablet:p,isDesktop:g,deviceType:b,screenWidth:s,breakpoint:h,hasTouchInput:d}}function Rt(){const[s,r]=c.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Ha());return c.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(Ha())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(Ha())},a=[],i=l=>{l&&(typeof l.addEventListener=="function"?(l.addEventListener("change",o),a.push(()=>l.removeEventListener("change",o))):typeof l.addListener=="function"&&(l.addListener(o),a.push(()=>l.removeListener(o))))};return i(t),i(n),()=>{a.forEach(l=>l())}},[]),c.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,l=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||l||d>0;Zu(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const go=5e3,ry=1e4,ny=5e3,oy=1e4,ay=25,iy=4,wc=15e3,Qs=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),ly=(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},cy=(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!!ly(s.diffStats,r.diffStats)},dy=(s,r)=>{const t=new Set;if(!r)return t;const n=s?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),i=new Map(o.map(f=>[f.path,f])),l=new Set([...a.keys(),...i.keys()]);for(const f of l){const p=a.get(f),g=i.get(f);if(!p||!g){t.add(f);continue}if(p.index!==g.index||p.working_dir!==g.working_dir){t.add(f);continue}}const d=s?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],g=u[f];if(!p||!g){t.add(f);continue}(p.insertions!==g.insertions||p.deletions!==g.deletions)&&t.add(f)}return t},Xt=zt()(Kt((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:go,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,Qs()),s({activeDirectory:t,directories:a})}else s({activeDirectory:t})},getDirectoryState:t=>r().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:i}=r();let l=i.get(t);l||(l=Qs()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(i);return f.set(t,{...l,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),s({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(t);if(cy(l.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??Qs(),g=dy(p.status,m),b=new Set((p.status?.files??[]).map(x=>x.path)),h=new Set((m.files??[]).map(x=>x.path)),j=new Map(p.diffCache);for(const x of b)h.has(x)||j.delete(x);for(const x of g)j.delete(x);const y=g.size>0;f.set(t,{...p,isGitRepo:!0,status:m,diffCache:j,lastStatusFetch:Date.now(),lastStatusChange:y?Date.now():p.lastStatusChange}),s({directories:f})}else{const f=new Map(r().directories),p=f.get(t)??Qs();f.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),s({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||s({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{s({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(r().directories),i=a.get(t)??Qs();a.set(t,{...i,branches:o}),s({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{s({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=r(),i=a.get(t),l=o??i?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:l}),u=new Map(r().directories),m=u.get(t)??Qs();u.set(t,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:l}),s({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{s({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{s({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(r().directories),i=a.get(t)??Qs();a.set(t,{...i,identity:o}),s({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{s({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=r();let i=a.get(t);if(!i){i=Qs();const f=new Map(a);f.set(t,i),s({directories:f})}const{force:l=!1}=o,d=Date.now();await r().fetchStatus(t,n);const u=r().directories.get(t);if(!u?.isGitRepo)return;await r().fetchBranches(t,n);const m=d-(u.lastLogFetch||0);(l||m>oy||!u.log)&&await r().fetchLog(t,n),await r().fetchIdentity(t,n),r().fetchAllDiffs(t,n)},getDiff:(t,n)=>r().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(r().directories),i=a.get(t)??Qs(),l=new Map(i.diffCache);l.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:l}),s({directories:a})},clearDiffCache:t=>{const n=new Map(r().directories),o=n.get(t);o&&(n.set(t,{...o,diffCache:new Map}),s({directories:n}))},fetchAllDiffs:async(t,n)=>{const o=r().directories.get(t);if(!o?.status?.files||o.status.files.length===0)return;const l=o.status.files.filter(x=>!o.diffCache.has(x.path)).slice(0,ay);if(l.length===0)return;let d=0;const u=[],m=()=>{const x=d;return d+=1,x<l.length?l[x]:null},f=async x=>{const v=n.getGitFileDiff(t,{path:x}),N=new Promise((k,D)=>{setTimeout(()=>D(new Error(`Timed out after ${wc}ms`)),wc)}),w=await Promise.race([v,N]);return{path:x,diff:{original:w.original??"",modified:w.modified??""}}},p=async()=>{for(;;){const x=m();if(!x)return;try{u.push(await f(x.path))}catch{}}},g=Math.min(iy,l.length);await Promise.allSettled(Array.from({length:g},()=>p()));const b=new Map(r().directories),h=b.get(t);if(!h)return;const j=new Map(h.diffCache),y=Date.now();u.forEach(x=>{j.set(x.path,{...x.diff,fetchedAt:y})}),b.set(t,{...h,diffCache:j}),s({directories:b})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??Qs();o.set(t,{...a,logMaxCount:n}),s({directories:o})},startPolling:t=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){s({pollIntervalId:o()});return}const{activeDirectory:l}=r();if(!l){s({pollIntervalId:o()});return}if(await r().fetchStatus(l,t,{silent:!0}))await r().fetchLog(l,t),r().fetchAllDiffs(l,t),s({currentPollInterval:go});else{const m=Math.min(a+ny,ry);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:go})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:go}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),em=s=>Xt(r=>s?r.directories.get(s)?.status??null:null),tm=s=>Xt(r=>s?r.directories.get(s)?.branches??null:null),uy=s=>Xt(r=>s?r.directories.get(s)?.log??null:null),my=s=>Xt(r=>s?r.directories.get(s)?.identity??null:null),cl=s=>Xt(r=>s?r.directories.get(s)?.isGitRepo??null:null),fy=s=>Xt(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function Ut({...s}){return e.jsx($f,{"data-slot":"dropdown-menu",...s})}function Vt({...s}){return e.jsx(Lf,{"data-slot":"dropdown-menu-trigger",...s})}function Gt({className:s,sideOffset:r=4,...t}){return e.jsx(Bf,{children:e.jsx(zf,{"data-slot":"dropdown-menu-content",sideOffset:r,className:T("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 kt({className:s,inset:r,variant:t="default",...n}){return e.jsx(Vf,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:T("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 sm({...s}){return e.jsx(Wf,{"data-slot":"dropdown-menu-radio-group",...s})}function rm({className:s,children:r,...t}){return e.jsxs(Hf,{"data-slot":"dropdown-menu-radio-item",className:T("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(Uf,{children:e.jsx(Tt,{className:"size-3"})})}),r]})}function Wr({className:s,inset:r,...t}){return e.jsx(qf,{"data-slot":"dropdown-menu-label","data-inset":r,className:T("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function Ms({className:s,...r}){return e.jsx(Gf,{"data-slot":"dropdown-menu-separator",className:T("bg-border -mx-1 my-0.5 h-px",s),...r})}const py={read:{displayName:"Read File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"offset",label:"Start Line",type:"text"},{key:"limit",label:"Lines to Read",type:"text"}]},write:{displayName:"Write File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit File",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace All",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},bash:{displayName:"Shell Command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include Pattern",type:"pattern"}]},glob:{displayName:"Find Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List Directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore Patterns",type:"pattern"}]},task:{displayName:"Agent Task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent Type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"numResults",label:"Results Count",type:"text"},{key:"type",label:"Search Type",type:"text"}]},codesearch:{displayName:"Code Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update Todo List",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo Items",type:"code",language:"json"}]},todoread:{displayName:"Read Todo List",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Load Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill Name",type:"text"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]}};function dl(s){return py[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function hy(s,r,t){const n=dl(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=rn(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 rn(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 gy=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function nm(s){const r=s.split(".").pop()?.toLowerCase();return gy.includes(r||"")}function xy(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 yy(s,r){if(!s)return"";const t=n=>{const o=s[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=t("command");if(n)return n}if(r==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((r==="edit"||r==="multiedit")&&typeof s=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof s=="object"){const n=t("content");if(n)return n}return typeof s=="object"?Object.entries(s).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let l=a;return typeof a=="object"?l=JSON.stringify(a,null,2):typeof a=="boolean"&&(l=a?"Yes":"No"),`${i}: ${l}`}).join(`
12
- `):String(s)}const ul=c.createContext(null),In=()=>{const s=c.useContext(ul);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},om=s=>{const r=In();return s(r)},by=()=>om(s=>s.runtime.isDesktop),am=()=>om(s=>s.runtime.isVSCode),wy=Kf("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 Ne({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?tu:"button";return e.jsx(a,{"data-slot":"button",className:T(wy({variant:r,size:t,className:s})),...o})}const vy=({mode:s,onModeChange:r,className:t})=>{const n=c.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(Ne,{size:"sm",variant:"ghost",className:T("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(Yf,{className:"h-3 w-3"}):e.jsx(Qf,{className:"h-3 w-3"})})},ml=Ce.createContext(void 0);function nn(){const s=Ce.useContext(ml);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function pa(){return Ce.useContext(ml)}const jy="Flexoki",Sy="dark",ky={"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"},Ny=[{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"}}],Cy={name:jy,type:Sy,colors:ky,tokenColors:Ny},My="Flexoki",Dy="light",Ay={"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"},Ey=[{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"}}],Iy={name:My,type:Dy,colors:Ay,tokenColors:Ey},fl="flexoki-dark",pl="flexoki-light",Py=Cy,Ty=Iy;function im(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 lm(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 hl=lm(Py,fl,"dark"),gl=lm(Ty,pl,"light");im(hl,fl);im(gl,pl);const Nn={dark:fl,light:pl},vc=[gl,hl];let jc=!1;function cm(){jc||(Rl(Nn.dark,async()=>hl),Rl(Nn.light,async()=>gl),jc=!0)}const Fy=`
13
- :host {
14
- font-family: var(--font-mono);
15
- font-size: var(--text-code);
16
- }
17
-
18
- :host, pre, [data-diffs], [data-code] {
19
- transform: translateZ(0);
20
- -webkit-transform: translateZ(0);
21
- -webkit-backface-visibility: hidden;
22
- backface-visibility: hidden;
23
- }
24
-
25
- pre, [data-code] {
26
- font-family: var(--font-mono);
27
- font-size: var(--text-code);
28
- }
29
-
30
- [data-code] {
31
- -webkit-overflow-scrolling: touch;
32
- }
33
- /* Reduce hunk separator height */
34
- [data-separator-content] {
35
- height: 24px !important;
36
- }
37
- [data-expand-button] {
38
- height: 24px !important;
39
- width: 24px !important;
40
- }
41
- [data-separator-multi-button] {
42
- row-gap: 0 !important;
43
- }
44
- [data-expand-up] {
45
- height: 12px !important;
46
- min-height: 12px !important;
47
- max-height: 12px !important;
48
- margin: 0 !important;
49
- margin-top: 3px !important;
50
- padding: 0 !important;
51
- border-radius: 4px 4px 0 0 !important;
52
- }
53
- [data-expand-down] {
54
- height: 12px !important;
55
- min-height: 12px !important;
56
- max-height: 12px !important;
57
- margin: 0 !important;
58
- margin-top: -3px !important;
59
- padding: 0 !important;
60
- border-radius: 0 0 4px 4px !important;
61
- }
62
- `;function Ry(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 Sc=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const l=pa()?.currentTheme?.metadata?.variant==="dark";cm();const d=Ce.useRef(null),u=Ce.useMemo(()=>{const f=Ry(n,s,r);if(d.current?.key===f)return d.current.fileDiff;const p={name:n,contents:s,cacheKey:`old-${f}`},g={name:n,contents:r,cacheKey:`new-${f}`},b=hi(p,g);return d.current={key:f,fileDiff:b},b},[n,s,r,t]),m=Ce.useMemo(()=>({theme:{dark:Nn.dark,light:Nn.light},themeType:l?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!1,enableHoverUtility:!1,unsafeCSS:Fy}),[l,o,a]);return typeof window>"u"?null:e.jsx(mt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(Xf,{fileDiff:u,options:m})})},_y=1100,Oy=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},kc=(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]})},$y=c.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=c.useCallback(i=>{if(!o)return i;const l=i.lastIndexOf("/");return l>=0?i.slice(l+1):i},[o]);return s.length===0?null:e.jsxs(Ut,{children:[e.jsx(Vt,{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)}),kc(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Et,{className:"size-4 opacity-50"})]})}),e.jsx(Gt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(sm,{value:r??"",onValueChange:n,children:s.map(i=>e.jsx(rm,{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:kc(i.insertions,i.deletions)})]})},i.path))})})]})}),Ly=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",l=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:i,children:[o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),By=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=c.useMemo(()=>rn(s)||"text",[s]);return nm(s)?e.jsx(Ly,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(Sc,{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(Sc,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),zy=c.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Xt(c.useCallback(l=>l.directories.get(s)?.diffCache.get(r)??null,[s,r])),i=c.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return i?e.jsx(By,{filePath:r,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),Wy=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=ue(),{currentDirectory:n}=dt(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},Hy=()=>{const{git:s}=In(),r=Wy(),{screenWidth:t,isMobile:n}=Rt(),o=cl(r??null),a=em(r??null),i=Xt(L=>L.isLoadingStatus),{setActiveDirectory:l,fetchStatus:d,setDiff:u}=Xt(),[m,f]=c.useState(null),[p,g]=c.useState(0),[b,h]=c.useState(null),j=c.useRef(null),y=$e(L=>L.pendingDiffFile),x=$e(L=>L.setPendingDiffFile),v=$e(L=>L.diffLayoutPreference),N=$e(L=>L.diffFileLayout),w=$e(L=>L.setDiffFileLayout),k=$e(L=>L.diffWrapLines),D=$e(L=>L.setDiffWrapLines),M=n||k,C=c.useMemo(()=>{if(!a?.files)return[];const L=a.diffStats??{};return a.files.map(G=>({...G,insertions:L[G.path]?.insertions??0,deletions:L[G.path]?.deletions??0,isNew:Oy(G)})).sort((G,B)=>G.path.localeCompare(B.path))},[a]),S=c.useMemo(()=>m?C.find(L=>L.path===m)??null:null,[C,m]),A=c.useMemo(()=>{if(!S)return null;const L=N[S.path];if(L)return L;if(v==="inline")return"inline";if(v==="side-by-side")return"side-by-side";const G=t<_y;return S.isNew||G?"inline":"side-by-side"},[S,N,v,t]);c.useEffect(()=>{r&&(l(r),Xt.getState().directories.get(r)?.status||d(r,s))},[r,l,d,s]),c.useEffect(()=>{y&&(f(y),x(null))},[y,x]),c.useEffect(()=>{!m&&!y&&C.length>0&&f(C[0].path)},[C,m,y]),c.useEffect(()=>{m&&C.length>0&&(C.some(G=>G.path===m)||f(C[0]?.path??null))},[C,m]);const E=c.useCallback(L=>{f(L)},[]),R=(A??"side-by-side")==="side-by-side",_=Xt(c.useCallback(L=>!r||!m?null:L.directories.get(r)?.diffCache.get(m)??null,[r,m])),P=!!_,O=!!m&&!P;c.useEffect(()=>{if(h(null),!r||!m){j.current=null;return}if(_){j.current=null;return}const L=`${r}::${m}::${p}`;if(j.current===L)return;j.current=L;let G=!1;return(async()=>{try{const B=s.getGitFileDiff(r,{path:m}),H=15e3,V=new Promise((se,Y)=>{setTimeout(()=>Y(new Error(`Timed out after ${H}ms`)),H)}),oe=await Promise.race([B,V]);if(G)return;u(r,m,{original:oe.original??"",modified:oe.modified??""})}catch(B){if(G)return;const H=B instanceof Error?B.message:String(B);h(H)}})(),()=>{G=!0,j.current===L&&(j.current=null)}},[r,m,_,s,u,p]);const J=()=>!r||C.length===0?null:C.map(L=>e.jsx(zy,{directory:r,filePath:L.path,isVisible:L.path===m,renderSideBySide:R,wrapLines:M},L.path)),K=()=>r?i&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cs,{size:16,className:"animate-spin"}),"Loading repository status…"]}):o===!1?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):C.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:[J(),O&&!P&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:b?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:b}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{h(null),g(L=>L+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{size:16,className:"animate-spin"}),"Loading diff…"]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 bg-background",children:[!n&&e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(Hi,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${C.length} ${C.length===1?"file":"files"} changed`})]}),e.jsx($y,{changedFiles:C,selectedFile:m,selectedFileEntry:S,onSelectFile:E,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),S&&e.jsx("button",{type:"button",onClick:()=>D(!k),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${M?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:M?"Disable line wrap":"Enable line wrap",children:e.jsx(Jf,{className:"size-4"})}),S&&A&&e.jsx(vy,{mode:A==="side-by-side"?"side-by-side":"unified",onModeChange:L=>{if(!S)return;const G=L==="side-by-side"?"side-by-side":"inline";w(S.path,G)}})]}),K()]})},Uy=()=>{const{git:s}=In(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=ue(),{currentDirectory:o}=dt(),a=r?n.get(r)??void 0:void 0,l=t.find(p=>p.id===r)?.directory,d=a?.path??l??o??void 0,{setActiveDirectory:u,fetchStatus:m}=Xt(),f=fy(d??null);return c.useEffect(()=>{d&&(u(d),Xt.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},dm=Ce.forwardRef(({className:s,...r},t)=>e.jsx(su,{className:T("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",s),...r,ref:t,children:e.jsx(Zf,{className:T("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));dm.displayName=su.displayName;const Vy={},$o=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},Nc=s=>$o(s)??"__global__",Gy=s=>{const r=Object.entries(s??{}),t=r.filter(([,i])=>i?.status==="connected").length,n=r.length,o=r.some(([,i])=>i?.status==="failed"),a=r.some(([,i])=>i?.status==="needs_auth"||i?.status==="needs_client_registration");return{connected:t,total:n,hasFailed:o,hasAuthRequired:a}},Bn=zt()(Kt((s,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:t=>{const n=Nc(t??dt.getState().currentDirectory);return r().byDirectory[n]??Vy},refresh:async t=>{const n=$o(t?.directory??dt.getState().currentDirectory),o=Nc(n);t?.silent||s(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const l=(await ke.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};s(d=>({byDirectory:{...d.byDirectory,[o]:l},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const i=a instanceof Error?a.message:"Failed to load MCP status";s(l=>({loadingKeys:{...l.loadingKeys,[o]:!1},lastErrorKeys:{...l.lastErrorKeys,[o]:i}}))}},connect:async(t,n)=>{const o=$o(n??dt.getState().currentDirectory);await ke.getApiClient().mcp.connect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(t,n)=>{const o=$o(n??dt.getState().currentDirectory);await ke.getApiClient().mcp.disconnect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function qy(s){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",fillRule:"evenodd",viewBox:"-0.5 -0.5 25 25",...s,children:[e.jsx("path",{d:"M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"}),e.jsx("path",{d:"M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"})]})}const Ky=s=>{if(!s)return"Unknown";switch(s.status){case"connected":return"Connected";case"failed":return`Failed: ${s.error||"Unknown error"}`;case"needs_auth":return"Needs authentication";case"needs_client_registration":return`Needs registration: ${s.error||""}`;default:return s.status}},Yy=s=>{switch(s?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Di=({headerIconButtonClass:s})=>{const[r,t]=c.useState(!1),[n,o]=c.useState(!1),a=c.useRef(!1),{isMobile:i}=Rt(),d=dt(M=>M.currentDirectory)??null,u=Bn(M=>M.getStatusForDirectory(d)),m=Bn(M=>M.refresh),f=Bn(M=>M.connect),p=Bn(M=>M.disconnect),g=c.useCallback(M=>{M||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),t(M)},[]),b=c.useCallback(M=>{a.current||o(M)},[]),[h,j]=c.useState(!1),[y,x]=c.useState(null);c.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),c.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const v=c.useMemo(()=>Gy(u),[u]),N=c.useMemo(()=>Object.keys(u).sort((M,C)=>M.localeCompare(C)),[u]),w=c.useCallback(M=>{if(M?.preventDefault(),h)return;j(!0);const C=new Promise(S=>setTimeout(S,500));Promise.all([m({directory:d}),C]).finally(()=>{j(!1)})},[h,m,d]),k=()=>e.jsxs(e.Fragment,{children:[N.map(M=>{const C=u[M],S=Yy(C),A=C?.status==="connected",E=y===M,R=Ky(C);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i?e.jsx("span",{className:T("h-2 w-2 rounded-full flex-shrink-0",S==="success"&&"bg-status-success",S==="error"&&"bg-status-error",S==="warning"&&"bg-status-warning",S==="default"&&"bg-muted-foreground/40"),"aria-label":R}):e.jsxs(nt,{delayDuration:300,children:[e.jsx(ot,{asChild:!0,children:e.jsx("span",{className:T("h-2 w-2 rounded-full flex-shrink-0",S==="success"&&"bg-status-success",S==="error"&&"bg-status-error",S==="warning"&&"bg-status-warning",S==="default"&&"bg-muted-foreground/40"),"aria-label":R})}),e.jsx(rt,{side:"left",children:e.jsx("p",{children:R})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:M})]})}),e.jsx(dm,{checked:A,disabled:E,className:"data-[state=checked]:bg-status-info",onCheckedChange:async _=>{x(M);try{_?await f(M,d):await p(M,d)}finally{x(null)}}})]},M)}),N.length===0&&e.jsx("div",{className:"px-2 py-3 typography-ui-label text-muted-foreground text-center",children:"Configure MCP servers in settings."})]}),D=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:T(s,"relative"),onClick:i?()=>t(!0):void 0,children:[e.jsx(qy,{className:"h-[1.0625rem] w-[1.0625rem]"}),v.total>0&&e.jsx("span",{className:T("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",v.hasFailed?"bg-status-error":v.hasAuthRequired?"bg-status-warning":v.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return i?e.jsxs(e.Fragment,{children:[D,e.jsxs(ws,{open:r,title:"MCP Servers",onClose:()=>t(!1),renderHeader:M=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"MCP Servers"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:h,onClick:w,"aria-label":"Refresh",children:e.jsx(Dr,{className:T("h-4 w-4",h&&"animate-spin")})}),M]})]}),children:[e.jsx("div",{className:"py-1",children:k()}),d&&e.jsx("div",{className:"px-2 py-1 border-t border-border/40 mt-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]}):e.jsxs(Ut,{open:r,onOpenChange:g,children:[e.jsxs(nt,{delayDuration:1e3,open:r?!1:n,onOpenChange:b,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:D})}),e.jsx(rt,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(Gt,{align:"end",className:"w-72",children:[e.jsxs("div",{className:"flex items-center justify-between px-2 py-1",children:[e.jsx("span",{className:"typography-ui-label font-semibold",children:"MCP Servers"}),e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:h,onClick:w,"aria-label":"Refresh",children:e.jsx(Dr,{className:T("h-4 w-4",h&&"animate-spin")})})]}),e.jsx(Ms,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:k()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ms,{}),e.jsx("div",{className:"px-2 py-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]})]})},Qy=()=>{const s=$e(d=>d.setSessionSwitcherOpen),r=$e(d=>d.toggleSidebar),{isMobile:t}=Rt(),[n,o]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=c.useCallback(()=>{t?s(!0):r()},[t,s,r]),l="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground";return t||!n||!a?null:e.jsx("div",{className:"fixed top-[0.375rem] left-[5.25rem] z-[9999]",style:{pointerEvents:"auto","--padding-scale":"1"},children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Open sessions",className:l,children:e.jsx(aa,{className:"h-5 w-5"})})})},Cc=()=>{const s=$e(B=>B.setSessionSwitcherOpen),r=$e(B=>B.toggleSidebar),t=$e(B=>B.setSettingsDialogOpen),n=$e(B=>B.toggleCommandPalette),o=$e(B=>B.toggleHelpDialog),a=$e(B=>B.isSidebarOpen),i=$e(B=>B.sidebarWidth),l=$e(B=>B.activeMainTab),d=$e(B=>B.setActiveMainTab),{getCurrentModel:u}=st(),m=ue(B=>B.getContextUsage),{isMobile:f}=Rt(),p=Uy(),g=ua(B=>B.available),b=c.useRef(null),[h,j]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Ce.useEffect(()=>{if(typeof window>"u")return;const B=typeof window.opencodeDesktop<"u";j(B)},[]);const x=u(),v=x&&typeof x.limit=="object"&&x.limit!==null?x.limit:null,N=v&&typeof v.context=="number"?v.context:0,w=v&&typeof v.output=="number"?v.output:0,k=m(N,w),D=$e(B=>B.isSessionSwitcherOpen),M=c.useCallback(()=>{if(typeof document>"u")return;const B=document.activeElement;if(!B)return;const H=B.tagName;(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||B.isContentEditable)&&B.blur()},[]),C=c.useCallback(()=>{if(f){M(),s(!D);return}r()},[M,f,D,s,r]),S=c.useCallback(()=>{f&&M(),s(!1),t(!0)},[M,f,s,t]),A="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground",E=c.useMemo(()=>h&&y?a?"pl-0":"pl-[8.0rem]":"pl-3",[h,y,a]),R=c.useCallback(()=>{if(typeof document>"u")return;const B=b.current?.getBoundingClientRect().height;B&&document.documentElement.style.setProperty("--oc-header-height",`${B}px`)},[]);Ce.useEffect(()=>{if(typeof window>"u")return;R();const B=b.current;if(!B||typeof ResizeObserver>"u")return()=>{};const H=new ResizeObserver(()=>{R()});return H.observe(B),window.addEventListener("resize",R),window.addEventListener("orientationchange",R),()=>{H.disconnect(),window.removeEventListener("resize",R),window.removeEventListener("orientationchange",R)}},[R]),Ce.useEffect(()=>{R()},[R,f]);const _=c.useCallback(async B=>{if(!B.target.closest("button, a, input, select, textarea")&&B.button===0&&h)try{const{getCurrentWindow:H}=await rs(async()=>{const{getCurrentWindow:oe}=await import("./vendor-.bun-C07YQe9X.js").then(se=>se.ct);return{getCurrentWindow:oe}},__vite__mapDeps([0,1]));await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[h]),P=c.useCallback(async B=>{if(B.button===0&&h)try{const{getCurrentWindow:H}=await rs(async()=>{const{getCurrentWindow:oe}=await import("./vendor-.bun-C07YQe9X.js").then(se=>se.ct);return{getCurrentWindow:oe}},__vite__mapDeps([0,1]));await H().startDragging()}catch(H){console.error("Failed to start window dragging:",H)}},[h]),O=c.useMemo(()=>[{id:"chat",label:"Chat",icon:ep},{id:"diff",label:"Diff",icon:nr,badge:!f&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:Er},{id:"git",label:"Git",icon:$t,showDot:f&&p>0}],[p,f]);Ce.useEffect(()=>{const B=H=>{if(Cs(H)&&!H.shiftKey&&!H.altKey){const V=parseInt(H.key,10);V>=1&&V<=O.length&&(H.preventDefault(),d(O[V-1].id))}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[O,d]);const J=(B,H)=>{const V=l===B.id,oe=B.icon,se=B.id==="chat",Y=B.id==="git";return e.jsxs(c.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(B.id),onMouseDown:V?P:void 0,className:T("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",V?"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",V?"text-foreground":"text-muted-foreground",V&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",V&&se&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",se&&!(h&&y&&a)&&"border-l",Y&&"border-r",se&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...V&&se&&a?{"--sidebar-w":h&&y?`${i}px`:"64px"}:{},...se&&!(h&&y&&a)||Y?{borderColor:"var(--interactive-border)"}:{}},"aria-label":B.label,"aria-selected":V,role:"tab",children:[f?e.jsx(oe,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{size:16}),e.jsx("span",{className:"header-tab-label",children:B.label})]}),se&&!f&&k&&k.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Mi,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})}),B.badge!==void 0&&B.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:B.badge})]}),!H&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},B.id)},K=()=>e.jsxs("div",{onMouseDown:_,className:T("app-region-drag relative flex h-12 select-none items-center",E),role:"tablist","aria-label":"Main navigation",children:[!(h&&y)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:C,"aria-label":"Open sessions",className:`${A} mr-2.5`,children:e.jsx(aa,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:O.map((B,H)=>J(B,H===O.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:A,children:e.jsx(Zr,{className:"h-5 w-5"})})}),e.jsx(rt,{children:e.jsxs("p",{children:["Command Palette (",Zt(),"+K)"]})})]}),e.jsx(Di,{headerIconButtonClass:A}),e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:A,children:e.jsx(Kr,{className:"h-5 w-5"})})}),e.jsx(rt,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Zt(),"+.)"]})})]})]})]}),L=()=>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:C,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(tp,{className:"h-5 w-5"})}),k&&k.totalTokens>0&&l==="chat"&&e.jsx(Mi,{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:O.map(B=>{const H=l===B.id,V=B.icon;return e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&M(),d(B.id)},"aria-label":B.label,"aria-selected":H,role:"tab",className:T(A,"relative",H&&"text-foreground"),children:[e.jsx(V,{className:"h-5 w-5"}),B.badge!==void 0&&B.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:B.badge}),B.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(rt,{children:e.jsx("p",{children:B.label})})]},B.id)})}),e.jsx(Di,{headerIconButtonClass:A}),e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:S,"aria-label":"Open settings",className:T(A,"relative"),children:[e.jsx(qr,{className:"h-5 w-5"}),g&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Update available"})]})}),e.jsx(rt,{children:e.jsx("p",{children:g?"Settings (Update available)":"Settings"})})]})]})]}),G=T("header-safe-area border-b relative z-10",h?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:b,className:G,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?L():K()})};function xl({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:T("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function um({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:T("@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 mm({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",s),...r})}function fm({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:T("px-6",s),...r})}class is extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(xl,{className:"w-full max-w-md",children:[e.jsx(um,{className:"text-center",children:e.jsxs(mm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(gi,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(fm,{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(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ps,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let xo=0;function ms({...s}){return e.jsx(sp,{"data-slot":"dialog",...s})}function Xy({...s}){return e.jsx(op,{"data-slot":"dialog-portal",...s})}const pm=Ce.forwardRef(({className:s,...r},t)=>(Ce.useEffect(()=>(xo+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{xo=Math.max(0,xo-1),xo===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(ru,{ref:t,"data-slot":"dialog-overlay",className:T("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));pm.displayName=ru.displayName;function fs({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Xy,{"data-slot":"dialog-portal",children:[e.jsx(pm,{className:"rounded-none"}),e.jsxs(rp,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:T("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(np,{"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(Wt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function xs({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:T("flex flex-col gap-2 text-center sm:text-left",s),...r})}function Ks({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:T("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",s),...r})}function ys({className:s,...r}){return e.jsx(ap,{"data-slot":"dialog-title",className:T("typography-markdown leading-none font-semibold text-foreground",s),...r})}function Ns({className:s,...r}){return e.jsx(ip,{"data-slot":"dialog-description",className:T("text-muted-foreground typography-ui-label",s),...r})}const Mc="https://github.com/btriapitsyn/openchamber/releases";async function Jy(){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 Zy(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 Ai=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:l,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Ce.useState(!1),[p,g]=Ce.useState("idle"),[b,h]=Ce.useState(null),j=t?.version?`${Mc}/tag/v${t.version}`:Mc,y=a?.total?Math.round(a.downloaded/a.total*100):0,x=u==="web",v=t?.updateCommand||"openchamber update";Ce.useEffect(()=>{s||(g("idle"),h(null))},[s]);const N=async()=>{try{await navigator.clipboard.writeText(v),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},w=Ce.useCallback(async()=>{g("updating"),h(null);const D=await Jy();if(!D.success){g("error"),h(D.error||"Update failed");return}g("restarting"),await new Promise(C=>setTimeout(C,2e3)),g("reconnecting"),await Zy()?window.location.reload():(g("error"),h("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),k=p!=="idle"&&p!=="error";return e.jsx(ms,{open:s,onOpenChange:k?void 0:r,children:e.jsxs(fs,{className:"max-w-md",children:[e.jsx(xs,{children:e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(lp,{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})]}),x&&k&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Do,{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(mt,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((D,M)=>/^\d+\.\d+\.\d+$/.test(D.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",D.trim(),`
63
- `]},M):D.replace(/^- /gm,"• ").trim()+`
64
-
65
- `)})}),x&&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(cp,{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:v}),e.jsx("button",{onClick:N,className:T("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(Tt,{className:"h-4 w-4"}):e.jsx(dp,{className:"h-4 w-4"})})]})]}),!x&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[y,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${y}%`}})})]}),(i||b)&&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||b})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:T("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(Ho,{className:"h-4 w-4"}),"GitHub"]}),!x&&!o&&!n&&e.jsxs("button",{onClick:l,className:T("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(Yr,{className:"h-4 w-4"}),"Download Update"]}),!x&&n&&e.jsxs("button",{disabled:!0,className:T("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(Do,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!x&&o&&e.jsxs("button",{onClick:d,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Ps,{className:"h-4 w-4"}),"Restart to Update"]}),x&&!k&&e.jsxs("button",{onClick:w,className:T("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(Yr,{className:"h-4 w-4"}),"Update Now"]}),x&&k&&e.jsxs("button",{disabled:!0,className:T("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(Do,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Dc=264,Ac=200,Ec=500,eb=40,Ic="openchamber:check-for-updates",tb=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=$e(),[l,d]=c.useState(!1),u=c.useRef(0),m=c.useRef(n||Dc),[f,p]=c.useState(!1),g=ua(),b=c.useRef(!1),h=g.checkForUpdates,{available:j,downloaded:y,checking:x}=g,[v,N]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const S=typeof window.opencodeDesktop<"u";N(S)},[]),c.useEffect(()=>{if(typeof window>"u")return;const S=()=>{typeof window.opencodeDesktop<"u"&&(b.current=!0,h())};return window.addEventListener(Ic,S),()=>{window.removeEventListener(Ic,S)}},[h]),c.useEffect(()=>{b.current&&(x||(j||y?p(!0):ne.success("No updates available",{description:"You are running the latest version."}),b.current=!1))},[j,y,x]),c.useEffect(()=>{if(r||!l)return;const S=E=>{const R=E.clientX-u.current,_=Math.min(Ec,Math.max(Ac,m.current+R));o(_)},A=()=>{d(!1)};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",A,{once:!0}),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",A)}},[r,l,o]),c.useEffect(()=>{r&&l&&d(!1)},[r,l]);const k=c.useCallback(async S=>{if(S.button===0&&v)try{const{getCurrentWindow:A}=await rs(async()=>{const{getCurrentWindow:R}=await import("./vendor-.bun-C07YQe9X.js").then(_=>_.ct);return{getCurrentWindow:R}},__vite__mapDeps([0,1]));await A().startDragging()}catch(A){console.error("Failed to start window dragging from sidebar:",A)}},[v]);if(r)return null;const D=s?Math.min(Ec,Math.max(Ac,n||Dc)):0,M=v&&w,C=S=>{s&&(d(!0),u.current=S.clientX,m.current=D,S.preventDefault())};return e.jsxs("aside",{className:T("relative flex h-full overflow-hidden border-r",v?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",l?"transition-none":"",!s&&"border-r-0"),style:{width:`${D}px`,minWidth:`${D}px`,maxWidth:`${D}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||D===0,children:[s&&e.jsx("div",{className:T("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",l?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:C,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:T("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!s&&"pointer-events-none select-none opacity-0"),style:{width:`${D}px`,overflowX:"hidden"},"aria-hidden":!s,children:[M&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${eb}px`},onMouseDown:k,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(is,{children:t})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:T("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(qr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),j||y?e.jsxs("button",{onClick:()=>p(!0),className:T("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(Yr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!v&&e.jsxs(nt,{children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:T("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(ls,{className:"h-4 w-4"})})}),e.jsx(rt,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Ai,{open:f,onOpenChange:p,info:g.info,downloading:g.downloading,downloaded:g.downloaded,progress:g.progress,error:g.error,onDownload:g.downloadUpdate,onRestart:g.restartToUpdate,runtimeType:g.runtimeType})]})]})};function hm({className:s,...r}){return e.jsx(en,{"data-slot":"command",className:T("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function sb({title:s="Command Palette",description:r="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(ms,{...a,children:[e.jsxs(xs,{className:"sr-only",children:[e.jsx(ys,{children:s}),e.jsx(Ns,{children:r})]}),e.jsx(fs,{className:T("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(hm,{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 gm({className:s,...r}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(yr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(en.Input,{"data-slot":"command-input",className:T("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 xm({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(mt,{as:en.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:T("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 ym({...s}){return e.jsx(en.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function wn({className:s,...r}){return e.jsx(en.Group,{"data-slot":"command-group",className:T("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 Zo({className:s,...r}){return e.jsx(en.Separator,{"data-slot":"command-separator",className:T("bg-border -mx-1 h-px",s),...r})}function ss({className:s,...r}){return e.jsx(en.Item,{"data-slot":"command-item",className:T("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...r})}function dr({className:s,...r}){const t=a=>{const i=a.trim().toLowerCase();return i==="ctrl"||i==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?e.jsx(Zr,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(so,{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:T("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,i)=>e.jsxs(Ce.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):r.children})}const Pc=["artful","bionic","cosmic","disco","focal","groovy","jammy","kinetic","lunar","noble","bold","brave","calm","eager","gentle","happy","keen","lively","merry","swift","warm","wise","bright","clever","daring","agile","crisp","fresh","lucid","quick","sharp","vivid","zealous"],Tc=["aardvark","beaver","chipmunk","dolphin","falcon","gopher","hedgehog","jackal","koala","lemur","mongoose","narwhal","otter","pangolin","quokka","raccoon","salamander","toucan","walrus","yak","zebra","badger","condor","dingo","egret","ferret","gecko","heron","iguana"];function rb(){const s=Pc[Math.floor(Math.random()*Pc.length)],r=Tc[Math.floor(Math.random()*Tc.length)];return`${s}-${r}`}function Fc(s){const r=rb();return s&&s.trim()?`${s.trim().replace(/\/+$/,"")}/${r}`:r}async function nb(s,r,t=10){let n;try{const o=await nl(s);n=new Set(o?.all??[])}catch{return Fc(r)}for(let o=0;o<t;o++){const a=Fc(r);if(!n.has(a))return a}return null}const ob=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Ua=!1;async function ha(){if(Ua)return null;const s=Ft.getState().getActiveProject();if(!s?.path)return ne.error("No active project",{description:"Please select a project first."}),null;const r=s.path;let t=!1;try{t=await sn(r)}catch{}if(!t)return ne.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Ua=!0,Vs("Creating new worktree session...");try{const n=s.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,i=await nb(r,o);if(!i)return ne.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const l=ob(i),u=await Uu({projectDirectory:r,worktreeSlug:l,branch:i,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await ol(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=ue.getState(),g=await p.createSession(void 0,u.path);if(!g)return await Mx({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),ne.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const b=st.getState(),h=b.agents;p.initializeNewOpenChamberSession(g.id,h),p.setSessionDirectory(g.id,u.path),p.setWorktreeMetadata(g.id,f);try{const x=b.getVisibleAgents();let v;if(b.settingsDefaultAgent){const N=x.find(w=>w.name===b.settingsDefaultAgent);N&&(v=N.name)}if(v||(v=x.find(N=>N.name==="build")?.name||x[0]?.name),v){b.setAgent(v),bt.getState().saveSessionAgentSelection(g.id,v);const N=b.settingsDefaultModel;if(N){const w=N.split("/");if(w.length===2){const[k,D]=w;if(b.getModelMetadata(k,D)){bt.getState().saveSessionModelSelection(g.id,k,D),bt.getState().saveAgentModelForSession(g.id,v,k,D);const C=b.settingsDefaultVariant;if(C){const E=b.providers.find(R=>R.id===k)?.models.find(R=>R.id===D)?.variants;E&&Object.prototype.hasOwnProperty.call(E,C)&&(b.setCurrentVariant(C),bt.getState().saveAgentModelVariantForSession(g.id,v,k,D,C))}}}}}}catch{}dt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const y=(await oo(r)).filter(x=>x.trim().length>0);return y.length>0?(ne.success("Worktree created",{description:`Branch: ${i}. Running ${y.length} setup command${y.length===1?"":"s"}...`}),Gu(u.path,r,y).then(x=>{if(x.success)ne.success("Setup commands completed",{description:`All ${x.results.length} command${x.results.length===1?"":"s"} succeeded.`});else{const v=x.results.filter(w=>!w.success),N=x.results.filter(w=>w.success);ne.error("Setup commands failed",{description:`${v.length} of ${x.results.length} command${x.results.length===1?"":"s"} failed.`+(N.length>0?` ${N.length} succeeded.`:"")})}}).catch(()=>{ne.error("Setup commands failed",{description:"Could not execute setup commands."})})):ne.success("Worktree created",{description:`Branch: ${i}`}),g}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return ne.error("Failed to create worktree",{description:o}),null}finally{Ds(),Ua=!1}}const ab=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:i,toggleSidebar:l}=$e(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=ue(),f=st(P=>P.settingsAutoCreateWorktree),{currentDirectory:p}=dt(),{themeMode:g,setThemeMode:b}=nn(),h=()=>{r(!1)},j=async()=>{n("chat"),a(!1),d(),h()},y=P=>{u(P),h()},x=P=>{b(P),h()},v=()=>{t(!0),h()},N=()=>{h(),ha()},{isMobile:w}=Rt(),k=()=>{if(w){const{isSessionSwitcherOpen:P}=$e.getState();a(!P)}else l();h()},D=()=>{n("diff"),h()},M=()=>{n("git"),h()},C=()=>{n("terminal"),h()},S=()=>{o(!0),h()},A=()=>{Un(),h()},E=()=>{i(!0),h()},R=m(p??""),_=c.useMemo(()=>R.slice(0,5),[R]);return e.jsxs(sb,{open:s,onOpenChange:r,children:[e.jsx(gm,{placeholder:"Type a command or search..."}),e.jsxs(xm,{children:[e.jsx(ym,{children:"No results found."}),e.jsxs(wn,{heading:"Actions",children:[e.jsxs(ss,{onSelect:k,children:[e.jsx(aa,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(dr,{children:[Zt()," + L"]})]}),e.jsxs(ss,{onSelect:j,children:[e.jsx(qt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(dr,{children:f?`Shift + ${Zt()} + N`:`${Zt()} + N`})]}),e.jsxs(ss,{onSelect:N,children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(dr,{children:f?`${Zt()} + N`:`Shift + ${Zt()} + N`})]}),e.jsxs(ss,{onSelect:v,children:[e.jsx(Kr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(dr,{children:[Zt()," + ."]})]}),e.jsxs(ss,{onSelect:D,children:[e.jsx(nr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(dr,{children:[Zt()," + 2"]})]}),e.jsxs(ss,{onSelect:C,children:[e.jsx(Er,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(dr,{children:[Zt()," + 3"]})]}),e.jsxs(ss,{onSelect:M,children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(dr,{children:[Zt()," + 4"]})]}),e.jsxs(ss,{onSelect:E,children:[e.jsx(or,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(dr,{children:[Zt()," + T"]})]}),e.jsxs(ss,{onSelect:S,children:[e.jsx(qr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(dr,{children:[Zt()," + ,"]})]}),e.jsxs(ss,{onSelect:A,children:[e.jsx(Ps,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Zo,{}),e.jsxs(wn,{heading:"Theme",children:[e.jsxs(ss,{onSelect:()=>x("light"),children:[e.jsx(up,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),g==="light"&&e.jsx(Tt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ss,{onSelect:()=>x("dark"),children:[e.jsx(mp,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),g==="dark"&&e.jsx(Tt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ss,{onSelect:()=>x("system"),children:[e.jsx(nu,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),g==="system"&&e.jsx(Tt,{className:"ml-auto h-4 w-4"})]})]}),_.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Zo,{}),e.jsx(wn,{heading:"Recent Sessions",children:_.map(P=>e.jsxs(ss,{onSelect:()=>y(P.id),children:[e.jsx(Ui,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})]},P.id))})]})]})]})},ib=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(ia,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(Zr,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},lb=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(c.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),ib(t,n)]},`${t}-${n}`))},cb=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=$e(),t=st(a=>a.settingsAutoCreateWorktree),n=Zt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:Zr},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:Kr},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:aa},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:Qr},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:ou},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:ar}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:t?"Create New Session in Worktree":"Create New Session",icon:t?$t:qt},{keys:[`Shift + ${n} + N`],description:t?"Create New Session":"Create New Session in Worktree",icon:t?qt:$t},{keys:[`${n} + I`],description:"Focus Chat Input",icon:au},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:jn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:fp},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:nr},{keys:[`${n} + 3`],description:"Open Terminal",icon:Er},{keys:[`${n} + 4`],description:"Open Git Panel",icon:$t},{keys:[`${n} + T`],description:"Open Timeline",icon:or},{keys:[`${n} + ,`],description:"Open Settings",icon:qr}]}];return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(qr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ns,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((i,l)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.icon&&e.jsx(i.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:i.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(i.keys)?i.keys:i.keys.split(" / ")).map((d,u)=>e.jsxs(c.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:lb(d)})]},`${d}-${u}`))})]},l))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Kr,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsxs("li",{children:["• Use Command Palette (",n," + K) to quickly access all actions"]}),e.jsx("li",{children:"• The 5 most recent sessions appear in the Command Palette"}),e.jsx("li",{children:"• Theme cycling remembers your preference across sessions"})]})]})]})})]})]})})},Va=new Set,Ga=new Set,qa=new Set,Cn={onDeleteRequest(s){return Va.add(s),()=>{Va.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||Va.forEach(r=>r(s))},onCreateRequest(s){return Ga.add(s),()=>{Ga.delete(s)}},requestCreate(s){const r=s??{};Ga.forEach(t=>t(r))},onDirectoryRequest(s){return qa.add(s),()=>{qa.delete(s)}},requestDirectoryDialog(){qa.forEach(s=>s())}};function bm(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 Rc="oc.sessions.projectCollapse",_c="oc.sessions.expandedParents",Oc=s=>{const r=new Date(s),t=new Date,n=(i,l)=>i.getFullYear()===l.getFullYear()&&i.getMonth()===l.getMonth()&&i.getDate()===l.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),n(r,t)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},Xs=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},$c=s=>s.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),db=({id:s,projectLabel:r,projectDescription:t,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:i,isDesktopRuntime:l,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:g,onOpenMultiRunLauncher:b,onClose:h,sentinelRef:j,children:y})=>{const{attributes:x,listeners:v,setNodeRef:N,isDragging:w}=Cp({id:s});return e.jsxs("div",{ref:N,className:T("relative",w&&"opacity-40"),children:[l&&e.jsx("div",{ref:j,"data-project-id":s,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:T("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b",!l&&"bg-sidebar"),style:{backgroundColor:l?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:i?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...x,children:[e.jsxs(nt,{delayDuration:1500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...v,className:"flex-1 min-w-0 flex items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-sm cursor-grab active:cursor-grabbing",children:e.jsx("span",{className:T("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(rt,{side:"right",sideOffset:8,children:t})]}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:T("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",m?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:k=>k.stopPropagation(),children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"min-w-[180px]",children:[a&&!u&&e.jsxs(kt,{onClick:b,children:[e.jsx(bm,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(kt,{onClick:h,className:"text-destructive focus:text-destructive",children:[e.jsx(Wt,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),e.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),g()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground flex-shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"New session",children:e.jsx(qt,{className:"h-4 w-4"})})]})}),y]})},ub=({projectLabel:s,isActiveProject:r})=>e.jsx("div",{className:"bg-sidebar border border-border rounded-md shadow-lg px-2 py-1.5",style:{width:"max-content",maxWidth:"280px"},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:s}),e.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground ml-auto",children:e.jsx(qt,{className:"h-4 w-4"})})]})}),Ei=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,i]=c.useState(null),[l,d]=c.useState(""),[u,m]=c.useState(null),f=c.useRef(null),[p,g]=c.useState(new Set),[b,h]=c.useState(()=>new Map),j=c.useRef(new Set),y=c.useMemo(()=>ds(),[]),[x,v]=c.useState(new Set),[N,w]=c.useState(new Map),[k,D]=c.useState(new Set),[M,C]=c.useState(null),[S,A]=c.useState(null),[E,R]=c.useState(new Set),_=c.useRef(new Map),P=c.useRef(0),O=dt(Z=>Z.homeDirectory),J=dt(Z=>Z.currentDirectory),K=dt(Z=>Z.setDirectory),L=Ft(Z=>Z.projects),G=Ft(Z=>Z.activeProjectId),B=Ft(Z=>Z.addProject),H=Ft(Z=>Z.removeProject),V=Ft(Z=>Z.setActiveProject),oe=Ft(Z=>Z.setActiveProjectIdOnly),se=Ft(Z=>Z.reorderProjects),Y=$e(Z=>Z.setActiveMainTab),le=$e(Z=>Z.setSessionSwitcherOpen),I=$e(Z=>Z.openMultiRunLauncher),W=st(Z=>Z.settingsAutoCreateWorktree),F=ue(Z=>Z.sessions),$=ue(Z=>Z.sessionsByDirectory),z=ue(Z=>Z.currentSessionId),X=ue(Z=>Z.setCurrentSession),fe=ue(Z=>Z.updateSessionTitle),ve=ue(Z=>Z.shareSession),ge=ue(Z=>Z.unshareSession),Re=ue(Z=>Z.sessionMemoryState),be=ue(Z=>Z.sessionActivityPhase),Ie=ue(Z=>Z.permissions),U=ue(Z=>Z.worktreeMetadata),Q=ue(Z=>Z.availableWorktreesByProject),te=ue(Z=>Z.getSessionsByDirectory),pe=ue(Z=>Z.openNewSessionDraft),[me,Me]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),Se=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{try{const Z=y.getItem(_c);if(Z){const de=JSON.parse(Z);Array.isArray(de)&&g(new Set(de.filter(Oe=>typeof Oe=="string")))}const xe=y.getItem(Rc);if(xe){const de=JSON.parse(xe);Array.isArray(de)&&v(new Set(de.filter(Oe=>typeof Oe=="string")))}}catch{}},[y]),c.useEffect(()=>{typeof window>"u"||Me(typeof window.opencodeDesktop<"u")},[]);const Pe=c.useMemo(()=>[...F].sort((Z,xe)=>(xe.time?.created||0)-(Z.time?.created||0)),[F]);c.useEffect(()=>{let Z=!1;const xe=L.map(de=>({id:de.id,path:Xs(de.path)})).filter(de=>!!de.path);return w(new Map),xe.length===0?()=>{Z=!0}:(xe.forEach(de=>{sn(de.path).then(Oe=>{Z||w(We=>{const Xe=new Map(We);return Xe.set(de.id,Oe),Xe})}).catch(()=>{Z||w(Oe=>{const We=new Map(Oe);return We.set(de.id,null),We})})}),()=>{Z=!0})},[L]);const q=c.useMemo(()=>{const Z=new Map;return Pe.forEach(xe=>{const de=xe.parentID;de&&Z.set(xe.id,de)}),Z},[Pe]),re=c.useMemo(()=>{const Z=new Map;return Pe.forEach(xe=>{const de=xe.parentID;if(!de)return;const Oe=Z.get(de)??[];Oe.push(xe),Z.set(de,Oe)}),Z.forEach(xe=>xe.sort((de,Oe)=>(Oe.time?.created||0)-(de.time?.created||0))),Z},[Pe]);c.useEffect(()=>{z&&g(Z=>{const xe=new Set(Z);let de=q.get(z)||null,Oe=!1;for(;de;)xe.has(de)||(xe.add(de),Oe=!0),de=q.get(de)||null;return Oe?xe:Z})},[z,q]),c.useEffect(()=>{const Z=new Set;Pe.forEach(xe=>{const de=Xs(xe.directory??null);de&&Z.add(de)}),L.forEach(xe=>{const de=Xs(xe.path);de&&Z.add(de)}),Z.forEach(xe=>{const de=b.get(xe);de&&de!=="unknown"||j.current.has(xe)||(j.current.add(xe),ke.listLocalDirectory(xe).then(()=>{h(Oe=>{const We=new Map(Oe);return We.get(xe)==="exists"?Oe:(We.set(xe,"exists"),We)})}).catch(()=>{h(Oe=>{const We=new Map(Oe);return We.get(xe)==="missing"?Oe:(We.set(xe,"missing"),We)})}).finally(()=>{j.current.delete(xe)}))})},[Pe,L,b]),c.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const Ve=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."})]}),he=c.useCallback((Z,xe,de,Oe)=>{if(!de){if(Oe&&Oe!==G&&oe(Oe),xe&&xe!==J&&K(xe,{showOverlay:!1}),s&&(Y("chat"),le(!1)),!t&&Z===z){r?.(Z);return}X(Z),r?.(Z)}},[G,t,J,z,s,r,Y,oe,X,K,le]),ye=c.useCallback(async()=>{a&&l.trim()&&(await fe(a,l.trim()),i(null),d(""))},[a,l,fe]),Le=c.useCallback(()=>{i(null),d("")},[]),Qe=c.useCallback(async Z=>{const xe=await ve(Z.id);xe&&xe.share?.url?ne.success("Session shared",{description:"You can copy the link from the menu."}):ne.error("Unable to share session")},[ve]),Ee=c.useCallback((Z,xe)=>{navigator.clipboard.writeText(Z).then(()=>{m(xe),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{ne.error("Failed to copy URL")})},[]),Te=c.useCallback(async Z=>{await ge(Z)?ne.success("Session unshared"):ne.error("Unable to unshare session")},[ge]),Ye=c.useCallback(Z=>{const xe=[],de=Oe=>{(re.get(Oe)??[]).forEach(Xe=>{xe.push(Xe),de(Xe.id)})};return de(Z),xe},[re]),jt=ue(Z=>Z.deleteSession),ft=ue(Z=>Z.deleteSessions),It=c.useCallback(async Z=>{const xe=Ye(Z.id),de=U.get(Z.id);if(de){const Oe=de.path,We=[],Xe=new Set;F.forEach(Ct=>{const xt=U.get(Ct.id);xt&&xt.path===Oe&&!Xe.has(Ct.id)&&(We.push(Ct),Xe.add(Ct.id),Ye(Ct.id).forEach(At=>{Xe.has(At.id)||(We.push(At),Xe.add(At.id))}))}),Cn.requestDelete({sessions:We,mode:"worktree",worktree:de});return}if(xe.length===0)await jt(Z.id)?ne.success("Session deleted"):ne.error("Failed to delete session");else{const Oe=[Z.id,...xe.map(Ct=>Ct.id)],{deletedIds:We,failedIds:Xe}=await ft(Oe);We.length>0&&ne.success(`Deleted ${We.length} session${We.length===1?"":"s"}`),Xe.length>0&&ne.error(`Failed to delete ${Xe.length} session${Xe.length===1?"":"s"}`)}},[Ye,jt,ft,U,F]),_t=c.useCallback(()=>{me&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(Z=>{Z.success&&Z.path?B(Z.path,{id:Z.projectId})||ne.error("Failed to add project",{description:"Please select a valid directory."}):Z.error&&Z.error!=="Directory selection cancelled"&&ne.error("Failed to select directory",{description:Z.error})}).catch(Z=>{console.error("Desktop: Error selecting directory:",Z),ne.error("Failed to select directory")}):Cn.requestDirectoryDialog()},[B,me]),Nt=c.useCallback(Z=>{g(xe=>{const de=new Set(xe);de.has(Z)?de.delete(Z):de.add(Z);try{y.setItem(_c,JSON.stringify(Array.from(de)))}catch{}return de})},[y]),je=c.useCallback(Z=>{const xe=re.get(Z.id)??[];return{session:Z,children:xe.map(de=>je(de)),worktree:U.get(Z.id)??null}},[re,U]),_e=c.useCallback((Z,xe,de)=>{const Oe=Xs(xe??null),We=[...Z].sort((Be,Ke)=>(Ke.time?.created||0)-(Be.time?.created||0)),Xe=new Map(We.map(Be=>[Be.id,Be])),Ct=new Map;We.forEach(Be=>{const Ke=Be.parentID;if(!Ke)return;const wt=Ct.get(Ke)??[];wt.push(Be),Ct.set(Ke,wt)}),Ct.forEach(Be=>Be.sort((Ke,wt)=>(wt.time?.created||0)-(Ke.time?.created||0)));const xt=new Map;de.forEach(Be=>{if(Be.path){const Ke=Xs(Be.path)??Be.path;xt.set(Ke,Be)}});const Pt=Be=>{const Ke=Xs(Be.directory??null),wt=U.get(Be.id)??null;if(wt)return wt;if(Ke){const Lt=xt.get(Ke)??null;if(Lt&&Ke!==Oe)return Lt}return null},At=Be=>{const Ke=Ct.get(Be.id)??[];return{session:Be,children:Ke.map(wt=>At(wt)),worktree:Pt(Be)}},et=We.filter(Be=>{const Ke=Be.parentID;return Ke?!Xe.has(Ke):!0}).map(Be=>At(Be));return[{id:"all",label:"All sessions",description:Oe?Hr(Oe,O):null,isMain:!0,worktree:null,directory:Oe,sessions:et}]},[O,U]),Ge=c.useCallback(Z=>{D(xe=>{const de=new Set(xe);return de.has(Z)?de.delete(Z):de.add(Z),de})},[]),at=c.useCallback(Z=>{P.current=Date.now()+150,v(xe=>{const de=new Set(xe);de.has(Z)?de.delete(Z):de.add(Z);try{y.setItem(Rc,JSON.stringify(Array.from(de)))}catch{}return de})},[y]),Mt=c.useMemo(()=>L.map(Z=>({...Z,normalizedPath:Xs(Z.path)})).filter(Z=>!!Z.normalizedPath),[L]),Yt=c.useCallback(Z=>{const xe=Se?[]:Q.get(Z.normalizedPath)??[],de=[Z.normalizedPath,...xe.map(Xe=>Xs(Xe.path)??Xe.path).filter(Xe=>!!Xe)],Oe=new Set,We=[];return de.forEach(Xe=>{($.get(Xe)??te(Xe)).forEach(xt=>{Oe.has(xt.id)||(Oe.add(xt.id),We.push(xt))})}),We},[Q,te,$,Se]),Jt=c.useMemo(()=>Mt.map(Z=>{const xe=Yt(Z),de=Q.get(Z.normalizedPath)??[],Oe=_e(xe,Z.normalizedPath,de);return{project:Z,groups:Oe}}),[Mt,Yt,_e,Q]);c.useEffect(()=>{if(!me)return;const Z=new IntersectionObserver(xe=>{xe.forEach(de=>{const Oe=de.target.dataset.projectId;Oe&&R(We=>{const Xe=new Set(We);return de.isIntersecting?Xe.delete(Oe):Xe.add(Oe),Xe})})},{threshold:0});return _.current.forEach(xe=>{xe&&Z.observe(xe)}),()=>Z.disconnect()},[me,Jt]);const Ue=c.useCallback((Z,xe=0,de,Oe)=>{const We=Z.session,Xe=Xs(We.directory??null)??Xs(de??null),xt=(Xe?b.get(Xe):null)==="missing",Pt=Re.get(We.id),At=z===We.id,Fe=We.title||"Untitled Session",et=Z.children.length>0,Be=p.has(We.id),Ke=We.summary?.additions,wt=We.summary?.deletions,Lt=typeof Ke=="number"||typeof wt=="number";if(a===We.id)return e.jsx("div",{className:T("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",xe>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsxs("form",{className:"flex w-full items-center gap-2","data-keyboard-avoid":"true",onSubmit:Ot=>{Ot.preventDefault(),ye()},children:[e.jsx("input",{value:l,onChange:Ot=>d(Ot.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename session",onKeyDown:Ot=>{Ot.key==="Escape"&&Le()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Tt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Le,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Wt,{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:[et?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Be?e.jsx(Et,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Oc(We.time?.created||Date.now())}),We.share?e.jsx(Ca,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Lt&&((Ke??0)!==0||(wt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Ke??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,wt??0)]})]}):null,et?e.jsxs("span",{className:"truncate",children:[Z.children.length," ",Z.children.length===1?"task":"tasks"]}):null]})]})},We.id);const ts=be?.get(We.id)??"idle",es=ts==="busy"||ts==="cooldown",ps=Ie.get(We.id)?.length??0,lr=Pt&&Pt.isZombie?e.jsx(gi,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(c.Fragment,{children:[e.jsx("div",{className:T("group relative flex items-center rounded-md px-1.5 py-1",At?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",xt?"opacity-75":"",xe>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:xt,onClick:()=>he(We.id,Xe,xt,Oe),className:T("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("span",{className:T("truncate typography-ui-label font-normal text-foreground",es&&"animate-pulse [animation-duration:1.8s]"),children:Fe}),ps>0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:"Permission required","aria-label":"Permission required",children:[e.jsx(pp,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:ps})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[et?e.jsx("span",{role:"button",tabIndex:0,onClick:Ot=>{Ot.stopPropagation(),Nt(We.id)},onKeyDown:Ot=>{(Ot.key==="Enter"||Ot.key===" ")&&(Ot.preventDefault(),Ot.stopPropagation(),Nt(We.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":Be?"Collapse subsessions":"Expand subsessions",children:Be?e.jsx(Et,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Oc(We.time?.created||Date.now())}),We.share?e.jsx(Ca,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Z.worktree?e.jsxs(nt,{delayDuration:700,children:[e.jsx(ot,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx($t,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(rt,{side:"top",className:"text-xs",children:Z.worktree.branch||Z.worktree.label||"Worktree"})]}):null,Lt&&((Ke??0)!==0||(wt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Ke??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,wt??0)]})]}):null,et?e.jsxs("span",{className:"truncate",children:[Z.children.length," ",Z.children.length===1?"task":"tasks"]}):null,xt?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(gi,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[lr,e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:T("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:Ot=>Ot.stopPropagation(),onKeyDown:Ot=>Ot.stopPropagation(),children:e.jsx(Ir,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(kt,{onClick:()=>{i(We.id),d(Fe)},className:"[&>svg]:mr-1",children:[e.jsx(mr,{className:"mr-1 h-4 w-4"}),"Rename"]}),We.share?e.jsxs(e.Fragment,{children:[e.jsx(kt,{onClick:()=>{We.share?.url&&Ee(We.share.url,We.id)},className:"[&>svg]:mr-1",children:u===We.id?e.jsxs(e.Fragment,{children:[e.jsx(Tt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Gs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(kt,{onClick:()=>Te(We.id),className:"[&>svg]:mr-1",children:[e.jsx(hp,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(kt,{onClick:()=>Qe(We),className:"[&>svg]:mr-1",children:[e.jsx(Ca,{className:"mr-1 h-4 w-4"}),"Share"]}),Z.worktree?e.jsxs(kt,{onClick:()=>{Oe&&Oe!==G&&V(Oe),Y("chat"),s&&le(!1),pe({directoryOverride:Z.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx($t,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(kt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>It(We),children:[e.jsx(qs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),et&&Be?Z.children.map(Ot=>Ue(Ot,xe+1,Xe??de,Oe)):null]},We.id)},[b,Re,be,Ie,z,p,a,l,ye,Le,Nt,he,Qe,Ee,Te,It,u,s,G,V,Y,le,pe]),Ze=c.useCallback((Z,xe,de)=>{const Oe=k.has(xe),We=n?10:5,Xe=Z.sessions.length,Ct=Oe?Z.sessions:Z.sessions.slice(0,We),xt=Xe-Ct.length;return e.jsxs(e.Fragment,{children:[Ct.map(Pt=>Ue(Pt,0,Z.directory,de)),Xe===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,xt>0&&!Oe?e.jsxs("button",{type:"button",onClick:()=>Ge(xe),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",xt," more ",xt===1?"session":"sessions"]}):null,Oe&&Xe>We?e.jsx("button",{type:"button",onClick:()=>Ge(xe),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})},[k,n,Ue,Ge]),ut=gp(_l(Np,{activationConstraint:{distance:8}}),_l(kp,{coordinateGetter:Sp})),tt=c.useCallback(Z=>{A(Z.active.id)},[]),ct=c.useCallback(Z=>{const{active:xe,over:de}=Z;if(A(null),!de||xe.id===de.id)return;const Oe=Mt.findIndex(Xe=>Xe.id===xe.id),We=Mt.findIndex(Xe=>Xe.id===de.id);Oe!==-1&&We!==-1&&se(Oe,We)},[Mt,se]),it=c.useCallback(()=>{A(null)},[]),St=c.useMemo(()=>{if(!S)return null;const Z=Jt.find(de=>de.project.id===S);if(!Z)return null;const xe=Z.project;return{id:xe.id,label:$c(xe.label?.trim()||$l(xe.normalizedPath,O)||xe.normalizedPath),isActive:xe.id===G}},[S,Jt,O,G]);return e.jsxs("div",{className:T("flex h-full flex-col text-foreground overflow-x-hidden",s?"":me?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-8 select-none pl-3.5 pr-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("p",{className:"typography-ui-label font-medium text-muted-foreground",children:"Projects"}),e.jsx("span",{className:"typography-micro text-muted-foreground/50",children:L.length})]}),e.jsx("button",{type:"button",onClick:_t,className:T("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!me&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(xp,{className:"h-4.5 w-4.5"})})]})}),e.jsx(mt,{outerClassName:"flex-1 min-h-0",className:T("space-y-1 pb-1 pl-2.5 pr-1",""),children:Jt.length===0?Ve:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const Z=Jt.find(Oe=>Oe.project.id===G)??Jt[0];if(!Z)return Ve;const xe=Z.groups.find(Oe=>Oe.isMain&&Oe.sessions.length>0)??Z.groups.find(Oe=>Oe.sessions.length>0)??Z.groups.find(Oe=>Oe.isMain)??Z.groups[0];if(!xe)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const de=`${Z.project.id}:${xe.id}`;return Ze(xe,de,Z.project.id)})()}):e.jsxs(yp,{sensors:ut,collisionDetection:bp,onDragStart:tt,onDragEnd:ct,onDragCancel:it,children:[e.jsx(wp,{items:Mt.map(Z=>Z.id),strategy:vp,children:Jt.map(Z=>{const xe=Z.project,de=xe.id,Oe=$c(xe.label?.trim()||$l(xe.normalizedPath,O)||xe.normalizedPath),We=Hr(xe.normalizedPath,O),Xe=x.has(de),Ct=de===G,xt=N.get(de),Pt=M===de;return e.jsx(db,{id:de,projectLabel:Oe,projectDescription:We,isCollapsed:Xe,isActiveProject:Ct,isRepo:!!xt,isHovered:Pt,isDesktopRuntime:me,isStuck:E.has(de),hideDirectoryControls:n,mobileVariant:s,onToggle:()=>at(de),onHoverChange:At=>C(At?de:null),onNewSession:()=>{de!==G&&V(de),Y("chat"),s&&le(!1),W&&xt?ha():pe({directoryOverride:xe.normalizedPath})},onOpenMultiRunLauncher:()=>{de!==G&&V(de),I()},onClose:()=>H(de),sentinelRef:At=>{_.current.set(de,At)},children:Xe?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:Z.groups[0]?Ze(Z.groups[0],`${de}:all`,de):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},de)})}),e.jsx(jp,{children:St?e.jsx(ub,{projectLabel:St.label,isActiveProject:St.isActive}):null})]})})]})};function ht({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:T("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",s),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...t})}const ga=()=>{const[s,r]=Ce.useState(!1);Ce.useEffect(()=>{r(as())},[]);const t=Ce.useCallback(async a=>s?await Gh(a):{success:!0,path:a},[s]),n=Ce.useCallback(async a=>s?await qh(a):{success:!0},[s]),o=Ce.useCallback(async a=>s?await Kh(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},Lc=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:l=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=c.useMemo(()=>as(),[]),{isMobile:p}=Rt(),[g,b]=c.useState([]),[h,j]=c.useState(new Set),[y,x]=c.useState(!0),[v,N]=c.useState(!1),[w,k]=c.useState(""),[D,M]=c.useState(new Set),[C,S]=c.useState(null),[A,E]=c.useState(""),[R,_]=c.useState(!0),P=c.useRef(null),{requestAccess:O,startAccessing:J,isDesktop:K}=ga(),L=c.useRef(l),G=c.useCallback(U=>{if(!U)return U;if(U==="/"||U.length===0)return"/";let Q=U;for(;Q.length>1&&Q.endsWith("/");)Q=Q.slice(0,-1);return Q.length===0?"/":Q},[]),B=c.useMemo(()=>{if(!w)return null;const U=w.replace(/\\/g,"/");return G(U)},[w,G]),H=c.useMemo(()=>{if(typeof d=="string"&&d.length>0){const U=d.replace(/\\/g,"/"),Q=G(U);if(Q&&Q!=="/")return Q}return B&&B!=="/"?B:null},[d,B,G]),V=c.useMemo(()=>typeof u=="boolean"?!!(u&&H):!!H,[u,H]);c.useEffect(()=>{V||(x(!0),b([]))},[V]);const oe=c.useCallback(U=>{if(!U||!V||!H)return!1;const Q=U.replace(/\\/g,"/"),te=G(Q)??Q;if(te===H)return!0;const pe=`${H}/`;return te.startsWith(pe)},[V,H,G]),se=async U=>{if(V){if(a==="deferred"){r(U);return}if(K){const Q=await O(U);Q.success&&Q.path?(await J(Q.path),r(Q.path)):(console.error("Failed to get directory access:",Q.error),r(U))}else r(U)}};c.useEffect(()=>{let U=!1;const Q=me=>{if(!me)return!1;const Me=G(me.replace(/\\/g,"/"));return!Me||Me==="/"?!1:(k(typeof Me=="string"?Me:me.replace(/\\/g,"/")),!0)};return d&&Q(d)||(async()=>{try{const me=await ke.getFilesystemHome();if(!U&&Q(me))return}catch(me){console.warn("Failed to resolve filesystem home directory:",me)}try{const me=await ke.getSystemInfo();if(!U&&Q(me?.homeDirectory))return}catch(me){console.warn("Failed to resolve home directory from system info:",me)}})(),()=>{U=!0}},[d,G]),c.useEffect(()=>{let U=!1;const Q=Me=>{if(U)return;const Se=Me.filter(Pe=>typeof Pe=="string"&&Pe.length>0).map(Pe=>{const q=Pe.replace(/\\/g,"/");return G(q)??q});M(new Set(Se))},te=()=>{try{const Me=localStorage.getItem("pinnedDirectories");if(!Me)return;const Se=JSON.parse(Me);Array.isArray(Se)&&Q(Se)}catch(Me){console.warn("Failed to load pinned directories from local storage:",Me)}},pe=async()=>{try{let Me=[];if(f){const Se=await En();Me=Array.isArray(Se?.pinnedDirectories)?Se.pinnedDirectories:[]}else{const Se=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(Se.ok){const Pe=await Se.json();Me=Array.isArray(Pe?.pinnedDirectories)?Pe.pinnedDirectories:[]}}if(U)return;Q(Me)}catch(Me){console.warn("Failed to load pinned directories:",Me)}};te();const me=Me=>{const Se=Me.detail;Se&&Array.isArray(Se.pinnedDirectories)&&Q(Se.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",me),pe(),()=>{U=!0,window.removeEventListener("openchamber:settings-synced",me)}},[f,G]);const Y=c.useRef(!0);c.useEffect(()=>{if(Y.current){Y.current=!1;return}const U={pinnedDirectories:Array.from(D)};os(U)},[D]),c.useEffect(()=>{H&&M(U=>{const Q=Array.from(U).map(te=>G(te.replace(/\\/g,"/"))??te).filter(te=>oe(te));return new Set(Q)})},[H,oe,G]),c.useEffect(()=>{L.current!==l&&(L.current=l)},[l]);const le=U=>{M(Q=>{if(!oe(U))return Q;const te=G(U.replace(/\\/g,"/"))??U.replace(/\\/g,"/"),pe=new Set(Q);return pe.has(te)?pe.delete(te):pe.add(te),pe})},I=c.useMemo(()=>Array.from(D).map(U=>G(U.replace(/\\/g,"/"))??U).filter(U=>oe(U)).map(U=>({path:U,name:U.split("/").pop()||U})).sort((U,Q)=>U.name.localeCompare(Q.name)),[D,oe,G]),W=c.useCallback(async U=>{const Q=Se=>l||!Se.startsWith("."),te=H;if(!V||!te)return[];const pe=U&&U.length>0?U:te,me=pe?pe.replace(/\\/g,"/"):null,Me=me?G(me)??me:null;if(Me){const Se=`${te}/`;if(!(Me===te||Me.startsWith(Se)))return[]}try{return(await ke.listLocalDirectory(U)).filter(Pe=>{if(!Pe.isDirectory||!Q(Pe.name))return!1;const q=Pe.path.replace(/\\/g,"/"),re=G(q)??q,Ve=re===te?te:`${te}/`;return re===te||re.startsWith(Ve)}).map(Pe=>({name:Pe.name,path:Pe.path.replace(/\\/g,"/"),isDirectory:!0})).sort((Pe,q)=>Pe.name.localeCompare(q.name))}catch{try{const Pe=await ke.getApiClient().file.list({path:".",directory:U});return Pe.data?Pe.data.filter(q=>{if(q.type!=="directory"||!q.name||!Q(q.name))return!1;const re=String(q.absolute||q.path||q.name).replace(/\\/g,"/"),Ve=G(re)??re,he=Ve===te?te:`${te}/`;return Ve===te||Ve.startsWith(he)}).map(q=>({name:q.name||"",path:String(q.absolute||q.path||q.name).replace(/\\/g,"/"),isDirectory:!0})).filter(q=>q.name!=="").sort((q,re)=>q.name.localeCompare(re.name)):[]}catch{return[]}}},[l,H,G,V]),F=c.useRef(!1),$=c.useCallback(async()=>{if(!V||!H){x(!0),b([]);return}F.current||x(!0);try{const U=await W(H);b(U),F.current=!0}catch{}finally{x(!1)}},[V,H,W]);c.useEffect(()=>{V&&(n==="inline"||v)&&$()},[n,v,V,$]);const z=async U=>{if(!V)return;const Q=h.has(U.path),te=new Set(h);if(Q){te.delete(U.path),j(te);return}te.add(U.path),j(te);const pe=await W(U.path),me=Me=>Me.map(Se=>Se.path===U.path?{...Se,children:pe}:Se.children?{...Se,children:me(Se.children)}:Se);b(Me=>me(Me))};c.useEffect(()=>{C&&P.current&&(P.current.focus(),P.current.select())},[C]);const X=(U,Q=[])=>{const te="new_directory",pe=Q.map(Pe=>Pe.name);if(!pe.includes(te))return te;let me=1;const Me=new RegExp(`^${te}(\\d+)$`);for(const Pe of pe){const q=Pe.match(Me);if(q){const re=parseInt(q[1],10);re>me&&(me=re)}}let Se=2;for(;pe.includes(`${te}${Se}`);)Se++;return`${te}${Math.max(Se,me+1)}`},fe=async U=>{if(V){if(h.has(U.path)){const Q=X(U.path,U.children);E(Q)}else{const Q=new Set(h);if(Q.add(U.path),j(Q),U.children){const te=X(U.path,U.children);E(te)}else{const te=await W(U.path),pe=Me=>Me.map(Se=>Se.path===U.path?{...Se,children:te}:Se.children?{...Se,children:pe(Se.children)}:Se);b(Me=>pe(Me));const me=X(U.path,te);E(me)}}S(U.path)}},ve=async()=>{if(!C||!V)return;const U=A.trim()||"new_directory",Q=`${C}/${U}`;try{await ke.createDirectory(Q);const te=await W(C),pe=me=>me.map(Me=>Me.path===C?{...Me,children:te}:Me.children?{...Me,children:pe(Me.children)}:Me);b(me=>pe(me)),S(null),E("")}catch(te){console.error("Failed to create directory:",te)}},ge=()=>{S(null),E("")},Re=(U,Q=0)=>{const te=h.has(U.path),pe=U.isDirectory,me=D.has(U.path),Me=s===U.path,Se=n==="inline",Pe=e.jsxs(e.Fragment,{children:[pe&&e.jsx("button",{onClick:q=>{q.stopPropagation(),z(U)},className:T("hover:bg-accent rounded","p-0.5"),children:te?e.jsx(Et,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Us,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!pe&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:q=>{q.stopPropagation(),se(U.path),n==="dropdown"&&a==="immediate"&&N(!1)},onDoubleClick:q=>{q.stopPropagation(),i&&i(U.path)},className:T("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",Se&&Me?"text-primary":"text-foreground"),children:[e.jsx(ur,{className:T("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",Se&&Me&&"text-primary")}),e.jsx("span",{className:T("font-medium truncate","typography-ui-label",Se&&Me?"text-primary":"text-foreground"),children:U.name})]}),e.jsx("button",{onClick:q=>{q.stopPropagation(),fe(U)},className:T("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(qt,{className:T("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:q=>{q.stopPropagation(),le(U.path)},className:T("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:me?"Unpin directory":"Pin directory",children:me?e.jsx(Ma,{className:T("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Mp,{className:T("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:T("group flex items-center gap-1 rounded-lg mx-1 text-left transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",Me?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${Q*(p?12:14)+(p?4:6)}px`},children:Pe}),te&&e.jsxs(e.Fragment,{children:[C===U.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(Q+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{ref:P,value:A,onChange:q=>E(q.target.value),onKeyDown:q=>{q.key==="Enter"?(q.preventDefault(),q.stopPropagation(),ve()):q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),ge())},onBlur:ve,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(),ve()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Tt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),ge()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"})})]}),U.children&&U.children.map(q=>Re(q,Q+1))]})]},U.path):e.jsxs("div",{children:[e.jsxs(kt,{className:T("flex items-center gap-1 cursor-pointer group",s===U.path&&"bg-accent"),style:{paddingLeft:`${Q*12+8}px`},onSelect:q=>{q.preventDefault()},children:[pe&&e.jsx("button",{onClick:q=>{q.stopPropagation(),z(U)},className:"p-0.5 hover:bg-accent rounded",children:te?e.jsx(Et,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}),!pe&&e.jsx("div",{className:"w-4"}),Pe]}),te&&e.jsxs("div",{children:[C===U.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(Q+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{ref:P,value:A,onChange:q=>E(q.target.value),onKeyDown:q=>{q.key==="Enter"?(q.preventDefault(),q.stopPropagation(),ve()):q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),ge())},onBlur:ve,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(),ve()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Tt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:q=>{q.preventDefault(),q.stopPropagation(),ge()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Wt,{className:"h-3 w-3 text-muted-foreground"})})]}),U.children&&U.children.map(q=>Re(q,Q+1))]})]},U.path)},be=(U,Q)=>{if(n==="inline"){const te=s===Q;return e.jsxs("div",{className:T("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",te?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>se(Q),onDoubleClick:pe=>{pe.stopPropagation(),i&&i(Q)},className:T("flex flex-1 items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded min-w-0",te?"text-primary":"text-foreground"),children:[e.jsx(ur,{className:T("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",te?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:T("typography-ui-label font-medium truncate flex-shrink-0",te?"text-primary":"text-foreground"),children:U}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:Hr(Q,w)})]}),e.jsx("button",{onClick:()=>le(Q),className:T("hover:bg-accent rounded-md transition-opacity",p?"p-1.5 opacity-60":"p-1 opacity-0 group-hover:opacity-100"),title:"Unpin directory",children:e.jsx(Ma,{className:T("text-primary","h-3.5 w-3.5")})})]},Q)}return e.jsxs(kt,{onSelect:te=>{te.preventDefault(),se(Q),a==="immediate"&&N(!1)},className:T("flex items-start gap-2 cursor-pointer group py-2",s===Q&&"bg-accent"),children:[e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium",children:U}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Hr(Q,w)})]}),e.jsx("button",{onClick:te=>{te.stopPropagation(),te.preventDefault(),le(Q)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Ma,{className:"h-3 w-3 text-primary"})})]},Q)},Ie=e.jsx(e.Fragment,{children:V?e.jsxs(e.Fragment,{children:[I.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>_(U=>!U),className:T("flex w-full items-center gap-1.5 typography-meta font-medium text-muted-foreground/80 hover:bg-accent/30 rounded transition-colors uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:[R?e.jsx(Et,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Us,{className:p?"h-3.5 w-3.5":"h-3 w-3"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/60 normal-case tracking-normal",children:I.length})]}),R&&I.map(({name:U,path:Q})=>be(U,Q)),n==="dropdown"&&e.jsx(Ms,{}),n==="inline"&&R&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:T("typography-meta font-medium text-muted-foreground/80 flex items-center gap-1.5 uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:"Browse"}),y?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):g.map(U=>Re(U)),!y&&g.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:T("overflow-hidden flex flex-col",o),children:e.jsx(mt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:Ie})}):e.jsxs(Ut,{open:v,onOpenChange:N,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",className:T("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",t),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(ur,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:Hr(s,w)})]}),e.jsx(Et,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Gt,{align:"start",className:"w-[350px]",children:e.jsx(mt,{outerClassName:"h-full",className:"w-full",children:Ie})})]})},yl=(s,r=200)=>{const[t,n]=Ce.useState(s);return Ce.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},wm=c.forwardRef(({inputValue:s,homeDirectory:r,onSelectSuggestion:t,visible:n,onClose:o,showHidden:a},i)=>{const[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(0),g=c.useRef(null),b=c.useRef([]),h=c.useCallback((w,k)=>{const D=w.trim().toLowerCase();if(!D)return 0;const M=k.toLowerCase();let C=0,S=-1,A=0;for(let E=0;E<D.length;E+=1){const R=D[E];if(!R||R===" ")continue;const _=M.indexOf(R,S+1);if(_===-1)return null;const P=_-S-1;if(P===0?A+=1:A=0,C+=10,C+=Math.max(0,18-_),C-=Math.max(0,P),_===0)C+=12;else{const O=M[_-1];(O==="/"||O==="_"||O==="-"||O==="."||O===" ")&&(C+=10)}C+=A>0?12:0,S=_}return C+=Math.max(0,24-Math.round(M.length/3)),C},[]),j=c.useCallback(w=>w.startsWith("~")&&r?w.replace(/^~/,r):w,[r]),y=c.useCallback(w=>{const k=j(w);if(k.endsWith("/"))return k;const D=k.lastIndexOf("/");return D===-1?"":D===0?"/":k.substring(0,D+1)},[j]),x=c.useCallback(w=>{const k=j(w);if(k.endsWith("/"))return"";const D=k.lastIndexOf("/");return D===-1?k:k.substring(D+1)},[j]),v=yl(s,150);c.useEffect(()=>{if(!n||!v){d([]);return}const w=y(v),k=x(v).toLowerCase();if(!w){d([]);return}let D=!1;return m(!0),ke.listLocalDirectory(w).then(M=>{if(D)return;const C=M.filter(A=>!(!A.isDirectory||!a&&A.name.startsWith("."))),S=k?C.map(A=>{const E=h(k,A.name);return E!==null?{entry:A,score:E}:null}).filter(A=>A!==null).sort((A,E)=>E.score-A.score||A.entry.name.localeCompare(E.entry.name)).map(A=>A.entry):C.sort((A,E)=>A.name.localeCompare(E.name));d(S.slice(0,10)),p(0)}).catch(()=>{D||d([])}).finally(()=>{D||m(!1)}),()=>{D=!0}},[n,v,y,x,a,h]),c.useEffect(()=>{b.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),c.useEffect(()=>{if(!n)return;const w=k=>{const D=k.target;!D||!g.current||g.current.contains(D)||o()};return document.addEventListener("pointerdown",w,!0),()=>{document.removeEventListener("pointerdown",w,!0)}},[n,o]);const N=c.useCallback(w=>{const k=w.path.endsWith("/")?w.path:w.path+"/";t(k)},[t]);return c.useImperativeHandle(i,()=>({handleKeyDown:w=>{if(!n||l.length===0)return!1;const k=l.length;if(w.key==="Tab"){if(w.preventDefault(),w.shiftKey)p(D=>(D-1+k)%k);else if(k===1){const D=l[0];D&&N(D)}else p(D=>(D+1)%k);return!0}if(w.key==="ArrowDown")return w.preventDefault(),p(D=>(D+1)%k),!0;if(w.key==="ArrowUp")return w.preventDefault(),p(D=>(D-1+k)%k),!0;if(w.key==="Enter"){w.preventDefault();const D=(f%k+k)%k,M=l[D];return M&&N(M),o(),!0}return w.key==="Escape"?(w.preventDefault(),o(),!0):!1}}),[n,l,f,N,o]),!n||l.length===0&&!u?null:e.jsxs("div",{ref:g,className:"absolute z-[100] w-full max-h-48 bg-background border border-border rounded-lg shadow-lg top-full mt-1 left-0 flex flex-col overflow-hidden",children:[u?e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(Dr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:l.map((w,k)=>{const D=f===k;return e.jsxs("div",{ref:M=>{b.current[k]=M},className:T("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",D&&"bg-muted"),onClick:()=>{N(w),o()},onMouseEnter:()=>p(k),children:[e.jsx(ir,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:w.name})]},w.path)})}),e.jsx("div",{className:"px-3 py-1.5 border-t typography-meta text-muted-foreground bg-sidebar/50",children:"Tab cycle • ↑↓ navigate • Enter select"})]})});wm.displayName="DirectoryAutocomplete";const Bc="directoryTreeShowHidden",mb=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,isHomeReady:o}=dt(),{addProject:a,getActiveProject:i}=Ft(),[l,d]=c.useState(null),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,b]=c.useState(!1),[h,j]=c.useState(()=>{if(typeof window>"u")return!1;try{const Y=window.localStorage.getItem(Bc);if(Y==="true")return!0;if(Y==="false")return!1}catch{}return!1}),{isDesktop:y,requestAccess:x,startAccessing:v}=ga(),{isMobile:N}=Rt(),[w,k]=c.useState(!1),D=c.useRef(null),M=c.useCallback(Y=>Y?Hr(Y,n):"",[n]);c.useEffect(()=>{if(s){p(!1),b(!1),k(!1);const le=i()?.path||t||n||"";d(le),m(M(le))}},[s,t,n,M,i]),c.useEffect(()=>{!s||f||l||n&&o&&(d(n),p(!0),m("~"))},[s,f,l,n,o]),c.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Bc,h?"true":"false")}catch{}},[h]);const C=c.useCallback(()=>{r(!1)},[r]),S=c.useCallback(async Y=>{if(!(!Y||g)){b(!0);try{let le=Y,I;if(y){const F=await x(Y);if(!F.success){ne.error("Unable to access directory",{description:F.error||"Desktop denied directory access."});return}le=F.path??Y,I=F.projectId;const $=await v(le);if(!$.success){ne.error("Failed to open directory",{description:$.error||"Desktop could not grant file access."});return}}if(!a(le,{id:I})){ne.error("Failed to add project",{description:"Please select a valid directory path."});return}C()}catch(le){ne.error("Failed to select directory",{description:le instanceof Error?le.message:"Unknown error occurred."})}finally{b(!1)}}},[a,C,y,x,v,g]),A=c.useCallback(async()=>{const Y=u.trim()||l;Y&&await S(Y)},[S,u,l]),E=c.useCallback(Y=>{d(Y),p(!0),m(M(Y))},[M]),R=c.useCallback(async Y=>{d(Y),p(!0),m(M(Y)),await S(Y)},[S,M]),_=c.useCallback(Y=>{const le=Y.target.value;if(m(le),p(!0),k(le.startsWith("/")||le.startsWith("~")),le.startsWith("/")||le.startsWith("~")){const I=le.startsWith("~")&&n?le.replace(/^~/,n):le;d(I)}},[n]),P=c.useCallback(Y=>{D.current?.handleKeyDown(Y)||Y.key==="Enter"&&(Y.preventDefault(),A())},[A]),O=c.useCallback(Y=>{d(Y),p(!0),m(M(Y))},[M]),J=c.useCallback(()=>{k(!1)},[]),K=c.useCallback(()=>{j(Y=>!Y)},[]),L=e.jsxs("button",{type:"button",onClick:K,className:"flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground flex-shrink-0",children:[h?e.jsx(Vi,{className:"h-4 w-4 text-primary"}):e.jsx(Gi,{className:"h-4 w-4"}),"Show hidden"]}),G=e.jsxs(xs,{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(ys,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(Ns,{className:"flex-1",children:"Choose a folder to add as a project."}),L]})]}),B=e.jsxs("div",{className:"relative",children:[e.jsx(ht,{value:u,onChange:_,onKeyDown:P,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(wm,{ref:D,inputValue:u,homeDirectory:n,onSelectSuggestion:O,visible:w,onClose:J,showHidden:h})]}),H=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(Lc,{variant:"inline",currentPath:l??t,onSelectPath:E,onDoubleClickPath:R,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:h,rootDirectory:o?n:null,isRootReady:o})}),V=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:B}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:L}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(Lc,{variant:"inline",currentPath:l??t,onSelectPath:E,onDoubleClickPath:R,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:h,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),oe=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[B,H]}),se=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",onClick:C,disabled:g,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Ne,{onClick:A,disabled:g||!f||!l&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:g?"Adding...":"Add Project"})]});return N?e.jsx(ws,{open:s,onClose:()=>r(!1),title:"Add project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:e.jsx("div",{className:"flex flex-row gap-2",children:se()}),children:V}):e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:T("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:Y=>{Y.preventDefault()},children:[G,oe,e.jsx(Ks,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-4 sm:pb-0",children:se()})]})})},yo=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,fb=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},pb=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=c.useRef(new Set),[a,i]=c.useState(null),[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(!1),{deleteSession:g,deleteSessions:b,loadSessions:h,getWorktreeMetadata:j}=ue(),{currentDirectory:y,homeDirectory:x,isHomeReady:v}=dt(),{projects:N,addProject:w,activeProjectId:k}=Ft(),{requestAccess:D,startAccessing:M}=ga(),{isMobile:C,isTablet:S,hasTouchInput:A}=Rt(),E=C||S||A,R=c.useMemo(()=>{const F=(k?N.find($=>$.id===k)??null:null)?.path??y;return fb(F)},[k,y,N]),_=c.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||l.some(W=>W.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,l]),P=c.useMemo(()=>{const W=a?.worktree;return W&&typeof W.branch=="string"&&W.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:F})=>typeof F.branch=="string"&&F.branch.trim().length>0)},[a?.worktree,l]),O=a?.mode==="worktree",J=O,K=f||!O||!P;c.useEffect(()=>{R&&(o.current.has(R)||mx(R).then(()=>o.current.add(R)).catch(W=>{console.warn("Failed to ensure .openchamber directory is ignored:",W),o.current.delete(R)}))},[R]),c.useEffect(()=>{h()},[h,y]);const L=c.useMemo(()=>N.map(W=>`${W.id}:${W.path}`).join("|"),[N]),G=c.useRef(L);c.useEffect(()=>{L!==G.current&&(G.current=L,h())},[h,L]),c.useEffect(()=>{if(!(t||!v||N.length>0)){if(n(!0),as()){D("").then(async W=>{if(!W.success||!W.path){W.error&&W.error!=="Directory selection cancelled"&&ne.error("Failed to select directory",{description:W.error});return}const F=await M(W.path);if(!F.success){ne.error("Failed to open directory",{description:F.error||"Desktop could not grant file access."});return}w(W.path,{id:W.projectId})||ne.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(W=>{console.error("Desktop: Error selecting directory:",W),ne.error("Failed to select directory")});return}r(!0)}},[w,t,v,N.length,D,M]);const B=c.useCallback(W=>{i({sessions:W.sessions,dateLabel:W.dateLabel,mode:W.mode??"session",worktree:W.worktree??null})},[]),H=c.useCallback(()=>{i(null),d([]),m(!1),p(!1)},[]);c.useEffect(()=>Cn.onDeleteRequest(W=>{B(W)}),[B]),c.useEffect(()=>Cn.onDirectoryRequest(()=>{r(!0)}),[]),c.useEffect(()=>{if(!a){d([]),m(!1);return}const W=a.sessions.map($=>{const z=j($.id);return z?{session:$,metadata:z}:null}).filter($=>!!$);if(d(W),m(!1),W.length===0)return;let F=!1;return(async()=>{const $=await Promise.all(W.map(async({metadata:z})=>{if(z.status&&typeof z.status.isDirty=="boolean")return z.status;try{return await ol(z.path)}catch{return z.status}})).catch(z=>(console.warn("Failed to inspect worktree status before deletion:",z),W.map(({metadata:X})=>X.status)));F||!Array.isArray($)||d(z=>z.map((X,fe)=>({session:X.session,metadata:{...X.metadata,status:$[fe]??X.metadata.status}})))})(),()=>{F=!0}},[a,j]),c.useEffect(()=>{P||m(!1)},[P]);const V=c.useCallback(async()=>{if(a){p(!0);try{const W=J,F=W&&u;if(a.sessions.length===0&&O&&a.worktree){const $=u&&P;await Vu({projectDirectory:R,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:$});const z=$?"Worktree and remote branch removed.":"Worktree removed.";ne.success("Worktree removed",{description:yo(z)}),H(),h();return}if(a.sessions.length===1){const $=a.sessions[0];if(!await g($.id,{archiveWorktree:W,deleteRemoteBranch:F})){ne.error("Failed to delete session"),p(!1);return}const X=W?F?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;ne.success("Session deleted",{description:yo(X)})}else{const $=a.sessions.map(fe=>fe.id),{deletedIds:z,failedIds:X}=await b($,{archiveWorktree:W,deleteRemoteBranch:F});if(z.length>0){const fe=W?F?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,ge=[X.length>0?`${X.length} session${X.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,fe].filter(Boolean).join(" ");ne.success(`Deleted ${z.length} session${z.length===1?"":"s"}`,{description:yo(ge||void 0)})}if(X.length>0&&(ne.error(`Failed to delete ${X.length} session${X.length===1?"":"s"}`,{description:yo("Please try again in a moment.")}),z.length===0)){p(!1);return}}H()}finally{p(!1)}}},[a,u,g,b,H,J,O,P,R,h]),oe=a?.worktree??l[0]?.metadata??null,se=a?a.mode==="worktree"?a.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${a.sessions.length===1?"1 linked session":`${a.sessions.length} linked sessions`}.`:`This action permanently removes ${a.sessions.length===1?"1 session":`${a.sessions.length} sessions`}${a.dateLabel?` from ${a.dateLabel}`:""}.`:"",Y=a?e.jsxs("div",{className:"space-y-2",children:[a.sessions.length>0&&e.jsxs("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[O&&e.jsx("span",{className:"typography-meta font-medium text-foreground",children:a.sessions.length===1?"Linked session":"Linked sessions"}),e.jsxs("ul",{className:"space-y-0.5",children:[a.sessions.slice(0,5).map(W=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:W.title||"Untitled Session"},W.id)),a.sessions.length>5&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",a.sessions.length-5," more"]})]})]}),O?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"}),oe?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:oe.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:oe?Hr(oe.path,x):"Worktree path unavailable."}),_&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),P?e.jsxs("button",{type:"button",onClick:()=>{K||m(W=>!W)},disabled:K,className:T("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",K?"cursor-not-allowed opacity-60":"hover:bg-sidebar/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[e.jsx("span",{className:"mt-0.5 flex size-5 items-center justify-center text-muted-foreground",children:u?e.jsx(Vi,{className:"size-4 text-primary"}):e.jsx(Gi,{className:"size-4"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Delete remote branch"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:u?"Remote branch on origin will also be removed.":"Keep the remote branch intact."})]})]}):e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Remote branch information unavailable for this worktree."})]}):e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,le=e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",onClick:H,disabled:f,children:"Cancel"}),e.jsx(Ne,{variant:"destructive",onClick:V,disabled:f,children:f?"Deleting…":O?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),I=O?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[E?e.jsx(ws,{open:!!a,onClose:()=>{f||H()},title:I,footer:e.jsx("div",{className:"flex justify-end gap-2",children:le}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[se&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:se}),Y]})}):e.jsx(ms,{open:!!a,onOpenChange:W=>{if(!W){if(f)return;H()}},children:e.jsxs(fs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(xs,{children:[e.jsx(ys,{children:I}),se&&e.jsx(Ns,{children:se})]}),Y,e.jsx(Ks,{className:"mt-2 gap-2 pt-1 pb-1",children:le})]})}),e.jsx(mb,{open:s,onOpenChange:r})]})};function hb(){return new Worker(Dp,{type:"module"})}const gb=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function xb(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 zc(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const yb=({children:s})=>{const r=Ep(),t=Xt(l=>l.activeDirectory),n=Xt(l=>t?l.directories.get(t)?.lastStatusChange??0:0),o=Xt(l=>t?l.directories.get(t)?.diffCache.size??0:0),a=Ce.useRef(!1),i=Ce.useRef(new Map);return Ce.useEffect(()=>{if(!r||a.current)return;a.current=!0;const l={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=hi(l,{...l,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Ce.useEffect(()=>{if(!r||!t||!n||o===0)return;const l=Xt.getState().directories.get(t);if(!l||l.diffCache.size===0||(i.current.get(t)??0)>=l.lastStatusChange)return;i.current.set(t,l.lastStatusChange);let u=!1,m=null;const f=Array.from(l.diffCache.entries());let p=0;const g=b=>{if(u)return;const h=Date.now();for(;p<f.length&&!(b&&b.timeRemaining()<8||!b&&Date.now()-h>8);){const[j,y]=f[p];p+=1,rn(j);const x=xb(j,y.original,y.modified),v={name:j,contents:y.original,cacheKey:`old-${x}`},N={name:j,contents:y.modified,cacheKey:`new-${x}`},w=hi(v,N),k={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(k,w)}p<f.length&&(m=zc(g))};return g(void 0),p<f.length&&(m=zc(g)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},bb=({children:s})=>{const t=pa()?.currentTheme?.metadata?.variant==="dark";cm();const n=Ce.useMemo(()=>({theme:{dark:Nn.dark,light:Nn.light},themeType:t?"dark":"light",langs:gb}),[t]);return e.jsx(Ap,{poolOptions:{workerFactory:hb,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(yb,{children:s})})},Ts=Ce.forwardRef(({className:s,...r},t)=>e.jsx(mt,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:T("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",s),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r}));Ts.displayName="Textarea";const xa=Ip,bl=({className:s,...r})=>e.jsx(Pp,{className:T("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}),ya=({className:s,...r})=>e.jsx(Tp,{className:T("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r}),Ii=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),wb=(s,r)=>{const t=Ii(s),n=Ii(r);return`${t}-${n}`.substring(0,60)},Wc=(s,r)=>`${s}/${r}`,vb=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),jb=()=>{const s=Ft.getState(),r=s.activeProjectId,t=r?s.projects.find(l=>l.id===r)?.path:void 0;if(typeof t=="string"&&t.trim().length>0)return t;const n=dt.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,i=o.indexOf("/.openchamber/");return i>0?o.slice(0,i):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},qn=zt()(Kt(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:i,setupCommands:l}=r;if(!t)return s({error:"Group name is required"}),null;if(!n)return s({error:"Prompt is required"}),null;if(o.length<1)return s({error:"Select at least 1 model"}),null;if(o.length>5)return s({error:"Maximum 5 models allowed"}),null;s({isLoading:!0,error:null});try{const d=jb();if(!d)return s({error:"No directory selected",isLoading:!1}),null;if(!await sn(d))return s({error:"Not in a git repository",isLoading:!1}),null;const m=Ii(t),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,g=[],b=l?.filter(w=>w.trim().length>0)??[],h=new Map;for(const w of o){const k=`${w.providerID}:${w.modelID}`;h.set(k,(h.get(k)||0)+1)}const j=new Map;for(const w of o){const k=`${w.providerID}:${w.modelID}`,D=h.get(k)||1,M=(j.get(k)||0)+1;j.set(k,M);const C=wb(w.providerID,w.modelID),S=D>1?Wc(m,`${C}/${M}`):Wc(m,C);if(!S)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const A=vb(S);if(!A)return s({error:`Invalid branch name: ${S}`,isLoading:!1}),null;try{const E=await Uu({projectDirectory:d,worktreeSlug:A,branch:S,createBranch:!0,startPoint:p}),R=D>1?`${m}/${w.providerID}/${w.modelID}/${M}`:`${m}/${w.providerID}/${w.modelID}`,_=await ke.withDirectory(E.path,()=>ke.createSession({title:R}));lt.getState().setWorktreeMetadata(_.id,E),g.push({sessionId:_.id,worktreePath:E.path,providerID:w.providerID,modelID:w.modelID,variant:w.variant})}catch(E){console.warn("[MultiRun] Failed to create session:",E)}}const y=l?.filter(w=>w.trim().length>0)??[];y.length>0&&zu(d,y).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const x=g.map(w=>w.sessionId),v=g[0]?.sessionId??null;if(x.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const N=i?.map(w=>({type:"file",mime:w.mime,filename:w.filename,url:w.url}));try{await lt.getState().loadSessions()}catch{}if(b.length>0)for(const w of g)Gu(w.worktreePath,d,b).then(k=>{if(!k.success){const D=k.results.filter(M=>!M.success);console.warn(`[MultiRun] Setup commands failed for ${w.worktreePath}:`,D)}}).catch(k=>{console.warn(`[MultiRun] Setup commands error for ${w.worktreePath}:`,k)});return(async()=>{try{await Promise.allSettled(g.map(async w=>{try{await ke.withDirectory(w.worktreePath,()=>ke.sendMessage({id:w.sessionId,providerID:w.providerID,modelID:w.modelID,variant:w.variant,text:n,agent:a,files:N}))}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(w){console.warn("[MultiRun] Failed to start runs:",w)}})(),s({isLoading:!1}),{groupSlug:m,sessionIds:x,firstSessionId:v}}catch(d){return s({error:d instanceof Error?d.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{s({error:null})}}),{name:"multirun-store"}));function vs({...s}){return e.jsx(Fp,{"data-slot":"select",...s})}function Vr({...s}){return e.jsx(zp,{"data-slot":"select-group",...s})}function Xr({...s}){return e.jsx(Op,{"data-slot":"select-value",...s})}function js({className:s,size:r="default",children:t,...n}){return e.jsxs(Rp,{"data-slot":"select-trigger","data-size":r,className:T("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-muted data-[state=open]:bg-muted focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 data-[size=lg]:h-8 data-[size=lg]:py-1.5 data-[size=chip]:h-7 data-[size=chip]:py-1 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...n,children:[t,e.jsx(_p,{asChild:!0,children:e.jsx(Et,{className:"size-4 opacity-50"})})]})}function Ss({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx($p,{children:e.jsx(Lp,{"data-slot":"select-content",className:T("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(mt,{as:Bp,outerClassName:T("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:T("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 vn({className:s,...r}){return e.jsx(Wp,{"data-slot":"select-label",className:T("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function Bt({className:s,children:r,...t}){return e.jsxs(Hp,{"data-slot":"select-item",className:T("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(Up,{children:e.jsx(Tt,{className:"size-4"})})}),e.jsx(Vp,{children:r})]})}function ea({className:s,...r}){return e.jsx(Gp,{"data-slot":"select-separator",className:T("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}const Sb="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",kb=Object.assign({"../assets/provider-logos/gocode.svg":Sb}),Pi=new Map;for(const[s,r]of Object.entries(kb)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&Pi.set(t[1].toLowerCase(),r)}function vm(s){const r=s?.toLowerCase()??null,t=r?Pi.has(r):!1,n=r?Pi.get(r)??null:null,[o,a]=Ce.useState(t?"local":"remote");Ce.useEffect(()=>{a(t?"local":"remote")},[t,r]);const i=Ce.useCallback(()=>{a(l=>l==="local"&&t?"remote":"none")},[t]);return r?o==="local"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const ns=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=vm(s),l=c.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:T("dark:invert",t),onError:l})},wl=s=>s.nativeEvent.isComposing||s.nativeEvent.keyCode===229,vl=()=>{const{providers:s}=st(),{favoriteModels:r,recentModels:t}=$e(),n=c.useMemo(()=>r.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[r,s]),o=c.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!r.some(l=>l.providerID===a&&l.modelID===i)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},jm="h-7",ta=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Nb=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Cb=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=Nb.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Mb=({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:T("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",jm),children:[e.jsx(ns,{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(Wt,{className:"h-3.5 w-3.5"})})]})},Sm=({selectedModels:s,onAdd:r,onRemove:t,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:i=!0,maxModels:l})=>{const{providers:d,modelsMetadata:u}=st(),{favoriteModelsList:m,recentModelsList:f}=vl(),[p,g]=c.useState(!1),[b,h]=c.useState(""),[j,y]=c.useState(0),[x,v]=c.useState(null),N=c.useRef(null),w=c.useRef(null),k=c.useRef(null),D=c.useRef([]),M=c.useMemo(()=>{const K=new Map;for(const L of s){const G=`${L.providerID}:${L.modelID}`;K.set(G,(K.get(G)||0)+1)}return K},[s]),C=c.useCallback(K=>s.filter(G=>G.providerID===K.providerID&&G.modelID===K.modelID).findIndex(G=>G.instanceId===K.instanceId)+1,[s]),S=(K,L)=>{const G=`${K}/${L}`;return u.get(G)},A=K=>{const L=K?.name||K?.id||"",G=String(L);return G.length>40?G.substring(0,37)+"...":G},E=c.useCallback((K,L)=>{if(!b.trim())return!0;const G=b.toLowerCase();return K.toLowerCase().includes(G)||L.toLowerCase().includes(G)},[b]),R=c.useMemo(()=>m.filter(({model:K,providerID:L})=>{const B=d.find(V=>V.id===L)?.name||L,H=A(K);return E(H,B)}),[m,d,E]),_=c.useMemo(()=>f.filter(({model:K,providerID:L})=>{const B=d.find(V=>V.id===L)?.name||L,H=A(K);return E(H,B)}),[f,d,E]),P=c.useMemo(()=>d.map(K=>{const G=(Array.isArray(K.models)?K.models:[]).filter(B=>{const H=A(B);return E(H,K.name||K.id||"")});return{...K,models:G}}).filter(K=>K.models.length>0),[d,E]),O=R.length>0||_.length>0||P.length>0;c.useEffect(()=>{if(p&&k.current){const L=k.current.getBoundingClientRect().top-100;v(Math.max(150,Math.min(400,L)))}},[p]),c.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),c.useEffect(()=>{if(!p)return;const K=L=>{w.current&&!w.current.contains(L.target)&&(g(!1),h(""),y(0))};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[p]),c.useEffect(()=>{y(0)},[b]);const J=(K,L,G,B,H,V)=>{const oe=`${L}:${G}`,se=M.get(oe)||0,Y=S(L,G),le=Cb(Y?.limit?.context);return e.jsxs("button",{ref:I=>{D.current[H]=I},type:"button",onClick:()=>{r({providerID:L,modelID:G,displayName:K.name||G,instanceId:ta()})},onMouseEnter:()=>y(H),className:T("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",V?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:A(K)}),le&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:le})]}),se>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",se]})]},`${B}-${oe}`)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs("div",{className:"relative",ref:w,children:[e.jsxs(Ne,{ref:k,type:"button",variant:"outline",size:"sm",className:jm,onClick:()=>g(!p),children:[e.jsx(qt,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const K=[];R.forEach(({model:H,providerID:V,modelID:oe})=>{K.push({model:H,providerID:V,modelID:oe,section:"fav"})}),_.forEach(({model:H,providerID:V,modelID:oe})=>{K.push({model:H,providerID:V,modelID:oe,section:"recent"})}),P.forEach(H=>{H.models.forEach(V=>{K.push({model:V,providerID:H.id,modelID:V.id,section:"provider"})})});const L=K.length,G=H=>{if(!wl(H))if(H.key==="ArrowDown"){H.preventDefault(),H.stopPropagation();const V=(j+1)%Math.max(1,L);y(V),setTimeout(()=>{D.current[V]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(H.key==="ArrowUp"){H.preventDefault(),H.stopPropagation();const V=(j-1+Math.max(1,L))%Math.max(1,L);y(V),setTimeout(()=>{D.current[V]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(H.key==="Enter"){H.preventDefault(),H.stopPropagation();const V=K[j];V&&r({providerID:V.providerID,modelID:V.modelID,displayName:V.model.name||V.modelID,instanceId:ta()})}else H.key==="Escape"&&(H.preventDefault(),H.stopPropagation(),g(!1),h(""),y(0))};let B=0;return e.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden bg-background shadow-lg w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{ref:N,type:"text",placeholder:"Search models",value:b,onChange:H=>h(H.target.value),onKeyDown:G,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(mt,{outerClassName:"flex-1",style:{maxHeight:x?`${x}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!O&&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("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),R.map(({model:H,providerID:V,modelID:oe})=>{const se=B++;return J(H,V,oe,"fav",se,j===se)})]}),_.length>0&&e.jsxs(e.Fragment,{children:[R.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),_.map(({model:H,providerID:V,modelID:oe})=>{const se=B++;return J(H,V,oe,"recent",se,j===se)})]}),(R.length>0||_.length>0)&&P.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),P.map((H,V)=>e.jsxs(c.Fragment,{children:[V>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ns,{providerId:H.id,className:"h-4 w-4 flex-shrink-0"}),H.name]}),H.models.map(oe=>{const se=B++;return J(oe,H.id,oe.id,"provider",se,j===se)})]},H.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),i&&s.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:s.map((K,L)=>{const G=`${K.providerID}:${K.modelID}`,B=M.get(G)||1,H=C(K),oe=d.find(W=>W.id===K.providerID)?.models.find(W=>W.id===K.modelID),se=oe?.variants?Object.keys(oe.variants):[],Y=se.length>0,le="__default__",I=K.variant??le;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Mb,{model:K,instanceIndex:H,totalSameModel:B,onRemove:()=>t(L)}),Y&&e.jsxs(vs,{value:I,onValueChange:W=>{if(!n)return;n(L,{...K,variant:W===le?void 0:W})},children:[e.jsxs(js,{size:"chip",className:"px-2 gap-1.5 rounded-md bg-accent/50 border-border/30 hover:bg-accent/60 typography-meta font-medium text-foreground",children:[e.jsx(ar,{className:T("h-3.5 w-3.5 flex-shrink-0",I===le?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(Xr,{placeholder:"Thinking"})]}),e.jsxs(Ss,{fitContent:!0,children:[e.jsx(Bt,{value:le,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),se.map(W=>e.jsx(Bt,{value:W,className:"pr-2 [&>span:first-child]:hidden",children:W},W))]})]})]},K.instanceId)})})]}),o!==void 0&&s.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",l!==void 0?`to ${l} models`:"","."]})]})};function jl(s){const[r,t]=c.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=c.useState(!1),[a,i]=c.useState(null);return c.useEffect(()=>{let l=!1;if(!s){i(null),o(!1),t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),i(null),(async()=>{try{const d=await sn(s);if(l)return;if(i(d),!d){t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await nl(s).catch(()=>null);if(l)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(b=>!b.startsWith("remotes/")).sort((b,h)=>b.localeCompare(h)).forEach(b=>{m.push({value:b,label:b,group:"local"})}),u.all.filter(b=>b.startsWith("remotes/")).map(b=>b.replace(/^remotes\//,"")).sort((b,h)=>b.localeCompare(h)).forEach(b=>{m.push({value:b,label:b,group:"remote"})})),t(m)}finally{l||o(!1)}})(),()=>{l=!0}},[s]),{branches:r,isLoading:n,isGitRepository:a}}const km=({directory:s,value:r,onChange:t,className:n,disabled:o,id:a})=>{const{branches:i,isLoading:l,isGitRepository:d}=jl(s),u=c.useMemo(()=>i.find(f=>f.value===r)?.label??null,[i,r]);c.useEffect(()=>{!i.some(p=>p.value===r)&&i.length>0&&t("HEAD")},[i,r,t]);const m=o||!d||l;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(vs,{value:r,onValueChange:t,disabled:m,children:[e.jsx(js,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(Xr,{children:u}):e.jsx(Xr,{placeholder:l?"Loading branches…":"Select a branch"})}),e.jsxs(Ss,{fitContent:!0,children:[e.jsxs(Vr,{children:[e.jsx(vn,{children:"Default"}),i.filter(f=>f.group==="special").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),i.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(ea,{}),e.jsxs(Vr,{children:[e.jsx(vn,{children:"Local branches"}),i.filter(f=>f.group==="local").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,i.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(ea,{}),e.jsxs(Vr,{children:[e.jsx(vn,{children:"Remote branches"}),i.filter(f=>f.group==="remote").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null]})]}),d===!1&&e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."})]})},Nm=({value:s,onChange:r,className:t,disabled:n,id:o})=>{const a=st(f=>f.getVisibleAgents),i=st(f=>f.loadAgents),l=st(f=>f.currentAgentName),d=a(),u=c.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);c.useEffect(()=>{i()},[i]),c.useEffect(()=>{if(n)return;const f=s.trim();if(f.length>0&&u.some(b=>b.name===f))return;const p=typeof l=="string"&&l.trim().length>0?l.trim():null;if(p&&u.some(b=>b.name===p)){r(p);return}const g=u[0]?.name;g&&r(g)},[l,n,r,u,s]);const m=s.trim().length>0?s:void 0;return e.jsxs(vs,{value:m,onValueChange:r,disabled:n,children:[e.jsx(js,{id:o,size:"lg",className:t??"max-w-full typography-meta text-foreground",children:e.jsx(Xr,{placeholder:"Select an agent"})}),e.jsx(Ss,{fitContent:!0,children:u.length>0&&e.jsx(Vr,{children:u.map(f=>e.jsx(Bt,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},Db=10*1024*1024,Hc=5,Uc=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=c.useState(""),[a,i]=c.useState(()=>s??""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState([]),[g,b]=c.useState(!1),[h,j]=c.useState([]),[y,x]=c.useState(!1),[v,N]=c.useState(!1),w=c.useRef(null),k=dt(F=>F.currentDirectory??null),D=c.useMemo(()=>{if(typeof window>"u")return null;const F=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof F=="string"&&F.trim().length>0?F.trim():null},[]),M=Ft(F=>F.activeProjectId),C=Ft(F=>F.projects),S=c.useMemo(()=>{if(M){const fe=C.find(ve=>ve.id===M);if(fe?.path)return fe.path}const F=k??D;if(!F)return null;const $=F.replace(/\\/g,"/").replace(/\/+$/,"")||F,X=$.indexOf("/.openchamber/");return X>0?$.slice(0,X):$.endsWith("/.openchamber")?$.slice(0,$.length-13):$},[M,C,k,D]),A=$e(F=>F.isSidebarOpen),[E,R]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),_=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const F=typeof window.opencodeDesktop<"u";R(F)},[]);const P=c.useMemo(()=>E&&_?A?"pl-0":"pl-[8.0rem]":"pl-3",[E,_,A]),[O,J]=c.useState("HEAD"),{isLoading:K,isGitRepository:L}=jl(k),G=qn(F=>F.createMultiRun),B=qn(F=>F.error),H=qn(F=>F.clearError);c.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&i(F=>F.trim().length>0?F:s)},[s]),c.useEffect(()=>{if(!S)return;let F=!1;return N(!0),(async()=>{try{const $=await oo(S);F||j($)}catch{}finally{F||N(!1)}})(),()=>{F=!0}},[S]);const V=F=>{l.length>=Hc||(d($=>[...$,F]),H())},oe=F=>{d($=>$.filter((z,X)=>X!==F)),H()},se=c.useCallback((F,$)=>{d(z=>z.map((X,fe)=>fe===F?$:X))},[]),Y=async F=>{const $=F.target.files;if(!$)return;let z=0;for(let X=0;X<$.length;X++){const fe=$[X];if(fe.size>Db){ne.error(`File "${fe.name}" is too large (max 10MB)`);continue}try{const ve=await new Promise((Re,be)=>{const Ie=new FileReader;Ie.onload=()=>Re(Ie.result),Ie.onerror=be,Ie.readAsDataURL(fe)}),ge={id:ta(),filename:fe.name,mimeType:fe.type||"application/octet-stream",size:fe.size,dataUrl:ve};p(Re=>[...Re,ge]),z++}catch(ve){console.error("File attach failed",ve),ne.error(`Failed to attach "${fe.name}"`)}}z>0&&ne.success(`Attached ${z} file${z>1?"s":""}`),w.current&&(w.current.value="")},le=F=>{p($=>$.filter(z=>z.id!==F))},I=async F=>{if(F.preventDefault(),!!a.trim()&&!(l.length<2)){b(!0),H();try{const $=l.map(({instanceId:ge,...Re})=>Re),z=f.map(ge=>({mime:ge.mimeType,filename:ge.filename,url:ge.dataUrl})),X=h.filter(ge=>ge.trim().length>0),fe={name:n.trim(),prompt:a.trim(),models:$,agent:u||void 0,worktreeBaseBranch:O,files:z.length>0?z:void 0,setupCommands:X.length>0?X:void 0},ve=await G(fe);ve&&(ve.firstSessionId&&ue.getState().setCurrentSession(ve.firstSessionId),r?.())}finally{b(!1)}}},W=!!(n.trim()&&a.trim()&&l.length>=2&&L&&!K);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:T("flex h-12 items-center justify-between border-b app-region-drag",P),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:T("flex items-center gap-3",E&&_&&A&&"pl-4"),children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),t&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{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(Wt,{className:"h-5 w-5"})})}),e.jsx(rt,{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:I,className:"space-y-6","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:["Group name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(ht,{id:"group-name",value:n,onChange:F=>o(F.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body max-w-full sm:max-w-xs",required:!0}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch names"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Worktrees"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create one worktree per model by creating a new branch from a base branch."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"multirun-worktree-base-branch",children:"Base branch"}),e.jsx(km,{directory:k,value:O,onChange:J,id:"multirun-worktree-base-branch"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:O||"HEAD"}),"."]})]}),e.jsxs(xa,{open:y,onOpenChange:x,children:[e.jsxs(bl,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",h.filter(F=>F.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",h.filter(F=>F.trim()).length," configured)"]})]}),e.jsx(Et,{className:T("h-4 w-4 text-muted-foreground transition-transform duration-200",y&&"rotate-180")})]}),e.jsx(ya,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),v?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[h.map((F,$)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{value:F,onChange:z=>{const X=[...h];X[$]=z.target.value,j(X)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const z=h.filter((X,fe)=>fe!==$);j(z)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(Wt,{className:"h-4 w-4"})})]},$)),e.jsxs("button",{type:"button",onClick:()=>j([...h,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(qt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",htmlFor:"multirun-agent",children:"Agent"}),e.jsx(Nm,{value:u,onChange:m,id:"multirun-agent"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:["Prompt ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Ts,{id:"prompt",value:a,onChange:F=>i(F.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),e.jsx("input",{ref:w,type:"file",multiple:!0,className:"hidden",onChange:Y,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(Ne,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>w.current?.click(),children:[e.jsx(Uo,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(F=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[F.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:F.filename,children:F.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",F.size<1024?`${F.size}B`:F.size<1024*1024?`${(F.size/1024).toFixed(1)}KB`:`${(F.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>le(F.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Wt,{className:"h-3.5 w-3.5"})})]},F.id))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Models ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Sm,{selectedModels:l,onAdd:V,onRemove:oe,onUpdate:se,minModels:2,maxModels:Hc})]}),B&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:B}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(Ne,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(Ne,{type:"submit",disabled:!W||g,children:g?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(qp,{className:"h-4 w-4 mr-2"}),"Start (",l.length," models)"]})})]})]})})})]})},Ab=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:l}=$e(),d=Ce.useRef(null),u=Ce.useRef(null);return Ce.useEffect(()=>{if(!o||!a)return;const m=b=>{const h=b.touches[0];if(!h){d.current=null;return}h.clientX<=r?d.current={x:h.clientX,y:h.clientY,time:Date.now()}:d.current=null},f=b=>{if(!d.current)return;const h=b.touches[0];if(!h)return;h.clientX-d.current.x>10&&b.preventDefault()},p=b=>{if(!d.current)return;const h=b.changedTouches[0];if(!h){d.current=null,u.current=null;return}u.current={x:h.clientX,y:h.clientY,time:Date.now()};const{x:j,y,time:x}=d.current,{x:v,y:N,time:w}=u.current,k=v-j,D=N-y,M=w-x,C=Math.abs(D)<Math.abs(k),S=M<=n,A=Math.abs(D)<t;k>=t&&C&&S&&A&&!l&&i(!0),d.current=null,u.current=null},g=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",m,{passive:!0,capture:!0}),document.addEventListener("touchmove",f,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",g,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",m,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",g,{capture:!0})}},[o,a,r,t,n,i,l]),null},zn=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;Ce.memo(()=>{const s=Ce.useRef(null),{addAttachedFile:r}=ue(),{isMobile:t}=$e(),n=am(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",i=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],g=ue.getState().attachedFiles.length;try{await r(p),ue.getState().attachedFiles.length>g&&m++}catch(b){console.error("File attach failed",b),ne.error(b instanceof Error?b.message:"Failed to attach file")}}m>0&&ne.success(`Attached ${m} file${m>1?"s":""}`)},l=async u=>{const m=u.target.files;m&&(await i(m),s.current&&(s.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const b=p.map(h=>`${h?.name||"file"}: ${h?.reason||"skipped"}`).join(`
66
- `);ne.error(`Some files were skipped:
67
- ${b}`)}const g=f.map(b=>{if(!b?.dataUrl)return null;try{const[h,j]=b.dataUrl.split(","),y=b.mimeType||h?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!j)return null;const x=atob(j),v=new Uint8Array(x.length);for(let w=0;w<x.length;w++)v[w]=x.charCodeAt(w);const N=new Blob([v],{type:y});return new File([N],b.name||"file",{type:y})}catch(h){return console.error("Failed to decode VS Code picked file",h),null}}).filter(Boolean);g.length>0&&await i(g)}catch(u){console.error("VS Code file pick failed",u),ne.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:s,type:"file",multiple:!0,className:"hidden",onChange:l,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:T(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(Uo,{className:T(a,"text-current")})})]})});const Eb=Ce.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(tr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(la,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}),n=i=>i<1024?i+" B":i<1048576?(i/1024).toFixed(1)+" KB":(i/1048576).toFixed(1)+" MB",a=(i=>{const d=i.replace(/\\/g,"/").split("/");return d[d.length-1]||i})(s.filename);return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:s.source==="server"?"Server file":"Local file",children:s.source==="server"?e.jsx(Kp,{className:"h-3 w-3 text-primary"}):e.jsx(nu,{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(Wt,{className:"h-3 w-3"})})]})}),Ib=Ce.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=ue();return s.length===0?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Attached:"}),s.map(t=>e.jsx(Eb,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),Cm=Ce.memo(({files:s,onShowPopup:r})=>{const t=s.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const m=d.replace(/\\/g,"/").split("/");return m[m.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(tr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(la,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),l=c.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return t.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const m=n(d.filename)||"Image";return e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>l(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(br,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(rt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Mm=Ce.memo(({message:s,sessionId:r,onEdit:t})=>{const n=Zs(i=>i.removeFromQueue),o=c.useMemo(()=>{const i=s.content.split(`
68
- `),l=i[0]||"",d=50;return l.length>d?l.substring(0,d)+"...":l+(i.length>1?"...":"")},[s.content]),a=s.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(Yp,{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(Wt,{className:"h-3 w-3"})})]})});Mm.displayName="QueuedMessageChip";const Vc=[],Dm=Ce.memo(({onEditMessage:s})=>{const r=ue(a=>a.currentSessionId),t=Zs(c.useCallback(a=>r?a.queuedMessages[r]??Vc:Vc,[r])),n=Zs(a=>a.popToInput),o=c.useCallback(a=>{if(!r)return;const i=n(r,a.id);if(i){if(i.attachments&&i.attachments.length>0){const l=er.getState().attachedFiles;er.setState({attachedFiles:[...l,...i.attachments]})}s(i.content,i.attachments)}},[r,n,s]);return t.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),t.map(a=>e.jsx(Mm,{message:a,sessionId:r,onEdit:o},a.id))]})})});Dm.displayName="QueuedMessageChips";const Pb=c.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=dt(),{addServerFile:a}=ue(),i=el(A=>A.searchFiles),l=yl(s,180),[d,u]=c.useState([]),[m,f]=c.useState(!1),[p,g]=c.useState(0),[b,h]=c.useState(360),[j,y]=c.useState({}),[x,v]=c.useState({}),N=c.useRef([]),w=c.useRef([]),k=c.useRef([]),D=c.useRef(null),M=c.useCallback((A,E)=>{const R=A.trim().toLowerCase();if(!R)return 0;const _=E.toLowerCase();let P=0,O=-1,J=0;for(let K=0;K<R.length;K+=1){const L=R[K];if(!L||L===" ")continue;const G=_.indexOf(L,O+1);if(G===-1)return null;const B=G-O-1;if(B===0?J+=1:J=0,P+=10,P+=Math.max(0,18-G),P-=Math.max(0,B),G===0)P+=12;else{const H=_[G-1];(H==="/"||H==="_"||H==="-"||H==="."||H===" ")&&(P+=10)}P+=J>0?12:0,O=G}return P+=Math.max(0,24-Math.round(_.length/3)),P},[]);c.useEffect(()=>{const A=E=>{const R=E.target;!R||!D.current||D.current.contains(R)||t()};return document.addEventListener("pointerdown",A,!0),()=>{document.removeEventListener("pointerdown",A,!0)}},[t]),c.useEffect(()=>{if(!o){u([]);return}const E=(l??"").trim().toLowerCase();let R=!1;return f(!0),i(o,E,80).then(_=>{if(R)return;const P=E?_.map(O=>{const J=O.relativePath||O.name||O.path,K=M(E,J);return K===null?null:{file:O,score:K,labelLength:J.length}}).filter(Boolean):_.map(O=>({file:O,score:0,labelLength:(O.relativePath||O.name||O.path).length}));P.sort((O,J)=>J.score-O.score||O.labelLength-J.labelLength||O.file.path.localeCompare(J.file.path)),u(P.slice(0,15).map(O=>O.file))}).catch(()=>{R||u([])}).finally(()=>{R||f(!1)}),()=>{R=!0}},[o,l,M,i]),c.useEffect(()=>{g(0),y({}),v({})},[d]),c.useEffect(()=>{N.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),c.useEffect(()=>{let A=null;const E=()=>{A!==null&&cancelAnimationFrame(A),A=requestAnimationFrame(()=>{const R={},_={};w.current.forEach((P,O)=>{if(!P)return;const K=k.current[O]?.offsetWidth??P.scrollWidth,L=Math.max(0,K-P.clientWidth),G=L>8;if(R[O]=G,G){const B=Math.max(.6,L/110);_[O]=B}}),y(R),v(_)})};return E(),window.addEventListener("resize",E),()=>{A!==null&&cancelAnimationFrame(A),window.removeEventListener("resize",E)}},[d]),c.useEffect(()=>{const A=w.current[p];if(!A)return;const E=()=>{const _=A.clientWidth;_>0&&h(_)};if(E(),typeof ResizeObserver>"u")return;const R=new ResizeObserver(E);return R.observe(A),()=>{R.disconnect()}},[p]);const C=c.useCallback(async A=>{await a(A.path,A.name),r(A)},[a,r]);c.useImperativeHandle(n,()=>({handleKeyDown:A=>{if(A==="Escape"){t();return}const E=d.length;if(E!==0){if(A==="ArrowDown"){g(R=>(R+1)%E);return}if(A==="ArrowUp"){g(R=>(R-1+E)%E);return}if(A==="Enter"||A==="Tab"){const R=(p%E+E)%E,_=d[R];_&&C(_)}}}}),[d,p,t,C]);const S=A=>{switch(A.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(nr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(nr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(tr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(br,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(la,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:D,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(mt,{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(Dr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((A,E)=>{const R=A.relativePath||A.name,_=ju(R,{maxLength:45}),P=p===E,O=j[E]??!1,J=x[E]??2.6,K=e.jsxs("div",{ref:L=>{N.current[E]=L},className:T("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",P&&"bg-muted"),onClick:()=>C(A),onMouseEnter:()=>g(E),children:[S(A),e.jsxs("span",{ref:L=>{w.current[E]=L},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:P?{"--file-mention-marquee-width":`${b}px`,"--file-mention-marquee-duration":`${J}s`}:void 0,"aria-label":R,children:[e.jsx("span",{ref:L=>{k.current[E]=L},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:R}),O&&P?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:R}):e.jsx("span",{className:"block truncate",children:_})]})]});return e.jsx(c.Fragment,{children:K},A.path)}),d.length>0&&e.jsx("div",{className:"h-2"}),d.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),Am=c.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=ue(qi(x=>{const v=x.currentSessionId;return{hasMessagesInCurrentSession:(v?x.messages.get(v)?.length??0:0)>0,currentSessionId:v}})),i=!!a,[l,d]=c.useState([]),[u,m]=c.useState(!1),{commands:f,loadCommands:p}=Tr(),[g,b]=c.useState(0),h=c.useRef([]),j=c.useRef(null);c.useEffect(()=>{const x=v=>{const N=v.target;!N||!j.current||j.current.contains(N)||t()};return document.addEventListener("pointerdown",x,!0),()=>{document.removeEventListener("pointerdown",x,!0)}},[t]),c.useEffect(()=>{p()},[p]),c.useEffect(()=>{(async()=>{m(!0);try{const v=f.map(C=>({name:C.name,description:C.description,agent:C.agent??void 0,model:C.model??void 0,isBuiltIn:C.name==="init"||C.name==="review",scope:C.scope})),N=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],w=new Map;N.forEach(C=>w.set(C.name,C)),v.forEach(C=>w.set(C.name,C));const k=Array.from(w.values()),D=!o,M=(s?k.filter(C=>Is(C.name,s)||C.description&&Is(C.description,s)):k).filter(C=>D||C.name!=="init");M.sort((C,S)=>{const A=C.name.toLowerCase().startsWith(s.toLowerCase()),E=S.name.toLowerCase().startsWith(s.toLowerCase());return A&&!E?-1:!A&&E?1:C.name.localeCompare(S.name)}),d(M)}catch{const v=!o,N=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],w=(s?N.filter(k=>Is(k.name,s)||k.description&&Is(k.description,s)):N).filter(k=>v||k.name!=="init");d(w)}finally{m(!1)}})()},[s,o,i,f]),c.useEffect(()=>{b(0)},[l]),c.useEffect(()=>{h.current[g]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[g]),c.useImperativeHandle(n,()=>({handleKeyDown:x=>{const v=l.length;if(x==="Escape"){t();return}if(v!==0){if(x==="ArrowDown"){b(N=>(N+1)%v);return}if(x==="ArrowUp"){b(N=>(N-1+v)%v);return}if(x==="Enter"||x==="Tab"){const N=(g%v+v)%v,w=l[N];w&&r(w)}}}}),[l,g,t,r]);const y=x=>{switch(x.name){case"init":return e.jsx(tr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Kn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(Jp,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(or,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(Xp,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Er,{className:"h-3.5 w-3.5 text-cyan-500"});default:return x.isBuiltIn?e.jsx(Qp,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(Zr,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:j,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(mt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:u?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Dr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[l.map((x,v)=>{const N=x.isBuiltIn,w=x.scope==="project";return e.jsxs("div",{ref:k=>{h.current[v]=k},className:T("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",v===g&&"bg-muted"),onClick:()=>r(x),onMouseEnter:()=>b(v),children:[e.jsx("div",{className:"mt-0.5",children:y(x)}),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:["/",x.name]}),N?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):x.scope?e.jsx("span",{className:T("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",w?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:x.scope}):null,x.agent&&e.jsx("span",{className:"text-[10px] leading-none font-bold tracking-tight bg-[var(--surface-subtle)] text-[var(--surface-foreground)] border-[var(--interactive-border)] px-1.5 py-1 rounded border flex-shrink-0",children:x.agent})]}),x.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:x.description})]})]},x.name)}),l.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Am.displayName="CommandAutocomplete";const Tb=s=>s?s!=="primary":!1,Em=c.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=c.useRef(null),[a,i]=c.useState(0),[l,d]=c.useState([]),u=c.useRef([]),{getVisibleAgents:m}=st(),{agents:f,loadAgents:p}=Fr();c.useEffect(()=>{f.length===0&&p()},[p,f.length]),c.useEffect(()=>{const h=m().filter(x=>Tb(x.mode)).map(x=>{const v=f.find(N=>N.name===x.name);return{name:x.name,description:x.description,mode:x.mode??void 0,scope:v?.scope,isBuiltIn:v?zr(v):!1}}),j=s.trim(),y=j.length?h.filter(x=>Is(x.name,j)):h;y.sort((x,v)=>x.name.localeCompare(v.name)),d(y),i(0)},[m,s,f]),c.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),c.useEffect(()=>{const b=h=>{const j=h.target;!j||!o.current||o.current.contains(j)||t()};return document.addEventListener("pointerdown",b,!0),()=>{document.removeEventListener("pointerdown",b,!0)}},[t]),c.useImperativeHandle(n,()=>({handleKeyDown:b=>{if(b==="Escape"){t();return}if(l.length){if(b==="ArrowDown"){i(h=>(h+1)%l.length);return}if(b==="ArrowUp"){i(h=>(h-1+l.length)%l.length);return}if(b==="Enter"||b==="Tab"){const h=l[(a+l.length)%l.length];h&&r(h.name)}}}}),[l,r,t,a]);const g=(b,h)=>{const j=b.isBuiltIn,y=b.scope==="project";return e.jsx("div",{ref:x=>{u.current[h]=x},className:T("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",h===a&&"bg-muted"),onClick:()=>r(b.name),onMouseEnter:()=>i(h),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["#",b.name]}),j?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):b.scope?e.jsx("span",{className:T("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",y?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:b.scope}):null]}),b.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:b.description})]})},b.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(mt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((b,h)=>g(b,h))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No agents found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Em.displayName="AgentMentionAutocomplete";const Im=c.forwardRef(({searchQuery:s,onSkillSelect:r,onClose:t},n)=>{const o=c.useRef(null),[a,i]=c.useState(0),[l,d]=c.useState([]),u=c.useRef([]),{skills:m,loadSkills:f}=Hs();c.useEffect(()=>{f()},[f]),c.useEffect(()=>{const g=s.trim(),h=[...g.length?m.filter(j=>Is(j.name,g)):m].sort((j,y)=>j.scope==="project"&&y.scope!=="project"?-1:j.scope!=="project"&&y.scope==="project"?1:j.name.localeCompare(y.name));d(h),i(0)},[m,s]),c.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),c.useEffect(()=>{const g=b=>{const h=b.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),c.useImperativeHandle(n,()=>({handleKeyDown:g=>{if(g==="Escape"){t();return}if(l.length){if(g==="ArrowDown"){i(b=>(b+1)%l.length);return}if(g==="ArrowUp"){i(b=>(b-1+l.length)%l.length);return}if(g==="Enter"||g==="Tab"){const b=l[a];b&&r(b.name)}}}}),[l,r,t,a]);const p=(g,b)=>{const h=g.scope==="project";return e.jsx("div",{ref:j=>{u.current[b]=j},className:T("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",b===a&&"bg-muted"),onClick:()=>r(g.name),onMouseEnter:()=>i(b),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold truncate",children:g.name}),e.jsx("span",{className:T("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 transition-colors",h?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:g.scope})]}),g.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:g.description})]})},`${g.name}-${g.scope}`)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(mt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((g,b)=>p(g,b))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No skills found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Im.displayName="SkillAutocomplete";function Fb({className:s,children:r,...t}){return e.jsxs(Zp,{"data-slot":"scroll-area",className:T("relative",s),...t,children:[e.jsx(eh,{"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(Rb,{}),e.jsx(th,{})]})}function Rb({className:s,orientation:r="vertical",...t}){return e.jsx(sh,{"data-slot":"scroll-area-scrollbar",orientation:r,className:T("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(rh,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const _b=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Rt(),l=i,{currentDirectory:d}=dt(),u=el(U=>U.searchFiles),[m,f]=c.useState(!1),[p,g]=c.useState(!1),[b,h]=c.useState(""),j=yl(b,200),[y,x]=c.useState(new Set),[v,N]=c.useState(new Set),[w,k]=c.useState({}),D=c.useRef(new Set),M=c.useRef(new Set),[C,S]=c.useState([]),[A,E]=c.useState(!1),[R,_]=c.useState(!1),[P,O]=c.useState(!1),[J,K]=c.useState(null),L=n??m,G=o??f,B=c.useCallback(U=>U.slice().sort((Q,te)=>Q.type!==te.type?Q.type==="directory"?-1:1:Q.name.localeCompare(te.name)),[]),H=c.useCallback((U,Q)=>B(Q.filter(te=>!te.name.startsWith(".")).map(te=>{const pe=te.name,me=!te.isDirectory&&pe.includes(".")?pe.split(".").pop()?.toLowerCase():void 0;return{name:pe,path:te.path||`${U}/${pe}`,type:te.isDirectory?"directory":"file",size:0,extension:me}})),[B]),V=c.useCallback(async U=>{_(!0),K(null);try{const Q=await ke.listLocalDirectory(U),te=H(U,Q.map(pe=>({name:pe.name,path:pe.path,isDirectory:pe.isDirectory})));D.current=new Set([U]),M.current=new Set,k({[U]:te}),N(new Set)}catch{K("Failed to load directory contents"),D.current=new Set([U]),M.current=new Set,k({[U]:[]}),N(new Set)}finally{_(!1)}},[H]),oe=c.useCallback(async U=>{const Q=U.trim();if(Q&&!D.current.has(Q)&&!M.current.has(Q)){M.current=new Set(M.current),M.current.add(Q);try{const te=await ke.listLocalDirectory(Q),pe=H(Q,te.map(me=>({name:me.name,path:me.path,isDirectory:me.isDirectory})));D.current=new Set(D.current),D.current.add(Q),k(me=>({...me,[Q]:pe}))}catch{k(te=>te[Q]?te:{...te,[Q]:[]})}finally{M.current=new Set(M.current),M.current.delete(Q)}}},[H]);c.useEffect(()=>{(L||p)&&d&&V(d)},[L,p,d,V]),c.useEffect(()=>{if(!(L||p)||!d){S([]),E(!1);return}const U=j.trim();if(!U){S([]),E(!1);return}let Q=!1;return E(!0),u(d,U,150).then(te=>{if(Q)return;const pe=te.map(me=>({name:me.name,path:me.path,type:"file",extension:me.extension,relativePath:me.relativePath,size:0}));S(pe)}).catch(()=>{Q||S([])}).finally(()=>{Q||E(!1)}),()=>{Q=!0}},[L,p,d,j,u]),c.useEffect(()=>{!L&&!p&&(x(new Set),h(""),S([]),E(!1))},[L,p]);const se=U=>{if(U.type==="directory")return v.has(U.path)?e.jsx(ur,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(ur,{className:"h-3.5 w-3.5 text-primary/60"});switch(U.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(nr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(nr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(xi,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(br,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(xi,{className:"h-3.5 w-3.5 text-muted-foreground"})}},Y=async U=>{v.has(U)?N(te=>{const pe=new Set(te);return pe.delete(U),pe}):(N(te=>{const pe=new Set(te);return pe.add(U),pe}),await oe(U))},le=U=>{x(r?Q=>{const te=new Set(Q);return te.has(U)?te.delete(U):te.add(U),te}:new Set([U]))},I=async()=>{const U=new Map;Object.values(w).forEach(pe=>{pe.forEach(me=>{me.type==="file"&&U.set(me.path,me)})});const Q=new Map(C.map(pe=>[pe.path,pe])),te=Array.from(y).map(pe=>U.get(pe)??Q.get(pe)).filter(pe=>!!pe);O(!0);try{await s(te),x(new Set),G(!1),g(!1)}finally{O(!1)}},W=c.useMemo(()=>d?w[d]??[]:[],[w,d]),F=b.trim().length>0,$=U=>w[U]??[],z=U=>{if(d&&U.startsWith(d)){const Q=U.substring(d.length);return Q.startsWith("/")?Q.substring(1):Q}return U.split("/").pop()||U},X=(U,Q)=>{const te=F?U.relativePath||z(U.path):U.name,pe=F&&te.includes("/")&&te.length>45,me=pe?ju(te,{maxLength:l?42:48}):te,Me=e.jsxs("div",{className:T("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",U.type==="file"&&y.has(U.path)&&"bg-primary/10"),style:{paddingLeft:`${Q*12}px`},onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),U.type==="file"&&le(U.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:se(U)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":te,children:me})]}),U.type==="file"&&y.has(U.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return pe?e.jsxs(nt,{delayDuration:120,children:[e.jsx(ot,{asChild:!0,children:Me}),e.jsx(rt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:te})})]},U.path):c.cloneElement(Me,{key:U.path})},fe=(U,Q)=>{const te=U.type==="directory",pe=te?$(U.path):[],me=v.has(U.path),Me=te&&me&&M.current.has(U.path)&&pe.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!te&&y.has(U.path)&&"bg-primary/10"),style:{paddingLeft:`${Q*12}px`},onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),te?Y(U.path):le(U.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:se(U)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:U.name}),!te&&y.has(U.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),te&&me&&pe.length>0&&e.jsx("div",{children:pe.map(Se=>fe(Se,Q+1))}),te&&me&&Me&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(Q+1)*12}px`},children:"Loading…"})]},U.path)},ve=y.size>0?`${y.size} file${y.size!==1?"s":""} selected`:"No files selected",ge=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:ve}),e.jsx(Ne,{size:"sm",onClick:I,disabled:y.size===0||P,className:"h-6 typography-meta",children:P?"Attaching...":"Attach Files"})]}),Re=l?"flex-1 min-h-[240px]":"h-[300px]",be=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsx("div",{className:"font-medium typography-ui-label text-foreground",children:"Select Project Files"})}),e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{value:b,onChange:U=>h(U.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:U=>U.stopPropagation()}),b&&e.jsx("button",{onClick:U=>{U.stopPropagation(),h("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Wt,{className:"h-3 w-3"})})]})}),e.jsxs(Fb,{className:Re,children:[R&&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..."})}),J&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:J})}),!R&&!J&&e.jsxs("div",{className:"py-1 px-2",children:[F?A?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):C.map(U=>X(U,0)):W.map(U=>fe(U,0)),!F&&W.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),F&&!A&&C.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),Ie=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:U=>{U.preventDefault(),U.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:U=>{U.preventDefault(),U.stopPropagation(),G(!0)},children:t}):null,e.jsx(ws,{open:L,onClose:()=>G(!1),title:"Select Project Files",footer:ge,children:e.jsx("div",{className:"flex flex-col gap-0",children:be})})]}):l?e.jsxs(e.Fragment,{children:[Ie,e.jsx(ws,{open:p,onClose:()=>g(!1),title:"Select Project Files",footer:ge,children:e.jsx("div",{className:"flex flex-col gap-0",children:be})})]}):e.jsxs(Ut,{open:L,onOpenChange:G,children:[e.jsx(Vt,{asChild:!0,children:t}),e.jsxs(Gt,{className:T("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[be,e.jsx(Ms,{}),ge]})]})},bo=[{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 kr(s){if(!s||s==="build")return bo[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)%(bo.length-1);return bo[t]}const Ob=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),Pm=s=>Ob(s),$b=s=>s?typeof s=="string"?s==="ask":Pm(s)?Object.values(s).some(r=>r==="ask"):!1:!1,Lb=s=>s?typeof s=="string"?s==="deny":Pm(s)?Object.values(s).some(r=>r==="deny"):!1:!1,Tm=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=$b(t),o=Lb(t),a=!n&&!o,i=r==="allow",l=r!=="deny",d=s==="allow"||s==="full",u=s==="ask";let m=s;d&&i&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:s!=="deny"&&l&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:l}},wo=s=>s==="primary"||s==="all"||s===void 0||s===null,sa=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},vo=(s,r)=>{const t=sa(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Bb=(s,r)=>{const t=sa(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},zb=[{key:"tool_call",icon:ca,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:ar,label:"Reasoning",isActive:s=>s?.reasoning===!0}],Wb={text:{icon:au,label:"Text"},image:{icon:br,label:"Image"},video:{icon:oh,label:"Video"},audio:{icon:nh,label:"Audio"},pdf:{icon:la,label:"PDF"}},Hb=s=>s.trim().toLowerCase(),$n=(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=>Hb(o)))).map(o=>{const a=Wb[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Ub=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Vb=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Os=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=Ub.format(s);return r.endsWith(".0")?r.slice(0,-2):r},jo=s=>typeof s!="number"||!Number.isFinite(s)?"—":Vb.format(s),Ka=s=>zb.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Gc=s=>{if(!s)return"—";const r=s.match(/^(\d{4})-(\d{2})$/);if(r){const t=Number.parseInt(r[1],10),n=Number.parseInt(r[2],10)-1,o=new Date(Date.UTC(t,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return s},qc=s=>{if(!s)return"—";const r=new Date(s);return Number.isNaN(r.getTime())?s:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(r)},Kc=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:i,setProvider:l,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:g,getCurrentAgent:b,getVisibleAgents:h}=st(),j=h(),{currentSessionId:y,messages:x,saveSessionAgentSelection:v,getSessionAgentSelection:N,saveAgentModelForSession:w,getAgentModelForSession:k,saveAgentModelVariantForSession:D,getAgentModelVariantForSession:M,analyzeAndSaveExternalSessionChoices:C,getSessionAgentEditMode:S,setSessionAgentEditMode:A}=ue(),E=bt(ee=>ee.hasHydrated),{toggleFavoriteModel:R,isFavoriteModel:_,addRecentModel:P,isModelSelectorOpen:O,setModelSelectorOpen:J}=$e(),{favoriteModelsList:K,recentModelsList:L}=vl(),{isMobile:G}=Rt(),B=by(),H=am(),V=G,[oe,se]=c.useState(null),[Y,le]=c.useState(null),[I,W]=c.useState(""),F=c.useCallback(()=>se(null),[]),$=c.useCallback(()=>le(null),[]),z=c.useRef(void 0),[X,fe]=c.useState(()=>{const ee=new Set;return t&&ee.add(t),ee}),[ve,ge]=c.useState(!1),Re=O,be=J,[Ie,U]=c.useState(!1),Q=c.useId(),[te,pe]=c.useState(""),[me,Me]=c.useState(0),Se=c.useRef([]);c.useEffect(()=>{oe==="model"&&fe(()=>{const ee=new Set;return t&&ee.add(t),ee})},[oe,t]),c.useEffect(()=>{oe!=="agent"&&ge(!1),oe!=="model"&&W("")},[oe]);const Pe=c.useRef(Re);c.useEffect(()=>{const ee=Pe.current;Pe.current=Re,Re||(U(!1),pe(""),Me(0),ee&&!V&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[Re,V]),c.useEffect(()=>{Me(0)},[te]);const q=b?.(),re=c.useMemo(()=>q?vo(q.permission,"edit")??"ask":"deny",[q]),Ve=c.useMemo(()=>{if(q)return vo(q.permission,"webfetch")},[q]),he=c.useMemo(()=>{if(!q)return;const ee=Bb(q.permission,"bash");return ee||void 0},[q]),ye=c.useMemo(()=>Tm({agentDefaultEditMode:re,webfetchPermission:Ve,bashPermission:he}),[re,Ve,he]),{cascadeDefaultMode:Le,modeAvailability:Qe,autoApproveAvailable:Ee}=ye,Te=!!(y&&a),Ye=Te&&y&&a?S(y,a,Le):Le,jt={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},ft=c.useCallback(ee=>!Qe[ee],[Qe]),It=c.useMemo(()=>!Te||ft(Ye)&&Ye!==Le?Le:Ye,[Le,ft,Te,Ye]),_t=[{mode:"ask",label:jt.ask,disabled:ft("ask")},{mode:"allow",label:jt.allow,disabled:ft("allow")},{mode:"full",label:jt.full,disabled:ft("full")}],Nt=c.useMemo(()=>zn(It),[It]),je=!Te||!Ee;c.useEffect(()=>{je&&(ge(!1),U(!1))},[je]);const _e=G?"mobile":H?"vscode":"default",Ge=_e==="mobile"?"h-9":_e==="vscode"?"h-6":"h-8",at=_e==="mobile"?"h-5 w-5":"h-4 w-4",Mt=_e==="mobile"?"h-5 w-5":"h-4 w-4",Yt=V?"typography-micro":"typography-meta",Jt=_e==="mobile"?"gap-x-2":_e==="vscode"?"gap-x-1":"gap-x-3",Ue=jt[It],Ze=c.useCallback((ee,ie=at)=>{const ce=T(ie,"flex-shrink-0"),we=zn(ee),He={color:we?we.text:"var(--foreground)"};return ee==="full"?e.jsx(mr,{className:ce,style:He}):ee==="allow"?e.jsx(Ao,{className:ce,style:He}):ee==="deny"?e.jsx(jn,{className:ce,style:He}):e.jsx(Kr,{className:ce,style:He})},[at]),ut=c.useCallback(ee=>{je||!y||!a||ft(ee)||(A(y,a,ee,Le),be(!1),ge(!1),U(!1))},[Le,je,y,a,A,be,U,ft]),tt=p(),ct=Array.isArray(tt?.models)?tt.models:[],it=t&&n?g(t,n):void 0,St=Ka(it),Z=$n(it,"input"),xe=$n(it,"output"),de=c.useMemo(()=>`${t}/${n}`?m():[],[m,t,n]),Oe=de.length>0,We=[{label:"Input",value:jo(it?.cost?.input)},{label:"Output",value:jo(it?.cost?.output)},{label:"Cache read",value:jo(it?.cost?.cache_read)},{label:"Cache write",value:jo(it?.cost?.cache_write)}],Xe=[{label:"Context",value:Os(it?.limit?.context)},{label:"Output",value:Os(it?.limit?.output)}],Ct=c.useRef(void 0),xt=y?x.get(y)?.length??-1:-1,Pt=c.useRef(null),At=c.useCallback((ee,ie,ce)=>{if(!ee||!ie)return"model-missing";const we=r.find(De=>De.id===ee);return we?(Array.isArray(we.models)?we.models:[]).find(De=>De.id===ie)?(l(ee),d(ie),y&&ce&&w(y,ce,ee,ie),"applied"):"model-missing":"provider-missing"},[r,l,d,y,w]);c.useEffect(()=>{if(!y){Pt.current=null;return}if(!E||r.length===0||j.length===0)return;(!Pt.current||Pt.current.sessionId!==y)&&(Pt.current={sessionId:y,resolved:!1,inFlight:!1});const ee=Pt.current;if(!ee||ee.resolved||ee.inFlight)return;let ie=!1;const ce=()=>{if(ie)return;const De=Pt.current;De&&De.sessionId===y&&(De.resolved=!0,De.inFlight=!1)},we=()=>{const De=N(y);if(De){a!==De&&f(De);const qe=k(y,De);if(qe){const Ae=At(qe.providerId,qe.modelId,De);if(Ae==="applied")return"resolved";if(Ae==="provider-missing")return"waiting"}else return"resolved"}for(const qe of j){const Ae=k(y,qe.name);if(!Ae)continue;a!==qe.name&&f(qe.name),v(y,qe.name);const Je=At(Ae.providerId,Ae.modelId,qe.name);if(Je==="applied")return"resolved";if(Je==="provider-missing")return"waiting"}return"continue"},ze=()=>{if(j.length===0)return;const De=j.filter(Ae=>wo(Ae.mode)),qe=j.find(Ae=>Ae.name==="build")||De[0]||j[0];qe&&(v(y,qe.name),a!==qe.name&&f(qe.name),qe.model?.providerID&&qe.model?.modelID&&At(qe.model.providerID,qe.model.modelID,qe.name))};return(async()=>{try{const De=we();if(De==="resolved"){ce();return}if(De==="waiting"||xt===-1)return;if(xt>0){ee.inFlight=!0;try{const qe=await C(y,j);if(ie)return;if(qe.size>0){let Ae=null,Je=-1/0;for(const[vt,gt]of qe)gt.timestamp>Je&&(Je=gt.timestamp,Ae=vt);if(Ae){v(y,Ae),a!==Ae&&f(Ae);const vt=qe.get(Ae);if(vt){const gt=At(vt.providerId,vt.modelId,Ae);if(gt==="applied"){ce();return}if(gt==="provider-missing")return}else{ce();return}}}}catch(qe){ie||console.error("[ModelControls] Error resolving session from messages:",qe)}finally{const qe=Pt.current;!ie&&qe&&qe.sessionId===y&&(qe.inFlight=!1)}}ze(),ce()}catch(De){ie||console.error("[ModelControls] Error in session switch:",De)}})(),()=>{ie=!0}},[y,xt,j,a,N,k,f,At,C,v,E,r]),c.useEffect(()=>{if(!E||!y||r.length===0||j.length===0)return;const ie=N(y)||a;if(!ie)return;const ce=k(y,ie);if(!ce)return;const we=r.find(qe=>qe.id===ce.providerId);if(!we||!(Array.isArray(we.models)?we.models.some(qe=>qe.id===ce.modelId):!1))return;const He=t===ce.providerId,De=n===ce.modelId;He&&De||(ie!==a&&f(ie),At(ce.providerId,ce.modelId,ie))},[E,y,a,t,n,r,j,N,k,At,f]),c.useEffect(()=>{if(!E)return;(async()=>{try{if(a!==Ct.current&&(Ct.current=a,a&&y)){await new Promise(we=>setTimeout(we,50));const ie=k(y,a);if(ie){const we=At(ie.providerId,ie.modelId,a);if(we==="applied"||we==="provider-missing")return}const ce=j.find(we=>we.name===a);if(ce?.model?.providerID&&ce?.model?.modelID&&At(ce.model.providerID,ce.model.modelID,a)==="provider-missing")return}}catch(ie){console.error("[ModelControls] Agent change error:",ie)}})()},[a,y,k,At,j,E]),c.useEffect(()=>{if(!E||!a){u(void 0);return}if(!t||!n){u(void 0);return}if(de.length===0){u(void 0);return}if(o&&!de.includes(o)){u(void 0);return}if(!y){if(!o){const ce=i&&de.includes(i)?i:void 0;u(ce)}return}const ee=M(y,a,t,n),ie=ee&&de.includes(ee)?ee:void 0;u(ie)},[de,E,y,a,t,n,o,M,u,i]);const Fe=c.useCallback(ee=>{u(ee),y&&a&&t&&n&&D(y,a,t,n,ee)},[a,n,t,y,D,u]),et=ee=>{try{f(ee),be(!1),y&&v(y,ee),V&&F()}catch(ie){console.error("[ModelControls] Handle agent change error:",ie)}},Be=(ee,ie)=>{try{const ce=At(ee,ie,a||void 0);if(ce!=="applied"){ce==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",ee):ce==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:ee,modelId:ie});return}P(ee,ie),be(!1),V&&F(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(ce){console.error("[ModelControls] Handle model change error:",ce)}},Ke=ee=>{const ie=typeof ee?.name=="string"?ee.name:typeof ee?.id=="string"?ee.id:"";return ie.length>40?ie.substring(0,37)+"...":ie},wt=()=>r.find(ie=>ie.id===t)?.name||t,Lt=()=>{if(!t||!n||ct.length===0)return"Not selected";const ee=ct.find(ie=>ie.id===n);return Ke(ee)},ts=()=>{if(!a){const ie=j.filter(ze=>wo(ze.mode)),we=ie.find(ze=>ze.name==="build")||ie[0];return we?es(we.name):"Select Agent"}const ee=j.find(ie=>ie.name===a);return es(ee?ee.name:a)},es=ee=>ee.charAt(0).toUpperCase()+ee.slice(1),ps=(ee,ie,ce)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:ie,"aria-label":ie,role:"img",children:e.jsx(ee,{className:"h-3.5 w-3.5"})},ce),lr=c.useCallback(ee=>{fe(ie=>{const ce=new Set(ie);return ce.has(ee)?ce.delete(ee):ce.add(ee),ce})},[]),Ot=c.useCallback(ee=>{z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{le(ee)},500)},[]),vr=c.useCallback(()=>{z.current&&clearTimeout(z.current)},[]);c.useEffect(()=>()=>{z.current&&clearTimeout(z.current)},[]);const Pn=()=>!V||Y!=="model"?null:e.jsx(ws,{open:!0,onClose:$,title:it?.name||Lt(),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:wt()})]}),St.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:St.map(({key:ee,icon:ie,label:ce})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[ps(ie,ce,`cap-${ee}`),e.jsx("span",{className:"typography-meta text-foreground",children:ce})]},ee))})]}),(Z.length>0||xe.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[Z.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:Z.map(({key:ee,icon:ie,label:ce})=>ps(ie,`${ce} input`,`input-${ee}`))})]}),xe.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Output"}),e.jsx("div",{className:"flex gap-1",children:xe.map(({key:ee,icon:ie,label:ce})=>ps(ie,`${ce} output`,`output-${ee}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Os(it?.limit?.context)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Output"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Os(it?.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:Gc(it?.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:qc(it?.release_date)})]})]})]})]})}),va=()=>{if(!V||Y!=="agent"||!q)return null;const ee=!!(q.prompt&&q.prompt.trim().length>0),ie=q.model?.providerID&&q.model?.modelID,ce=q.temperature!==void 0||q.topP!==void 0,we=qe=>{const Ae=sa(q.permission)??[],Je=Ae.some(gt=>gt.permission===qe&&gt.pattern!=="*"),vt=vo(Ae,qe)??"ask";return Je?{mode:"ask",label:"Custom"}:vt==="allow"?{mode:"allow",label:"Allow"}:vt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},ze=we("edit"),He=we("bash"),De=we("webfetch");return e.jsx(ws,{open:!0,onClose:$,title:es(q.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[q.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:q.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:q.mode==="primary"?"Primary":q.mode==="subagent"?"Subagent":q.mode==="all"?"All":"—"})]}),(ie||ce)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),ie&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[q.model.providerID," / ",q.model.modelID]}),ce&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[q.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:q.temperature})]}),q.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:q.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ze(ze.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ze.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ze(He.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:He.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ze(De.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:De.label})]})]})]})]}),ee&&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(Ao,{className:"h-4 w-4 text-foreground"})]})})]})})},ja=()=>{if(!V)return null;const ee=I.trim(),ie=r.map(ce=>{const we=Array.isArray(ce.models)?ce.models:[],ze=ee.length===0?!0:Is(ce.name,ee)||Is(ce.id,ee),He=ee.length===0?we:we.filter(De=>{const qe=Ke(De),Ae=typeof De.id=="string"?De.id:"";return Is(qe,ee)||Is(Ae,ee)});return{provider:ce,providerModels:He,matchesProvider:ze}}).filter(({matchesProvider:ce,providerModels:we})=>ce||we.length>0);return e.jsx(ws,{open:oe==="model",onClose:F,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{value:I,onChange:ce=>W(ce.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),I&&e.jsx("button",{type:"button",onClick:()=>W(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(jn,{className:"h-4 w-4"})})]})}),ie.length===0&&e.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),!I&&K.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(fr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:K.map(({model:ce,providerID:we,modelID:ze})=>{const He=we===t&&ze===n,De=g(we,ze);return e.jsxs("button",{type:"button",onClick:()=>Be(we,ze),className:T("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",He?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ns,{providerId:we,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ke(ce)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(De?.limit?.context||De?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[De?.limit?.context?`${Os(De?.limit?.context)} ctx`:"",De?.limit?.context&&De?.limit?.output?" • ":"",De?.limit?.output?`${Os(De?.limit?.output)} out`:""]})})]},`fav-mobile-${we}-${ze}`)})})]}),!I&&L.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(or,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:L.map(({model:ce,providerID:we,modelID:ze})=>{const He=we===t&&ze===n,De=g(we,ze);return e.jsxs("button",{type:"button",onClick:()=>Be(we,ze),className:T("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",He?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ns,{providerId:we,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ke(ce)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(De?.limit?.context||De?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[De?.limit?.context?`${Os(De?.limit?.context)} ctx`:"",De?.limit?.context&&De?.limit?.output?" • ":"",De?.limit?.output?`${Os(De?.limit?.output)} out`:""]})})]},`recent-mobile-${we}-${ze}`)})})]}),ie.map(({provider:ce,providerModels:we})=>{if(we.length===0&&!ee.length)return null;const ze=ce.id===t,He=X.has(ce.id)||ee.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>lr(ce.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":He,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{providerId:ce.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ce.name}),ze&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),He?e.jsx(Et,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Us,{className:"h-3 w-3 text-muted-foreground"})]}),He&&we.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:we.map(De=>{const qe=ze&&De.id===n,Ae=g(ce.id,De.id),Je=Ka(Ae).slice(0,3),vt=$n(Ae,"input");return e.jsxs("div",{className:T("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",!qe&&"hover:bg-muted",qe?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Be(ce.id,De.id),className:T("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:Ke(De)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Ae?.limit?.context||Ae?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Ae?.limit?.context?e.jsxs("span",{children:[Os(Ae?.limit?.context)," ctx"]}):null,Ae?.limit?.context&&Ae?.limit?.output?e.jsx("span",{children:"•"}):null,Ae?.limit?.output?e.jsxs("span",{children:[Os(Ae?.limit?.output)," out"]}):null]}),(Je.length>0||vt.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Je,...vt].map(({key:gt,icon:bs,label:Rs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Rs,"aria-label":Rs,children:e.jsx(bs,{className:"h-3 w-3"})},`meta-${ce.id}-${De.id}-${gt}`))})]})]}),e.jsx("button",{type:"button",onClick:gt=>{gt.preventDefault(),gt.stopPropagation(),R(ce.id,De.id)},className:T("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",_(ce.id,De.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":_(ce.id,De.id)?"Unfavorite":"Favorite",title:_(ce.id,De.id)?"Remove from favorites":"Add to favorites",children:_(ce.id,De.id)?e.jsx(fr,{className:"h-4 w-4"}):e.jsx(xn,{className:"h-4 w-4"})})]},De.id)})})]},ce.id)})]})})},Rr=()=>{if(!V||!Oe)return null;const ee=!o,ie=ce=>{Fe(ce),F(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(ws,{open:oe==="variant",onClose:F,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",ee?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ie(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),ee&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),de.map(ce=>{const we=o===ce,ze=ce.charAt(0).toUpperCase()+ce.slice(1);return e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",we?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ie(ce),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ze}),we&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},ce)})]})})},_r=()=>{if(!V)return null;const ee=j.filter(ie=>wo(ie.mode));return e.jsx(ws,{open:oe==="agent",onClose:F,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ee.map(ie=>{const ce=ie.name===a,we=kr(ie.name);return e.jsxs("button",{type:"button",className:T("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",we.class,ce?"active":"border-border/40"),onClick:()=>et(ie.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("h-2 w-2 rounded-full",we.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:ce?{color:`var(${we.var})`}:void 0,children:es(ie.name)})]}),ie.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:ie.description})]},ie.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:je,onClick:()=>{je||ge(ie=>!ie)},className:T("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",je?"cursor-not-allowed opacity-60":void 0),children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:Nt?Nt.text:"var(--foreground)",mixBlendMode:"normal"},children:Ue})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!Nt&&"text-muted-foreground"),style:Nt?{color:Nt.text}:void 0,children:Ze(It,at)}),e.jsx(Et,{className:T("h-4 w-4 text-muted-foreground transition-transform",ve?"rotate-180":"")})]})]}),ve&&!je&&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:_t.map(ie=>{const ce=ie.mode===It,we=zn(ie.mode);return e.jsxs("button",{type:"button",disabled:ie.disabled,onClick:()=>ut(ie.mode),className:T("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",ie.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",ce?"bg-primary/10":void 0),style:ce&&we?{backgroundColor:we.background??void 0}:void 0,children:[Ze(ie.mode,at),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:we?we.text:"var(--foreground)"},children:ie.label})})]},ie.mode)})})})]})]})})},Tl=()=>e.jsx(rt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:it?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:it.name||Lt()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:wt()})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:St.length>0?St.map(({key:ee,icon:ie,label:ce})=>ps(ie,ce,`cap-${ee}`)):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:Z.length>0?Z.map(({key:ee,icon:ie,label:ce})=>ps(ie,`${ce} input`,`input-${ee}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:xe.length>0?xe.map(({key:ee,icon:ie,label:ce})=>ps(ie,`${ce} output`,`output-${ee}`)):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)"}),We.map(ee=>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:ee.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ee.value})]},ee.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"}),Xe.map(ee=>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:ee.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ee.value})]},ee.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:Gc(it.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:qc(it.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),on=(ee,ie,ce,we,ze,He)=>{const De=g(ie,ce),qe=Ka(De).map(hs=>({...hs,id:`cap-${hs.key}`})),Ae=[...$n(De,"input"),...$n(De,"output")],Je=Array.from(new Map(Ae.map(hs=>[hs.key,hs])).values()).map(hs=>({...hs,id:`mod-${hs.key}`})),vt=[...qe,...Je],gt=Os(De?.limit?.context),bs=t===ie&&n===ce,Rs=_(ie,ce);return e.jsxs("div",{ref:hs=>{Se.current[ze]=hs},className:T("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",He?"bg-accent":"hover:bg-accent/50"),onClick:()=>Be(ie,ce),onMouseEnter:()=>Me(ze),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:Ke(ee)}),De?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:gt}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[vt.length>0&&e.jsx("div",{className:T("items-center gap-0.5",He?"flex":"hidden group-hover:flex"),children:vt.map(({id:hs,icon:Nf,label:Fl})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Fl,role:"img",title:Fl,children:e.jsx(Nf,{className:"h-2.5 w-2.5"})},hs))}),bs&&e.jsx(Tt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:hs=>{hs.preventDefault(),hs.stopPropagation(),R(ie,ce)},className:T("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Rs?"text-yellow-500":"text-muted-foreground"),"aria-label":Rs?"Unfavorite":"Favorite",title:Rs?"Remove from favorites":"Add to favorites",children:Rs?e.jsx(fr,{className:"h-3.5 w-3.5"}):e.jsx(xn,{className:"h-3.5 w-3.5"})})]})]},`${we}-${ie}-${ce}`)},Tn=(ee,ie,ce)=>ce.trim()?Is(ee,ce)||Is(ie,ce):!0,Sa=()=>{const ee=K.filter(({model:Ae,providerID:Je})=>{const gt=r.find(Rs=>Rs.id===Je)?.name||Je,bs=Ke(Ae);return Tn(bs,gt,te)}),ie=L.filter(({model:Ae,providerID:Je})=>{const gt=r.find(Rs=>Rs.id===Je)?.name||Je,bs=Ke(Ae);return Tn(bs,gt,te)}),ce=r.map(Ae=>{const vt=(Array.isArray(Ae.models)?Ae.models:[]).filter(gt=>{const bs=Ke(gt);return Tn(bs,Ae.name||Ae.id||"",te)});return{...Ae,models:vt}}).filter(Ae=>Ae.models.length>0),we=ee.length>0||ie.length>0||ce.length>0,ze=[];ee.forEach(({model:Ae,providerID:Je,modelID:vt})=>{ze.push({model:Ae,providerID:Je,modelID:vt,section:"fav"})}),ie.forEach(({model:Ae,providerID:Je,modelID:vt})=>{ze.push({model:Ae,providerID:Je,modelID:vt,section:"recent"})}),ce.forEach(Ae=>{Ae.models.forEach(Je=>{ze.push({model:Je,providerID:Ae.id,modelID:Je.id,section:"provider"})})});const He=ze.length,De=Ae=>{if(Ae.key==="ArrowDown")Ae.preventDefault(),Ae.stopPropagation(),Me(Je=>(Je+1)%Math.max(1,He)),setTimeout(()=>{const Je=(me+1)%Math.max(1,He);Se.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Ae.key==="ArrowUp")Ae.preventDefault(),Ae.stopPropagation(),Me(Je=>(Je-1+Math.max(1,He))%Math.max(1,He)),setTimeout(()=>{const Je=(me-1+Math.max(1,He))%Math.max(1,He);Se.current[Je]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Ae.key==="Enter"){Ae.preventDefault(),Ae.stopPropagation();const Je=ze[me];Je&&Be(Je.providerID,Je.modelID)}else Ae.key==="Escape"&&(Ae.preventDefault(),Ae.stopPropagation(),be(!1))};let qe=0;return e.jsxs(nt,{delayDuration:1e3,children:[V?e.jsxs("button",{type:"button",onClick:()=>se("model"),onTouchStart:()=>Ot("model"),onTouchEnd:vr,onTouchCancel:vr,className:T("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",Ge),children:[t?e.jsx(ns,{providerId:t,className:T(Mt,"flex-shrink-0")}):e.jsx(mr,{className:T(Mt,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label typography-micro font-medium truncate min-w-0",!G&&"max-w-[220px]"),children:Lt()})]}):e.jsxs(Ut,{open:Re,onOpenChange:be,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:T("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",Ge),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(ns,{providerId:t,className:T(Mt,"flex-shrink-0")}),e.jsx(mr,{className:T(Mt,"text-primary/60 hidden")})]}):e.jsx(mr,{className:T(Mt,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label",Yt,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:Lt()},`${t}-${n}`)]})})}),e.jsxs(Gt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{type:"text",placeholder:"Search models",value:te,onChange:Ae=>pe(Ae.target.value),onKeyDown:De,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(mt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!we&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),ee.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),ee.map(({model:Ae,providerID:Je,modelID:vt})=>{const gt=qe++;return on(Ae,Je,vt,"fav",gt,me===gt)})]}),ie.length>0&&e.jsxs(e.Fragment,{children:[ee.length>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),ie.map(({model:Ae,providerID:Je,modelID:vt})=>{const gt=qe++;return on(Ae,Je,vt,"recent",gt,me===gt)})]}),(ee.length>0||ie.length>0)&&ce.length>0&&e.jsx(Ms,{}),ce.map((Ae,Je)=>e.jsxs(c.Fragment,{children:[Je>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ns,{providerId:Ae.id,className:"h-4 w-4 flex-shrink-0"}),Ae.name]}),Ae.models.map(vt=>{const gt=qe++;return on(vt,Ae.id,vt.id,"provider",gt,me===gt)})]},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"})]})]}),Tl()]})},ao=()=>{if(!q)return e.jsx(rt,{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 ee=!!(q.prompt&&q.prompt.trim().length>0),ie=q.model?.providerID&&q.model?.modelID,ce=q.temperature!==void 0||q.topP!==void 0,we=qe=>{const Ae=sa(q.permission)??[],Je=Ae.some(gt=>gt.permission===qe&&gt.pattern!=="*"),vt=vo(Ae,qe)??"ask";return Je?{mode:"ask",label:"Custom"}:vt==="allow"?{mode:"allow",label:"Allow"}:vt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},ze=we("edit"),He=we("bash"),De=we("webfetch");return e.jsx(rt,{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:es(q.name)}),q.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:q.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:q.mode==="primary"?"Primary":q.mode==="subagent"?"Subagent":q.mode==="all"?"All":"—"})]}),(ie||ce)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),ie?e.jsxs("span",{className:"typography-meta text-foreground",children:[q.model.providerID," / ",q.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),ce&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[q.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:q.temperature})]}),q.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:q.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ze(ze.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:ze.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ze(He.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:He.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ze(De.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:De.label})]})]})]}),ee&&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(Ao,{className:"h-4 w-4 text-foreground"})]})]})})},ka=()=>{if(!Oe)return null;const ee=o??"Default",ie=!o,ce=ie?"text-muted-foreground":"text-[color:var(--status-info)]";return V?e.jsxs("button",{type:"button",onClick:()=>se("variant"),className:T("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ge,"cursor-pointer hover:opacity-70"),children:[e.jsx(ar,{className:T(Mt,"flex-shrink-0",ce)}),e.jsx("span",{className:T("model-controls__variant-label",Yt,"font-medium truncate min-w-0",ce),children:ee})]}):e.jsxs(nt,{delayDuration:800,children:[e.jsxs(Ut,{children:[e.jsx(ot,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:T("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ge),children:[e.jsx(ar,{className:T(Mt,"flex-shrink-0",ce)}),e.jsx("span",{className:T("model-controls__variant-label",Yt,"font-medium min-w-0 truncate",B?"max-w-[180px]":void 0,ce),children:ee})]})})}),e.jsxs(Gt,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Wr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(kt,{className:"typography-meta",onSelect:()=>Fe(void 0),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:"Default"}),ie&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),de.length>0&&e.jsx(Ms,{}),de.map(we=>{const ze=o===we,He=we.charAt(0).toUpperCase()+we.slice(1);return e.jsx(kt,{className:"typography-meta",onSelect:()=>Fe(we),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:He}),ze&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},we)})]})]}),e.jsx(rt,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",ee]})})]})},Na=()=>V?e.jsxs("button",{type:"button",onClick:()=>se("agent"),onTouchStart:()=>Ot("agent"),onTouchEnd:vr,onTouchCancel:vr,className:T("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ge,"cursor-pointer hover:opacity-70",V&&"ml-1"),children:[e.jsx(Qr,{className:T(Mt,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${kr(a).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",Yt,"font-medium truncate min-w-0"),style:a?{color:`var(${kr(a).var})`}:void 0,children:ts()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(nt,{delayDuration:1e3,children:[e.jsxs(Ut,{children:[e.jsx(ot,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ge),children:[e.jsx(Qr,{className:T(Mt,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${kr(a).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",Yt,"font-medium min-w-0 truncate",B?"max-w-[220px]":void 0),style:a?{color:`var(${kr(a).var})`}:void 0,children:ts()})]})})}),e.jsxs(Gt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[j.filter(ee=>wo(ee.mode)).map(ee=>e.jsx(kt,{className:"typography-meta",onSelect:()=>et(ee.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:T("h-1 w-1 rounded-full agent-dot",kr(ee.name).class)}),e.jsx("span",{className:"font-medium",children:es(ee.name)})]}),ee.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:ee.description})]})},ee.name)),e.jsx(Ms,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:je,onClick:()=>{je||U(ee=>!ee)},className:T("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",je?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Ie,"aria-controls":Q,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:Nt?Nt.text:"var(--foreground)"},children:Ue})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!Nt&&"text-muted-foreground"),style:Nt?{color:Nt.text}:void 0,children:Ze(It)}),e.jsx(Et,{className:T("h-3.5 w-3.5 transition-transform text-muted-foreground",Ie?"rotate-180":"")})]})]}),Ie&&!je&&e.jsx("div",{id:Q,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:_t.map(ee=>{const ie=ee.mode===It,ce=zn(ee.mode);return e.jsxs("button",{type:"button",disabled:ee.disabled,onClick:()=>ut(ee.mode),className:T("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",ee.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",ie?"bg-primary/10":void 0),style:ie&&ce?{backgroundColor:ce.background??void 0}:void 0,children:[Ze(ee.mode,at),e.jsx("span",{className:"typography-meta font-medium",style:{color:ce?ce.text:"var(--foreground)"},children:ee.label})]},ee.mode)})})]})]})]}),ao()]})}),ae=T("@container/model-controls flex items-center min-w-0",G&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:ae,children:e.jsxs("div",{className:T("flex items-center min-w-0 flex-1 justify-end",Jt,G&&"overflow-hidden"),children:[ka(),Sa(),Na()]})}),ja(),Rr(),_r(),Pn(),va()]})},Gb=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,Yc=(s,r)=>{if(typeof s!="string"||s.length===0)return{sanitizedText:s,mention:null};const t=r.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!s.includes("#"))return{sanitizedText:s,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(s))!==null;){const l=i.index,d=l+i[0].length,u=l>0?s[l-1]:null;if(!Gb(u))continue;const m={name:o.name,source:{value:i[0],start:l,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},Fm=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),Ti=zt()(Kt((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const n=ue.getState().getDirectoryForSession(t),a=(n?await ke.withDirectory(n,()=>ke.getSessionTodos(t)):await ke.getSessionTodos(t)).map(Fm);s(i=>{const l=new Map(i.sessionTodos);return l.set(t,a),{sessionTodos:l,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),s({isLoading:!1})}}},updateTodos:(t,n)=>{s(o=>{const a=new Map(o.sessionTodos);return a.set(t,n),{sessionTodos:a}})},getTodosForSession:t=>r().sessionTodos.get(t)||[],clearTodos:t=>{s(n=>{const o=new Map(n.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),qb=(s,r)=>{const t=r.map(Fm);Ti.getState().updateTodos(s,t)},Qc=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(fn.span,{...t,className:T("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)=>Ce.createElement(fn.span,{...t,key:n+String(o),className:T("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:T("invisible",r),children:s}),e.jsx("span",{...t,className:T("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:T("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(fn.span,{...t,className:T("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((i,l)=>e.jsx(fn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))}),e.jsx("div",{className:T("absolute inset-0"),children:a.map((i,l)=>e.jsx(fn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:T("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:T("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:T("text-primary-muted",r),children:s})})}];function Ya({variant:s="shine",className:r,...t}){const a=Qc.find(i=>i.variant===s)?.component||Qc[0].component;return e.jsx(tu,{children:e.jsx(a,{...t,className:r})})}const Xc=1500,Kb=2e3;function Yb({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:i}){const[l,d]=Ce.useState("idle"),[u,m]=Ce.useState(null),[f,p]=Ce.useState(!1),g=Ce.useRef(0),b=Ce.useRef(null),h=Ce.useRef(null),j=Ce.useRef(null),y=Ce.useRef(null),x=Ce.useRef(!1),v=Ce.useRef(!1),N=Ce.useRef(!1),w=Ce.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null),j.current&&(clearTimeout(j.current),j.current=null)},[]),k=Ce.useCallback((R,_)=>{w(),b.current=null,m(R),p(_),d("showing"),g.current=Date.now(),x.current=!0},[w]),D=Ce.useCallback(()=>{if(h.current)return;const R=Date.now()-g.current,_=Math.max(0,Xc-R);h.current=setTimeout(()=>{h.current=null;const P=b.current;P&&k(P.text,P.permission)},_)},[k]),M=Ce.useCallback(R=>{if(w(),b.current=null,!x.current){d("idle"),m(null),i?.(!1);return}if(R==="done"&&o&&y.current===o){d("idle"),m(null),x.current=!1,i?.(!1);return}R==="done"&&o&&(y.current=o),d(R),m(null),i?.(!0),j.current=setTimeout(()=>{j.current=null,d("idle"),x.current=!1,i?.(!1)},Kb)},[w,o,i]);if(Ce.useEffect(()=>{if(n&&!N.current){N.current=!0,M("aborted");return}if(N.current=!!n,a&&!v.current){v.current=!0,M("done");return}if(!a&&v.current&&(v.current=!1),!(l==="done"||l==="aborted")&&s){const _=Date.now()-g.current;if(l==="idle"||!u)k(s,!!t);else if(s!==u||!!t!==f){if(r)return;_>=Xc?k(s,!!t):(b.current={text:s,permission:!!t},D())}}},[s,t,n,a,l,u,f,k,M,D,r]),Ce.useEffect(()=>()=>w(),[w]),Ce.useEffect(()=>{const R=()=>{typeof document>"u"||document.visibilityState==="visible"&&(l==="done"||l==="aborted")&&(w(),d("idle"),m(null),x.current=!1)};return document.addEventListener("visibilitychange",R),()=>document.removeEventListener("visibilitychange",R)},[l,w]),l==="idle"&&!u)return null;let C,S=!0;l==="done"?(C="Done",S=!1):l==="aborted"?(C="Aborted",S=!1):u?C=u.charAt(0).toUpperCase()+u.slice(1):C="Working";const A=S?`${C}...`:C,E=l!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${E?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":C,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:l==="done"?e.jsx(Ya,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):l==="aborted"?e.jsx(Ya,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(Ya,{variant:"shine",className:"typography-ui-header",children:A})})})}const Jc={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Qb=({todo:s})=>{const r=Jc[s.status]||Jc.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:T("flex-1 typography-ui-label",r.textClassName),children:s.content})})},Zc=[],Xb=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:i,isComplete:l,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=c.useState(!1),g=ue(_=>_.currentSessionId),b=Ti(_=>g?_.sessionTodos.get(g)??Zc:Zc),h=Ti(_=>_.loadTodos),{isMobile:j}=$e(),y=j||Ht();c.useEffect(()=>{g&&h(g)},[g,h]);const x=c.useMemo(()=>{const _={in_progress:0,pending:1,completed:2,cancelled:3};return[...b].filter(P=>P.status!=="cancelled").sort((P,O)=>_[P.status]-_[O.status])},[b]),v=c.useMemo(()=>x.find(_=>_.status==="in_progress")||x.find(_=>_.status==="pending")||null,[x]),N=c.useMemo(()=>{const _=b.filter(O=>O.status!=="cancelled").length;return{completed:b.filter(O=>O.status==="completed").length,total:_}},[b]),w=x.length>0,k=!m&&(o||!a),[D,M]=c.useState(!1),C=s||l||o||D||w||m,S=c.useRef(null);if(c.useEffect(()=>{if(!f)return;const _=P=>{S.current&&!S.current.contains(P.target)&&p(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[f]),!C)return null;const A=()=>p(_=>!_),E=d&&u?e.jsx("button",{type:"button",onClick:u,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(jn,{size:18,"aria-hidden":"true"})}):null,R=w?e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!y&&v?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:v.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[N.completed,"/",N.total]}),f?e.jsx(ia,{className:"h-3.5 w-3.5"}):e.jsx(Et,{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(jn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(Yb,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:i??null,isComplete:l,onResultVisibilityChange:M},g??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:S,children:[E,R,f&&w&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:T("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:x.map(_=>e.jsx(Qb,{todo:_},_.id))})]})]})]})})},Fi=s=>!s||typeof s!="object"?!1:!!s.synthetic,ed=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>Fi(r)),Jb=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!Fi(t))?s.filter(t=>!Fi(t)):s,Zb={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function ew(s){const r=ue(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return c.useMemo(()=>{if(r==="idle")return Zb;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function Sl(){const s=ue(r=>r.currentSessionId);return ew(s)}const tw={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},td=s=>s.role==="assistant",sw=s=>s.type==="reasoning",Rm=s=>s.type==="text",sd=s=>{if(Rm(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},rd=s=>(Rm(s)||sw(s),s.time),rw=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function _m(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=ue(qi(g=>({currentSessionId:g.currentSessionId,messages:g.messages,permissions:g.permissions,sessionAbortFlags:g.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=Sl(),l=c.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=c.useMemo(()=>{if(l.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const g=l.filter(C=>td(C.info)&&!ed(C.parts));if(g.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const b=[...g].sort((C,S)=>{const A=typeof C.info.time?.created=="number"?C.info.time.created:null,E=typeof S.info.time?.created=="number"?S.info.time.created:null;return A!==null&&E!==null&&A!==E?A-E:C.info.id.localeCompare(S.info.id)}),h=b[b.length-1];let j,y;const x=new Set(["edit","write"]);for(let C=(h.parts??[]).length-1;C>=0;C-=1){const S=h.parts?.[C];if(S)switch(S.type){case"reasoning":{const A=S.time??rd(S);(!A||typeof A.end>"u")&&!j&&(j="reasoning");break}case"tool":{const A=S.state?.status;if((A==="running"||A==="pending")&&!j){const E=rw(S);x.has(E)?j="editing":(j="tool",y=E)}break}case"text":{const A=sd(S)??"";if(typeof A=="string"&&A.trim().length>0){const E=rd(S);(!E||typeof E.end>"u")&&!j&&(j="text")}break}}}const v={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos",skill:"learning skill",question:"asking question"},N=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],w=C=>v[C]??`using ${C}`,k=()=>N[Math.floor(Math.random()*N.length)],D=j===void 0,M=j==="editing"?"editing file":j==="tool"&&y?w(y):j==="reasoning"?"thinking":j==="text"?"composing":k();return{activePartType:j,activeToolName:y,statusText:M,isGenericStatus:D}},[l]),u=c.useMemo(()=>{const g=s,b=g?n?.get(g)??null:null,h=!!(b&&!b.acknowledged);return{wasAborted:h,abortActive:h}},[s,n]),m=c.useMemo(()=>{if(u.wasAborted)return{...tw,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const g=a,b=o==="busy",h=i;let j="idle";return g&&(d.activePartType==="tool"||d.activePartType==="editing"?j="tooling":j=h?"cooldown":"streaming"),{activity:j,hasWorkingContext:g,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:g,isStreaming:b,isCooldown:h,lifecyclePhase:b?"streaming":h?"cooldown":null,statusText:g?d.statusText:null,isGenericStatus:g?d.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:g,compactionDeadline:null,activePartType:g?d.activePartType:void 0,activeToolName:g?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:h}},[o,a,i,d,u]),f=c.useMemo(()=>{const g=a&&d.activePartType==="text";if(!g||l.length===0)return{isActive:g,characterCount:0};const b=l.filter(y=>td(y.info)&&!ed(y.parts));if(b.length===0)return{isActive:g,characterCount:0};const h=b[b.length-1];let j=0;return(h.parts??[]).forEach(y=>{if(y.type!=="text")return;const x=sd(y)??"";typeof x=="string"&&x.trim().length>0&&(j+=x.length)}),{isActive:g,characterCount:j}},[l,a,d.activePartType]),p=c.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const g=s;return(g?t?.get(g)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[s,t,m]);return{forming:f,working:p}}const nw=8,nd=[],ow=s=>s==="primary"||s==="all"||s===void 0||s===null,Om=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},od=(s,r)=>{const t=Om(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},aw=(s,r)=>{const t=Om(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},So=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=c.useState(""),[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,u]=c.useState(""),[m,f]=c.useState(!1),[p,g]=c.useState(""),[b,h]=c.useState(!1),[j,y]=c.useState(""),[x,v]=c.useState(!1),[N,w]=c.useState(""),[k,D]=c.useState(null),M=c.useRef(null),C=c.useRef(null),S=c.useRef(null),A=c.useRef(null),E=c.useRef(null),R=c.useRef(null),_=ue(ae=>ae.sendMessage),P=ue(ae=>ae.currentSessionId),O=ue(ae=>ae.newSessionDraft?.open),J=ue(ae=>ae.abortCurrentOperation),K=ue(ae=>ae.acknowledgeSessionAbort),L=ue(ae=>ae.abortPromptSessionId),G=ue(ae=>ae.abortPromptExpiresAt),B=ue(ae=>ae.clearAbortPrompt),H=ue(ae=>ae.sessionAbortFlags),V=ue(ae=>ae.attachedFiles),oe=ue(ae=>ae.addAttachedFile),se=ue(ae=>ae.addServerFile),Y=ue(ae=>ae.clearAttachedFiles),le=ue(ae=>ae.saveSessionAgentSelection),I=ue(ae=>ae.consumePendingInputText),W=ue(ae=>ae.pendingInputText),{currentProviderId:F,currentModelId:$,currentVariant:z,currentAgentName:X,setAgent:fe,getVisibleAgents:ve}=st(),ge=ve(),{isMobile:Re,inputBarOffset:be,isKeyboardOpen:Ie,setTimelineDialogOpen:U}=$e(),{working:Q}=_m(),[te,pe]=c.useState(!1),me=c.useRef(null),Me=c.useRef(!1),Se=c.useRef(!1),Pe=Zs(ae=>ae.queueModeEnabled),q=Zs(c.useCallback(ae=>P?ae.queuedMessages[P]??nd:nd,[P])),re=Zs(ae=>ae.addToQueue),Ve=Zs(ae=>ae.clearQueue),{phase:he}=Sl(),ye=c.useRef(he),Le=c.useRef(!1),Qe=c.useCallback(ae=>{if(!Re||ae.pointerType!=="touch")return;const ee=M.current;if(!ee||document.activeElement===ee)return;ae.preventDefault(),ae.stopPropagation();const ie=document.scrollingElement;ie&&ie.scrollTop!==0&&(ie.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{ee.focus({preventScroll:!0})}catch{ee.focus()}const ce=ee.value.length;try{ee.setSelectionRange(ce,ce)}catch{}},[Re]);c.useEffect(()=>{if(W!==null){const ae=I();ae&&(n(ae),setTimeout(()=>{M.current?.focus()},0))}},[W,I]);const Ee=c.useMemo(()=>{if(X)return ge.find(ae=>ae.name===X)},[ge,X]),Te=c.useMemo(()=>Ee?od(Ee.permission,"edit")??"ask":"deny",[Ee]),Ye=ue(c.useCallback(ae=>!P||!X?void 0:ae.sessionAgentEditModes.get(P)?.get(X),[P,X])),jt=c.useMemo(()=>{if(Ee)return od(Ee.permission,"webfetch")},[Ee]),ft=c.useMemo(()=>{if(!Ee)return;const ae=aw(Ee.permission,"bash");return ae||void 0},[Ee]),It=c.useMemo(()=>Tm({agentDefaultEditMode:Te,webfetchPermission:jt,bashPermission:ft}),[Te,jt,ft]),_t=!!(P&&X),Nt=c.useMemo(()=>_t&&Ye&&It.modeAvailability[Ye]?Ye:It.cascadeDefaultMode,[It,_t,Ye]),je=c.useMemo(()=>zn(Nt),[Nt]),_e=c.useCallback(ae=>Ht()?`color-mix(in srgb, ${ae} 55%, transparent)`:ae,[]),Ge=c.useMemo(()=>{const ae=Ht()?1:2;if(!je)return{borderWidth:ae};const ee=je.border??je.text;return{borderColor:_e(ee),borderWidth:ae}},[je,_e]),at=t.trim()||V.length>0,Mt=q.length>0,Yt=at||Mt,Jt=Q.isWorking,Ue=c.useMemo(()=>P?L===P&&!!G:!1,[L,G,P]),Ze=c.useCallback(()=>{if(!at||!P)return;const ae=t.replace(/^\n+|\n+$/g,""),ee=V.map(ie=>({...ie}));re(P,{content:ae,attachments:ee.length>0?ee:void 0}),n(""),ee.length>0&&Y(),Re||M.current?.focus()},[at,P,t,V,re,Y,Re]),ut=async ae=>{if(ae?.preventDefault(),!Yt||!P&&!O)return;if(r?.({instant:!0,force:!0}),!F||!$){console.warn("Cannot send message: provider or model not selected");return}let ee="",ie=[],ce;const we=[];for(let De=0;De<q.length;De++){const qe=q[De],{sanitizedText:Ae,mention:Je}=Yc(qe.content,ge);!ce&&Je?.name&&(ce=Je.name),De===0?(ee=Ae,ie=qe.attachments??[]):we.push({text:Ae,attachments:qe.attachments})}if(at){const De=t.replace(/^\n+|\n+$/g,""),{sanitizedText:qe,mention:Ae}=Yc(De,ge),Je=V.map(vt=>({...vt}));!ce&&Ae?.name&&(ce=Ae.name),q.length===0?(ee=qe,ie=Je):we.push({text:qe,attachments:Je.length>0?Je:void 0})}if(!ee&&we.length===0)return;P&&Mt&&Ve(P),n(""),V.length>0&&Y(),Re&&M.current?.blur();const ze=ee.trimStart();if(ze.startsWith("/")){const De=ze.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(De==="undo"&&P){await ue.getState().handleSlashUndo(P),r?.({instant:!0,force:!0});return}else if(De==="redo"&&P){await ue.getState().handleSlashRedo(P),r?.({instant:!0,force:!0});return}else if(De==="timeline"&&P){U(!0),n("");return}else if(De==="compact"&&P){try{const{opencodeClient:qe}=await rs(async()=>{const{opencodeClient:vt}=await Promise.resolve().then(()=>lg);return{opencodeClient:vt}},void 0),Ae=qe.getDirectory();if((await qe.getApiClient().session.summarize({sessionID:P,directory:Ae||void 0,providerID:F,modelID:$})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(qe){console.error("Failed to compact session:",qe),ne.error("Failed to compact session")}n("");return}}const He=[...ie,...we.flatMap(De=>De.attachments??[])];await _(ee,F,$,X,ie,ce,we.length>0?we:void 0,z).catch(De=>{const qe=De instanceof Error?De.message:typeof De=="string"?De:String(De??""),Ae=qe.toLowerCase();console.error("Message send failed:",qe||De),!(Ae.includes("timeout")||Ae.includes("timed out")||Ae.includes("may still be processing")||Ae.includes("being processed")||Ae.includes("failed to fetch")||Ae.includes("networkerror")||Ae.includes("network error")||Ae.includes("gateway timeout")||Ae==="failed to send message")&&(He.length>0&&er.setState({attachedFiles:He}),ne.error(qe||"Message failed to send. Attachments restored."))}),Re||M.current?.focus()},tt=c.useRef(ut);tt.current=ut,c.useEffect(()=>{const ae=ye.current==="busy"||ye.current==="cooldown",ee=he==="idle",ie=P&&H.has(P)&&(()=>{const ce=H.get(P);return ce?Date.now()-ce.timestamp<2e3:!1})();ae&&ee&&q.length>0&&!Le.current&&!ie&&(Le.current=!0,setTimeout(()=>{P&&F&&$&&tt.current(),Le.current=!1},100)),ye.current=he},[he,q.length,P,F,$,H]);const ct=ae=>{if(!wl(ae)){if(m&&A.current&&(ae.key==="Enter"||ae.key==="ArrowUp"||ae.key==="ArrowDown"||ae.key==="Escape"||ae.key==="Tab")){ae.preventDefault(),A.current.handleKeyDown(ae.key);return}if(b&&E.current&&(ae.key==="Enter"||ae.key==="ArrowUp"||ae.key==="ArrowDown"||ae.key==="Escape"||ae.key==="Tab")){ae.preventDefault(),E.current.handleKeyDown(ae.key);return}if(x&&R.current&&(ae.key==="Enter"||ae.key==="ArrowUp"||ae.key==="ArrowDown"||ae.key==="Escape"||ae.key==="Tab")){ae.preventDefault(),R.current.handleKeyDown(ae.key);return}if(i&&S.current&&(ae.key==="Enter"||ae.key==="ArrowUp"||ae.key==="ArrowDown"||ae.key==="Escape"||ae.key==="Tab")){ae.preventDefault(),S.current.handleKeyDown(ae.key);return}if(ae.key==="Tab"&&!m&&!b&&!i){ae.preventDefault(),Z();return}if(ae.key==="Enter"&&!ae.shiftKey&&!Re){ae.preventDefault();const ee=ae.ctrlKey||ae.metaKey,ie=at&&P&&he!=="idle";Pe?ee||!ie?ut():Ze():ee&&ie?Ze():ut()}}},it=c.useCallback(()=>{me.current&&(clearTimeout(me.current),me.current=null),pe(!0),me.current=setTimeout(()=>{pe(!1),me.current=null},1800)},[]),St=c.useCallback(()=>{B(),it(),J()},[J,B,it]),Z=()=>{const ae=ge.filter(we=>ow(we.mode));if(ae.length<=1)return;const ie=(ae.findIndex(we=>we.name===X)+1)%ae.length,ce=ae[ie];fe(ce.name),P&&le(P,ce.name)},xe=c.useCallback(()=>{const ae=M.current;if(!ae)return;ae.style.height="auto";const ee=ae.ownerDocument?.defaultView,ie=ee?ee.getComputedStyle(ae):null,ce=ie?parseFloat(ie.lineHeight):NaN,we=ie?parseFloat(ie.paddingTop):NaN,ze=ie?parseFloat(ie.paddingBottom):NaN,He=22,qe=Number.isNaN(we)||Number.isNaN(ze)?16:we+ze,Je=(Number.isNaN(ce)?He:ce)*nw+qe,vt=ae.scrollHeight||ae.offsetHeight,gt=Math.min(vt,Je);ae.style.height=`${gt}px`,ae.style.maxHeight=`${Je}px`,D(bs=>bs&&bs.height===gt&&bs.maxHeight===Je?bs:{height:gt,maxHeight:Je})},[]);c.useLayoutEffect(()=>{xe()},[xe,t,Re]);const de=c.useCallback((ae,ee)=>{if(ae.startsWith("/")){const He=ae.indexOf(" "),De=ae.indexOf(`
69
- `),qe=Math.min(He===-1?ae.length:He,De===-1?ae.length:De);if(ee<=qe&&He===-1){const Ae=ae.substring(1,qe);g(Ae),f(!0),l(!1),h(!1),v(!1);return}}f(!1);const ie=ae.substring(0,ee),ce=ie.lastIndexOf("#");if(ce!==-1){const He=ce>0?ie[ce-1]:null,De=ie.substring(ce+1),qe=De.includes(" ")||De.includes(`
70
- `);if((!He||/\s/.test(He))&&!qe){y(De),h(!0),l(!1);return}}h(!1),y("");const we=ie.lastIndexOf("/");if(we!==-1){const He=we>0?ie[we-1]:null,De=ie.substring(we+1),qe=De.includes(" ")||De.includes(`
71
- `);if((!He||/\s/.test(He))&&!qe){w(De),v(!0),l(!1),h(!1);return}}v(!1),w("");const ze=ie.lastIndexOf("@");if(ze!==-1){const He=ie.substring(ze+1);!He.includes(" ")&&!He.includes(`
72
- `)?(u(He),l(!0)):l(!1)}else l(!1)},[y,g,u,h,f,l,v,w]),Oe=c.useCallback(ae=>{if(!ae)return;const ee=M.current;if(!ee){const He=t+ae;n(He),de(He,He.length),requestAnimationFrame(()=>xe());return}const ie=ee.selectionStart??t.length,ce=ee.selectionEnd??t.length,we=`${t.substring(0,ie)}${ae}${t.substring(ce)}`;n(we);const ze=ie+ae.length;requestAnimationFrame(()=>{const He=M.current;He&&(He.selectionStart=ze,He.selectionEnd=ze),xe()}),de(we,ze)},[xe,t,de]),We=ae=>{const ee=ae.target.value,ie=ae.target.selectionStart??ee.length;n(ee),xe(),de(ee,ie)},Xe=c.useCallback(async ae=>{const ee=new Map;Array.from(ae.clipboardData.files||[]).forEach(ze=>{ze.type.startsWith("image/")&&ee.set(`${ze.name}-${ze.size}`,ze)}),Array.from(ae.clipboardData.items||[]).forEach(ze=>{if(ze.kind==="file"&&ze.type.startsWith("image/")){const He=ze.getAsFile();He&&ee.set(`${He.name}-${He.size}`,He)}});const ie=Array.from(ee.values());if(ie.length===0||!P&&!O)return;ae.preventDefault();const ce=ae.clipboardData.getData("text");ce&&Oe(ce);let we=0;for(const ze of ie){const He=ue.getState().attachedFiles.length;try{await oe(ze),ue.getState().attachedFiles.length>He&&(we+=1)}catch(De){console.error("Clipboard image attach failed",De),ne.error(De instanceof Error?De.message:"Failed to attach image from clipboard")}}we>0&&ne.success(`Attached ${we} image${we>1?"s":""} from clipboard`)},[oe,P,O,Oe]),Ct=ae=>{const ee=M.current?.selectionStart||0,ce=t.substring(0,ee).lastIndexOf("@");if(ce!==-1){const we=t.substring(0,ce)+ae.name+t.substring(ee);n(we)}l(!1),u(""),M.current?.focus()},xt=ae=>{const ie=M.current?.selectionStart??t.length,we=t.substring(0,ie).lastIndexOf("#");if(we!==-1){const ze=t.substring(0,we)+`#${ae} `+t.substring(ie);n(ze);const He=we+ae.length+2;requestAnimationFrame(()=>{M.current&&(M.current.selectionStart=He,M.current.selectionEnd=He),xe(),de(ze,He)})}h(!1),y(""),M.current?.focus()},Pt=ae=>{const ie=M.current?.selectionStart??t.length,we=t.substring(0,ie).lastIndexOf("/");if(we!==-1){const ze=t.substring(0,we)+`${ae} `+t.substring(ie);n(ze);const He=we+ae.length+1;requestAnimationFrame(()=>{M.current&&(M.current.selectionStart=He,M.current.selectionEnd=He),xe(),de(ze,He)})}v(!1),w(""),M.current?.focus()},At=ae=>{n(`/${ae.name} `);const ee=M.current;ee&&(ee._commandMetadata=ae),f(!1),g(""),setTimeout(()=>{M.current&&(M.current.focus(),M.current.setSelectionRange(M.current.value.length,M.current.value.length))},0)};c.useEffect(()=>{P&&M.current&&!Re&&M.current.focus()},[P,Re]),c.useEffect(()=>{L&&L!==P&&B()},[L,P,B]);const Fe=ae=>{ae.preventDefault(),ae.stopPropagation(),(P||O)&&!o&&a(!0)},et=ae=>{ae.preventDefault(),ae.stopPropagation(),ae.currentTarget===ae.target&&a(!1)},Be=async ae=>{if(ae.preventDefault(),ae.stopPropagation(),a(!1),!P&&!O)return;const ee=Array.from(ae.dataTransfer.files);let ie=0;for(const ce of ee){const we=ue.getState().attachedFiles.length;try{await oe(ce),ue.getState().attachedFiles.length>we&&(ie+=1)}catch(ze){console.error("File attach failed",ze),ne.error(ze instanceof Error?ze.message:"Failed to attach file")}}ie>0&&ne.success(`Attached ${ie} file${ie>1?"s":""}`)},Ke=c.useCallback(async ae=>{let ee=0;for(const ie of ae){const ce=ue.getState().attachedFiles.length;try{await se(ie.path,ie.name),ue.getState().attachedFiles.length>ce&&(ee+=1)}catch(we){console.error("Server file attach failed",we),ne.error(we instanceof Error?we.message:"Failed to attach file")}}ee>0&&ne.success(`Attached ${ee} file${ee>1?"s":""}`)},[se]),wt=c.useRef(null),[Lt,ts]=c.useState(!1),es=c.useCallback(async ae=>{let ee=0;const ie=Array.isArray(ae)?ae:Array.from(ae);for(const ce of ie){const we=ue.getState().attachedFiles.length;try{await oe(ce),ue.getState().attachedFiles.length>we&&(ee+=1)}catch(ze){console.error("File attach failed",ze),ne.error(ze instanceof Error?ze.message:"Failed to attach file")}}ee>0&&ne.success(`Attached ${ee} file${ee>1?"s":""}`)},[oe]),ps=c.useCallback(async()=>{try{const ee=await(await fetch("/api/vscode/pick-files")).json(),ie=Array.isArray(ee?.files)?ee.files:[],ce=Array.isArray(ee?.skipped)?ee.skipped:[];if(ce.length>0){const ze=ce.map(He=>`${He?.name||"file"}: ${He?.reason||"skipped"}`).join(`
73
- `);ne.error(`Some files were skipped:
74
- ${ze}`)}const we=ie.map(ze=>{if(!ze?.dataUrl)return null;try{const[He,De]=ze.dataUrl.split(","),qe=ze.mimeType||He?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!De)return null;const Ae=atob(De),Je=new Uint8Array(Ae.length);for(let gt=0;gt<Ae.length;gt++)Je[gt]=Ae.charCodeAt(gt);const vt=new Blob([Je],{type:qe});return new File([vt],ze.name||"file",{type:qe})}catch(He){return console.error("Failed to decode VS Code picked file",He),null}}).filter(Boolean);we.length>0&&await es(we)}catch(ae){console.error("VS Code file pick failed",ae),ne.error(ae instanceof Error?ae.message:"Failed to pick files in VS Code")}},[es]),lr=c.useCallback(()=>{if(Ht()){ps();return}wt.current?.click()},[ps]),Ot=c.useCallback(async ae=>{const ee=ae.target.files;ee&&(await es(ee),ae.target.value="")},[es]),vr="gap-x-1.5 gap-y-0",Pn=Ht(),va=Re?"px-1.5 py-1.5":Pn?"px-1.5 py-1":"px-2.5 py-1.5",ja=Re?"h-9 w-9":Pn?"h-[22px] w-[22px]":"h-7 w-7",Rr=Re?"h-5 w-5":Pn?"h-4 w-4":"h-[18px] w-[18px]",_r=T(ja,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),on=!Re&&Ue&&Jt?e.jsx("button",{type:"button",onClick:St,className:T(_r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(jn,{className:T(Rr)})}):e.jsx("button",{type:Re?"button":"submit",disabled:!Yt||!P&&!O,onPointerDownCapture:ae=>{!Re||ae.pointerType!=="touch"||!Yt||!P&&!O||(Se.current=!0,ae.preventDefault(),ae.stopPropagation(),ut())},onClick:ae=>{if(Re){if(Se.current){Se.current=!1;return}ae.preventDefault(),ut()}},className:T(_r,Yt&&(P||O)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(iu,{className:T(Rr)})}),Tn=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:wt,type:"file",multiple:!0,className:"hidden",onChange:Ot,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(_b,{onFilesSelected:Ke,multiSelect:!0,presentation:Re?"modal":"dropdown",open:Lt,onOpenChange:ts,children:Re?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:_r,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(lu,{className:T(Rr,"text-current")})})}),e.jsxs(Gt,{align:"start",children:[e.jsxs(kt,{onSelect:()=>{requestAnimationFrame(()=>lr())},children:[e.jsx(Uo,{}),"Attach files"]}),e.jsxs(kt,{onSelect:()=>{requestAnimationFrame(()=>{ts(!0)})},children:[e.jsx(ah,{}),"Attach from project"]})]})]})]})]}),Sa=s?e.jsx("button",{type:"button",onClick:s,className:_r,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(Qr,{className:T(Rr,"text-current")})}):null,ao=e.jsxs(e.Fragment,{children:[Tn,Sa]}),ka=Q.statusText;c.useEffect(()=>{const ae=!!Q.wasAborted;!Me.current&&ae&&!te&&(it(),P&&K(P)),Me.current=ae},[K,P,te,it,Q.wasAborted]),c.useEffect(()=>()=>{me.current&&(clearTimeout(me.current),me.current=null)},[]);const Na=Re&&Jt;return e.jsxs("form",{onSubmit:ut,className:"pt-0 pb-2 md:pb-4 bottom-safe-area","data-keyboard-avoid":"true",style:Re&&be>0&&!Ie?{marginBottom:`${be}px`}:void 0,children:[e.jsx(Xb,{isWorking:Q.isWorking,statusText:ka,isGenericStatus:Q.isGenericStatus,isWaitingForPermission:Q.isWaitingForPermission,wasAborted:Q.wasAborted,abortActive:Q.abortActive,completionId:Q.lastCompletionId,isComplete:Q.isComplete,showAbort:Na,onAbort:St,showAbortStatus:te}),e.jsxs("div",{ref:C,className:T("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Fe,onDragLeave:et,onDrop:Be,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:_r,onClick:()=>lr(),title:"Attach files","aria-label":"Attach files",children:e.jsx(Uo,{className:T(Rr,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Ib,{}),e.jsx(Dm,{onEditMessage:ae=>{n(ae),setTimeout(()=>{M.current?.focus()},0)}}),e.jsxs("div",{className:T("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Ge,children:[m&&e.jsx(Am,{ref:A,searchQuery:p,onCommandSelect:At,onClose:()=>f(!1)}),b&&e.jsx(Em,{ref:E,searchQuery:j,onAgentSelect:xt,onClose:()=>h(!1)}),x&&e.jsx(Im,{ref:R,searchQuery:N,onSkillSelect:Pt,onClose:()=>v(!1)}),i&&e.jsx(Pb,{ref:S,searchQuery:d,onFileSelect:Ct,onClose:()=>l(!1)}),e.jsx(Ts,{ref:M,"data-chat-input":"true",value:t,onChange:We,onKeyDown:ct,onPaste:Xe,onPointerDownCapture:Qe,placeholder:P||O?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!P&&!O,className:T("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",Re?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:k?`${k.height}px`:void 0,maxHeight:k?`${k.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:T("rounded-b-xl bg-transparent",va,Re?"flex items-center gap-x-1.5":T("flex items-center justify-between",vr)),"data-chat-input-footer":"true",children:Re?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:ao}),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(Kc,{className:T("w-full flex items-center justify-end min-w-0")})}),on]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("flex items-center flex-shrink-0",vr),children:ao}),e.jsxs("div",{className:T("flex items-center flex-1 justify-end",vr,"md:gap-x-3"),children:[e.jsx(Kc,{className:T("flex-1 min-w-0 justify-end")}),on]})]})})]})]})]})};function Qa({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:T("bg-accent animate-pulse rounded-xl",s),...r})}const ad=(s,r,t,n,o=4)=>{const a=[];for(let i=0;i<o;i++)for(let l=0;l<o;l++){const d=l/o,u=(l+1)/o,m=i/o,f=(i+1)/o,p=(x,v,N)=>x+(v-x)*N,g=(x,v,N,w,k,D)=>{const M=p(x,v,k),C=p(w,N,k);return p(M,C,D)},b={x:g(s.x,r.x,t.x,n.x,d,m),y:g(s.y,r.y,t.y,n.y,d,m)},h={x:g(s.x,r.x,t.x,n.x,u,m),y:g(s.y,r.y,t.y,n.y,u,m)},j={x:g(s.x,r.x,t.x,n.x,u,f),y:g(s.y,r.y,t.y,n.y,u,f)},y={x:g(s.x,r.x,t.x,n.x,d,f),y:g(s.y,r.y,t.y,n.y,d,f)};a.push({path:`M${b.x} ${b.y} L${h.x} ${h.y} L${j.x} ${j.y} L${y.x} ${y.y} Z`,row:i,col:l})}return a},kl=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=pa();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const i=a?"white":"black",l=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,g=50,b={x:50,y:g-m},h={x:50-m*f,y:g-m*p},j={x:50+m*f,y:g-m*p},y={x:50,y:g},x={x:50-m*f,y:g+m*p},v={x:50+m*f,y:g+m*p},N={x:50,y:g+m},k=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(b.y+h.y+y.y+j.y)/4})`,D=ad(h,y,N,x),M=ad(y,j,v,N),C=Ce.useMemo(()=>{const S=[];for(let A=0;A<32;A++)S.push(.1+Math.random()*.5);return S},[]);return e.jsxs("svg",{width:r,height:t,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:s,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${y.x} ${y.y} L${h.x} ${h.y} L${x.x} ${x.y} L${N.x} ${N.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),D.map((S,A)=>e.jsx("path",{d:S.path,fill:u,opacity:C[A]},`left-${A}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${j.x} ${j.y} L${v.x} ${v.y} L${N.x} ${N.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),M.map((S,A)=>e.jsx("path",{d:S.path,fill:u,opacity:C[A+16]},`right-${A}`)),e.jsx("path",{d:`M${b.x} ${b.y} L${h.x} ${h.y} L${y.x} ${y.y} L${j.x} ${j.y} Z`,fill:"none",stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${k} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function iw({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:i=!0,mode:l="popLayout"}){const[d,u]=Ce.useState(0),m=Ce.Children.toArray(s);Ce.useEffect(()=>{if(!i)return;const p=t*1e3,g=setInterval(()=>{u(b=>{const h=(b+1)%m.length;return a?.(h),h})},p);return()=>clearInterval(g)},[m.length,t,a,i]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:T("relative",r),children:[e.jsx("div",{className:"invisible whitespace-nowrap",children:m.map((p,g)=>e.jsx("div",{className:g===0?"":"absolute",children:p},g))}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(ih,{mode:l,initial:!1,children:e.jsx(fn.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const lw=["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"],cw=()=>{const s=pa();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(kl,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(iw,{className:"text-body-md",interval:4,transition:{duration:.5},children:lw.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},Xa=c.memo(cw),dw={'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"}},uw={'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 Cr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Cr.instance||(Cr.instance=new Cr),Cr.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 $m(s){const r=s.colors.syntax,t=s.colors.surface;return{'code[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:r.base.comment,fontStyle:"italic"},prolog:{color:r.base.comment},doctype:{color:r.base.comment},cdata:{color:r.base.comment},punctuation:{color:r.tokens?.punctuation||t.mutedForeground},property:{color:r.tokens?.variableProperty||r.base.variable},tag:{color:r.tokens?.tag||r.base.keyword},"attr-name":{color:r.tokens?.tagAttribute||r.base.variable},"attr-value":{color:r.tokens?.tagAttributeValue||r.base.string},boolean:{color:r.tokens?.boolean||r.base.number},number:{color:r.base.number},constant:{color:r.tokens?.constant||r.base.number},symbol:{color:r.tokens?.constant||r.base.number},string:{color:r.base.string},char:{color:r.base.string},function:{color:r.base.function},builtin:{color:r.tokens?.functionBuiltin||r.base.function},"class-name":{color:r.tokens?.className||r.base.type},namespace:{color:r.tokens?.namespace||r.base.type,opacity:.8},keyword:{color:r.base.keyword},atrule:{color:r.base.keyword},selector:{color:r.base.function},operator:{color:r.base.operator},variable:{color:r.base.variable},regex:{color:r.tokens?.regex||r.base.string},url:{color:r.base.function,textDecoration:"underline"},entity:{color:r.base.function,cursor:"help"},".language-css .token.string":{color:r.base.string},".style .token.string":{color:r.base.string},deleted:{color:s.colors.status.error,backgroundColor:s.colors.status.errorBackground},inserted:{color:s.colors.status.success,backgroundColor:s.colors.status.successBackground},title:{color:s.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:t.mutedForeground},table:{color:r.base.function},blockquote:{color:t.mutedForeground,fontStyle:"italic"},important:{color:r.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:r.tokens?.decorator||r.base.function},annotation:{color:r.tokens?.decorator||r.base.function}}}const gs=({children:s,className:r})=>{const[t,n]=c.useState(!1);return c.useEffect(()=>{let o=null;const a=()=>n(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:T("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},mw=({isUser:s,providerID:r,agentName:t,modelName:n,variant:o,isDarkTheme:a})=>{const{src:i,onError:l,hasLogo:d}=vm(r);return e.jsx(gs,{children:e.jsx("div",{className:T("pl-3","mb-2"),children:e.jsx("div",{className:T("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:s?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Fs,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&i?e.jsx("img",{src:i,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:l}):e.jsx(ar,{className:"h-4 w-4",style:{color:`var(${kr(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:T("font-bold typography-ui-header tracking-tight leading-none",s?"text-primary":"text-foreground"),children:s?"You":n||"Assistant"}),!s&&t&&e.jsxs("div",{className:T("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",kr(t).class),children:[e.jsx(Qr,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:t})]}),!s&&o&&e.jsxs("div",{className:T("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",o==="Default"?void 0:"agent-info"),style:o==="Default"?{"--agent-color":"var(--muted-foreground)","--agent-color-bg":"var(--muted-foreground)"}:void 0,children:[e.jsx(ar,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:o.length>0?o[0].toLowerCase()+o.slice(1):o})]})]})]})})})})},fw=c.memo(mw),id=(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},ld=()=>{if(!Ht()||typeof window>"u")return vc;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=id({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=id({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return vc},Lm=()=>{const[s,r]=c.useState(ld);return c.useEffect(()=>{if(!Ht()||typeof window>"u")return;const t=n=>{r(ld())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},Bm=s=>{const r=[],t=[],n=s.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>r.push(i.innerText.trim()));const o=s.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const l=i.querySelectorAll("td"),d=[];l.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},zm=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
75
- `)?`"${o.replace(/"/g,'""')}"`:o,n=[];return s.length>0&&n.push(s.map(t).join(",")),r.forEach(o=>n.push(o.map(t).join(","))),n.join(`
76
- `)},pw=({headers:s,rows:r})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return s.length>0&&n.push(s.map(t).join(" ")),r.forEach(o=>n.push(o.map(t).join(" "))),n.join(`
77
- `)},hw=({headers:s,rows:r})=>{if(s.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${s.map(t).join(" | ")} |`),n.push(`| ${s.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=s.map((i,l)=>t(o[l]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
78
- `)},gw=(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)},xw=({tableRef:s})=>{const[r,t]=c.useState(!1),[n,o]=c.useState(!1),a=c.useRef(null);c.useEffect(()=>{const l=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[]);const i=async l=>{const d=s.current?.querySelector("table");if(d)try{const u=Bm(d),m=l==="csv"?zm(u):pw(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(Tt,{className:"size-3.5"}):e.jsx(Gs,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("tsv"),children:"TSV"})]})]})},yw=({tableRef:s})=>{const[r,t]=c.useState(!1),n=c.useRef(null);c.useEffect(()=>{const a=i=>{n.current&&!n.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=s.current?.querySelector("table");if(i)try{const l=Bm(i),d=a==="csv"?zm(l):hw(l);gw(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(l){console.error("Failed to download table:",l)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>t(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(Yr,{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"})]})]})},bw=({children:s,className:r})=>{const t=c.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:t,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(xw,{tableRef:t}),e.jsx(yw,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:T("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},ww=({children:s,className:r,style:t,...n})=>{const[o,a]=c.useState(!1),i=c.useRef(null),l=c.useMemo(()=>{if(!t)return t;const m={...t},f=b=>{if(typeof b!="string")return{value:void 0,vars:{}};const[h,...j]=b.split(";").map(x=>x.trim()).filter(Boolean),y={};for(const x of j){const v=x.indexOf(":");if(v===-1)continue;const N=x.slice(0,v).trim(),w=x.slice(v+1).trim();!N.startsWith("--")||w.length===0||(y[N]=w)}return{value:h,vars:y}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[b,h]of Object.entries(p.vars))m[b]=h;const g=f(t.color);g.value&&(m.color=g.value,m["--shiki-light"]=g.value);for(const[b,h]of Object.entries(g.vars))m[b]=h;return m},[t]),d=()=>i.current&&i.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:T(r),style:l,children:s}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(Tt,{className:"size-3.5"}):e.jsx(Gs,{className:"size-3.5"})})})]})},Wm={pre:ww,table:bw},vw=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const l=Lm(),d=c.useMemo(()=>`markdown-${r?.id?`part-${r.id}`:`message-${t}`}`,[t,r?.id]),u=i==="tool"?"streamdown-content streamdown-tool":"streamdown-content",m=e.jsx("div",{className:T("break-words",o),children:e.jsx(cu,{mode:a?"streaming":"static",shikiTheme:l,className:u,controls:{code:!1,table:!1},components:Wm,children:s})});return n?e.jsx(gs,{children:m},d):m},Gr=({content:s,className:r,variant:t="assistant"})=>{const n=Lm(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:T("break-words",r),children:e.jsx(cu,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:Wm,children:s})})},jw={thinking:{label:"Thinking",Icon:ar},justification:{label:"Justification",Icon:Ui}},Hm=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
79
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
80
- `).trim(),Sw=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
81
- `),n=r.indexOf("."),o=[t>=0?t:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},Nl=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=c.useState(!1),i=c.useMemo(()=>Sw(s),[s]),{label:l,Icon:d}=jw[r];return c.useEffect(()=>{s.trim().length!==0&&t?.("structural")},[t,o,s]),!s||s.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:T("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:T("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:T("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(Et,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:l})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className:T("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(mt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},Um=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>Hm(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Nl,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},kw=s=>Hm(s),Nw=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=s,l=i.text,d=typeof l=="string"?l:i.content||i.value||"",u=c.useMemo(()=>a?kw(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=c.useRef(m);if(m||f)return p.current=!0,null;const g=i.time;return!(g&&typeof g.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(Nl,{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(vw,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},Cw=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,Mw=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,l]=c.useState(!1),[d,u]=c.useState(!1),m=c.useRef(null);c.useEffect(()=>{const g=m.current;if(!g||i)return;const b=()=>{u(g.scrollHeight>g.clientHeight)};b();const h=new ResizeObserver(b);return h.observe(g),()=>h.disconnect()},[a,i]);const f=c.useCallback(()=>{(d||i)&&l(g=>!g)},[d,i]);if(!a||a.trim().length===0)return null;const p=()=>{if(!t?.token||!a.includes(t.token))return a;const g=a.indexOf(t.token),b=a.slice(0,g),h=a.slice(g+t.token.length);return e.jsxs(e.Fragment,{children:[b,e.jsx("a",{href:Cw(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:j=>j.stopPropagation(),children:t.token}),h]})};return e.jsx("div",{className:T("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`)},Dw=c.memo(Mw),Aw=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},Vm=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,Ew=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",cd=(s,r)=>!s||typeof s!="object"?String(s):yy(s,r||""),Ja=(s,r,t)=>{let n=Aw(s);if((r==="edit"||r==="multiedit")&&Vm(n)&&(n=Ew(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Iw=(s,r)=>{try{const t=s.trim().split(`
82
- `).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,l]=a,d=Math.floor(i.length/2),u=!l.endsWith("/");n.push({name:l.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:T("w-full min-w-0 font-mono space-y-0.5",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},Pw=(s,r,t)=>{try{const n=s.trim().split(`
83
- `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,l,d,u]=i,m=u!==void 0?d:"",f=u!==void 0?u:d;o[l]||(o[l]=[]),o[l].push({lineNum:m,content:f})}}),e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:T("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((l,d)=>!l.lineNum&&!l.content?null:e.jsxs("div",{className:T("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[l.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",l.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:l.content||" "})]})]},d))})]},a))]})}catch{return null}},Tw=(s,r,t)=>{try{const n=s.trim().split(`
84
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const l=i.lastIndexOf("/"),d=l>0?i.substring(0,l):"/",u=l>=0?i.substring(l+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:T("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:T("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(l=>e.jsxs("div",{className:T("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:l})]},l))})]},i))]})}catch{return null}},Fw=(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:T("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tt,{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(Tt,{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}},Rw=(s,r,t)=>{try{return e.jsx("div",{className:T("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:pr.tool.popup,children:e.jsx(Gr,{content:s,variant:"tool"})})}catch{return null}},Gm=s=>{const r=s.split(`
85
- `);let t="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),l=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let m=d,f=o+1;for(;f<r.length&&!r[f].startsWith("@@")&&!r[f].startsWith("Index:");){const p=r[f];p.startsWith("+")?(u.push({type:"added",lineNumber:m,content:p.substring(1)}),m++):p.startsWith("-")?u.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(u.push({type:"context",lineNumber:m,content:p.substring(1)}),m++),f++}n.push({file:t,oldStart:l,newStart:d,lines:u}),o=f;continue}o++}return n},Ri=(s,r,t)=>hy(r,s,t),qm=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(lh,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(du,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(xi,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Er,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(ur,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(ch,{className:r}):t==="glob"?e.jsx(dh,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(yi,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(yi,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(uu,{className:r}):t==="skill"?e.jsx(mu,{className:r}):t==="question"?e.jsx(uh,{className:r}):t.startsWith("git")?e.jsx($t,{className:r}):e.jsx(ca,{className:r})},_w=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},Ow=({start:s,end:r,active:t})=>{const[n,o]=c.useState(()=>Date.now());return c.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:_w(s,r,n)})},$w=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
86
- `);let t=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&n++;return t===0&&n===0?null:{added:t,removed:n}},_i=(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},Lw=s=>{const r=s.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!r)return null;const t=[],n=r[1],o=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let a;for(;(a=o.exec(n))!==null;)t.push({question:a[1],answer:a[2]});return t.length>0?t:null},Bw=(s,r,t,n)=>{const o=r,a=o.metadata,i=o.input;if(s.tool==="question"&&i?.questions&&Array.isArray(i.questions)){const d=i.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((s.tool==="edit"||s.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return _i(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 _i(d,n,t)}if(s.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
87
- `)[0];return t?d.substring(0,50):d.substring(0,100)}if(s.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);if(s.tool==="skill"&&i?.name&&typeof i.name=="string")return i.name;const l=i?.description||a?.description||"title"in r&&r.title||"";return typeof l=="string"?l:""},Oi=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(mt,{outerClassName:T("w-full min-w-0 flex-none overflow-hidden",r,n),className:T("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})}),zw=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"},Ww=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Hw=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o,sessionId:a})=>{const i=ue(h=>h.setCurrentSession),l=c.useMemo(()=>s.filter(h=>h.state?.status==="completed"),[s]),d=typeof o=="string"?Ww(o):"",u=d.length>0,[m,f]=c.useState(!1),p=h=>{h.stopPropagation(),a&&i(a)};if(l.length===0&&!u&&!a)return null;const g=r?l:l.slice(-6),b=Math.max(0,l.length-g.length);return e.jsxs("div",{className:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',t?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[l.length>0?e.jsx(Oi,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[b>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",b," more…"]}):null,g.map((h,j)=>{const y=typeof h.tool=="string"&&h.tool.trim().length>0?h.tool:"tool",x=zw(h),v=dl(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:qm(y)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:v}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:x})]},h.id??`${y}-${j}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:h=>h.stopPropagation(),onClick:p,children:[e.jsx(Ho,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-primary font-medium",children:"Open subAgent session"})]}),u?e.jsxs("div",{className:T("space-y-1",(l.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:h=>h.stopPropagation(),onClick:h=>{h.stopPropagation(),f(j=>!j)},children:[m?e.jsx(Et,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Us,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?e.jsx(Oi,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:d,variant:"tool"})})}):null]}):null]})},Uw=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Gm(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:T("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:rn(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))}),Vw=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
88
- `),a=rn(t??"")||Ri(s,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${l})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:a||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},Gw=({content:s,filePath:r,displayPath:t})=>{const n=xy(r),o=r.toLowerCase().endsWith(".svg"),a=c.useMemo(()=>o&&!s.startsWith("data:")?`data:image/svg+xml;base64,${btoa(s)}`:s.startsWith("data:")?s:`data:${n};base64,${s}`,[s,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:t}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:t,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})},qw=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const l=r,d=l.metadata,u=l.input,m=l.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",g=typeof d?.diff=="string"?d.diff:null,b=s.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,h=s.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,j=s.tool==="write"&&!!h,y=b?nm(b):!1,x=j?b?_i(b,o,n):"New file":null,v=c.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?cd(u,s.tool):typeof u.content=="string"?u.content??"":cd(u,s.tool),[u,s.tool]),N=v.trim().length>0,w=(D,M)=>e.jsx(Oi,{maxHeightClass:M?.maxHeightClass,className:M?.className,disableHorizontal:M?.disableHorizontal,outerClassName:M?.outerClassName,children:D}),k=()=>{if(s.tool==="question"){if(r.status==="completed"&&f){const D=Lw(p);if(D&&D.length>0)return w(e.jsx("div",{className:"space-y-2",children:D.map((M,C)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:M.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:M.answer})]},C))}),{maxHeightClass:"max-h-[40vh]"})}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Awaiting response..."})}if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const D=Fw(p,{unstyled:!0});return w(D??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(s.tool==="list"&&f){const D=Iw(p,{unstyled:!0});return w(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="grep"&&f){const D=Pw(p,n,{unstyled:!0});return w(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="glob"&&f){const D=Tw(p,n,{unstyled:!0});return w(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="task"&&f)return w(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const D=Rw(p,t,{unstyled:!0});return w(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="codesearch"&&f)return w(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return w(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&(!f&&g||p.trim().length===0||Vm(p))&&g)return w(e.jsx(Uw,{diff:g,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const D=Ja(p,s.tool,d),M=D.split(`
89
- `),C=typeof u?.offset=="number"?u.offset:0,S=typeof u?.limit=="number"?u.limit:void 0,A=E=>E.trim().startsWith("(");return w(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:M.map((E,R)=>{const _=A(E),P=C+R+1,O=!_&&(S===void 0||R<S);return e.jsxs("div",{className:T("typography-code font-mono flex w-full min-w-0",_&&"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:O?P:""}),e.jsx("div",{className:"flex-1 min-w-0",children:_?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(hr,{style:t,language:Ri(D,s.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:E})})]},R)})}),{className:"p-1"})}return w(e.jsx(hr,{style:t,language:Ri(Ja(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...Eo.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Ja(p,s.tool,d)}),{className:"p-1"})}return w(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:s.tool==="todowrite"||s.tool==="todoread"||s.tool==="question"?k():e.jsxs(e.Fragment,{children:[j&&y?e.jsx("div",{className:"my-1",children:w(e.jsx(Gw,{content:h,filePath:b,displayPath:x??"New file"}))}):j?e.jsx("div",{className:"my-1",children:w(e.jsx(Vw,{content:h,syntaxTheme:t,filePath:b,displayPath:x??"New file"}))}):N?e.jsx("div",{className:"my-1",children:w(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:v}),{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})]})]})})},Lo=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:l=!1})=>{const d=s.state,u=dt(P=>P.currentDirectory),m=s.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",g=d.status==="error",b=c.useRef(r);c.useEffect(()=>{!f&&!m||b.current!==r&&(b.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const h=d,j=h.metadata,y=h.input,x=h.time,v=c.useRef({}),N=c.useRef(s.id);if(N.current!==s.id&&(N.current=s.id,v.current={}),m){if(typeof x?.start=="number"){const P=v.current.start;(typeof P!="number"||x.start<P)&&(v.current.start=x.start)}typeof x?.end=="number"&&(v.current.end=x.end)}const w=m?v.current.start??x?.start:x?.start,k=m?v.current.end??x?.end:x?.end,D=c.useMemo(()=>{if(!m)return;const P=j;return typeof P?.sessionId=="string"?P.sessionId:void 0},[m,j]),M=c.useMemo(()=>{if(!m)return[];const P=j?.summary;return Array.isArray(P)?P.filter(O=>typeof O=="object"&&O!==null):[]},[m,j]),C=c.useRef(M.length);c.useEffect(()=>{m&&C.current!==M.length&&(C.current=M.length,a?.("structural"))},[m,a,M.length]);const S=s.tool==="edit"||s.tool==="multiedit"?$w(j):null,A=Bw(s,d,o,u),E=dl(s.tool).displayName,R=c.useContext(ul),_=P=>{if(m||!R?.editor){t(s.id);return}let O;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(O=y?.filePath||y?.file_path||y?.path||j?.filePath||j?.file_path||j?.path),typeof O=="string"){P.stopPropagation();let J=O;O.startsWith("/")||(J=u.endsWith("/")?u+O:u+"/"+O),R.editor.openFile(J)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:_,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:P=>{P.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&g?{color:"var(--status-error)"}:{},children:qm(s.tool)}),e.jsx("div",{className:T("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(Et,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&g?{color:"var(--status-error)"}:{},children:E})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[A&&e.jsx("span",{className:T("truncate",o&&"max-w-[120px]"),children:A}),S&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",S.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",S.removed]})]}),typeof w=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(Ow,{start:w,end:typeof k=="number"?k:void 0,active:!!(m&&p&&typeof k!="number")})})]})]}),m&&(M.length>0||p||f||D)?e.jsx(Hw,{entries:M,isExpanded:r,hasPrevTool:i,hasNextTool:l,output:typeof h.output=="string"?h.output:void 0,sessionId:D}):null,!m&&r?e.jsx(qw,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:l}):null]})},Kw=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
90
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
91
- `).trim(),Yw=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>Kw(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Nl,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},Qw=c.memo(Yw),Xw=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(", ")},dd=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}),Jw=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},Zw=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:l,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=c.useRef(r),[p,g]=c.useState(0);c.useEffect(()=>{if(f.current===r)return;const y=f.current===!1;f.current=r,l?.("structural"),r&&y&&g(x=>x+1)},[r,l]);const b=c.useMemo(()=>dd(d?s.filter(y=>y.part.id&&u.has(y.id)):s),[s,d,u]),h=Xw(b),j=Jw(b);return b.length===0?null:e.jsx(gs,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("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:T("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(Yn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("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(Et,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(h||m)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[h&&e.jsx("span",{className:"truncate block",children:h}),m&&(m.additions>0||m.deletions>0)&&e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,m.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,m.deletions)]})]})]})]}),r&&e.jsx("div",{className:T("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:b.map((y,x)=>{const v=y.part.id||`group-part-${x}`,N=j[v],w=`${v}-exp${p}`;switch(y.kind){case"tool":return e.jsx(gs,{children:e.jsx(Lo,{part:y.part,isExpanded:a.has(v),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:l,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},w);case"reasoning":return e.jsx(gs,{children:e.jsx(Um,{part:y.part,messageId:y.messageId,onContentChange:l})},w);case"justification":return e.jsx(gs,{children:e.jsx(Qw,{part:y.part,messageId:y.messageId,onContentChange:l})},w);default:return null}})})]})})},ev=c.memo(Zw),tv=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:T("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),Za=c.memo(tv),Km=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},Ym=s=>{if(s.type!=="text")return!1;const r=Km(s);return!r||r.trim().length===0},sv=(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"))},rv=(s,r)=>{const t=c.useRef(null),n=c.useRef(null),[o,a]=c.useState(!1),i=c.useRef(s);i.current=s;const l=c.useRef(r);l.current=r;const d=c.useRef(!1),u=r.size>0;return c.useEffect(()=>{s&&s.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const m=i.current;if(!m)return;const f=Array.from(l.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),c.useEffect(()=>{s&&(!s.isWorking||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[u,s]),c.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},nv=new Set(["task"]),mn=s=>typeof s=="string"&&nv.has(s.toLowerCase()),ov=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:l,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=c.useState(!1),g=c.useRef(null),b=c.useMemo(()=>r.filter(M=>M.type!=="text"?!1:!Ym(M)),[r]),h=d?.token;let j=!1;const y=!!a,x=!!i,v=!!(n??t),N=!!o,w=c.useCallback(()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),k=c.useCallback(()=>{!v||!y||!N||typeof window>"u"||(w(),p(!0),g.current=window.setTimeout(()=>{p(!1),g.current=null},1800))},[y,w,N,v]);c.useEffect(()=>{N||(p(!1),w())},[w,N]);const D=c.useCallback(M=>{!a||!N||(M.stopPropagation(),M.preventDefault(),a(),v&&k())},[N,v,a,k]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:v&&y&&N?k:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:b.map((M,C)=>{let S;return d&&h&&!j&&Km(M).includes(h)&&(S=d,j=!0),e.jsx(gs,{children:e.jsx(Dw,{part:M,messageId:s,isMobile:t,agentMention:S})},`user-text-${C}`)})}),e.jsx(Cm,{files:r,onShowPopup:l}),y&&N||u||m?e.jsxs("div",{className:T("mt-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",f&&"opacity-100 pointer-events-auto"),children:[u&&e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{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:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),u()},children:e.jsx(Kn,{className:"h-3.5 w-3.5"})})}),e.jsx(rt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),m()},children:e.jsx($t,{className:"h-3.5 w-3.5"})})}),e.jsx(rt,{sideOffset:6,children:"Fork from here"})]}),y&&N&&e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon","data-visible":f||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:M=>M.stopPropagation(),onClick:D,onFocus:()=>p(!0),onBlur:()=>{x||p(!1)},children:x?e.jsx(Tt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gs,{className:"h-3.5 w-3.5"})})}),e.jsx(rt,{sideOffset:6,children:"Copy message"})]})]}):null]})},av=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,syntaxTheme:o,isMobile:a,hasTouchInput:i,expandedTools:l,onToggleTool:d,onShowPopup:u,streamPhase:m,allowAnimation:f,onContentChange:p,hasTextContent:g=!1,onCopyMessage:b,copiedMessage:h=!1,onAuxiliaryContentComplete:j,showReasoningTraces:y=!1,turnGroupingContext:x,errorMessage:v})=>{const[N,w]=c.useState(!1),k=c.useRef(null),D=!!b,M=!!h,C=!!(i??a),S=!t,A=c.useMemo(()=>r.filter(Ue=>!Ym(Ue)).filter(Ue=>Ue.type!=="compaction"),[r]),E=c.useMemo(()=>A.filter(Ue=>Ue.type==="tool"),[A]),R=c.useMemo(()=>A.filter(Ue=>Ue.type==="text"),[A]),_=ue(Ue=>Ue.createSessionFromAssistantMessage),P=$e(Ue=>Ue.openMultiRunLauncherWithPrompt),O=x?.isLastAssistantInTurn??!1,J=n==="stop",K=E.length>0,L=c.useMemo(()=>E.some(Ue=>{const ut=(Ue.state??{})?.status;return ut==="pending"||ut==="running"||ut==="started"}),[E]),G=c.useCallback(Ue=>{const Ze=Ue.state??{},ut=Ze?.status;if(ut==="pending"||ut==="running"||ut==="started")return!1;const tt=Ze?.time??{},ct=typeof tt?.end=="number"?tt.end:void 0,it=typeof tt?.start=="number"?tt.start:void 0;return!(typeof ct!="number"||typeof it=="number"&&ct<it)},[]),B=c.useMemo(()=>E.length===0?!0:L?!1:E.every(Ue=>G(Ue)),[E,L,G]),H=c.useMemo(()=>R.length===0?!0:R.every(Ue=>typeof Ue.time?.end=="number"),[R]),V=c.useMemo(()=>A.filter(Ue=>Ue.type==="reasoning"),[A]),oe=c.useMemo(()=>V.length===0?!0:V.every(Ue=>typeof Ue.time?.end=="number"),[V]),se=typeof n!="string",Y=V.length>0&&K&&(L||se||!B),le=c.useMemo(()=>K?R.length===0?se||L||!B:!0:R.length>0?Y:!1,[R.length,se,L,K,Y,B]),I=S||le&&(!H||!B||L||se)||Y,W=S||K&&(L||se||!B),F=S||Y,$=K||V.length>0,z=R.length===0,X=$&&z&&!W&&!F&&B&&oe,fe=c.useRef(!1),ve=c.useRef(!1);c.useEffect(()=>{ve.current=!1},[s]),c.useEffect(()=>{if(!X){fe.current=!1;return}fe.current||(fe.current=!0,j?.())},[X,j]),c.useEffect(()=>{if(S){ve.current=!1;return}if(K){ve.current=!1;return}V.length!==0&&(F||!oe||ve.current||(ve.current=!0,p?.("structural")))},[S,K,p,oe,V.length,F]);const ge=!!g&&!S,Re=c.useCallback(()=>{k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null)},[]),be=c.useCallback(()=>{!C||!D||!ge||typeof window>"u"||(Re(),w(!0),k.current=window.setTimeout(()=>{w(!1),k.current=null},1800))},[D,Re,ge,C]);c.useEffect(()=>{ge||(w(!1),Re())},[Re,ge]);const Ie=c.useCallback(Ue=>{!b||!ge||(Ue.stopPropagation(),Ue.preventDefault(),b(),C&&be())},[ge,C,b,be]),U=c.useCallback(Ue=>{Ue.stopPropagation(),Ue.preventDefault(),_&&_(s)},[_,s]),Q=c.useCallback(Ue=>{Ue.stopPropagation(),Ue.preventDefault();const Ze=il(R);if(!Ze.trim())return;const ut=`${Px}
92
-
93
- ${Ze}`;P(ut)},[R,P]);c.useEffect(()=>()=>{Re()},[Re]);const te=c.useMemo(()=>{const Ue={},Ze=E.filter(ut=>mn(ut.tool)||W?!1:G(ut));return Ze.forEach((ut,tt)=>{Ue[ut.id]={hasPrev:tt>0,hasNext:tt<Ze.length-1}}),Ue},[E,W,G]),pe=c.useMemo(()=>x?.activityParts??[],[x]),me=c.useMemo(()=>x?pe.filter(Ue=>Ue.messageId===s):[],[pe,s,x]),Me=c.useMemo(()=>x?x.activityGroupSegments.filter(Ue=>Ue.anchorMessageId===s):[],[s,x]),Se=c.useMemo(()=>{const Ue=new Map;return me.forEach(Ze=>{Ue.set(Ze.part,Ze)}),Ue},[me]),Pe=c.useMemo(()=>x?(y?pe:pe.filter(Ze=>Ze.kind==="tool")).filter(Ze=>{if(Ze.kind!=="tool")return!0;const ut=Ze.part.tool;return!mn(ut)}):[],[pe,y,x]),[q,re]=c.useState(!1);c.useEffect(()=>{if(!x)return;const Ue=x.activityGroupSegments.some(Ze=>Ze.afterToolPartId!==null);(Pe.length>1||Ue&&Pe.length>0)&&re(!0)},[x,Pe.length]);const Ve=!!(x&&q),he=c.useMemo(()=>{if(!x)return[];if(!Ve)return[];if(!x.isWorking)return[];const Ue=[];return me.forEach(Ze=>{if(x.previewedPartIds.has(Ze.id)||!y&&Ze.kind!=="tool")return;const ut=Ze.part;if(Ze.kind==="tool"){const tt=ut;if(mn(tt.tool)||W||!G(tt))return}else if(Ze.kind==="reasoning"){if(!y||F||typeof ut.time?.end!="number")return}else if(Ze.kind==="justification"&&(!y||I||typeof ut.time?.end!="number"))return;Ue.push(Ze)}),Ue},[me,G,I,F,W,y,Ve,x]),ye=c.useMemo(()=>{const Ue=new Set;return he.forEach(Ze=>{Ue.add(Ze.id)}),Ue},[he]),{isAnimating:Le}=rv(x,ye),Qe=!!(x&&Ve&&Pe.length>0&&Me.length>0),Ee=c.useMemo(()=>E.filter(Ue=>mn(Ue.tool)),[E]),Te=c.useMemo(()=>{const Ue=[],Ze=tt=>{!x||!Qe||Me.filter(ct=>(ct.afterToolPartId??null)===tt).forEach(ct=>{const it=y?ct.parts:ct.parts.filter(St=>St.kind==="tool");it.length!==0&&Ue.push(e.jsx(ev,{parts:it,isExpanded:x.isGroupExpanded,onToggle:x.toggleGroup,syntaxTheme:o,isMobile:a,expandedTools:l,onToggleTool:d,onShowPopup:u,onContentChange:p,isWorking:x.isWorking,previewedPartIds:x.previewedPartIds,diffStats:x.diffStats},`progressive-group-${ct.id}`))})};Ze(null),Ee.forEach(tt=>{Ue.push(e.jsx(gs,{children:e.jsx(Lo,{part:tt,isExpanded:l.has(tt.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${tt.id}`)),Ze(tt.id)});const ut=[];return A.forEach((tt,ct)=>{const it=Se.get(tt);if(!it||!x)return;let St=null,Z=null;if(!Ve){if(it.kind==="tool"){const de=tt;if(mn(de.tool))return;const We=de.state?.time,Xe=G(de);if(!(!W&&Xe))return;const xt=te[de.id];Z=e.jsx(gs,{children:e.jsx(Lo,{part:de,isExpanded:l.has(de.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:xt?.hasPrev??!1,hasNextTool:xt?.hasNext??!1})},`tool-${de.id}`),St=Xe&&typeof We?.end=="number"?We.end:null}Z&&ut.push({part:tt,index:ct,endTime:St,element:Z});return}if(!x.isWorking||x.isGroupExpanded||x.previewedPartIds.has(it.id)||!y&&it.kind!=="tool")return;const xe=ye.has(it.id);switch(it.kind){case"tool":{const de=tt;if(mn(de.tool))break;const We=de.state?.time,Xe=G(de);if(!(!W&&Xe))break;const xt=te[de.id],Pt=e.jsx(gs,{children:e.jsx(Lo,{part:de,isExpanded:l.has(de.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:xt?.hasPrev??!1,hasNextTool:xt?.hasNext??!1})},`tool-${de.id}`);Z=xe?e.jsx(Za,{isMigrating:Le,children:Pt},`migrating-tool-${de.id}`):Pt,St=Xe&&typeof We?.end=="number"?We.end:null;break}case"reasoning":{if(!y)break;const de=tt.time,Oe=typeof de?.end=="number";if(!(Oe&&!F))break;const Xe=e.jsx(gs,{children:e.jsx(Um,{part:tt,messageId:s,onContentChange:p})},`reasoning-${ct}`);Z=xe?e.jsx(Za,{isMigrating:Le,children:Xe},`migrating-reasoning-${ct}`):Xe,St=Oe?de?.end??null:null;break}case"justification":{if(!y)break;const de=tt.time,Oe=typeof de?.end=="number";if(!(Oe&&!I))break;const Xe=e.jsx(gs,{children:e.jsx(Nw,{part:tt,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:p,renderAsReasoning:!0})},`assistant-text-${ct}`);Z=xe?e.jsx(Za,{isMigrating:Le,children:Xe},`migrating-text-${ct}`):Xe,St=Oe?de?.end??null:null;break}}Z&&ut.push({part:tt,index:ct,endTime:St,element:Z})}),ut.sort((tt,ct)=>tt.endTime===null&&ct.endTime===null?tt.index-ct.index:tt.endTime===null?1:ct.endTime===null?-1:tt.endTime-ct.endTime),ut.forEach(({element:tt})=>{Ue.push(tt)}),Ue},[Se,Me,l,Le,a,G,s,p,u,d,ye,I,F,W,Ve,y,o,te,x,A,Ee,Qe]),Ye=x?.turnId,jt=ue(Ue=>Ue.currentSessionId),ft=pt(Ue=>{if(!Ye||!jt)return;const Ze=Ue.messages.get(jt);if(!Ze)return;const ut=Ze.find(it=>it.info?.id===Ye);if(!ut)return;const ct=ut.info.summary?.body;return typeof ct=="string"&&ct.trim().length>0?ct:void 0}),It=typeof x?.summaryBody=="string"&&x.summaryBody.trim().length>0?x.summaryBody:ft,_t=c.useRef(void 0);It&&It.trim().length>0&&(_t.current=It);const Nt=c.useRef(Ye);Nt.current!==Ye&&(Nt.current=Ye,_t.current=void 0);const je=_t.current,_e=x?.isLastAssistantInTurn&&je&&je.trim().length>0,Ge=!!v,at=O&&g&&(J||!!v),[Mt,Yt]=c.useState(!1),Jt=e.jsxs(e.Fragment,{children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{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:Ue=>Ue.stopPropagation(),onClick:U,children:e.jsx(mh,{className:"h-4 w-4"})})}),e.jsx(rt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{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:Ue=>Ue.stopPropagation(),onClick:Q,children:e.jsx(bm,{className:"h-4 w-4"})})}),e.jsx(rt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),b&&e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon","data-visible":N||M?"true":void 0,className:T("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",!ge&&"opacity-50"),disabled:!ge,"aria-label":"Copy message text","aria-hidden":!ge,onPointerDown:Ue=>Ue.stopPropagation(),onClick:Ie,onFocus:()=>{ge&&w(!0)},onBlur:()=>{M||w(!1)},children:M?e.jsx(Tt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gs,{className:"h-3.5 w-3.5"})})}),e.jsx(rt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:T("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:C&&D&&ge?be:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Te,Ge&&e.jsx(gs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Gr,{content:v??""})})},"assistant-error"),_e&&e.jsx(gs,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Yt(!0),onMouseLeave:()=>Yt(!1),children:[e.jsx(Gr,{content:je}),at&&e.jsx("div",{className:T("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",Mt&&"opacity-100 pointer-events-auto"),children:Jt})]})},"summary-body")]}),e.jsx(Cm,{files:r,onShowPopup:u}),!_e&&at&&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:Jt})]})})},iv=({isUser:s,...r})=>s?e.jsx(ov,{messageId:r.messageId,parts:r.parts,isMobile:r.isMobile,hasTouchInput:r.hasTouchInput,hasTextContent:r.hasTextContent,onCopyMessage:r.onCopyMessage,copiedMessage:r.copiedMessage,onShowPopup:r.onShowPopup,agentMention:r.agentMention,onRevert:r.onRevert,onFork:r.onFork}):e.jsx(av,{...r}),ud=c.memo(iv),ei=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}},lv=c.lazy(()=>rs(()=>import("./ToolOutputDialog-oDE1UvDN.js"),__vite__mapDeps([2,0,1,3,4]))),cv=new Set(["task","edit","multiedit","write","bash"]),md=s=>typeof s=="string"&&cv.has(s.toLowerCase());function ti(s){const r=c.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&s!==void 0&&s!==null&&(r.current={hasValue:!0,value:s}),r.current.hasValue?r.current.value:s}const Js=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},dv=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:l,hasTouchInput:d}=Rt(),{currentTheme:u}=nn(),m=c.useRef(null),f=ue(qi(Fe=>({lifecyclePhase:Fe.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const et=s.info.sessionID??Fe.currentSessionId??null;return et?(Fe.streamingMessageIds.get(et)??null)===s.info.id:!1})(),currentSessionId:Fe.currentSessionId,getCurrentAgent:Fe.getCurrentAgent,getSessionAgentSelection:Fe.getSessionAgentSelection,getAgentModelForSession:Fe.getAgentModelForSession,getSessionModelSelection:Fe.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:b,getCurrentAgent:h,getSessionAgentSelection:j,getAgentModelForSession:y,getSessionModelSelection:x}=f,v=st(Fe=>Fe.providers),N=$e(Fe=>Fe.showReasoningTraces),w=$e(Fe=>Fe.toolCallExpansion);c.useEffect(()=>{b&&Cr.getInstance().recordSessionStart(b)},[b]);const[k,D]=c.useState(null),[M,C]=c.useState(!1),[S,A]=c.useState(new Set),[E,R]=c.useState({open:!1,title:"",content:""});c.useEffect(()=>{A(new Set)},[s.info.id,w]);const P=c.useMemo(()=>ei(s.info),[s.info]).isUser,O=c.useMemo(()=>P?s.parts.map(Fe=>Fe.type==="compaction"?{type:"text",text:"/compact"}:Fe):s.parts,[P,s.parts]),J=c.useMemo(()=>{if(P||!r)return null;const Fe=Js(r.info,"clientRole"),et=Js(r.info,"role");if((typeof Fe=="string"?Fe:typeof et=="string"?et:void 0)!=="user")return null;const Ke=Js(r.info,"mode"),wt=Js(r.info,"providerID"),Lt=Js(r.info,"modelID"),ts=Js(r.info,"variant"),es=typeof Ke=="string"&&Ke.trim().length>0?Ke:void 0,ps=typeof wt=="string"&&wt.trim().length>0?wt:void 0,lr=typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0,Ot=typeof ts=="string"&&ts.trim().length>0?ts:void 0;return!es&&!ps&&!lr&&!Ot?null:{agentName:es,providerId:ps,modelId:lr,variant:Ot}},[P,r]),K=c.useMemo(()=>{if(P)return;const Fe=Js(s.info,"mode");if(typeof Fe=="string"&&Fe.trim().length>0)return Fe;if(J?.agentName)return J.agentName;const et=s.info.sessionID;if(!et)return;const Be=h(et);return Be||(j(et)??void 0)},[P,s.info,J,h,j]),L=s.info.sessionID,G=P?null:Js(s.info,"providerID"),B=P?null:Js(s.info,"modelID"),H=c.useMemo(()=>{if(P||!L)return null;if(J?.providerId&&J?.modelId)return{providerId:J.providerId,modelId:J.modelId};if(K){const et=y(L,K);if(et?.providerId&&et?.modelId)return et}const Fe=x(L);return Fe?.providerId&&Fe?.modelId?Fe:null},[P,L,K,J,y,x]),V=c.useMemo(()=>P?null:typeof G=="string"&&G.trim().length>0?G:H?.providerId??null,[P,G,H]),oe=c.useMemo(()=>P?null:typeof B=="string"&&B.trim().length>0?B:H?.modelId??null,[P,B,H]),se=c.useMemo(()=>{if(!P&&V&&oe&&v.length>0){const Fe=v.find(et=>et.id===V);if(Fe?.models&&Array.isArray(Fe.models)){const Ke=Fe.models.find(wt=>wt.id===oe)?.name;return typeof Ke=="string"?Ke:void 0}}},[P,V,oe,v]),Y=c.useMemo(()=>{if(P||!V||!oe)return!1;const Fe=v.find(Ke=>Ke.id===V);if(!Fe?.models||!Array.isArray(Fe.models))return!1;const Be=Fe.models.find(Ke=>Ke.id===oe)?.variants;return!!(Be&&Object.keys(Be).length>0)},[P,oe,V,v]),le=ti(K),I=ti(V??void 0),W=ti(se),F=le??void 0,$=I??null,z=W??void 0,X=c.useMemo(()=>{const Fe=s.info.time;return typeof Fe?.completed=="number"?Fe.completed:null},[s.info.time]),fe=c.useMemo(()=>P?!0:!!(X&&X>0),[P,X]),ve=c.useMemo(()=>{const Fe=s.info.finish;return typeof Fe=="string"?Fe:void 0},[s.info]),ge=c.useMemo(()=>sv(O,{includeReasoning:N}),[O,N]),Re=c.useMemo(()=>P||fe?ge:[],[P,fe,ge]),be=c.useMemo(()=>P?[]:ge.filter(Fe=>Fe.type==="text"),[P,ge]),Ie=c.useMemo(()=>P?[]:ge.filter(et=>et.type==="tool"),[P,ge]),U=c.useMemo(()=>{if(w==="collapsed"||w==="activity")return S;const Fe=new Set;for(const Be of Ie){const Ke=Be.tool;Be.id&&md(Ke)&&Fe.add(Be.id)}if(i?.isFirstAssistantInTurn)for(const Be of i.activityParts){if(Be.kind!=="tool")continue;const Ke=Be.part;Ke.id&&md(Ke.tool)&&Fe.add(Ke.id)}const et=new Set(Fe);for(const Be of S)et.has(Be)?et.delete(Be):et.add(Be);return et},[S,w,Ie,i]),Q=c.useMemo(()=>{if(!P)return;const Fe=s.parts.find(wt=>wt.type==="agent");if(!Fe)return;const et=Fe,Be=typeof et.name=="string"?et.name:void 0;if(!Be)return;const Ke=et.source&&typeof et.source.value=="string"&&et.source.value.trim().length>0?et.source.value:`#${Be}`;return{name:Be,token:Ke}},[P,s.parts]),te=typeof ve!="string",pe=c.useMemo(()=>P?!1:be.length===0||Ie.length===0?te:!0,[be.length,Ie.length,te,P]),me=u?.metadata.variant,Me=c.useMemo(()=>me?me==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[me]),Se=c.useMemo(()=>u?$m(u):Me?dw:uw,[u,Me]),Pe=c.useMemo(()=>P?!1:Cr.getInstance().shouldAnimateMessage(s.info,b||s.info.sessionID),[s.info,b,P]),q=c.useRef(!1),re=c.useMemo(()=>r?ei(r.info):null,[r]),Ve=c.useMemo(()=>t?ei(t.info):null,[t]),he=c.useMemo(()=>P||!Ve?!1:!Ve.isUser&&Ve.role==="assistant",[P,Ve]),ye=c.useMemo(()=>fe?"completed":p||(g?"streaming":"completed"),[fe,p,g]),Le=c.useMemo(()=>{if(P)return!0;const Fe=i?.headerMessageId;if(Fe){if(s.info.id===Fe){if(ye==="completed")return!0;const Be=ye==="streaming"||ye==="cooldown",Ke=q.current;return Be&&!Ke&&(q.current=!0),Ke||Be}return!1}return re?re.isUser:!0},[P,re,i,ye,s.info]),Qe=c.useCallback(Fe=>{navigator.clipboard.writeText(Fe),D(Fe),setTimeout(()=>D(null),2e3)},[]),Ee=i?.turnId,Te=pt(Fe=>{if(!Ee)return;const et=s.info.sessionID;if(!et)return;const Be=Fe.messages.get(et);if(!Be)return;const Ke=Be.find(ts=>ts.info?.id===Ee);if(!Ke)return;const Lt=Ke.info.summary?.body;return typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0}),Ye=pt(Fe=>{if(!Ee)return;const et=s.info.sessionID;if(!et)return;const Be=Fe.messages.get(et);if(!Be)return;const Ke=Be.find(Lt=>Lt.info?.id===Ee);if(!Ke)return;const wt=Ke.info.variant;return typeof wt=="string"&&wt.trim().length>0?wt:void 0}),jt=P?void 0:Ye??J?.variant,ft=!P&&Y?jt??"Default":void 0,It=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:Te,_t=c.useRef(void 0);It&&It.trim().length>0&&(_t.current=It);const Nt=c.useRef(Ee);Nt.current!==Ee&&(Nt.current=Ee,_t.current=void 0);const je=_t.current,_e=c.useMemo(()=>{if(P)return;const Fe=s.info?.error;if(!Fe)return;const et=typeof Fe.data?.message=="string"?Fe.data.message:void 0,Be=typeof Fe.message=="string"?Fe.message:void 0,Ke=typeof Fe.name=="string"?Fe.name:void 0,wt=et||Be||Ke;if(wt)return`Opencode failed to send message with error:
94
- \`${wt}\``},[P,s.info]),Ge=c.useMemo(()=>P?Re.filter(Be=>Be.type==="text").map(Be=>(Be.text||Be.content||"").trim()).filter(Be=>Be.length>0).join(`
95
- `).replace(/\n\s*\n+/g,`
96
- `):_e&&_e.trim().length>0?_e:je&&je.trim().length>0?je:il(Re),[_e,je,Re,P]),at=Ge.length>0,Mt=c.useCallback(()=>{navigator.clipboard.writeText(Ge),C(!0),setTimeout(()=>C(!1),2e3)},[Ge]),Yt=ue(Fe=>Fe.revertToMessage),Jt=ue(Fe=>Fe.forkFromMessage),Ue=c.useCallback(()=>{!L||!s.info.id||Yt(L,s.info.id)},[L,s.info.id,Yt]),Ze=c.useCallback(()=>{!L||!s.info.id||Jt(L,s.info.id)},[L,s.info.id,Jt]),ut=c.useCallback(Fe=>{A(et=>{const Be=new Set(et);return Be.has(Fe)?Be.delete(Fe):Be.add(Fe),Be})},[]),tt=o??null,ct=c.useRef(!1),it=c.useRef(!1),St=c.useRef(!1),Z=c.useRef(!1),xe=c.useRef(!1);c.useEffect(()=>{it.current=!1,St.current=!1,Z.current=!1,xe.current=!1,ct.current=!1},[s.info.id]);const de=c.useCallback(()=>{P||ct.current||(ct.current=!0,n?.("structural"))},[P,n]),Oe=c.useCallback(Fe=>{Fe.image&&R(Fe)},[]),We=c.useCallback(Fe=>{R(et=>({...et,open:Fe}))},[]),Xe=!!Js(s.info,"animationSettled"),Ct=ye==="streaming",xt=c.useMemo(()=>P?!1:ge.some(Fe=>Fe.type==="reasoning"),[P,ge]),Pt=Pe&&!Xe&&!Ct,At=!P&&Pe&&be.length>0&&!pe;return c.useEffect(()=>{if(tt?.onStreamingCandidate){if(!At){St.current&&(xt&&tt?.onReasoningBlock?tt.onReasoningBlock():tt?.onReservationCancelled&&tt.onReservationCancelled(),St.current=!1);return}xe.current||(xe.current=!0,tt.onStreamingCandidate(),St.current=!0)}},[tt,At,xt]),c.useEffect(()=>{tt?.onAnimationStart&&Pt&&(Z.current||(tt.onAnimationStart(),Z.current=!0))},[tt,Pt]),c.useEffect(()=>{if(P)return;const Fe=tt?.onAnimatedHeightChange;if(!Fe||!(Pt||At))return;const Be=m.current;if(!Be)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Fe(Be.getBoundingClientRect().height);return}let Ke=null;const wt=ts=>{if(typeof window>"u"){Fe(ts);return}Ke!==null&&window.cancelAnimationFrame(Ke),Ke=window.requestAnimationFrame(()=>{Fe(ts)})},Lt=new ResizeObserver(ts=>{const es=ts[0];es&&wt(es.contentRect.height)});return Lt.observe(Be),wt(Be.getBoundingClientRect().height),()=>{Ke!==null&&(window.cancelAnimationFrame(Ke),Ke=null),Lt.disconnect()}},[Pt,P,tt,At]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("group w-full",Le?"pt-2":"pt-0",P?"pb-2":he?"pb-0":"pb-2"),"data-message-id":s.info.id,ref:m,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:P?e.jsx(gs,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-xl rounded-br-xs bg-primary/10 dark:bg-primary/8 px-3.5 pt-2.5 pb-1.5",children:e.jsx(ud,{messageId:s.info.id,parts:ge,isUser:P,isMessageCompleted:fe,messageFinish:ve,syntaxTheme:Se,isMobile:l,hasTouchInput:d,copiedCode:k,onCopyCode:Qe,expandedTools:S,onToggleTool:ut,onShowPopup:Oe,streamPhase:ye,allowAnimation:Pt,onContentChange:n,shouldShowHeader:!1,hasTextContent:at,onCopyMessage:Mt,copiedMessage:M,showReasoningTraces:N,onAuxiliaryContentComplete:de,agentMention:Q,onRevert:Ue,onFork:P?Ze:void 0,errorMessage:_e})})})}):e.jsxs("div",{children:[Le&&e.jsx(fw,{isUser:P,providerID:$,agentName:F,modelName:z,variant:ft,isDarkTheme:Me}),e.jsx(ud,{messageId:s.info.id,parts:ge,isUser:P,isMessageCompleted:fe,messageFinish:ve,syntaxTheme:Se,isMobile:l,hasTouchInput:d,copiedCode:k,onCopyCode:Qe,expandedTools:U,onToggleTool:ut,onShowPopup:Oe,streamPhase:ye,allowAnimation:Pt,onContentChange:n,shouldShowHeader:Le,hasTextContent:at,onCopyMessage:Mt,copiedMessage:M,onAuxiliaryContentComplete:de,showReasoningTraces:N,agentMention:Q,turnGroupingContext:i,errorMessage:_e})]})})}),e.jsx(c.Suspense,{fallback:null,children:e.jsx(lv,{popup:E,onOpenChange:We,syntaxTheme:Se,isMobile:l})})]})},uv=c.memo(dv),mv=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Gm(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:T("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:rn(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))}),fv=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
97
- `),o=rn(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(n.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${l})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:o,PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},pv=s=>{const r="h-3 w-3",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(mr,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(du,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Er,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(yi,{className:r}):e.jsx(ca,{className:r})},hv=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},gv=({permission:s,onResponse:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(!1),{respondToPermission:i}=ue(),{currentTheme:l}=nn(),d=c.useMemo(()=>$m(l),[l]),u=async y=>{n(!0);try{await i(s.sessionID,s.id,y),a(!0),r?.(y)}catch{}finally{n(!1)}};if(o)return null;const m=s.permission||"unknown",f=m.toLowerCase(),p=(y,x="")=>{const v=s.metadata[y];return typeof v=="string"?v:typeof v=="number"?String(v):x},g=y=>{const x=s.metadata[y];return typeof x=="number"?x:void 0},b=y=>!!s.metadata[y],h=hv(m),j=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const v=p("command")||p("cmd")||p("script"),N=p("description"),w=p("cwd")||p("working_directory")||p("directory")||p("path"),k=g("timeout");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),w&&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:w})]}),k&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",k,"ms"]}),v&&e.jsx("div",{children:e.jsx(hr,{language:"bash",style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:v})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const v=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("changes")||p("diff"),w=b("replace_all")||b("replaceAll");return e.jsxs(e.Fragment,{children:[w&&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(mt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(mv,{diff:N,syntaxTheme:d,filePath:v})})]})}if(f==="write"||f==="create"||f==="file_write"){const v=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(mt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(fv,{content:N,syntaxTheme:d,filePath:v})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const v=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",w=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,k=p("body")||p("data")||p("payload"),D=g("timeout"),M=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[v&&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:v})]})]}),w&&Object.keys(w).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(mt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(hr,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(w,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(mt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(hr,{language:typeof k=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof k=="object"?JSON.stringify(k,null,2):String(k)})})]}),(D||M)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[D&&e.jsxs("span",{children:["Timeout: ",D,"ms"]}),D&&M&&e.jsx("span",{children:" • "}),M&&e.jsxs("span",{children:["Response format: ",M]})]})]})}const y=p("command")||p("content")||p("action")||p("operation"),x=p("description");return e.jsxs(e.Fragment,{children:[x&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:x}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(mt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(y)})})]}),Object.keys(s.metadata).length>0&&!y&&!x&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(mt,{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(Kr,{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:[pv(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:h})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[s.patterns.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Patterns:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:s.patterns.join(", ")})]}),j()]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Tt,{className:"h-3 w-3"}),"Allow Once"]}),s.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(or,{className:"h-3 w-3"}),(()=>{const y=s.always||s.metadata.always||[];if(y.length===0)return"Always Allow";const v=y.slice(0,2).join(", ");return y.length>2?`Always: ${v}...`:`Always: ${v}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(or,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:y=>{y.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(Wt,{className:"h-3 w-3"}),"Deny"]}),t&&e.jsx("div",{className:"ml-auto typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},si="summary",xv=({question:s})=>{const{respondToQuestion:r,rejectQuestion:t}=ue(),[n,o]=c.useState("0"),[a,i]=c.useState(!1),[l,d]=c.useState(!1),[u,m]=c.useState({}),[f,p]=c.useState({}),[g,b]=c.useState({}),h=c.useMemo(()=>s.questions??[],[s.questions]),j=n===si,y=j?-1:Math.max(0,Math.min(h.length-1,Number(n)||0)),x=j?null:h[y];c.useEffect(()=>{o("0"),m({}),p({}),b({}),d(!1)},[s.id]);const v=c.useMemo(()=>{const _=h.map((P,O)=>({value:String(O),label:P.header?.trim()||`Q${O+1}`}));return h.length>1&&_.push({value:si,label:"Summary"}),_},[h]),N=c.useCallback(_=>{if(!!f[_])return(g[_]??"").trim()||"(no answer)";const O=u[_]??[];return O.length>0?O.join(", "):"(no answer)"},[f,g,u]),w=!!x?.multiple,k=u[y]??[],D=!!f[y],M=c.useMemo(()=>{if(h.length===0)return!1;for(let _=0;_<h.length;_+=1){if(!!f[_]){if(!(g[_]??"").trim())return!1;continue}if((u[_]??[]).length===0)return!1}return!0},[f,g,h.length,u]),C=c.useCallback(()=>{const _=[];for(let P=0;P<h.length;P+=1){if(!!f[P]){const J=(g[P]??"").trim();_.push(J?[J]:[]);continue}_.push(u[P]??[])}return _},[f,g,h.length,u]),S=c.useCallback(_=>{x&&(p(P=>({...P,[y]:!1})),m(P=>{const O=P[y]??[];if(w){const K=O.includes(_)?O.filter(L=>L!==_):[...O,_];return{...P,[y]:K}}return{...P,[y]:[_]}}))},[y,x,w]),A=c.useCallback(()=>{p(_=>({..._,[y]:!0})),m(_=>({..._,[y]:[]}))},[y]),E=c.useCallback(async()=>{if(M){i(!0);try{const _=C();await r(s.sessionID,s.id,_),d(!0)}catch{}finally{i(!1)}}},[C,s.id,s.sessionID,M,r]),R=c.useCallback(async()=>{i(!0);try{await t(s.sessionID,s.id),d(!0)}catch{}finally{i(!1)}},[s.id,s.sessionID,t]);return l||h.length===0?null:e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Input needed"})]})}),e.jsxs("div",{className:"px-2 py-2",children:[v.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:v.map(_=>{const P=n===_.value,O=_.value===si;return e.jsxs("button",{type:"button",onClick:()=>o(_.value),className:T("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",P?"bg-muted/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-muted/20"),children:[O?e.jsx(uu,{className:"h-3 w-3"}):null,_.label]},_.value)})}):null,j?e.jsx("div",{className:"space-y-2",children:h.map((_,P)=>{const O=N(P),J=O!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(P)),className:"w-full text-left rounded px-1.5 py-1 hover:bg-muted/20 transition-colors",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:_.header||`Question ${P+1}`}),e.jsx("div",{className:T("typography-meta",J?"text-foreground":"text-muted-foreground/50 italic"),children:O})]},P)})}):x?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:x.question}),w?e.jsx("div",{className:"typography-micro text-muted-foreground mb-1.5",children:"Select multiple"}):null,e.jsxs("div",{className:"space-y-0.5",children:[x.options.map((_,P)=>{const O=k.includes(_.label),J=/\(recommended\)/i.test(_.label);return e.jsx("button",{type:"button",onClick:()=>S(_.label),disabled:a,className:T("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",O?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5 shrink-0",children:O?e.jsx(fh,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(bi,{className:"h-3.5 w-3.5 text-muted-foreground/50"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:T("typography-meta break-all",O?"text-foreground font-medium":"text-foreground/80"),children:_.label}),J?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),_.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:_.description}):null]})]})},`${P}:${_.label}`)}),e.jsx("button",{type:"button",onClick:A,disabled:a,className:T("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",D?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ro,{className:T("h-3.5 w-3.5",D?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:T("typography-meta",D?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),D?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:_=>{if(_){_.style.height="auto";const P=20,O=P*2,J=P*4;_.style.height=`${Math.min(Math.max(_.scrollHeight,O),J)}px`}},value:g[y]??"",onChange:_=>{const P=_.target;P.style.height="auto";const O=20,J=O*2,K=O*4;P.style.height=`${Math.min(Math.max(P.scrollHeight,J),K)}px`,b(L=>({...L,[y]:P.value}))},placeholder:"Your answer",disabled:a,rows:2,className:"w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none overflow-hidden",autoFocus:!0})}):null]})]}):null]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{type:"button",onClick:E,disabled:a||!M,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(Tt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:R,disabled:a,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(Wt,{className:"h-3 w-3"}),"Dismiss"]}),a?e.jsx("div",{className:"ml-auto",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})}):null]})]})})})},yv=new Set(["task"]),fd=s=>typeof s=="string"&&yv.has(s.toLowerCase()),bv=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},wv=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}}},vv=s=>{const r=wv(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let y=0,x=0,v=0;o.forEach(N=>{if(!N)return;const w=typeof N.additions=="number"?N.additions:0,k=typeof N.deletions=="number"?N.deletions:0;(w!==0||k!==0)&&(v+=1),y+=w,x+=k}),v>0&&(t={additions:y,deletions:x,files:v})}let a=!1,i=!1;s.assistantMessages.forEach(y=>{y.parts.forEach(x=>{x.type==="tool"?a=!0:x.type==="reasoning"&&(i=!0)})});const l=[];let d=0;s.assistantMessages.forEach(y=>{const x=y.info.id;y.info.finish,y.parts.forEach(v=>{const N=typeof v.id=="string"&&v.id.trim().length>0?v.id:`${x}-activity-${d++}`;if(v.type==="tool"){const k=v.state?.time,D=typeof k?.end=="number"?k.end:void 0;l.push({id:N,turnId:s.turnId,messageId:x,kind:"tool",part:v,endedAt:D});return}if(v.type==="reasoning"){const w=v.text??v.content;if(typeof w!="string"||w.trim().length===0)return;const k=v.time,D=typeof k?.end=="number"?k.end:void 0;l.push({id:N,turnId:s.turnId,messageId:x,kind:"reasoning",part:v,endedAt:D});return}})});const u=[],m=new WeakMap;l.forEach(y=>{m.set(y.part,y)});const f=new Map,p=[],g=new Map;let b=null;s.assistantMessages.forEach(y=>{const x=y.info.id;y.parts.forEach(v=>{if(v.type==="tool"){const k=v.tool;if(fd(k)){const D=typeof v.id=="string"&&v.id.trim().length>0?v.id:`${x}-task-${p.length+1}`;f.has(D)||(f.set(D,x),p.push(D)),b=D;return}}const N=m.get(v);if(!N)return;if(N.kind==="tool"){const k=N.part.tool;if(fd(k))return}const w=g.get(b)??[];w.push(N),g.set(b,w)})});const h=y=>{if(y.length===0)return;const x=new Map;y.forEach(w=>{x.set(w.messageId,(x.get(w.messageId)??0)+1)});let v,N=0;for(const w of s.assistantMessages){const k=x.get(w.info.id)??0;if(k>0&&!v&&(v=w.info.id),N+=k,N>=2)return w.info.id}return v};return[null,...p].forEach(y=>{const x=g.get(y)??[];if(x.length===0)return;const v=y===null?h(x):f.get(y);v&&u.push({id:`${s.turnId}:${v}:${y??"start"}`,anchorMessageId:v,afterToolPartId:y,parts:x})}),{activityParts:l,activityGroupSegments:u,hasTools:a,hasReasoning:i,summaryBody:r,diffStats:t}},jv=s=>{const{isWorking:r}=Sl(),t=c.useMemo(()=>bv(s),[s]),n=c.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=c.useMemo(()=>{const h=new Map;return t.forEach(j=>{h.set(j.userMessage.info.id,j),j.assistantMessages.forEach(y=>{h.set(y.info.id,j)})}),h},[t]),a=c.useMemo(()=>{const h=new Map;return t.forEach(j=>{h.set(j.turnId,vv(j))}),h},[t]),[i,l]=c.useState(()=>new Map),d=$e(h=>h.toolCallExpansion),u=d==="activity"||d==="detailed";c.useEffect(()=>{l(new Map)},[d]);const m=c.useCallback(h=>{const j=i.get(h);return j||{isExpanded:u,previewedPartIds:new Set}},[i,u]),f=c.useCallback(h=>{l(j=>{const y=new Map(j),x=y.get(h)??{isExpanded:u,previewedPartIds:new Set};return y.set(h,{...x,isExpanded:!x.isExpanded}),y})},[u]),p=c.useCallback((h,j)=>{j.length!==0&&l(y=>{const x=new Map(y),v=x.get(h)??{isExpanded:u,previewedPartIds:new Set},N=new Set(v.previewedPartIds);return j.forEach(w=>{w&&w.trim().length>0&&N.add(w)}),x.set(h,{...v,previewedPartIds:N}),x})},[u]),g=c.useCallback(h=>o.get(h),[o]),b=c.useCallback(h=>{const j=o.get(h);if(!j||!j.assistantMessages.some(O=>O.info.id===h))return;const x=a.get(j.turnId),v=x?.activityParts??[],N=x?.activityGroupSegments??[],w=!!x?.hasTools,k=!!x?.hasReasoning,D=x?.summaryBody,M=x?.diffStats,C=j.assistantMessages[0]?.info.id,S=h===C,A=j.assistantMessages[j.assistantMessages.length-1]?.info.id,E=h===A,R=C,_=m(j.turnId),P=r&&n===j.turnId;return{turnId:j.turnId,isFirstAssistantInTurn:S,isLastAssistantInTurn:E,summaryBody:D,activityParts:v,activityGroupSegments:N,headerMessageId:R,hasTools:w,hasReasoning:k,diffStats:M,isWorking:P,isGroupExpanded:_.isExpanded,previewedPartIds:_.previewedPartIds,toggleGroup:()=>f(j.turnId),markPartsPreviewed:O=>p(j.turnId,O)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:g,getContextForMessage:b}},Sv=({messages:s,permissions:r,questions:t,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:i,onLoadOlder:l,scrollToBottom:d,pendingAnchorId:u})=>{c.useEffect(()=>{r.length===0&&t.length===0||n("permission")},[r,t,n]);const m=c.useMemo(()=>{const p=new Set;return s.filter(g=>{const b=g.info?.id;if(typeof b=="string"){if(p.has(b))return!1;p.add(b)}return!0}).map(g=>({...g,parts:Jb(g.parts)}))},[s]),{getContextForMessage:f}=jv(m);return e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:i?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:l,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:m.map((p,g)=>e.jsx(uv,{message:p,previousMessage:g>0?m[g-1]:void 0,nextMessage:g<m.length-1?m[g+1]:void 0,onContentChange:n,animationHandlers:o(p.info.id),scrollToBottom:d,isPendingAnchor:u===p.info.id,turnGroupingContext:f(p.info.id)},p.info.id))}),(t.length>0||r.length>0)&&e.jsxs("div",{children:[t.map(p=>e.jsx(xv,{question:p},p.id)),r.map(p=>e.jsx(gv,{permission:p},p.id))]})]})},kv=c.memo(Sv);function Nv(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const Qm=c.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:l,children:d,...u},m)=>{const f=c.useRef(null),p=c.useRef("none"),g=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const b=c.useMemo(()=>{const x={...i};return x["--scroll-shadow-size"]=`${t}px`,x},[t,i]),h=c.useCallback((x,v,N,w,k)=>{const D=`${w}${k.charAt(0).toUpperCase()}${k.slice(1)}Scroll`;v&&N?(x.dataset[D]="true",x.removeAttribute(`data-${w}-scroll`),x.removeAttribute(`data-${k}-scroll`)):(x.dataset[`${w}Scroll`]=String(v),x.dataset[`${k}Scroll`]=String(N),x.removeAttribute(`data-${w}-${k}-scroll`))},[]),j=c.useCallback(x=>{["top","bottom","top-bottom","left","right","left-right"].forEach(v=>{x.removeAttribute(`data-${v}-scroll`)})},[]),y=c.useCallback(()=>{const x=f.current;if(!x)return;if(!n){j(x);return}const v=s==="vertical"?x.scrollTop>r:x.scrollLeft>r;let N=s==="vertical"?x.scrollTop+x.clientHeight+r<x.scrollHeight:x.scrollLeft+x.clientWidth+r<x.scrollWidth;o&&s==="vertical"&&(N=!1),h(x,v,N,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const w=v&&N?"both":v?s==="vertical"?"top":"left":N?s==="vertical"?"bottom":"right":"none";w!==p.current&&(p.current=w,a?.(w))},[j,o,n,r,a,s,h]);return c.useEffect(()=>{const x=f.current;if(!x)return;const v=()=>y(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null,w=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return y(),x.addEventListener("scroll",v,{passive:!0}),N?.observe(x),w?.observe(x,{childList:!0,subtree:!0,characterData:!0}),()=>{x.removeEventListener("scroll",v),N?.disconnect(),w?.disconnect()}},[y]),e.jsx("div",{...u,ref:Nv(f,m),className:l,"data-orientation":s,"data-scroll-shadow":g??!0,style:b,children:d})});Qm.displayName="ScrollShadow";const Cv=160,Mv=({containerRef:s})=>{const[r,t]=c.useState(!0),n=c.useRef(!0),o=c.useRef(!1),a=c.useRef(null),i=c.useRef(null),l=c.useRef(0),d=c.useRef(0),u=c.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),m=c.useCallback(v=>{const N=s.current;if(!N){u();return}i.current===null&&(i.current=v);const w=Math.min(1,(v-i.current)/Cv),k=1-Math.pow(1-w,3),D=l.current,M=d.current,C=D+(M-D)*k;if(N.scrollTop=C,w<1){a.current=window.requestAnimationFrame(m);return}N.scrollTop=M,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=c.useCallback((v,N)=>{const w=s.current;if(!w)return;const k=Math.max(0,v),D=N?.instant??!1;if(o.current=!1,typeof window>"u"||D){u(),w.scrollTop=k;const C=k<=1;n.current!==C&&(n.current=C,t(C));return}if(u(),Math.abs(k-w.scrollTop)<=.5){w.scrollTop=k;const C=k<=1;n.current!==C&&(n.current=C,t(C));return}l.current=w.scrollTop,d.current=k,i.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=c.useCallback(()=>{o.current=!0},[]),g=c.useCallback(()=>{o.current=!0},[]),b=c.useCallback(()=>o.current,[]),h=c.useCallback(()=>s.current?.scrollTop??0,[s]),j=c.useCallback(()=>s.current?.scrollHeight??0,[s]),y=c.useCallback(()=>s.current?.clientHeight??0,[s]),x=c.useCallback(()=>{const v=s.current;if(!v)return;o.current&&a.current!==null&&u();const N=v.scrollTop<=1;n.current!==N&&(n.current=N,t(N))},[u,s]);return c.useEffect(()=>{const v=s.current;if(v)return v.addEventListener("wheel",g,{passive:!0}),v.addEventListener("touchstart",g,{passive:!0}),()=>{v.removeEventListener("wheel",g),v.removeEventListener("touchstart",g)}},[s,g]),c.useEffect(()=>()=>{u()},[u]),c.useMemo(()=>({handleScroll:x,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:b,getScrollTop:h,getScrollHeight:j,getClientHeight:y}),[x,f,p,r,b,h,j,y])},pd=typeof window<"u"?c.useLayoutEffect:c.useEffect,hd=50,gd=40,Dv=.2,Av=.1,Ev=150,$s=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},Iv=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},Pv=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:i,sessionActivityPhase:l})=>{const d=c.useRef(null),u=Mv({containerRef:d}),[m,f]=c.useState(null),[p,g]=c.useState(0),[b,h]=c.useState(!1),[j,y]=c.useState(null),x=c.useRef(null),v=c.useRef(null),N=c.useRef(r.length),w=c.useRef(r.length>0?$s(r[0]):null),k=c.useRef(r.length>0?$s(r[r.length-1]):null),D=c.useRef(0),M=c.useRef(0),C=c.useRef(void 0),S=c.useRef(null),A=c.useRef(!1),E=c.useRef(!1),R=c.useRef(null),_=s?l?.get(s)??"idle":"idle",P=c.useCallback(I=>{const W=Math.max(0,I);D.current!==W&&(D.current=W,g(W))},[]),O=c.useCallback(()=>{const I=d.current;I&&(M.current=I.clientHeight)},[]),J=c.useCallback(()=>{if(!m)return null;const I=d.current;return I?I.querySelector(`[data-message-id="${m}"]`):null},[m]),K=c.useCallback(()=>{const I=d.current,W=D.current;if(!I||W<=0)return!0;const F=I.scrollHeight-W;return I.scrollTop+I.clientHeight<F},[]),L=c.useCallback((I,W)=>{const F=I.offsetHeight,$=I.offsetTop;if(F>W*Dv){const X=W*Av;return $+F-X}else return $-hd},[]),G=c.useCallback(()=>{const I=d.current;if(!I||!S.current)return;const W=J();if(!W)return;const F=I.clientHeight,$=I.scrollHeight,X=L(W,F)+F,fe=D.current,ve=$-fe;if(!A.current&&ve<X){const ge=X-ve;ge>fe&&(P(ge),s&&S.current&&n(s,S.current,ge))}},[L,s,J,n,P]),B=c.useCallback(()=>{const I=d.current;if(!I){h(!1);return}if(j){h(!1);return}if(!(I.scrollHeight>I.clientHeight)){h(!1);return}const F=I.scrollHeight-I.scrollTop-I.clientHeight,$=D.current;if($>0){const z=I.scrollHeight-$,X=I.scrollTop+I.clientHeight;h(X<z)}else h(F>gd)},[j]),H=c.useCallback(I=>{const W=d.current;if(!W)return;const F=W.scrollHeight-W.scrollTop-W.clientHeight;if(E.current&&_==="idle"&&!a&&!I?.force&&F>gd)return;I?.force&&(E.current=!1);const z=W.scrollHeight-W.clientHeight;u.scrollToPosition(Math.max(0,z),I)},[_,a,u]),V=c.useCallback(I=>{if(x.current===I)return;x.current=I,y(I);const W=d.current;if(!W){y(null);return}const F=W.scrollHeight,$=D.current,z=F-$,X=M.current>0?M.current:W.clientHeight,ve=z-hd,ge=ve+X;let Re=0;z<ge&&(Re=ge-z),Re!==$&&P(Re),s&&n(s,I,Re),A.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(ve,{instant:!0}),window.requestAnimationFrame(()=>{y(null)})})},[s,u,n,P]),oe=c.useCallback(I=>{const W=d.current;if(!W||!s)return;I?.isTrusted&&(E.current=!0),u.handleScroll(),B(),_==="idle"&&D.current>0&&K()&&(P(0),S.current=null,f(null),n(s,null,0));const{scrollTop:F,scrollHeight:$,clientHeight:z}=W,X=(F+z/2)/Math.max($,1),fe=Math.floor(X*r.length);t(s,fe)},[s,_,K,u,r.length,n,B,P,t]);c.useEffect(()=>{const I=d.current;if(I)return I.addEventListener("scroll",oe,{passive:!0}),()=>{I.removeEventListener("scroll",oe)}},[oe]),pd(()=>{if(typeof window>"u")return;O();const I=()=>{C.current!==void 0&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{O()},Ev)};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),C.current!==void 0&&window.clearTimeout(C.current)}},[O]),c.useEffect(()=>{if(s&&s!==v.current){v.current=s,Cr.getInstance().recordSessionStart(s),N.current=r.length,w.current=r.length>0?$s(r[0]):null,k.current=r.length>0?$s(r[r.length-1]):null;const I=o(s);_!=="idle"&&I&&I.anchorId?(S.current=I.anchorId,x.current=I.anchorId,A.current=!0,f(I.anchorId),D.current=I.spacerHeight,g(I.spacerHeight),window.requestAnimationFrame(()=>{const F=d.current;if(!F)return;const $=F.querySelector(`[data-message-id="${I.anchorId}"]`);if($){const z=F.clientHeight,X=L($,z);u.scrollToPosition(X,{instant:!0})}})):(x.current=null,S.current=null,A.current=!1,f(null),D.current=0,g(0),window.requestAnimationFrame(()=>{H({instant:!0,force:!0})})),y(null),h(!1),E.current=!1,R.current=null}},[_,s,H,r.length,o]),pd(()=>{if(a){N.current=r.length,w.current=r.length>0?$s(r[0]):null,k.current=r.length>0?$s(r[r.length-1]):null;return}if(v.current!==s)return;const I=N.current,W=r.length;if(W>I&&I>0){const F=w.current,$=$s(r[0]),z=$s(r[W-1]),X=k.current,fe=F!==null&&$!==F,ve=X!==null&&z!==X,ge=fe&&!ve,Re=ve&&!fe;if(ge){S.current=null,A.current=!1,f(null),P(0),N.current=W,w.current=$,k.current=z;return}if(Re){const Ie=r.slice(I,W).find(Iv);if(Ie){const U=$s(Ie);U&&(S.current=U,f(U),V(U))}else G()}}N.current=W,w.current=r.length>0?$s(r[0]):null,k.current=r.length>0?$s(r[r.length-1]):null},[s,a,G,V,r]),c.useEffect(()=>{const I=d.current;if(!I||typeof ResizeObserver>"u")return;const W=new ResizeObserver(()=>{G(),B()});return W.observe(I),()=>{W.disconnect()}},[G,B]),c.useEffect(()=>{if(typeof window>"u"){B();return}const I=window.requestAnimationFrame(()=>{B()});return()=>{window.cancelAnimationFrame(I)}},[s,r.length,B]),c.useEffect(()=>{m&&(G(),B())},[m,G,B]),c.useEffect(()=>{const I=R.current;R.current=_,I!==null&&I!=="idle"&&_==="idle"&&D.current>0&&K()&&S.current!==null&&(P(0),S.current=null,A.current=!1,f(null),s&&n(s,null,0))},[_,s,K,n,P]),c.useEffect(()=>{B()},[p,B]);const se=c.useRef(new Map),Y=c.useCallback(()=>{G(),B()},[G,B]),le=c.useCallback(I=>{const W=se.current.get(I);if(W)return W;const F={onChunk:()=>{G()},onComplete:()=>{G()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{G()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return se.current.set(I,F),F},[G]);return{scrollRef:d,handleMessageContentChange:Y,getAnimationHandlers:le,showScrollButton:b,scrollToBottom:H,spacerHeight:p,pendingAnchorId:j,hasActiveAnchor:m!==null}};function Tv(s){const t=Date.now()-s,n=Math.floor(t/1e3),o=Math.floor(n/60),a=Math.floor(o/60),i=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:i<7?`${i}d ago`:new Date(s).toLocaleDateString()}const Fv=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=ue(h=>h.currentSessionId),o=pt(h=>n?h.messages.get(n)||[]:[]),a=ue(h=>h.revertToMessage),i=ue(h=>h.forkFromMessage),l=ue(h=>h.loadSessions),[d,u]=c.useState(null),[m,f]=c.useState(""),p=c.useMemo(()=>o.filter(j=>j.info.role==="user").reverse(),[o]),g=c.useMemo(()=>{if(!m.trim())return p;const h=m.toLowerCase();return p.filter(j=>xd(j.parts).toLowerCase().includes(h))},[p,m]),b=async h=>{if(n){u(h);try{await i(n,h),await l(),r(!1)}finally{u(null)}}};return n?e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(or,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ns,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ht,{placeholder:"Search messages...",value:m,onChange:h=>f(h.target.value),className:"pl-9 w-full"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:g.length===0?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No messages found":"No messages in this session yet"}):g.map(h=>{const j=xd(h.parts),y=h.info.time.created,x=Tv(y),v=p.length-p.indexOf(h);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",onClick:()=>{t?.(h.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[v,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[j||"[No text content]",j&&j.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:x}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:async N=>{N.stopPropagation(),await a(n,h.info.id),r(!1)},children:e.jsx(Kn,{className:"h-4 w-4"})})}),e.jsx(rt,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:N=>{N.stopPropagation(),b(h.info.id)},disabled:d===h.info.id,children:d===h.info.id?e.jsx(cs,{className:"h-4 w-4 animate-spin"}):e.jsx($t,{className:"h-4 w-4"})})}),e.jsx(rt,{sideOffset:6,children:"Fork from here"})]})]})]})]},h.info.id)})}),e.jsxs("div",{className:"mt-4 p-3 bg-muted/30 rounded-lg",children:[e.jsx("p",{className:"typography-meta text-muted-foreground font-medium mb-2",children:"Actions"}),e.jsxs("div",{className:"flex flex-col gap-1.5 typography-meta text-muted-foreground",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{children:"Click on a message to scroll to it in the conversation"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Undo to this point (message text will populate input)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($t,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function xd(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Xm=()=>{const{currentSessionId:s,messages:r,permissions:t,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:i,loadMoreMessages:l,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,sessionMemoryState:f,openNewSessionDraft:p,isSyncing:g,messageStreamStates:b,trimToViewportWindow:h,sessionActivityPhase:j,newSessionDraft:y}=ue(),{isTimelineDialogOpen:x,setTimelineDialogOpen:v}=$e(),N=c.useMemo(()=>s?o.get(s)??null:null,[s,o]),{isMobile:w}=Rt(),k=!!y?.open;c.useEffect(()=>{!s&&!k&&p()},[s,k,p]);const D=c.useMemo(()=>s?r.get(s)||[]:[],[s,r]),M=c.useMemo(()=>s?t.get(s)||[]:[],[s,t]),C=c.useMemo(()=>s?n.get(s)||[]:[],[s,n]);c.useMemo(()=>[...M,...C],[M,C]);const{scrollRef:S,handleMessageContentChange:A,getAnimationHandlers:E,showScrollButton:R,scrollToBottom:_,spacerHeight:P,pendingAnchorId:O,hasActiveAnchor:J}=Pv({currentSessionId:s,sessionMessages:D,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,isSyncing:g,isMobile:w,sessionActivityPhase:j}),L=!!c.useMemo(()=>s?f.get(s)??null:null,[s,f])?.hasMoreAbove,[G,B]=c.useState(!1);c.useEffect(()=>{B(!1)},[s]);const H=c.useRef(null);c.useLayoutEffect(()=>{if(!(!s||s===H.current)&&(H.current=s,!J)){const se=S.current;se&&(se.scrollTop=se.scrollHeight-se.clientHeight)}},[s,S,J]);const V=c.useCallback(async()=>{if(!s||G)return;const se=S.current,Y=se?.scrollHeight??null,le=se?.scrollTop??null;B(!0);try{if(await l(s,"up"),se&&Y!==null&&le!==null){const I=se.scrollHeight-Y;se.scrollTop=le+I}}finally{B(!1)}},[s,G,l,S]),oe=c.useCallback(se=>{const Y=S.current;if(!Y)return;const le=Y.querySelector(`[data-message-id="${se}"]`);if(le){const I=Y.getBoundingClientRect(),$=le.getBoundingClientRect().top-I.top+Y.scrollTop-50;Y.scrollTo({top:$,behavior:"smooth"})}},[S]);return c.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await i(s)}finally{typeof window>"u"?_():window.requestAnimationFrame(()=>{_()})}})()},[s,i,r,_]),!s&&!k?e.jsx("div",{className:"flex flex-col h-full bg-background",style:w?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(Xa,{})}):!s&&k?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:w?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Xa,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(So,{scrollToBottom:_})})]}):s?a&&D.length===0&&!N&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:w?{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(Y=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Qa,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Qa,{className:"h-4 w-24"}),e.jsx(Qa,{className:"h-20 w-full"})]})]},Y))})}),e.jsx(So,{scrollToBottom:_})]}):D.length===0&&!N?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:w?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Xa,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(So,{scrollToBottom:_})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:w?{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(Qm,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:S,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!O,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(kv,{messages:D,permissions:M,questions:C,onMessageContentChange:A,getAnimationHandlers:E,hasMoreAbove:L,isLoadingOlder:G,onLoadOlder:V,scrollToBottom:_,pendingAnchorId:O}),P>0&&J&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:P},"aria-hidden":"true"})]})}),e.jsx(ll,{containerRef:S})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[R&&D.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>_({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(An,{className:"h-4 w-4"})})}),e.jsx(So,{scrollToBottom:_})]}),e.jsx(Fv,{open:x,onOpenChange:v,onScrollToMessage:oe})]}):null};class Jm extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(xl,{className:"w-full max-w-md",children:[e.jsx(um,{className:"text-center",children:e.jsxs(mm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(ph,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(fm,{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(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ps,{className:"h-4 w-4 mr-2"}),"Reset Chat"]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:"If the problem persists, try refreshing the page."})]})]})}):this.props.children}}const $i=()=>{const s=ue(r=>r.currentSessionId);return e.jsx(Jm,{sessionId:s||void 0,children:e.jsx(Xm,{})})},yd=12,Rv=[{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"}],_v=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=Rv,onComplete:a})=>{const i=Ce.useRef(!1);Ce.useEffect(()=>{!s&&i.current&&a?.(),s&&(i.current=!0)},[s,a]);const l=Ce.useMemo(()=>Array.from({length:yd},(d,u)=>{const m=Math.PI*2*u/yd;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:T("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:l.map((m,f)=>{const p=m.x*d.radius,g=m.y*d.radius,b={"--translate-x":`${p}px`,"--translate-y":`${g}px`,"--particle-delay":`${m.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:b},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},Ov=({durationMs:s=3400}={})=>{const[r,t]=Ce.useState({isActive:!1,cycle:0}),n=Ce.useRef(null),o=Ce.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Ce.useCallback(()=>{o(),t(l=>l.isActive?{...l,isActive:!1}:l)},[o]),i=Ce.useCallback(()=>{o(),t(l=>({isActive:!0,cycle:l.cycle+1})),n.current=window.setTimeout(()=>{t(l=>l.isActive?{...l,isActive:!1}:l),n.current=null},s)},[o,s]);return Ce.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:i,dismissFireworks:a}},Zm=c.createContext(void 0),bd=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=Ov(),a=c.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Zm.Provider,{value:a,children:[s,e.jsx(_v,{isActive:r,burstKey:t})]})},$v=()=>{const s=c.useContext(Zm);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},ba=zt()(Kt(As((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 fx();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 xx("");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 px(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 hx(t,a),await r().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async t=>{try{return await gx(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:Es(()=>ds()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ba);const Lv=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Bv=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:i=!1})=>{const[l,d]=c.useState(!1),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,b]=c.useState(""),[h,j]=c.useState(!1),y=c.useRef(null),x=c.useMemo(()=>Lv(g),[g]),v=c.useMemo(()=>{const C=u.toLowerCase();return C?r.filter(S=>S.toLowerCase().includes(C)):r},[u,r]),N=c.useMemo(()=>{const C=u.toLowerCase();return C?t.filter(S=>S.toLowerCase().includes(C)):t},[u,t]),w=C=>{if(C===s){d(!1);return}o(C),d(!1),m("")},k=()=>{p(!0),setTimeout(()=>y.current?.focus(),50)},D=async()=>{if(!(!x||h)){j(!0);try{await a(x),b(""),p(!1),d(!1)}finally{j(!1)}}},M=()=>{b(""),p(!1)};return c.useEffect(()=>{l||(m(""),p(!1),b(""))},[l]),e.jsxs(Ut,{open:l,onOpenChange:d,children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx($t,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(Et,{className:"size-4 opacity-60"})]})})}),e.jsxs(rt,{sideOffset:8,children:["Switch branch (",r.length," local · ",t.length," remote)"]})]}),e.jsx(Gt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(hm,{className:"h-full min-h-0",children:[e.jsx(gm,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(xm,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(ym,{children:"No branches found."}),e.jsx(wn,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:y,placeholder:"New branch name",value:g,onChange:C=>b(C.target.value),onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),D()):C.key==="Escape"&&(C.preventDefault(),M())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:D,disabled:!x||h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:h?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(qt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:M,disabled:h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Wt,{className:"size-4"})})]}):e.jsxs(ss,{onSelect:k,children:[e.jsx(qt,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Zo,{}),e.jsxs(wn,{heading:"Local branches",children:[v.map(C=>e.jsxs(ss,{onSelect:()=>w(C),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:C}),(n?.[C]?.ahead||n?.[C]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[C].ahead||0," ahead ·"," ",n[C].behind||0," behind"]})]}),s===C&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${C}`)),v.length===0&&e.jsx(ss,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Zo,{}),e.jsxs(wn,{heading:"Remote branches",children:[N.map(C=>e.jsx(ss,{onSelect:()=>w(C),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:C})},`remote-${C}`)),N.length===0&&e.jsx(ss,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},zv=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Wv=({currentBranch:s,onRename:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(s||""),[i,l]=c.useState(!1),d=c.useRef(null),u=()=>{!s||!r||(a(s),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!s||!r||!o.trim())return;const g=zv(o);if(g===s){n(!1);return}l(!0);try{await r(s,g),n(!1),a("")}finally{l(!1)}},f=()=>{n(!1),a("")},p=g=>{g.key==="Enter"?(g.preventDefault(),m()):g.key==="Escape"&&(g.preventDefault(),f())};return t?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:g=>{g.preventDefault(),m()},children:[e.jsx($t,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:g=>a(g.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:i?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Tt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Wt,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx($t,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate typography-ui-label font-normal text-foreground",children:s||"Detached HEAD"})]}),r&&s&&e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(ro,{className:"size-4"})})]})},Hv=({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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[s==="fetch"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Dr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(rt,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[s==="pull"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(An,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(rt,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[s==="push"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(so,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(rt,{sideOffset:8,children:"Push changes"})]})]})},Uv={branch:$t,briefcase:Qi,house:Yi,graduation:Ki,code:nr,heart:fu,user:Fs},Vv={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 ef(s){return s&&Vv[s]||"var(--primary)"}const wd=({icon:s,className:r,colorToken:t})=>{const n=Uv[s??"branch"]??Fs;return e.jsx(n,{className:r,style:{color:ef(t)}})},Gv=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(Ut,{children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:ef(s?.color)},disabled:o,children:[n?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(wd,{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(Et,{className:"size-4 opacity-60"})]})})}),e.jsxs(rt,{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(Gt,{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(kt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(wd,{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))})]})},qv=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:i,onPush:l,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:g,isApplyingIdentity:b,isWorktreeMode:h})=>s?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[h?e.jsx(Wv,{currentBranch:s.current,onRename:m}):e.jsx(Bv,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(nt,{delayDuration:800,children:[e.jsx(ot,{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(so,{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(An,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(rt,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(Hv,{syncAction:o,onFetch:a,onPull:i,onPush:l,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(Gv,{activeProfile:f,identities:p,onSelect:g,isApplying:b})]}):null,Kv=({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(Hi,{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(Ne,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(An,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),tf={"?":{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"}},Yv=tf.M;function Qv(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 Xv(s){const r=Qv(s);return tf[r]??Yv}const Jv=c.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:l}){const d=Ce.useMemo(()=>Xv(r),[r]),u=d.description,m=l?.insertions??0,f=l?.deletions??0,p=Ce.useCallback(h=>{h.key===" "?(h.preventDefault(),n()):h.key==="Enter"&&(h.preventDefault(),o())},[n,o]),g=Ce.useCallback(h=>{h.preventDefault(),h.stopPropagation(),n()},[n]),b=Ce.useCallback(h=>{h.preventDefault(),h.stopPropagation(),a()},[a]);return e.jsx("li",{children:e.jsxs("div",{className:"group flex items-center gap-2 px-3 py-1.5 hover:bg-sidebar/40 cursor-pointer",role:"button",tabIndex:0,onClick:o,onKeyDown:p,children:[e.jsx("button",{type:"button",onClick:g,"aria-pressed":t,"aria-label":`Select ${r.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t?e.jsx(Vi,{className:"size-4 text-primary"}):e.jsx(Gi,{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(nt,{delayDuration:200,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:b,disabled:i,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:i?e.jsx(cs,{className:"size-3.5 animate-spin"}):e.jsx(Dr,{className:"size-3.5"})})}),e.jsx(rt,{sideOffset:8,children:"Revert changes"})]})]})})}),Zv=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:i,onViewDiff:l,onRevertFile:d})=>{const u=r.size,m=s.length;return e.jsxs("section",{className:"flex flex-col rounded-xl border border-border/60 bg-background/70",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[u,"/",m]}),m>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(mt,{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(Jv,{file:f,checked:r.has(f.path),stats:t?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>l(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function Jr({className:s,variant:r,...t}){return e.jsx(Ne,{variant:r,size:"sm",className:T("h-7 px-2 py-0",s),...t})}const ri=38,vd=200,e0=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=c.useRef(null);return c.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${ri}px`;const i=Math.min(Math.max(a.scrollHeight,ri),vd);a.style.height=`${i}px`},[s]),e.jsx(Ts,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:T("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:ri,maxHeight:vd}})},t0=({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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(An,{className:"size-4"})})}),e.jsx(rt,{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))})]})},s0=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:l,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f})=>{const p=s>0,g=r.trim()&&p&&m===null;return e.jsxs(xa,{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(ya,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(t0,{highlights:n,onInsert:o,onClear:a}),e.jsx(e0,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:l||m!==null||s===0||f,"aria-label":"Generate commit message",children:l?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(ou,{className:"size-4 text-primary"})})}),e.jsx(rt,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Jr,{variant:"outline",onClick:d,disabled:!g||l,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Hi,{className:"size-4"}),"Commit"]})}),e.jsx(Jr,{variant:"default",onClick:u,disabled:!g||l,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(so,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function jd(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 r0(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 n0=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:T("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:jd(s.date),children:jd(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(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(s.hash)},children:e.jsx(Gs,{className:"size-3"})})}),e.jsx(rt,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),r&&e.jsx("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:o?e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(cs,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(i=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:T("font-semibold w-3 text-center",r0(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))})})]}),o0=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],a0=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:l,onCopyHash:d})=>{const[u,m]=c.useState(!0);return s?e.jsxs(xa,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(bl,{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(vs,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(js,{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(Xr,{placeholder:"Commits"})}),e.jsx(Ss,{children:o0.map(f=>e.jsx(Bt,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(ia,{className:"size-4 text-muted-foreground"}):e.jsx(Et,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(ya,{children:e.jsx(mt,{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(n0,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:i.get(f.hash)??[],isLoadingFiles:l.has(f.hash),onCopyHash:d},f.hash))})})})]}):null};let Ln=null;const i0=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=ue(),{currentDirectory:n}=dt(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},l0=()=>{const{git:s}=In(),r=i0(),{currentSessionId:t,worktreeMetadata:n}=ue(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:l,loadGlobalIdentity:d}=ba(),u=cl(r??null),m=em(r??null),f=tm(r??null),p=uy(r??null),g=my(r??null),b=Xt(je=>je.isLoadingStatus),h=Xt(je=>je.isLoadingLog),{setActiveDirectory:j,fetchAll:y,fetchStatus:x,fetchBranches:v,fetchLog:N,fetchIdentity:w,setLogMaxCount:k}=Xt(),D=c.useMemo(()=>!Ln||Ln.directory!==r?null:Ln,[r]),[M,C]=c.useState(D?.commitMessage??""),[S,A]=c.useState(null),[E,R]=c.useState(null),[_,P]=c.useState(25),[O,J]=c.useState(!1),{triggerFireworks:K}=$v(),[L,G]=c.useState(()=>new Set(D?.selectedPaths??[])),[B,H]=c.useState(!1),[V,oe]=c.useState(new Set),[se,Y]=c.useState(!1),[le,I]=c.useState([]),W=c.useCallback(()=>{I([])},[]),[F,$]=c.useState(new Set),[z,X]=c.useState(new Map),[fe,ve]=c.useState(new Set),ge=c.useCallback(je=>{navigator.clipboard.writeText(je).then(()=>{ne.success("Commit hash copied")}).catch(()=>{ne.error("Failed to copy")})},[]),Re=c.useCallback(je=>{$(_e=>{const Ge=new Set(_e);return Ge.has(je)?Ge.delete(je):Ge.add(je),Ge})},[]);c.useEffect(()=>{if(!r||!s)return;const je=Array.from(F).filter(_e=>!z.has(_e)&&!fe.has(_e));je.length!==0&&(ve(_e=>{const Ge=new Set(_e);return je.forEach(at=>Ge.add(at)),Ge}),je.forEach(_e=>{s.getCommitFiles(r,_e).then(Ge=>{X(at=>new Map(at).set(_e,Ge.files))}).catch(Ge=>{console.error("Failed to fetch commit files:",Ge),X(at=>new Map(at).set(_e,[]))}).finally(()=>{ve(Ge=>{const at=new Set(Ge);return at.delete(_e),at})})}))},[F,r,s,z,fe]),c.useEffect(()=>()=>{if(!r){Ln=null;return}Ln={directory:r,selectedPaths:Array.from(L),commitMessage:M}},[M,r,L]),c.useEffect(()=>{l(),d()},[l,d]),c.useEffect(()=>{r&&(j(r),Xt.getState().directories.get(r)?.status||y(r,s,{force:!0}))},[r,j,y,s]);const be=c.useCallback(async(je=!0)=>{if(r)try{await Promise.all([x(r,s),v(r,s)])}catch(_e){if(je){const Ge=_e instanceof Error?_e.message:"Failed to refresh repository state";ne.error(Ge)}}},[r,s,x,v]),Ie=c.useCallback(async()=>{r&&await N(r,s,_)},[r,s,N,_]),U=c.useCallback(async()=>{r&&await w(r,s)},[r,s,w]),Q=c.useMemo(()=>{if(!m)return[];const je=m.files??[],_e=new Map;return je.forEach(Ge=>{_e.set(Ge.path,Ge)}),Array.from(_e.values()).sort((Ge,at)=>Ge.path.localeCompare(at.path))},[m]);c.useEffect(()=>{if(!m||Q.length===0){G(new Set),H(!1);return}G(je=>{const _e=new Set,Ge=je??new Set;return Q.forEach(at=>{Ge.has(at.path)?_e.add(at.path):B||_e.add(at.path)}),_e})},[m,Q,B]);const te=async je=>{if(r){A(je);try{if(je==="fetch")await s.gitFetch(r),ne.success("Fetched latest updates");else if(je==="pull"){const _e=await s.gitPull(r);ne.success(`Pulled ${_e.files.length} file${_e.files.length===1?"":"s"}`)}else je==="push"&&(await s.gitPush(r),ne.success("Pushed to remote"));await be(!1),await Ie()}catch(_e){const Ge=_e instanceof Error?_e.message:`Failed to ${je==="pull"?"pull":je}`;ne.error(Ge)}finally{A(null)}}},pe=async(je={})=>{if(!r)return;if(!M.trim()){ne.error("Please enter a commit message");return}const _e=Array.from(L).sort();if(_e.length===0){ne.error("Select at least one file to commit");return}const Ge=je.pushAfter?"commitAndPush":"commit";R(Ge);try{await s.createGitCommit(r,M.trim(),{files:_e}),ne.success("Commit created successfully"),C(""),G(new Set),H(!1),W(),await be(),je.pushAfter?(await s.gitPush(r),ne.success("Pushed to remote"),K(),await be(!1)):await be(!1),await Ie()}catch(at){const Mt=at instanceof Error?at.message:"Failed to create commit";ne.error(Mt)}finally{R(null)}},me=c.useCallback(async()=>{if(r){if(L.size===0){ne.error("Select at least one file to describe");return}Y(!0);try{const{message:je}=await s.generateCommitMessage(r,Array.from(L)),_e=je.subject?.trim()??"",Ge=Array.isArray(je.highlights)?je.highlights:[];_e&&C(_e),I(Ge),ne.success("Commit message generated")}catch(je){const _e=je instanceof Error?je.message:"Failed to generate commit message";ne.error(_e)}finally{Y(!1)}}},[r,L,s]),Me=async je=>{if(!r||!m)return;const _e=m.current??null;try{await s.createBranch(r,je,_e??"HEAD"),ne.success(`Created branch ${je}`);let Ge=!1;try{await s.checkoutBranch(r,je),await s.gitPush(r,{remote:"origin",branch:je,options:["--set-upstream"]}),Ge=!0}catch(at){const Mt=at instanceof Error?at.message:"Unable to push new branch to origin.";ne.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Mt]})})}finally{if(_e)try{await s.checkoutBranch(r,_e)}catch(at){console.warn("Failed to restore original branch after creation:",at)}}await be(),await Ie(),Ge&&ne.success(`Upstream set for ${je}`)}catch(Ge){const at=Ge instanceof Error?Ge.message:"Failed to create branch";throw ne.error(at),Ge}},Se=async(je,_e)=>{if(r)try{await s.renameBranch(r,je,_e),ne.success(`Renamed branch ${je} to ${_e}`),await be(),await Ie()}catch(Ge){const at=Ge instanceof Error?Ge.message:`Failed to rename branch ${je} to ${_e}`;ne.error(at)}},Pe=async je=>{if(!r)return;const _e=je.replace(/^remotes\//,"");if(m?.current!==_e)try{await s.checkoutBranch(r,_e),ne.success(`Checked out ${_e}`),await be(),await Ie()}catch(Ge){const at=Ge instanceof Error?Ge.message:`Failed to checkout ${_e}`;ne.error(at)}},q=async je=>{if(r){J(!0);try{await s.setGitIdentity(r,je.id),ne.success(`Applied "${je.name}" to repository`),await U()}catch(_e){const Ge=_e instanceof Error?_e.message:"Failed to apply git identity";ne.error(Ge)}finally{J(!1)}}},re=c.useMemo(()=>f?.all?f.all.filter(je=>!je.startsWith("remotes/")).sort():[],[f]),Ve=c.useMemo(()=>f?.all?f.all.filter(je=>je.startsWith("remotes/")).map(je=>je.replace(/^remotes\//,"")).sort():[],[f]),he=c.useMemo(()=>{const je=new Map;i&&je.set(i.id,i);for(const _e of a)je.set(_e.id,_e);return Array.from(je.values())},[a,i]),ye=c.useMemo(()=>{if(g?.userName&&g?.userEmail){const je=a.find(_e=>_e.userName===g.userName&&_e.userEmail===g.userEmail);return je||(i&&i.userName===g.userName&&i.userEmail===g.userEmail?i:{id:"local-config",name:g.userName,userName:g.userName,userEmail:g.userEmail,sshKey:g.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[g,a,i]),Le=Q.length,Qe=L.size,Ee=b||S!==null||E!==null,Te=Le>0,Ye=je=>{G(_e=>{const Ge=new Set(_e);return Ge.has(je)?Ge.delete(je):Ge.add(je),Ge}),H(!0)},jt=()=>{const je=new Set(Q.map(_e=>_e.path));G(je),H(!0)},ft=()=>{G(new Set),H(!0)},It=c.useCallback(async je=>{if(r){oe(_e=>{const Ge=new Set(_e);return Ge.add(je),Ge});try{await s.revertGitFile(r,je),ne.success(`Reverted ${je}`),await be(!1)}catch(_e){const Ge=_e instanceof Error?_e.message:"Failed to revert changes";ne.error(Ge)}finally{oe(_e=>{const Ge=new Set(_e);return Ge.delete(je),Ge})}}},[r,be,s]),_t=c.useCallback(()=>{if(le.length===0)return;const je=le.map(_e=>_e.trim()).filter(Boolean);if(je.length===0){W();return}C(_e=>{const Ge=_e.trim(),at=Ge.length>0?`
98
-
99
- `:"";return`${Ge}${at}${je.join(`
100
- `)}`.trim()})},[le,W]),Nt=c.useCallback(je=>{P(je),r&&(k(r,je),N(r,s,je))},[r,k,N,s]);return r?b&&u===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(cs,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):u===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx($t,{className:"mb-3 size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Not a Git repository"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Choose a different directory or initialize Git to use this workspace."})]}):e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background","data-keyboard-avoid":"true",children:[e.jsx(qv,{status:m,localBranches:re,remoteBranches:Ve,branchInfo:f?.branches,syncAction:S,onFetch:()=>te("fetch"),onPull:()=>te("pull"),onPush:()=>te("push"),onCheckoutBranch:Pe,onCreateBranch:Me,onRenameBranch:Se,activeIdentityProfile:ye,availableIdentities:he,onSelectIdentity:q,isApplyingIdentity:O,isWorktreeMode:!!o}),e.jsx(mt,{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:[Te?e.jsx(Zv,{changeEntries:Q,selectedPaths:L,diffStats:m?.diffStats,revertingPaths:V,onToggleFile:Ye,onSelectAll:jt,onClearSelection:ft,onViewDiff:je=>$e.getState().navigateToDiff(je),onRevertFile:It}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(Kv,{behind:m?.behind??0,onPull:()=>te("pull"),isPulling:S==="pull"})}),Q.length>0&&e.jsx(s0,{selectedCount:Qe,commitMessage:M,onCommitMessageChange:C,generatedHighlights:le,onInsertHighlights:_t,onClearHighlights:W,onGenerateMessage:me,isGeneratingMessage:se,onCommit:()=>pe({pushAfter:!1}),onCommitAndPush:()=>pe({pushAfter:!0}),commitAction:E,isBusy:Ee})]}),e.jsx(a0,{log:p,isLogLoading:h,logMaxCount:_,onLogMaxCountChange:Nt,expandedCommitHashes:F,onToggleCommit:Re,commitFilesMap:z,loadingCommitHashes:fe,onCopyHash:ge})]})})]}):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."})})},c0=1e6;function Lr(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const ko=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Sd=zt((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=Lr(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=Lr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o),u=!l||l.terminalSessionId!==n.sessionId?ko(o):l??ko(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=Lr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??ko(o);return i.set(o,{...l,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=Lr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??ko(o),d=a.nextChunkId,u={id:d,data:n},m=[...l.bufferChunks,u];let f=l.bufferLength+n.length;for(;f>c0&&m.length>1;){const g=m.shift();if(!g)break;f-=g.data.length}const p=m.map(g=>g.data).join("");return i.set(o,{...l,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=Lr(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=Lr(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=Lr(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),sf=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),d0=[{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'}],u0=[{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'}],rf=s=>Object.fromEntries(s.map(r=>[r.id,r])),kd=rf(d0),Br=rf(u0),m0="ibm-plex-sans",Bo="ibm-plex-mono";function f0(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 p0(s,r,t,n){const a=`${s}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!0,fontSize:r,lineHeight:1.15,fontFamily:a,allowTransparency:!1,theme:{background:t.background,foreground:t.foreground,cursor:t.cursor,cursorAccent:t.cursorAccent,selectionBackground:t.selectionBackground,selectionForeground:t.selectionForeground,black:t.black,red:t.red,green:t.green,yellow:t.yellow,blue:t.blue,magenta:t.magenta,cyan:t.cyan,white:t.white,brightBlack:t.brightBlack,brightRed:t.brightRed,brightGreen:t.brightGreen,brightYellow:t.brightYellow,brightBlue:t.brightBlue,brightMagenta:t.brightMagenta,brightCyan:t.brightCyan,brightWhite:t.brightWhite},scrollback:5e4,ghostty:n}}let ni=null;function h0(){return ni||(ni=xh.load()),ni}function g0(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 Li=c.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:l,enableTouchScroll:d},u)=>{const m=c.useRef(null),f=c.useRef(null),p=c.useRef(null),g=c.useRef(null),b=c.useRef(t),h=c.useRef(n),j=c.useRef(null),y=c.useRef(""),x=c.useRef(null),v=c.useRef(!1),N=c.useRef(null),w=c.useRef(null),k=c.useRef(null),D=c.useRef(0),M=c.useRef(null),[,C]=c.useReducer(L=>L+1,0),[S,A]=c.useReducer(L=>L+1,0);b.current=t,h.current=n;const E=c.useCallback((L,G)=>{const B=M.current,H=m.current;if(!B||!H)return;const V=H.getBoundingClientRect(),oe=V.left+V.width/2,se=V.top+V.height-12,Y=typeof L=="number"?L:oe,le=typeof G=="number"?G:se,I=8,W=Math.max(I,Math.min(V.width-I,Y-V.left)),F=Math.max(I,Math.min(V.height-I,le-V.top));B.style.left=`${W}px`,B.style.top=`${F}px`,B.style.bottom="";try{B.focus({preventScroll:!0})}catch{try{B.focus()}catch{}}},[]),R=c.useCallback(()=>{y.current="",x.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(x.current),x.current=null,v.current=!1,N.current=null},[]),_=c.useCallback(()=>{const L=g.current,G=p.current,B=m.current;if(!L||!G||!B)return;const H=B.getBoundingClientRect();if(!(H.width<24||H.height<24))try{L.fit();const V={cols:G.cols,rows:G.rows},oe=j.current;(!oe||oe.cols!==V.cols||oe.rows!==V.rows)&&(j.current=V,h.current(V.cols,V.rows))}catch{}},[]),P=c.useCallback(()=>{if(v.current)return;const L=p.current;if(!L){R();return}if(!y.current)return;const G=y.current;y.current="",v.current=!0,L.write(G,()=>{v.current=!1,y.current&&(typeof window<"u"?x.current=window.requestAnimationFrame(()=>{x.current=null,P()}):P())})},[R]),O=c.useCallback(()=>{x.current===null&&(typeof window<"u"?x.current=window.requestAnimationFrame(()=>{x.current=null,P()}):P())},[P]),J=c.useCallback(L=>{L&&(y.current+=L,O())},[O]),K=c.useCallback(()=>{if(w.current?.(),w.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),!d){D.current=0;return}const L=m.current;if(!L)return;const G=p.current;if(!G)return;D.current=0;const B=2.2,H=2.8,V=25,oe=.25,se=8,Y=.05,le=.015,I={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},W=()=>typeof performance<"u"?performance.now():Date.now(),F=Math.max(12,Math.round(i*1.35));let $=0;const z=Q=>{if(!Q)return!1;const te=G.getViewportY(),pe=$+Q,me=Math.trunc(pe/F);return $=pe-me*F,me!==0&&G.scrollLines(me),G.getViewportY()!==te},X=()=>{I.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(I.rafId),I.rafId=null},fe={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const Q=Object.assign(I,{pointerId:null,startX:null,startY:null,moved:!1}),te=6,pe=Pe=>{if(Pe.pointerType==="touch"){X(),Q.pointerId=Pe.pointerId,Q.startX=Pe.clientX,Q.startY=Pe.clientY,Q.moved=!1,Q.lastY=Pe.clientY,Q.lastTime=W(),Q.velocity=0;try{L.setPointerCapture(Pe.pointerId)}catch{}}},me=Pe=>{if(Pe.pointerType!=="touch"||Q.pointerId!==Pe.pointerId)return;if(Q.startX!==null&&Q.startY!==null&&!Q.moved){const Te=Pe.clientX-Q.startX,Ye=Pe.clientY-Q.startY;Math.hypot(Te,Ye)>=te&&(Q.moved=!0)}if(Q.lastY===null){Q.lastY=Pe.clientY,Q.lastTime=W();return}const q=Q.lastY,re=Q.lastTime??W(),Ve=W();Q.lastY=Pe.clientY,Q.lastTime=Ve;const he=q-Pe.clientY;if(Math.abs(he)<1)return;const ye=Math.max(Ve-re,8),Le=B+Math.min(H,Math.abs(he)/V),Qe=he*Le,Ee=Qe/ye;Q.velocity=Q.velocity*(1-oe)+Ee*oe,Q.velocity>se?Q.velocity=se:Q.velocity<-se&&(Q.velocity=-se),Q.moved&&(Pe.cancelable&&Pe.preventDefault(),Pe.stopPropagation()),z(Qe)},Me=Pe=>{if(Pe.pointerType!=="touch"||Q.pointerId!==Pe.pointerId)return;const q=!Q.moved;Q.pointerId=null,Q.startX=null,Q.startY=null,Q.moved=!1,Q.lastY=null,Q.lastTime=null;try{L.releasePointerCapture(Pe.pointerId)}catch{}if(q){E(Pe.clientX,Pe.clientY);return}if(typeof window>"u")return;if(Math.abs(Q.velocity)<Y){Q.velocity=0;return}let re=W();const Ve=()=>{const he=W(),ye=Math.max(he-re,8);re=he;const Le=z(Q.velocity*ye)??!1,Qe=Math.sign(Q.velocity),Ee=Math.max(0,Math.abs(Q.velocity)-le*ye);if(Q.velocity=Ee*Qe,!Le||Ee<=Y){X(),Q.velocity=0;return}Q.rafId=window.requestAnimationFrame(Ve)};Q.rafId=window.requestAnimationFrame(Ve)};L.addEventListener("pointerdown",pe,fe),L.addEventListener("pointermove",me,fe),L.addEventListener("pointerup",Me,fe),L.addEventListener("pointercancel",Me,fe);const Se=L.style.touchAction;L.style.touchAction="manipulation",w.current=()=>{X(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),D.current=0,L.removeEventListener("pointerdown",pe,fe),L.removeEventListener("pointermove",me,fe),L.removeEventListener("pointerup",Me,fe),L.removeEventListener("pointercancel",Me,fe),L.style.touchAction=Se};return}const ge=6,Re=Q=>{Q.touches.length===1&&(X(),I.lastY=Q.touches[0].clientY,I.lastTime=W(),I.velocity=0,I.startX=Q.touches[0].clientX,I.startY=Q.touches[0].clientY,I.didMove=!1)},be=Q=>{if(Q.touches.length!==1){I.lastY=null,I.lastTime=null,I.velocity=0,I.startX=null,I.startY=null,I.didMove=!1,X();return}const te=Q.touches[0].clientX,pe=Q.touches[0].clientY;if(I.startX!==null&&I.startY!==null&&!I.didMove){const ye=te-I.startX,Le=pe-I.startY;Math.hypot(ye,Le)>=ge&&(I.didMove=!0)}if(I.lastY===null){I.lastY=pe,I.lastTime=W();return}const me=I.lastY,Me=I.lastTime??W(),Se=W();I.lastY=pe,I.lastTime=Se;const Pe=me-pe;if(Math.abs(Pe)<1)return;const q=Math.max(Se-Me,8),re=B+Math.min(H,Math.abs(Pe)/V),Ve=Pe*re,he=Ve/q;I.velocity=I.velocity*(1-oe)+he*oe,I.velocity>se?I.velocity=se:I.velocity<-se&&(I.velocity=-se),I.didMove&&(Q.preventDefault(),Q.stopPropagation()),z(Ve)},Ie=Q=>{const te=!I.didMove;I.lastY=null,I.lastTime=null;const pe=I.velocity;if(I.startX=null,I.startY=null,I.didMove=!1,te){const Se=Q.changedTouches?.[0];E(Se?.clientX,Se?.clientY);return}if(typeof window>"u")return;if(Math.abs(pe)<Y){I.velocity=0;return}let me=W();const Me=()=>{const Se=W(),Pe=Math.max(Se-me,8);me=Se;const q=z(I.velocity*Pe)??!1,re=Math.sign(I.velocity),Ve=Math.max(0,Math.abs(I.velocity)-le*Pe);if(I.velocity=Ve*re,!q||Ve<=Y){X(),I.velocity=0;return}I.rafId=window.requestAnimationFrame(Me)};I.rafId=window.requestAnimationFrame(Me)};L.addEventListener("touchstart",Re,fe),L.addEventListener("touchmove",be,fe),L.addEventListener("touchend",Ie,fe),L.addEventListener("touchcancel",Ie,fe);const U=L.style.touchAction;L.style.touchAction="manipulation",w.current=()=>{X(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),D.current=0,L.removeEventListener("touchstart",Re,fe),L.removeEventListener("touchmove",be,fe),L.removeEventListener("touchend",Ie,fe),L.removeEventListener("touchcancel",Ie,fe),L.style.touchAction=U}},[d,E,i]);return c.useEffect(()=>{let L=!1,G=null,B=null,H=[];const V=m.current;return V?(V.tabIndex=0,(async()=>{try{const se=await h0();if(L)return;const Y=p0(a,i,o,se),le=new hh(Y),I=new gh;G=le,p.current=le,g.current=I,le.loadAddon(I),le.open(V),A();const W=g0(V);W?(W.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=W,C()):f.current=null,_(),K(),le.focus(),H=[le.onData(F=>{b.current(F)})],B=new ResizeObserver(()=>{_()}),B.observe(V),typeof window<"u"&&window.setTimeout(()=>{_()},0)}catch{}})(),()=>{L=!0,w.current?.(),w.current=null,H.forEach(se=>se.dispose()),B?.disconnect(),G?.dispose(),p.current=null,g.current=null,f.current=null,j.current=null,R()}):void 0},[_,a,i,K,o,R]),c.useEffect(()=>{const L=p.current;L&&(L.reset(),R(),j.current=null,_(),L.focus())},[s,S,_,R]),c.useEffect(()=>(K(),()=>{w.current?.(),w.current=null}),[K,s]),c.useEffect(()=>{const L=p.current;if(!L)return;if(r.length===0){N.current!==null&&(L.reset(),R(),_());return}const G=N.current;let B;if(G===null)B=r;else{const H=r.findIndex(V=>V.id===G);B=H>=0?r.slice(H+1):r}B.length>0&&J(B.map(H=>H.data).join("")),N.current=r[r.length-1].id},[r,S,J,_,R]),c.useImperativeHandle(u,()=>({focus:()=>{if(d){E();return}p.current?.focus()},clear:()=>{const L=p.current;L&&(L.reset(),R(),_())},fit:()=>{_()}}),[d,E,_,R]),e.jsxs("div",{ref:m,className:T("relative h-full w-full terminal-viewport-container",l),style:{backgroundColor:o.background},onClick:L=>{d?E(L.clientX,L.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:M,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,"aria-hidden":"true",style:{position:"absolute",left:0,top:0,width:1,height:1,opacity:0,zIndex:1,background:"transparent",color:"transparent",caretColor:"transparent",resize:"none",overflow:"hidden",whiteSpace:"nowrap",border:"none",padding:0,margin:0,outline:"none"},onInput:L=>{const G=String(L.currentTarget.value||"");if(!G)return;const B=G.replace(/\r\n|\r|\n/g,"\r");b.current(B),L.currentTarget.value=""},onKeyDown:L=>{L.key==="Backspace"&&(L.currentTarget.value||b.current(""))}}):null,f.current&&!d?e.jsx(ll,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Li.displayName="TerminalViewport";const Nd=13,x0={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},No={ctrl:"5",cmd:"3"},y0={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},b0=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${No[r]}A`;case"arrow-down":return`\x1B[1;${No[r]}B`;case"arrow-right":return`\x1B[1;${No[r]}C`;case"arrow-left":return`\x1B[1;${No[r]}D`}return x0[s]??null},w0=()=>{const{terminal:s}=In(),{currentTheme:r}=nn(),{monoFont:t}=sf(),{isMobile:n,hasTouchInput:o}=Rt(),{currentSessionId:a,sessions:i,worktreeMetadata:l}=ue(),d=a?l.get(a)??void 0:void 0,u=c.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const te=i.find(me=>me.id===a),pe=typeof te?.directory=="string"?te.directory:null;return pe&&pe.length>0?pe:null},[a,i,d]),{currentDirectory:m,homeDirectory:f}=dt(),p=u||m||null,g=c.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),b=Sd(),h=b.sessions,j=b.setTerminalSession,y=b.setConnecting,x=b.appendToBuffer,v=b.clearTerminalSession,N=b.removeTerminalSession,w=b.clearBuffer,k=c.useMemo(()=>{if(p)return h.get(p)},[h,p]),D=k?.terminalSessionId??null,M=k?.bufferChunks??[],C=k?.bufferLength??0,S=k?.isConnecting??!1,A=D,[E,R]=c.useState(null),[_,P]=c.useState(!1),[O,J]=c.useState(null),[K,L]=c.useState(!1),G=c.useRef(null),B=c.useRef(null),H=c.useRef(A),V=c.useRef(p),oe=c.useRef(null),Y=$e(te=>te.activeMainTab)==="terminal";c.useEffect(()=>{H.current=A},[A]),c.useEffect(()=>{V.current=p},[p]),c.useEffect(()=>{!n&&O!==null&&J(null)},[n,O,J]),c.useEffect(()=>{!A&&O!==null&&J(null)},[A,O,J]);const le=c.useCallback(()=>{G.current?.(),G.current=null,B.current=null},[]);c.useEffect(()=>()=>{le(),H.current=null},[le]);const I=c.useCallback(te=>{if(B.current===te)return;le();const pe=s.connect(te,{onEvent:me=>{const Me=V.current;if(Me)switch(me.type){case"connected":{(me.runtime||me.ptyBackend)&&console.log(`[Terminal] connected runtime=${me.runtime??"unknown"} pty=${me.ptyBackend??"unknown"}`),y(Me,!1),R(null),P(!1),oe.current?.focus();break}case"reconnecting":{const Se=me.attempt??0,Pe=me.maxAttempts??3;R(`Reconnecting (${Se}/${Pe})...`),P(!1);break}case"data":{me.data&&x(Me,me.data);break}case"exit":{const Se=typeof me.exitCode=="number"?me.exitCode:null,Pe=typeof me.signal=="number"?me.signal:null;x(Me,`\r
101
- [Process exited${Se!==null?` with code ${Se}`:""}${Pe!==null?` (signal ${Pe})`:""}]\r
102
- `),v(Me),y(Me,!1),R("Terminal session ended"),P(!1),le();break}}},onError:(me,Me)=>{const Se=V.current;if(!Se)return;const Pe=Me?`Connection failed: ${me.message}`:me.message||"Terminal stream connection error";R(Pe),P(!!Me),Me&&(y(Se,!1),le(),N(Se))}},y0);G.current=()=>{pe.close(),B.current=null},B.current=te},[x,v,le,N,y,s,R]);c.useEffect(()=>{let te=!1;if(!p){R(a?"No working directory available for terminal.":"Select a session to open the terminal."),le();return}return(async()=>{const me=p;if(!V.current||V.current!==me)return;let Se=Sd.getState().getTerminalSession(me)?.terminalSessionId??null;if(!Se){R(null),P(!1),y(me,!0);try{const Pe=await s.createSession({cwd:me});if(te){try{await s.close(Pe.sessionId)}catch{}return}j(me,Pe),Se=Pe.sessionId}catch(Pe){te||(R(Pe instanceof Error?Pe.message:"Failed to start terminal session"),P(!0),y(me,!1));return}}!Se||te||(H.current=Se,I(Se))})(),()=>{te=!0,H.current=null,le()}},[a,p,A,N,y,j,I,le,s]);const W=c.useCallback(async()=>{if(!p||K)return;L(!0),R(null),P(!1),le();const te=H.current;try{if(s.restartSession&&te){const pe=await s.restartSession(te,{cwd:p});j(p,pe),H.current=pe.sessionId,I(pe.sessionId)}else{if(te)try{await s.close(te)}catch{}N(p)}}catch(pe){R(pe instanceof Error?pe.message:"Failed to restart terminal"),P(!0)}finally{L(!1)}},[p,K,le,s,j,I,N]),F=c.useCallback(async()=>{if(p&&!K){L(!0),R(null),P(!1),le();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}N(p),w(p),oe.current?.clear(),await new Promise(te=>setTimeout(te,100));try{y(p,!0);const te=await s.createSession({cwd:p});j(p,te),H.current=te.sessionId,I(te.sessionId)}catch(te){R(te instanceof Error?te.message:"Failed to create terminal"),P(!0),y(p,!1)}finally{L(!1)}}},[p,K,le,s,N,w,y,j,I]),$=c.useCallback(()=>{if(!p)return;w(p),oe.current?.clear(),oe.current?.focus();const te=H.current;te&&s.sendInput(te,"\f").catch(pe=>{R(pe instanceof Error?pe.message:"Failed to refresh prompt")})},[w,p,R,s]),z=c.useCallback(te=>{if(!te)return;let pe=te,me=!1;if(O&&te.length>0){const Se=te[0];if(Se.length===1&&/[a-zA-Z]/.test(Se)){const Pe=Se.toUpperCase();(O==="ctrl"||O==="cmd")&&(pe=String.fromCharCode(Pe.charCodeAt(0)&31),me=!0)}me||(me=!0)}const Me=H.current;Me&&(s.sendInput(Me,pe).catch(Se=>{R(Se instanceof Error?Se.message:"Failed to send input")}),me&&(J(null),oe.current?.focus()))},[O,J,s]),X=c.useCallback((te,pe)=>{const me=H.current;me&&s.resize({sessionId:me,cols:te,rows:pe}).catch(()=>{})},[s]),fe=c.useCallback(te=>{J(pe=>pe===te?null:te),oe.current?.focus()},[J]),ve=c.useCallback(te=>{const pe=b0(te,O);pe&&(z(pe),J(null),oe.current?.focus())},[O,z,J]);c.useEffect(()=>{if(!n||!O||!A)return;const te=pe=>{if(pe.repeat)return;const me=pe.key;if(!me||me==="Control"||me==="Meta"||me==="Alt"||me==="Shift")return;const Me=me.length===1?me.toLowerCase():me,Se=pe.code??"",Pe=Se.startsWith("Key")&&Se.length===4?Se.slice(3).toUpperCase():null,q=me.length===1&&/[a-zA-Z]/.test(me)?me.toUpperCase():Pe,re={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(Me in re){pe.preventDefault(),pe.stopPropagation(),ve(re[Me]);return}if(O==="ctrl"&&q&&q.length===1&&q>="A"&&q<="Z"){const Ve=String.fromCharCode(q.charCodeAt(0)&31);pe.preventDefault(),pe.stopPropagation(),z(Ve),J(null),oe.current?.focus()}};return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[O,ve,z,n,J,A]);const ge=c.useMemo(()=>{const te=Br[Bo].stack;if(typeof window>"u")return(Br[t]??Br[Bo]).stack;const me=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return me&&me.trim().length>0?me.trim():(Br[t]??Br[Bo]).stack??te},[t]),Re=c.useMemo(()=>f0(r),[r]),be=c.useMemo(()=>`${p??"no-dir"}::${A??"pending"}`,[p,A]);c.useEffect(()=>{if(!Y)return;const te=oe.current;if(!te)return;const pe=()=>{te.fit()};if(typeof window<"u"){const me=window.requestAnimationFrame(()=>{pe(),te.focus()}),Me=[220,400].map(Se=>window.setTimeout(pe,Se));return()=>{window.cancelAnimationFrame(me),Me.forEach(Se=>window.clearTimeout(Se))}}pe()},[Y,be,A]);const Ie=E?.includes("Reconnecting"),U=E?Ie?e.jsx(yh,{size:20,className:"text-amber-400"}):e.jsx(Wt,{size:20,className:"text-destructive"}):A&&!S&&!K?e.jsx(Ao,{size:20,className:"text-emerald-400"}):S||K?e.jsx(bi,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(bi,{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:W,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Q=!A||S||K;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:g})}),e.jsxs("div",{className:"flex items-center gap-2",children:[U,e.jsxs(Ne,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:$,disabled:!C,title:"Clear output",type:"button",children:[e.jsx(qs,{size:16}),"Clear"]}),e.jsxs(Ne,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:W,disabled:K,title:"Restart terminal session",type:"button",children:[e.jsx(Ps,{size:16,className:T((S||K)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>ve("esc"),disabled:Q,children:"Esc"}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ve("tab"),disabled:Q,children:[e.jsx(Ol,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:O==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>fe("ctrl"),disabled:Q,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:O==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>fe("cmd"),disabled:Q,children:[e.jsx(Zr,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ve("arrow-up"),disabled:Q,children:[e.jsx(so,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ve("arrow-left"),disabled:Q,children:[e.jsx(pu,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ve("arrow-down"),disabled:Q,children:[e.jsx(An,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ve("arrow-right"),disabled:Q,children:[e.jsx(Ol,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>ve("enter"),disabled:Q,children:[e.jsx(Kn,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Re.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:Y?n?e.jsx(Li,{ref:te=>{oe.current=te},sessionKey:be,chunks:M,onInput:z,onResize:X,theme:Re,fontFamily:ge,fontSize:Nd,enableTouchScroll:o},be):e.jsx(mt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Li,{ref:te=>{oe.current=te},sessionKey:be,chunks:M,onInput:z,onResize:X,theme:Re,fontFamily:ge,fontSize:Nd,enableTouchScroll:o},be)}):null}),E&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:E}),_&&e.jsx(Ne,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:F,disabled:K,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},nf=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Ui},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:ar},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:Zr},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:mu},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:Yn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:$t},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:qr}],v0={},j0={},S0={};nf.forEach(s=>{v0[s.id]=s.label,j0[s.id]=s.description,S0[s.id]=s});const k0=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",N0=s=>{if(!Array.isArray(s))return[];const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},Cd=s=>{const r=N0(s);if(r.length===0)return;const t={};for(const i of r)i.permission&&((t[i.permission]||={})[i.pattern]=i.action);const n=t["*"]?.["*"],o=Object.keys(t);if(o.length===1&&o[0]==="*"&&Object.keys(t["*"]||{}).length===1&&t["*"]?.["*"])return t["*"]["*"];const a={};for(const i of o){const l=t[i],d=Object.keys(l);if(d.length===1&&d[0]==="*"&&i!=="*"){const u=l["*"],m=k0(i);if(n){if(u===n)continue}else if(u===m)continue;a[i]=u}else i==="*"&&d.length===1&&d[0]==="*"?a[i]=l["*"]:a[i]=l}return Object.keys(a).length>0?a:void 0},C0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedAgentName:a,agents:i,setSelectedAgent:l,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=Fr(),{setSidebarOpen:p}=$e(),{isMobile:g}=Rt(),[b,h]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const y=b?"bg-transparent":j?"bg-background":"bg-sidebar",x=()=>{const E="new-agent";let R=E,_=1;for(;i.some(P=>P.name===R);)R=`${E}-${_}`,_++;d({name:R,scope:"user"}),l(R),s?.(),g&&p(!1)},v=async E=>{if(zr(E)){ne.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${E.name}"?`)&&(await m(E.name)?ne.success(`Agent "${E.name}" deleted successfully`):ne.error("Failed to delete agent"))},N=async E=>{zr(E)&&window.confirm(`Are you sure you want to reset agent "${E.name}" to its default configuration?`)&&(await m(E.name)?ne.success(`Agent "${E.name}" reset to default`):ne.error("Failed to reset agent"))},w=E=>{const R=E.name;let _=1,P=`${R}-copy`;for(;i.some(L=>L.name===P);)_++,P=`${R}-copy-${_}`;const O=E,J=E.model?.providerID&&E.model?.modelID?`${E.model.providerID}/${E.model.modelID}`:null,K=E;d({name:P,scope:O.scope||"user",description:E.description,model:J,temperature:E.temperature,top_p:E.topP,prompt:E.prompt,mode:E.mode,permission:Cd(E.permission),disable:K.disable}),l(P),g&&p(!1)},k=E=>{o(E.name),t(E)},D=async()=>{if(!r)return;const E=n.trim().replace(/\s+/g,"-");if(!E){ne.error("Agent name is required");return}if(E===r.name){t(null);return}if(i.some(O=>O.name===E)){ne.error("An agent with this name already exists");return}const R=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,_=r;await u({name:E,description:r.description,model:R,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:Cd(r.permission),disable:_.disable,scope:_.scope})?await m(r.name)?(ne.success(`Agent renamed to "${E}"`),l(E)):ne.error("Failed to remove old agent after rename"):ne.error("Failed to rename agent"),t(null)},M=E=>{switch(E){case"primary":return e.jsx(Qr,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(gu,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(hu,{className:"h-3 w-3 text-primary"});default:return null}},C=i.filter(E=>!Tu(E)),S=C.filter(zr),A=C.filter(E=>!zr(E));return e.jsxs("div",{className:T("flex h-full flex-col",y),children:[e.jsx("div",{className:T("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",C.length]}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:x,children:e.jsx(qt,{className:"size-4"})})]})}),e.jsx(mt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:C.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Qn,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),S.map(E=>e.jsx(Md,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),s?.(),g&&p(!1)},onReset:()=>N(E),onDuplicate:()=>w(E),getAgentModeIcon:M},E.name))]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Agents"}),A.map(E=>e.jsx(Md,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),s?.(),g&&p(!1)},onRename:()=>k(E),onDelete:()=>v(E),onDuplicate:()=>w(E),getAgentModeIcon:M},E.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:E=>!E&&t(null),children:e.jsxs(fs,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Agent"}),e.jsxs(Ns,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(ht,{value:n,onChange:E=>o(E.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:E=>{E.key==="Enter"&&D()}}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Jr,{onClick:D,children:"Rename"})]})]})})]})},Md=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i,getAgentModeIcon:l})=>{const d=s;return e.jsx("div",{className:T("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s.name}),l(s.mode),(d.scope||zr(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:zr(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{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(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(ro,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:u=>{u.stopPropagation(),i()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Ps,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(kt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Bs({className:s,variant:r,...t}){return e.jsx(Ne,{variant:r,size:"sm",className:T("h-6 px-2 text-xs",s),...t})}const M0=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),D0=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=M0.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Cl=({providerId:s,modelId:r,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=st(),i=$e(B=>B.isMobile),{toggleFavoriteModel:l,isFavoriteModel:d,addRecentModel:u}=$e(),{favoriteModelsList:m,recentModelsList:f}=vl(),{isMobile:p}=Rt(),g=i||p,[b,h]=c.useState(!1),[j,y]=c.useState(new Set),[x,v]=c.useState(!1),[N,w]=c.useState(""),[k,D]=c.useState(0),M=c.useRef([]),C=()=>h(!1),S=B=>{y(H=>{const V=new Set(H);return V.has(B)?V.delete(B):V.add(B),V})};c.useEffect(()=>{x||(w(""),D(0))},[x]),c.useEffect(()=>{D(0)},[N]);const A=B=>{const H=B?.name||B?.id||"",V=String(H);return V.length>40?V.substring(0,37)+"...":V},E=(B,H)=>{const V=`${B}/${H}`;return a.get(V)},R=(B,H)=>{t(B,H),B&&H&&u(B,H),v(!1)},_=(B,H)=>{if(!N.trim())return!0;const V=N.toLowerCase();return B.toLowerCase().includes(V)||H.toLowerCase().includes(V)},P=(B,H,V,oe,se,Y)=>{const le=E(H,V),I=D0(le?.limit?.context),W=s===H&&r===V,F=d(H,V);return e.jsxs("div",{ref:$=>{M.current[se]=$},className:T("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Y?"bg-accent":"hover:bg-accent/50"),onClick:()=>R(H,V),onMouseEnter:()=>D(se),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:A(B)}),I?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:I}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[W&&e.jsx(Tt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),l(H,V)},className:T("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",F?"text-yellow-500":"text-muted-foreground"),"aria-label":F?"Unfavorite":"Favorite",title:F?"Remove from favorites":"Add to favorites",children:F?e.jsx(fr,{className:"h-3.5 w-3.5"}):e.jsx(xn,{className:"h-3.5 w-3.5"})})]})]},`${oe}-${H}-${V}`)},O=m.filter(({model:B,providerID:H})=>{const oe=o.find(Y=>Y.id===H)?.name||H,se=A(B);return _(se,oe)}),J=f.filter(({model:B,providerID:H})=>{const oe=o.find(Y=>Y.id===H)?.name||H,se=A(B);return _(se,oe)}),K=o.map(B=>{const V=(Array.isArray(B.models)?B.models:[]).filter(oe=>{const se=A(oe);return _(se,B.name||B.id||"")});return{...B,models:V}}).filter(B=>B.models.length>0),L=O.length>0||J.length>0||K.length>0,G=()=>g?e.jsx(ws,{open:b,onClose:C,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:B,providerID:H,modelID:V})=>{const oe=H===s&&V===r;return e.jsxs("div",{className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",oe?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(H,V),C()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{providerId:H,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(B)})]})}),e.jsx("button",{onClick:se=>{se.preventDefault(),se.stopPropagation(),l(H,V)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-yellow-500 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(fr,{className:"h-4 w-4"})})]},`fav-mobile-${H}-${V}`)})})]}),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:B,providerID:H,modelID:V})=>{const oe=H===s&&V===r;return e.jsxs("div",{className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",oe?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(H,V),C()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{providerId:H,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(B)})]})}),e.jsx("button",{onClick:se=>{se.preventDefault(),se.stopPropagation(),l(H,V)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Favorite",children:e.jsx(xn,{className:"h-4 w-4"})})]},`recent-mobile-${H}-${V}`)})})]}),o.map(B=>{const H=Array.isArray(B.models)?B.models:[];if(H.length===0)return null;const V=B.id===s,oe=j.has(B.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:()=>S(B.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{providerId:B.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:B.name}),V&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),oe?e.jsx(Et,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Us,{className:"h-3 w-3 text-muted-foreground"})]}),oe&&e.jsx("div",{className:"border-t border-border/20",children:H.map(se=>{const Y=B.id===s&&se.id===r;return e.jsxs("div",{className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",Y?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(B.id,se.id),C()},children:e.jsx("span",{className:"font-medium truncate",children:A(se)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:le=>{le.preventDefault(),le.stopPropagation(),l(B.id,se.id)},className:T("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(B.id,se.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(B.id,se.id)?"Unfavorite":"Favorite",children:d(B.id,se.id)?e.jsx(fr,{className:"h-4 w-4"}):e.jsx(xn,{className:"h-4 w-4"})}),Y&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},se.id)})})]},B.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{R("",""),C()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[g?e.jsxs("button",{type:"button",onClick:()=>h(!0),className:T("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(ns,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(mr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s&&r?`${s}/${r}`:"Select model..."})]}),e.jsx(Et,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Ut,{open:x,onOpenChange:v,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:T("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(ns,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(mr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(mr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s&&r?`${s}/${r}`:"Not selected"}),e.jsx(Et,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Gt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const B=[];O.forEach(({model:se,providerID:Y,modelID:le})=>{B.push({model:se,providerID:Y,modelID:le,section:"fav"})}),J.forEach(({model:se,providerID:Y,modelID:le})=>{B.push({model:se,providerID:Y,modelID:le,section:"recent"})}),K.forEach(se=>{se.models.forEach(Y=>{B.push({model:Y,providerID:se.id,modelID:Y.id,section:"provider"})})});const H=B.length,V=se=>{if(se.key==="ArrowDown"){se.preventDefault(),se.stopPropagation();const Y=(k+1)%Math.max(1,H);D(Y),setTimeout(()=>{M.current[Y]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(se.key==="ArrowUp"){se.preventDefault(),se.stopPropagation();const Y=(k-1+Math.max(1,H))%Math.max(1,H);D(Y),setTimeout(()=>{M.current[Y]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(se.key==="Enter"){se.preventDefault(),se.stopPropagation();const Y=B[k];Y&&R(Y.providerID,Y.modelID)}else se.key==="Escape"&&(se.preventDefault(),se.stopPropagation(),v(!1))};let oe=0;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{type:"text",placeholder:"Search models",value:N,onChange:se=>w(se.target.value),onKeyDown:V,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(mt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:T("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>R("",""),children:[e.jsx(Wt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!s&&!r&&e.jsx(Tt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ms,{}),!L&&N&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),O.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),O.map(({model:se,providerID:Y,modelID:le})=>{const I=oe++;return P(se,Y,le,"fav",I,k===I)})]}),J.length>0&&e.jsxs(e.Fragment,{children:[O.length>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),J.map(({model:se,providerID:Y,modelID:le})=>{const I=oe++;return P(se,Y,le,"recent",I,k===I)})]}),(O.length>0||J.length>0)&&K.length>0&&e.jsx(Ms,{}),K.map((se,Y)=>e.jsxs(c.Fragment,{children:[Y>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(ns,{providerId:se.id,className:"h-4 w-4 flex-shrink-0"}),se.name]}),se.models.map(le=>{const I=oe++;return P(le,se.id,le.id,"provider",I,k===I)})]},se.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"})]})})()})]}),G()]})},A0=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],xr=s=>s==="allow"||s==="ask"||s==="deny",E0=s=>{if(xr(s))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const r=s["*"];if(xr(r))return r}},I0=s=>{if(xr(s))return{entries:{"*":s}};if(!s||typeof s!="object"||Array.isArray(s))return{entries:{}};const r={};for(const[t,n]of Object.entries(s)){const o=E0(n);o!==void 0&&(r[t]=o)}return{entries:r}},P0=s=>{const r={...s},t=r["*"];return xr(t)?(delete r["*"],{defaultOverride:t,overrides:r}):{defaultOverride:"default",overrides:r}},wa=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",zo=(s,r)=>r==="default"?wa(s):r,Dd=(s,r)=>{const t={...s};for(const[n,o]of Object.entries(s)){if(n==="*")continue;const a=zo(n,r),i=wa(n);if(!(xr(o)&&o!==i)){if(xr(o)&&o===a){delete t[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const l=o,d=Object.keys(l),u=l["*"];if(u!==void 0&&u!==i)continue;d.length===1&&d[0]==="*"&&u===a&&delete t[n]}}}return t},of=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},T0=s=>{const r=of(s);if(!r||r.length===0)return{entries:{}};const t={};for(const a of r)!a.permission||a.permission==="invalid"||a.pattern==="*"&&(t[a.permission]=a.action);const n=t["*"],o={};for(const[a,i]of Object.entries(t)){if(a==="*"){o[a]=i;continue}const l=wa(a);if(n){if(i===n)continue}else if(i===l)continue;o[a]=i}return{entries:o}},F0=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:i}=Fr();st();const l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[g,b]=c.useState(""),[h,j]=c.useState("subagent"),[y,x]=c.useState(""),[v,N]=c.useState(void 0),[w,k]=c.useState(void 0),[D,M]=c.useState(""),[C,S]=c.useState("default"),[A,E]=c.useState({}),[R,_]=c.useState(""),[P,O]=c.useState(!1),J=dt($=>$.currentDirectory??null),[K,L]=c.useState([]),G=eo($=>$.permissions);c.useEffect(()=>{let $=!1;return(async()=>{const X=await ke.listToolIds({directory:J});if($)return;const fe=new Set(["write","patch","multiedit"]),ve=X.map(ge=>typeof ge=="string"?ge.trim():"").filter(Boolean).filter(ge=>ge!=="*").filter(ge=>ge!=="invalid").filter(ge=>!fe.has(ge));L(Array.from(new Set(ve)).sort((ge,Re)=>ge.localeCompare(Re)))})(),()=>{$=!0}},[J]);const B=c.useMemo(()=>{const $=new Set;for(const z of o){const X=of(z.permission);if(X)for(const fe of X)fe.permission&&fe.permission!=="*"&&fe.permission!=="invalid"&&$.add(fe.permission)}for(const z of G.values())for(const X of z){const fe=X.permission?.trim();fe&&fe!=="invalid"&&$.add(fe)}for(const z of K)$.add(z);return Array.from($).sort((z,X)=>z.localeCompare(X))},[o,G,K]),H=c.useCallback($=>{const z=A[$];if(xr(z))return z;if(z&&typeof z=="object"&&!Array.isArray(z)){const X=z["*"];if(xr(X))return X}},[A]),V=c.useCallback($=>{const z=A[$];return!z||typeof z!="object"||Array.isArray(z)?0:Object.keys(z).filter(fe=>fe!=="*").length},[A]),oe=c.useCallback(($,z)=>{$!=="*"&&E(X=>{const fe={...X},ve=fe[$],ge=zo($,C),Re=wa($),be=z===ge&&z===Re;if(ve&&typeof ve=="object"&&!Array.isArray(ve)){const Ie={...ve};Ie["*"]=z;const U=Object.keys(Ie).filter(Q=>Q!=="*");return be&&U.length===0?(delete fe[$],fe):(fe[$]=Ie,fe)}return be?(delete fe[$],fe):(fe[$]=z,fe)})},[C]),se=c.useCallback($=>{E(z=>{if(!($ in z))return z;const X={...z};return delete X[$],X})},[]),Y=c.useMemo(()=>{const $=Object.entries(A).filter(([z])=>z!=="*");return $.sort(([z],[X])=>z.localeCompare(X)),$},[A]),le=c.useMemo(()=>{const $=new Set;for(const z of A0)$.add(z);for(const z of B)$.add(z);for(const z of Object.keys(A))$.delete(z);return Array.from($).sort((z,X)=>z.localeCompare(X))},[B,A]),I=c.useCallback($=>{const z=R.trim();if(!z)return;const X=zo(z,C);if($===X){const fe=C==="default"?"OpenCode defaults":`Default Permissions ("${C}")`;ne.message(`"${z}" already matches ${fe} (${X}).`),_("");return}oe(z,$),_("")},[R,oe,C]),W=c.useCallback($=>$==="webfetch"?"WebFetch":$==="websearch"?"WebSearch":$==="codesearch"?"CodeSearch":$==="doom_loop"?"Doom Loop":$==="external_directory"?"External Directory":$==="todowrite"?"TodoWrite":$==="todoread"?"TodoRead":$.split(/[_-]+/g).filter(Boolean).map(z=>z.charAt(0).toUpperCase()+z.slice(1)).join(" "),[]);c.useEffect(()=>{_("");const $=z=>{const X=P0(z);S(X.defaultOverride),E(Dd(X.overrides,X.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),b(a.description||""),j(a.mode||"subagent"),x(a.model||""),N(a.temperature),k(a.top_p),M(a.prompt||"");const z=I0(a.permission);$(z.entries);return}if(l&&s===l.name){b(l.description||""),j(l.mode||"subagent"),l.model?.providerID&&l.model?.modelID?x(`${l.model.providerID}/${l.model.modelID}`):x(""),N(l.temperature),k(l.topP),M(l.prompt||"");const z=T0(l.permission);$(z.entries)}},[a,d,l,s]);const F=async()=>{const $=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!$){ne.error("Agent name is required");return}if(d&&o.some(z=>z.name===$)){ne.error("An agent with this name already exists");return}O(!0);try{const z=y.trim(),X={name:$,description:g.trim()||void 0,mode:h,model:z===""?null:z,temperature:v,top_p:w,prompt:D.trim()||void 0,permission:(()=>{const ve=Dd(A,C),ge=C==="default"?ve:{"*":C,...ve},Re=["doom_loop","external_directory"];for(const Ie of Re)if(!(Ie in ge)){const U=A[Ie];xr(U)?ge[Ie]=U:ge[Ie]=zo(Ie,C)}return Object.keys(ge).length===0?d?void 0:null:ge})(),scope:d?f:void 0};let fe;d?(fe=await t(X),fe&&i(null)):fe=await n($,X),fe?ne.success(d?"Agent created successfully":"Agent updated successfully"):ne.error(d?"Failed to create agent":"Failed to update agent")}catch(z){console.error("Error saving agent:",z);const X=z instanceof Error&&z.message?z.message:"An error occurred while saving";ne.error(X)}finally{O(!1)}};return s?e.jsx(mt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Agent":s})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"@"}),e.jsx(ht,{value:u,onChange:$=>m($.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(vs,{value:f,onValueChange:$=>p($),children:[e.jsxs(js,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Ss,{align:"end",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Ts,{value:g,onChange:$=>b($.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(Bs,{variant:h==="primary"?"default":"outline",onClick:()=>j("primary"),className:T("gap-2",h==="primary"?void 0:"text-foreground"),children:[e.jsx(Qr,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Bs,{variant:h==="subagent"?"default":"outline",onClick:()=>j("subagent"),className:T("gap-2",h==="subagent"?void 0:"text-foreground"),children:[e.jsx(hu,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Bs,{variant:h==="all"?"default":"outline",onClick:()=>j("all"),className:T("gap-2",h==="all"?void 0:"text-foreground"),children:[e.jsx(gu,{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(Cl,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:($,z)=>{x($&&z?`${$}/${z}`:"")}})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Temperature",e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{sideOffset:8,className:"max-w-xs",children:["Controls randomness in responses.",e.jsx("br",{}),"Higher values make output more creative and unpredictable,",e.jsx("br",{}),"lower values make it more focused and deterministic."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const z=Math.max(0,(v!==void 0?v:.7)-.1);N(parseFloat(z.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx(ht,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:$=>{const z=$.target.value;if(z===""){N(void 0);return}const X=parseFloat(z);!isNaN(X)&&X>=0&&X<=2&&N(X)},onBlur:$=>{const z=$.target.value;if(z!==""){const X=parseFloat(z);if(!isNaN(X)){const fe=Math.max(0,Math.min(2,X));N(parseFloat(fe.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const z=Math.min(2,(v!==void 0?v:.7)+.1);N(parseFloat(z.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(qt,{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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{sideOffset:8,className:"max-w-xs",children:["Controls diversity via nucleus sampling.",e.jsx("br",{}),"Lower values focus on most likely tokens,",e.jsx("br",{}),"higher values consider more possibilities."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const z=Math.max(0,(w!==void 0?w:.9)-.1);k(parseFloat(z.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx(ht,{type:"text",inputMode:"decimal",value:w!==void 0?w:"",onChange:$=>{const z=$.target.value;if(z===""){k(void 0);return}const X=parseFloat(z);!isNaN(X)&&X>=0&&X<=1&&k(X)},onBlur:$=>{const z=$.target.value;if(z!==""){const X=parseFloat(z);if(!isNaN(X)){const fe=Math.max(0,Math.min(1,X));k(parseFloat(fe.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const z=Math.min(1,(w!==void 0?w:.9)+.1);k(parseFloat(z.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(qt,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"System Prompt"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Override the default system prompt for this agent"})]}),e.jsx(Ts,{value:D,onChange:$=>M($.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Tool Access"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"OpenCode v1.1.1+ configures tool access via the permissions below."})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:'This editor only updates wildcard ("*") rules; existing pattern rules are preserved.'})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Set the default behavior for all permissions for this agent."}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ne,{size:"sm",variant:C==="default"?"default":"outline",onClick:()=>S("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(Ne,{size:"sm",variant:C==="allow"?"default":"outline",onClick:()=>S("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:C==="ask"?"default":"outline",onClick:()=>S("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:C==="deny"?"default":"outline",onClick:()=>S("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:C==="default"?"Uses OpenCode defaults unless overridden below.":"Applies to any permission without an explicit override below."}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Default:"})," Follow OpenCode default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block the operation"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Overrides"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Add overrides for permissions that should behave differently for this agent."}),e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(vs,{value:R,onValueChange:_,children:[e.jsx(js,{className:"h-8 w-full sm:w-72",children:R?e.jsx("span",{className:"truncate",children:W(R)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(Ss,{children:le.map($=>e.jsx(Bt,{value:$,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:W($)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:$})]})},$))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ne,{size:"sm",variant:"outline",disabled:!R,onClick:()=>I("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:"outline",disabled:!R,onClick:()=>I("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:"outline",disabled:!R,onClick:()=>I("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),Y.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:C==="default"?"No overrides configured. Everything follows OpenCode defaults.":`No overrides configured. All permissions default to "${C}" for this agent.`}):e.jsx("div",{className:"space-y-4",children:Y.map(([$])=>{const z=H($),X=V($),fe=W($);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:[e.jsx("span",{children:fe}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:$}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block this operation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Remove:"})," Return to default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Note:"}),' Buttons set the "*" rule only']}),X>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",X," pattern rules preserved"]}):null]})})]})]}),e.jsxs(Ne,{size:"sm",variant:"outline",onClick:()=>se($),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ne,{size:"sm",variant:z==="allow"?"default":"outline",onClick:()=>oe($,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:z==="ask"?"default":"outline",onClick:()=>oe($,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:z==="deny"?"default":"outline",onClick:()=>oe($,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},$)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:F,disabled:P,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(da,{className:"h-3 w-3"}),P?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Qn,{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"})]})})},R0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedCommandName:a,commands:i,setSelectedCommand:l,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=Tr(),{setSidebarOpen:p}=$e(),{isMobile:g}=Rt(),[b,h]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const y=b?"bg-transparent":j?"bg-background":"bg-sidebar",x=()=>{const S="new-command";let A=S,E=1;for(;i.some(R=>R.name===A);)A=`${S}-${E}`,E++;d({name:A,scope:"user"}),l(A),s?.(),g&&p(!1)},v=async S=>{if(pn(S)){ne.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${S.name}"?`)&&(await m(S.name)?ne.success(`Command "${S.name}" deleted successfully`):ne.error("Failed to delete command"))},N=async S=>{pn(S)&&window.confirm(`Are you sure you want to reset command "${S.name}" to its default configuration?`)&&(await m(S.name)?ne.success(`Command "${S.name}" reset to default`):ne.error("Failed to reset command"))},w=S=>{const A=S.name;let E=1,R=`${A}-copy`;for(;i.some(_=>_.name===R);)E++,R=`${A}-copy-${E}`;d({name:R,scope:S.scope||"user",description:S.description,template:S.template,agent:S.agent,model:S.model,subtask:S.subtask}),l(R),g&&p(!1)},k=S=>{o(S.name),t(S)},D=async()=>{if(!r)return;const S=n.trim().replace(/\s+/g,"-");if(!S){ne.error("Command name is required");return}if(S===r.name){t(null);return}if(i.some(E=>E.name===S)){ne.error("A command with this name already exists");return}await u({name:S,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(ne.success(`Command renamed to "${S}"`),l(S)):ne.error("Failed to remove old command after rename"):ne.error("Failed to rename command"),t(null)},M=i.filter(pn),C=i.filter(S=>!pn(S));return e.jsxs("div",{className:T("flex h-full flex-col",y),children:[e.jsx("div",{className:T("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",i.length]}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:x,children:e.jsx(qt,{className:"size-4"})})]})}),e.jsx(mt,{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(Er,{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:[M.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"}),[...M].sort((S,A)=>S.name.localeCompare(A.name)).map(S=>e.jsx(Ad,{command:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),g&&p(!1)},onReset:()=>N(S),onDuplicate:()=>w(S)},S.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 Commands"}),[...C].sort((S,A)=>S.name.localeCompare(A.name)).map(S=>e.jsx(Ad,{command:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),g&&p(!1)},onRename:()=>k(S),onDelete:()=>v(S),onDuplicate:()=>w(S)},S.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:S=>!S&&t(null),children:e.jsxs(fs,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Command"}),e.jsxs(Ns,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(ht,{value:n,onChange:S=>o(S.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&D()}}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Jr,{onClick:D,children:"Rename"})]})]})})]})},Ad=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i})=>e.jsx("div",{className:T("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||pn(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:pn(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{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(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(kt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(ro,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:l=>{l.stopPropagation(),i()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(kt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(Ps,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(kt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),af=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=Fr(),a=o(),i=$e(b=>b.isMobile),{isMobile:l}=Rt(),d=i||l,[u,m]=c.useState(!1);c.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=b=>{r(b)},g=()=>d?e.jsx(ws,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(b=>{const h=b.name===s;return e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",h?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(b.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:b.name}),b.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:b.description})]}),h&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},b.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:T("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(Qn,{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(Et,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:T("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(Qn,{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(Et,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Gt,{className:"max-w-[300px]",children:[a.map(b=>e.jsx(kt,{className:"typography-meta",onSelect:()=>p(b.name),children:e.jsx("span",{className:"font-medium",children:b.name})},b.name)),e.jsx(kt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),g()]})},_0=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:i}=Tr(),l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[g,b]=c.useState(""),[h,j]=c.useState(""),[y,x]=c.useState(""),[v,N]=c.useState(""),[w,k]=c.useState(!1),[D,M]=c.useState(!1);c.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),b(a.description||""),j(a.agent||""),x(a.model||""),N(a.template||""),k(a.subtask||!1)):l&&(b(l.description||""),j(l.agent||""),x(l.model||""),N(l.template||""),k(l.subtask||!1))},[l,d,s,o,a]);const C=async()=>{const S=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!S){ne.error("Command name is required");return}if(!v.trim()){ne.error("Command template is required");return}if(d&&o.some(A=>A.name===S)){ne.error("A command with this name already exists");return}M(!0);try{const A=h.trim(),E=y.trim(),R=v.trim(),_={name:S,description:g.trim()||void 0,agent:A===""?null:A,model:E===""?null:E,template:R,subtask:w,scope:d?f:void 0};let P;d?(P=await t(_),P&&i(null)):P=await n(S,_),P?ne.success(d?"Command created successfully":"Command updated successfully"):ne.error(d?"Failed to create command":"Failed to update command")}catch(A){console.error("Error saving command:",A),ne.error("An error occurred while saving")}finally{M(!1)}};return s?e.jsx(mt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Command":`/${s}`})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"/"}),e.jsx(ht,{value:u,onChange:S=>m(S.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(vs,{value:f,onValueChange:S=>p(S),children:[e.jsxs(js,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Ss,{align:"end",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Ts,{value:g,onChange:S=>b(S.target.value),placeholder:"What does this command do?",rows:3})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model & Agent Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and agent for command execution"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(af,{agentName:h,onChange:S=>j(S)}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Agent to execute this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(Cl,{providerId:y?y.split("/")[0]:"",modelId:y?y.split("/")[1]:"",onChange:(S,A)=>{x(S&&A?`${S}/${A}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:w,onChange:S=>k(S.target.checked),className:"sr-only"}),e.jsx("div",{className:T("w-5 h-5 rounded border-2 flex items-center justify-center",w?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:w&&e.jsx(Tt,{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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{sideOffset:8,className:"max-w-xs",children:["When enabled, this command will always execute in a subagent context,",e.jsx("br",{}),"even if triggered from main agent.",e.jsx("br",{}),"Useful for isolating command logic and maintaining clean separation of concerns."]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Command Template"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Define the prompt template for this command. Use $ARGUMENTS for user input."})]}),e.jsx(Ts,{value:v,onChange:S=>N(S.target.value),placeholder:`Your command template here...
103
-
104
- Use $ARGUMENTS to reference user input.
105
- Use !\`shell command\` to inject shell output.
106
- Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(Ne,{size:"sm",variant:"default",onClick:C,disabled:D,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(da,{className:"h-3 w-3"}),D?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Er,{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"})]})})},O0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedSkillName:a,skills:i,setSelectedSkill:l,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=Hs(),{setSidebarOpen:g}=$e(),{isMobile:b}=Rt(),[h,j]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const x=h?"bg-transparent":y?"bg-background":"bg-sidebar",v=()=>{const S="new-skill";let A=S,E=1;for(;i.some(R=>R.name===A);)A=`${S}-${E}`,E++;d({name:A,scope:"user",description:""}),l(A),s?.(),b&&g(!1)},N=async S=>{window.confirm(`Are you sure you want to delete skill "${S.name}"?`)&&(await m(S.name)?ne.success(`Skill "${S.name}" deleted successfully`):ne.error("Failed to delete skill"))},w=async S=>{const A=S.name;let E=1,R=`${A}-copy`;for(;i.some(P=>P.name===R);)E++,R=`${A}-copy-${E}`;const _=await p(S.name);if(!_){ne.error("Failed to load skill details for duplication");return}d({name:R,scope:S.scope||"user",description:(_.sources.md.fields.includes("description"),""),instructions:""}),l(R),b&&g(!1)},k=S=>{o(S.name),t(S)},D=async()=>{if(!r)return;const S=n.trim().replace(/\s+/g,"-").toLowerCase();if(!S){ne.error("Skill name is required");return}if(S===r.name){t(null);return}if(i.some(R=>R.name===S)){ne.error("A skill with this name already exists");return}if(!await p(r.name)){ne.error("Failed to load skill details"),t(null);return}await u({name:S,description:"Renamed skill",scope:r.scope})?await m(r.name)?(ne.success(`Skill renamed to "${S}"`),l(S)):ne.error("Failed to remove old skill after rename"):ne.error("Failed to rename skill"),t(null)},M=i.filter(S=>S.scope==="project"),C=i.filter(S=>S.scope==="user");return e.jsxs("div",{className:T("flex h-full flex-col",x),children:[e.jsx("div",{className:T("border-b px-3",b?"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(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(qt,{className:"size-4"})})]})}),e.jsx(mt,{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(xu,{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:[M.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"}),M.map(S=>e.jsx(Ed,{skill:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),b&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>w(S)},S.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:"User Skills"}),C.map(S=>e.jsx(Ed,{skill:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),b&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>w(S)},S.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:S=>!S&&t(null),children:e.jsxs(fs,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Skill"}),e.jsxs(Ns,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(ht,{value:n,onChange:S=>o(S.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&D()}}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Jr,{onClick:D,children:"Rename"})]})]})})]})},Ed=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:T("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(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{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(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(kt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(ro,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(kt,{onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(kt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function lf({tabs:s,value:r,onValueChange:t,className:n,isInteractive:o=!0,animate:a=!0}){const i=c.useRef(null),l=c.useRef(null),d=c.useCallback(()=>{const u=i.current,m=l.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:g}=m,b=Math.max(0,Math.min(100,p/f*100)),h=Math.max(0,Math.min(100,(p+g)/f*100));u.style.clipPath=`inset(0 ${Number(100-h).toFixed(2)}% 0 ${Number(b).toFixed(2)}% round 8px)`},[]);return c.useLayoutEffect(()=>{d()},[d,r,s.length]),c.useEffect(()=>{const u=i.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:T("relative isolate w-full",n),children:[e.jsx("div",{ref:i,"aria-hidden":!0,className:T("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children:s.map(u=>{const m=u.icon;return e.jsxs("div",{className:"flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold",children:[m?e.jsx(m,{className:"h-4 w-4"}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})}),e.jsx("div",{className:"relative z-20 flex h-9 items-center gap-1 rounded-lg bg-muted/20 px-1.5",children:s.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?l:null,type:"button",onClick:()=>{o&&t(u.value)},className:T("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:T("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const $0=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,L0=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},B0=async()=>{try{if(as())return await En();const s=tn()?.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}},z0=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=no(),[a,i]=c.useState(""),[l,d]=c.useState(""),[u,m]=c.useState(""),[f,p]=c.useState([]),[g,b]=c.useState(null),[h,j]=c.useState(!1),[y,x]=c.useState([]),[v,N]=c.useState(null);c.useEffect(()=>{s&&(i(""),d(""),m(""),b(null),j(!1),x([]),N(null),(async()=>{const M=await B0(),C=Array.isArray(M?.skillCatalogs)?M?.skillCatalogs:[];p(C||[])})())},[s]);const w=c.useMemo(()=>{const M=l.trim(),C=u.trim();return f.some(S=>{const A=(S.source||"").trim(),E=(S.subpath||"").trim();return A===M&&E===C})},[f,l,u]),k=async()=>{const M=l.trim();if(!M){ne.error("Repository source is required");return}a.trim()||i(L0(M)),j(!1),b(null);const C=await t({source:M,subpath:u.trim()||void 0,gitIdentityId:v||void 0});if(!C.ok){if(C.error?.kind==="authRequired"){if(Ht()){ne.error("Private repositories are not supported in VS Code yet");return}const A=C.error.identities||[];x(A),!v&&A.length>0&&N(A[0].id),ne.error("Authentication required. Select a Git identity and scan again.");return}ne.error(C.error?.message||"Failed to scan repository");return}const S=C.items?.length||0;if(b(S),S===0){ne.error("No skills found in this repository"),j(!1);return}x([]),j(!0),ne.success(`Found ${S} skill(s)`)},D=async()=>{const M=a.trim(),C=l.trim(),S=u.trim();if(!M){ne.error("Catalog name is required");return}if(!C){ne.error("Repository source is required");return}if(!h){ne.error("Scan the repository before adding this catalog");return}if(w){ne.error("This catalog already exists");return}const A={id:$0(),label:M,source:C,...S?{subpath:S}:{},...v?{gitIdentityId:v}:{}},E=[...f,A];try{await os({skillCatalogs:E}),p(E),ne.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(R){ne.error(R instanceof Error?R.message:"Failed to save catalog")}};return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Add skills catalog"}),e.jsxs(Ns,{children:["Add a Git repository as a new catalog source. OpenChamber will scan it for folders containing ",e.jsx("code",{className:"font-mono",children:"SKILL.md"}),"."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Catalog name"}),e.jsx(ht,{value:a,onChange:M=>i(M.target.value),placeholder:"e.g. Team Skills"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Repository"}),e.jsx(ht,{value:l,onChange:M=>{d(M.target.value),j(!1),b(null)},placeholder:"owner/repo or git@github.com:owner/repo.git"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Public repos work everywhere. Private repos require SSH identity (Desktop/Web only)."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Optional subpath"}),e.jsx(ht,{value:u,onChange:M=>{m(M.target.value),j(!1),b(null)},placeholder:"e.g. skills"})]}),y.length>0&&!Ht()?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(vs,{value:v||"",onValueChange:M=>N(M),children:[e.jsx(js,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:y.find(M=>M.id===v)?.name||"Choose identity"})}),e.jsx(Ss,{align:"start",children:y.map(M=>e.jsx(Bt,{value:M.id,className:"pr-2 [&>span:first-child]:hidden",children:M.name},M.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,g!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",g," skill(s) found"]}):null,w?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(Ne,{variant:"outline",onClick:()=>{k()},disabled:o||!l.trim(),className:"gap-2",children:[e.jsx(bh,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Ne,{variant:"default",onClick:()=>{D()},disabled:!h||w||!a.trim()||!l.trim(),children:"Add catalog"})]})]})})},W0=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=c.useState({});c.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const i=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},l=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl",children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Skills already exist"}),e.jsx(Ns,{children:"Some selected skills are already installed in this scope. Choose whether to skip or overwrite them."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[t.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>i("skip"),children:"Skip all"}),e.jsx(Ne,{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(vs,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(js,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Ss,{align:"end",children:[e.jsx(Bt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Bt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Jr,{onClick:()=>n(o),disabled:!l,children:"Continue"})]})]})})},H0=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=no(),[a,i]=c.useState("user"),[l,d]=c.useState(!1),[u,m]=c.useState([]),[f,p]=c.useState(null);c.useEffect(()=>{s&&(i("user"),d(!1),m([]),p(null))},[s]);const g=async b=>{const h={skillDir:b.skillDir};t?.clawdhub&&(h.clawdhub={slug:t.clawdhub.slug,version:t.clawdhub.version});const j=await n({source:b.source,subpath:b.subpath,gitIdentityId:t?.gitIdentityId,scope:b.scope,selections:[h],conflictPolicy:"prompt",conflictDecisions:b.conflictDecisions});if(j.ok){ne.success("Skill installed successfully"),r(!1);return}if(j.error?.kind==="conflicts"){p({source:b.source,subpath:b.subpath,scope:b.scope,skillDir:b.skillDir}),m(j.error.conflicts),d(!0);return}if(j.error?.kind==="authRequired"){ne.error(j.error.message||"Authentication required");return}ne.error(j.error?.message||"Failed to install skill")};return t?e.jsxs(e.Fragment,{children:[e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Install skill"}),e.jsxs(Ns,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:t.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:t.warnings?.length?e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-3 py-2",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Warnings"}),e.jsx("ul",{className:"mt-1 space-y-1",children:t.warnings.map(b=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:b},b))})]}):null}),e.jsxs(Ks,{className:"flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(vs,{value:a,onValueChange:b=>i(b),children:[e.jsx(js,{className:"!h-9 w-full sm:w-36 justify-between",children:e.jsxs("span",{className:"flex flex-1 items-center gap-2 justify-start",children:[a==="user"?e.jsx(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Ss,{align:"start",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]})})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(Ne,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Ne,{className:"w-full sm:w-auto",variant:"default",disabled:o||!t.installable,onClick:()=>{g({source:t.repoSource,subpath:t.repoSubpath,scope:a,skillDir:t.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(W0,{open:l,onOpenChange:d,conflicts:u,onConfirm:b=>{f&&(g({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:b}),d(!1))}})]}):null},U0=async()=>{try{if(as())return await En();const s=tn()?.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}},V0=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:i,isLoadingCatalog:l,lastCatalogError:d}=no(),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,b]=c.useState(!1),[h,j]=c.useState(null),[y,x]=c.useState(!1);c.useEffect(()=>{i()},[i]);const v=c.useMemo(()=>o?n[o]||[]:[],[n,o]),N=c.useMemo(()=>{const M=u.trim().toLowerCase();return M?v.filter(C=>{const S=C.skillName.toLowerCase(),A=(C.description||"").toLowerCase(),E=(C.frontmatterName||"").toLowerCase();return S.includes(M)||A.includes(M)||E.includes(M)}):v},[v,u]),w=c.useMemo(()=>t.find(M=>M.id===o)||null,[t,o]),k=!!(o&&o.startsWith("custom:")),D=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){x(!0);try{const M=await U0(),S=(Array.isArray(M?.skillCatalogs)?M?.skillCatalogs:[]).filter(A=>A.id!==o);await os({skillCatalogs:S}),await i({refresh:!0})}finally{x(!1)}}};return e.jsx(mt,{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(lf,{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(vs,{value:o||"",onValueChange:M=>a(M),children:[e.jsx(js,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:w?.label||"Select source"})}),e.jsx(Ss,{align:"start",children:t.map(M=>e.jsx(Bt,{value:M.id,className:"pr-2 [&>span:first-child]:hidden",children:M.label},M.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ne,{type:"button",variant:"outline",onClick:()=>{i({refresh:!0})},disabled:l,className:"gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(Ne,{type:"button",variant:"outline",onClick:()=>{D()},disabled:y,className:"gap-2",children:[e.jsx(qs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Ne,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(qt,{className:"h-4 w-4"}),"Add catalog"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(ht,{value:u,onChange:M=>m(M.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:l?"Loading…":`${N.length} skill(s)`})]}),d?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.length===0?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):N.map(M=>{const C=M.installed?.isInstalled,S=M.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:M.skillName}),C?e.jsxs("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:["installed (",S||"unknown",")"]}):null,M.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"})]}),M.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:M.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),M.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[M.clawdhub.owner?e.jsxs("span",{children:["by ",M.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yr,{className:"h-3 w-3"}),M.clawdhub.downloads?.toLocaleString()??0]}),(M.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(xn,{className:"h-3 w-3"}),M.clawdhub.stars]}):null,e.jsxs("span",{children:["v",M.clawdhub.version]})]}):null,M.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:M.warnings.join(" · ")}):null]}),e.jsx(Ne,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!M.installable,onClick:()=>{j(M),b(!0)},children:"Install"})]})},`${M.sourceId}:${M.skillDir}`)})}),e.jsx(z0,{open:f,onOpenChange:p}),e.jsx(H0,{open:g,onOpenChange:b,item:h})]})})},G0=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:i,setSkillDraft:l,setSelectedSkill:d}=Hs(),u=s?r(s):null,m=!!(i&&i.name===s&&!u),f=!!(s&&!u&&!i),[p,g]=c.useState("manual");c.useEffect(()=>{!m&&p!=="manual"&&g("manual")},[m,p]),c.useEffect(()=>{f&&d(null)},[f,d]);const b=m?e.jsx(lf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:g,animate:!1}):null,[h,j]=c.useState(""),[y,x]=c.useState("user"),[v,N]=c.useState(""),[w,k]=c.useState(""),[D,M]=c.useState([]),[C,S]=c.useState([]),[A,E]=c.useState(!1),[R,_]=c.useState(!1),[P,O]=c.useState(""),[J,K]=c.useState(""),[L,G]=c.useState(!1),[B,H]=c.useState(""),[V,oe]=c.useState(""),[se,Y]=c.useState(null),[le,I]=c.useState(!1),[W,F]=c.useState(""),$=m?h.trim()!==""||v.trim()!==""||w.trim()!==""||C.length>0:v!==P||w!==J,z=se?V!==W:B.trim()!=="";c.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&i)j(i.name||""),x(i.scope||"user"),N(i.description||""),k(i.instructions||""),O(""),K(""),M([]),S(i.pendingFiles||[]);else if(s&&u){_(!0);try{const Ie=await t(s);if(Ie){const U=Ie.sources.md;N(U.description||""),k(U.instructions||""),O(U.description||""),K(U.instructions||""),M(U.supportingFiles||[])}}catch(Ie){console.error("Failed to load skill details:",Ie)}finally{_(!1)}}})()},[u,m,s,a,i,t,p]);const X=async()=>{const be=m?h.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!be){ne.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(be)||be.length>64){ne.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!v.trim()){ne.error("Description is required");return}if(m&&a.some(Ie=>Ie.name===be)){ne.error("A skill with this name already exists");return}E(!0);try{const Ie={name:be,description:v.trim(),instructions:w.trim()||void 0,scope:m?y:void 0,supportingFiles:m&&C.length>0?C:void 0};let U;m?(U=await n(Ie),U&&(l(null),S([]),d(be))):(U=await o(be,Ie),U&&(O(v.trim()),K(w.trim()))),U?ne.success(m?"Skill created successfully":"Skill updated successfully"):ne.error(m?"Failed to create skill":"Failed to update skill")}catch(Ie){console.error("Error saving skill:",Ie),ne.error("An error occurred while saving")}finally{E(!1)}},fe=()=>{Y(null),H(""),oe(""),F(""),G(!0)},ve=async be=>{if(Y(be),H(be),m){const U=C.find(Q=>Q.path===be)?.content||"";oe(U),F(U),G(!0);return}if(s){I(!0),G(!0);try{const{readSupportingFile:Ie}=Hs.getState(),U=await Ie(s,be);oe(U||""),F(U||"")}catch{ne.error("Failed to load file content"),oe(""),F("")}finally{I(!1)}}},ge=async()=>{if(!B.trim()){ne.error("File name is required");return}const be=B.trim(),Ie=se!==null;if(m){if(Ie)S(te=>te.map(pe=>pe.path===se?{path:be,content:V}:pe)),ne.success(`File "${be}" updated`);else{if(C.some(te=>te.path===be)){ne.error("A file with this name already exists");return}S(te=>[...te,{path:be,content:V}]),ne.success(`File "${be}" added`)}G(!1),Y(null);return}if(!s){ne.error("No skill selected");return}const{writeSupportingFile:U}=Hs.getState();if(await U(s,be,V)){ne.success(Ie?`File "${be}" updated`:`File "${be}" created`),G(!1),Y(null);const te=await t(s);te&&M(te.sources.md.supportingFiles||[])}else ne.error(Ie?"Failed to update file":"Failed to create file")},Re=async be=>{if(m){S(Ie=>Ie.filter(U=>U.path!==be)),ne.success(`File "${be}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${be}"?`)){const{deleteSupportingFile:Ie}=Hs.getState();if(await Ie(s,be)){ne.success(`File "${be}" deleted`);const Q=await t(s);Q&&M(Q.sources.md.supportingFiles||[])}else ne.error("Failed to delete file")}};return m&&p==="external"?e.jsx(V0,{mode:p,onModeChange:g}):!s&&!i||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(xu,{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"})]})}):R?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(mt,{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?b:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":s}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[u.scope==="project"?"Project":"User"," skill",u.source==="claude"&&" (Claude-compatible)"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure skill identity and description"})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{value:h,onChange:be=>j(be.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(vs,{value:y,onValueChange:be=>x(be),children:[e.jsxs(js,{className:"!h-9 w-auto gap-1.5",children:[y==="user"?e.jsx(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:y})]}),e.jsxs(Ss,{align:"end",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Lowercase letters, numbers, and hyphens only. Cannot start or end with hyphen."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Description ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Ts,{value:v,onChange:be=>N(be.target.value),placeholder:"Brief description of what this skill does...",rows:2,className:"max-h-32 resize-none"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The agent uses this to decide when to load the skill"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Instructions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Detailed instructions for the agent when this skill is loaded"})]}),e.jsx(Ts,{value:w,onChange:be=>k(be.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(Ne,{variant:"outline",size:"sm",onClick:fe,className:"gap-1.5",children:[e.jsx(qt,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const be=m?C:D;return be.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:be.map(Ie=>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:()=>ve(Ie.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(tr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:Ie.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(Ne,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:U=>{U.stopPropagation(),Re(Ie.path)},children:e.jsx(qs,{className:"h-3.5 w-3.5"})})]},Ie.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:X,disabled:A||!$,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(da,{className:"h-3 w-3"}),A?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(ms,{open:L,onOpenChange:be=>{G(be),be||Y(null)},children:e.jsxs(fs,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(xs,{className:"flex-shrink-0",children:[e.jsx(ys,{children:se?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ns,{children:se?"Modify the file content":"Create a new file in the skill directory"})]}),le?e.jsx("div",{className:"flex-1 flex items-center justify-center py-8",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading file content..."})}):e.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"File Path"}),e.jsx(ht,{value:B,onChange:be=>H(be.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:se!==null}),!se&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Relative path within the skill directory. Subdirectories will be created automatically."})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-h-0 flex flex-col",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:"Content"}),e.jsx(Ts,{value:V,onChange:be=>oe(be.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>{G(!1),Y(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Jr,{onClick:ge,disabled:le||!z,children:se?"Save Changes":"Create File"})]})]})})]})})},q0="__add_provider__",K0=({onItemSelect:s})=>{const r=st(u=>u.providers),t=st(u=>u.selectedProviderId),n=st(u=>u.setSelectedProvider),{isMobile:o}=Rt(),[a,i]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||i(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:T("flex h-full flex-col",d),children:[e.jsx("div",{className:T("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(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(q0),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(qt,{className:"size-4"})})]})}),e.jsx(mt,{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(Yn,{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:T("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(ns,{providerId:u.id,className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 min-w-0 text-foreground",children:u.name||u.id}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:m})]})},u.id)})})]})},Y0=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Id=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=Y0.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Pd="__add_provider__",Mn=s=>typeof s=="object"&&s!==null,Td=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()},Q0=s=>{if(!Mn(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>Mn(o)));return r},X0=s=>{if(typeof s=="string")return{id:s};if(!Mn(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}},J0=s=>{let r=[];Array.isArray(s)?r=s:Mn(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>X0(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},Z0=()=>{const s=st(F=>F.providers),r=st(F=>F.selectedProviderId),t=st(F=>F.setSelectedProvider),n=st(F=>F.getModelMetadata),[o,a]=c.useState({}),[i,l]=c.useState(!1),[d,u]=c.useState({}),[m,f]=c.useState(null),[p,g]=c.useState(""),[b,h]=c.useState(null),[j,y]=c.useState({}),[x,v]=c.useState({}),[N,w]=c.useState([]),[k,D]=c.useState(!1),[M,C]=c.useState(null),[S,A]=c.useState(""),[E,R]=c.useState(""),[_,P]=c.useState(!1);c.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),c.useEffect(()=>{let F=!0;return(async()=>{l(!0);try{const z=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error(`Auth methods request failed (${z.status})`);const X=await z.json().catch(()=>({}));if(!F)return;a(Q0(X))}catch(z){if(!F)return;console.error("Failed to load provider auth methods:",z),ne.error("Failed to load provider authentication methods")}finally{F&&l(!1)}})(),()=>{F=!1}},[]),c.useEffect(()=>{let F=!0;return(async()=>{D(!0),C(null);try{const z=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error(`Provider list request failed (${z.status})`);const X=await z.json().catch(()=>({}));if(!F)return;w(J0(X))}catch(z){if(!F)return;console.error("Failed to load available providers:",z),C("Unable to load provider list")}finally{F&&D(!1)}})(),()=>{F=!1}},[]);const O=c.useMemo(()=>new Set(s.map(F=>F.id)),[s]),J=c.useMemo(()=>N.filter(F=>!O.has(F.id)),[N,O]);c.useEffect(()=>{if(r===Pd){if(!S&&J.length>0){A(J[0].id);return}S&&!J.some(F=>F.id===S)&&A(J[0]?.id??"")}},[r,S,J]);const K=s.find(F=>F.id===r),L=async F=>{const $=d[F]?.trim()??"";if(!$){ne.error("API key is required");return}const z=`api:${F}`;f(z);try{const X=await fetch(`/api/auth/${encodeURIComponent(F)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:$})}),fe=await X.json().catch(()=>null);if(!X.ok){const ve=fe?.error||"Failed to save API key";throw new Error(ve)}ne.success("API key saved"),u(ve=>({...ve,[F]:""})),await Un({scopes:["providers"],mode:"active"}),t(F)}catch(X){console.error("Failed to save API key:",X),ne.error("Failed to save API key")}finally{f(null)}},G=async(F,$)=>{const z=`oauth:${F}:${$}`;f(z);try{const X=await fetch(`/api/provider/${encodeURIComponent(F)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:$})}),fe=await X.json().catch(()=>null);if(!X.ok){const Q=fe?.error||"Failed to start OAuth flow";throw new Error(Q)}const ve=Mn(fe)?fe:{},ge=Mn(ve.data)?ve.data:ve,Re=typeof ge.url=="string"&&ge.url||typeof ge.verification_uri_complete=="string"&&ge.verification_uri_complete||typeof ge.verification_uri=="string"&&ge.verification_uri||void 0,be=typeof ge.instructions=="string"&&ge.instructions||typeof ge.message=="string"&&ge.message||void 0,Ie=typeof ge.user_code=="string"&&ge.user_code||typeof ge.code=="string"&&ge.code||typeof ge.userCode=="string"&&ge.userCode||void 0;if(!Re&&!be&&!Ie)throw new Error("No OAuth details returned");const U=`${F}:${$}`;v(Q=>({...Q,[U]:{url:Re,instructions:be,userCode:Ie}})),Re&&window.open(Re,"_blank","noopener,noreferrer"),h({providerId:F,methodIndex:$}),ne.message("Complete the OAuth flow in your browser")}catch(X){console.error("Failed to start OAuth flow:",X),ne.error("Failed to start OAuth flow")}finally{f(null)}},B=async(F,$)=>{const z=`${F}:${$}`,X=j[z]?.trim(),fe=`oauth-complete:${F}:${$}`;f(fe);try{const ve={method:$};X&&(ve.code=X);const ge=await fetch(`/api/provider/${encodeURIComponent(F)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ve)}),Re=await ge.json().catch(()=>null);if(!ge.ok){const be=Re?.error||"Failed to complete OAuth flow";throw new Error(be)}ne.success("OAuth connection completed"),y(be=>({...be,[z]:""})),h(null),await Un({scopes:["providers"],mode:"active"}),t(F)}catch(ve){console.error("Failed to complete OAuth flow:",ve),ne.error("Failed to complete OAuth flow")}finally{f(null)}},H=async F=>{try{await navigator.clipboard.writeText(F),ne.success("OAuth link copied")}catch($){console.error("Failed to copy OAuth link:",$),ne.error("Failed to copy OAuth link")}},V=async F=>{try{await navigator.clipboard.writeText(F),ne.success("Device code copied")}catch($){console.error("Failed to copy device code:",$),ne.error("Failed to copy device code")}},oe=async F=>{const $=`disconnect:${F}`;f($);try{const z=await fetch(`/api/provider/${encodeURIComponent(F)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),X=await z.json().catch(()=>null);if(!z.ok){const fe=X?.error||"Failed to disconnect provider";throw new Error(fe)}ne.success("Provider disconnected"),await Un({scopes:["providers"],mode:"active"})}catch(z){console.error("Failed to disconnect provider:",z),ne.error("Failed to disconnect provider")}finally{f(null)}},se=r===Pd;if(!se&&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(Yn,{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(se)return e.jsx(mt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Connect provider"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:"Choose a provider to connect and set up its authentication."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Provider"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select a provider that is not connected yet."})]}),k?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M}):J.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(Ut,{open:_,onOpenChange:F=>{P(F),F||R("")},children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{type:"button",className:T("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:S?"text-foreground":"text-muted-foreground",children:S?J.find(F=>F.id===S)?.name||S:"Select provider"}),e.jsx(Et,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Gt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:F=>F.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:F=>F.stopPropagation(),children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:F=>R(F.target.value),onKeyDown:F=>F.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(mt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const F=J.filter($=>{const z=E.toLowerCase();return($.name||$.id).toLowerCase().includes(z)||$.id.toLowerCase().includes(z)});return F.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):F.map($=>e.jsxs(kt,{onSelect:()=>{A($.id),P(!1),R("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:$.name||$.id}),S===$.id&&e.jsx(Tt,{className:"h-4 w-4 text-primary"})]},$.id))})()})]})]})]}),S&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),i?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{type:"password",value:d[S]??"",onChange:F=>u($=>({...$,[S]:F.target.value})),placeholder:"sk-..."}),e.jsx(Ne,{size:"sm",onClick:()=>L(S),disabled:m===`api:${S}`,className:"h-8",children:m===`api:${S}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),(()=>{const $=(o[S]??[]).filter(z=>Td(z)==="oauth");return $.length===0?null:e.jsx("div",{className:"space-y-3",children:$.map((z,X)=>{const fe=z.label||z.name||`OAuth method ${X+1}`,ve=`${S}:${X}`,ge=b?.providerId===S&&b?.methodIndex===X;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:fe}),(z.description||z.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(z.description||z.help)})]}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>G(S,X),disabled:m===`oauth:${S}:${X}`,className:"h-8",children:"Connect"})]}),x[ve]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:x[ve]?.instructions}),x[ve]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:x[ve]?.userCode,readOnly:!0}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>V(x[ve]?.userCode??""),className:"h-8",children:"Copy code"})]}),x[ve]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:x[ve]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:x[ve]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>H(x[ve]?.url??""),className:"h-8",children:"Copy link"})]})]}),ge&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:j[ve]??"",onChange:Re=>y(be=>({...be,[ve]:Re.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Ne,{size:"sm",onClick:()=>B(S,X),disabled:m===`oauth-complete:${S}:${X}`,className:"h-8",children:m===`oauth-complete:${S}:${X}`?"Saving…":"Complete"})]})]},`${S}-${fe}`)})})})()]})]})]})});if(!K)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(Yn,{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 Y=Array.isArray(K.models)?K.models:[],I=(o[K.id]??[]).filter(F=>Td(F)==="oauth"),W=Y.filter(F=>{const $=typeof F?.name=="string"?F.name:"",z=typeof F?.id=="string"?F.id:"",X=p.trim().toLowerCase();return X?$.toLowerCase().includes(X)||z.toLowerCase().includes(X):!0});return e.jsx(mt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{providerId:K.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:K.name||K.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",K.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),i?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{type:"password",value:d[K.id]??"",onChange:F=>u($=>({...$,[K.id]:F.target.value})),placeholder:"sk-..."}),e.jsx(Ne,{size:"sm",onClick:()=>L(K.id),disabled:m===`api:${K.id}`,className:"h-8",children:m===`api:${K.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(Ne,{size:"sm",variant:"outline",onClick:()=>oe(K.id),disabled:m===`disconnect:${K.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${K.id}`?"Disconnecting…":"Disconnect provider"})}),I.length>0&&e.jsx("div",{className:"space-y-3",children:I.map((F,$)=>{const z=F.label||F.name||`OAuth method ${$+1}`,X=`${K.id}:${$}`,fe=b?.providerId===K.id&&b?.methodIndex===$;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:z}),(F.description||F.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(F.description||F.help)})]}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>G(K.id,$),disabled:m===`oauth:${K.id}:${$}`,className:"h-8",children:"Connect"})]}),x[X]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:x[X]?.instructions}),x[X]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:x[X]?.userCode,readOnly:!0}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>V(x[X]?.userCode??""),className:"h-8",children:"Copy code"})]}),x[X]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:x[X]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:x[X]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>H(x[X]?.url??""),className:"h-8",children:"Copy link"})]})]}),fe&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:j[X]??"",onChange:ve=>y(ge=>({...ge,[X]:ve.target.value})),placeholder:"Paste authorization code"}),e.jsx(Ne,{size:"sm",onClick:()=>B(K.id,$),disabled:m===`oauth-complete:${K.id}:${$}`,className:"h-8",children:m===`oauth-complete:${K.id}:${$}`?"Saving…":"Complete"})]})]},`${K.id}-${z}`)})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Models"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Browse and filter models exposed by this provider."})]}),e.jsx(ht,{value:p,onChange:F=>g(F.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:W.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):W.map(F=>{const $=typeof F?.id=="string"?F.id:"",z=typeof F?.name=="string"?F.name:$,X=$?n(K.id,$):void 0,fe=Id(X?.limit?.context),ve=Id(X?.limit?.output),ge=[];return X?.tool_call&&ge.push({key:"tools",icon:ca,label:"Tool calling"}),X?.reasoning&&ge.push({key:"reasoning",icon:ar,label:"Reasoning"}),X?.attachment&&ge.push({key:"image",icon:br,label:"Image input"}),e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:z}),(fe||ve)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[fe?`${fe} ctx`:"",fe&&ve?" · ":"",ve?`${ve} out`:""]}),ge.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:ge.map(({key:Re,icon:be,label:Ie})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Ie,"aria-label":Ie,children:e.jsx(be,{className:"h-3 w-3"})},Re))})]},$)})})]})]})})},ej={branch:$t,briefcase:Qi,house:Yi,graduation:Ki,code:nr,heart:fu},tj={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},sj=({onItemSelect:s})=>{const{selectedProfileId:r,profiles:t,globalIdentity:n,setSelectedProfile:o,deleteProfile:a,loadProfiles:i,loadGlobalIdentity:l}=ba(),{setSidebarOpen:d}=$e(),{isMobile:u}=Rt(),[m,f]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),p=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{i(),l()},[i,l]);const g=m?"bg-transparent":p?"bg-background":"bg-sidebar",b=()=>{o("new"),s?.(),u&&d(!1)},h=async j=>{window.confirm(`Are you sure you want to delete profile "${j.name}"?`)&&(await a(j.id)?ne.success(`Profile "${j.name}" deleted successfully`):ne.error("Failed to delete profile"))};return e.jsxs("div",{className:T("flex h-full flex-col",g),children:[e.jsx("div",{className:T("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(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:b,children:e.jsx(qt,{className:"size-4"})})]})}),e.jsxs(mt,{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(Fd,{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($t,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:t.map(j=>e.jsx(Fd,{profile:j,isSelected:r===j.id,onSelect:()=>{o(j.id),s?.(),u&&d(!1)},onDelete:()=>h(j)},j.id))})]})]})},Fd=({profile:s,isSelected:r,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=ej[s.icon||"branch"]||$t,i=tj[s.color||""];return e.jsx("div",{className:T("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(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{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(Ir,{className:"h-3.5 w-3.5"})})}),e.jsx(Gt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(kt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})},Rd=[{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)"}],rj=[{key:"branch",Icon:$t,label:"Branch"},{key:"briefcase",Icon:Qi,label:"Work"},{key:"house",Icon:Yi,label:"Personal"},{key:"graduation",Icon:Ki,label:"School"},{key:"code",Icon:nr,label:"Code"}],nj=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=ba(),a=c.useMemo(()=>s&&s!=="new"?r(s):null,[s,r]),i=s==="new",l=s==="global",[d,u]=c.useState(""),[m,f]=c.useState(""),[p,g]=c.useState(""),[b,h]=c.useState(""),[j,y]=c.useState("keyword"),[x,v]=c.useState("branch"),[N,w]=c.useState(!1);c.useEffect(()=>{i?(u(""),f(""),g(""),h(""),y("keyword"),v("branch")):a&&(u(a.name),f(a.userName),g(a.userEmail),h(a.sshKey||""),y(a.color||"keyword"),v(a.icon||"branch"))},[a,i,s]);const k=async()=>{if(!m.trim()||!p.trim()){ne.error("User name and email are required");return}w(!0);try{const C={name:d.trim()||m.trim(),userName:m.trim(),userEmail:p.trim(),sshKey:b.trim()||null,color:j,icon:x};let S;if(i)S=await t(C);else if(s)S=await n(s,C);else return;S?ne.success(i?"Profile created successfully":"Profile updated successfully"):ne.error(i?"Failed to create profile":"Failed to update profile")}catch(C){console.error("Error saving profile:",C),ne.error("An error occurred while saving")}finally{w(!1)}},D=async()=>{if(!(!s||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(s)?ne.success("Profile deleted successfully"):ne.error("Failed to delete profile")}catch(C){console.error("Error deleting profile:",C),ne.error("An error occurred while deleting")}},M=c.useMemo(()=>Rd.find(S=>S.key===j)?.cssVar||"var(--syntax-keyword)",[j]);return s?e.jsx(mt,{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":l?"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":l?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!l&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(ht,{value:d,onChange:C=>u(C.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:Rd.map(C=>e.jsx("button",{onClick:()=>y(C.key),className:T("w-8 h-8 rounded-lg border-2 transition-all",j===C.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:C.cssVar},title:C.label},C.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:rj.map(C=>{const S=C.Icon;return e.jsx("button",{onClick:()=>v(C.key),className:T("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",x===C.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:C.label,children:e.jsx(S,{className:"w-4 h-4",style:{color:M}})},C.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 ",!l&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{sideOffset:8,className:"max-w-xs",children:["The name that will appear in Git commit messages.",e.jsx("br",{}),"This is the author name shown in git log and GitHub/GitLab interfaces."]})]})]}),e.jsx(ht,{value:m,onChange:C=>f(C.target.value),placeholder:"John Doe",required:!l,readOnly:l,disabled:l}),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 ",!l&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{sideOffset:8,className:"max-w-xs",children:["The email address for Git commits.",e.jsx("br",{}),"This should match your email in GitHub/GitLab",e.jsx("br",{}),"to ensure proper attribution of commits."]})]})]}),e.jsx(ht,{type:"email",value:p,onChange:C=>g(C.target.value),placeholder:"john@example.com",required:!l,readOnly:l,disabled:l}),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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(ht,{value:b,onChange:C=>h(C.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:l,disabled:l}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!l&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(Ne,{size:"sm",variant:"destructive",onClick:D,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(qs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:T("flex gap-2",i&&"ml-auto"),children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:k,disabled:N,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(da,{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(Fs,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a profile from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})};function oi(s,r,t){return Math.min(t,Math.max(r,s))}const ra=Ce.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:l,onKeyDown:d,disabled:u,...m},f)=>{const p=Ce.useRef(null);Ce.useImperativeHandle(f,()=>p.current);const[g,b]=Ce.useState(()=>String(s));Ce.useEffect(()=>{document.activeElement!==p.current&&b(String(s))},[s]);const h=Ce.useCallback(()=>{p.current?.focus()},[]),j=Ce.useCallback(S=>{const A=oi(S,t,n);r(A),b(String(A))},[n,t,r]),y=Ce.useCallback(()=>{const S=Number(g);return Number.isFinite(S)?S:s},[g,s]),x=Ce.useCallback(()=>{j(y()+o),h()},[j,y,h,o]),v=Ce.useCallback(()=>{j(y()-o),h()},[j,y,h,o]),N=S=>{const A=S.target.value;b(A);const E=Number(A);Number.isFinite(E)&&r(oi(E,t,n))},w=S=>{const A=Number(g);if(!Number.isFinite(A))b(String(s));else{const E=oi(A,t,n);E!==A&&r(E),b(String(E))}l?.(S)},k=S=>{if(S.key==="ArrowUp"){S.preventDefault(),x();return}if(S.key==="ArrowDown"){S.preventDefault(),v();return}d?.(S)},D=y(),M=u||D<=t,C=u||D>=n;return e.jsxs("div",{className:T("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",i),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:g,onChange:N,onBlur:w,onKeyDown:k,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:T("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:C,onClick:x,className:T("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(ia,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:M,onClick:v,className:T("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(Et,{className:"h-3.5 w-3.5"})})]})]})});ra.displayName="NumberInput";const oj=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],_d=[{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"}],Od=[{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."}],Ml=({visibleSettings:s})=>{const{isMobile:r}=Rt(),t=$e(v=>v.showReasoningTraces),n=$e(v=>v.setShowReasoningTraces),o=$e(v=>v.toolCallExpansion),a=$e(v=>v.setToolCallExpansion),i=$e(v=>v.fontSize),l=$e(v=>v.setFontSize),d=$e(v=>v.padding),u=$e(v=>v.setPadding),m=$e(v=>v.inputBarOffset),f=$e(v=>v.setInputBarOffset),p=$e(v=>v.diffLayoutPreference),g=$e(v=>v.setDiffLayoutPreference),b=Zs(v=>v.queueModeEnabled),h=Zs(v=>v.setQueueMode),{themeMode:j,setThemeMode:y}=nn(),x=v=>s?s.includes(v):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[x("theme")&&!Ht()&&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:oj.map(v=>e.jsx(Bs,{variant:j===v.value?"default":"outline",className:T(j===v.value?void 0:"text-foreground"),onClick:()=>y(v.value),children:v.label},v.value))})]}),x("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:v=>l(Number(v.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(ra,{value:i,onValueChange:l,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>l(100),disabled:i===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(Ps,{className:"h-3.5 w-3.5"})})]})]}),x("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:v=>u(Number(v.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Spacing percentage"}),e.jsx("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:d}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ps,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:d,onChange:v=>u(Number(v.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(ra,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ps,{className:"h-3.5 w-3.5"})})]})]}),x("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:v=>f(Number(v.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[m,"px"]}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>f(0),disabled:m===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(Ps,{className:"h-3.5 w-3.5"})})]})]}),x("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:_d.find(v=>v.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:_d.map(v=>e.jsx(Bs,{variant:o===v.value?"default":"outline",className:T(o===v.value?void 0:"text-foreground"),onClick:()=>a(v.value),children:v.label},v.value))})]}),x("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:Od.map(v=>e.jsx(Bs,{variant:p===v.id?"default":"outline",className:T(p===v.id?void 0:"text-foreground"),onClick:()=>g(v.id),children:v.label},v.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Od.find(v=>v.id===p)?.description})]})]}),x("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:v=>n(v.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),x("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:b,onChange:v=>h(v.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:b?`Enter queues messages, ${Zt()}+Enter sends immediately.`:`Enter sends immediately, ${Zt()}+Enter queues messages.`})]})]})},$d="https://github.com/btriapitsyn/openchamber",aj=800,cf=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=ua(),{isMobile:a}=Rt(),i=o.info?.currentVersion||"unknown",l=c.useRef(!1);c.useEffect(()=>{if(o.checking)n(!0),l.current=!0;else if(t){const u=setTimeout(()=>{n(!1),l.current&&!o.available&&!o.error&&(ne.success("You are on the latest version"),l.current=!1)},aj);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(Ps,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",i]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:T("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(Yr,{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:$d,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(wi,{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(yu,{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(vi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ai,{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(Do,{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:T("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(Yr,{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:T("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:$d,target:"_blank",rel:"noopener noreferrer",className:T("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(wi,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:T("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(vi,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ai,{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})]})},ij=1440*60*1e3,df=5,Ld=1440*60*1e3,ai=s=>s.time?.updated??s.time?.created??0,Bd=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=df,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*ij,i=[...s].sort((d,u)=>ai(u)-ai(d)),l=new Set(i.slice(0,n).map(d=>d.id));return i.filter(d=>{if(!d?.id||l.has(d.id)||d.id===r||d.share)return!1;const u=ai(d);return u?u<a:!1}).map(d=>d.id)},uf=s=>{const r=s?.autoRun!==!1,t=ue(h=>h.sessions),n=ue(h=>h.currentSessionId),o=ue(h=>h.isLoading),a=ue(h=>h.deleteSessions),i=$e(h=>h.autoDeleteEnabled),l=$e(h=>h.autoDeleteAfterDays),d=$e(h=>h.autoDeleteLastRunAt),u=$e(h=>h.setAutoDeleteLastRunAt),[m,f]=c.useState(!1),p=c.useRef(!1),g=c.useMemo(()=>l<=0?[]:Bd({sessions:t,currentSessionId:n,cutoffDays:l}),[l,n,t]),b=c.useCallback(async({force:h=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!i||l<=0)&&!h)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const j=Date.now();if(!h&&d&&j-d<Ld)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const y=Bd({sessions:t,currentSessionId:n,cutoffDays:l,now:j});if(y.length===0)return u(j),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(y,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[l,i,d,n,a,o,t,u]);return c.useEffect(()=>{if(!r||!i||l<=0||o||t.length===0)return;const h=Date.now();d&&h-d<Ld||b()},[l,i,d,r,o,t.length,b]),{candidates:g,isRunning:m,runCleanup:b,keepRecentCount:df}},ii=1,li=365,mf=()=>{const{isMobile:s}=Rt(),r=$e(p=>p.autoDeleteEnabled),t=$e(p=>p.autoDeleteAfterDays),n=$e(p=>p.setAutoDeleteEnabled),o=$e(p=>p.setAutoDeleteAfterDays),[a,i]=c.useState(String(t));c.useEffect(()=>{i(String(t))},[t]);const{candidates:l,isRunning:d,runCleanup:u}=uf({autoRun:!1}),m=l.length,f=c.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){ne.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&ne.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&ne.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(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:r,onChange:p=>n(p.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const g=p.target.value;if(i(g),g.trim()==="")return;const b=Number(g);if(!Number.isFinite(b))return;const h=Math.min(li,Math.max(ii,Math.round(b)));o(h)},onBlur:()=>{if(a.trim()===""){i(String(t));return}const p=Number(a);if(!Number.isFinite(p)){i(String(t));return}const g=Math.min(li,Math.max(ii,Math.round(p)));o(g),i(String(g))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(ra,{value:t,onValueChange:o,min:ii,max:li,step:1,"aria-label":"Retention period in days"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days since last activity"})]}),e.jsx(Bs,{type:"button",variant:"outline",onClick:f,disabled:d,children:d?"Cleaning up...":"Run cleanup now"})]}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Eligible for deletion right now: ",m]})]})},ff=()=>{const s=st(S=>S.setProvider),r=st(S=>S.setModel),t=st(S=>S.setAgent),n=st(S=>S.setCurrentVariant),o=st(S=>S.setSettingsDefaultModel),a=st(S=>S.setSettingsDefaultVariant),i=st(S=>S.setSettingsDefaultAgent),l=st(S=>S.settingsAutoCreateWorktree),d=st(S=>S.setSettingsAutoCreateWorktree),u=st(S=>S.providers),[m,f]=c.useState(),[p,g]=c.useState(),[b,h]=c.useState(),[j,y]=c.useState(!0),x=c.useMemo(()=>{if(!m)return{providerId:"",modelId:""};const S=m.split("/");return S.length!==2?{providerId:"",modelId:""}:{providerId:S[0]||"",modelId:S[1]||""}},[m]);c.useEffect(()=>{(async()=>{try{let A=null;if(as())A=await En();else{const E=tn()?.settings;if(E)try{const _=(await E.load())?.settings;_&&(A={defaultModel:typeof _.defaultModel=="string"?_.defaultModel:void 0,defaultVariant:typeof _.defaultVariant=="string"?_.defaultVariant:void 0,defaultAgent:typeof _.defaultAgent=="string"?_.defaultAgent:void 0})}catch{}if(!A){const R=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});R.ok&&(A=await R.json())}}if(A){const E=typeof A.defaultModel=="string"&&A.defaultModel.trim().length>0?A.defaultModel.trim():void 0,R=typeof A.defaultVariant=="string"&&A.defaultVariant.trim().length>0?A.defaultVariant.trim():void 0,_=typeof A.defaultAgent=="string"&&A.defaultAgent.trim().length>0?A.defaultAgent.trim():void 0;f(E),g(R),h(_)}}catch(A){console.warn("Failed to load defaults settings:",A)}finally{y(!1)}})()},[]);const v=c.useCallback(async(S,A)=>{const E=S&&A?`${S}/${A}`:void 0;f(E),g(void 0),a(void 0),n(void 0),o(E),S&&A&&u.find(_=>_.id===S)&&(s(S),r(A));try{await os({defaultModel:E??"",defaultVariant:""})}catch(R){console.warn("Failed to save default model:",R)}},[u,n,s,r,o,a]),N="__default__",w=c.useCallback(async S=>{const A=S===N?void 0:S||void 0;g(A),a(A),n(A);try{await os({defaultVariant:A??""})}catch(E){console.warn("Failed to save default variant:",E)}},[n,a]),k=c.useCallback(async S=>{const A=S||void 0;h(A),i(A),S&&t(S);try{await os({defaultAgent:A??""})}catch(E){console.warn("Failed to save default agent:",E)}},[t,i]),D=c.useMemo(()=>{const E=u.find(R=>R.id===x.providerId)?.models.find(R=>R.id===x.modelId)?.variants;return E?Object.keys(E):[]},[x.modelId,x.providerId,u]),M=D.length>0;c.useEffect(()=>{!M&&p&&(g(void 0),a(void 0),n(void 0),os({defaultVariant:""}).catch(()=>{}))},[p,n,a,M]);const C=c.useCallback(async S=>{const A=S.target.checked;d(A);try{await os({autoCreateWorktree:A})}catch(E){console.warn("Failed to save auto create worktree setting:",E)}},[d]);return j?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session Defaults"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{sideOffset:8,className:"max-w-xs",children:"Configure default behaviors for new sessions."})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default model"}),e.jsx(Cl,{providerId:x.providerId,modelId:x.modelId,onChange:v})]}),M&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default thinking"}),e.jsxs(vs,{value:p??N,onValueChange:w,children:[e.jsx(js,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Xr,{placeholder:"Thinking"})}),e.jsxs(Ss,{children:[e.jsx(Bt,{value:N,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),D.map(S=>e.jsx(Bt,{value:S,className:"pr-2 [&>span:first-child]:hidden",children:S},S))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default agent"}),e.jsx(af,{agentName:b||"",onChange:k})]})]}),(m||b)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",m&&e.jsxs("span",{className:"text-foreground",children:[m,M?` (${p??"default"})`:""]}),m&&b&&" / ",b&&e.jsx("span",{className:"text-foreground",children:b})]}),e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:l,onChange:C}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Always create worktree for new sessions"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5 mt-1",children:l?`New session (Worktree): ${Zt()} + N • New session (Standard): Shift + ${Zt()} + N`:`New session (Standard): ${Zt()} + N • New session (Worktree): Shift + ${Zt()} + N`})]})]})},lj=()=>{const s=Ft(I=>I.getActiveProject()),r=Ft(I=>I.updateWorktreeDefaults),t=s?.path??null,n=s?.worktreeDefaults,o=cl(t),a=tm(t),{sessions:i,getWorktreeMetadata:l}=ue(),[d,u]=c.useState(n?.branchPrefix??""),[m,f]=c.useState(n?.baseBranch??"HEAD"),[p,g]=c.useState([]),[b,h]=c.useState(!1),[j,y]=c.useState(!1),[x,v]=c.useState(null),[N,w]=c.useState(null),[k,D]=c.useState([]),[M,C]=c.useState(!1),S=".openchamber",A=c.useCallback((I,W)=>{const F=I.replace(/\\/g,"/").replace(/\/+$/,""),$=!F||F==="/"?`/${S}`:`${F}/${S}`;return W?`${$}/${W}`:$},[]),E=c.useCallback(async()=>{if(!(!t||x===!1))try{const W=(await Sn(t)).map(X=>kn(t,X)),$=`${A(t,"")}/`,z=W.filter(X=>X.path.startsWith($));D(z)}catch{}},[t,x,A]);c.useEffect(()=>{if(!t)return;let I=!1;return y(!0),C(!0),v(null),w(null),D([]),(async()=>{try{const W=await sn(t);if(I)return;if(v(W),W){const[F,$]=await Promise.all([nl(t),Sn(t).catch(()=>[])]);if(!I){F&&w({all:F.all,current:F.current});const z=$.map(ge=>kn(t,ge)),fe=`${`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/${S}`}/`,ve=z.filter(ge=>ge.path.startsWith(fe));D(ve)}}}catch{}finally{I||(y(!1),C(!1))}})(),()=>{I=!0}},[t]),c.useEffect(()=>{if(!t)return;let I=!1;return h(!0),(async()=>{try{const W=await oo(t);I||g(W.length>0?W:[""])}catch{I||g([""])}finally{I||h(!1)}})(),()=>{I=!0}},[t]),c.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const R=N??a,_=x??o,P=c.useMemo(()=>{const I=[],W=R?.current?`Current (HEAD: ${R.current})`:"Current (HEAD)";return I.push({value:"HEAD",label:W,group:"special"}),R&&(R.all.filter(z=>!z.startsWith("remotes/")).sort((z,X)=>z.localeCompare(X)).forEach(z=>{I.push({value:z,label:z,group:"local"})}),R.all.filter(z=>z.startsWith("remotes/")).map(z=>z.replace(/^remotes\//,"")).sort((z,X)=>z.localeCompare(X)).forEach(z=>{I.push({value:z,label:z,group:"remote"})})),I},[R]),O=c.useRef(null),J=c.useCallback(I=>{u(I),O.current=I},[]),K=c.useCallback(I=>{s?.id&&(r(s.id,{branchPrefix:I}),O.current=null)},[s?.id,r]),L=c.useCallback(()=>{K(d)},[d,K]);c.useEffect(()=>()=>{O.current!==null&&s?.id&&r(s.id,{branchPrefix:O.current})},[s?.id,r]);const G=c.useCallback(I=>{f(I),s?.id&&r(s.id,{baseBranch:I})},[s?.id,r]),B=c.useCallback((I,W)=>{g(F=>{const $=[...F];return $[I]=W,$})},[]),H=c.useCallback(()=>{g(I=>[...I,""])},[]),V=c.useCallback(I=>{g(W=>W.filter((F,$)=>$!==I))},[]),oe=c.useCallback(async()=>{if(!t)return;const I=p.filter(W=>W.trim().length>0);await zu(t,I)},[t,p]),se=c.useCallback(()=>{oe()},[oe]),Y=c.useCallback(I=>{const W=I.path.replace(/\\/g,"/").replace(/\/+$/,""),F=i.filter(ge=>{if(l(ge.id)?.path===I.path)return!0;const be=ge.directory;return!!(be&&be.replace(/\\/g,"/").replace(/\/+$/,"")===W)}),$=new Set(F.map(ge=>ge.id)),z=ge=>{const Re=i.filter(Ie=>{const U=Ie.parentID;return U&&ge.has(U)});if(Re.length===0)return[];const be=new Set(Re.map(Ie=>Ie.id));return[...Re,...z(be)]},X=z($),fe=new Set,ve=[...F,...X].filter(ge=>fe.has(ge.id)?!1:(fe.add(ge.id),!0));Cn.requestDelete({sessions:ve,mode:"worktree",worktree:I})},[i,l]),le=c.useMemo(()=>i.map(I=>I.id).join(","),[i]);return c.useEffect(()=>{x&&t&&E()},[le,x,t,E]),t?j?e.jsx("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:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."})]})}):_===!1?e.jsx("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:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Worktree settings are only available for Git repositories."})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Branch prefix"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{sideOffset:8,className:"max-w-xs",children:"Prefix for auto-generated branch names when creating new worktrees."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"e.g. feature, bugfix, wip (no trailing slash)"})]}),e.jsx(ht,{value:d,onChange:I=>J(I.target.value),onBlur:L,placeholder:"feature",className:"max-w-xs"})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Base branch"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{sideOffset:8,className:"max-w-xs",children:"Default branch to create new worktrees from."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default branch for new worktree branches"})]}),e.jsxs(vs,{value:m,onValueChange:G,children:[e.jsx(js,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Xr,{placeholder:"Select a branch"})}),e.jsxs(Ss,{children:[e.jsxs(Vr,{children:[e.jsx(vn,{children:"Default"}),P.filter(I=>I.group==="special").map(I=>e.jsx(Bt,{value:I.value,children:I.label},I.value))]}),P.some(I=>I.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(ea,{}),e.jsxs(Vr,{children:[e.jsx(vn,{children:"Local branches"}),P.filter(I=>I.group==="local").map(I=>e.jsx(Bt,{value:I.value,children:I.label},I.value))]})]}),P.some(I=>I.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(ea,{}),e.jsxs(Vr,{children:[e.jsx(vn,{children:"Remote branches"}),P.filter(I=>I.group==="remote").map(I=>e.jsx(Bt,{value:I.value,children:I.label},I.value))]})]})]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Setup commands"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Run automatically when a new worktree is created. Use ",e.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_WORKTREE_PATH"})," for the project root."]})]}),b?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((I,W)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{value:I,onChange:F=>B(W,F.target.value),onBlur:se,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{V(W),setTimeout(oe,0)},className:"flex-shrink-0 flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(Wt,{className:"h-4 w-4"})})]},W)),e.jsxs("button",{type:"button",onClick:H,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(qt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Existing worktrees"}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{sideOffset:8,className:"max-w-xs",children:["Worktrees created under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})," directory. Deleting a worktree will also remove any linked sessions."]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Manage worktrees for this project"})]}),M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):k.length===0?e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["No worktrees found under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})]}):e.jsx("div",{className:"space-y-1",children:k.map(I=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-sidebar-accent/30 transition-colors group",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-meta text-foreground truncate",children:I.label||I.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:I.relativePath||I.path})]}),e.jsx("button",{type:"button",onClick:()=>Y(I),className:"flex-shrink-0 flex h-7 w-7 items-center justify-center rounded text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete worktree ${I.branch||I.label}`,children:e.jsx(qs,{className:"h-4 w-4"})})]},I.path))})]})]}):e.jsx("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:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})]})})},cj=({section:s})=>{const{isMobile:r}=Rt(),t=r&&Xi();if(!s)return e.jsxs(mt,{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(Ml,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(ff,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(mf,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(cf,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(dj,{});case"chat":return e.jsx(uj,{});case"sessions":return e.jsx(mj,{});case"worktree":return e.jsx(lj,{});default:return null}};return e.jsx(mt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},dj=()=>e.jsx(Ml,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),uj=()=>e.jsx(Ml,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),mj=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(ff,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(mf,{})})]}),fj=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"worktree",label:"Worktree",items:["Branch","Setup"]}],pj=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=Rt(),n=t&&Xi(),[o,a]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),i=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const l=o?"bg-transparent":i?"bg-background":"bg-sidebar";return e.jsxs("div",{className:T("flex h-full flex-col",l),children:[e.jsx(mt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:fj.map(d=>{const u=s===d.id;return e.jsx("div",{className:T("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(cf,{})})]})},hj=(()=>{const s=nf.filter(n=>n.id!=="sessions"),r=s.find(n=>n.id==="settings"),t=s.filter(n=>n.id!=="settings");return r?[r,...t]:s})(),ci=200,di=500,gj=264,xj=700,Bi=({onClose:s,forceMobile:r})=>{const t=Rt(),n=r??t.isMobile,[o,a]=c.useState("settings"),[i,l]=c.useState("visual"),[d,u]=c.useState(!1),[m,f]=c.useState(()=>typeof window<"u"?Math.min(di,Math.max(ci,Math.floor(window.innerWidth*.2))):gj),[p,g]=c.useState(!1),[b,h]=c.useState(!1),[j,y]=c.useState(0),x=c.useRef(null),v=c.useRef(0),N=c.useRef(m),[w,k]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),D=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=c.useMemo(()=>Ht(),[]);c.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{const I=x.current;if(!I)return;const W=new ResizeObserver(F=>{for(const $ of F)y($.contentRect.width)});return W.observe(I),y(I.clientWidth),()=>W.disconnect()},[]);const C=Ft(I=>I.projects),S=Ft(I=>I.activeProjectId),A=Ft(I=>I.setActiveProject),E=c.useMemo(()=>[...C].sort((I,W)=>(I.label||I.path).localeCompare(W.label||W.path)),[C]),R=c.useMemo(()=>E.length===0?null:E.find(I=>I.id===S)??E[0],[S,E]),_=c.useCallback(I=>I.replace(/[-_]/g," ").replace(/\b\w/g,W=>W.toUpperCase()),[]),P=c.useMemo(()=>{if(!R)return"Project";const I=R.label&&R.label.trim().length>0?R.label:R.path.split("/").filter(Boolean).pop()||R.path;return _(I)},[R,_]),O=E.length>0,J=j===0||j>=xj;c.useEffect(()=>{if(o==="agents"){setTimeout(()=>{Fr.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{Tr.getState().loadCommands()},0);return}o==="skills"&&(Hs.getState().loadSkills(),no.getState().loadCatalog())},[S,o]),c.useEffect(()=>{if(typeof window>"u")return;const I=()=>{if(!p){const W=Math.min(di,Math.max(ci,Math.floor(window.innerWidth*.2)));f(W)}};return window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[p]),c.useEffect(()=>{if(!b)return;const I=F=>{const $=F.clientX-v.current,z=Math.min(di,Math.max(ci,N.current+$));f(z),g(!0)},W=()=>h(!1);return window.addEventListener("pointermove",I),window.addEventListener("pointerup",W,{once:!0}),()=>{window.removeEventListener("pointermove",I),window.removeEventListener("pointerup",W)}},[b]);const K=I=>{h(!0),v.current=I.clientX,N.current=m,I.preventDefault()},L=c.useCallback(async I=>{if(!I.target.closest("button, a, input, select, textarea")&&I.button===0&&w)try{const{getCurrentWindow:W}=await rs(async()=>{const{getCurrentWindow:$}=await import("./vendor-.bun-C07YQe9X.js").then(z=>z.ct);return{getCurrentWindow:$}},__vite__mapDeps([0,1]));await W().startDragging()}catch(W){console.error("Failed to start window dragging:",W)}},[w]),G=c.useCallback(async I=>{if(I.button===0&&w)try{const{getCurrentWindow:W}=await rs(async()=>{const{getCurrentWindow:$}=await import("./vendor-.bun-C07YQe9X.js").then(z=>z.ct);return{getCurrentWindow:$}},__vite__mapDeps([0,1]));await W().startDragging()}catch(W){console.error("Failed to start window dragging:",W)}},[w]),B=c.useCallback(I=>{a(I),u(!1)},[]),H=c.useCallback(()=>{n&&u(!0)},[n]),V=()=>{switch(o){case"settings":return e.jsx(pj,{selectedSection:i,onSelectSection:I=>{l(I),H()}});case"agents":return e.jsx(C0,{onItemSelect:H});case"commands":return e.jsx(R0,{onItemSelect:H});case"skills":return e.jsx(O0,{onItemSelect:H});case"providers":return e.jsx(K0,{onItemSelect:H});case"git-identities":return e.jsx(sj,{onItemSelect:H});default:return null}},oe=()=>{switch(o){case"agents":return e.jsx(F0,{});case"commands":return e.jsx(_0,{});case"skills":return e.jsx(G0,{});case"providers":return e.jsx(Z0,{});case"git-identities":return e.jsx(nj,{});case"settings":return e.jsx(cj,{section:i});default:return null}},se=Zt(),Y=c.useMemo(()=>w&&D?"pl-[5.75rem]":"",[w,D]),le=w&&D;return e.jsxs("div",{ref:x,className:T("flex h-full flex-col overflow-hidden",w?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:L,className:T("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&Y,w?"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(wh,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:T("flex items-center",n?"gap-1":"h-full"),children:[!n&&le&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),hj.map(({id:I,label:W,icon:F})=>{const $=o===I,z=F;return n?e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{onClick:()=>B(I),className:T("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",$?"text-foreground":"text-muted-foreground"),"aria-pressed":$,"aria-label":W,children:e.jsx(z,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(rt,{children:e.jsx("p",{children:W})})]},I):e.jsxs(c.Fragment,{children:[e.jsxs("button",{onClick:()=>B(I),onMouseDown:$?G:void 0,className:T("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",$?"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",$?"text-foreground":"text-muted-foreground"),"aria-pressed":$,"aria-label":W,children:[e.jsx(z,{className:"h-4 w-4",weight:"regular"}),J&&e.jsx("span",{children:W})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},I)})]}),(s||O)&&e.jsxs("div",{className:T("flex items-center gap-2",n?"":"pr-3"),children:[O&&e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:P,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(ir,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:P,className:T("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 text-foreground outline-none hover:text-foreground/80 focus-visible:ring-2 focus-visible:ring-ring",!n&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:P}),e.jsx(Et,{className:"size-4 opacity-50"})]})}),e.jsx(Gt,{align:"end",className:"w-auto",children:e.jsx(sm,{value:R?.id??"",onValueChange:I=>{I&&A(I)},children:E.map(I=>{const W=I.label?.trim()?I.label.trim():I.path.split("/").filter(Boolean).pop()||I.path,F=_(W);return e.jsx(rm,{value:I.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:F})},I.id)})})})]}),s&&e.jsxs(nt,{delayDuration:500,children:[e.jsx(ot,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",className:T("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(Wt,{className:"h-5 w-5"})})}),e.jsx(rt,{children:e.jsxs("p",{children:["Close Settings (",se,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:n?d?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(is,{children:oe()})}):e.jsx("div",{className:T("flex-1 overflow-hidden",M?"bg-background":"bg-sidebar"),children:e.jsx(is,{children:V()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:T("relative overflow-hidden border-r",w?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":M?"bg-background":"bg-sidebar",b?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:T("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",b?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:K,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(is,{children:V()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(is,{children:oe()})})]})})]})},yj=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=$e(),{isMobile:m}=Rt(),[f,p]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");c.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),Ab({enabled:!0});const g=ua(y=>y.checkForUpdates);c.useEffect(()=>{const y=setTimeout(()=>{g()},3e3);return()=>clearTimeout(y)},[g]),c.useEffect(()=>{$e.getState().isMobile!==m&&t(m)},[m,t]),c.useEffect(()=>{if(typeof window>"u")return;let y;const x=()=>{y!==void 0&&window.clearTimeout(y),y=window.setTimeout(()=>{$e.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x),y!==void 0&&window.clearTimeout(y)}},[]),c.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const y=document.documentElement;let x=0,v=!1,N=0,w=null;const k=$e.getState().setKeyboardOpen,D=()=>{w&&(w.style.setProperty("--oc-keyboard-avoid-offset","0px"),w.removeAttribute("data-keyboard-avoid-active"),w=null)},M=_=>{if(!_)return null;const P=_.closest("[data-keyboard-avoid]");if(P)return P;if(_.classList.contains("overlay-scrollbar-container")){const O=_.parentElement;if(O instanceof HTMLElement)return O}return _},C=()=>{x=0,v=!0,y.style.setProperty("--oc-keyboard-inset","0px"),k(!1)},S=()=>{const _=window.visualViewport,P=_?Math.round(_.height):window.innerHeight,O=_?Math.max(0,Math.round(_.offsetTop)):0;y.style.setProperty("--oc-visual-viewport-offset-top",`${O}px`);const J=document.activeElement,K=J?.tagName,G=K==="INPUT"||K==="TEXTAREA"||K==="SELECT"||!!J?.isContentEditable,B=Math.round(y.clientHeight||window.innerHeight),H=P+O,V=Math.max(0,B-H),se=V>=(G?120:180)?V:0;if(v)se===0&&(v=!1),x=0;else if(x===0)se>0&&G&&(x=se);else{const le=!G&&P>N+6;se===0?(x=0,k(!1)):le?C():(se>0&&G||se>x)&&(x=se,k(!0))}y.style.setProperty("--oc-keyboard-inset",`${x}px`),N=P;const Y=G?M(J):null;if(!m||!Y||!J)D();else{Y!==w&&(D(),w=Y);const le=O+P,W=J.getBoundingClientRect().bottom-le,F=8,$=Math.max(x,se),z=W>F&&$>0?Math.min(W,$):0,X=w;X&&(X.style.setProperty("--oc-keyboard-avoid-offset",`${z}px`),X.setAttribute("data-keyboard-avoid-active","true"))}if(m&&G){const le=document.scrollingElement;le&&le.scrollTop!==0&&(le.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};S();const A=window.visualViewport;A?.addEventListener("resize",S),A?.addEventListener("scroll",S),window.addEventListener("resize",S),window.addEventListener("orientationchange",S);const E=_=>{const P=_.target;if(!P)return;const O=P.tagName;(O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||P.isContentEditable)&&(v=!1),S()};document.addEventListener("focusin",E,!0);const R=_=>{const P=_.target;if(!P)return;const O=P.tagName;if(O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||P.isContentEditable){const K=_.relatedTarget,L=K?.tagName;if(L==="INPUT"||L==="TEXTAREA"||L==="SELECT"||K?.isContentEditable)return;C()}};return document.addEventListener("focusout",R,!0),()=>{A?.removeEventListener("resize",S),A?.removeEventListener("scroll",S),window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S),document.removeEventListener("focusin",E,!0),document.removeEventListener("focusout",R,!0),D()}},[m]);const b=c.useMemo(()=>{switch(r){case"git":return e.jsx(l0,{});case"diff":return e.jsx(Hy,{});case"terminal":return e.jsx(w0,{});default:return null}},[r]),h=r==="chat",j=a&&!m;return e.jsx(bb,{children:e.jsxs("div",{className:T("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(ab,{}),e.jsx(cb,{}),e.jsx(pb,{}),m?e.jsxs(e.Fragment,{children:[!(a||l)&&e.jsx(Cc,{}),e.jsx("div",{className:T("flex flex-1 overflow-hidden bg-background",(a||l)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:T("absolute inset-0",!h&&"invisible"),children:e.jsx(is,{children:e.jsx($i,{})})}),b&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(is,{children:b})})]})}),e.jsx(ws,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Ei,{mobileVariant:!0})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(is,{children:e.jsx(Uc,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(is,{children:e.jsx(Bi,{onClose:()=>i(!1)})})})]}):e.jsxs(e.Fragment,{children:[!j&&e.jsx(tb,{isOpen:s,isMobile:m,children:e.jsx(Ei,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:T("absolute inset-0 flex flex-col",(j||l)&&"invisible"),children:[e.jsx(Cc,{}),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:T("absolute inset-0",!h&&"invisible"),children:e.jsx(is,{children:e.jsx($i,{})})}),b&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(is,{children:b})})]})})]}),l&&e.jsx("div",{className:T("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(is,{children:e.jsx(Uc,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),j&&e.jsx("div",{className:T("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(is,{children:e.jsx(Bi,{onClose:()=>i(!1)})})})]}),!j&&e.jsx(Qy,{})]})})},bj=550,wj=()=>{const[s,r]=c.useState("chat"),[t,n]=c.useState(0),o=c.useRef(null),a=ue(D=>D.currentSessionId),i=ue(D=>D.sessions),l=ue(D=>!!D.newSessionDraft?.open),d=ue(D=>D.openNewSessionDraft),[u,m]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),f=st(D=>D.isInitialized),p=st(D=>D.initializeApp),g=ue(D=>D.loadSessions),b=ue(D=>D.loadMessages),h=ue(D=>D.messages),[j,y]=c.useState(()=>f),[x,v]=c.useState(!1),N=c.useRef(0);c.useEffect(()=>{a&&r("chat")},[a]),c.useEffect(()=>{!a&&!l&&d()},[a,l,d]);const w=c.useCallback(()=>{r("sessions")},[]);c.useEffect(()=>{const D=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&m(D);const M=C=>{const A=C.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&m(A)};return window.addEventListener("openchamber:connection-status",M),()=>window.removeEventListener("openchamber:connection-status",M)},[]),c.useEffect(()=>{const D=M=>{const S=M.detail?.view;S==="settings"?r("settings"):S==="chat"?r("chat"):S==="sessions"&&r("sessions")};return window.addEventListener("openchamber:navigate",D),()=>window.removeEventListener("openchamber:navigate",D)},[]),c.useEffect(()=>{(async()=>{if(x||j||u!=="connected")return;const M=Date.now();if(!(M-N.current<750)){N.current=M,v(!0);try{const C=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();C&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:f}),f||await p();const S=st.getState();if(!S.isInitialized||!S.isConnected||S.providers.length===0||S.agents.length===0)return;await g();const A=ue.getState().error;if(C&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:S.providers.length,agents:S.agents.length,sessions:ue.getState().sessions.length,sessionsError:A}),typeof A=="string"&&A.length>0)return;y(!0)}catch{}finally{v(!1)}}})()},[u,f,j,p,x,g]),c.useEffect(()=>{(async()=>{if(!j||u!=="connected"||s!=="chat"||l||!a)return;if(!(h.has(a)&&(h.get(a)?.length||0)>0))try{await b(a)}catch{}})()},[u,a,s,j,b,h,l]),c.useEffect(()=>{const D=o.current;if(!D)return;const M=new ResizeObserver(C=>{for(const S of C)n(S.contentRect.width)});return M.observe(D),n(D.clientWidth),()=>M.disconnect()},[]);const k=t>0&&t<bj;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(zd,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ei,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>r("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):s==="settings"?e.jsx(Bi,{onClose:()=>r("sessions"),forceMobile:k}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(zd,{title:l&&!a?"New session":i.find(D=>D.id===a)?.title||"Chat",showBack:!0,onBack:w,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(is,{children:e.jsx($i,{})})})]})})},zd=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:i,showContextUsage:l})=>{const{getCurrentModel:d}=st(),u=ue(h=>h.getContextUsage),m=d(),f=m?.limit&&typeof m.limit=="object"?m.limit:null,p=typeof f?.context=="number"?f.context:0,g=typeof f?.output=="number"?f.output:0,b=u(p,g);return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border bg-background shrink-0",children:[r&&t&&e.jsx("button",{onClick:t,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(pu,{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(qt,{className:"h-5 w-5"})}),a&&e.jsx("button",{onClick:a,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Agent Manager",children:e.jsx(Qn,{className:"h-5 w-5"})}),i&&e.jsx(Di,{headerIconButtonClass:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"}),o&&e.jsx("button",{onClick:o,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Settings",children:e.jsx(qr,{className:"h-5 w-5"})}),l&&b&&b.totalTokens>0&&e.jsx(Mi,{totalTokens:b.totalTokens,percentage:b.percentage,contextLimit:b.contextLimit,outputLimit:b.outputLimit??0,size:"compact"})]})},zi=".openchamber",Co=s=>{const r=Ft.getState(),t=r.activeProjectId,n=t?r.projects.find(l=>l.id===t)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof s=="string"?Dt(s):"",a=`/${zi}/`,i=o.indexOf(a);return i>0?o.slice(0,i):s?Dt(s):null},Dt=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Wd=s=>{const r=Dt(s);return!r||r==="/"?`/${zi}`:`${r}/${zi}`},vj=(s,r)=>{const t=Dt(s);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const i=Dt(o);if(i)return i}const a=typeof n.name=="string"?n.name.trim():"";return!a||!t?null:`${t}/${a}`}).filter(n=>!!n)},jj=async s=>{const r=Dt(s);if(!r)return[];try{const n=(await ke.listLocalDirectory(r)).filter(o=>o.isDirectory);return vj(r,n)}catch{return[]}},Nr=(s,r)=>{const t=Dt(s),n=Dt(r);if(!t||!n)return!1;if(t===n)return!0;const o=n==="/"?"/":`${n}/`;return t.startsWith(o)},pf=async(s,r)=>{const t=Dt(r);if(!t)return t;try{const n=await s.path.get({directory:t});return Dt(n.data?.directory??"")||t}catch{return t}},hf=async(s,r)=>{const t=Dt(r);if(!t)return[];const n=await pf(s,t),o=i=>i.filter(l=>{const d=Dt(l.directory??"");return d?Nr(d,t)||n!==t&&Nr(d,n):!1}),a=async i=>{const l=await s.session.list({directory:i});return Array.isArray(l.data)?l.data:[]};try{const i=o(await a(t));if(i.length>0)return i}catch{}if(n&&n!==t)try{const i=o(await a(n));if(i.length>0)return i}catch{}try{const i=await s.session.list(void 0),l=Array.isArray(i.data)?i.data:[];return o(l)}catch{return[]}},Sj=async(s,r)=>{const t=new Map;s.sessions.forEach(o=>{o.worktreeMetadata&&t.set(Dt(o.path),o.worktreeMetadata)});const n=Array.from(new Set(s.sessions.map(o=>Dt(o.path)))).filter(Boolean).filter(o=>!t.has(o));if(n.length===0)return t;try{const o=await Sn(r),a=new Map(o.map(i=>[Dt(i.worktree),i]));n.forEach(i=>{const l=a.get(i);l&&t.set(i,kn(r,l))})}catch{}return t},ui=async s=>{const{apiClient:r,group:t,projectDirectory:n,worktreePaths:o}=s,a=await Sj(t,n),i=ue.getState(),l=Array.from(new Set(o.map(p=>Dt(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<l.length;){const p=l[u];u+=1;const g=t.sessions.filter(x=>Dt(x.path)===p).map(x=>x.id),b=i.getSessionsByDirectory(p),h=Array.isArray(b)?b.map(x=>x.id):[];let j=[];if(h.length===0)try{j=(await hf(r,p)).map(v=>v.id)}catch{j=[]}const y=Array.from(new Set([...h,...j,...g].filter(Boolean)));m.push({worktreePath:p,sessionIds:y,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,l.length)},f)),m};function kj(s){if(!s)return null;const r=s.split("/");if(r.length<3)return null;const t=r[0];if(!t||t.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),i=r.length>=4&&!isNaN(a)&&String(a)===o,l=i?r.slice(2,-1):r.slice(2);if(l.length===0)return null;const d=l.join("/");return{groupSlug:t,provider:n,model:d,index:i?a:1}}const Mr=zt()(Kt((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=dt.getState().currentDirectory,n=Co(t);if(!n){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Dt(n),a=Wd(o),i=r().groups;s({isLoading:!0,error:null});try{const l=ke.getApiClient(),d=await pf(l,o),u=Wd(d);let m=new Map,f=[];try{f=await Sn(o),m=new Map(f.map(v=>[Dt(v.worktree),v]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const N=await l.session.list({directory:o}),w=Array.isArray(N.data)?N.data:[];if(w.some(k=>{const D=Dt(k.directory??"");return Nr(D,a)||Nr(D,u)}))return w}catch{}const v=await l.session.list(void 0);return Array.isArray(v.data)?v.data:[]},g=async v=>{const N=new Map,w=5;let k=0;const D=async()=>{for(;k<v.length;){const M=v[k];k+=1;const C=Dt(M);if(C)try{(await hf(l,C)).forEach(A=>N.set(A.id,A))}catch(S){console.debug("Failed to fetch sessions from worktree:",C,S)}}};return await Promise.all(Array.from({length:Math.min(w,v.length)},D)),Array.from(N.values())};let h=(await p()).filter(v=>{const N=Dt(v.directory??"");return N?Nr(N,a)||Nr(N,u):!1});if(h.length===0){const v=new Set;f.map(w=>Dt(w.worktree)).filter(w=>Nr(w,a)||Nr(w,u)).forEach(w=>v.add(w));const N=Array.from(new Set([a,u].map(w=>Dt(w)).filter(Boolean)));await Promise.all(N.map(async w=>{(await jj(w)).forEach(D=>v.add(D))})),v.size>0&&(h=await g(Array.from(v)))}const j=new Map;for(const v of h){const N=v.time?.updated??0;j.set(v.id,typeof N=="number"?N:0)}const y=new Map;for(const v of h){const N=kj(v.title);if(!N)continue;const w=Dt(v.directory),k=m.get(w),D={id:v.id,path:w,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:k?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:k?kn(o,k):void 0},M=y.get(N.groupSlug);M?M.push(D):y.set(N.groupSlug,[D])}const x=Array.from(y.entries()).map(([v,N])=>{const w=N.reduce((k,D)=>{const M=j.get(D.id)??0;return Math.max(k,M)},0);return{name:v,sessions:N.sort((k,D)=>{const M=k.providerId.localeCompare(D.providerId);if(M!==0)return M;const C=k.modelId.localeCompare(D.modelId);return C!==0?C:k.instanceNumber-D.instanceNumber}),lastActive:w||Date.now(),sessionCount:N.length}});x.sort((v,N)=>v.name.localeCompare(N.name)),s({groups:x,isLoading:!1,error:null})}catch(l){console.error("Failed to load agent groups:",l),s({groups:i.length>0?i:[],isLoading:!1,error:l instanceof Error?l.message:"Failed to load agent groups"})}},selectGroup:t=>{const{groups:n}=r(),o=n.find(a=>a.name===t);s({selectedGroupName:t,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:t=>{s({selectedSessionId:t})},deleteGroup:async t=>{const n=r().groups.find(i=>i.name===t);if(!n)return!1;const o=dt.getState().currentDirectory,a=Co(o);if(!a)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const i=ke.getApiClient(),l=await ui({apiClient:i,group:n,projectDirectory:Dt(a),worktreePaths:n.sessions.map(f=>f.path)}),d=ue.getState(),u=new Set;l.forEach(({worktreePath:f,sessionIds:p,metadata:g})=>{p.forEach(b=>{u.add(b),g&&(d.setWorktreeMetadata(b,g),d.setSessionDirectory(b,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&s({error:"Failed to delete some sessions"}),r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(i){return s({error:i instanceof Error?i.message:"Failed to delete group"}),!1}finally{s({isLoading:!1})}},deleteGroupWorktree:async(t,n)=>{const o=r().groups.find(d=>d.name===t);if(!o)return!1;const a=Dt(n);if(!a)return!1;const i=dt.getState().currentDirectory,l=Co(i);if(!l)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const d=ke.getApiClient(),u=await ui({apiClient:d,group:o,projectDirectory:Dt(l),worktreePaths:[a]}),m=ue.getState(),f=new Set;u.forEach(({worktreePath:b,sessionIds:h,metadata:j})=>{h.forEach(y=>{f.add(y),j&&(m.setWorktreeMetadata(y,j),m.setSessionDirectory(y,b))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups();const g=r().groups.find(b=>b.name===t);if(!g)return r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===t){const b=r().selectedSessionId,h=new Set(g.sessions.map(j=>j.id));(!b||!h.has(b))&&s({selectedSessionId:g.sessions[0]?.id??null})}return p.length===0}catch(d){return s({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{s({isLoading:!1})}},keepOnlyGroupWorktree:async(t,n)=>{const o=r().groups.find(m=>m.name===t);if(!o)return!1;const a=Dt(n);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(m=>Dt(m.path)).filter(Boolean))).filter(m=>m!==a);if(l.length===0)return!0;const d=dt.getState().currentDirectory,u=Co(d);if(!u)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const m=ke.getApiClient(),f=await ui({apiClient:m,group:o,projectDirectory:Dt(u),worktreePaths:l}),p=ue.getState(),g=new Set;f.forEach(({worktreePath:h,sessionIds:j,metadata:y})=>{j.forEach(x=>{g.add(x),y&&(p.setWorktreeMetadata(x,y),p.setSessionDirectory(x,h))})});const{failedIds:b}=await p.deleteSessions(Array.from(g),{archiveWorktree:!0,silent:!0});if(b.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===t){const h=r().groups.find(y=>y.name===t),j=h?.sessions.find(y=>Dt(y.path)===a)??h?.sessions[0]??null;s({selectedSessionId:j?.id??null})}return b.length===0}catch(m){return s({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{s({isLoading:!1})}},getSelectedGroup:()=>{const{groups:t,selectedGroupName:n}=r();return n?t.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:t}=r(),n=r().getSelectedGroup();return!n||!t?null:n.sessions.find(o=>o.id===t)??null},clearError:()=>{s({error:null})}}),{name:"agent-groups-store"})),Nj=s=>{const t=Date.now()-s,n=Math.floor(t/(60*1e3)),o=Math.floor(t/(3600*1e3)),a=Math.floor(t/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},Cj=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=c.useState(!1),[a,i]=c.useState(!1),[l,d]=c.useState(!1),u=Mr(f=>f.deleteGroup),m=c.useCallback(async()=>{if(l)return;if(d(!0),ne.info(`Deleting "${s.name}"...`),await u(s.name))ne.success(`Deleted "${s.name}"`);else{const p=Mr.getState().error;ne.error(p||`Failed to delete "${s.name}"`)}d(!1),i(!1)},[u,s.name,l]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),onClick:t,children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col gap-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[e.jsx($t,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:Nj(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(Ut,{open:n,onOpenChange:o,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:T("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:f=>f.stopPropagation(),children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsx(Gt,{align:"end",className:"min-w-[140px]",children:e.jsx(kt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),i(!0)},children:"Delete"})})]})})]})}),e.jsx(ms,{open:a,onOpenChange:i,children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Delete agent group"}),e.jsxs(Ns,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"outline",onClick:()=>i(!1),disabled:l,children:"Cancel"}),e.jsx(Ne,{variant:"destructive",onClick:()=>{m()},disabled:l,children:l?"Deleting…":"Delete"})]})]})})]})},Mj=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=c.useState(""),[i,l]=c.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Mr(),f=dt(j=>j.currentDirectory);c.useEffect(()=>{f&&m()},[f,m]);const p=5,g=c.useMemo(()=>{if(!o.trim())return d;const j=o.toLowerCase();return d.filter(y=>y.name.toLowerCase().includes(j))},[o,d]),b=i?g:g.slice(0,p),h=g.length-p;return e.jsxs("div",{className:T("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",s),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ht,{value:o,onChange:j=>a(j.target.value),placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e.jsx("div",{className:"px-2.5 pb-2",children:e.jsxs(Ne,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(qt,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label",children:"New Agent Group"})]})}),e.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[e.jsx(Et,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),u&&e.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."})]}),e.jsxs(mt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[b.map(j=>e.jsx(Cj,{group:j,isSelected:r===j.name,onSelect:()=>t?.(j.name)},j.name)),!i&&h>0&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",h,")"]}),i&&g.length>p&&e.jsx("button",{type:"button",onClick:()=>l(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&g.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},Dj=10*1024*1024,Aj=5,Ej=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=c.useState(""),[a,i]=c.useState(""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState("HEAD"),[g,b]=c.useState([]),[h,j]=c.useState(!1),[y,x]=c.useState([]),[v,N]=c.useState(!1),[w,k]=c.useState(!1),D=c.useRef(null),M=c.useRef(null),C=dt(Y=>Y.currentDirectory??null),{isGitRepository:S,isLoading:A}=jl(C),E=c.useMemo(()=>{if(typeof window>"u")return null;const Y=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof Y=="string"&&Y.trim().length>0?Y.trim():null},[]),R=c.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),_=Ft(Y=>Y.activeProjectId),P=Ft(Y=>Y.projects),O=c.useMemo(()=>{if(R&&E)return E;if(_){const F=P.find($=>$.id===_);if(F?.path)return F.path}const Y=C??E;if(!Y)return null;const le=Y.replace(/\\/g,"/").replace(/\/+$/,"")||Y,W=le.indexOf("/.openchamber/");return W>0?le.slice(0,W):le.endsWith("/.openchamber")?le.slice(0,le.length-13):le},[_,P,C,E,R]);c.useEffect(()=>{if(!O)return;let Y=!1;return k(!0),(async()=>{try{const le=await oo(O);Y||x(le)}catch{}finally{Y||k(!1)}})(),()=>{Y=!0}},[O]);const J=c.useCallback(Y=>{l.length>=Aj||d(le=>[...le,Y])},[l.length]),K=c.useCallback(Y=>{d(le=>le.filter((I,W)=>W!==Y))},[]),L=c.useCallback((Y,le)=>{d(I=>I.map((W,F)=>F===Y?le:W))},[]),G=async Y=>{const le=Y.target.files;if(!le)return;let I=0;for(let W=0;W<le.length;W++){const F=le[W];if(F.size>Dj){ne.error(`File "${F.name}" is too large (max 10MB)`);continue}try{const $=await new Promise((X,fe)=>{const ve=new FileReader;ve.onload=()=>X(ve.result),ve.onerror=fe,ve.readAsDataURL(F)}),z={id:ta(),filename:F.name,mimeType:F.type||"application/octet-stream",size:F.size,dataUrl:$};b(X=>[...X,z]),I++}catch($){console.error("File attach failed",$),ne.error(`Failed to attach "${F.name}"`)}}I>0&&ne.success(`Attached ${I} file${I>1?"s":""}`),D.current&&(D.current.value="")},B=Y=>{b(le=>le.filter(I=>I.id!==Y))},H=h||t,V=!!(n.trim()&&a.trim()&&l.length>=1&&S&&!A),oe=async Y=>{if(Y.preventDefault(),!(!V||H)){j(!0);try{const le=l.map(({providerID:F,modelID:$,displayName:z,variant:X})=>({providerID:F,modelID:$,displayName:z,variant:X})),I=g.length>0?g.map(F=>({mime:F.mimeType,filename:F.filename,url:F.dataUrl})):void 0,W=y.filter(F=>F.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:le,agent:u||void 0,worktreeBaseBranch:f,files:I,setupCommands:W.length>0?W:void 0}),o(""),i(""),d([]),m(""),b([]),p("HEAD")}catch(le){console.error("Failed to create agent group:",le),ne.error("Failed to create agent group")}finally{j(!1)}}},se=Y=>{wl(Y)||Y.key==="Enter"&&!Y.shiftKey&&(Y.preventDefault(),V&&!H&&oe(Y))};return e.jsx("div",{className:T("flex flex-col items-center justify-center h-full w-full p-4",s),children:e.jsxs("form",{onSubmit:oe,className:"w-full max-w-2xl space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:"Group Name"}),e.jsx(ht,{id:"group-name",value:n,onChange:Y=>o(Y.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[e.jsx($t,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(km,{directory:C,value:f,onChange:p}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from ",e.jsx("code",{className:"font-mono text-xs",children:f})]})]}),e.jsxs(xa,{open:v,onOpenChange:N,children:[e.jsxs(bl,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",y.filter(Y=>Y.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",y.filter(Y=>Y.trim()).length," configured)"]})]}),e.jsx(Et,{className:T("h-4 w-4 text-muted-foreground transition-transform duration-200",v&&"rotate-180")})]}),e.jsx(ya,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),w?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[y.map((Y,le)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{value:Y,onChange:I=>{const W=[...y];W[le]=I.target.value,x(W)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const I=y.filter((W,F)=>F!==le);x(I)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(Wt,{className:"h-4 w-4"})})]},le)),e.jsxs("button",{type:"button",onClick:()=>x([...y,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(qt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(Nm,{value:u,onChange:m}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Models"}),e.jsx(Sm,{selectedModels:l,onAdd:J,onRemove:K,onUpdate:L,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-input/10 dark:bg-input/30 overflow-hidden",children:[e.jsx(Ts,{ref:M,id:"prompt",value:a,onChange:Y=>i(Y.target.value),onKeyDown:se,placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),g.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:g.map(Y=>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:[Y.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:Y.filename,children:Y.filename}),e.jsx("button",{type:"button",onClick:()=>B(Y.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Wt,{className:"h-3.5 w-3.5"})})]},Y.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:D,type:"file",multiple:!0,className:"hidden",onChange:G,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>D.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(lu,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length," model",l.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!V||H,className:T("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",V?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:H?e.jsx(vh,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(iu,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},Ij=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Mr(),{setCurrentSession:i,currentSessionId:l}=ue(),[d,u]=c.useState(null),[m,f]=c.useState(!1),p=c.useMemo(()=>t?s.sessions.find(v=>v.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),g=c.useCallback(v=>{n(v.id),i(v.id)},[n,i]);c.useEffect(()=>{if(s.sessions.length>0){const v=t?s.sessions.find(N=>N.id===t)??s.sessions[0]:s.sessions[0];v&&(v.id!==l&&i(v.id),t||n(v.id))}},[s.name,s.sessions,t,l,n,i]);const b=p?.id===l,h=c.useCallback(()=>{if(!p?.path){ne.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{ne.success("Worktree path copied")}).catch(()=>{ne.error("Failed to copy path")})},[p?.path]),j=c.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),y=c.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),x=c.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(ne.info("Removing worktree..."),await o(s.name,d.path))ne.success("Worktree removed");else{const N=Mr.getState().error;ne.error(N||"Failed to remove worktree");return}else if(ne.info("Removing other worktrees..."),await a(s.name,d.path))ne.success("Removed other worktrees");else{const N=Mr.getState().error;ne.error(N||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,s.name,m,a,d]);return e.jsxs("div",{className:T("flex h-full flex-col bg-background",r),children:[e.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($t,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),s.sessions.length>0&&e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"outline",className:"w-full justify-between h-10 px-3",children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:p&&e.jsxs(e.Fragment,{children:[e.jsx(ns,{providerId:p.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsx("span",{className:"truncate typography-body",children:p.modelId}),p.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",p.instanceNumber]})]})}),e.jsx(Et,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Gt,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:s.sessions.map(v=>e.jsxs(kt,{onClick:()=>g(v),className:"flex items-center gap-2 py-2",children:[e.jsx(ns,{providerId:v.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate typography-body",children:v.modelId}),v.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",v.instanceNumber]})]}),v.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx($t,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:v.worktreeMetadata?.label||v.branch})]})]}),p?.id===v.id&&e.jsx(Tt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},v.id))})]})}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Ir,{className:"h-4 w-4"})})}),e.jsxs(Gt,{align:"end",className:"min-w-[220px]",children:[e.jsx(kt,{onSelect:v=>{v.preventDefault(),j()},variant:"destructive",children:"Remove this worktree"}),e.jsx(kt,{onSelect:v=>{v.preventDefault(),y()},children:"Leave this one, remove others"}),e.jsxs(kt,{onClick:v=>{v.stopPropagation(),h()},disabled:!p?.path,children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(ms,{open:!!d,onOpenChange:v=>{v||u(null)},children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Ns,{children:d?.kind==="remove"?e.jsxs(e.Fragment,{children:["Remove ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):e.jsxs(e.Fragment,{children:["Keep ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label})," and remove the other worktrees in ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"."]})})]}),e.jsxs(Ks,{children:[e.jsx(Ne,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Ne,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{x()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?b?e.jsx(Jm,{sessionId:p.id,children:e.jsx(Xm,{})}):e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:"px-4 py-2 bg-muted/30 border-b border-border/30",children:e.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(ns,{providerId:p.providerId,className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel}),e.jsx("span",{children:"·"}),e.jsx("span",{className:"font-mono text-xs truncate",children:p.path})]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center p-8",children:[e.jsxs("p",{className:"typography-body text-muted-foreground mb-2",children:["Loading session for ",e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground/60",children:["Session ID: ",p.id]})]})})]}):e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("p",{className:"typography-body text-muted-foreground",children:"No sessions in this group"})})})]})},Pj=({className:s})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[t,n]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=st(v=>v.isInitialized),a=st(v=>v.initializeApp),i=ue(v=>v.loadSessions),l=dt(v=>v.setDirectory),d=c.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Mr(),{createMultiRun:g,isLoading:b}=qn();c.useEffect(()=>{if(!r)return;const v=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(v==="connected"||v==="connecting"||v==="error"||v==="disconnected")&&n(v);const N=w=>{const D=w.detail?.status;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&n(D)};return window.addEventListener("openchamber:connection-status",N),()=>window.removeEventListener("openchamber:connection-status",N)},[r]),c.useEffect(()=>{if(!r||t!=="connected")return;const v=Date.now();if(v-d.current<750)return;d.current=v;const N=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof N=="string"&&N.trim().length>0)try{l(N,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const k=st.getState();if(!k.isInitialized||!k.isConnected||k.providers.length===0||k.agents.length===0)return;await i(),Qt()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:k.providers.length,agents:k.agents.length,sessions:ue.getState().sessions.length})}catch{}})()},[t,o,a,r,i,l]);const h=c.useCallback(v=>{m(v)},[m]),j=c.useCallback(()=>{m(null)},[m]),y=c.useCallback(async v=>{ne.info(`Creating agent group "${v.name}" with ${v.models.length} model(s)...`);const N=await g(v);if(N){ne.success(`Agent group "${v.name}" created with ${N.sessionIds.length} session(s)`);const w=N.groupSlug,k=async(D=6)=>{for(let M=0;M<D;M+=1){if(await p(),Mr.getState().groups.some(S=>S.name===w))return!0;await new Promise(S=>setTimeout(S,500))}return!1};try{await ue.getState().loadSessions()}catch{}await k(),m(w)}else{const w=qn.getState().error;ne.error(w||"Failed to create agent group")}},[g,p,m]),x=f();return e.jsxs("div",{className:T("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(Mj,{selectedGroupName:u,onGroupSelect:h,onNewAgent:j})}),e.jsx("div",{className:"flex-1 min-w-0",children:x?e.jsx(Ij,{group:x}):e.jsx(Ej,{onCreateGroup:y,isCreating:b})})]})},mi=({...s})=>{const{theme:r="system"}=jh();return e.jsx(Sh,{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})},Tj=(s=5e3)=>{const[r,t]=Ce.useState(null);return Ce.useEffect(()=>{if(!as())return;let n=!1,o=null;const a=async()=>{const i=await Hh();n||(t(i),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},Fj=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=ue(),l=Tj(4e3),d=c.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=c.useMemo(()=>r.map(f=>{const p=t.get(f.id)?.length||0,g=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:g?.isStreaming||!1,isZombie:g?.isZombie||!1,backgroundCount:g?.backgroundMessageCount||0,lastAccessed:g?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,t,n,o]),m=t.size;return e.jsxs(xl,{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(kh,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:s,children:e.jsx(Wt,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Messages"}),e.jsx("div",{className:"typography-markdown font-semibold",children:d})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Cached Sessions"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[m," / ",us.MAX_SESSIONS]})]})]}),l&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:l.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[l.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:l.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[us.VIEWPORT_MESSAGES," messages"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Background Stream Limit:"}),e.jsxs("span",{children:[us.BACKGROUND_STREAMING_BUFFER," messages"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Zombie Timeout:"}),e.jsxs("span",{children:[us.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]})]}),e.jsxs("div",{className:"border-t pt-2",children:[e.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e.jsx(mt,{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(Nh,{className:"h-3 w-3 text-primary animate-pulse"}),f.isZombie&&e.jsx("span",{className:"text-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${f.messageCount>us.VIEWPORT_MESSAGES?"text-warning":""}`,children:[f.messageCount," msgs"]}),f.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",f.backgroundCount]})]})]},f.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsxs(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(qs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(rt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(rt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(nt,{delayDuration:1e3,children:[e.jsx(ot,{asChild:!0,children:e.jsx(Ne,{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(rt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},Rj="openchamber-message-cursors",Dn="cursors",_j=1,gf="openchamber.messageCursors",Dl=()=>typeof window<"u",Al=()=>Dl()&&typeof indexedDB<"u",xf=()=>Al()?new Promise((s,r)=>{const t=indexedDB.open(Rj,_j);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Dn)||n.createObjectStore(Dn)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),yf=()=>{if(!Dl())return{};try{const s=window.localStorage.getItem(gf);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},Oj=s=>{if(Dl())try{window.localStorage.setItem(gf,JSON.stringify(s))}catch{}},$j=async(s,r,t)=>{if(!s||!r)return;if(Al())try{const o=await xf();await new Promise((a,i)=>{const l=o.transaction(Dn,"readwrite");l.objectStore(Dn).put({messageId:r,completedAt:t},s),l.oncomplete=()=>a(),l.onerror=()=>i(l.error??new Error("Cursor write failed")),l.onabort=()=>i(l.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=yf();n[s]={messageId:r,completedAt:t},Oj(n)},Lj=async s=>{if(!s)return null;if(Al())try{const t=await xf(),n=await new Promise((o,a)=>{const i=t.transaction(Dn,"readonly"),d=i.objectStore(Dn).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 yf()[s]??null},Bj=50,zj=750,Hd=new WeakMap,Ud=s=>{if(!s||!Array.isArray(s))return 0;const r=Hd.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 Hd.set(s,t),t},Wj=10,Vd=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<Wj?null:n},Gd=(s,r)=>{const t=Vd(s),n=Vd(r);return!t||!n||t.length!==n.length?!0:t>n},Wi=new Map,qd=(s,r)=>{const t=`${s}:${r}`,n=Wi.get(t);if(n&&n.sessionId===s)return n.message;const i=(ue.getState().messages.get(s)||[]).find(l=>l.info.id===r)||null;return Wi.set(t,{sessionId:s,message:i}),i},Hj=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:i,currentSessionId:l,applySessionMetadata:d,sessions:u,getWorktreeMetadata:m,loadMessages:f,loadSessions:p,updateSession:g,removeSessionFromStore:b}=ue(),{checkConnection:h}=st(),j=dt(q=>q.currentDirectory),y=c.useMemo(()=>{if(!l)return;try{const re=m?.(l);if(re?.path)return re.path}catch(re){console.warn("Failed to inspect worktree metadata for session directory:",re)}const q=u.find(re=>re.id===l);if(q&&typeof q.directory=="string"&&q.directory.trim().length>0)return q.directory.trim()},[l,m,u]),x=c.useMemo(()=>{if(y&&y.length>0)return y;if(typeof j=="string"&&j.trim().length>0)return j.trim()},[y,j]);c.useEffect(()=>{let q=!1;const re=async()=>{try{const he=await ke.listPendingPermissions();if(q||he.length===0)return;he.forEach(ye=>{o(ye)})}catch{}},Ve=async()=>{try{const ye=Ft.getState().projects.map(Te=>Te.path),Le=u.map(Te=>Te.directory),Qe=[x,...ye,...Le],Ee=await ke.listPendingQuestions({directories:Qe});if(q||Ee.length===0)return;Ee.forEach(Te=>{a(Te)})}catch{}};return re(),Ve(),()=>{q=!0}},[o,a,x,u]);const v=c.useCallback(q=>{if(typeof q!="string")return null;const re=q.trim();if(!re)return null;const Ve=re.replace(/\\/g,"/");return Ve.length>1?Ve.replace(/\/+$/,""):Ve},[]),N=c.useCallback(q=>{if(!q)return null;try{const Ve=m?.(q),he=v(Ve?.path??null);if(he)return he}catch{}const re=u.find(Ve=>Ve.id===q);return v(re?.directory??null)},[m,v,u]),w=$e(q=>q.setEventStreamStatus),k=c.useRef(null),D=c.useCallback((q,re)=>{const Ve=re??null,he=k.current;if(!(he&&he.status===q&&he.hint===Ve)){if(k.current={status:q,hint:Ve},Qt()){const Le={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[q]??"[INFO]",Qe=Ve?`${Le} SSE ${q}: ${Ve}`:`${Le} SSE ${q}`;console.info(Qe)}w(q,Ve)}},[w]),M=c.useCallback((q,re)=>{if(!q)return Promise.resolve();const Ve=Date.now();if(K.current)return K.current;if(Ve-L.current<zj)return Promise.resolve();const he=f(q).catch(ye=>{console.warn(`[useEventStream] Failed to resync messages (${re}):`,ye)}).finally(()=>{K.current=null,L.current=Date.now()});return K.current=he,he},[f]),C=c.useCallback(async q=>{Qt()&&console.info("[useEventStream] Bootstrapping state:",q);try{await Promise.all([p(),l?M(l,q):Promise.resolve()])}catch(re){console.warn("[useEventStream] Bootstrap failed:",q,re)}},[l,p,M]),S=c.useCallback((q,re,Ve)=>{Qt()&&console.debug(`[MessageTracker] ${q}: ${re}`,Ve)},[]),A=c.useCallback(q=>{Qt()&&console.debug(`[MessageTracker] ${q}: reported`)},[]),E=c.useRef(null),R=c.useRef(null),_=c.useRef(0);c.useRef(new Set);const P=c.useRef(new Map),O=c.useRef(null),J=c.useRef(!1),K=c.useRef(null),L=c.useRef(0),G=c.useRef(new Set),B=c.useRef(new Set),H=c.useCallback(()=>{if(typeof document>"u")return"visible";const q=document.visibilityState;return q==="hidden"&&document.hasFocus()?"visible":q},[]),V=c.useRef(H()),oe=c.useRef(typeof navigator>"u"?!0:navigator.onLine),se=c.useRef(!1),Y=c.useRef(null),le=c.useRef(null),I=c.useRef(Date.now()),W=c.useRef(!1),F=c.useCallback(q=>{const re=Date.now();re-I.current>25e3&&(C(q),I.current=re)},[C]);c.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(W.current=!0)},[]);const $=c.useRef(new Map),z=c.useRef(new Map),X=c.useRef(0),fe=c.useRef(null),ve=c.useRef(l),ge=c.useRef(null),Re=c.useRef(null);c.useEffect(()=>{ve.current=l},[l]);const be=c.useCallback((q,re)=>{if(!q)return;const Ve=Date.now(),he=P.current,ye=he.get(q);if(ye&&Ve-ye<3e3)return;he.set(q,Ve);const Le=Qe=>{if(typeof re=="string"&&re.trim().length>0)return re.trim();try{const Te=m?.(Qe);if(Te?.path)return Te.path}catch{}const Ee=u.find(Te=>Te.id===Qe);return Ee&&typeof Ee.directory=="string"&&Ee.directory.trim().length>0?Ee.directory.trim():null};setTimeout(async()=>{try{const Qe=Le(q),Ee=Qe?await ke.withDirectory(Qe,()=>ke.getSession(q)):await ke.getSession(q);if(Ee){const Te={};typeof Ee.title=="string"&&Ee.title.length>0&&(Te.title=Ee.title),Ee.summary!==void 0&&(Te.summary=Ee.summary),Object.keys(Te).length>0&&d(q,Te)}}catch(Qe){console.warn("Failed to refresh session metadata:",Qe)}},100)},[d,m,u]),Ie=c.useCallback((q,re)=>{if(ue.getState().sessionActivityPhase?.get(q)===re){z.current=new Map(ue.getState().sessionActivityPhase??new Map);return}const he=$.current.get(q);he&&(clearTimeout(he),$.current.delete(q));const ye=new Map(ue.getState().sessionActivityPhase??new Map);if(ye.set(q,re),z.current=ye,ue.setState({sessionActivityPhase:ye}),re==="cooldown"){const Le=setTimeout(()=>{if($.current.delete(q),ue.getState().sessionActivityPhase?.get(q)==="cooldown"){const Ee=new Map(ue.getState().sessionActivityPhase??new Map);Ee.set(q,"idle"),z.current=Ee,ue.setState({sessionActivityPhase:Ee})}},2e3);$.current.set(q,Le)}},[]),U=c.useCallback(async()=>{const q=Date.now();if(fe.current)return fe.current;if(q-X.current<1500)return;X.current=q;const re=he=>{const ye=new Set,Le=new Set(u.map(Ee=>Ee.id));Object.entries(he).forEach(([Ee,Te])=>{if(!Ee||!Te)return;ye.add(Ee);const Ye=Te.type==="busy"||Te.type==="retry"?"busy":"idle";Ie(Ee,Ye)});const Qe=ue.getState().sessionActivityPhase;if(Qe)for(const[Ee,Te]of Qe.entries())Le.has(Ee)&&(Te==="busy"||Te==="cooldown")&&!ye.has(Ee)&&Ie(Ee,"idle")},Ve=(async()=>{try{const he=await ke.getGlobalSessionStatus();if(he&&Object.keys(he).length>0){re(he);return}const ye=new Set;u.forEach(Ye=>{const jt=N(Ye.id);jt&&ye.add(jt)});const Le=v(x??null);Le&&ye.add(Le);const Qe=Array.from(ye);if(Qe.length===0){const Ye=await ke.getSessionStatus();Ye&&re(Ye);return}const Ee=await Promise.allSettled(Qe.map(Ye=>ke.getSessionStatusForDirectory(Ye))),Te={};if(Ee.forEach(Ye=>{Ye.status!=="fulfilled"||!Ye.value||Object.assign(Te,Ye.value)}),Object.keys(Te).length===0&&Array.from(ue.getState().sessionActivityPhase?.values?.()??[]).some(jt=>jt==="busy"||jt==="cooldown")&&!await ke.checkHealth().catch(()=>!1))return;re(Te)}catch{}})().finally(()=>{fe.current=null});return fe.current=Ve,Ve},[x,v,N,u,Ie]);c.useEffect(()=>{const q=l??null,re=ge.current,Ve=N(q),he=Re.current;re&&q&&re!==q&&he&&Ve&&he!==Ve&&U(),ge.current=q,Re.current=Ve},[l,U,N]);const Q=c.useCallback(q=>{if(I.current=Date.now(),Qt()&&console.debug("[useEventStream] Received event:",q.type,q.properties),!q.properties)return;const re=q.properties;if(!new Set(["session.abort","session.error"]).has(q.type)){const he=(typeof re.session=="object"&&re.session!==null?re.session:null)||(typeof re.sessionInfo=="object"&&re.sessionInfo!==null?re.sessionInfo:null);if(he){const ye=he,Le=typeof ye.id=="string"&&ye.id.length>0?ye.id:typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:typeof re.id=="string"&&re.id.length>0?re.id:void 0;if(Le){const Qe=typeof ye.title=="string"?ye.title:typeof re.title=="string"?re.title:void 0,Ee=typeof ye.summary=="object"&&ye.summary!==null?ye.summary:typeof re.summary=="object"&&re.summary!==null?re.summary:void 0;if(Qe!==void 0||Ee!==void 0){const Te={};Qe!==void 0&&(Te.title=Qe),Ee!==void 0&&(Te.summary=Ee),d(Le,Te)}}}}switch(q.type){case"server.connected":h();break;case"global.disposed":case"server.instance.disposed":{C("server_disposed_event");break}case"openchamber:session-activity":{const he=typeof re.sessionId=="string"?re.sessionId:null,ye=typeof re.phase=="string"?re.phase:null;he&&(ye==="idle"||ye==="busy"||ye==="cooldown")&&(Ie(he,ye),be(he,typeof re.directory=="string"?re.directory:null));break}case"mcp.tools.changed":{const he=typeof re.directory=="string"?re.directory:x;Bn.getState().refresh({directory:he??null,silent:!0});break}case"session.status":if(W.current)break;{const he=typeof re.sessionID=="string"?re.sessionID:null,ye=typeof re.status=="object"&&re.status!==null?re.status:null,Le=typeof ye?.type=="string"?ye.type:null;he&&Le&&(Ie(he,Le==="busy"||Le==="retry"?"busy":"idle"),be(he,typeof re.directory=="string"?re.directory:null))}break;case"message.part.updated":{const he=typeof re.part=="object"&&re.part!==null?re.part:null;if(!he)break;const ye=he,Le=typeof re.info=="object"&&re.info!==null?re.info:re,Qe=typeof Le.sessionID=="string"?Le.sessionID:null,Ee=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof Qe=="string"&&Qe.length>0?Qe:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:null,Te=typeof Le.id=="string"?Le.id:null,Ye=typeof ye.messageID=="string"&&ye.messageID.length>0?ye.messageID:typeof Te=="string"&&Te.length>0?Te:typeof re.messageID=="string"&&re.messageID.length>0?re.messageID:null;if(!Ee||!Ye){Qt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ye.sessionID??Qe??re.sessionID,messageID:ye.messageID??Te??re.messageID});break}const jt=Ee,ft=Ye,It=ue.getState().sessionMemoryState.get(jt)?.trimmedHeadMaxId;if(It&&!Gd(ft,It)){Qt()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:jt,messageId:ft,trimmedHeadMaxId:It});break}let _t="assistant";if(Le&&typeof Le.role=="string")_t=Le.role;else{const je=qd(jt,ft);if(je){const _e=je.info.role;typeof _e=="string"&&(_t=_e)}}if(S(ft,"part_received",{role:_t}),_t==="user"&&ye.synthetic===!0){S(ft,"skipped_synthetic_user_part");break}const Nt={...he,type:he.type||"text"};S(ft,"addStreamingPart_called"),s(jt,ft,Nt,_t);break}case"message.updated":{const he=typeof re.info=="object"&&re.info!==null?re.info:re,ye=he,Le=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:null,Qe=typeof ye.id=="string"&&ye.id.length>0?ye.id:typeof re.messageID=="string"&&re.messageID.length>0?re.messageID:null;if(!Le||!Qe){Qt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ye.sessionID??re.sessionID,messageID:ye.id??re.messageID});break}const Ee=Le,Te=Qe,Ye=ue.getState().sessionMemoryState.get(Ee)?.trimmedHeadMaxId;if(Ye&&!Gd(Te,Ye)){Qt()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Ee,messageId:Te,trimmedHeadMaxId:Ye});break}if(W.current&&Qt())try{const ct=re.parts||ye.parts||[],St=(Array.isArray(ct)?ct.filter(Z=>Z?.type==="text"):[]).map(Z=>{const xe=Z;return typeof xe?.text=="string"?xe.text:typeof xe?.content=="string"?xe.content:""}).join(`
107
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Te,role:ye.role,status:ye.status,textLen:St.length,textPreview:St.slice(0,120),partsCount:Array.isArray(ct)?ct.length:0})}catch{}if(S(Te,"message_updated",{role:ye.role}),ye.role==="user"){const ct=re.parts||ye.parts,it=Array.isArray(ct)?ct:[],St={...he,userMessageMarker:!0,clientRole:"user"};if(t(Ee,Te,St),it.length>0)for(let Z=0;Z<it.length;Z++){const xe=it[Z];if(xe.synthetic===!0)continue;const de={...xe,type:xe?.type||"text",sessionID:xe?.sessionID||Ee,messageID:xe?.messageID||Te};s(Ee,Te,de,"user")}S(Te,"user_message_created_from_event",{partsCount:it.length});break}const jt=qd(Ee,Te),ft=Ud(jt?.parts||[]),It=jt?.info?.finish==="stop",_t=re.parts||ye.parts,Nt=Array.isArray(_t)?_t:[],je=Nt.length>0,Ge=typeof(ye.time||{})?.completed=="number";if(!je&&!Ge)break;const at=he.finish,Mt=typeof at=="string"?at:null,Yt=Mt==="stop";if(ye.role==="assistant"&&je){const ct=Ud(Nt);if(ft>0&&ct+Bj<ft&&!Yt){S(Te,"skipped_shrinking_update",{incomingLen:ct,existingLen:ft});break}if(W.current){const St=ft>0&&ct<ft,Z=Nt.some(de=>{if(!de||de.type!=="text")return!1;const Oe=de;return typeof Oe.text=="string"&&Oe.text.length>0});if(St&&!(Yt&&Z)){S(Te,"desktop_shrinking_update_suppressed",{incomingLen:ct,existingLen:ft});break}}}if(t(Ee,Te,he),je&&ye.role!=="user"){const St=(ue.getState().messages.get(Ee)||[]).find(de=>de.info.id===Te),Z=!St||St.parts.length===0;S(Te,Z?"server_parts_injected":"server_parts_refreshed",{count:Nt.length});const xe=W.current&&ye.role==="assistant"?Nt.filter(de=>de?.type!=="text"):Nt;for(let de=0;de<xe.length;de++){const Oe=xe[de],We={...Oe,type:Oe?.type||"text",sessionID:Oe?.sessionID||Ee,messageID:Oe?.messageID||Te};s(Ee,Te,We,ye.role),S(Te,`server_part_${de}`)}}const Jt=he.time,Ue=Jt?.completed,Ze=typeof Ue=="number"&&Number.isFinite(Ue),ut=Mt==="stop"||It;if(he.role==="assistant"&&(Ze||ut)&&he.role==="assistant"){const it=ue.getState().messages.get(Ee)||[];let St=null,Z="";for(let Ct=0;Ct<it.length;Ct++){const xt=it[Ct];xt.info.role==="assistant"&&xt.info.id>Z&&(Z=xt.info.id,St=xt.info.id)}if(l===Ee&&Te!==St)break;if(!ut&&W.current){S(Te,"desktop_completion_without_stop");break}const de=Ze?Ue:Date.now();Ze||t(Ee,Te,{...he,time:{...Jt??{},completed:de}}),S(Te,"completed",{timeCompleted:de}),A(Te),$j(Ee,Te,de),r(Ee,Te),W.current||Mt==="stop"&&ue.getState().sessionActivityPhase?.get(Ee)==="busy"&&Ie(Ee,"cooldown");const Oe=he.sessionID,We=typeof Oe=="string"&&Oe.length>0?Oe:Ee;be(We,typeof re.directory=="string"?re.directory:null),he.summary&&typeof We=="string"&&n(We,null)}break}case"session.created":case"session.updated":{const he=typeof re.info=="object"&&re.info!==null?re.info:typeof re.sessionInfo=="object"&&re.sessionInfo!==null?re.sessionInfo:typeof re.session=="object"&&re.session!==null?re.session:re,ye=typeof he.id=="string"&&he.id.length>0?he.id:typeof he.sessionID=="string"&&he.sessionID.length>0?he.sessionID:typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:typeof re.id=="string"&&re.id.length>0?re.id:void 0;if(ye){const Le=typeof he.time=="object"&&he.time!==null?he.time:typeof re.time=="object"&&re.time!==null?re.time:null,Qe=Le&&typeof Le.compacting=="number"?Le.compacting:null;n(ye,Qe);const Ee=typeof he.directory=="string"?he.directory:typeof re.directory=="string"?re.directory:null,Te={...he,id:ye,...Ee?{directory:Ee}:{}};g(Te)}break}case"session.deleted":{const he=typeof re.sessionID=="string"?re.sessionID:typeof re.id=="string"?re.id:null;he&&b(he);break}case"session.abort":{const he=typeof re.sessionID=="string"&&re.sessionID.length>0?re.sessionID:null,ye=typeof re.messageID=="string"&&re.messageID.length>0?re.messageID:null;he&&ye&&r(he,ye);break}case"permission.asked":{if(!("sessionID"in re)||typeof re.sessionID!="string")break;const he=re;o(he);const ye=`${he.sessionID}:${he.id}`;G.current.has(ye)||setTimeout(()=>{if(ve.current===he.sessionID||!ue.getState().permissions.get(he.sessionID)?.some(Te=>Te.id===he.id))return;G.current.add(ye);const Ee=ue.getState().sessions.find(Te=>Te.id===he.sessionID)?.title||"Session";rs(async()=>{const{toast:Te}=await import("./vendor-.bun-C07YQe9X.js").then(Ye=>Ye.cs);return{toast:Te}},__vite__mapDeps([0,1])).then(({toast:Te})=>{Te.warning("Permission required",{description:Ee,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),ue.getState().setCurrentSession(he.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in re)||typeof re.sessionID!="string")break;const he=re;a(he);const ye=`${he.sessionID}:${he.id}`;B.current.has(ye)||setTimeout(()=>{if(ve.current===he.sessionID||!ue.getState().questions.get(he.sessionID)?.some(Te=>Te.id===he.id))return;B.current.add(ye);const Ee=ue.getState().sessions.find(Te=>Te.id===he.sessionID)?.title||"Session";rs(async()=>{const{toast:Te}=await import("./vendor-.bun-C07YQe9X.js").then(Ye=>Ye.cs);return{toast:Te}},__vite__mapDeps([0,1])).then(({toast:Te})=>{Te.info("Input needed",{description:Ee,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),ue.getState().setCurrentSession(he.sessionID)}}})})},0);break}case"question.replied":{const he=typeof re.sessionID=="string"?re.sessionID:null,ye=typeof re.requestID=="string"?re.requestID:null;he&&ye&&i(he,ye);break}case"todo.updated":{const he=typeof re.sessionID=="string"?re.sessionID:null,ye=Array.isArray(re.todos)?re.todos:null;he&&ye&&qb(he,ye);break}}},[l,s,r,t,o,a,i,h,be,n,d,S,A,Ie,g,b,C,x]),te=c.useCallback(()=>{const q=H();return V.current=q,q==="visible"&&oe.current},[H]),pe=c.useCallback(()=>{Qt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:W.current,hasUnsubscribe:!!E.current,currentSessionId:ve.current,effectiveDirectory:x,onlineStatus:oe.current,visibilityState:V.current,lastEventTimestamp:I.current,reconnectAttempts:_.current})},[x]),me=c.useCallback(async()=>!0,[]),Me=c.useCallback(()=>{if(J.current){Qt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(J.current=!0,R.current&&(clearTimeout(R.current),R.current=null),E.current){const q=E.current;E.current=null;try{q()}catch(re){console.warn("[useEventStream] Error during unsubscribe:",re)}}J.current=!1},[]),Se=c.useCallback(async q=>{if(pe(),!te()){se.current=!0,oe.current?D("paused","Paused while hidden"):D("offline","Waiting for network");return}W.current&&(await me()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),q?.resetAttempts&&(_.current=0),Me(),I.current=Date.now(),D("connecting",null),Qt()&&console.info("[useEventStream] Starting event stream...");const re=he=>{console.warn("Event stream error:",he)},Ve=()=>{const he=se.current;if(_.current=0,se.current=!1,I.current=Date.now(),D("connected",null),h(),Array.from(ue.getState().sessionActivityPhase?.values?.()??[]).some(Le=>Le==="busy"||Le==="cooldown")&&U(),he)C("sse_reconnected");else{const Le=ve.current;Le&&setTimeout(()=>{M(Le,"sse_reconnected").then(()=>be(Le)).catch(Qe=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Qe)})},0)}};if(Qt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:x,isCleaningUp:J.current}),J.current){Qt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const he=ke.subscribeToGlobalEvents(Le=>{const Qe=Le.payload,Ee=Le.payload,Te=typeof Ee.properties=="object"&&Ee.properties!==null?Ee.properties:{},Ye=Le.directory&&Le.directory!=="global"?{...Te,directory:Le.directory}:Te;Q({type:typeof Qe.type=="string"?Qe.type:"",properties:Ye})},re,Ve),ye=()=>{try{he()}catch(Le){console.warn("[useEventStream] Error during unsubscribe:",Le)}};J.current?ye():E.current=ye}catch(he){console.error("[useEventStream] Error during subscription:",he),re(he)}},[te,Me,D,h,M,be,Q,x,U,me,pe,C]),Pe=c.useCallback(q=>{if(!te()){se.current=!0,Me(),oe.current?D("paused","Paused while hidden"):D("offline","Waiting for network");return}const re=_.current+1;_.current=re;const Ve=q??`Retrying (${re})`;D("reconnecting",Ve);const he=re<=3?Math.min(1e3*Math.pow(2,re-1),8e3):Math.min(2e3*Math.pow(2,re-3),32e3),ye=Math.floor(Math.random()*250),Le=he+ye;R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{Se({resetAttempts:!1})},Le)},[te,Me,D,Se]);c.useEffect(()=>{const q=$.current;typeof window<"u"&&(window.__messageTracker=S);let re=null;W.current&&typeof window<"u"&&(re=Ye=>{const jt=typeof Ye.detail?.sessionId=="string"?Ye.detail.sessionId:null,ft=typeof Ye.detail?.phase=="string"?Ye.detail.phase:null;jt&&(ft==="idle"||ft==="busy"||ft==="cooldown")&&(Ie(jt,ft),be(jt))},window.addEventListener("openchamber:session-activity",re));const Ve=()=>{Y.current&&(clearTimeout(Y.current),Y.current=null)},he=()=>{Y.current||(Y.current=setTimeout(()=>{const Ye=H();V.current=Ye,Ye!=="visible"?(Me(),se.current=!0,D("paused","Paused while hidden")):Ve()},5e3))},ye=()=>{if(V.current=H(),V.current==="visible"){if(Ve(),F("visibility_restore"),se.current||!E.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ye=ve.current;Ye&&(M(Ye,"visibility_restore").catch(()=>{}),be(Ye)),U(),D("connecting","Resuming stream"),Se({resetAttempts:!0})}}else D("paused","Paused while hidden"),he()},Le=()=>{if(V.current=H(),V.current==="visible"&&(Ve(),F("window_focus"),se.current||!E.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ye=ve.current;Ye&&(be(Ye),M(Ye,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(jt=>console.warn("[useEventStream] Failed to refresh messages:",jt))),U(),D("connecting","Resuming stream"),Se({resetAttempts:!0})}},Qe=()=>{oe.current=!0,F("network_restored"),(se.current||!E.current)&&(D("connecting","Network restored"),Se({resetAttempts:!0}))},Ee=()=>{oe.current=!1,se.current=!0,D("offline","Waiting for network"),Me()};typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",Qe),window.addEventListener("offline",Ee),window.addEventListener("focus",Le));const Te=setTimeout(()=>{Se({resetAttempts:!0})},100);return le.current&&clearInterval(le.current),le.current=setInterval(()=>{if(!te())return;const Ye=Date.now();Array.from(ue.getState().sessionActivityPhase?.values?.()??[]).some(ft=>ft==="busy"||ft==="cooldown")&&U(),Ye-I.current>25e3&&Promise.resolve().then(async()=>{try{await ke.checkHealth()?I.current=Date.now():Pe("Refreshing stalled stream")}catch(ft){console.warn("Health check after stale stream failed:",ft),Pe("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Te),re&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",re),typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",Qe),window.removeEventListener("offline",Ee),window.removeEventListener("focus",Le)),Ve(),le.current&&(clearInterval(le.current),le.current=null),q.forEach(Ye=>clearTimeout(Ye)),q.clear(),Wi.clear(),se.current=!1,V.current=H(),oe.current=typeof navigator>"u"?!0:navigator.onLine,Me(),O.current&&(clearTimeout(O.current),O.current=null),D("idle",null)}},[x,S,H,Me,D,Se,Pe,f,be,Ie,U,te,p,F,M])},Uj=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=ue(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:l,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=$e(),{themeMode:p,setThemeMode:g}=nn(),{working:b}=_m(),h=c.useRef(null),j=c.useRef(null),y=c.useRef(!1),x=c.useCallback(()=>{j.current&&(clearTimeout(j.current),j.current=null),h.current=null,n()},[n]);c.useEffect(()=>{const v=N=>{if(Cs(N)&&N.key==="k"&&(N.preventDefault(),a()),Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const k=tn()?.diagnostics;if(!k||(N.preventDefault(),y.current))return;y.current=!0,k.downloadLogs().then(({fileName:D,content:M})=>{const C=D||"openchamber.log",S=new Blob([M],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),E=document.createElement("a");E.href=A,E.download=C,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(A)}).finally(()=>{y.current=!1});return}if(Cs(N)&&N.key==="."&&(N.preventDefault(),i()),Cs(N)&&N.key.toLowerCase()==="n"){if(N.preventDefault(),st.getState().settingsAutoCreateWorktree?!N.shiftKey:N.shiftKey){u("chat"),d(!1),ha();return}u("chat"),d(!1),s()}if(Cs(N)&&N.key==="/"){N.preventDefault();const w=["light","dark","system"],D=(w.indexOf(p)+1)%w.length;g(w[D])}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:w,setTimelineDialogOpen:k}=$e.getState();k(!w);return}if(Cs(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:w}=$e.getState();m(!w);return}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:w,isSessionSwitcherOpen:k}=$e.getState();w?d(!k):l();return}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:w,isCommandPaletteOpen:k,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:S,isModelSelectorOpen:A}=$e.getState();if(w||k||D||M||C||!(S==="chat"))return;N.preventDefault(),f(!A);return}if(Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:w,isCommandPaletteOpen:k,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:S}=$e.getState();if(w||k||D||M||C||!(S==="chat"))return;const R=st.getState();if(R.getCurrentModelVariants().length===0)return;N.preventDefault(),R.cycleCurrentVariant();const P=st.getState().currentVariant,O=ue.getState(),J=O.currentSessionId,K=st.getState().currentAgentName,L=st.getState().currentProviderId,G=st.getState().currentModelId;J&&K&&L&&G&&O.saveAgentModelVariantForSession(J,K,L,G,P);return}if(N.key==="Escape"){const{isSettingsDialogOpen:w,isCommandPaletteOpen:k,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:S}=$e.getState();if(w){N.preventDefault(),m(!1),x();return}if(k||D||M||C||!(S==="chat")){x();return}const R=o;if(!(b.canAbort&&!!R)){x();return}const P=Date.now(),O=h.current;if(O&&P<O){N.preventDefault(),x(),r();return}N.preventDefault();const J=t(3e3)??P+3e3;h.current=J,j.current&&clearTimeout(j.current);const K=Math.max(J-P,0);j.current=setTimeout(()=>{h.current&&Date.now()>=h.current&&x()},K||0);return}};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[s,r,a,i,l,d,u,m,f,g,p,b,t,x,o]),c.useEffect(()=>()=>{x()},[x])},Kd="openchamber:menu-action",Vj=s=>{const{openNewSessionDraft:r}=ue(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:i,setSettingsDialogOpen:l,setAboutDialogOpen:d}=$e(),{addProject:u}=Ft(),{requestAccess:m,startAccessing:f}=ga(),{setThemeMode:p}=nn(),g=c.useRef(!1),b=c.useCallback(()=>{as()?m("").then(async h=>{if(!h.success||!h.path){h.error&&h.error!=="Directory selection cancelled"&&ne.error("Failed to select directory",{description:h.error});return}const j=await f(h.path);if(!j.success){ne.error("Failed to open directory",{description:j.error||"Desktop could not grant file access."});return}u(h.path,{id:h.projectId})||ne.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(h=>{console.error("Desktop: Error selecting directory:",h),ne.error("Failed to select directory")}):Cn.requestDirectoryDialog()},[u,m,f]);c.useEffect(()=>{const h=j=>{switch(j.detail){case"about":d(!0);break;case"settings":l(!0);break;case"command-palette":t();break;case"new-session":i("chat"),a(!1),r();break;case"new-worktree-session":i("chat"),a(!1),ha();break;case"change-workspace":b();break;case"open-git-tab":{const{activeMainTab:x}=$e.getState();i(x==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:x}=$e.getState();i(x==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:x}=$e.getState();i(x==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":s?.();break;case"help-dialog":n();break;case"download-logs":{const v=tn()?.diagnostics;if(!v||g.current)break;g.current=!0,v.downloadLogs().then(({fileName:N,content:w})=>{const k=N||"openchamber.log",D=new Blob([w],{type:"text/plain;charset=utf-8"}),M=URL.createObjectURL(D),C=document.createElement("a");C.href=M,C.download=k,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(M),ne.success("Logs saved",{description:`Downloaded to ~/Downloads/${k}`})}).catch(()=>{ne.error("Failed to download logs")}).finally(()=>{g.current=!1});break}}};return window.addEventListener(Kd,h),()=>window.removeEventListener(Kd,h)},[r,t,n,o,a,i,l,d,p,s,b])},Gj=s=>s.role==="assistant",Yd=s=>{const r=s.info;if(!Gj(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},Wo=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},Qd=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Vn(n)).join(" ").replace(/\s+/g," ").trim(),qj=(s,r)=>{if(!s||!Wo(s.info))return-1;const t=Qd(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((i,l)=>{if(!Wo(i.info))return;const d=Qd(i),u=!!(t&&d&&d===t),m=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=l,a=p);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=l,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(i=>{if(!Wo(i.info))return!1;const l=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof l!="number"?!1:Math.abs(l-n)<1e3}):-1},Kj=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=ue(),n=c.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=c.useRef(void 0),a=c.useRef(0),i=c.useCallback(async()=>{if(!s||n)return;const l=Date.now();if(!(l-a.current<2e3)){a.current=l;try{const d=r.get(s)||[],u=await ke.getSessionMessages(s),m=await Lj(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(h=>h.info.id===f.info.id),b=p===-1?qj(f,u):p;if(b!==-1)if(b<u.length-1){const h=u.slice(b+1);console.log(`[SYNC] Found ${h.length} new messages to append`);const j=[...d,...h],{syncMessages:y}=ue.getState();y(s,j)}else{const h=u[b],j=d[d.length-1],y=Yd(h),x=Yd(j);if(y&&!x){console.log("[SYNC] Last message completed on server");const v=[...d.slice(0,-1),h],{syncMessages:N}=ue.getState();N(s,v)}}else if(Wo(f.info)){const h=u.slice(-us.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:j}=ue.getState();j(s,h)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(m){const p=u.findIndex(g=>g.info.id===m.messageId);if(p!==-1){if(p<u.length-1){const b=u.slice(p+1).slice(-us.VIEWPORT_MESSAGES);if(b.length>0){console.log(`[SYNC] Restoring ${b.length} messages after cursor`);const{syncMessages:h}=ue.getState();h(s,b)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const g=u.slice(-us.VIEWPORT_MESSAGES),{syncMessages:b}=ue.getState();b(s,g)}}else if(u.length>0){const p=u.slice(-us.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:g}=ue.getState();g(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);c.useEffect(()=>{const l=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",l),()=>window.removeEventListener("focus",l)},[i]),c.useEffect(()=>{if(!s||n)return;const l=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(l,3e4)};return o.current=setTimeout(l,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,i]),c.useEffect(()=>{const l=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",l),()=>document.removeEventListener("visibilitychange",l)},[i])},Yj=()=>{c.useEffect(()=>{let s=!1;return(async()=>{try{const t=await ke.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,l=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,l)}),n.size>0&&ue.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function Qj(){const{git:s}=In(),r=dt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=ue(),{setActiveDirectory:a,startPolling:i,stopPolling:l,fetchAll:d}=Xt(),u=c.useMemo(()=>{const m=t?o.get(t)??void 0:void 0,p=n.find(g=>g.id===t)?.directory??null;return m?.path??p??r??null},[t,n,o,r]);c.useEffect(()=>{if(!u||!s){l();return}return a(u),d(u,s),i(s),()=>{l()}},[u,s,a,i,l,d])}function Xj({children:s}){return Qj(),e.jsx(e.Fragment,{children:s})}const Jj=()=>{const[{isUpdating:s,message:r},t]=c.useState(()=>dg());return c.useEffect(()=>cg(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(kl,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Zj=({open:s,onOpenChange:r})=>{const[t,n]=c.useState(null);c.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:l}=await rs(async()=>{const{getVersion:u}=await import("./vendor-.bun-C07YQe9X.js").then(m=>m.cu);return{getVersion:u}},__vite__mapDeps([0,1])),d=await l();n(d)}catch{n("1.4.7")}})():n("1.4.7")},[s]);const o=t;return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsx(fs,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(kl,{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(wi,{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(yu,{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(vi,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:"Made with love to comunity"})]})})})};function fi({apis:s,children:r}){return e.jsx(ul.Provider,{value:s,children:r})}const eS="curl -fsSL https://opencode.ai/install | bash",tS=3e3;function sS({onCopy:s}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:s,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Gs,{className:"h-4 w-4"})})]})}const rS=3e4;function nS({onCliAvailable:s}){const[r,t]=c.useState(!1),[n,o]=c.useState(!1),[a,i]=c.useState(!1);c.useEffect(()=>{const m=setTimeout(()=>o(!0),rS);return()=>clearTimeout(m)},[]),c.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const l=c.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await rs(async()=>{const{getCurrentWindow:g}=await import("./vendor-.bun-C07YQe9X.js").then(b=>b.ct);return{getCurrentWindow:g}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=c.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=c.useCallback(async()=>{try{await navigator.clipboard.writeText(eS),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return c.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,tS);return m(),()=>clearInterval(f)},[d,s]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:l,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(Ho,{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(Tt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(sS,{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(Ho,{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 oS=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=$e();return e.jsx(Zj,{open:s,onOpenChange:r})};function aS({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=st(),{error:o,clearError:a,loadSessions:i}=ue(),l=dt(w=>w.currentDirectory),d=dt(w=>w.isSwitchingDirectory),[u,m]=c.useState(!1),{uiFont:f,monoFont:p}=sf(),[g,b]=c.useState(()=>s.runtime.isDesktop),[h,j]=c.useState(()=>s.runtime.isVSCode),[y,x]=c.useState(()=>s.runtime.isDesktop?Uh():!0);c.useEffect(()=>{b(s.runtime.isDesktop),j(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),c.useEffect(()=>(Hl(s),()=>Hl(null)),[s]),c.useEffect(()=>{if(typeof document>"u")return;const w=document.documentElement,k=kd[f]?.stack??kd[m0].stack,D=Br[p]?.stack??Br[Bo].stack;w.style.setProperty("--font-sans",k),w.style.setProperty("--font-heading",k),w.style.setProperty("--font-family-sans",k),w.style.setProperty("--font-mono",D),w.style.setProperty("--font-family-mono",D),w.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[f,p]),c.useEffect(()=>{if(t){const k=setTimeout(()=>{const D=document.getElementById("initial-loading");D&&(D.classList.add("fade-out"),setTimeout(()=>{D.remove()},300))},150);return()=>clearTimeout(k)}},[t]),c.useEffect(()=>{const w=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!t&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},5e3);return()=>clearTimeout(w)},[t]),c.useEffect(()=>{(async()=>h||await r())()},[r,h]),c.useEffect(()=>{if(d)return;(async()=>h||n&&(ke.setDirectory(l),await i()))()},[l,d,i,n,h]),Hj(),Uj();const v=c.useCallback(()=>{m(w=>!w)},[]);Vj(v),Kj(),Yj(),uf(),c.useEffect(()=>{const w=k=>{Cs(k)&&k.shiftKey&&k.key==="D"&&(k.preventDefault(),m(D=>!D))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),c.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=c.useCallback(()=>{x(!0),window.location.reload()},[]);return g&&!y?e.jsx(is,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(nS,{onCliAvailable:N})})}):h?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(is,{children:e.jsx(fi,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Pj,{}),e.jsx(mi,{})]})})}):e.jsx(is,{children:e.jsx(fi,{apis:s,children:e.jsx(bd,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(wj,{}),e.jsx(mi,{})]})})})}):e.jsx(is,{children:e.jsx(fi,{apis:s,children:e.jsx(Xj,{children:e.jsx(bd,{children:e.jsxs("div",{className:`h-full text-foreground ${g?"bg-transparent":"bg-background"}`,children:[e.jsx(yj,{}),e.jsx(mi,{}),e.jsx(Jj,{}),e.jsx(oS,{}),u&&e.jsx(Fj,{onClose:()=>m(!1)})]})})})})})}const bf=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=dt.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},wf="/auth/session",iS=async()=>fetch(wf,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Xd=async s=>fetch(wf,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),El=({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})]}),lS=({message:s="Preparing workspace…"})=>e.jsx(El,{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})})}),cS=({onRetry:s})=>e.jsx(El,{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(Ne,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),dS=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},uS=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},mS=({children:s})=>{const r=c.useMemo(()=>as(),[]),t=c.useMemo(()=>Ht(),[]),n=r||t,[o,a]=c.useState(()=>n?"authenticated":"pending"),[i,l]=c.useState(""),[d,u]=c.useState(!1),[m,f]=c.useState(""),p=c.useRef(null),g=c.useRef(n),b=c.useRef(!1),h=c.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await iS();if(y.ok){a("authenticated"),f("");return}if(y.status===401){a("locked");return}a("error")}catch(y){console.warn("Failed to check session status:",y),a("error")}},[n]);c.useEffect(()=>{n||h()},[h,n]),c.useEffect(()=>{!n&&o==="locked"&&(g.current=!1)},[n,o]),c.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),c.useEffect(()=>{if(n||o!=="locked"||b.current||d)return;const y=dS();y&&(b.current=!0,uS(),u(!0),f(""),Xd(y).then(x=>{if(x.ok){l(""),a("authenticated");return}if(x.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(x=>{console.warn("Failed to submit URL token:",x),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),c.useEffect(()=>{n||o==="authenticated"&&!g.current&&(g.current=!0,(async()=>(await Cu(),await Mu(),await bf()))())},[n,o]);const j=async y=>{if(y.preventDefault(),!(!i||d)){u(!0),f("");try{const x=await Xd(i);if(x.ok){l(""),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(lS,{}):o==="error"?e.jsx(cS,{onRetry:()=>{h()}}):o==="locked"?e.jsx(El,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Unlock OpenChamber"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"This session is password-protected."})]}),e.jsxs("form",{onSubmit:j,className:"w-full space-y-2","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ch,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(ht,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:y=>{l(y.target.value),m&&f("")},className:"pl-10","aria-invalid":!!m||void 0,"aria-describedby":m?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(Ne,{type:"submit",size:"icon",disabled:!i||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(cs,{className:"h-4 w-4 animate-spin"}):e.jsx(Mh,{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})},pi=s=>{if(!s||typeof s!="string")return null;const r=s.trim();if(!r.startsWith("#"))return null;let t=r.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(l=>l+l).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,i=n&255;return`${o} ${a} ${i}`};class fS{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const t=[];return t.push(...this.generateTailwindVariables(r)),t.push(...this.generatePrimaryColors(r.colors.primary)),t.push(...this.generateSurfaceColors(r.colors.surface)),t.push(...this.generateInteractiveColors(r.colors.interactive)),t.push(...this.generateStatusColors(r.colors.status)),t.push(...this.generateSyntaxColors(r.colors.syntax)),t.push(...this.generateComponentColors(r.colors,r)),t.push(...this.generateTypographyVariables()),r.config&&t.push(...this.generateConfigVariables(r.config)),t.join(`
108
- `)}generateTailwindVariables(r){const t=[];t.push(` --background: ${r.colors.surface.background} !important;`),t.push(` --foreground: ${r.colors.surface.foreground} !important;`),t.push(` --muted: ${r.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --card: ${r.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${r.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${r.colors.interactive.border} !important;`),t.push(` --input: ${r.colors.interactive.border} !important;`),t.push(` --primary: ${r.colors.primary.base} !important;`),t.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --secondary: ${r.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${r.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --destructive: ${r.colors.status.error} !important;`),t.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),t.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&t.push(` --radius: ${r.config.radius.md} !important;`);const n=pi(r.colors.surface.muted),o=pi(r.colors.surface.subtle),a=pi(r.colors.interactive.border);t.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const i=r.metadata.variant==="dark",l=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${l}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,l)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return r.colors.charts?.series&&Array.isArray(r.colors.charts.series)&&r.colors.charts.series.forEach((u,m)=>{t.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(t.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(t.push(` --loading-spinner: ${r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),t}apply(r){const t=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
109
- ${t}
110
- }
111
-
112
- .dark {
113
- ${t}
114
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
115
- ${t}
116
- }
117
-
118
- :root:not(.dark) {
119
- ${t}
120
- }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",r.metadata.variant)}generatePrimaryColors(r){const t=[];return t.push(` --primary-base: ${r.base};`),t.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),t.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),t.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),t.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),t.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),t}generateSurfaceColors(r){const t=[];return t.push(` --surface-background: ${r.background};`),t.push(` --surface-foreground: ${r.foreground};`),t.push(` --surface-muted: ${r.muted};`),t.push(` --surface-muted-foreground: ${r.mutedForeground};`),t.push(` --surface-elevated: ${r.elevated};`),t.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),t.push(` --surface-overlay: ${r.overlay};`),t.push(` --surface-subtle: ${r.subtle};`),t}generateInteractiveColors(r){const t=[];return t.push(` --interactive-border: ${r.border};`),t.push(` --interactive-border-hover: ${r.borderHover};`),t.push(` --interactive-border-focus: ${r.borderFocus};`),t.push(` --interactive-selection: ${r.selection};`),t.push(` --interactive-selection-foreground: ${r.selectionForeground};`),t.push(` --interactive-focus: ${r.focus};`),t.push(` --interactive-focus-ring: ${r.focusRing};`),t.push(` --interactive-cursor: ${r.cursor};`),t.push(` --interactive-hover: ${r.hover};`),t.push(` --interactive-active: ${r.active};`),t}generateStatusColors(r){const t=[];return t.push(` --status-error: ${r.error};`),t.push(` --status-error-foreground: ${r.errorForeground};`),t.push(` --status-error-background: ${r.errorBackground};`),t.push(` --status-error-border: ${r.errorBorder};`),t.push(` --status-warning: ${r.warning};`),t.push(` --status-warning-foreground: ${r.warningForeground};`),t.push(` --status-warning-background: ${r.warningBackground};`),t.push(` --status-warning-border: ${r.warningBorder};`),t.push(` --status-success: ${r.success};`),t.push(` --status-success-foreground: ${r.successForeground};`),t.push(` --status-success-background: ${r.successBackground};`),t.push(` --status-success-border: ${r.successBorder};`),t.push(` --status-info: ${r.info};`),t.push(` --status-info-foreground: ${r.infoForeground};`),t.push(` --status-info-background: ${r.infoBackground};`),t.push(` --status-info-border: ${r.infoBorder};`),t}generateSyntaxColors(r){const t=[];t.push(` --syntax-background: ${r.base.background};`),t.push(` --syntax-foreground: ${r.base.foreground};`),t.push(` --syntax-comment: ${r.base.comment};`),t.push(` --syntax-keyword: ${r.base.keyword};`),t.push(` --syntax-string: ${r.base.string};`),t.push(` --syntax-number: ${r.base.number};`),t.push(` --syntax-function: ${r.base.function};`),t.push(` --syntax-variable: ${r.base.variable};`),t.push(` --syntax-type: ${r.base.type};`),t.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(r){const t=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(r,t){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),r.chat?n.push(...this.generateChatColors(r.chat,t)):n.push(...this.generateDefaultChatColors(t)),r.tools?n.push(...this.generateToolColors(r.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(r,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r.heading1||o};`),n.push(` --markdown-heading2: ${r.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${r.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${r.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const t=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${r.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${r.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${r.colors.interactive.border};`),t}generateChatColors(r,t){const n=[],o=r.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const t=[];return t.push(` --chat-background: ${r.colors.surface.background};`),t.push(` --chat-user-message: ${r.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),t.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${r.colors.interactive.border};`),t.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),t}generateToolColors(r,t){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const t=[];return t.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),t.push(` --tools-title: ${r.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${r.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${r.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${r.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(r){const t=[];return r&&(r.fonts&&(r.fonts.sans&&(t.push(` --font-sans: ${r.fonts.sans};`),t.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(t.push(` --font-mono: ${r.fonts.mono};`),t.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&t.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&t.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&t.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&t.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&t.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&t.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&t.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&t.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&t.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&t.push(` --transition-slow: ${r.transitions.slow};`))),t}generateTypographyVariables(){const r=[],t=Ht()?eg:Ji;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${t.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${t.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${t.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${t.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${t.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${t.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,t){return r.startsWith("#")?`${r}${Math.round(t*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,t){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),i=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${i}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${i}, ${t})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}darken(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,i=(n>>8&255)-o,l=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}lighten(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)+o,i=(n>>8&255)+o,l=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}adjustHue(r,t){return this.lighten(r,t/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const Il={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"}}},Pl={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"}}},to=[Il,Pl];function na(s){return to.find(r=>r.metadata.id===s)}const vf=Il.metadata.id,jf=Pl.metadata.id,pS=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Sf=s=>s==="dark"?Pl:Il,hS=s=>(to.find(t=>t.metadata.variant===s)??Sf(s)).metadata.id,Mo=(s,r)=>{const t=na(s);return t&&t.metadata.variant===r?t:to.find(o=>o.metadata.variant===r)??Sf(r)},gS=typeof window<"u"?c.useLayoutEffect:c.useEffect,oa=(s,r)=>{if(!s)return r==="light"?vf:jf;const t=na(s);return t&&t.metadata.variant===r?t.metadata.id:hS(r)},xS=s=>{let r=vf,t=jf,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),l=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(l!==null){if(l==="true")n="system";else if(d){const f=na(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?t=f.metadata.id:r=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);r=oa(a,"light"),t=oa(i,"dark")}if(s){const o=na(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function yS({children:s,defaultThemeId:r}){const t=Ce.useMemo(()=>new fS,[]),[n,o]=Ce.useState(()=>xS(r)),[a,i]=Ce.useState(()=>pS()),[l,d]=Ce.useState(()=>typeof window>"u"||!Ht()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Ce.useMemo(()=>Ht(),[]),m=Ce.useMemo(()=>u&&l?l:n.themeMode==="light"?Mo(n.lightThemeId,"light"):n.themeMode==="dark"||a?Mo(n.darkThemeId,"dark"):Mo(n.lightThemeId,"light"),[u,n,a,l]),f=Ce.useMemo(()=>u&&l?[l,...to]:to,[u,l]);Ce.useEffect(()=>{if(!u)return;const N=D=>{d(D);const M=D.metadata.variant==="dark"?"dark":"light",C=$e.getState();C.theme!==M&&C.setTheme(M)},w=D=>{const M=D.detail;M?.theme&&N(M.theme)},k=window.__OPENCHAMBER_VSCODE_THEME__;return k&&N(k),window.addEventListener("openchamber:vscode-theme",w),()=>window.removeEventListener("openchamber:vscode-theme",w)},[u]);const p=Ce.useCallback(N=>{if(typeof document>"u")return;const w=N.colors.surface.background;as()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=w;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",w);const D=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let M=document.querySelector(`meta[name="theme-color"][media="${D}"]`);M||(M=document.createElement("meta"),M.setAttribute("name","theme-color"),M.setAttribute("media",D),document.head.appendChild(M)),M.setAttribute("content",w)},[]),g=Ce.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);gS(()=>{if(typeof window>"u")return;t.apply(m),g(u),p(m);const N=document.documentElement;N.classList.remove("light","dark"),N.classList.add(m.metadata.variant)},[g,t,m,u,p]),Ce.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),w=k=>{i(k.matches)};return i(N.matches),N.addEventListener("change",w),()=>N.removeEventListener("change",w)},[n.themeMode]),Ce.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]),Ce.useEffect(()=>{os({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]),Ce.useEffect(()=>{if(typeof window>"u")return;const N=w=>{const k=w.detail;k&&o(D=>{let M=D.themeMode;k.useSystemTheme===!0?M="system":k.useSystemTheme===!1&&(k.themeVariant==="dark"||k.themeVariant==="light")&&(M=k.themeVariant);let C=D.lightThemeId;typeof k.lightThemeId=="string"&&k.lightThemeId.length>0&&(C=oa(k.lightThemeId,"light"));let S=D.darkThemeId;return typeof k.darkThemeId=="string"&&k.darkThemeId.length>0&&(S=oa(k.darkThemeId,"dark")),M===D.themeMode&&C===D.lightThemeId&&S===D.darkThemeId?D:{themeMode:M,lightThemeId:C,darkThemeId:S}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const b=Ce.useCallback(N=>{const w=f.find(k=>k.metadata.id===N);w&&o(k=>w.metadata.variant==="dark"?k.darkThemeId===w.metadata.id&&k.themeMode==="dark"?k:{...k,darkThemeId:w.metadata.id,themeMode:"dark"}:k.lightThemeId===w.metadata.id&&k.themeMode==="light"?k:{...k,lightThemeId:w.metadata.id,themeMode:"light"})},[f]),h=Ce.useCallback(N=>{o(w=>w.themeMode===N?w:{...w,themeMode:N})},[]),j=Ce.useCallback(N=>{if(N){o(k=>k.themeMode==="system"?k:{...k,themeMode:"system"});return}const w=m.metadata.variant==="dark"?"dark":"light";o(k=>k.themeMode===w?k:{...k,themeMode:w})},[m.metadata.variant]),y=Ce.useCallback(N=>{const w=f.find(k=>k.metadata.id===N&&k.metadata.variant==="light");w&&o(k=>k.lightThemeId===w.metadata.id?k:{...k,lightThemeId:w.metadata.id})},[f]),x=Ce.useCallback(N=>{const w=f.find(k=>k.metadata.id===N&&k.metadata.variant==="dark");w&&o(k=>k.darkThemeId===w.metadata.id?k:{...k,darkThemeId:w.metadata.id})},[f]),v={currentTheme:m,availableThemes:f,setTheme:b,isSystemPreference:n.themeMode==="system",setSystemPreference:j,themeMode:n.themeMode,setThemeMode:h,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:y,setDarkThemePreference:x};return e.jsx(ml.Provider,{value:v,children:s})}const bS=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=$e();return c.useLayoutEffect(()=>{t(),o(),i()},[r,t,n,o,a,i]),c.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&t()};return l.addEventListener("change",d),()=>{l.removeEventListener("change",d)}},[r,t]),e.jsx(e.Fragment,{children:s})},wS={getLastAssistantMessage(){const s=ue.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const t=s.messages.get(r);if(!t||t.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=t.length-1;n>=0;n--){const o=t[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const g={id:p.id,type:p.type};return p.type==="text"?(g.text=p.text,g.textLength=p.text?.length||0):p.type==="tool"?(g.tool=p.tool,g.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(g.isStepMarker=!0),g}),i=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),l=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!i&&!l&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:i,hasTools:l,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!l}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!l&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(s,r=80){return!s||typeof s!="string"||s.length<=r?s:s.substring(0,r)+"…"},truncateMessages(s){return s.map(r=>({...r,parts:(r.parts||[]).map(t=>{const n={...t};return"text"in t&&(n.text=this.truncateString(t.text)),"textPreview"in t&&(n.textPreview=this.truncateString(t.textPreview)),t.state&&(n.state={...t.state},"output"in t.state&&(n.state.output=this.truncateString(t.state.output)),"error"in t.state&&(n.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(n.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),n})}))},getAllMessages(s=!1){const r=ue.getState(),t=r.currentSessionId;if(!t)return console.log("[ERROR] No active session"),[];const n=r.messages.get(t)||[];return console.log(`[MESSAGES] Total messages in session: ${n.length}`),n.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),s?this.truncateMessages(n):n},async getAppStatus(){const s=dt.getState(),r=ue.getState(),t=s.currentDirectory||null,n=ke.getDirectory()??null,o=r.sessions||[],a=new Set,i={};o.forEach(k=>{const D=k.directory;typeof D=="string"&&D.trim().length>0?(a.add(D),i[D]=(i[D]??0)+1):i["(none)"]=(i["(none)"]??0)+1});const l=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(k){return{available:!1,error:k instanceof Error?k.message:String(k)}}})(),d=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,u=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,m=!!(d?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),f=async k=>{try{return await k.json()}catch{return null}},p=async k=>{try{return await k.text()}catch{return null}},g=async k=>{try{const D=await fetch(k);return D.ok?await f(D):{status:D.status}}catch(D){return{error:D instanceof Error?D.message:String(D)}}};let b=null,h=null,j=null,y=null;const x=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";b=await g(x);const v=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";h=await g(v),j=await g("/api/config/settings");try{const k=await fetch("/api/health"),D=k.headers.get("content-type")||"",M=await p(k);y={status:k.status,ok:k.ok,contentType:D,type:D.includes("application/json")?"json":"html",preview:M?M.slice(0,120):null}}catch(k){y={error:k instanceof Error?k.message:String(k)}}let N={isGitRepo:null};if(t)try{N.isGitRepo=await sn(t)}catch(k){N={isGitRepo:null,error:k instanceof Error?k.message:String(k)}}const w={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:b?.directory||b?.worktree||n,homeDirectory:s.homeDirectory||null,isHomeReady:s.isHomeReady,hasPersistedDirectory:s.hasPersistedDirectory,isSwitchingDirectory:s.isSwitchingDirectory},sessions:{total:o.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:a.size,directorySamples:Array.from(a).slice(0,5),directoryCounts:i},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:N,localStorage:l,opencode:{pathInfo:b,projectInfo:h,health:y},openchamber:{settingsInfo:j}};return console.log("[DEBUG] App status snapshot:",w),w},checkLastMessage(){const s=this.getLastAssistantMessage();if(!s)return!1;const r=s.isEmpty||s.isEmptyResponse;return r?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:s.messageId,isEmpty:s.isEmpty,isEmptyResponse:s.isEmptyResponse,partsCount:s.partsCount}),s.parts.length>0&&console.log("Parts:",s.parts)):console.log("[OK] Last message looks good!"),r},getStreamingState(){const s=ue.getState(),r=s.currentSessionId?s.streamingMessageIds.get(s.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:r,streamingMessageIds:Array.from(s.streamingMessageIds.entries()),messageStreamStates:Array.from(s.messageStreamStates.entries())}),{streamingMessageId:r,streamingMessageIds:s.streamingMessageIds,streamStates:s.messageStreamStates}},findEmptyMessages(){const s=ue.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(s.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),l=a.some(d=>d.type==="tool");return a.length===0||!i&&!l});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
121
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
122
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
123
- `),console.log("3. To retry, you can:"),console.log(" - Edit your last user message and resend"),console.log(' - Send a follow-up message like "Please provide the response"'),console.log(` - Try a different model (OpenAI models tend to be more reliable)
124
- `),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(s={}){const{includeNonAssistant:r=!1,verbose:t=!0,maxTableRows:n=25}=s,o=ue.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],l=r?i:i.filter(p=>p.info.role==="assistant"),d={totalMessages:i.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const g=p.filter(b=>typeof b=="number");return g.length>0?Math.max(...g):null},f=l.map((p,g)=>{const b=p.info??{},h=Array.isArray(p.parts)?p.parts:[],j=b.time??{},y=u(j.completed),x=y!==null,v=h.filter(E=>E.type==="tool"),N=h.filter(E=>E.type==="reasoning"),w=m(v.map(E=>u(E.state?.time?.end??E.state?.time?.start))),k=m(N.map(E=>u(E.time?.end??E.time?.start))),D=m([w,k].filter(E=>E!==null)),M=v.some(E=>["pending","running","started"].includes(E.state?.status)),C=N.some(E=>typeof E.time?.end!="number");v.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),x||(d.completedMissing+=1);const S=!!(x&&typeof w=="number"&&y<w);S&&(d.completedBeforeTool+=1);const A=!!(x&&typeof k=="number"&&y<k);return A&&(d.completedBeforeReasoning+=1),x&&M&&(d.runningToolsWhenCompleted+=1),x&&C&&(d.reasoningOpenWhenCompleted+=1),{index:g,messageId:b.id,role:b.role,completedAt:y,latestToolTimestamp:w,latestReasoningTimestamp:k,latestPartTimestamp:D,completed_missing:!x,completed_before_tool:S,completed_before_reasoning:A,running_tools_when_completed:!!(x&&M),reasoning_open_when_completed:!!(x&&C),has_tools:v.length>0,has_reasoning:N.length>0}});return t&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const s=ue.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(s.messages.get(r)||[]).filter(j=>j.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(j=>j.type==="step-finish"),i=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&i),p=s.messageStreamStates,g=o.info.sessionID?s.streamingMessageIds.get(o.info.sessionID)??null:null,b=p.get(o.info.id),h=o.info.id===g;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",i),console.log("messageIsComplete:",f),console.log("lifecycle phase:",b?.phase),console.log("isStreamingCandidate:",h),console.log("streamingMessageId:",g),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:i,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=wS,Qt()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",s=>{try{const r=s.message||"",t=s.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&s.preventDefault()}catch{}}));let Jd=!1;const vS=()=>{if(Jd||typeof window>"u")return;Jd=!0;let s={showReasoningTraces:$e.getState().showReasoningTraces,autoDeleteEnabled:$e.getState().autoDeleteEnabled,autoDeleteAfterDays:$e.getState().autoDeleteAfterDays},r=null,t=null;const n=()=>{const a=r;r=null,t=null,a&&Object.keys(a).length>0&&os(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};$e.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},l={};i.showReasoningTraces!==s.showReasoningTraces&&(l.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==s.autoDeleteEnabled&&(l.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(l.autoDeleteAfterDays=i.autoDeleteAfterDays),s=i,Object.keys(l).length>0&&o(l)})};let Zd=!1;const eu="openchamber-typography-base",jS=()=>{if(typeof document>"u")return;const r=`:root {
125
- ${Object.entries(Ji).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
126
- `)}
127
- }
128
- `,t=document.getElementById(eu);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=eu,n.textContent=r,document.head.appendChild(n)},SS=()=>{Zd||typeof window>"u"||(Zd=!0,jS())},kS=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Cu();await Mu();vS();SS();await bf();typeof window<"u"&&(window.debugContextTokens=()=>{const s=window.__zustand_session_store__;if(!s)return;const r=s.getState(),t=r.currentSessionId;if(!t)return;const o=(r.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const i=o[o.length-1].info.tokens;i&&typeof i=="object"&&console.debug("Token breakdown:",{base:(i.input||0)+(i.output||0)+(i.reasoning||0),cache:i.cache?(i.cache.read||0)+(i.cache.write||0):0}),r.sessionContextUsage.get(t);const l=window.__zustand_config_store__;if(l){const d=l.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const kf=document.getElementById("root");if(!kf)throw new Error("Root element not found");Dh.createRoot(kf).render(e.jsx(Ce.StrictMode,{children:e.jsx(yS,{children:e.jsx(bS,{children:e.jsx(mS,{children:e.jsx(aS,{apis:kS})})})})}));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 MS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ms as D,Gr as S,fs as a,vy as b,T as c,Iw as d,Pw as e,cd as f,rn as g,Tw as h,Rw as i,MS as m,Gm as p,Fw as r,Eo as t};