@openchamber/web 1.2.5 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,118 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.pnpm-B7ko08Tb.js","assets/vendor--B3aGWKBE.css","assets/ToolOutputDialog-BK6SvVkC.js","assets/index-DcXQiyJT.js","assets/index-BgMc3ajO.css"])))=>i.map(i=>d[i]);
2
- import{t as od,c as ad,j as e,R as id,T as ld,P as cd,C as dd,A as ud,a as md,b as $t,d as Wt,p as ys,e as bs,f as fd,g as l,r as pd,h as ds,I as hd,i as gd,k as xd,l as yd,m as bd,n as wd,o as vd,q as jd,s as Tt,u as Sd,S as kd,v as Nd,w as Cd,x as us,y as Md,z as pl,B as hl,D as Ad,E as Dd,F as le,G as Ma,H as So,J as Ed,K as vt,L as Vo,M as Td,U as Bt,_ as Lr,Z as Id,Y as zs,Q as Ws,W as Yt,O as Hn,N as Fd,V as hr,X as ko,$ as Ds,a0 as gl,a1 as Pd,a2 as Rd,a3 as Ld,a4 as _d,a5 as Od,a6 as Bd,a7 as $d,a8 as zd,a9 as No,aa as Go,ab as Hd,ac as qo,ad as Wn,ae as wr,af as xl,ag as Wd,ah as os,ai as kn,aj as Un,ak as Ls,al as Us,am as yl,an as bl,ao as _r,ap as be,aq as Cs,ar as hs,as as Nn,at as Zs,au as ss,av as Aa,aw as Ko,ax as wl,ay as Yo,az as Xo,aA as Jo,aB as Vn,aC as Vr,aD as Da,aE as Zo,aF as sr,aG as Gr,aH as Or,aI as Ud,aJ as Vd,aK as vl,aL as jl,aM as gr,aN as Gd,aO as qd,aP as Yn,aQ as Kd,aR as is,aS as Yd,aT as Xd,aU as Xn,aV as Jd,aW as Qo,aX as ea,aY as Zd,aZ as Qd,a_ as eu,a$ as Co,b0 as tu,b1 as xr,b2 as Qs,b3 as Gn,b4 as qn,b5 as ta,b6 as su,b7 as ru,b8 as nu,b9 as ou,ba as au,bb as iu,bc as lu,bd as Mo,be as fn,bf as sa,bg as cu,bh as du,bi as Nr,bj as uu,bk as mu,bl as fu,bm as Sl,bn as pu,bo as hu,bp as gu,bq as xu,br as Ao,bs as yu,bt as ks,bu,bv as vr,bw as wu,bx as vu,by as ju,bz as Su,bA as ku,bB as Nu,bC as Cu,bD as Mu,bE as Au,bF as Du,bG as Eu,bH as Tu,bI as Iu,bJ as Fu,bK as Pu,bL as Ru,bM as Lu,bN as _u,bO as Ou,bP as Ea,bQ as kl,bR as Bu,bS as $u,bT as Ta,bU as zu,bV as Hu,bW as Wu,bX as Uu,bY as Vu,bZ as Gu,b_ as qu}from"./vendor-.pnpm-B7ko08Tb.js";import{c as Ku,l as Yu,g as Xu,r as Ju,d as Zu,a as Qu,b as em,u as tm,e as sm,f as rm,h as nm,i as om,j as am,k as im}from"./index-DcXQiyJT.js";function T(...r){return od(ad(r))}const Nl=(r,s)=>{const t=r??"",n=Math.max(16,s?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>i)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},Cn=r=>r?r==="/"?"/":r.replace(/\/+$/,""):"";function Gt(r,s){if(!r)return"";const t=Cn(r);if(t==="/")return"/";const n=s?Cn(s):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 Jn(r,s){if(!r)return"/";const t=Cn(r);if(!t||t==="/")return"/";const n=s?Cn(s):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function lm({delayDuration:r=0,...s}){return e.jsx(md,{"data-slot":"tooltip-provider",delayDuration:r,...s})}function ft({delayDuration:r=0,...s}){return e.jsx(lm,{delayDuration:r,children:e.jsx(id,{"data-slot":"tooltip",...s})})}function pt({...r}){return e.jsx(ld,{"data-slot":"tooltip-trigger",...r})}function ut({className:r,sideOffset:s=0,children:t,...n}){return e.jsx(cd,{children:e.jsxs(dd,{"data-slot":"tooltip-content",sideOffset:s,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",r),...n,children:[t,e.jsx(ud,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Zn=null;const Ia=()=>{const r=new Map;return{getItem:s=>r.get(s)??null,setItem:(s,t)=>{r.set(s,t)},removeItem:s=>{r.delete(s)},clear:()=>{r.clear()},key:s=>Array.from(r.keys())[s]??null,get length(){return r.size}}},cm=()=>{if(typeof window>"u"||!window.localStorage)return Ia();const r=window.localStorage,s=Ia();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const p=r.getItem(u);if(p!==null)return p}catch{n()}return s.getItem(u)},setItem:(u,p)=>{if(t)try{r.setItem(u,p),s.removeItem(u);return}catch{n()}s.setItem(u,p)},removeItem:u=>{if(t)try{r.removeItem(u)}catch{n()}s.removeItem(u)},clear:()=>{if(t)try{r.clear()}catch{n()}s.clear()},key:u=>{if(t)try{return r.key(u)}catch{n()}return s.key(u)},get length(){if(t)try{return r.length+s.length}catch{n()}return s.length}}},ts=()=>(Zn||(Zn=cm()),Zn),ra={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},dm={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Fa(r){return`--text-${r.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Ms={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)"}}},pn={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Ms.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:pn.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Ms.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:pn.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Ms.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:pn.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Ms.tool.inline})},Pe=$t()(Wt(ys((r,s)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",pendingDiffFile:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!1,toolCallExpansion:"collapsed",fontSize:100,padding:100,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,setTheme:t=>{r({theme:t}),s().applyTheme()},toggleSidebar:()=>{r(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=>{r(()=>{if(t&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:t,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:t}})},setSidebarWidth:t=>{r({sidebarWidth:t,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:t=>{r({isSessionSwitcherOpen:t})},setActiveMainTab:t=>{r({activeMainTab:t})},setPendingDiffFile:t=>{r({pendingDiffFile:t})},navigateToDiff:t=>{r({pendingDiffFile:t,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:t}=s();return t&&r({pendingDiffFile:null}),t},setIsMobile:t=>{r({isMobile:t})},toggleCommandPalette:()=>{r(t=>({isCommandPaletteOpen:!t.isCommandPaletteOpen}))},setCommandPaletteOpen:t=>{r({isCommandPaletteOpen:t})},toggleHelpDialog:()=>{r(t=>({isHelpDialogOpen:!t.isHelpDialogOpen}))},setHelpDialogOpen:t=>{r({isHelpDialogOpen:t})},setSessionCreateDialogOpen:t=>{r({isSessionCreateDialogOpen:t})},setSettingsDialogOpen:t=>{r({isSettingsDialogOpen:t})},setSidebarSection:t=>{r({sidebarSection:t})},setEventStreamStatus:(t,n)=>{r({eventStreamStatus:t,eventStreamHint:n??null})},setShowReasoningTraces:t=>{r({showReasoningTraces:t})},setToolCallExpansion:t=>{r({toolCallExpansion:t})},setFontSize:t=>{const n=Math.max(50,Math.min(200,t));r({fontSize:n}),s().applyTypography()},setPadding:t=>{const n=Math.max(50,Math.min(200,t));r({padding:n}),s().applyPadding()},applyTypography:()=>{const{fontSize:t}=s(),n=document.documentElement,o=t/100,a=Object.entries(ra);if(o===1){for(const[i]of a)n.style.removeProperty(Fa(i));return}for(const[i,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Fa(i),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=s(),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=>{r({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{r(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{r({diffWrapLines:t})},toggleFavoriteModel:(t,n)=>{r(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}=s();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{r(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"||r(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=s(),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)}}),{name:"ui-store",storage:bs(()=>ts()),partialize:r=>({theme:r.theme,isSidebarOpen:r.isSidebarOpen,sidebarWidth:r.sidebarWidth,isSessionSwitcherOpen:r.isSessionSwitcherOpen,activeMainTab:r.activeMainTab,sidebarSection:r.sidebarSection,isSessionCreateDialogOpen:r.isSessionCreateDialogOpen,isSettingsDialogOpen:r.isSettingsDialogOpen,showReasoningTraces:r.showReasoningTraces,toolCallExpansion:r.toolCallExpansion,fontSize:r.fontSize,padding:r.padding,favoriteModels:r.favoriteModels,recentModels:r.recentModels,diffLayoutPreference:r.diffLayoutPreference,diffWrapLines:r.diffWrapLines})}),{name:"ui-store"})),es=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",rs=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Vs=()=>es()?window.opencodeDesktop??null:null,Cl=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const r=window.opencodeDesktop;return r?.getSettings&&r?.updateSettings?{getSettings:r.getSettings.bind(r),updateSettings:r.updateSettings.bind(r)}:null},Ml=async()=>{const r=Vs();if(typeof window<"u"){const s=window.__OPENCHAMBER_HOME__;if(s&&s.length>0)return s}if(!r)return null;if(typeof r.homeDirectory=="string"&&r.homeDirectory.length>0)return r.homeDirectory;try{if(!r.getHomeDirectory)return null;const s=await r.getHomeDirectory();if(s?.success&&typeof s.path=="string"&&s.path.length>0)return s.path}catch(s){console.warn("Failed to obtain desktop home directory:",s)}return null},um=async()=>{const r=Vs();if(!r)return null;try{return await r.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},mm=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Al=async()=>{const r=Cl();if(!r)return null;try{return await r.getSettings()}catch(s){return console.warn("Failed to read desktop settings",s),null}},fm=async r=>{const s=Cl();if(!s)return null;try{return await s.updateSettings(r)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},pm=async r=>{const s=Vs();if(!s||!s.requestDirectoryAccess)return{success:!0,path:r};try{return await s.requestDirectoryAccess(r)}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},hm=async r=>{const s=Vs();if(!s||!s.startAccessingDirectory)return{success:!0};try{return await s.startAccessingDirectory(r)}catch(t){return console.warn("Failed to start accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},gm=async r=>{const s=Vs();if(!s||!s.stopAccessingDirectory)return{success:!0};try{return await s.stopAccessingDirectory(r)}catch(t){return console.warn("Failed to stop accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},xm=async()=>{const r=Vs();if(!r||!r.checkForUpdates)return null;try{return await r.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},ym=async r=>{const s=Vs();if(!s||!s.downloadUpdate)return!1;try{return await s.downloadUpdate(r),!0}catch(t){return console.warn("Failed to download update",t),!1}},bm=async()=>{const r=Vs();if(!r||!r.restartToUpdate)return!1;try{return await r.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}},wm="/api",vm=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,jm=r=>{const s=typeof r=="string"&&r.trim().length>0?r.trim():"/api";if(vm.test(s)||typeof window>"u")return s;const t=window.location?.href||window.location?.origin;if(!t)return s;try{return new URL(s,t).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),s}},Sm=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_DESKTOP_SERVER__,s=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!r||!s)return null;const t=typeof r.origin=="string"&&r.origin.length>0?r.origin:null;return t?`${t}/api`:null},Kr=r=>r.replace(/\\/g,"/"),Qn=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_RUNTIME_APIS__;return r&&r.runtime?.isDesktop&&r.files?r.files:null};class km{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=wm){const n=Sm()||s;this.baseUrl=jm(n),this.client=fd({baseUrl:this.baseUrl})}normalizeCandidatePath(s){if(typeof s!="string")return null;const t=s.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(s){const t=s.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],c=s.slice(a.length+(s.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=s.startsWith("/"),o=s.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(s){this.currentDirectory=s}getDirectory(){return this.currentDirectory}async withDirectory(s,t){if(s==null)return t();const n=this.currentDirectory;this.currentDirectory=s;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const s=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&s.add(a)};try{const a=(await this.client.path.get({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!s.size)try{const o=await this.client.project.current({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!s.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(!s.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!s.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(s);return this.deriveHomeDirectory(n)}async listSessions(){const s=await this.client.session.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});return Array.isArray(s.data)?s.data:[]}async createSession(s){const t=await this.client.session.create({query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{parentID:s?.parentID,title:s?.title}});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(s){const t=await this.client.session.get({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(s){return(await this.client.session.delete({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||!1}async updateSession(s,t){const n=await this.client.session.update({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{title:t}});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(s){return(await this.client.session.messages({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}async getSessionTodos(s){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(s)}/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[]}}async sendMessage(s){const t=Date.now(),n=s.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(s.prefaceText&&s.prefaceText.trim()&&o.push({type:"text",text:s.prefaceText}),s.text&&s.text.trim()){const a={type:"text",text:s.text};o.push(a)}if(s.files&&s.files.length>0&&s.files.forEach(a=>{const i={type:"file",mime:a.mime,filename:a.filename,url:a.url};o.push(i)}),s.agentMentions&&s.agentMentions.length>0){const[a]=s.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({path:{id:s.id},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{model:{providerID:s.providerID,modelID:s.modelID},agent:s.agent,parts:o}}),n}async abortSession(s){return!!(await this.client.session.abort({path:{id:s},throwOnError:!0})).data}async getSessionStatus(){try{const s=this.baseUrl.replace(/\/$/,""),t=new URL(`${s}/session/status`);this.currentDirectory&&this.currentDirectory.length>0&&t.searchParams.set("directory",this.currentDirectory);const n=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return{};const o=await n.json().catch(()=>null);return!o||typeof o!="object"?{}:o}catch{return{}}}async respondToPermission(s,t,n){return(await this.client.postSessionIdPermissionsPermissionId({path:{id:s,permissionID:t},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{response:n}})).data||!1}async getConfig(){const s=await this.client.config.get();if(!s.data)throw new Error("Failed to get config");return s.data}async updateConfig(s){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});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(s){const t=await this.getConfig(),n=s(t);return await this.updateConfig(n)}async getProviders(){const s=await this.client.config.providers({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!s.data)throw new Error("Failed to get providers");return s.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}catch{return[]}}subscribeToEvents(s,t,n,o){this.sseAbortController&&this.sseAbortController.abort();const a=new AbortController;this.sseAbortController=a;let i;return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const c=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",c);const d=async u=>{try{const p={query:c?{directory:c}:void 0,signal:a.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:f=>{f instanceof Error&&f.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",f),t&&!a.signal.aborted&&t(f))},onSseEvent:f=>{if(a.signal.aborted)return;f.id&&typeof f.id=="string"&&(i=f.id);const h=f.data;h&&typeof h=="object"&&s(h)}};i&&(p.lastEventId=i,p.headers={...p.headers||{},"Last-Event-ID":i});const m=await this.client.event.subscribe(p);n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const f of m.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}if(!a.signal.aborted){const f=Math.min(3e3*Math.pow(2,u),3e4);await new Promise(h=>setTimeout(h,f)),await d(u+1)}}catch(p){if(p?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",p),t&&t(p);const m=Math.min(3e3*Math.pow(2,u),3e4);await new Promise(f=>setTimeout(f,m)),a.signal.aborted||await d(u+1)}};try{await d(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortController===a&&(this.sseAbortController=null)}})(),()=>{this.sseAbortController===a&&(this.sseAbortController=null),a.abort()}}async readFile(s){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${s}
3
- // This would be loaded from the server`}}async listFiles(s){try{const t=s||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model,template:t.template,subtask:t.subtask}))}catch{return[]}}async getCommandDetails(s){try{const t=await this.client.command.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(t.data){const n=t.data.find(o=>o.name===s);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 s;const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;t==="/api"?s="/health":t.endsWith("/api")?s=`${t.slice(0,-4)}/health`:s=`${t}/health`;const n=await fetch(s);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(s){const t=Qn();if(t?.createDirectory)try{return await t.createDirectory(s)}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:s})});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(s){const t=Qn();if(t)try{const n=await t.listDirectory(s||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:Kr(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;s&&s.trim().length>0&&n.set("path",s);const o=n.toString(),a=await fetch(`${this.baseUrl}/fs/list${o?`?${o}`:""}`);if(!a.ok){const c=await a.json().catch(()=>({})),d=typeof c.error=="string"?c.error:"Failed to list directory";throw new Error(d)}const i=await a.json();return!i||!Array.isArray(i.entries)?[]:i.entries}catch(n){throw console.error("Failed to list directory contents:",n),n}}async searchFiles(s,t){const n=Qn(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Kr(o):null;if(n)try{const p=await n.search({directory:o||"",query:s,maxResults:t?.limit});return Array.isArray(p)?p.map(m=>{const f=Kr(m.path),h=f.split("/").filter(Boolean).pop()||f,g=m.preview&&m.preview.length>0&&typeof m.preview[0]=="string"?Kr(m.preview[0]):a&&f.startsWith(a)&&f.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:f,relativePath:g,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(p){throw console.error("Failed to search files:",p),p}const i=new URLSearchParams;o&&o.length>0&&i.set("directory",o),typeof s=="string"&&i.set("q",s),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&i.set("limit",String(t.limit));const c=`${this.baseUrl}/fs/search${i.toString()?`?${i.toString()}`:""}`,d=await fetch(c,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const p=await d.json().catch(()=>({})),m=typeof p.error=="string"?p.error:"Failed to search files";throw new Error(m)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const s=await Ml();if(s)return s;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(s){if(!s||typeof s!="string"||!s.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",s),null;const t=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",t,"with path:",s);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s})}),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:s}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const Ce=new km,Do=new Set;function na(r){return Do.add(r),()=>{Do.delete(r)}}function Es(r,s){const t=Array.isArray(r)?r:[r],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:s?.source,timestamp:Date.now()};for(const a of Do)try{const i=a(o);i instanceof Promise&&i.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function Mn(r,s){return r.scopes.includes("all")||r.scopes.includes(s)}const oa="Updating OpenCode configuration...";let xs=0,Hs=oa;const Eo=new Set;function An(){const r={isUpdating:xs>0,message:Hs};Eo.forEach(s=>s(r))}function $s(r){xs+=1,xs===1?(Hs=r||oa,An()):r&&(Hs=r,An())}function ns(){xs!==0&&(xs-=1,xs===0&&(Hs=oa,An()))}function cs(r){Hs===r&&xs>0||(Hs=r,xs>0&&An())}function Nm(r){return Eo.add(r),r({isUpdating:xs>0,message:Hs}),()=>{Eo.delete(r)}}function Cm(){return{isUpdating:xs>0,message:Hs}}const hn=r=>r.builtIn||r.native===!0,Dl=r=>r.hidden===!0,El=r=>r.filter(s=>!Dl(s)),Fr="useAgentsStore",Dn=r=>new Promise(s=>setTimeout(s,r)),Mm=2e4,Pa=300,Ra=4,Am=800,Dm=200,Em=2e3,jr=$t()(Wt(ys((r,s)=>({selectedAgentName:null,agents:[],isLoading:!1,setSelectedAgent:t=>{r({selectedAgentName:t})},loadAgents:async()=>{r({isLoading:!0});const t=s().agents;let n=null;for(let o=0;o<3;o++)try{const a=await Ce.listAgents();return r({agents:a,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),r({agents:t,isLoading:!1}),!1},createAgent:async t=>{$s("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.tools&&Object.keys(t.tools).length>0&&(o.tools=t.tools),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),console.log("[AgentsStore] Agent config to save:",o);const a=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const u=i?.error||"Failed to create agent";throw new Error(u)}if(console.log("[AgentsStore] Agent created successfully"),i?.requiresReload??!0)return n=!0,await dr({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadAgents();return d&&Es("agents",{source:Fr}),d}catch(o){return console.error("[AgentsStore] Failed to create agent:",o),!1}finally{n||ns()}},updateAgent:async(t,n)=>{$s("Updating agent configuration…");let o=!1;try{console.log("[AgentsStore] Updating agent:",t),console.log("[AgentsStore] Config received:",n);const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.tools!==void 0&&(a.tools=n.tools),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable),console.log("[AgentsStore] Agent config to update:",a);const i=await fetch(`/api/config/agents/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),c=await i.json().catch(()=>null);if(!i.ok){const p=c?.error||"Failed to update agent";throw new Error(p)}if(console.log("[AgentsStore] Agent updated successfully"),c?.requiresReload??!0)return o=!0,await dr({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadAgents();return u&&Es("agents",{source:Fr}),u}catch(a){return console.error("[AgentsStore] Failed to update agent:",a),!1}finally{o||ns()}},deleteAgent:async t=>{$s("Deleting agent configuration…");let n=!1;try{const o=await fetch(`/api/config/agents/${encodeURIComponent(t)}`,{method:"DELETE"}),a=await o.json().catch(()=>null);if(!o.ok){const d=a?.error||"Failed to delete agent";throw new Error(d)}if(console.log("[AgentsStore] Agent deleted successfully"),a?.requiresReload??!0)return n=!0,await dr({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadAgents();return c&&Es("agents",{source:Fr}),s().selectedAgentName===t&&r({selectedAgentName:null}),c}catch(o){return console.error("Failed to delete agent:",o),!1}finally{n||ns()}},getAgentByName:t=>{const{agents:n}=s();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=s();return El(t)}}),{name:"agents-store",storage:bs(()=>ts()),partialize:r=>({selectedAgentName:r.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=jr);async function Tm(r){const s=typeof r=="number"&&r>0?Math.min(r,Pa):0;s>0&&await Dn(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Mm;){n+=1,cs(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ce.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=Ra&&a<1200?Pa:Math.min(Am+Math.max(0,n-Ra)*Dm,Em);await Dn(i)}throw o||new Error("OpenCode did not become ready in time")}async function dr(r={}){const{message:s,delayMs:t}=r;try{cs(s||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("agents-store"),window.localStorage.removeItem("config-store"))}catch(n){console.warn("[AgentsStore] Failed to prepare config refresh:",n)}try{await Tm(t),cs("Refreshing providers and agents…");const n=kt.getState(),o=jr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),Es("agents",{source:Fr})}catch(n){console.error("[AgentsStore] Failed to refresh configuration after OpenCode restart:",n),cs("OpenCode reload failed. Please retry refreshing configuration manually."),await Dn(1500)}finally{ns()}}async function Im(r){await dr(r)}async function Fm(r){$s("Reloading OpenCode configuration…");try{const s=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await s.json().catch(()=>null);if(!s.ok){const n=t?.error||"Failed to reload configuration";throw new Error(n)}t?.requiresReload?await dr({message:t.message,delayMs:t.reloadDelayMs}):await dr(r)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),cs("Failed to reload configuration. Please try again."),await Dn(2e3),ns(),s}}let La=null;La||(La=na(r=>{if(r.source!==Fr&&Mn(r,"agents")){const{loadAgents:s}=jr.getState();s()}}));const Pm="https://models.dev/api.json",Rm="/api/openchamber/models-metadata",Lm=r=>r?.toLowerCase?.()??"",_m=r=>r==="primary"||r==="all"||r===void 0||r===null,Br=r=>typeof r=="object"&&r!==null,En=r=>Array.isArray(r)&&r.every(s=>typeof s=="string"),Om=r=>{if(!Br(r))return!1;const s=r;if(s.modalities){const{input:t,output:n}=s.modalities;if(t&&!En(t)||n&&!En(n))return!1}return!0},Bm=r=>{if(!Br(r))return!1;const s=r;return s.models===void 0||Br(s.models)},Tl=(r,s)=>{const t=Lm(r);return!t||!s?"":`${t}/${s}`},$m=r=>{const s=new Map;if(!Br(r))return s;for(const[t,n]of Object.entries(r)){if(!Bm(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!Br(a)))for(const[i,c]of Object.entries(a)){if(!Om(c))continue;const d=typeof i=="string"&&i.length>0?i:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:En(c.modalities.input)?c.modalities.input:void 0,output:En(c.modalities.output)?c.modalities.output:void 0}:void 0,cost:c.cost,limit:c.limit,knowledge:typeof c.knowledge=="string"?c.knowledge:void 0,release_date:typeof c.release_date=="string"?c.release_date:void 0,last_updated:typeof c.last_updated=="string"?c.last_updated:void 0},p=Tl(o,d);p&&s.set(p,u)}}return s},zm=async()=>{if(typeof fetch!="function")return new Map;const r=[Rm,Pm];for(const s of r){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(s),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(s,a);if(!i.ok)throw new Error(`Metadata request to ${s} returned status ${i.status}`);const c=await i.json();return $m(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${s})`):console.warn(`Failed to fetch model metadata from ${s}:`,o)}finally{n&&clearTimeout(n)}}return new Map},Hm=r=>new Promise(s=>setTimeout(s,r)),kt=$t()(Wt(ys((r,s)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,loadProviders:async()=>{try{const t=zm(),n=await Ce.getProviders(),o=Array.isArray(n?.providers)?n.providers:[],a=n?.default||{},i=o.map(m=>{const f=m.models??{},h=Object.keys(f).map(g=>f[g]);return{...m,models:h}}),c=a.provider||i[0]?.id||"",d=i.find(m=>m.id===c),u=a.model||d?.models?.[0]?.id||"";r({providers:i,defaultProviders:a,currentProviderId:c,currentModelId:u});const p=await t;p.size>0&&r({modelsMetadata:p})}catch(t){console.error("Failed to load providers:",t),r({providers:[],defaultProviders:{},currentProviderId:"",currentModelId:""})}},setProvider:t=>{const{providers:n}=s(),o=n.find(a=>a.id===t);if(o){const i=o.models[0]?.id||"";r({currentProviderId:t,currentModelId:i})}},setModel:t=>{r({currentModelId:t})},saveAgentModelSelection:(t,n,o)=>{r(a=>({agentModelSelections:{...a.agentModelSelections,[t]:{providerId:n,modelId:o}}}))},getAgentModelSelection:t=>{const{agentModelSelections:n}=s();return n[t]||null},loadAgents:async()=>{const t=s().agents;let n=null;for(let o=0;o<3;o++)try{const a=await Ce.listAgents(),i=Array.isArray(a)?a:[];r({agents:i});const{providers:c}=s();if(i.length===0)return r({currentAgentName:void 0}),!0;const d=i.filter(m=>_m(m.mode)),p=d.find(m=>m.name==="build")||d[0]||i[0];if(r({currentAgentName:p.name}),p?.model?.providerID&&p?.model?.modelID){const m=c.find(f=>f.id===p.model.providerID);m&&m.models.find(h=>h.id===p.model.modelID)&&r({currentProviderId:p.model.providerID,currentModelId:p.model.modelID})}return!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),r({agents:t}),!1},setAgent:t=>{const{agents:n,providers:o}=s();if(r({currentAgentName:t}),t&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const i=a.getState(),{currentSessionId:c,isOpenChamberCreatedSession:d,initializeNewOpenChamberSession:u,getAgentModelForSession:p}=i;c&&a.setState(m=>{const f=new Map(m.currentAgentContext);return f.set(c,t),{currentAgentContext:f}}),c&&d(c)&&(p(c,t)||u(c,n))}}if(t&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const{currentSessionId:c,getAgentModelForSession:d}=a.getState();if(c&&d(c,t))return}const i=n.find(c=>c.name===t);if(i?.model?.providerID&&i?.model?.modelID){const c=o.find(d=>d.id===i.model.providerID);c&&c.models.find(u=>u.id===i.model.modelID)&&r({currentProviderId:i.model.providerID,currentModelId:i.model.modelID})}}},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Ce.checkHealth();return r({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await Hm(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),r({isConnected:!1}),!1},initializeApp:async()=>{try{console.log("Starting app initialization...");const t=await s().checkConnection();if(console.log("Connection check result:",t),!t){console.log("Server not connected"),r({isConnected:!1});return}console.log("Initializing app..."),await Ce.initApp(),console.log("Loading providers..."),await s().loadProviders(),console.log("Loading agents..."),await s().loadAgents(),r({isInitialized:!0,isConnected:!0}),console.log("App initialized successfully")}catch(t){console.error("Failed to initialize app:",t),r({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:t,currentProviderId:n}=s();return t.find(o=>o.id===n)},getCurrentModel:()=>{const t=s().getCurrentProvider(),{currentModelId:n}=s();if(t)return t.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:t,currentAgentName:n}=s();if(n)return t.find(o=>o.name===n)},getModelMetadata:(t,n)=>{const o=Tl(t,n);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=s();return El(t)}}),{name:"config-store",storage:bs(()=>ts()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=kt);let _a=null;_a||(_a=na(async r=>{const s=[];if(Mn(r,"agents")){const{loadAgents:t}=kt.getState();s.push(t().then(()=>{}))}if(Mn(r,"providers")){const{loadProviders:t}=kt.getState();s.push(t())}s.length>0&&await Promise.all(s)}));const Ot={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Wm=180,Qt=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function aa(r){const s=Qt();return s?s.checkIsGitRepository(r):Ku(r)}async function Um(r){const s=Qt();return s?s.getGitStatus(r):Xu(r)}async function Vm(r,s){const t=Qt();return t?t.deleteGitBranch(r,s):Zu(r,s)}async function Gm(r,s){const t=Qt();return t?t.deleteRemoteBranch(r,s):Qu(r,s)}async function qm(r){const s=Qt();return s?s.listGitWorktrees(r):Yu(r)}async function Km(r,s){const t=Qt();return t?t.addGitWorktree(r,s):im(r,s)}async function Il(r,s){const t=Qt();return t?t.removeGitWorktree(r,s):Ju(r,s)}async function Ym(r){const s=Qt();return s?s.ensureOpenChamberIgnored(r):om(r)}async function Xm(r,s={}){const t=Qt();return t?t.gitPush(r,s):am(r,s)}async function Jm(){const r=Qt();return r?r.getGitIdentities():nm()}async function Zm(r){const s=Qt();return s?s.createGitIdentity(r):sm(r)}async function Qm(r,s){const t=Qt();return t?t.updateGitIdentity(r,s):tm(r,s)}async function ef(r){const s=Qt();return s?s.deleteGitIdentity(r):em(r)}async function tf(r){const s=Qt();return s?s.getCurrentGitIdentity(r):rm(r)}const sf=".openchamber",Ts=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Oa=(r,s)=>{const t=Ts(r),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Fl=r=>r?r.startsWith("refs/heads/")?r.substring(11):r.startsWith("heads/")?r.substring(6):r.startsWith("refs/")?r.substring(5):r:"",rf=async r=>{try{await Ce.createDirectory(r)}catch(s){if(s instanceof Error&&/exist/i.test(s.message))return;throw s}};async function nf(r,s){const t=Ts(r),n=Oa(t,sf);return await rf(n),Oa(n,s)}async function of(r){const{projectDirectory:s,worktreeSlug:t,branch:n,createBranch:o}=r,a=Ts(s),i=await nf(a,t);return await Km(a,{path:i,branch:n,createBranch:!!o}),{path:i,branch:n,label:Fl(n),projectDirectory:a,relativePath:i.startsWith(`${a}/`)?i.slice(a.length+1):i}}async function Ba(r){const{projectDirectory:s,path:t,force:n}=r,o=Ts(s);await Il(o,{path:t,force:n})}async function af(r){const{projectDirectory:s,path:t,branch:n,force:o,deleteRemote:a,remote:i}=r,c=Ts(s),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Il(c,{path:t,force:o}),d&&(await Vm(c,{branch:d,force:!0}),a))try{await Gm(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Tn(r){const s=Ts(r);return qm(s)}async function gn(r){const s=Ts(r),t=await Um(s);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function In(r,s){const t=Ts(r),n=Ts(s.worktree);return{path:n,branch:s.branch??"",label:Fl(s.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const $a=r=>{if(!r||typeof r!="object")return null;const s={};return typeof r.showReasoningTraces=="boolean"&&(s.showReasoningTraces=r.showReasoningTraces),Object.keys(s).length>0?s:null},lf=r=>!r||typeof r!="object"?null:{showReasoningTraces:r.showReasoningTraces},cf=r=>{const s=Pe.getState();typeof r.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(r.showReasoningTraces)},df=async()=>{if(typeof window>"u")return null;if(es()){const s=window.opencodeAppearance;if(!s||typeof s.load!="function")return null;try{const t=await s.load();return $a(typeof t=="object"&&t!==null?t:null)}catch(t){return console.warn("Failed to load appearance preferences from desktop storage:",t),null}}const r=localStorage.getItem("appearance-preferences");if(!r)return null;try{const s=JSON.parse(r),t=lf(s);return $a(t)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let Pl=null;const za=r=>{Pl=r},Rl=()=>Pl,xn=r=>{typeof window>"u"||(r.themeId&&localStorage.setItem("selectedThemeId",r.themeId),r.themeVariant&&localStorage.setItem("selectedThemeVariant",r.themeVariant),r.lightThemeId&&localStorage.setItem("lightThemeId",r.lightThemeId),r.darkThemeId&&localStorage.setItem("darkThemeId",r.darkThemeId),typeof r.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(r.useSystemTheme)),r.lastDirectory&&localStorage.setItem("lastDirectory",r.lastDirectory),r.homeDirectory&&(localStorage.setItem("homeDirectory",r.homeDirectory),window.__OPENCHAMBER_HOME__=r.homeDirectory),Array.isArray(r.pinnedDirectories)&&r.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(r.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},Ll=()=>{const r=Pe.persist;if(r&&typeof r=="object")return r},_l=()=>Rl()?.settings??null,yn=r=>{const s=Pe.getState();typeof r.showReasoningTraces=="boolean"&&r.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(r.showReasoningTraces)},Ha=r=>{if(!r||typeof r!="object")return null;const s=r,t={};return typeof s.themeId=="string"&&s.themeId.length>0&&(t.themeId=s.themeId),(s.useSystemTheme===!0||s.useSystemTheme===!1)&&(t.useSystemTheme=s.useSystemTheme),typeof s.themeVariant=="string"&&(s.themeVariant==="light"||s.themeVariant==="dark")&&(t.themeVariant=s.themeVariant),typeof s.lightThemeId=="string"&&s.lightThemeId.length>0&&(t.lightThemeId=s.lightThemeId),typeof s.darkThemeId=="string"&&s.darkThemeId.length>0&&(t.darkThemeId=s.darkThemeId),typeof s.lastDirectory=="string"&&s.lastDirectory.length>0&&(t.lastDirectory=s.lastDirectory),typeof s.homeDirectory=="string"&&s.homeDirectory.length>0&&(t.homeDirectory=s.homeDirectory),Array.isArray(s.approvedDirectories)&&(t.approvedDirectories=s.approvedDirectories.filter(n=>typeof n=="string"&&n.length>0)),Array.isArray(s.securityScopedBookmarks)&&(t.securityScopedBookmarks=s.securityScopedBookmarks.filter(n=>typeof n=="string"&&n.length>0)),Array.isArray(s.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(s.pinnedDirectories.filter(n=>typeof n=="string"&&n.length>0)))),typeof s.showReasoningTraces=="boolean"&&(t.showReasoningTraces=s.showReasoningTraces),t},uf=async()=>{const r=_l();if(r)try{const s=await r.load();return Ha(s.settings)}catch(s){console.warn("Failed to load shared settings from runtime settings API:",s)}try{const s=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)return null;const t=await s.json().catch(()=>null);return Ha(t)}catch(s){return console.warn("Failed to load shared settings from server:",s),null}},Ol=async()=>{if(typeof window>"u")return;const r=Ll(),s=t=>{xn(t);const n=()=>yn(t);if(r?.hasHydrated?.())n();else if(n(),r?.onFinishHydration){const o=r.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))};try{const t=es()?await Al():await uf();t&&s(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},Ns=async r=>{if(typeof window>"u")return;if(es()){try{const t=await fm(r);t&&(xn(t),yn(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const s=_l();if(s)try{const t=await s.save(r);t&&(xn(t),yn(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(r)});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&&(xn(n),yn(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Bl=async()=>{if(typeof window>"u")return;const r=Ll();try{const s=await df();if(!s)return;const t=()=>cf(s);if(r?.hasHydrated?.()){t();return}if(t(),r?.onFinishHydration){const n=r.onFinishHydration(()=>{n?.(),t()})}}catch(s){console.warn("Failed to load appearance preferences:",s)}},Pr="useCommandsStore",To=r=>new Promise(s=>setTimeout(s,r)),mf=2e4,Wa=300,Ua=4,ff=800,pf=200,hf=2e3,Sr=$t()(Wt(ys((r,s)=>({selectedCommandName:null,commands:[],isLoading:!1,setSelectedCommand:t=>{r({selectedCommandName:t})},loadCommands:async()=>{r({isLoading:!0});const t=s().commands;let n=null;for(let o=0;o<3;o++)try{const a=await Ce.listCommandsWithDetails();return r({commands:a,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load commands:",n),r({commands:t,isLoading:!1}),!1},createCommand:async t=>{$s("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),console.log("[CommandsStore] Command config to save:",o);const a=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const u=i?.error||"Failed to create command";throw new Error(u)}if(console.log("[CommandsStore] Command created successfully"),i?.requiresReload??!0)return n=!0,await eo({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadCommands();return d&&Es("commands",{source:Pr}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||ns()}},updateCommand:async(t,n)=>{$s("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=await fetch(`/api/config/commands/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),c=await i.json().catch(()=>null);if(!i.ok){const p=c?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),c?.requiresReload??!0)return o=!0,await eo({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadCommands();return u&&Es("commands",{source:Pr}),u}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||ns()}},deleteCommand:async t=>{$s("Deleting command configuration…");let n=!1;try{const o=await fetch(`/api/config/commands/${encodeURIComponent(t)}`,{method:"DELETE"}),a=await o.json().catch(()=>null);if(!o.ok){const d=a?.error||"Failed to delete command";throw new Error(d)}if(console.log("[CommandsStore] Command deleted successfully"),a?.requiresReload??!0)return n=!0,await eo({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadCommands();return c&&Es("commands",{source:Pr}),s().selectedCommandName===t&&r({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||ns()}},getCommandByName:t=>{const{commands:n}=s();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:bs(()=>ts()),partialize:r=>({selectedCommandName:r.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Sr);async function gf(r){const s=typeof r=="number"&&r>0?Math.min(r,Wa):0;s>0&&await To(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<mf;){n+=1,cs(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ce.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=Ua&&a<1200?Wa:Math.min(ff+Math.max(0,n-Ua)*pf,hf);await To(i)}throw o||new Error("OpenCode did not become ready in time")}async function eo(r={}){const{message:s,delayMs:t}=r;try{cs(s||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("commands-store"),window.localStorage.removeItem("config-store"))}catch(n){console.warn("[CommandsStore] Failed to prepare config refresh:",n)}try{await gf(t),cs("Refreshing providers and commands…");const n=kt.getState(),o=Sr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),Es("commands",{source:Pr})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),cs("OpenCode reload failed. Please retry refreshing configuration manually."),await To(1500)}finally{ns()}}let Va=null;Va||(Va=na(r=>{if(r.source!==Pr&&Mn(r,"commands")){const{loadCommands:s}=Sr.getState();s()}}));const xf=3e4,yf=40,bf=60,wf=(r,s,t)=>{const n=r.trim(),o=s.trim().toLowerCase();return`${n}::${o}::${t}`},ia=$t()(Wt((r,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=bf){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=wf(a,i,o),d=Date.now(),u=s().cache[c];if(u&&d-u.timestamp<xf)return u.files;const p=s().inFlight[c];if(p)return p;const m=Ce.searchFiles(i,{directory:a,limit:o}).then(f=>(r(h=>{const g={...h.cache,[c]:{files:f,timestamp:Date.now()}},b=h.cacheKeys.filter(x=>x!==c);for(b.push(c);b.length>yf;){const x=b.shift();x&&delete g[x]}return{cache:g,cacheKeys:b}}),f)).finally(()=>{r(f=>{const h={...f.inFlight};return delete h[c],{inFlight:h}})});return r(f=>({inFlight:{...f.inFlight,[c]:m}})),m},invalidateDirectory(t){if(!t||t.trim().length===0){r({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;r(a=>{const i={...a.cache},c=a.cacheKeys.filter(p=>p.startsWith(o)?(delete i[p],!1):!0),d=Object.entries(a.inFlight).filter(([p])=>!p.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"}));var vf={};let As=null;const gs=ts(),Ga=gs.getItem("lastDirectory"),jf=typeof Ga=="string"&&Ga.length>0,Yr=(r,s)=>((s?.showOverlay??!0)&&$s("Switching project directory…"),Ce.setOpenCodeWorkingDirectory(r).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),Xr=(r,s,t)=>{const{showOverlay:n}=s,o=()=>{try{me.getState().loadSessions()}catch(a){console.error("Failed to reload sessions after directory change:",a)}};(async()=>{let a=null;try{a=await r}catch(i){console.error("Failed to update OpenCode working directory:",i),n&&(cs("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),ns()),t?.(a),o();return}try{if(a&&a.restarted){try{typeof window<"u"&&window.localStorage&&window.localStorage.removeItem("commands-store")}catch(i){console.warn("Failed to reset commands-store cache:",i)}await Im({message:"Refreshing OpenCode configuration…"});try{await Sr.getState().loadCommands();try{Es("commands",{source:"useCommandsStore"})}catch(i){console.warn("Failed to emit command configuration change:",i)}}catch(i){console.warn("Failed to reload commands after directory change:",i)}}else n&&ns()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(cs("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),ns())}finally{t?.(a),o()}})()},Jr=r=>{try{ia.getState().invalidateDirectory(r)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},Fn=()=>{if(typeof window<"u"){const s=gs.getItem("lastDirectory");if(s)return s;if(As)return As;const t=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(t&&t.length>0)return As=t,gs.setItem("homeDirectory",t),t;const n=gs.getItem("homeDirectory");if(n)return As=n,n}const r=typeof process<"u"&&vf?.HOME;return r||process?.cwd?.()||"/"},Sf=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.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},kf=r=>(As=r,typeof window<"u"&&gs.setItem("homeDirectory",r),Ns({homeDirectory:r}),r),$l=async()=>{const r=n=>{const o=Sf(n);return o?kf(o):null};try{const n=await Ce.getFilesystemHome(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Ce.getSystemInfo(),o=r(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await Ml(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const s=Fn(),t=r(s);return t||s},er=Fn();er&&Ce.setDirectory(er);const Nf=!!(er&&er!=="/"),St=$t()(Wt((r,s)=>({currentDirectory:er,directoryHistory:[er],historyIndex:0,homeDirectory:er,hasPersistedDirectory:jf,isHomeReady:Nf,isSwitchingDirectory:!1,setDirectory:(t,n)=>{console.log("[DirectoryStore] setDirectory called with path:",t);const o=n?.showOverlay??!0;Ce.setDirectory(t),Jr();const a=Yr(t,{showOverlay:o});console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),r(i=>{const c=[...i.directoryHistory.slice(0,i.historyIndex+1),t];return gs.setItem("lastDirectory",t),Ns({lastDirectory:t}),{currentDirectory:t,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),Xr(a,{showOverlay:o},()=>{r(i=>i.currentDirectory!==t?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})},goBack:()=>{const t=s();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];Ce.setDirectory(o),Jr();const a=Yr(o);gs.setItem("lastDirectory",o),Ns({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Xr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goForward:()=>{const t=s();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];Ce.setDirectory(o),Jr();const a=Yr(o);gs.setItem("lastDirectory",o),Ns({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Xr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=s(),o=As||s().homeDirectory||Fn();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=As||Fn();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=As||s().homeDirectory||await $l();s().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=s(),o=t;As=o;const a=n.homeDirectory!==o,i=gs.getItem("lastDirectory"),c=typeof i=="string"&&i.length>0,d=!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||r({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",p={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d&&(p.currentDirectory=o,p.directoryHistory=[o],p.historyIndex=0,p.isSwitchingDirectory=!0),r(()=>p),d&&u){Ce.setDirectory(o),Jr(),gs.setItem("lastDirectory",o),Ns({lastDirectory:o});const m=Yr(o,{showOverlay:!1});Xr(m,{showOverlay:!1},()=>{r(f=>f.currentDirectory!==o?{}:f.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}Ns({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&$l().then(r=>{St.getState().synchronizeHomeDirectory(r)});const zl=ts(),Hl="oc.sessionSelectionByDirectory",qa=".openchamber",Cf=()=>{try{const r=zl.getItem(Hl);if(!r)return{};const s=JSON.parse(r);return!s||typeof s!="object"?{}:Object.entries(s).reduce((t,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(t[n]=o),t),{})}catch{return{}}};let bn=null;const la=()=>(bn||(bn=Cf()),bn),Wl=r=>{bn=r;try{zl.setItem(Hl,JSON.stringify(r))}catch{}},Ul=r=>{if(!r)return null;const t=la()[r];return typeof t=="string"?t:null},Gs=(r,s)=>{if(!r)return;const t={...la()};s?t[r]=s:delete t[r],Wl(t)},Mf=(r,s)=>{if(!r)return;const t=Ul(r);if(!t)return;if(!new Set(s).has(t)){const o={...la()};delete o[r],Wl(o)}},Ka=async(r,s)=>{const t=r.status??await gn(r.path).catch(()=>{});await af({projectDirectory:r.projectDirectory,path:r.path,branch:r.branch,force:!!t?.isDirty,deleteRemote:!!s?.deleteRemoteBranch,remote:s?.remoteName})},_t=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},or=(r,s)=>{const t=r.find(n=>n.id===s);return t?_t(t.directory??null):null},Af=async(r,s,t)=>{const n=_t(s);if(!n||r.length===0)return null;const o=r.map(u=>({id:u.id,directory:_t(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Tn(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 p=new Map(t);return o.forEach(({id:m})=>{p.delete(m)&&(u=!0)}),u?p:null}const i=new Map;a.forEach(u=>{const p=In(n,u),m=_t(p.path)??p.path;m!==n&&i.set(m,p)});let c=!1;const d=new Map(t);return o.forEach(({id:u,directory:p})=>{const m=i.get(p);if(!m){d.delete(u)&&(c=!0);return}const f=d.get(u);(!f||f.path!==m.path||f.branch!==m.branch||f.label!==m.label)&&(d.set(u,m),c=!0)}),c?d:null},st=$t()(Wt(ys((r,s)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],loadSessions:async()=>{r({isLoading:!0,error:null});try{const n=St.getState().currentDirectory??Ce.getDirectory()??null,o=Ce.getApiClient(),a=async D=>{const N=await o.session.list({query:D?{directory:D}:void 0});return Array.isArray(N.data)?N.data:[]},i=_t(n),c=i?await aa(i).catch(()=>!1):!1,d=await a(i||null),u=[];let p=[];if(n&&c&&i){const D=`${i}/${qa}`;try{const N=new Set;D&&(await Ce.listLocalDirectory(D)).filter(E=>E.isDirectory).forEach(E=>{const W=/^([A-Za-z]:)?\//.test(E.path)?E.path:`${D}/${E.name}`;N.add(_t(W)??W)});const C=await Tn(i);Array.isArray(C)&&(p=C.map(M=>In(i,M)).filter(M=>M.path.includes(`/${qa}/`)),p.forEach(M=>N.add(M.path))),N.size>0&&(await Promise.allSettled(Array.from(N).map(E=>a(E)))).forEach(E=>{E.status==="fulfilled"&&Array.isArray(E.value)&&u.push(...E.value)})}catch{p=[]}}const m=new Set;i&&m.add(i),p.forEach(D=>{const N=_t(D.path);N&&m.add(N)});const f=[...d,...u].filter(D=>{const N=D.directory??i??null,C=_t(N);return C?m.has(C):!1}),h=s(),g=h.lastLoadedDirectory??null,b=n!==g;let x=[...f],w=h.currentSessionId;const S=D=>{x=[D,...x.filter(N=>N.id!==D.id)]};if(b)w=x.length>0?x[0].id:null;else if(w){if(!x.some(N=>N.id===w)){const N=h.sessions.find(C=>C.id===w);if(N)S(N);else try{const C=await Ce.getSession(w);S(C)}catch{w=x.length>0?x[0].id:null}}}else w=x.length>0?x[0].id:null;const v=x.reduce((D,N)=>(D.some(C=>C.id===N.id)||D.push(N),D),[]);w&&!v.some(D=>D.id===w)&&(w=v.length>0?v[0].id:null);const j=new Set(v.map(D=>D.id));if(n){Mf(n,j);const D=Ul(n);D&&j.has(D)&&(w=D)}let k=null;try{k=await Af(v,n,h.worktreeMetadata)}catch(D){console.debug("Failed to refresh worktree metadata during session load:",D)}const y=(()=>{const D=k??h.worktreeMetadata;if(!b||!i)return D;const N=new Map;return D.forEach((C,M)=>{_t(C.projectDirectory)===i&&N.set(M,C)}),N})(),A=(()=>{if(!w)return i??null;const D=y.get(w)?.path;if(D)return _t(D)??D;const N=or(v,w);return N||(i??null)})();try{Ce.setDirectory(A??void 0)}catch(D){console.warn("Failed to sync OpenCode directory after session load:",D)}r({sessions:v,currentSessionId:w,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:y,availableWorktrees:p}),Gs(A??n,w)}catch(t){r({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,n,o)=>{r({error:null});const a=St.getState(),i=_t(a.currentDirectory),c=_t(n??Ce.getDirectory()??i),d=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=s(),p=new Set(u.sessions.map(g=>g.id)),m={id:d,title:t||"New session",parentID:o??void 0,directory:c??null,projectID:u.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(r(g=>({sessions:[m,...g.sessions],currentSessionId:d,webUICreatedSessions:new Set([...g.webUICreatedSessions,d]),isLoading:!1})),c)try{Ce.setDirectory(c)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const f=g=>{r(b=>({sessions:b.sessions.map(w=>w.id===d?g:w),currentSessionId:g.id,webUICreatedSessions:new Set([...Array.from(b.webUICreatedSessions).filter(w=>w!==d),g.id])})),Gs(c??null,g.id)},h=async()=>{const g=Ce.getApiClient(),b=20;for(let x=0;x<b;x+=1){try{const w=await g.session.list({query:c?{directory:c}:void 0}),v=(Array.isArray(w.data)?w.data:[]).find(j=>!(p.has(j.id)||t&&j.title&&j.title!==t));if(v)return v}catch(w){console.debug("Session poll attempt failed:",w)}await new Promise(w=>setTimeout(w,2e3))}return null};try{const g=()=>Ce.createSession({title:t,parentID:o??void 0});let b=null;try{b=c?await Ce.withDirectory(c,g):await g()}catch(x){console.warn("Direct session create failed or timed out, falling back to polling:",x)}return b||(b=await h()),b?(f(b),b):(r(x=>({sessions:x.sessions.filter(w=>w.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(x.webUICreatedSessions).filter(w=>w!==d)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return r(b=>({sessions:b.sessions.filter(x=>x.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(x=>x!==d)),isLoading:!1,error:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{r({isLoading:!0,error:null});const o=s().worktreeMetadata.get(t),a=or(s().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await Ka(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Ce.deleteSession(t);if(!(i?await Ce.withDirectory(i,d):await d()))return r(f=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const g=new Map(f.worktreeMetadata);g.delete(t),h.worktreeMetadata=g}return h}),!1;let p=null;r(f=>{const h=f.sessions.filter(x=>x.id!==t);p=f.currentSessionId===t?null:f.currentSessionId;const g=new Map(f.worktreeMetadata);g.delete(t);const b=n?.archiveWorktree&&o?f.availableWorktrees.filter(x=>_t(x.path)!==_t(o.path)):f.availableWorktrees;return{sessions:h,currentSessionId:p,isLoading:!1,worktreeMetadata:g,availableWorktrees:b}});const m=i??Ce.getDirectory()??null;return Gs(m,p),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return r(c?p=>{const m=new Map(p.worktreeMetadata);return m.delete(t),{worktreeMetadata:m,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(b=>typeof b=="string"&&b.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};r({isLoading:!0,error:null});const a=[],i=[],c=new Set,d=[],u=new Set;for(const b of o)try{const x=s().worktreeMetadata.get(b),w=or(s().sessions,b),S=x?.path??w;x&&n?.archiveWorktree&&!u.has(x.path)&&(await Ka(x,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c.add(b),d.push({path:x.path,projectDirectory:x.projectDirectory}),u.add(x.path));const v=()=>Ce.deleteSession(b);(S?await Ce.withDirectory(S,v):await v())?(a.push(b),x?.path&&!d.some(k=>k.path===x.path)&&d.push({path:x.path,projectDirectory:x.projectDirectory})):i.push(b)}catch{i.push(b)}const p=St.getState();d.forEach(({path:b,projectDirectory:x})=>{p.currentDirectory===b&&p.setDirectory(x,{showOverlay:!1})});const m=new Set(a),f=i.length>0?i.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let h=null;r(b=>{const x=b.sessions.filter(j=>!m.has(j.id));b.currentSessionId&&m.has(b.currentSessionId)?h=x.length>0?x[0].id:null:h=b.currentSessionId;const w=new Map(b.worktreeMetadata);for(const j of m)w.delete(j);for(const j of c)w.delete(j);const S=new Set(d.map(j=>_t(j.path)).filter(j=>!!j)),v=S.size>0?b.availableWorktrees.filter(j=>!S.has(_t(j.path)??j.path)):b.availableWorktrees;return{sessions:x,currentSessionId:h,isLoading:!1,worktreeMetadata:w,availableWorktrees:v,error:f}});const g=Ce.getDirectory()??null;return Gs(g,h),{deletedIds:a,failedIds:i}},updateSessionTitle:async(t,n)=>{try{const o=or(s().sessions,t),a=s().worktreeMetadata.get(t),i=()=>Ce.updateSession(t,n),c=a?.path??o,d=c?await Ce.withDirectory(c,i):await i();r(u=>({sessions:u.sessions.map(p=>p.id===t?d:p)}))}catch(o){r({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=or(s().sessions,t),o=Ce.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ce.getDirectory();return o.session.share({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Ce.withDirectory(i,c):await c();return d.data?(r(u=>({sessions:u.sessions.map(p=>p.id===t?d.data:p)})),d.data):null}catch(n){return r({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=or(s().sessions,t),o=Ce.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ce.getDirectory();return o.session.unshare({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Ce.withDirectory(i,c):await c();return d.data?(r(u=>({sessions:u.sessions.map(p=>p.id===t?d.data:p)})),d.data):null}catch(n){return r({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{r({currentSessionId:t,error:null});const n=Ce.getDirectory()??null;Gs(n,t)},clearError:()=>{r({error:null})},getSessionsByDirectory:()=>{const{sessions:t}=s();return t},applySessionMetadata:(t,n)=>{!t||!n||r(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const i=o.sessions[a],c=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,p={...i,...n,time:c,summary:d,share:u},m=p.title!==i.title||p.parentID!==i.parentID||p.directory!==i.directory||p.version!==i.version||p.projectID!==i.projectID||JSON.stringify(p.time)!==JSON.stringify(i.time)||JSON.stringify(p.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(p.share??null)!==JSON.stringify(i.share??null),f=[...o.sessions];return f[a]=m?p:i,m?{sessions:f}:o})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=s();return n.has(t)},markSessionAsOpenChamberCreated:t=>{r(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=s();n(t)},setWorktreeMetadata:(t,n)=>{t&&r(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return s().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=s().sessions,a=o.findIndex(u=>u.id===t);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(r(u=>{const p=[...u.sessions],m={...p[a]};return d!==void 0?m.directory=d:delete m.directory,p[a]=m,{sessions:p}}),c&&Gs(c,null),n&&Gs(n,t))},updateSession:t=>{r(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:bs(()=>ts()),partialize:r=>({currentSessionId:r.currentSessionId,sessions:r.sessions,lastLoadedDirectory:r.lastLoadedDirectory,webUICreatedSessions:Array.from(r.webUICreatedSessions),worktreeMetadata:Array.from(r.worktreeMetadata.entries()),availableWorktrees:r.availableWorktrees}),merge:(r,s)=>{if(!(u=>typeof u=="object"&&u!==null)(r))return s;const n=Array.isArray(r.sessions)?r.sessions:s.sessions,o=typeof r.currentSessionId=="string"||r.currentSessionId===null?r.currentSessionId:s.currentSessionId,a=Array.isArray(r.webUICreatedSessions)?r.webUICreatedSessions:[],i=Array.isArray(r.worktreeMetadata)?r.worktreeMetadata:[],c=Array.isArray(r.availableWorktrees)?r.availableWorktrees:s.availableWorktrees,d=typeof r.lastLoadedDirectory=="string"?r.lastLoadedDirectory:s.lastLoadedDirectory??null;return{...s,...r,sessions:n,currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:c,lastLoadedDirectory:d}}}),{name:"session-store"})),Vl="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.",to=r=>typeof r=="string"&&r.trim()===Vl.trim(),so=(r,s)=>{const t=Date.now(),n=r.get(s),o=new Map(r);return o.set(s,{phase:"streaming",startedAt:n?.startedAt??t,lastUpdateAt:t}),o},Cr=(r,s)=>{const t=Array.from(s);if(!t.some(a=>r.has(a)))return r;const o=new Map(r);return t.forEach(a=>{o.delete(a)}),o},Ya=new Map,Gl=r=>{const s=Ya.get(r);s&&(clearTimeout(s),Ya.delete(r))},qs=r=>{for(const s of r)Gl(s)},$r=r=>{if(!r)return"";if(typeof r=="string")return r;if(Array.isArray(r))return r.map(s=>$r(s)).join("");if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(Array.isArray(r.content))return r.content.map(s=>$r(s)).join("")}return""},Rr=r=>{if(!r)return"";const s=r;if(typeof s.text=="string")return s.text;if(Array.isArray(s.text))return s.text.map(n=>typeof n=="string"?n:Rr(n)).join("");const t=$r(s.delta);return t||(typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||$r(o.delta)||""}return""}).join(""):"")},Mr=(r,s)=>{const t={...r};if(t.type=t.type||"text",t.type==="text"){const n=s&&typeof s.text=="string"?s.text:"",o=typeof t.text=="string"?t.text:"",a=$r(r.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},Xa=10*1024*1024,Df=r=>{const s=(r||"").toLowerCase();switch(s.includes(".")&&s.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"}},Ef=r=>{if(r.type&&r.type.trim().length>0)return r.type;const s=(r.name||"").toLowerCase(),t=s.includes(".")&&s.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(s))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"}},Tf=r=>{const s=r.replace(/\s+/g,"");if(!s)return 0;const t=s.endsWith("==")?2:s.endsWith("=")?1:0;return Math.floor(s.length*3/4)-t},If=r=>{const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<r.length;n+=3){const o=r[n]??0,a=r[n+1],i=r[n+2],c=o<<16|(a??0)<<8|(i??0);t+=s[c>>18&63],t+=s[c>>12&63],t+=typeof a=="number"?s[c>>6&63]:"=",t+=typeof i=="number"?s[c&63]:"="}return t},Os=$t()(Wt(ys((r,s)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=s();if(n.some(g=>g.filename===t.name&&g.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=Xa;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 10MB.`);const i=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],c=Ef(t);!i.some(g=>c.startsWith(g)||c===g||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,p=await new Promise((g,b)=>{u.onload=()=>g(u.result),u.onerror=b,u.readAsDataURL(t)}),m=p.startsWith("data:")?p.replace(/^data:[^;]*/,`data:${c}`):p,f=g=>{const b=g.replace(/\\/g,"/").split("/");return b[b.length-1]||g},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:m,mimeType:c,filename:f(t.name),size:t.size,source:"local"};r(g=>({attachedFiles:[...g.attachedFiles,h]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=s();if(a.some(w=>w.serverPath===t&&w.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,u;if(!c)try{const w=Ce.getApiClient(),S=t.lastIndexOf("/"),v=S>0?t.substring(0,S):"/",j=S>0?t.substring(S+1):t,k=await w.file.read({query:{path:j,directory:v}});k.data&&"content"in k.data?(c=k.data.content,d=k.data.encoding??void 0,u=k.data.mimeType??void 0):c=""}catch(w){console.error("Failed to read server file:",w),c=`[File: ${n}]`}const p=u||Df(n),m=p&&p.trim().length>0?p:"application/octet-stream",f=(()=>{if(d==="base64")return c||"";const S=new TextEncoder().encode(c||"");return If(S)})(),h=d==="base64"?Tf(f):new TextEncoder().encode(c||"").length;if(h>Xa)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const g=new File([],n,{type:m}),b=`data:${m};base64,${f}`,x={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:g,dataUrl:b,mimeType:m,filename:n,size:h,source:"server",serverPath:t};r(w=>({attachedFiles:[...w.attachedFiles,x]}))},removeAttachedFile:t=>{r(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{r({attachedFiles:[]})}}),{name:"file-store",storage:bs(()=>ts()),partialize:r=>({attachedFiles:r.attachedFiles})}),{name:"file-store"}));let ro=[],no=null;const Ff=50,Pf=3e4,Ks=new Map,Zr=new Map,ar=new Map,Rf=10,Pn=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.indexOf("_"),n=t>=0?s.slice(t+1):s;return!n||n.length<Rf?null:n},Qr=(r,s)=>{const t=Pn(r),n=Pn(s);return!t||!n||t.length!==n.length?!0:t>n},Lf=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},en=r=>!Array.isArray(r)||r.length===0?0:r.reduce((s,t)=>{if(!t||t.type!=="text")return s;const n=t.text??t.content;return typeof n=="string"?s+n.length:s},0),Ja=r=>Array.isArray(r)?r.some(s=>s?.type==="step-finish"&&s?.reason==="stop"):!1,Za=r=>{if(r){if(typeof r.id=="string"&&r.id.length>0)return r.id;if(r.type){const s=r.reason,t=r.callID;return`${r.type}-${s??""}-${t??""}`}}},Qa=new Set,ei=(r=[],s=[])=>{if(!s.length)return[...r];const t=[...r],n=new Set(r.map(Za).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=Za(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},_f=(r,s)=>{let t=s,n=s?Pn(s):null;for(const o of r){const a=o?.info?.id,i=Pn(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},fs=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return t?o.set(s,t):o.delete(s),o},ir=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return o.set(s,t),o},tn=(r,s)=>{const t=new Map(r);let n=!1;for(const o of s)t.delete(o)&&(n=!0);return n?t:r},Of=(r,s)=>{const t=new Set,n=r.streamingMessageIds.get(s);return n&&t.add(n),r.messageStreamStates.forEach((o,a)=>{r.messageSessionIndex.get(a)===s&&t.add(a)}),t},ti=(r,s,t)=>r.streamingMessageIds.get(s)===t?!0:r.messageSessionIndex.get(t)===s&&r.messageStreamStates.has(t),Bf=async r=>{if(r)try{const s=st.getState(),t=s.getWorktreeMetadata(r);if(t?.path)return t.path;const n=s.sessions.find(a=>a.id===r);return typeof n?.directory=="string"&&n.directory.length>0?n.directory:void 0}catch(s){console.warn("Failed to resolve session directory override:",s);return}},oo=async(r,s)=>{const t=await Bf(r);return t?Ce.withDirectory(t,s):s()},lt=$t()(Wt(ys((r,s)=>({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,loadMessages:async(t,n=Ot.VIEWPORT_MESSAGES)=>{const o=await oo(t,()=>Ce.getSessionMessages(t)),a=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=(a?o.filter(d=>{const u=d?.info?.id;return u?Qr(u,a):!0}):o).slice(-n);r(d=>{const u=new Map(d.messages),p=d.messages.get(t)||[],m=new Map(p.filter(A=>typeof A.info?.id=="string").map(A=>[A.info.id,A])),h=c.map(A=>{const D={...A.info,clientRole:A.info?.clientRole??A.info.role,userMessageMarker:A.info.role==="user"?!0:A.info?.userMessageMarker},N=(Array.isArray(A.parts)?A.parts:[]).map(M=>{if(M?.type==="text"){const E=M.text??M.content??"";if(to(E))return{...M,synthetic:!0}}return M}),C=D?.id?m.get(D.id):void 0;if(C&&C.info.role==="assistant"){const M=Array.isArray(C.parts)?C.parts:[],E=en(M),F=en(N);if(Ja(M)&&E>F){const L=ei(M,N);return{...A,info:D,parts:L}}}return{...A,info:D,parts:N}}),g=new Set(p.map(A=>A.info.id)),b=new Set(h.map(A=>A.info.id)),x=[];g.forEach(A=>{b.has(A)||x.push(A)}),u.set(t,h);const w=new Map(d.sessionMemoryState),S=d.sessionMemoryState.get(t);w.set(t,{viewportAnchor:h.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>c.length,trimmedHeadMaxId:S?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const v={messages:u,sessionMemoryState:w};qs(x);const j=Cr(d.messageStreamStates,x);if(j!==d.messageStreamStates&&(v.messageStreamStates=j),x.length>0){const A=d.streamingMessageIds.get(t);A&&x.includes(A)&&(v.streamingMessageIds=fs(v.streamingMessageIds??d.streamingMessageIds,t,null))}if(x.length>0){const A=tn(v.messageSessionIndex??d.messageSessionIndex,x);A!==(v.messageSessionIndex??d.messageSessionIndex)&&(v.messageSessionIndex=A)}if(x.length>0){const A=new Map(d.pendingAssistantParts);let D=!1;x.forEach(N=>{A.delete(N)&&(D=!0)}),D&&(v.pendingAssistantParts=A)}const k=v.messageSessionIndex??d.messageSessionIndex;let y=k;return h.forEach(A=>{const D=A?.info?.id;typeof D=="string"&&D.length>0&&(y=ir(y,D,t))}),y!==k&&(v.messageSessionIndex=y),v})},sendMessage:async(t,n,o,a,i,c,d)=>{if(!i)throw new Error("No session selected");const u=i;s().sessionAbortFlags.has(u)&&r(p=>{const m=new Map(p.sessionAbortFlags);return m.delete(u),{sessionAbortFlags:m}}),await oo(u,async()=>{try{let p=t;if(t.startsWith("/")){const f=t.indexOf(" "),h=f===-1?t.substring(1):t.substring(1,f),g=f===-1?"":t.substring(f+1).trim(),b=Ce.getApiClient(),x=Ce.getDirectory();if(h==="init"){const w=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await b.session.init({path:{id:u},body:{messageID:w,providerID:n,modelID:o},query:x?{directory:x}:void 0});return}if(h==="summarize"){await b.session.summarize({path:{id:u},body:{providerID:n,modelID:o},query:x?{directory:x}:void 0});return}try{const w=await Ce.getCommandDetails(h);w?.template?p=w.template.replace(/\$ARGUMENTS/g,g):p=t}catch(w){console.error("Command template resolution failed:",w),p=t}}r({lastUsedProvider:{providerID:n,modelID:o}}),r(f=>{const h=f.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=ar.get(u);g&&(clearTimeout(g),ar.delete(u));const b=new Map(f.sessionMemoryState);return b.set(u,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:b}});try{const f=new AbortController;r(g=>{const b=new Map(g.abortControllers);return b.set(u,f),{abortControllers:b}});const h=(c??[]).map(g=>({type:"file",mime:g.mimeType,filename:g.filename,url:g.dataUrl}));if(await Ce.sendMessage({id:u,providerID:n,modelID:o,text:p,agent:a,files:h.length>0?h:void 0,agentMentions:d?[{name:d}]:void 0}),h.length>0)try{Os.getState().clearAttachedFiles()}catch(g){console.error("Failed to clear attached files after send",g)}r(g=>{const b=new Map(g.abortControllers);return b.delete(u),{abortControllers:b}})}catch(f){let h="Network error while sending message. The message may still be processing.";if(f.name==="AbortError")h="Request timed out. The message may still be processing.";else if(f.message?.includes("504")||f.message?.includes("Gateway")){h="Gateway timeout - your message is being processed. Please wait for response.",r(g=>{const b=new Map(g.abortControllers);return b.delete(u),{abortControllers:b}});return}else f.message&&(h=f.message);throw r(g=>{const b=new Map(g.abortControllers);return b.delete(u),{abortControllers:b}}),new Error(h)}}catch(p){let m="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?m="Request timed out. The message may still be processing.":p.response?.status===401?m="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?m="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?m="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(m=p.message),r(f=>{const h=new Map(f.abortControllers);return h.delete(u),{abortControllers:h}}),new Error(m)}})},abortCurrentOperation:async t=>{if(!t)return;const n=s(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=Of(n,t);if(c.size===0){const u=t?a.get(t)??[]:[];let p=null;for(let m=u.length-1;m>=0;m-=1){const f=u[m];if(!f||f.info.role!=="assistant")continue;if(p||(p=f.info.id),(f.parts??[]).some(g=>g.type==="reasoning"||g.type==="tool"||g.type==="step-start")){c.add(f.info.id);break}}c.size===0&&p&&c.add(p)}for(const u of c){const p=Ks.get(u);p&&(clearTimeout(p),Ks.delete(u),Zr.delete(u))}c.size>0&&qs(c);const d=Date.now();r(u=>{const p=Cr(u.messageStreamStates,c),m=u.messages.get(t)??[];let f=!1,h=u.messages;if(m.length>0&&c.size>0){const w=m.map(S=>{if(!c.has(S.info.id)&&c.size>0)return S;const v=(S.parts??[]).map(j=>{if(j.type==="reasoning"){const k=j,y={...k.time??{}};return typeof y.end!="number"&&(y.end=d),{...k,time:y}}if(j.type==="tool"){const k=j,y={...k.state??{}};return(y.status==="running"||y.status==="pending")&&(y.status="aborted"),{...k,state:y}}return j.type==="step-start"?{...j,type:"step-finish",aborted:!0}:j});return f=!0,{...S,info:{...S.info,abortedAt:d,streaming:!1,status:"aborted"},parts:v}});f&&(h=new Map(u.messages),h.set(t,w))}const g=u.sessionMemoryState.get(t);let b=u.sessionMemoryState;if(g){const w=new Map(u.sessionMemoryState);w.set(t,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),b=w}const x=new Map(u.sessionAbortFlags);return x.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:p,sessionMemoryState:b,sessionAbortFlags:x,abortControllers:(()=>{const w=new Map(u.abortControllers);return w.delete(t),w})(),streamingMessageIds:fs(u.streamingMessageIds,t,null),...f?{messages:h}:{}}}),Ce.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=s();if(Qa.has(n))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!Qr(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.messages.get(t)||[],p=u.find(g=>g.info.id===n),m=a==="user"||p?.info.role==="user"?"user":a||p?.info.role||"assistant",f=s().sessionMemoryState.get(t);if(f?.streamStartTime&&Date.now()-f.streamStartTime>Ot.ZOMBIE_TIMEOUT){f.isZombie||r(b=>{const x=new Map(b.sessionMemoryState);return x.set(t,{...f,isZombie:!0}),{sessionMemoryState:x}}),setTimeout(()=>{s().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}r(g=>{const x=[...g.messages.get(t)||[]],w={},S=ir(g.messageSessionIndex,n,t);S!==g.messageSessionIndex&&(w.messageSessionIndex=S);const v=C=>{if(!((m==="assistant"||m==="user")&&g.sessionAbortFlags.has(t)))return C;const E=new Map(g.sessionAbortFlags);return E.delete(t),{...C,sessionAbortFlags:E}},j=C=>{const M=C||"",E=Zr.get(n);if(M&&E===M){const L=s();if(ti(L,t,n)){const K=Ks.get(n);K&&(clearTimeout(K),Ks.delete(n)),setTimeout(()=>{const X=s();typeof X.forceCompleteMessage=="function"&&X.forceCompleteMessage(t,n,"timeout"),X.completeStreamingMessage(t,n)},100)}}Zr.set(n,M);const F=Ks.get(n);F&&clearTimeout(F);const W=setTimeout(()=>{const L=s();typeof L.forceCompleteMessage=="function"&&L.forceCompleteMessage(t,n,"timeout"),ti(L,t,n)&&L.completeStreamingMessage(t,n),Ks.delete(n),Zr.delete(n)},8e3);Ks.set(n,W)},k=t!==i,y=g.sessionMemoryState.get(t);if(k&&y?.isStreaming){x.length>=Ot.BACKGROUND_STREAMING_BUFFER&&x.shift();const C=new Map(g.sessionMemoryState);C.set(t,{...y,backgroundMessageCount:(y.backgroundMessageCount||0)+1}),g.sessionMemoryState=C}if(m==="assistant"){const C=g.sessionMemoryState.get(t);if(C){const M=Date.now(),E=new Map(g.sessionMemoryState);E.set(t,{...C,isStreaming:!0,streamStartTime:C.streamStartTime??M,lastAccessedAt:M,isZombie:!1}),g.sessionMemoryState=E}}const A=Rr(o);if(to(A)&&(o.synthetic=!0),Lf()&&m==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:m,type:o?.type||"text",textLen:A.length,snapshotParts:u.length})}catch{}const D=w.streamingMessageIds??g.streamingMessageIds;if(m==="assistant"){const C=fs(D,t,n);C!==D&&(w.streamingMessageIds=C,window.__messageTracker?.(n,"streamingId_set_latest"))}const N=x.findIndex(C=>C.info.id===n);if(N!==-1&&m==="user"){const C=x[N],M=C.parts.findIndex(K=>K.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),g;const E=Mr(o,M!==-1?C.parts[M]:void 0);window.__messageTracker?.(n,`user_part_type:${E.type||"unknown"}`);const F={...C};M!==-1?F.parts=F.parts.map((K,X)=>X===M?E:K):F.parts=[...F.parts,E];const W=[...x];W[N]=F;const L=new Map(g.messages);return L.set(t,W),v({messages:L})}if(m==="assistant"&&N!==-1){const C=x[N],M=C.parts.findIndex(X=>X.id===o.id),E=Mr(o,M!==-1?C.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${E.type||"unknown"}`);const F={...C};M!==-1?F.parts=F.parts.map((X,z)=>z===M?E:X):F.parts=[...F.parts,E];const W=[...x];W[N]=F;const L=new Map(g.messages);L.set(t,W),w.messageStreamStates=so(g.messageStreamStates,n);const K=fs(w.streamingMessageIds??g.streamingMessageIds,t,n);return K!==(w.streamingMessageIds??g.streamingMessageIds)&&(w.streamingMessageIds=K,window.__messageTracker?.(n,"streamingId_set")),E.type==="text"?j(E.text||""):j(""),v({messages:L,...w})}if(N===-1){if(m==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),g;const G=Mr(o);window.__messageTracker?.(n,`new_user_part_type:${G.type||"unknown"}`);const H={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,time:{created:Date.now()}},parts:[G]},oe=[...x,H];oe.sort((Ee,Ie)=>{const ge=Ee.info?.time?.created||0,de=Ie.info?.time?.created||0;return ge-de});const ve=new Map(g.messages);return ve.set(t,oe),v({messages:ve})}if(o?.type==="text"){const G=Rr(o).trim();if(G.length>0){const H=[...x].reverse().find(oe=>oe.info.role==="user");if(H){const oe=H.parts.map(ve=>Rr(ve)).join("").trim();if(oe.length>0&&oe===G)return Qa.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),g}}}const C=Mr(o);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`),C.type==="text"?j(C.text||""):j("");const M=g.pendingAssistantParts.get(n),E=M?[...M.parts]:[],F=E.findIndex(G=>G.id===C.id);F!==-1?E[F]=C:E.push(C);const W=new Map(g.pendingAssistantParts);W.set(n,{sessionId:t,parts:E});const K={info:{id:n,sessionID:t,role:m,clientRole:m,providerID:g.lastUsedProvider?.providerID||"",modelID:g.lastUsedProvider?.modelID||"",time:{created:Date.now()},animationSettled:m==="assistant"?!1:void 0,streaming:m==="assistant"?!0:void 0},parts:E},X=[...x,K],z=new Map(g.messages);if(z.set(t,X),m==="assistant"){w.messageStreamStates=so(g.messageStreamStates,n);const G=fs(w.streamingMessageIds??g.streamingMessageIds,t,n);G!==(w.streamingMessageIds??g.streamingMessageIds)&&(w.streamingMessageIds=G,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:z,pendingAssistantParts:W,...w})}else{const C=x[N],M=C.parts.findIndex(K=>K.id===o.id),E=Mr(o,M!==-1?C.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${E.type||"unknown"}`);const F={...C};M!==-1?F.parts=F.parts.map((K,X)=>X===M?E:K):F.parts=[...F.parts,E];const W=[...x];W[N]=F;const L=new Map(g.messages);if(L.set(t,W),F.info.role==="assistant"){w.messageStreamStates=so(g.messageStreamStates,n);const K=fs(w.streamingMessageIds??g.streamingMessageIds,t,n);K!==(w.streamingMessageIds??g.streamingMessageIds)&&(w.streamingMessageIds=K,window.__messageTracker?.(n,"streamingId_set"))}return E.type==="text"?j(E.text||""):j(""),v({messages:L,...w})}}),o?.type==="step-finish"&&m!=="user"&&setTimeout(()=>{s().completeStreamingMessage(t,n)},0)},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){s()._addStreamingPartImmediate(t,n,o,a,i);return}ro.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),no||(no=setTimeout(()=>{const c=[...ro];ro=[],no=null;const d=s();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Ff))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};r(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],u=d.findIndex(k=>k.info.id===n);if(u===-1)return i;const p=d[u];if(!p)return i;const m=Date.now(),f=p.info,h=typeof f?.time?.completed=="number"&&f.time.completed>0;let g=!1;const b={...f};h||(b.time={...f.time??{},completed:m},g=!0),b.status!=="completed"&&(b.status="completed",g=!0),b.streaming&&(b.streaming=!1,g=!0);let x=!1;const w=p.parts.map(k=>{if(!k)return k;if(k.type==="tool"){const y=k.state;if(!y)return k;const A=y.status,D=A==="running"||A==="pending"||A==="started",N=!y.time||typeof y.time?.end!="number";if(D||N){const C={...y};return D&&(C.status="completed"),N&&(C.time={...y.time??{},end:m}),x=!0,{...k,state:C}}return k}if(k.type==="reasoning"){const y=k.time;return!y||typeof y.end!="number"?(x=!0,{...k,time:{...y??{},end:m}}):k}if(k.type==="text"){const y=k.time;return y&&typeof y.end!="number"?(x=!0,{...k,time:{...y,end:m}}):k}return k});if(!g&&!x)return i;window.__messageTracker?.(n,`force_complete:${o}`);const S={...p,info:b,parts:x?w:p.parts},v=[...d];v[u]=S;const j=new Map(i.messages);return j.set(c,v),{messages:j}})},markMessageStreamSettled:t=>{r(n=>{Gl(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 p=d.findIndex(b=>b.info.id===t);if(p===-1)return;const m=d[p];if(m.info?.animationSettled)return;const f={...m,info:{...m.info,animationSettled:!0}},h=[...d];h[p]=f;const g=new Map(n.messages);g.set(u,h),a=g,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),qs([t])},updateMessageInfo:(t,n,o)=>{r(a=>{const i=a.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(i&&!Qr(n,i))return window.__messageTracker?.(n,"ignored_trimmed_update"),a;const d=[...a.messages.get(t)??[]],u=d.findIndex(y=>y.info.id===n),p=a.pendingAssistantParts.get(n),m=(y=[],A=[])=>{if(!A.length)return y;const D=[...y];return A.forEach(N=>{const C=D.findIndex(M=>M.id===N.id);C===-1?D.push(N):D[C]=N}),D},f=y=>{if(!y)return y;const A=y.clientRole??y.role,D=A==="user"?!0:y.userMessageMarker;return{...y,clientRole:A,...D?{userMessageMarker:!0}:{}}};if(u===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:t,messageId:n,messageInfo:o,existingCount:d.length}),d.length>0){const W=d[0]?.info,L=typeof W?.time?.created=="number"?W.time.created:null,K=typeof W?.id=="string"?W.id:null,X=o,z=typeof X?.time?.created=="number"?X.time.created:null,G=typeof X?.id=="string"?X.id:n;let H=!1;if(z!==null&&L!==null&&(H=z<L),!H&&G&&K&&(H=G.localeCompare(K)<0),H)return window.__messageTracker?.(n,"skipped_evicted_message_update"),a}const y=f(o);if(y&&y.role==="user"){const F=p?.parts??[],W={info:{...y,userMessageMarker:!0,clientRole:"user"},parts:F.length>0?[...F]:[]},L=new Map(a.messages),K=[...d,W];K.sort((G,H)=>{const oe=G.info?.time?.created||0,ve=H.info?.time?.created||0;return oe-ve}),L.set(t,K);const X={messages:L},z=ir(X.messageSessionIndex??a.messageSessionIndex,n,t);if(z!==(X.messageSessionIndex??a.messageSessionIndex)&&(X.messageSessionIndex=z),p){const G=new Map(a.pendingAssistantParts);G.delete(n),X.pendingAssistantParts=G}return X}if(!y||y.role!=="assistant")return a;const A=p?.parts??[],D={info:{...y,animationSettled:y?.animationSettled??!1},parts:A.length>0?[...A]:[]},N=new Map(a.messages),C=[...d,D];N.set(t,C);const M={messages:N},E=ir(M.messageSessionIndex??a.messageSessionIndex,n,t);if(E!==(M.messageSessionIndex??a.messageSessionIndex)&&(M.messageSessionIndex=E),p){const F=new Map(a.pendingAssistantParts);F.delete(n),M.pendingAssistantParts=F}return M}const h=d[u],g=h.info;if(g.userMessageMarker===!0||g.clientRole==="user"||g.role==="user"){const y={...h.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:g.providerID||void 0,modelID:g.modelID||void 0},A={...h,info:y},D=new Map(a.messages),N=[...d];return N[u]=A,D.set(t,N),{messages:D}}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 w=p?.parts?m(h.parts,p.parts):h.parts,S={...h,info:x,parts:w},v=new Map(a.messages),j=[...d];j[u]=S,v.set(t,j);const k={messages:v};if(p){const y=new Map(a.pendingAssistantParts);y.delete(n),k.pendingAssistantParts=y}return k})},completeStreamingMessage:(t,n)=>{const o=s();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=fs(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&&r(i),o.pendingAssistantParts.has(n)&&r(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),qs([n]);let c=!1;if(r(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const p=new Map(d.sessionMemoryState),m=Date.now(),f={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:m,streamingCooldownUntil:m+2e3};return p.set(t,f),c=!0,{sessionMemoryState:p}}),c){const d=ar.get(t);d&&(clearTimeout(d),ar.delete(t));const u=setTimeout(()=>{r(p=>{const m=p.sessionMemoryState.get(t);if(!m||m.isStreaming)return p;const f=new Map(p.sessionMemoryState),{streamingCooldownUntil:h,...g}=m;return f.set(t,g),{sessionMemoryState:f}}),ar.delete(t)},2e3);ar.set(t,u)}},syncMessages:(t,n)=>{const o=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,a=o?n.filter(i=>{const c=i?.info?.id;return c?Qr(c,o):!0}):n;r(i=>{const c=new Map(i.messages),d=i.messages.get(t)||[],u=new Map(d.filter(v=>typeof v.info?.id=="string").map(v=>[v.info.id,v])),m=a.map(v=>{const j={...v.info,clientRole:v.info?.clientRole??v.info.role,userMessageMarker:v.info.role==="user"?!0:v.info?.userMessageMarker,animationSettled:v.info.role==="assistant"?v.info?.animationSettled??!0:v.info?.animationSettled},k=(Array.isArray(v.parts)?v.parts:[]).map(D=>{if(D?.type==="text"){const N=D.text??D.content??"";if(to(N))return{...D,synthetic:!0}}return D}),y=typeof j?.id=="string"?j.id:void 0,A=y?u.get(y):void 0;if(A&&A.info.role==="assistant"){const D=Array.isArray(A.parts)?A.parts:[],N=en(D),C=en(k);if(Ja(D)&&N>C){const E=ei(D,k);return{...v,info:j,parts:E}}}return{...v,info:j,parts:k}}),f=new Set(d.map(v=>v.info.id)),h=new Set(m.map(v=>v.info.id)),g=[];f.forEach(v=>{h.has(v)||g.push(v)}),c.set(t,m);const b={messages:c,isSyncing:!0};qs(g);const x=Cr(i.messageStreamStates,g);if(x!==i.messageStreamStates&&(b.messageStreamStates=x),g.length>0){const v=i.streamingMessageIds.get(t);v&&g.includes(v)&&(b.streamingMessageIds=fs(b.streamingMessageIds??i.streamingMessageIds,t,null))}if(g.length>0){const v=tn(b.messageSessionIndex??i.messageSessionIndex,g);v!==(b.messageSessionIndex??i.messageSessionIndex)&&(b.messageSessionIndex=v)}if(g.length>0){const v=new Map(i.pendingAssistantParts);let j=!1;g.forEach(k=>{v.delete(k)&&(j=!0)}),j&&(b.pendingAssistantParts=v)}const w=b.messageSessionIndex??i.messageSessionIndex;let S=w;return m.forEach(v=>{const j=v?.info?.id;typeof j=="string"&&j.length>0&&(S=ir(S,j,t))}),S!==w&&(b.messageSessionIndex=S),b}),setTimeout(()=>{r({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{r(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=n+Pf;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&r(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)=>{r(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}})},trimToViewportWindow:(t,n=Ot.VIEWPORT_MESSAGES,o)=>{const a=s(),i=a.messages.get(t);if(!i||i.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const p=Math.min(i.length,u+n);p===i.length&&p-u<n&&(u=Math.max(0,p-n));const m=i.slice(u,p),f=i.slice(0,u),h=new Set(m.map(b=>b.info.id)),g=i.filter(b=>!h.has(b.info.id)).map(b=>b.info.id);r(b=>{const x=new Map(b.messages);x.set(t,m);const w=new Map(b.sessionMemoryState),S={...c,viewportAnchor:d-u,trimmedHeadMaxId:_f(f,c.trimmedHeadMaxId)};w.set(t,S);const v={messages:x,sessionMemoryState:w};qs(g);const j=Cr(b.messageStreamStates,g);if(j!==b.messageStreamStates&&(v.messageStreamStates=j),g.length>0){const A=b.streamingMessageIds.get(t);A&&g.includes(A)&&(v.streamingMessageIds=fs(v.streamingMessageIds??b.streamingMessageIds,t,null))}if(g.length>0){const A=tn(v.messageSessionIndex??b.messageSessionIndex,g);A!==(v.messageSessionIndex??b.messageSessionIndex)&&(v.messageSessionIndex=A)}const k=v.messageSessionIndex??b.messageSessionIndex;let y=k;return m.forEach(A=>{const D=A?.info?.id;typeof D=="string"&&D.length>0&&(y=ir(y,D,t))}),y!==k&&(v.messageSessionIndex=y),v})},evictLeastRecentlyUsed:t=>{const n=s();if(n.messages.size<=Ot.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const p=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,p])});const i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=i[0][0];r(d=>{const p=(d.messages.get(c)||[]).map(j=>j.info.id),m=new Map(d.messages),f=new Map(d.sessionMemoryState);m.delete(c),f.delete(c);const h={messages:m,sessionMemoryState:f},g=new Map(d.pendingAssistantParts);let b=!1;g.forEach((j,k)=>{j.sessionId===c&&(g.delete(k),b=!0)}),b&&(h.pendingAssistantParts=g);const x=new Map(d.sessionCompactionUntil);x.delete(c)&&(h.sessionCompactionUntil=x),qs(p);const w=Cr(d.messageStreamStates,p);w!==d.messageStreamStates&&(h.messageStreamStates=w);const S=tn(h.messageSessionIndex??d.messageSessionIndex,p);S!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=S);const v=fs(d.streamingMessageIds,c,null);if(v!==d.streamingMessageIds&&(h.streamingMessageIds=v),d.abortControllers.has(c)){const j=new Map(d.abortControllers);j.delete(c),h.abortControllers=j}return h})},loadMoreMessages:async(t,n="up")=>{const o=s(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const c=await oo(t,()=>Ce.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=c.findIndex(p=>p.info.id===d.info.id);if(u>0){const p=Math.min(Ot.VIEWPORT_MESSAGES,u),m=c.slice(u-p,u);r(f=>{const h=[...m,...a],g=new Map(f.messages);g.set(t,h);const b=new Map(f.sessionMemoryState);return b.set(t,{...i,viewportAnchor:i.viewportAnchor+m.length,hasMoreAbove:u-p>0,totalAvailableMessages:c.length}),{messages:g,sessionMemoryState:b}})}else u===0&&r(p=>{const m=new Map(p.sessionMemoryState);return m.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:m}})}},getLastMessageModel:t=>{const{messages:n}=s(),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:bs(()=>ts()),partialize:r=>({lastUsedProvider:r.lastUsedProvider,sessionMemoryState:Array.from(r.sessionMemoryState.entries()).map(([s,t])=>[s,{viewportAnchor:t.viewportAnchor,isStreaming:t.isStreaming,lastAccessedAt:t.lastAccessedAt,backgroundMessageCount:t.backgroundMessageCount,totalAvailableMessages:t.totalAvailableMessages,hasMoreAbove:t.hasMoreAbove,trimmedHeadMaxId:t.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(r.sessionAbortFlags.entries()).map(([s,t])=>[s,{timestamp:t.timestamp,acknowledged:t.acknowledged}])}),merge:(r,s)=>{if(!r)return s;let t=s.sessionMemoryState;Array.isArray(r.sessionMemoryState)&&(t=new Map(r.sessionMemoryState.map(o=>o)));let n=s.sessionAbortFlags;return Array.isArray(r.sessionAbortFlags)&&(n=new Map(r.sessionAbortFlags)),{...s,lastUsedProvider:r.lastUsedProvider??s.lastUsedProvider,sessionMemoryState:t,sessionAbortFlags:n}}}),{name:"message-store"})),$f=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),zf=r=>r?$f.has(r.toLowerCase()):!1,Hf=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Wf=r=>{if(r)try{const s=Hf();if(s?.getState)return s.getState().agents?.find?.(n=>n.name===r)}catch{}},wn=r=>{const s=Wf(r);if(!s)return"ask";const t=s.permission?.edit;return t==="allow"||t==="ask"||t==="deny"||t==="full"?t:(s.tools?s.tools.edit!==!1:!0)?"ask":"deny"},si=r=>{if(!r||typeof r!="object")return 0;const s=r.input??0,t=r.output??0,n=r.reasoning??0,o=r.cache&&typeof r.cache=="object"?r.cache.read??0:0,a=r.cache&&typeof r.cache=="object"?r.cache.write??0:0;return s+t+n+o+a},ao=r=>{const s=r.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return si(s);const t=r.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:si(t.tokens)},io=(r,s,t)=>{const n=Number.isFinite(s)?Math.max(s,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),c=Math.min(i,n),d=n>0?Math.max(n-c,1):0,u=d>0?r/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},Ar=["ask","allow","full"],bt=$t()(Wt(ys((r,s)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{r(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=s();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{r(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=s();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{r(i=>{const c=new Map(i.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=s(),a=o.get(t);return a&&a.get(n)||null},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a}=s(),i=new Map,c=(m,f)=>{if("mode"in m&&m.mode&&typeof m.mode=="string"&&n.find(x=>x.name===m.mode))return m.mode;if(m.providerID&&m.modelID){const b=n.find(x=>x.model?.providerID===m.providerID&&x.model?.modelID===m.modelID);if(b)return b.name}const{currentAgentContext:h}=s(),g=h.get(t);if(g&&n.find(b=>b.name===g))return g;if(f>0&&m.providerID&&m.modelID){const x=(o.get(t)||[]).filter(w=>w.info.role==="assistant").sort((w,S)=>w.info.time.created-S.info.time.created);for(let w=f-1;w>=0;w--){const v=x[w].info;if(v.providerID===m.providerID&&v.modelID===m.modelID){if(v.mode&&typeof v.mode=="string"&&n.find(y=>y.name===v.mode))return v.mode;const j=n.find(k=>k.model?.providerID===v.providerID&&k.model?.modelID===v.modelID);if(j)return j.name}}}return m.providerID&&m.modelID&&n.find(x=>x.name==="build")?"build":null},d=o.get(t)||[],u=d.filter(m=>m.info.role==="assistant"||m.info.role==="user").sort((m,f)=>m.info.time.created-f.info.time.created),p=d.filter(m=>m.info.role==="assistant").sort((m,f)=>m.info.time.created-f.info.time.created);for(let m=0;m<u.length;m++){const f=u[m],{info:h}=f,g=h;if(g.providerID&&g.modelID){const b=c(g,p.indexOf(f));if(b&&n.find(x=>x.name===b)){const x={providerId:g.providerID,modelId:g.modelID,timestamp:h.time.created},w=i.get(b);(!w||x.timestamp>w.timestamp)&&i.set(b,x)}}}for(const[m,f]of i)a(t,m,f.providerId,f.modelId);return i},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=io(0,n,o),c=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(c===0||u===0)return null;const m=(a.get(t)||[]).filter(v=>v.info.role==="assistant");if(m.length===0)return null;const f=m[m.length-1],h=f.info.id,g=v=>{const j=()=>{r(k=>{const y=k.sessionContextUsage.get(t);if(y&&y.totalTokens===v.totalTokens&&y.percentage===v.percentage&&y.contextLimit===v.contextLimit&&(y.outputLimit??0)===(v.outputLimit??0)&&(y.normalizedOutput??0)===(v.normalizedOutput??0)&&y.thresholdLimit===v.thresholdLimit&&y.lastMessageId===v.lastMessageId)return k;const A=new Map(k.sessionContextUsage);return A.set(t,v),{sessionContextUsage:A}})};typeof queueMicrotask=="function"?queueMicrotask(j):typeof window<"u"?window.setTimeout(j,0):setTimeout(j,0)},b=s().sessionContextUsage.get(t);if(b&&b.lastMessageId===h){const v=b.normalizedOutput??b.outputLimit??0,j=b.contextLimit!==c||v!==d||b.thresholdLimit!==u;if(j&&b.totalTokens>0){const k=b.totalTokens/u*100,y={totalTokens:b.totalTokens,percentage:Math.min(k,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(y),y}if(!j&&b.totalTokens>0)return b}const x=ao(f);if(x===0)return b||null;const w=io(x,n,o),S={totalTokens:x,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.outputLimit,normalizedOutput:w.normalizedOutput,thresholdLimit:w.thresholdLimit,lastMessageId:h};return g(S),S},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(m=>m.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=ao(d);if(u===0)return;const p=io(u,n,o);r(m=>{const f=new Map(m.sessionContextUsage);return f.set(t,{totalTokens:u,percentage:p.percentage,contextLimit:p.contextLimit,outputLimit:p.outputLimit,normalizedOutput:p.normalizedOutput,thresholdLimit:p.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:f}})},initializeSessionContextUsage:(t,n,o,a)=>{const c=s().sessionContextUsage.get(t);(!c||c.totalTokens===0)&&s().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const c=()=>{i++;const u=(o.get(t)||[]).find(p=>p.info.id===n);if(u&&u.info.role==="assistant"&&ao(u)>0){s().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=s();return n.get(t)},getSessionAgentEditMode:(t,n,o=wn(n))=>!t||!n?o:s().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=wn(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||Ar.includes(o)&&r(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=wn(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=s().getSessionAgentEditMode(t,n,a),c=Ar.indexOf(i),d=Ar.indexOf(a),p=((c>=0?c:d>=0?d:0)+1)%Ar.length,m=Ar[p];s().setSessionAgentEditMode(t,n,m,a)}}),{name:"context-store",storage:bs(()=>ts()),partialize:r=>({sessionModelSelections:Array.from(r.sessionModelSelections.entries()),sessionAgentSelections:Array.from(r.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(r.sessionAgentModelSelections.entries()).map(([s,t])=>[s,Array.from(t.entries())]),currentAgentContext:Array.from(r.currentAgentContext.entries()),sessionContextUsage:Array.from(r.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(r.sessionAgentEditModes.entries()).map(([s,t])=>[s,Array.from(t.entries())])}),merge:(r,s)=>{const t=new Map;r?.sessionAgentModelSelections&&r.sessionAgentModelSelections.forEach(([o,a])=>{t.set(o,new Map(a))});const n=new Map;return r?.sessionAgentEditModes&&r.sessionAgentEditModes.forEach(([o,a])=>{n.set(o,new Map(a))}),{...s,...r,sessionModelSelections:new Map(r?.sessionModelSelections||[]),sessionAgentSelections:new Map(r?.sessionAgentSelections||[]),sessionAgentModelSelections:t,currentAgentContext:new Map(r?.currentAgentContext||[]),sessionContextUsage:new Map(r?.sessionContextUsage||[]),sessionAgentEditModes:n,hasHydrated:!0}}}),{name:"context-store"})),Uf=r=>typeof r=="object"&&r!==null,Vf=r=>{if(!Array.isArray(r))return[];const s=[];return r.forEach(t=>{if(!Array.isArray(t)||t.length!==2)return;const[n,o]=t;typeof n!="string"||!Array.isArray(o)||s.push([n,o])}),s},Gf=async(r,s)=>{try{const t=st.getState(),n=t.getWorktreeMetadata(r);if(n?.path)return Ce.withDirectory(n.path,s);const o=t.sessions.find(i=>i.id===r),a=typeof o?.directory=="string"&&o.directory.length>0?o.directory:void 0;if(a)return Ce.withDirectory(a,s)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return s()},Rn=$t()(Wt(ys((r,s)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o)return;const a=t.type?.toLowerCase?.()??null;let i=n?.currentAgentContext?.get(o);if(i||(i=n?.sessionAgentSelections?.get(o)??void 0),!i&&typeof window<"u"){const p=window.__zustand_config_store__;p?.getState&&(i=p.getState().currentAgentName??void 0)}const c=wn(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&zf(a)){s().respondToPermission(o,t.id,"once").catch(()=>{});return}r(p=>{const m=p.permissions.get(o)||[],f=new Map(p.permissions);return f.set(o,[...m,t]),{permissions:f}})},respondToPermission:async(t,n,o)=>{await Gf(t,()=>Ce.respondToPermission(t,n,o)),o==="reject"&&await lt.getState().abortCurrentOperation(t),r(a=>{const c=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:bs(()=>ts()),partialize:r=>({permissions:Array.from(r.permissions.entries())}),merge:(r,s)=>{if(!Uf(r))return s;const t=Vf(r.permissions);return{...s,permissions:new Map(t)}}}),{name:"permission-store"})),ql=r=>r.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
4
- `).replace(/\n\s*\n+/g,`
5
- `),ri=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},ni=(r,s,t)=>{if(!s)return null;const n=t(s)?.path;if(typeof n=="string"&&n.trim().length>0)return ri(n);const o=r.find(a=>a.id===s);return o?ri(o.directory??null):null},me=$t()(Wt((r,s)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,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:()=>st.getState().loadSessions(),createSession:async(t,n,o)=>{const a=await st.getState().createSession(t,n,o);return a?.id&&await s().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=lt.getState(),{messages:o,lastUsedProvider:a}=n;let i,c;if(o.forEach((w,S)=>{const v=w.find(j=>j.info?.id===t);v&&!i&&(i=v,c=S)}),!i||i.info.role!=="assistant")return;const d=ql(i.parts);if(!d.trim())return;const u=st.getState(),p=ni(u.sessions,c??null,u.getWorktreeMetadata),m=await s().createSession(void 0,p??null,null);if(!m)return;const{currentProviderId:f,currentModelId:h,currentAgentName:g}=kt.getState(),b=f||a?.providerID,x=h||a?.modelID;!b||!x||await Ce.sendMessage({id:m.id,providerID:b,modelID:x,text:d,prefaceText:Vl,agent:g??void 0})},deleteSession:(t,n)=>st.getState().deleteSession(t,n),deleteSessions:(t,n)=>st.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>st.getState().updateSessionTitle(t,n),shareSession:t=>st.getState().shareSession(t),unshareSession:t=>st.getState().unshareSession(t),setCurrentSession:async t=>{const n=s().currentSessionId,o=ni(st.getState().sessions,t,st.getState().getWorktreeMetadata),a=Ce.getDirectory()??St.getState().currentDirectory??null,i=o??a;try{Ce.setDirectory(i??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}if(n&&n!==t&&!s().sessionMemoryState.get(n)?.isStreaming){const d=s().messages.get(n)||[];d.length>0&&s().updateViewportAnchor(n,d.length-1),s().trimToViewportWindow(n,Ot.VIEWPORT_MESSAGES)}st.getState().setCurrentSession(t),t&&(s().messages.get(t)||await s().loadMessages(t),s().trimToViewportWindow(t,Wm)),s().evictLeastRecentlyUsed()},loadMessages:t=>lt.getState().loadMessages(t),sendMessage:(t,n,o,a,i,c)=>{const d=st.getState().currentSessionId;return lt.getState().sendMessage(t,n,o,a,d||void 0,i,c)},abortCurrentOperation:()=>{const t=st.getState().currentSessionId;return lt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=st.getState().currentSessionId;if(!n)return null;const o=Date.now()+t;return r({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{r({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&&lt.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=st.getState().currentSessionId||t;return lt.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>lt.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>lt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>lt.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>lt.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:bt.getState().currentAgentContext,sessionAgentSelections:bt.getState().sessionAgentSelections,getSessionAgentEditMode:bt.getState().getSessionAgentEditMode};return Rn.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>Rn.getState().respondToPermission(t,n,o),clearError:()=>st.getState().clearError(),getSessionsByDirectory:t=>st.getState().getSessionsByDirectory(t),getLastMessageModel:t=>lt.getState().getLastMessageModel(t),getCurrentAgent:t=>bt.getState().getCurrentAgent(t),syncMessages:(t,n)=>lt.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>st.getState().applySessionMetadata(t,n),addAttachedFile:t=>Os.getState().addAttachedFile(t),addServerFile:(t,n,o)=>Os.getState().addServerFile(t,n,o),removeAttachedFile:t=>Os.getState().removeAttachedFile(t),clearAttachedFiles:()=>Os.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>lt.getState().updateViewportAnchor(t,n),trimToViewportWindow:(t,n)=>{const o=st.getState().currentSessionId;return lt.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=st.getState().currentSessionId;return lt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>lt.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),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=lt.getState().messages;return bt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>st.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>st.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>st.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>st.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>st.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>st.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{const o=st.getState().currentSessionId;if(!o)return null;const a=lt.getState().messages;return bt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=lt.getState().messages;return bt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=lt.getState().messages;return bt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=lt.getState().messages.get(t)||[],o=st.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=lt.getState().messages;return bt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>st.getState().updateSession(t)}),{name:"composed-session-store"}));st.subscribe((r,s)=>{r.sessions===s.sessions&&r.currentSessionId===s.currentSessionId&&r.lastLoadedDirectory===s.lastLoadedDirectory&&r.isLoading===s.isLoading&&r.error===s.error&&r.webUICreatedSessions===s.webUICreatedSessions&&r.worktreeMetadata===s.worktreeMetadata&&r.availableWorktrees===s.availableWorktrees||me.setState({sessions:r.sessions,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,isLoading:r.isLoading,error:r.error,webUICreatedSessions:r.webUICreatedSessions,worktreeMetadata:r.worktreeMetadata,availableWorktrees:r.availableWorktrees})});lt.subscribe((r,s)=>{if(r.messages===s.messages&&r.sessionMemoryState===s.sessionMemoryState&&r.messageStreamStates===s.messageStreamStates&&r.sessionCompactionUntil===s.sessionCompactionUntil&&r.sessionAbortFlags===s.sessionAbortFlags&&r.streamingMessageIds===s.streamingMessageIds&&r.abortControllers===s.abortControllers&&r.lastUsedProvider===s.lastUsedProvider&&r.isSyncing===s.isSyncing)return;const t=new Map;r.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const c=i.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const p=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:u,createdAt:p});break}}}}}),me.setState({messages:r.messages,sessionMemoryState:r.sessionMemoryState,messageStreamStates:r.messageStreamStates,sessionCompactionUntil:r.sessionCompactionUntil,sessionAbortFlags:r.sessionAbortFlags,streamingMessageIds:r.streamingMessageIds,abortControllers:r.abortControllers,lastUsedProvider:r.lastUsedProvider,isSyncing:r.isSyncing,userSummaryTitles:t})});Os.subscribe((r,s)=>{r.attachedFiles!==s.attachedFiles&&me.setState({attachedFiles:r.attachedFiles})});bt.subscribe((r,s)=>{r.sessionModelSelections===s.sessionModelSelections&&r.sessionAgentSelections===s.sessionAgentSelections&&r.sessionAgentModelSelections===s.sessionAgentModelSelections&&r.currentAgentContext===s.currentAgentContext&&r.sessionContextUsage===s.sessionContextUsage&&r.sessionAgentEditModes===s.sessionAgentEditModes||me.setState({sessionModelSelections:r.sessionModelSelections,sessionAgentSelections:r.sessionAgentSelections,sessionAgentModelSelections:r.sessionAgentModelSelections,currentAgentContext:r.currentAgentContext,sessionContextUsage:r.sessionContextUsage,sessionAgentEditModes:r.sessionAgentEditModes})});Rn.subscribe((r,s)=>{r.permissions!==s.permissions&&me.setState({permissions:r.permissions})});me.setState({sessions:st.getState().sessions,currentSessionId:st.getState().currentSessionId,lastLoadedDirectory:st.getState().lastLoadedDirectory,isLoading:st.getState().isLoading,error:st.getState().error,webUICreatedSessions:st.getState().webUICreatedSessions,worktreeMetadata:st.getState().worktreeMetadata,availableWorktrees:st.getState().availableWorktrees,messages:lt.getState().messages,sessionMemoryState:lt.getState().sessionMemoryState,messageStreamStates:lt.getState().messageStreamStates,sessionCompactionUntil:lt.getState().sessionCompactionUntil,sessionAbortFlags:lt.getState().sessionAbortFlags,streamingMessageIds:lt.getState().streamingMessageIds,abortControllers:lt.getState().abortControllers,lastUsedProvider:lt.getState().lastUsedProvider,isSyncing:lt.getState().isSyncing,permissions:Rn.getState().permissions,attachedFiles:Os.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__=me);const ca=({containerRef:r,minThumbSize:s=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=l.useState(!1),[c,d]=l.useState({length:0,offset:0}),[u,p]=l.useState({length:0,offset:0}),m=l.useRef(null),f=l.useRef(null),h=l.useRef(!1),g=l.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),b=l.useRef(null),x=l.useCallback(()=>{const N=r.current;if(!N)return;const{scrollHeight:C,clientHeight:M,scrollTop:E,scrollWidth:F,clientWidth:W,scrollLeft:L}=N,K=8;if(C>M){const X=Math.max(M-K*2,0),z=M/C*X,G=Math.max(s,Math.min(X,z)),H=Math.max(X-G,0),oe=Math.max(C-M,1),ve=E/oe*H;d({length:G,offset:ve})}else d({length:0,offset:0});if(!o&&F>W){const X=Math.max(W-K*2,0),z=W/F*X,G=Math.max(s,Math.min(X,z)),H=Math.max(X-G,0),oe=Math.max(F-W,1),ve=L/oe*H;p({length:G,offset:ve})}else p({length:0,offset:0})},[r,s,o]),w=l.useCallback(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(()=>i(!1),t)},[t]),S=l.useCallback(()=>{f.current&&cancelAnimationFrame(f.current),f.current=requestAnimationFrame(()=>{x(),i(!0),w()})},[w,x]);l.useEffect(()=>{const N=r.current;if(!N)return;x(),i(!0),w(),N.addEventListener("scroll",S,{passive:!0});const C=typeof ResizeObserver<"u"?new ResizeObserver(()=>x()):null;C?.observe(N);const M=typeof MutationObserver<"u"?new MutationObserver(()=>x()):null;return M?.observe(N,{childList:!0,subtree:!0,characterData:!0}),()=>{N.removeEventListener("scroll",S),C?.disconnect(),M?.disconnect(),m.current&&clearTimeout(m.current),f.current&&cancelAnimationFrame(f.current)}},[r,S,w,x]);const v=(N,C)=>{const M=r.current;M&&(h.current=!0,g.current={pointerX:N.clientX,pointerY:N.clientY,scrollTop:M.scrollTop,scrollLeft:M.scrollLeft},b.current=C,i(!0),m.current&&clearTimeout(m.current),N.currentTarget.setPointerCapture(N.pointerId))},j=N=>{if(!h.current)return;const C=r.current;if(!C)return;const M=b.current;if(M==="vertical"){const{pointerY:E,scrollTop:F}=g.current,W=N.clientY-E,L=C.clientHeight,K=Math.max(L-c.length,1),X=Math.max(C.scrollHeight-C.clientHeight,1),z=W/K*X;C.scrollTop=F+z}else if(M==="horizontal"){const{pointerX:E,scrollLeft:F}=g.current,W=N.clientX-E,L=C.clientWidth,K=Math.max(L-u.length,1),X=Math.max(C.scrollWidth-C.clientWidth,1),z=W/K*X;C.scrollLeft=F+z}},k=N=>{h.current&&(h.current=!1,N.currentTarget.releasePointerCapture(N.pointerId),w())},y=c.length>0,A=u.length>0;if(!y&&!A)return null;const D=8;return e.jsxs("div",{className:T("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[y&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${D+c.offset}px`,right:`${D/2}px`},onPointerDown:N=>v(N,"vertical"),onPointerMove:j,onPointerUp:k,onPointerCancel:k}),A&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${D+u.offset}px`,bottom:`${D/2}px`},onPointerDown:N=>v(N,"horizontal"),onPointerMove:j,onPointerUp:k,onPointerCancel:k})]})},Xe=l.forwardRef(({className:r,outerClassName:s,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,...p},m)=>{const f=l.useRef(null);return l.useImperativeHandle(m,()=>f.current,[]),e.jsxs("div",{className:T("relative flex flex-col min-h-0 w-full overflow-hidden",s),children:[e.jsx(i,{ref:f,className:T("overlay-scrollbar-target overlay-scrollbar-container",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",r),style:n,...p,children:t}),e.jsx(ca,{containerRef:f,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});Xe.displayName="ScrollableOverlay";const oi="mobile-overlay-root",qf=()=>{if(typeof document>"u")return null;let r=document.getElementById(oi);return r||(r=document.createElement("div"),r.id=oi,document.body.appendChild(r)),r},Kt=({open:r,title:s,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:c})=>{const d=l.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=qf()),l.useEffect(()=>{if(!r)return;const m=document.body.style.overflow;document.body.style.overflow="hidden";const f=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",f),()=>{document.body.style.overflow=m,document.removeEventListener("keydown",f)}},[r,t]),!r||!d.current)return null;const u=i??"max-h-[min(70vh,520px)]",p=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),onClick:m=>m.stopPropagation(),children:[(()=>{const m=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(ds,{className:"h-4 w-4"})});return c?c(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:s}),m]})})(),e.jsx(Xe,{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 pd.createPortal(p,d.current)},Io=({totalTokens:r,percentage:s,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,c]=l.useState(!1),d=l.useRef(void 0),u=x=>x>=1e6?`${(x/1e6).toFixed(1)}M`:x>=1e3?`${(x/1e3).toFixed(1)}K`:x.toFixed(1).replace(/\.0$/,""),p=x=>x>=90?"text-status-error":x>=75?"text-status-warning":"text-status-success",m=typeof n=="number"?Math.max(n,0):0,f=[`Used tokens: ${u(r)}`,`Context limit: ${u(t)}`,`Output limit: ${u(m)}`],h=l.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c(!0)},500)},[]),g=l.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);l.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const b=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?h:void 0,onTouchEnd:a?g:void 0,children:[e.jsx(hd,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:T(p(s),"font-medium"),children:[Math.min(s,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[b,e.jsx(Kt,{open:i,onClose:()=>c(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(r)})]}),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(m)})]}),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",p(s)),children:[Math.min(s,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:b}),e.jsx(ut,{children:e.jsx("div",{className:"space-y-0.5",children:f.map(x=>e.jsx("p",{className:"typography-micro leading-tight",children:x},x))})})]})},Dr={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Kl=(r,s,t)=>{if(typeof window>"u")return;const n=document.documentElement,o=s==="mobile",a=s==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(s==="mobile"?"device-mobile":s==="tablet"?"device-tablet":"device-desktop"),r?(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",s),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 lo(){const r=window.innerWidth,s=typeof window.matchMedia=="function",t=s?window.matchMedia("(pointer: coarse)"):null,n=s?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=r>Dr.md&&r<=Dr.lg,p=r<=Dr.md;let m=d&&p,f=d&&!m&&u,h=!d||r>Dr.lg,g="desktop";c?(m=!1,f=!1,h=!0,g="desktop"):m?g="mobile":f?g="tablet":(h=!0,g="desktop"),Kl(c,g,d);let b="xs";for(const[x,w]of Object.entries(Dr))r>=w&&(b=x);return{isMobile:m,isTablet:f,isDesktop:h,deviceType:g,screenWidth:r,breakpoint:b,hasTouchInput:d}}function Dt(){const[r,s]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:lo());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{s(lo())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{s(lo())},a=[],i=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return i(t),i(n),()=>{a.forEach(c=>c())}},[]),l.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||c||d>0;Kl(t,r.deviceType,u)},[r.deviceType,r.hasTouchInput]),r}const sn=5e3,Kf=1e4,Yf=5e3,Xf=1e4,ps=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Jf=(r,s)=>{if(!r&&!s)return!1;if(!r||!s)return!0;const t=new Set([...Object.keys(r),...Object.keys(s)]);for(const n of t){const o=r[n],a=s[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},Zf=(r,s)=>{if(!r&&!s)return!1;if(!r||!s)return!0;const t=r.files??[],n=s.files??[];if(t.length!==n.length||r.ahead!==s.ahead||r.behind!==s.behind||r.current!==s.current||r.tracking!==s.tracking||r.isClean!==s.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!!Jf(r.diffStats,s.diffStats)},Qf=(r,s)=>{const t=new Set;if(!s)return t;const n=r?.files??[],o=s.files??[],a=new Map(n.map(m=>[m.path,m])),i=new Map(o.map(m=>[m.path,m])),c=new Set([...a.keys(),...i.keys()]);for(const m of c){const f=a.get(m),h=i.get(m);if(!f||!h){t.add(m);continue}if(f.index!==h.index||f.working_dir!==h.working_dir){t.add(m);continue}}const d=r?.diffStats??{},u=s.diffStats??{},p=new Set([...Object.keys(d),...Object.keys(u)]);for(const m of p){const f=d[m],h=u[m];if(!f||!h){t.add(m);continue}(f.insertions!==h.insertions||f.deletions!==h.deletions)&&t.add(m)}return t},Mt=$t()(Wt((r,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:sn,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=s();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,ps()),r({activeDirectory:t,directories:a})}else r({activeDirectory:t})},getDirectoryState:t=>s().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:i}=s();let c=i.get(t);c||(c=ps()),a||r({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const m=new Map(i);return m.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),r({directories:m,isLoadingStatus:!1}),!1}const p=await n.getGitStatus(t);if(Zf(c.status,p)){d=!0;const m=new Map(s().directories),f=m.get(t)??ps(),h=Qf(f.status,p),g=new Set((f.status?.files??[]).map(S=>S.path)),b=new Set((p.files??[]).map(S=>S.path)),x=new Map(f.diffCache);for(const S of g)b.has(S)||x.delete(S);for(const S of h)x.delete(S);const w=h.size>0;m.set(t,{...f,isGitRepo:!0,status:p,diffCache:x,lastStatusFetch:Date.now(),lastStatusChange:w?Date.now():f.lastStatusChange}),r({directories:m})}else{const m=new Map(s().directories),f=m.get(t)??ps();m.set(t,{...f,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:f.lastStatusChange}),r({directories:m})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||r({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{r({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(s().directories),i=a.get(t)??ps();a.set(t,{...i,branches:o}),r({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{r({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=s(),i=a.get(t),c=o??i?.logMaxCount??25;r({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),u=new Map(s().directories),p=u.get(t)??ps();u.set(t,{...p,log:d,lastLogFetch:Date.now(),logMaxCount:c}),r({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{r({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{r({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(s().directories),i=a.get(t)??ps();a.set(t,{...i,identity:o}),r({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{r({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=s();let i=a.get(t);if(!i){i=ps();const m=new Map(a);m.set(t,i),r({directories:m})}const{force:c=!1}=o,d=Date.now();await s().fetchStatus(t,n);const u=s().directories.get(t);if(!u?.isGitRepo)return;await s().fetchBranches(t,n);const p=d-(u.lastLogFetch||0);(c||p>Xf||!u.log)&&await s().fetchLog(t,n),await s().fetchIdentity(t,n),await s().fetchAllDiffs(t,n)},getDiff:(t,n)=>s().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(s().directories),i=a.get(t)??ps(),c=new Map(i.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:c}),r({directories:a})},clearDiffCache:t=>{const n=new Map(s().directories),o=n.get(t);o&&(n.set(t,{...o,diffCache:new Map}),r({directories:n}))},fetchAllDiffs:async(t,n)=>{const o=s().directories.get(t);if(!o?.status?.files||o.status.files.length===0)return;const i=o.status.files.filter(f=>!o.diffCache.has(f.path));if(i.length===0)return;const c=await Promise.allSettled(i.map(async f=>{const h=await n.getGitFileDiff(t,{path:f.path});return{path:f.path,diff:{original:h.original??"",modified:h.modified??""}}})),d=new Map(s().directories),u=d.get(t);if(!u)return;const p=new Map(u.diffCache),m=Date.now();c.forEach(f=>{f.status==="fulfilled"&&p.set(f.value.path,{...f.value.diff,fetchedAt:m})}),d.set(t,{...u,diffCache:p}),r({directories:d})},setLogMaxCount:(t,n)=>{const o=new Map(s().directories),a=o.get(t)??ps();o.set(t,{...a,logMaxCount:n}),r({directories:o})},startPolling:t=>{const{pollIntervalId:n}=s();if(n)return;const o=()=>{const{currentPollInterval:a}=s();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){r({pollIntervalId:o()});return}const{activeDirectory:c}=s();if(!c){r({pollIntervalId:o()});return}if(await s().fetchStatus(c,t,{silent:!0}))await s().fetchLog(c,t),await s().fetchAllDiffs(c,t),r({currentPollInterval:sn});else{const p=Math.min(a+Yf,Kf);r({currentPollInterval:p})}const{pollIntervalId:u}=s();u!==null&&r({pollIntervalId:o()})},a)};r({pollIntervalId:o(),currentPollInterval:sn})},stopPolling:()=>{const{pollIntervalId:t}=s();t&&(clearTimeout(t),r({pollIntervalId:null,currentPollInterval:sn}))},refresh:async(t,n={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,t,n)}}),{name:"git-store"})),Yl=r=>Mt(s=>r?s.directories.get(r)?.status??null:null),ep=r=>Mt(s=>r?s.directories.get(r)?.branches??null:null),tp=r=>Mt(s=>r?s.directories.get(r)?.log??null:null),sp=r=>Mt(s=>r?s.directories.get(r)?.identity??null:null),Xl=r=>Mt(s=>r?s.directories.get(r)?.isGitRepo??null:null),rp=r=>Mt(s=>r?s.directories.get(r)?.status?.files?.length??0:0);function Xt({...r}){return e.jsx(gd,{"data-slot":"dropdown-menu",...r})}function Jt({...r}){return e.jsx(xd,{"data-slot":"dropdown-menu-trigger",...r})}function Zt({className:r,sideOffset:s=4,...t}){return e.jsx(yd,{children:e.jsx(bd,{"data-slot":"dropdown-menu-content",sideOffset:s,className:T("bg-popover text-popover-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",r),...t})})}function gt({className:r,inset:s,variant:t="default",...n}){return e.jsx(Sd,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":t,className:T("hover:bg-accent hover:text-accent-foreground 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",r),...n})}function np({...r}){return e.jsx(wd,{"data-slot":"dropdown-menu-radio-group",...r})}function op({className:r,children:s,...t}){return e.jsxs(vd,{"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-accent hover:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),...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(jd,{children:e.jsx(Tt,{className:"size-3"})})}),s]})}function zr({className:r,...s}){return e.jsx(kd,{"data-slot":"dropdown-menu-separator",className:T("bg-border -mx-1 my-0.5 h-px",r),...s})}function ur({...r}){return e.jsx(Nd,{"data-slot":"dropdown-menu-sub",...r})}function mr({className:r,inset:s,children:t,...n}){return e.jsxs(Cd,{"data-slot":"dropdown-menu-sub-trigger","data-inset":s,className:T("hover:bg-accent hover:text-accent-foreground flex cursor-default items-center rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8",r),...n,children:[t,e.jsx(us,{className:"ml-auto size-3.5"})]})}function fr({className:r,...s}){return e.jsx(Md,{"data-slot":"dropdown-menu-sub-content",className:T("bg-popover text-popover-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 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...s})}const ap={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:[]}};function da(r){return ap[r]||{displayName:r.charAt(0).toUpperCase()+r.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function ip(r,s,t){const n=da(r);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=qr(o);if(a)return a}if(r==="webfetch"){if(s.trim().startsWith("{")||s.trim().startsWith("["))try{return JSON.parse(s),"json"}catch{}if(s.trim().startsWith("<"))return"html";if(s.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function qr(r){const s=r.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",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"}[s||""]||null}const lp=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Jl(r){const s=r.split(".").pop()?.toLowerCase();return lp.includes(s||"")}function cp(r){const s=r.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"}[s||""]||"image/png"}function dp(r,s){if(!r)return"";const t=n=>{const o=r[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(s==="bash"){const n=t("command");if(n)return n}if(s==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((s==="edit"||s==="multiedit")&&typeof r=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(s==="write"&&typeof r=="object"){const n=t("content");if(n)return n}return typeof r=="object"?Object.entries(r).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${i}: ${c}`}).join(`
6
- `):String(r)}const ua=l.createContext(null),rr=()=>{const r=l.useContext(ua);if(!r)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return r},Zl=r=>{const s=rr();return r(s)},up=()=>Zl(r=>r.runtime.isDesktop),ma=()=>Zl(r=>r.runtime.isVSCode),mp=hl("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 Ae({className:r,variant:s,size:t,asChild:n=!1,...o}){const a=n?pl:"button";return e.jsx(a,{"data-slot":"button",className:T(mp({variant:s,size:t,className:r})),...o})}const fp=({mode:r,onModeChange:s,className:t})=>{const n=l.useCallback(o=>{o.stopPropagation(),s(r==="side-by-side"?"unified":"side-by-side")},[r,s]);return e.jsx(Ae,{size:"sm",variant:"ghost",className:T("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:n,title:r==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:r==="side-by-side"?e.jsx(Ad,{className:"h-3 w-3"}):e.jsx(Dd,{className:"h-3 w-3"})})},fa=le.createContext(void 0);function kr(){const r=le.useContext(fa);if(!r)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return r}function pa(){return le.useContext(fa)}const pp="Flexoki",hp="dark",gp={"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"},xp=[{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"}}],yp={name:pp,type:hp,colors:gp,tokenColors:xp},bp="Flexoki",wp="light",vp={"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"},jp=[{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"}}],Sp={name:bp,type:wp,colors:vp,tokenColors:jp},ha="flexoki-dark",ga="flexoki-light",kp=yp,Np=Sp;function Ql(r,s){return Object.defineProperty(r,"toString",{value:()=>s,enumerable:!1,configurable:!0}),Object.defineProperty(r,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0}),r}function ec(r,s,t){const n=r.colors?.["editor.background"],o=r.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${s}" is missing editor.background/editor.foreground`);const a=r.tokenColors??[];return{...r,name:s,type:t,fg:o,bg:n,settings:a}}const xa=ec(kp,ha,"dark"),ya=ec(Np,ga,"light");Ql(xa,ha);Ql(ya,ga);const yr={dark:ha,light:ga},ai=[ya,xa];let ii=!1;function tc(){ii||(Ma(yr.dark,async()=>xa),Ma(yr.light,async()=>ya),ii=!0)}const Cp=`
7
- :host {
8
- font-family: var(--font-mono);
9
- font-size: var(--text-code);
10
- }
11
-
12
- :host, pre, [data-diffs], [data-code] {
13
- transform: translateZ(0);
14
- -webkit-transform: translateZ(0);
15
- -webkit-backface-visibility: hidden;
16
- backface-visibility: hidden;
17
- }
18
-
19
- pre, [data-code] {
20
- font-family: var(--font-mono);
21
- font-size: var(--text-code);
22
- }
23
-
24
- [data-code] {
25
- -webkit-overflow-scrolling: touch;
26
- }
27
- /* Reduce hunk separator height */
28
- [data-separator-content] {
29
- height: 24px !important;
30
- }
31
- [data-expand-button] {
32
- height: 24px !important;
33
- width: 24px !important;
34
- }
35
- [data-separator-multi-button] {
36
- row-gap: 0 !important;
37
- }
38
- [data-expand-up] {
39
- height: 12px !important;
40
- min-height: 12px !important;
41
- max-height: 12px !important;
42
- margin: 0 !important;
43
- margin-top: 3px !important;
44
- padding: 0 !important;
45
- border-radius: 4px 4px 0 0 !important;
46
- }
47
- [data-expand-down] {
48
- height: 12px !important;
49
- min-height: 12px !important;
50
- max-height: 12px !important;
51
- margin: 0 !important;
52
- margin-top: -3px !important;
53
- padding: 0 !important;
54
- border-radius: 0 0 4px 4px !important;
55
- }
56
- `;function Mp(r,s,t){const n=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${r}:${s.length}:${t.length}:${n.length}:${o.length}`}const li=({original:r,modified:s,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=pa()?.currentTheme?.metadata?.variant==="dark";tc();const d=le.useRef(null),u=le.useMemo(()=>{const m=Mp(n,r,s);if(d.current?.key===m)return d.current.fileDiff;const f={name:n,contents:r,cacheKey:`old-${m}`},h={name:n,contents:s,cacheKey:`new-${m}`},g=So(f,h);return d.current={key:m,fileDiff:g},g},[n,r,s,t]),p=le.useMemo(()=>({theme:{dark:yr.dark,light:yr.light},themeType:c?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!1,enableHoverUtility:!1,unsafeCSS:Cp}),[c,o,a]);return typeof window>"u"?null:e.jsx(Xe,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(Ed,{fileDiff:u,options:p})})},Ap=1100,Dp=r=>{const{index:s,working_dir:t}=r;return s==="A"||t==="A"||s==="?"||t==="?"},ci=(r,s)=>{const t=r??0,n=s??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]})},Ep=l.memo(({changedFiles:r,selectedFile:s,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=l.useCallback(i=>{if(!o)return i;const c=i.lastIndexOf("/");return c>=0?i.slice(c+1):i},[o]);return r.length===0?null:e.jsxs(Xt,{children:[e.jsx(Jt,{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)}),ci(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(vt,{className:"size-4 opacity-50"})]})}),e.jsx(Zt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(np,{value:s??"",onValueChange:n,children:r.map(i=>e.jsx(op,{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:ci(i.insertions,i.deletions)})]})},i.path))})})]})}),Tp=l.memo(({filePath:r,diff:s,isVisible:t,renderSideBySide:n})=>{const o=s.original.length>0,a=s.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:i,children:[o&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:s.original,alt:`Original: ${r}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:s.modified,alt:`Modified: ${r}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Ip=l.memo(({filePath:r,diff:s,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=l.useMemo(()=>qr(r)||"text",[r]);return Jl(r)?e.jsx(Tp,{filePath:r,diff:s,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(li,{original:s.original,modified:s.modified,language:a,fileName:r,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(li,{original:s.original,modified:s.modified,language:a,fileName:r,renderSideBySide:n,wrapLines:o})})}),Fp=l.memo(({directory:r,filePath:s,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Mt(l.useCallback(c=>c.directories.get(r)?.diffCache.get(s)??null,[r,s])),i=l.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a?.original,a?.modified]);return i?e.jsx(Ip,{filePath:s,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),Pp=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=me(),{currentDirectory:n}=St(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},Rp=()=>{const{git:r}=rr(),s=Pp(),{screenWidth:t,isMobile:n}=Dt(),o=Xl(s??null),a=Yl(s??null),i=Mt(E=>E.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d}=Mt(),[u,p]=l.useState(null),m=Pe(E=>E.pendingDiffFile),f=Pe(E=>E.setPendingDiffFile),h=Pe(E=>E.diffLayoutPreference),g=Pe(E=>E.diffFileLayout),b=Pe(E=>E.setDiffFileLayout),x=Pe(E=>E.diffWrapLines),w=Pe(E=>E.setDiffWrapLines),S=l.useMemo(()=>{if(!a?.files)return[];const E=a.diffStats??{};return a.files.map(F=>({...F,insertions:E[F.path]?.insertions??0,deletions:E[F.path]?.deletions??0,isNew:Dp(F)})).sort((F,W)=>F.path.localeCompare(W.path))},[a]),v=l.useMemo(()=>u?S.find(E=>E.path===u)??null:null,[S,u]),j=l.useMemo(()=>{if(!v)return null;const E=g[v.path];if(E)return E;if(h==="inline")return"inline";if(h==="side-by-side")return"side-by-side";const F=t<Ap;return v.isNew||F?"inline":"side-by-side"},[v,g,h,t]);l.useEffect(()=>{s&&(c(s),Mt.getState().directories.get(s)?.status||d(s,r))},[s,c,d,r]),l.useEffect(()=>{m&&(p(m),f(null))},[m,f]),l.useEffect(()=>{!u&&!m&&S.length>0&&p(S[0].path)},[S,u,m]),l.useEffect(()=>{u&&S.length>0&&(S.some(F=>F.path===u)||p(S[0]?.path??null))},[S,u]);const k=l.useCallback(E=>{p(E)},[]),y=(j??"side-by-side")==="side-by-side",D=!!Mt(l.useCallback(E=>!s||!u?null:E.directories.get(s)?.diffCache.get(u)??null,[s,u])),N=!!u&&!D,C=()=>!s||S.length===0?null:S.map(E=>e.jsx(Fp,{directory:s,filePath:E.path,isVisible:E.path===u,renderSideBySide:y,wrapLines:x},E.path)),M=()=>s?i&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Bt,{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."}):S.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:[C(),N&&!D&&e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Bt,{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(Vo,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${S.length} ${S.length===1?"file":"files"} changed`})]}),e.jsx(Ep,{changedFiles:S,selectedFile:u,selectedFileEntry:v,onSelectFile:k,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),v&&e.jsx("button",{type:"button",onClick:()=>w(!x),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${x?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:x?"Disable line wrap":"Enable line wrap",children:e.jsx(Td,{className:"size-4"})}),v&&j&&e.jsx(fp,{mode:j==="side-by-side"?"side-by-side":"unified",onModeChange:E=>{if(!v)return;const F=E==="side-by-side"?"side-by-side":"inline";b(v.path,F)}})]}),M()]})},Lp=()=>{const{git:r}=rr(),{currentSessionId:s,sessions:t,worktreeMetadata:n}=me(),{currentDirectory:o}=St(),a=s?n.get(s)??void 0:void 0,c=t.find(f=>f.id===s)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:u,fetchStatus:p}=Mt(),m=rp(d??null);return l.useEffect(()=>{d&&(u(d),Mt.getState().directories.get(d)?.status||p(d,r))},[d,u,p,r]),m},_p=()=>{const r=Pe(d=>d.setSessionSwitcherOpen),s=Pe(d=>d.toggleSidebar),{isMobile:t}=Dt(),[n,o]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=l.useCallback(()=>{t?r(!0):s()},[t,r,s]),c="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground";return t||!n||!a?null:e.jsx("div",{className:"fixed top-[0.375rem] left-[5.25rem] z-[9999]",style:{pointerEvents:"auto","--padding-scale":"1"},children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Open sessions",className:c,children:e.jsx(Hn,{className:"h-5 w-5"})})})},di=()=>{const r=Pe(z=>z.setSessionSwitcherOpen),s=Pe(z=>z.toggleSidebar),t=Pe(z=>z.setSettingsDialogOpen),n=Pe(z=>z.isSidebarOpen),o=Pe(z=>z.sidebarWidth),a=Pe(z=>z.activeMainTab),i=Pe(z=>z.setActiveMainTab),{getCurrentModel:c}=kt(),d=me(z=>z.getContextUsage),{isMobile:u}=Dt(),p=Lp(),m=l.useRef(null),[f,h]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),g=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);le.useEffect(()=>{if(typeof window>"u")return;const z=typeof window.opencodeDesktop<"u";h(z)},[]);const b=c(),x=b&&typeof b.limit=="object"&&b.limit!==null?b.limit:null,w=x&&typeof x.context=="number"?x.context:0,S=x&&typeof x.output=="number"?x.output:0,v=d(w,S),j=Pe(z=>z.isSessionSwitcherOpen),k=l.useCallback(()=>{if(typeof document>"u")return;const z=document.activeElement;if(!z)return;const G=z.tagName;(G==="INPUT"||G==="TEXTAREA"||G==="SELECT"||z.isContentEditable)&&z.blur()},[]),y=l.useCallback(()=>{if(u){k(),r(!j);return}s()},[k,u,j,r,s]),A=l.useCallback(()=>{u&&k(),r(!1),t(!0)},[k,u,r,t]),D="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",N=l.useMemo(()=>f&&g?n?"pl-0":"pl-[8.0rem]":"pl-3",[f,g,n]),C=l.useCallback(()=>{if(typeof document>"u")return;const z=m.current?.getBoundingClientRect().height;z&&document.documentElement.style.setProperty("--oc-header-height",`${z}px`)},[]);le.useEffect(()=>{if(typeof window>"u")return;C();const z=m.current;if(!z||typeof ResizeObserver>"u")return()=>{};const G=new ResizeObserver(()=>{C()});return G.observe(z),window.addEventListener("resize",C),window.addEventListener("orientationchange",C),()=>{G.disconnect(),window.removeEventListener("resize",C),window.removeEventListener("orientationchange",C)}},[C]),le.useEffect(()=>{C()},[C,u]);const M=l.useCallback(async z=>{if(!z.target.closest("button, a, input, select, textarea")&&z.button===0&&f)try{const{getCurrentWindow:G}=await Lr(async()=>{const{getCurrentWindow:oe}=await import("./vendor-.pnpm-B7ko08Tb.js").then(ve=>ve.b$);return{getCurrentWindow:oe}},__vite__mapDeps([0,1]));await G().startDragging()}catch(G){console.error("Failed to start window dragging:",G)}},[f]),E=l.useCallback(async z=>{if(z.button===0&&f)try{const{getCurrentWindow:G}=await Lr(async()=>{const{getCurrentWindow:oe}=await import("./vendor-.pnpm-B7ko08Tb.js").then(ve=>ve.b$);return{getCurrentWindow:oe}},__vite__mapDeps([0,1]));await G().startDragging()}catch(G){console.error("Failed to start window dragging:",G)}},[f]),F=l.useMemo(()=>[{id:"chat",label:"Chat",icon:Id},{id:"diff",label:"Diff",icon:zs,badge:!u&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:Ws},{id:"git",label:"Git",icon:Yt}],[p,u]);le.useEffect(()=>{const z=G=>{if((G.metaKey||G.ctrlKey)&&!G.shiftKey&&!G.altKey){const H=parseInt(G.key,10);H>=1&&H<=F.length&&(G.preventDefault(),i(F[H-1].id))}};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[F,i]);const W=(z,G)=>{const H=a===z.id,oe=z.icon,ve=z.id==="chat",Ee=z.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>i(z.id),onMouseDown:H?E:void 0,className:T("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",H?"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",H?"text-foreground":"text-muted-foreground",H&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",H&&ve&&n&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",ve&&!(f&&g&&n)&&"border-l",Ee&&"border-r",ve&&!u&&"min-w-[165px]"),style:{...H&&ve&&n?{"--sidebar-w":f&&g?`${o}px`:"64px"}:{},...ve&&!(f&&g&&n)||Ee?{borderColor:"var(--interactive-border)"}:{}},"aria-selected":H,role:"tab",children:[u?e.jsx(oe,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{size:16}),e.jsx("span",{children:z.label})]}),ve&&!u&&v&&v.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Io,{totalTokens:v.totalTokens,percentage:v.percentage,contextLimit:v.contextLimit,outputLimit:v.outputLimit??0,size:"compact"})}),z.badge!==void 0&&z.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:z.badge})]}),!G&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},z.id)},L=()=>e.jsxs("div",{onMouseDown:M,className:T("app-region-drag relative flex h-12 select-none items-center",N),role:"tablist","aria-label":"Main navigation",children:[!(f&&g)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:y,"aria-label":"Open sessions",className:`${D} mr-2.5`,children:e.jsx(Hn,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:F.map((z,G)=>W(z,G===F.length-1))}),e.jsx("div",{className:"flex-1"})]}),K=()=>e.jsxs("div",{className:"app-region-drag relative flex items-center justify-between gap-2 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:y,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(Fd,{className:"h-5 w-5"})}),v&&v.totalTokens>0&&a==="chat"&&e.jsx(Io,{totalTokens:v.totalTokens,percentage:v.percentage,contextLimit:v.contextLimit,outputLimit:v.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:F.map(z=>{const G=a===z.id,H=z.icon;return e.jsxs(ft,{delayDuration:500,children:[e.jsx(pt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{u&&k(),i(z.id)},"aria-label":z.label,"aria-selected":G,role:"tab",className:T(D,G&&"text-foreground"),children:[e.jsx(H,{className:"h-5 w-5"}),z.badge!==void 0&&z.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:z.badge})]})}),e.jsx(ut,{children:e.jsx("p",{children:z.label})})]},z.id)})}),e.jsxs(ft,{delayDuration:500,children:[e.jsx(pt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:A,"aria-label":"Open settings",className:D,children:e.jsx(hr,{className:"h-5 w-5"})})}),e.jsx(ut,{children:e.jsx("p",{children:"Settings"})})]})]})]}),X=T("header-safe-area border-b relative z-10",f?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:m,className:X,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:u?K():L()})};function ba({className:r,...s}){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",r),...s})}function sc({className:r,...s}){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",r),...s})}function rc({className:r,...s}){return e.jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",r),...s})}function nc({className:r,...s}){return e.jsx("div",{"data-slot":"card-content",className:T("px-6",r),...s})}class ls extends l.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,t){this.setState({error:s,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(ba,{className:"w-full max-w-md",children:[e.jsx(sc,{className:"text-center",children:e.jsxs(rc,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(ko,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(nc,{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(Ae,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ds,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}const Fo=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_MOCK_UPDATE__;return r?r===!0?{currentVersion:"1.0.3",newVersion:"1.0.8"}:r:null},ui=r=>({checking:!1,available:!0,downloading:!1,downloaded:!1,info:{available:!0,version:r.newVersion??"99.0.0-test",currentVersion:r.currentVersion??"0.0.0",body:void 0},progress:null,error:null}),mi=()=>Fo()!==null,Op=(r=!0)=>{const[s,t]=le.useState({checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null}),[n]=le.useState(mi),[o,a]=le.useState(()=>{if(mi()){const m=Fo();return m?ui(m):null}return null}),i=le.useCallback(async()=>{if(n){const m=Fo();if(m){const f=ui(m);f.info={...f.info,body:`## [${m.newVersion}] - 2025-01-01
57
- - Mock update for UI testing`},a(f)}return}if(es()){t(m=>({...m,checking:!0,error:null}));try{const m=await xm();t(f=>({...f,checking:!1,available:m?.available??!1,info:m}))}catch(m){t(f=>({...f,checking:!1,error:m instanceof Error?m.message:"Failed to check for updates"}))}}},[n]),c=le.useCallback(async()=>{if(n){a(h=>h&&{...h,downloading:!0});let m=0;const f=setInterval(()=>{m+=20,a(h=>h&&{...h,progress:{downloaded:m*1e3,total:1e5}}),m>=100&&(clearInterval(f),a(h=>h&&{...h,downloading:!1,downloaded:!0,progress:null}))},500);return}if(!(!es()||!s.available)){t(m=>({...m,downloading:!0,error:null,progress:null}));try{await ym(m=>{t(f=>({...f,progress:m}))}),t(m=>({...m,downloading:!1,downloaded:!0}))}catch(m){t(f=>({...f,downloading:!1,error:m instanceof Error?m.message:"Failed to download update"}))}}},[n,s.available]),d=le.useCallback(async()=>{if(!n&&!(!es()||!s.downloaded))try{await bm()}catch(m){t(f=>({...f,error:m instanceof Error?m.message:"Failed to restart"}))}},[n,s.downloaded]),u=le.useCallback(()=>{if(n){a(null);return}t(m=>({...m,available:!1,downloaded:!1,info:null}))},[n]);return le.useEffect(()=>{if(r&&(es()||n)){const m=setTimeout(()=>{i()},3e3);return()=>clearTimeout(m)}},[r,i,n]),{...n&&o?o:s,checkForUpdates:i,downloadUpdate:c,restartToUpdate:d,dismiss:u}};let rn=0;function Is({...r}){return e.jsx(Pd,{"data-slot":"dialog",...r})}function oc({...r}){return e.jsx($d,{"data-slot":"dialog-trigger",...r})}function Bp({...r}){return e.jsx(_d,{"data-slot":"dialog-portal",...r})}const ac=le.forwardRef(({className:r,...s},t)=>(le.useEffect(()=>(rn+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{rn=Math.max(0,rn-1),rn===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(gl,{ref:t,"data-slot":"dialog-overlay",className:T("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",r),...s})));ac.displayName=gl.displayName;function Fs({className:r,children:s,showCloseButton:t=!0,...n}){return e.jsxs(Bp,{"data-slot":"dialog-portal",children:[e.jsx(ac,{className:"rounded-none"}),e.jsxs(Rd,{"data-slot":"dialog-content",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",r),...n,children:[s,t&&e.jsxs(Ld,{"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(ds,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Ps({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:T("flex flex-col gap-2 text-center sm:text-left",r),...s})}function Hr({className:r,...s}){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",r),...s})}function Rs({className:r,...s}){return e.jsx(Od,{"data-slot":"dialog-title",className:T("typography-markdown leading-none font-semibold text-foreground",r),...s})}function nr({className:r,...s}){return e.jsx(Bd,{"data-slot":"dialog-description",className:T("text-muted-foreground typography-ui-label",r),...s})}const fi="https://github.com/btriapitsyn/openchamber/releases",$p=({open:r,onOpenChange:s,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d})=>{const u=t?.version?`${fi}/tag/v${t.version}`:fi,p=a?.total?Math.round(a.downloaded/a.total*100):0;return e.jsx(Is,{open:r,onOpenChange:s,children:e.jsxs(Fs,{className:"max-w-md",children:[e.jsx(Ps,{children:e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(zd,{className:"h-5 w-5 text-primary"}),"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})]}),t?.body&&e.jsx(Xe,{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((m,f)=>/^\d+\.\d+\.\d+$/.test(m.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",m.trim(),`
58
- `]},f):m.replace(/^- /gm,"• ").trim()+`
59
-
60
- `)})}),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:[p,"%"]})]}),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:`${p}%`}})})]}),i&&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})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:u,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(No,{className:"h-4 w-4"}),"GitHub"]}),!o&&!n&&e.jsxs("button",{onClick:c,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(Go,{className:"h-4 w-4"}),"Download Update"]}),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(Hd,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),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(Ds,{className:"h-4 w-4"}),"Restart to Update"]})]})]})]})})},Ln=264,pi=200,hi=500,zp=40,gi="openchamber:check-for-updates",Hp=({isOpen:r,isMobile:s,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a}=Pe(),[i,c]=l.useState(!1),d=l.useRef(0),u=l.useRef(n||Ln),[p,m]=l.useState(!1),f=Op(),h=l.useRef(!1),g=f.checkForUpdates,{available:b,downloaded:x,checking:w}=f,[S,v]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const N=typeof window.opencodeDesktop<"u";v(N)},[]),l.useEffect(()=>{if(typeof window>"u")return;const N=()=>{typeof window.opencodeDesktop<"u"&&(h.current=!0,g())};return window.addEventListener(gi,N),()=>{window.removeEventListener(gi,N)}},[g]),l.useEffect(()=>{h.current&&(w||((b||x)&&m(!0),h.current=!1))},[b,x,w]),l.useEffect(()=>{if(s||!i)return;const N=M=>{const E=M.clientX-d.current,F=Math.min(hi,Math.max(pi,u.current+E));o(F)},C=()=>{c(!1)};return window.addEventListener("pointermove",N),window.addEventListener("pointerup",C,{once:!0}),()=>{window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",C)}},[s,i,o]),l.useEffect(()=>{s&&i&&c(!1)},[s,i]);const k=l.useCallback(async N=>{if(N.button===0&&S)try{const{getCurrentWindow:C}=await Lr(async()=>{const{getCurrentWindow:E}=await import("./vendor-.pnpm-B7ko08Tb.js").then(F=>F.b$);return{getCurrentWindow:E}},__vite__mapDeps([0,1]));await C().startDragging()}catch(C){console.error("Failed to start window dragging from sidebar:",C)}},[S]);if(s)return null;const y=r?Math.min(hi,Math.max(pi,n||Ln)):0,A=S&&j,D=N=>{r&&(c(!0),d.current=N.clientX,u.current=y,N.preventDefault())};return e.jsxs("aside",{className:T("relative flex h-full overflow-hidden border-r",S?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",i?"transition-none":"",!r&&"border-r-0"),style:{width:`${y}px`,minWidth:`${y}px`,maxWidth:`${y}px`,pointerEvents:r?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!r||y===0,children:[r&&e.jsx("div",{className:T("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",i?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:D,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",!r&&"pointer-events-none select-none opacity-0"),style:{width:`${y}px`,overflowX:"hidden"},"aria-hidden":!r,children:[A&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${zp}px`},onMouseDown:k,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{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(hr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),(b||x)&&e.jsxs("button",{onClick:()=>m(!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(Go,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]})]})}),e.jsx($p,{open:p,onOpenChange:m,info:f.info,downloading:f.downloading,downloaded:f.downloaded,progress:f.progress,error:f.error,onDownload:f.downloadUpdate,onRestart:f.restartToUpdate})]})]})},ic=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:qo},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Wn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:wr},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:xl},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Yt},{id:"settings",label:"Appearance",description:"Fine-tune themes, fonts, and typography across the interface.",icon:Wd}],Wp={},lc={},cc={};ic.forEach(r=>{Wp[r.id]=r.label,lc[r.id]=r.description,cc[r.id]=r});const xi=lc,Up=cc;function _n({className:r,variant:s,...t}){return e.jsx(Ae,{variant:s,size:"sm",className:T("h-7 px-2 py-0",r),...t})}function Pt({className:r,type:s,...t}){return e.jsx("input",{type:s,"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",r),...t})}const Vp=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedAgentName:o,agents:a,setSelectedAgent:i,deleteAgent:c,loadAgents:d}=jr(),{setSidebarOpen:u}=Pe(),{isMobile:p}=Dt();l.useEffect(()=>{d()},[d]);const m=()=>{if(!r.trim()){be.error("Agent name is required");return}if(a.some(S=>S.name===r)){be.error("An agent with this name already exists");return}i(r),s(""),n(!1),p&&u(!1)},f=async S=>{if(hn(S)){be.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${S.name}"?`)&&(await c(S.name)?be.success(`Agent "${S.name}" deleted successfully`):be.error("Failed to delete agent"))},h=S=>{const v=S.name;let j=1,k=`${v} Copy`;for(;a.some(y=>y.name===k);)j++,k=`${v} Copy ${j}`;i(k),n(!1),p&&u(!1)},g=S=>{switch(S){case"primary":return e.jsx(_r,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(bl,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(yl,{className:"h-3 w-3 text-primary"});default:return null}},b=a.filter(S=>!Dl(S)),x=b.filter(hn),w=b.filter(S=>!hn(S));return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(Is,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",p?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Agents"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:b.length}),e.jsx(oc,{asChild:!0,children:e.jsx(Ae,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(os,{className:"size-4"})})})]})]})}),e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:b.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(kn,{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:[x.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"}),x.map(S=>e.jsx(yi,{agent:S,isSelected:o===S.name,onSelect:()=>{i(S.name),p&&u(!1)},onDuplicate:()=>h(S),getAgentModeIcon:g},S.name))]}),w.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"}),w.map(S=>e.jsx(yi,{agent:S,isSelected:o===S.name,onSelect:()=>{i(S.name),p&&u(!1)},onDelete:()=>f(S),onDuplicate:()=>h(S),getAgentModeIcon:g},S.name))]})]})}),e.jsxs(Fs,{children:[e.jsxs(Ps,{children:[e.jsx(Rs,{children:"Create New Agent"}),e.jsx(nr,{children:"Enter a unique name for your new agent"})]}),e.jsx(Pt,{value:r,onChange:S=>s(S.target.value),placeholder:"Agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&m()}}),e.jsxs(Hr,{children:[e.jsx(Ae,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(_n,{onClick:m,children:"Create"})]})]})]})})},yi=({agent:r,isSelected:s,onSelect:t,onDelete:n,onDuplicate:o,getAgentModeIcon:a})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",s?"text-primary":"text-foreground hover:text-primary/80"),children:r.name}),a(r.mode)]}),r.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.description})]}),e.jsxs(Xt,{children:[e.jsx(Jt,{asChild:!0,children:e.jsx(Ae,{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(Un,{className:"h-3.5 w-3.5"})})}),e.jsxs(Zt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(gt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),!hn(r)&&n&&e.jsxs(gt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})});function Ss({className:r,variant:s,...t}){return e.jsx(Ae,{variant:s,size:"sm",className:T("h-6 px-2 text-xs",r),...t})}const tr=le.forwardRef(({className:r,...s},t)=>e.jsx(Xe,{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",r),...s}));tr.displayName="Textarea";const Gp="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",qp="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eMoonshotAI%3c/title%3e%3cpath%20d='M1.052%2016.916l9.539%202.552a21.007%2021.007%200%2000.06%202.033l5.956%201.593a11.997%2011.997%200%2001-5.586.865l-.18-.016-.044-.004-.084-.009-.094-.01a11.605%2011.605%200%2001-.157-.02l-.107-.014-.11-.016a11.962%2011.962%200%2001-.32-.051l-.042-.008-.075-.013-.107-.02-.07-.015-.093-.019-.075-.016-.095-.02-.097-.023-.094-.022-.068-.017-.088-.022-.09-.024-.095-.025-.082-.023-.109-.03-.062-.02-.084-.025-.093-.028-.105-.034-.058-.019-.08-.026-.09-.031-.066-.024a6.293%206.293%200%2001-.044-.015l-.068-.025-.101-.037-.057-.022-.08-.03-.087-.035-.088-.035-.079-.032-.095-.04-.063-.028-.063-.027a5.655%205.655%200%2001-.041-.018l-.066-.03-.103-.047-.052-.024-.096-.046-.062-.03-.084-.04-.086-.044-.093-.047-.052-.027-.103-.055-.057-.03-.058-.032a6.49%206.49%200%2001-.046-.026l-.094-.053-.06-.034-.051-.03-.072-.041-.082-.05-.093-.056-.052-.032-.084-.053-.061-.039-.079-.05-.07-.047-.053-.035a7.785%207.785%200%2001-.054-.036l-.044-.03-.044-.03a6.066%206.066%200%2001-.04-.028l-.057-.04-.076-.054-.069-.05-.074-.054-.056-.042-.076-.057-.076-.059-.086-.067-.045-.035-.064-.052-.074-.06-.089-.073-.046-.039-.046-.039a7.516%207.516%200%2001-.043-.037l-.045-.04-.061-.053-.07-.062-.068-.06-.062-.058-.067-.062-.053-.05-.088-.084a13.28%2013.28%200%2001-.099-.097l-.029-.028-.041-.042-.069-.07-.05-.051-.05-.053a6.457%206.457%200%2001-.168-.179l-.08-.088-.062-.07-.071-.08-.042-.049-.053-.062-.058-.068-.046-.056a7.175%207.175%200%2001-.027-.033l-.045-.055-.066-.082-.041-.052-.05-.064-.02-.025a11.99%2011.99%200%2001-1.44-2.402zm-1.02-5.794l11.353%203.037a20.468%2020.468%200%2000-.469%202.011l10.817%202.894a12.076%2012.076%200%2001-1.845%202.005L.657%2015.923l-.016-.046-.035-.104a11.965%2011.965%200%2001-.05-.153l-.007-.023a11.896%2011.896%200%2001-.207-.741l-.03-.126-.018-.08-.021-.097-.018-.081-.018-.09-.017-.084-.018-.094c-.026-.141-.05-.283-.071-.426l-.017-.118-.011-.083-.013-.102a12.01%2012.01%200%2001-.019-.161l-.005-.047a12.12%2012.12%200%2001-.034-2.145zm1.593-5.15l11.948%203.196c-.368.605-.705%201.231-1.01%201.875l11.295%203.022c-.142.82-.368%201.612-.668%202.365l-11.55-3.09L.124%2010.26l.015-.1.008-.049.01-.067.015-.087.018-.098c.026-.148.056-.295.088-.442l.028-.124.02-.085.024-.097c.022-.09.045-.18.07-.268l.028-.102.023-.083.03-.1.025-.082.03-.096.026-.082.031-.095a11.896%2011.896%200%20011.01-2.232zm4.442-4.4L17.352%204.59a20.77%2020.77%200%2000-1.688%201.721l7.823%202.093c.267.852.442%201.744.513%202.665L2.106%205.213l.045-.065.027-.04.04-.055.046-.065.055-.076.054-.072.064-.086.05-.065.057-.073.055-.07.06-.074.055-.069.065-.077.054-.066.066-.077.053-.06.072-.082.053-.06.067-.074.054-.058.073-.078.058-.06.063-.067.168-.17.1-.098.059-.056.076-.071a12.084%2012.084%200%20012.272-1.677zM12.017%200h.097l.082.001.069.001.054.002.068.002.046.001.076.003.047.002.06.003.054.002.087.005.105.007.144.011.088.007.044.004.077.008.082.008.047.005.102.012.05.006.108.014.081.01.042.006.065.01.207.032.07.012.065.011.14.026.092.018.11.022.046.01.075.016.041.01L14.7.3l.042.01.065.015.049.012.071.017.096.024.112.03.113.03.113.032.05.015.07.02.078.024.073.023.05.016.05.016.076.025.099.033.102.036.048.017.064.023.093.034.11.041.116.045.1.04.047.02.06.024.041.018.063.026.04.018.057.025.11.048.1.046.074.035.075.036.06.028.092.046.091.045.102.052.053.028.049.026.046.024.06.033.041.022.052.029.088.05.106.06.087.051.057.034.053.032.096.059.088.055.098.062.036.024.064.041.084.056.04.027.062.042.062.043.023.017c.054.037.108.075.161.114l.083.06.065.048.056.043.086.065.082.064.04.03.05.041.086.069.079.065.085.071c.712.6%201.353%201.283%201.909%202.031L7.222.994l.062-.027.065-.028.081-.034.086-.035c.113-.045.227-.09.341-.131l.096-.035.093-.033.084-.03.096-.031c.087-.03.176-.058.264-.085l.091-.027.086-.025.102-.03.085-.023.1-.026L9.04.37l.09-.023.091-.022.095-.022.09-.02.098-.021.091-.02.095-.018.092-.018.1-.018.091-.016.098-.017.092-.014.097-.015.092-.013.102-.013.091-.012.105-.012.09-.01.105-.01c.093-.01.186-.018.28-.024l.106-.008.09-.005.11-.006.093-.004.1-.004.097-.002.099-.002.197-.002z'%3e%3c/path%3e%3c/svg%3e",Kp=Object.assign({"../assets/provider-logos/gocode.svg":Gp,"../assets/provider-logos/kimi-for-coding.svg":qp}),Po=new Map;for(const[r,s]of Object.entries(Kp)){const t=r.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&s&&Po.set(t[1].toLowerCase(),s)}function dc(r){const s=r?.toLowerCase()??null,t=s?Po.has(s):!1,n=s?Po.get(s)??null:null,[o,a]=le.useState(t?"local":"remote");le.useEffect(()=>{a(t?"local":"remote")},[t,s]);const i=le.useCallback(()=>{a(c=>c==="local"&&t?"remote":"none")},[t]);return s?o==="local"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${s}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const Vt=({providerId:r,alt:s,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=dc(r),c=l.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:s||`${r} logo`,className:T("dark:invert",t),onError:c})},uc=()=>{const{providers:r}=kt(),{favoriteModels:s,recentModels:t}=Pe(),n=l.useMemo(()=>s.map(({providerID:a,modelID:i})=>{const c=r.find(p=>p.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(p=>p.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[s,r]),o=l.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const c=r.find(p=>p.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(p=>p.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!s.some(c=>c.providerID===a&&c.modelID===i)),[t,r,s]);return{favoriteModelsList:n,recentModelsList:o}},mc=({providerId:r,modelId:s,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=kt(),i=Pe(D=>D.isMobile),{toggleFavoriteModel:c,isFavoriteModel:d,addRecentModel:u}=Pe(),{favoriteModelsList:p,recentModelsList:m}=uc(),{isMobile:f}=Dt(),h=i||f,[g,b]=l.useState(!1),[x,w]=l.useState(new Set),S=()=>b(!1),v=D=>{w(N=>{const C=new Set(N);return C.has(D)?C.delete(D):C.add(D),C})},j=D=>{const N=D?.name||D?.id||"",C=String(N);return C.length>40?C.substring(0,37)+"...":C},k=(D,N)=>{const C=`${D}/${N}`;return a.get(C)},y=(D,N)=>{t(D,N),u(D,N)},A=()=>h?e.jsx(Kt,{open:g,onClose:S,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[p.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:p.map(({model:D,providerID:N,modelID:C})=>{const M=N===r&&C===s,E=k(N,C);return e.jsxs("div",{className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",M?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsxs("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{y(N,C),S()},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{providerId:N,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:j(D)})]}),typeof E?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:E.description})]}),e.jsx("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),c(N,C)},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(hs,{className:"h-4 w-4"})})]},`fav-mobile-${N}-${C}`)})})]}),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:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:m.map(({model:D,providerID:N,modelID:C})=>{const M=N===r&&C===s,E=k(N,C);return e.jsxs("div",{className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",M?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsxs("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{y(N,C),S()},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{providerId:N,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:j(D)})]}),typeof E?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:E.description})]}),e.jsx("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),c(N,C)},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(Zs,{className:"h-4 w-4"})})]},`recent-mobile-${N}-${C}`)})})]}),o.map(D=>{const N=Array.isArray(D.models)?D.models:[];if(N.length===0)return null;const C=D.id===r,M=x.has(D.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left",onClick:()=>v(D.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{providerId:D.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:D.name}),C&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),M?e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(us,{className:"h-3 w-3 text-muted-foreground"})]}),M&&e.jsx("div",{className:"border-t border-border/20",children:N.map(E=>{const F=D.id===r&&E.id===s,W=k(D.id,E.id);return e.jsxs("div",{className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",F?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsxs("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{y(D.id,E.id),S()},children:[e.jsx("span",{className:"font-medium truncate",children:j(E)}),typeof W?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:W.description})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),c(D.id,E.id)},className:T("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(D.id,E.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(D.id,E.id)?"Unfavorite":"Favorite",children:d(D.id,E.id)?e.jsx(hs,{className:"h-4 w-4"}):e.jsx(Zs,{className:"h-4 w-4"})}),F&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},E.id)})})]},D.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{y("",""),S()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[h?e.jsxs("button",{type:"button",onClick:()=>b(!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:[r?e.jsx(Vt,{providerId:r,className:"h-3.5 w-3.5"}):e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:r&&s?`${r}/${s}`:"Select model..."})]}),e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Xt,{children:[e.jsx(Jt,{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:[r?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{providerId:r,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Cs,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Cs,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:r&&s?`${r}/${s}`:"Not selected"}),e.jsx(vt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Zt,{className:"max-w-[300px]",children:[p.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(hs,{className:"h-3 w-3 flex-shrink-0 mr-2 text-yellow-500"}),"Favorites"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Xe,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:p.map(({model:D,providerID:N,modelID:C})=>{const M=k(N,C);return e.jsx(gt,{className:"typography-meta",onSelect:E=>{E.preventDefault(),y(N,C)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:j(D)}),typeof M?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:M.description})]}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),c(N,C)},className:"model-favorite-button flex h-4 w-4 items-center justify-center text-yellow-500 hover:text-yellow-600","aria-label":"Unfavorite",children:e.jsx(hs,{className:"h-3.5 w-3.5"})})]})},`fav-${N}-${C}`)})})})]}),m.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(Nn,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Xe,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:m.map(({model:D,providerID:N,modelID:C})=>{const M=k(N,C);return e.jsx(gt,{className:"typography-meta",onSelect:E=>{E.preventDefault(),y(N,C)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:j(D)}),typeof M?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:M.description})]}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),c(N,C)},className:"model-favorite-button flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-yellow-600","aria-label":"Favorite",children:e.jsx(Zs,{className:"h-3.5 w-3.5"})})]})},`recent-${N}-${C}`)})})})]}),(p.length>0||m.length>0)&&e.jsx(zr,{}),o.map(D=>{const N=Array.isArray(D.models)?D.models:[];return N.length===0?e.jsxs(gt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Vt,{providerId:D.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),D.name," (No models)"]},D.id):e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(Vt,{providerId:D.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),D.name]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Xe,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:N.map(C=>{const M=k(D.id,C.id);return e.jsx(gt,{className:"typography-meta",onSelect:E=>{E.preventDefault(),y(D.id,C.id)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:j(C)}),typeof M?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:M.description})]}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),c(D.id,C.id)},className:T("flex h-4 w-4 items-center justify-center hover:text-yellow-600",d(D.id,C.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":d(D.id,C.id)?"Unfavorite":"Favorite",children:d(D.id,C.id)?e.jsx(hs,{className:"h-3.5 w-3.5"}):e.jsx(Zs,{className:"h-3.5 w-3.5"})})]})},C.id)})})})]},D.id)}),e.jsx(gt,{className:"typography-meta",onSelect:()=>y("",""),children:e.jsx("span",{className:"text-muted-foreground",children:"No model (optional)"})})]})]}),A()]})},Yp=()=>{const{tools:r}=rr(),[s,t]=l.useState([]),[n,o]=l.useState(!0),[a,i]=l.useState(null);return l.useEffect(()=>{let c=!1;return(async()=>{o(!0),i(null);try{const u=await r.getAvailableTools();if(c)return;t(u)}catch(u){if(c)return;const p=u instanceof Error?u.message:"Failed to fetch tools";console.error("Failed to fetch available tools:",p),i(p),t([])}finally{c||o(!1)}})(),()=>{c=!0}},[r]),{tools:s,isLoading:n,error:a}},Xp=()=>{const{selectedAgentName:r,getAgentByName:s,createAgent:t,updateAgent:n,agents:o}=jr();kt();const{tools:a}=Yp(),i=r?s(r):null,c=r&&!i,[d,u]=l.useState(""),[p,m]=l.useState(""),[f,h]=l.useState("subagent"),[g,b]=l.useState(""),[x,w]=l.useState(void 0),[S,v]=l.useState(void 0),[j,k]=l.useState(""),[y,A]=l.useState({}),[D,N]=l.useState("allow"),[C,M]=l.useState("allow"),[E,F]=l.useState("ask"),[W,L]=l.useState(!1);l.useEffect(()=>{if(c)u(r||""),m(""),h("subagent"),b(""),w(void 0),v(void 0),k(""),A({}),N("allow"),M("allow"),F("ask");else if(i&&(u(i.name),m(i.description||""),h(i.mode||"subagent"),i.model?.providerID&&i.model?.modelID?b(`${i.model.providerID}/${i.model.modelID}`):b(""),w(i.temperature),v(i.topP),k(i.prompt||""),A(i.tools||{}),i.permission)){const G=i.permission.edit;(G==="allow"||G==="ask"||G==="deny"||G==="full")&&N(G),i.permission.webfetch&&M(i.permission.webfetch),typeof i.permission.bash=="string"&&F(i.permission.bash)}},[i,c,r,o]);const K=async()=>{if(!d.trim()){be.error("Agent name is required");return}L(!0);try{const G=g.trim(),H={name:d.trim(),description:p.trim()||void 0,mode:f,model:G===""?null:G,temperature:x,top_p:S,prompt:j.trim()||void 0,tools:Object.keys(y).length>0?y:void 0,permission:{edit:D,webfetch:C,bash:E}};let oe;c?oe=await t(H):oe=await n(d,H),oe?be.success(c?"Agent created successfully":"Agent updated successfully"):be.error(c?"Failed to create agent":"Failed to update agent")}catch(G){console.error("Error saving agent:",G),be.error("An error occurred while saving")}finally{L(!1)}},X=G=>{A(H=>({...H,[G]:!H[G]}))},z=G=>{const H={};a.forEach(oe=>{H[oe]=G}),A(H)};return r?e.jsxs(Xe,{outerClassName:"h-full",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:c?"New Agent":d})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name"}),e.jsx(Pt,{value:d,onChange:G=>u(G.target.value),placeholder:"my-agent",disabled:!c})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(tr,{value:p,onChange:G=>m(G.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(Ss,{variant:f==="primary"?"default":"outline",onClick:()=>h("primary"),className:T("gap-2",f==="primary"?void 0:"text-foreground"),children:[e.jsx(_r,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Ss,{variant:f==="subagent"?"default":"outline",onClick:()=>h("subagent"),className:T("gap-2",f==="subagent"?void 0:"text-foreground"),children:[e.jsx(yl,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Ss,{variant:f==="all"?"default":"outline",onClick:()=>h("all"),className:T("gap-2",f==="all"?void 0:"text-foreground"),children:[e.jsx(bl,{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(mc,{providerId:g?g.split("/")[0]:"",modelId:g?g.split("/")[1]:"",onChange:(G,H)=>{b(G&&H?`${G}/${H}`:"")}})]}),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(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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 H=Math.max(0,(x!==void 0?x:.7)-.1);w(parseFloat(H.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(Aa,{className:"h-3.5 w-3.5"})}),e.jsx(Pt,{type:"text",inputMode:"decimal",value:x!==void 0?x:"",onChange:G=>{const H=G.target.value;if(H===""){w(void 0);return}const oe=parseFloat(H);!isNaN(oe)&&oe>=0&&oe<=2&&w(oe)},onBlur:G=>{const H=G.target.value;if(H!==""){const oe=parseFloat(H);if(!isNaN(oe)){const ve=Math.max(0,Math.min(2,oe));w(parseFloat(ve.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 H=Math.min(2,(x!==void 0?x:.7)+.1);w(parseFloat(H.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(os,{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(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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 H=Math.max(0,(S!==void 0?S:.9)-.1);v(parseFloat(H.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(Aa,{className:"h-3.5 w-3.5"})}),e.jsx(Pt,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:G=>{const H=G.target.value;if(H===""){v(void 0);return}const oe=parseFloat(H);!isNaN(oe)&&oe>=0&&oe<=1&&v(oe)},onBlur:G=>{const H=G.target.value;if(H!==""){const oe=parseFloat(H);if(!isNaN(oe)){const ve=Math.max(0,Math.min(1,oe));v(parseFloat(ve.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 H=Math.min(1,(S!==void 0?S:.9)+.1);v(parseFloat(H.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(os,{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(tr,{value:j,onChange:G=>k(G.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Available Tools"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select tools this agent can access"})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ae,{variant:"outline",size:"sm",onClick:()=>z(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(Ae,{variant:"outline",size:"sm",onClick:()=>z(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(G=>e.jsx("button",{type:"button",onClick:()=>X(G),className:T("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",y[G]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:G},G))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure permission levels for different operations"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Edit Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ae,{size:"sm",variant:D==="full"?"default":"outline",onClick:()=>N("full"),className:"h-6 px-2 text-xs",children:"Full"}),e.jsx(Ae,{size:"sm",variant:D==="allow"?"default":"outline",onClick:()=>N("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ae,{size:"sm",variant:D==="ask"?"default":"outline",onClick:()=>N("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ae,{size:"sm",variant:D==="deny"?"default":"outline",onClick:()=>N("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Controls file editing permissions."}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ut,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Full:"})," Auto-approves all tool requests"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Allows file editing with standard checks"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompts for confirmation before editing"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Blocks all file editing operations"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Bash Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ae,{size:"sm",variant:E==="allow"?"default":"outline",onClick:()=>F("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ae,{size:"sm",variant:E==="ask"?"default":"outline",onClick:()=>F("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ae,{size:"sm",variant:E==="deny"?"default":"outline",onClick:()=>F("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Permission for running bash commands"}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ut,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run bash commands without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before execution"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all bash command execution"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"WebFetch Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ae,{size:"sm",variant:C==="allow"?"default":"outline",onClick:()=>M("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ae,{size:"sm",variant:C==="ask"?"default":"outline",onClick:()=>M("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ae,{size:"sm",variant:C==="deny"?"default":"outline",onClick:()=>M("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Permission for fetching web content"}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ut,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Fetch web content without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before fetching"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all web content access"]})]})})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ae,{size:"sm",variant:"default",onClick:K,disabled:W,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Ko,{className:"h-3 w-3"}),W?"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(kn,{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"})]})})},Jp=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedCommandName:o,commands:a,setSelectedCommand:i,deleteCommand:c,loadCommands:d}=Sr(),{setSidebarOpen:u}=Pe(),{isMobile:p}=Dt();l.useEffect(()=>{d()},[d]);const m=()=>{if(!r.trim()){be.error("Command name is required");return}const g=r.trim().replace(/\s+/g,"-");if(a.some(b=>b.name===g)){be.error("A command with this name already exists");return}i(g),s(""),n(!1),p&&u(!1)},f=async g=>{window.confirm(`Are you sure you want to delete command "${g.name}"?`)&&(await c(g.name)?be.success(`Command "${g.name}" deleted successfully`):be.error("Failed to delete command"))},h=g=>{const b=g.name;let x=1,w=`${b}-copy`;for(;a.some(S=>S.name===w);)x++,w=`${b}-copy-${x}`;i(w),n(!1),p&&u(!1)};return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(Is,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",p?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Commands"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.length}),e.jsx(oc,{asChild:!0,children:e.jsx(Ae,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(os,{className:"size-4"})})})]})]})}),e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:a.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ws,{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.jsx(e.Fragment,{children:[...a].sort((g,b)=>g.name.localeCompare(b.name)).map(g=>e.jsx(Zp,{command:g,isSelected:o===g.name,onSelect:()=>{i(g.name),p&&u(!1)},onDelete:()=>f(g),onDuplicate:()=>h(g)},g.name))})}),e.jsxs(Fs,{children:[e.jsxs(Ps,{children:[e.jsx(Rs,{children:"Create New Command"}),e.jsx(nr,{children:"Enter a unique name for your new slash command"})]}),e.jsx(Pt,{value:r,onChange:g=>s(g.target.value),placeholder:"Command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:g=>{g.key==="Enter"&&m()}}),e.jsxs(Hr,{children:[e.jsx(Ae,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(_n,{onClick:m,children:"Create"})]})]})]})})},Zp=({command:r,isSelected:s,onSelect:t,onDelete:n,onDuplicate:o})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:T("typography-ui-label font-medium truncate flex-1",s?"text-primary":"text-foreground hover:text-primary/80"),children:["/",r.name]})}),r.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.description})]}),e.jsxs(Xt,{children:[e.jsx(Jt,{asChild:!0,children:e.jsx(Ae,{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(Un,{className:"h-3.5 w-3.5"})})}),e.jsxs(Zt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(gt,{onClick:a=>{a.stopPropagation(),o()},children:[e.jsx(Ls,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(gt,{onClick:a=>{a.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})}),Qp=({agentName:r,onChange:s,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=jr(),a=o(),i=Pe(g=>g.isMobile),{isMobile:c}=Dt(),d=i||c,[u,p]=l.useState(!1);l.useEffect(()=>{n()},[n]);const m=()=>p(!1),f=g=>{s(g)},h=()=>d?e.jsx(Kt,{open:u,onClose:m,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(g=>{const b=g.name===r;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",b?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{f(g.name),m()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:g.name}),g.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:g.description})]}),b&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},g.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:()=>{f(""),m()},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:()=>p(!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(kn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:r||"Select agent..."})]}),e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Xt,{children:[e.jsx(Jt,{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(kn,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:r||"Not selected"}),e.jsx(vt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Zt,{className:"max-w-[300px]",children:[a.map(g=>e.jsx(gt,{className:"typography-meta",onSelect:()=>f(g.name),children:e.jsx("span",{className:"font-medium",children:g.name})},g.name)),e.jsx(gt,{className:"typography-meta",onSelect:()=>f(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},eh=()=>{const{selectedCommandName:r,getCommandByName:s,createCommand:t,updateCommand:n,commands:o}=Sr(),a=r?s(r):null,i=r&&!a,[c,d]=l.useState(""),[u,p]=l.useState(""),[m,f]=l.useState(""),[h,g]=l.useState(""),[b,x]=l.useState(""),[w,S]=l.useState(!1),[v,j]=l.useState(!1);l.useEffect(()=>{i?(d(r||""),p(""),f(""),g(""),x(""),S(!1)):a&&(d(a.name),p(a.description||""),f(a.agent||""),g(a.model||""),x(a.template||""),S(a.subtask||!1))},[a,i,r,o]);const k=async()=>{if(!c.trim()){be.error("Command name is required");return}if(!b.trim()){be.error("Command template is required");return}j(!0);try{const y=m.trim(),A=h.trim(),D=b.trim(),N={name:c.trim(),description:u.trim()||void 0,agent:y===""?null:y,model:A===""?null:A,template:D,subtask:w};let C;i?C=await t(N):C=await n(c,N),C?be.success(i?"Command created successfully":"Command updated successfully"):be.error(i?"Failed to create command":"Failed to update command")}catch(y){console.error("Error saving command:",y),be.error("An error occurred while saving")}finally{j(!1)}};return r?e.jsxs(Xe,{outerClassName:"h-full",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:i?"New Command":c})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name"}),e.jsx(Pt,{value:c,onChange:y=>d(y.target.value),placeholder:"my-command",disabled:!i}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Used with slash (/) prefix in chat"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(tr,{value:u,onChange:y=>p(y.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(Qp,{agentName:m,onChange:y=>f(y)}),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(mc,{providerId:h?h.split("/")[0]:"",modelId:h?h.split("/")[1]:"",onChange:(y,A)=>{g(y&&A?`${y}/${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:y=>S(y.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(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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(tr,{value:b,onChange:y=>x(y.target.value),placeholder:`Your command template here...
61
-
62
- Use $ARGUMENTS to reference user input.
63
- Use !\`shell command\` to inject shell output.
64
- 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(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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(Ae,{size:"sm",variant:"default",onClick:k,disabled:v,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Ko,{className:"h-3 w-3"}),v?"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(Ws,{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"})]})})},fc=({sectionId:r,variant:s})=>{const t=Up[r],n=t.icon;return s==="sidebar"?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[e.jsx("div",{className:"rounded-full bg-accent/40 p-3 text-muted-foreground",children:e.jsx(n,{className:"h-5 w-5"})}),e.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:t.label}),e.jsx("p",{className:"typography-meta max-w-xs text-muted-foreground",children:xi[r]})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-4 px-6 text-center",children:[e.jsx("div",{className:"rounded-full bg-accent/40 p-4 text-muted-foreground",children:e.jsx(n,{className:"h-8 w-8"})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:t.label}),e.jsx("p",{className:"typography-body max-w-md text-muted-foreground",children:xi[r]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60",children:"Coming soon..."})]})},th=()=>e.jsx(Xe,{outerClassName:"h-full",className:"px-3 py-2",children:e.jsx(fc,{sectionId:"providers",variant:"sidebar"})}),sh=()=>e.jsx(Xe,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:e.jsx(fc,{sectionId:"providers",variant:"page"})}),Kn=$t()(Wt(ys((r,s)=>({selectedProfileId:null,profiles:[],globalIdentity:null,isLoading:!1,setSelectedProfile:t=>{r({selectedProfileId:t})},loadProfiles:async()=>{r({isLoading:!0});const t=s().profiles;try{const n=await Jm();return r({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),r({profiles:t,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const t=await tf("");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"};r({globalIdentity:n})}else r({globalIdentity:null});return!0}catch(t){return console.error("Failed to load global git identity:",t),r({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 Zm(n),await s().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(t,n)=>{try{const o=s().profiles.find(i=>i.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Qm(t,a),await s().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async t=>{try{return await ef(t),s().selectedProfileId===t&&r({selectedProfileId:null}),await s().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:t=>{const{profiles:n,globalIdentity:o}=s();return t==="global"?o||void 0:n.find(a=>a.id===t)}}),{name:"git-identities-store",storage:bs(()=>ts()),partialize:r=>({selectedProfileId:r.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Kn);const rh={branch:Yt,briefcase:Jo,house:Xo,graduation:Yo,code:zs,heart:wl},nh={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},oh=()=>{const{selectedProfileId:r,profiles:s,globalIdentity:t,setSelectedProfile:n,deleteProfile:o,loadProfiles:a,loadGlobalIdentity:i}=Kn(),{setSidebarOpen:c}=Pe(),{isMobile:d}=Dt();l.useEffect(()=>{a(),i()},[a,i]);const u=()=>{n("new"),d&&c(!1)},p=async m=>{window.confirm(`Are you sure you want to delete profile "${m.name}"?`)&&(await o(m.id)?be.success(`Profile "${m.name}" deleted successfully`):be.error("Failed to delete profile"))};return e.jsxs("div",{className:"flex h-full flex-col bg-sidebar",children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",d?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Git Profiles"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:s.length}),e.jsx(Ae,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",onClick:u,children:e.jsx(os,{className:"size-4"})})]})]})}),e.jsxs(Xe,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[t&&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(bi,{profile:t,isSelected:r==="global",onSelect:()=>{n("global"),d&&c(!1)},onDelete:void 0,isReadOnly:!0})]}),s.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"}),s.length===0&&!t?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Yt,{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:s.map(m=>e.jsx(bi,{profile:m,isSelected:r===m.id,onSelect:()=>{n(m.id),d&&c(!1)},onDelete:()=>p(m)},m.id))})]})]})},bi=({profile:r,isSelected:s,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=rh[r.icon||"branch"]||Yt,i=nh[r.color||""];return e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",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("div",{className:T("typography-ui-label font-medium truncate flex-1",s?"text-primary":"text-foreground hover:text-primary/80"),children:r.name})]}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.userEmail})]}),!o&&n&&e.jsxs(Xt,{children:[e.jsx(Jt,{asChild:!0,children:e.jsx(Ae,{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(Un,{className:"h-3.5 w-3.5"})})}),e.jsx(Zt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(gt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})})},wi=[{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)"}],ah=[{key:"branch",Icon:Yt,label:"Branch"},{key:"briefcase",Icon:Jo,label:"Work"},{key:"house",Icon:Xo,label:"Personal"},{key:"graduation",Icon:Yo,label:"School"},{key:"code",Icon:zs,label:"Code"}],ih=()=>{const{selectedProfileId:r,getProfileById:s,createProfile:t,updateProfile:n,deleteProfile:o}=Kn(),a=l.useMemo(()=>r&&r!=="new"?s(r):null,[r,s]),i=r==="new",c=r==="global",[d,u]=l.useState(""),[p,m]=l.useState(""),[f,h]=l.useState(""),[g,b]=l.useState(""),[x,w]=l.useState("keyword"),[S,v]=l.useState("branch"),[j,k]=l.useState(!1);l.useEffect(()=>{i?(u(""),m(""),h(""),b(""),w("keyword"),v("branch")):a&&(u(a.name),m(a.userName),h(a.userEmail),b(a.sshKey||""),w(a.color||"keyword"),v(a.icon||"branch"))},[a,i,r]);const y=async()=>{if(!p.trim()||!f.trim()){be.error("User name and email are required");return}k(!0);try{const N={name:d.trim()||p.trim(),userName:p.trim(),userEmail:f.trim(),sshKey:g.trim()||null,color:x,icon:S};let C;if(i)C=await t(N);else if(r)C=await n(r,N);else return;C?be.success(i?"Profile created successfully":"Profile updated successfully"):be.error(i?"Failed to create profile":"Failed to update profile")}catch(N){console.error("Error saving profile:",N),be.error("An error occurred while saving")}finally{k(!1)}},A=async()=>{if(!(!r||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(r)?be.success("Profile deleted successfully"):be.error("Failed to delete profile")}catch(N){console.error("Error deleting profile:",N),be.error("An error occurred while deleting")}},D=l.useMemo(()=>wi.find(C=>C.key===x)?.cssVar||"var(--syntax-keyword)",[x]);return r?e.jsxs(Xe,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:i?"New Git Profile":c?"Global Identity":d||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:i?"Create a new Git identity profile for your repositories":c?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!c&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(Pt,{value:d,onChange:N=>u(N.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:wi.map(N=>e.jsx("button",{onClick:()=>w(N.key),className:T("w-8 h-8 rounded-lg border-2 transition-all",x===N.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:N.cssVar},title:N.label},N.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:ah.map(N=>{const C=N.Icon;return e.jsx("button",{onClick:()=>v(N.key),className:T("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",S===N.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:N.label,children:e.jsx(C,{className:"w-4 h-4",style:{color:D}})},N.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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(Pt,{value:p,onChange:N=>m(N.target.value),placeholder:"John Doe",required:!c,readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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(Pt,{type:"email",value:f,onChange:N=>h(N.target.value),placeholder:"john@example.com",required:!c,readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["SSH Key Path",e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ut,{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(Pt,{value:g,onChange:N=>b(N.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!c&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(Ae,{size:"sm",variant:"destructive",onClick:A,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Us,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:T("flex gap-2",i&&"ml-auto"),children:e.jsxs(Ae,{size:"sm",variant:"default",onClick:y,disabled:j,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Ko,{className:"h-3 w-3"}),j?"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(Vn,{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 co(r,s,t){return Math.min(t,Math.max(s,r))}const Ro=le.forwardRef(({value:r,onValueChange:s,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:c,onKeyDown:d,disabled:u,...p},m)=>{const f=le.useRef(null);le.useImperativeHandle(m,()=>f.current);const[h,g]=le.useState(()=>String(r));le.useEffect(()=>{document.activeElement!==f.current&&g(String(r))},[r]);const b=le.useCallback(()=>{f.current?.focus()},[]),x=le.useCallback(C=>{const M=co(C,t,n);s(M),g(String(M))},[n,t,s]),w=le.useCallback(()=>{const C=Number(h);return Number.isFinite(C)?C:r},[h,r]),S=le.useCallback(()=>{x(w()+o),b()},[x,w,b,o]),v=le.useCallback(()=>{x(w()-o),b()},[x,w,b,o]),j=C=>{const M=C.target.value;g(M);const E=Number(M);Number.isFinite(E)&&s(co(E,t,n))},k=C=>{const M=Number(h);if(!Number.isFinite(M))g(String(r));else{const E=co(M,t,n);E!==M&&s(E),g(String(E))}c?.(C)},y=C=>{if(C.key==="ArrowUp"){C.preventDefault(),S();return}if(C.key==="ArrowDown"){C.preventDefault(),v();return}d?.(C)},A=w(),D=u||A<=t,N=u||A>=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",{...p,ref:f,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:j,onBlur:k,onKeyDown:y,disabled:u,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:N,onClick:S,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(Vr,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:D,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(vt,{className:"h-3.5 w-3.5"})})]})]})});Ro.displayName="NumberInput";const lh=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],vi=[{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"}],ji=[{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."}],ch=()=>{const{isMobile:r}=Dt(),s=Pe(h=>h.showReasoningTraces),t=Pe(h=>h.setShowReasoningTraces),n=Pe(h=>h.toolCallExpansion),o=Pe(h=>h.setToolCallExpansion),a=Pe(h=>h.fontSize),i=Pe(h=>h.setFontSize),c=Pe(h=>h.padding),d=Pe(h=>h.setPadding),u=Pe(h=>h.diffLayoutPreference),p=Pe(h=>h.setDiffLayoutPreference),{themeMode:m,setThemeMode:f}=kr();return e.jsxs("div",{className:"w-full space-y-8",children:[!rs()&&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:lh.map(h=>e.jsx(Ss,{variant:m===h.value?"default":"outline",className:T(m===h.value?void 0:"text-foreground"),onClick:()=>f(h.value),children:h.label},h.value))})]}),!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:a,onChange:h=>i(Number(h.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(Ro,{value:a,onValueChange:i,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ss,{type:"button",variant:"ghost",onClick:()=>i(100),disabled:a===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(Ds,{className:"h-3.5 w-3.5"})})]})]}),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:c,onChange:h=>d(Number(h.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:c}),e.jsx(Ss,{type:"button",variant:"ghost",onClick:()=>d(100),disabled:c===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ds,{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:c,onChange:h=>d(Number(h.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(Ro,{value:c,onValueChange:d,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ss,{type:"button",variant:"ghost",onClick:()=>d(100),disabled:c===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ds,{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("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Tool Output"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:vi.find(h=>h.value===n)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:vi.map(h=>e.jsx(Ss,{variant:n===h.value?"default":"outline",className:T(n===h.value?void 0:"text-foreground"),onClick:()=>o(h.value),children:h.label},h.value))})]}),!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:ji.map(h=>e.jsx(Ss,{variant:u===h.id?"default":"outline",className:T(u===h.id?void 0:"text-foreground"),onClick:()=>p(h.id),children:h.label},h.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:ji.find(h=>h.id===u)?.description})]})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:s,onChange:h=>t(h.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]})]})},pc=()=>e.jsx(Xe,{outerClassName:"h-full",className:"settings-page-body mx-auto max-w-3xl space-y-3 p-3 sm:space-y-6 sm:p-6",children:e.jsx(ch,{})}),Si=(()=>{const r=ic.filter(n=>n.id!=="sessions"),s=r.find(n=>n.id==="settings"),t=r.filter(n=>n.id!=="settings");return s?[s,...t]:r})(),dh=({isOpen:r,onClose:s})=>{const[t,n]=l.useState("settings"),[o,a]=l.useState(!1),{isMobile:i}=Dt();l.useEffect(()=>{r&&(n("settings"),a(!1))},[r]);const c=l.useCallback(x=>{n(x),i&&a(!1)},[i]),d=l.useCallback(()=>{i&&a(!0)},[i]),u=()=>{if(t==="settings")return null;const x=(()=>{switch(t){case"agents":return e.jsx(Vp,{});case"commands":return e.jsx(Jp,{});case"providers":return e.jsx(th,{});case"git-identities":return e.jsx(oh,{});default:return null}})();return i?e.jsx("div",{onClick:d,children:x}):x},p=()=>{switch(t){case"agents":return e.jsx(Xp,{});case"commands":return e.jsx(eh,{});case"providers":return e.jsx(sh,{});case"git-identities":return e.jsx(ih,{});case"settings":return e.jsx(pc,{});default:return null}},m=Si.find(x=>x.id===t),f=i,h=e.jsxs(Ps,{className:"border-b border-border/40 px-6 pb-4 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)]",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[i&&o&&e.jsxs(Ae,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(Da,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx(Rs,{className:"typography-ui-header",children:"Settings"})]}),m&&e.jsx(nr,{className:"typography-meta text-muted-foreground hidden sm:block",children:m.description})]}),g=e.jsxs("div",{className:T("flex flex-col min-h-0",i?"h-full overflow-hidden":"flex-1 overflow-hidden"),children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1 border-b border-border/40 bg-background/95 px-3 py-1.5",children:Si.map(({id:x,label:w,icon:S})=>{const v=t===x,j=S;return e.jsxs("button",{onClick:()=>c(x),className:T("flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",v?"text-primary":"text-muted-foreground hover:text-foreground"),"aria-pressed":v,"aria-label":w,children:[e.jsx(j,{className:T("h-5 w-5 sm:h-4 sm:w-4"),weight:"regular"}),e.jsx("span",{className:"hidden sm:inline",children:w})]},x)})}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[t!=="settings"&&(!i||!o)&&e.jsx("div",{className:T("overflow-hidden border-r bg-sidebar",i&&"w-full border-r-0"),style:i?void 0:{width:`${Ln}px`,minWidth:`${Ln}px`},children:e.jsx(ls,{children:u()})}),(t==="settings"||!i||o)&&e.jsx("div",{className:T("flex-1 overflow-hidden bg-background",i&&"w-full"),children:e.jsx(ls,{children:p()})})]})]}),b=e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[!f&&h,g]});return f?e.jsx(Kt,{open:r,onClose:s,title:"Settings",className:"max-w-full",contentMaxHeightClassName:"h-[min(80dvh,720px)]",renderHeader:x=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsxs("div",{className:"relative flex flex-1 items-center justify-center",children:[o&&e.jsxs(Ae,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(Da,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx("span",{className:"typography-ui-header",children:"Settings"})]}),x]}),children:g}):e.jsx(Is,{open:r,onOpenChange:x=>!x&&s(),children:e.jsx(Fs,{className:T("flex flex-col gap-0 p-0","h-[88vh] w-[65vw] max-w-[900px]"),children:b})})};function hc({className:r,...s}){return e.jsx(sr,{"data-slot":"command",className:T("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",r),...s})}function uh({title:r="Command Palette",description:s="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(Is,{...a,children:[e.jsxs(Ps,{className:"sr-only",children:[e.jsx(Rs,{children:r}),e.jsx(nr,{children:s})]}),e.jsx(Fs,{className:T("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(hc,{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 gc({className:r,...s}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(Zo,{className:"size-4 shrink-0 opacity-50"}),e.jsx(sr.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",r),...s})]})}function xc({className:r,children:s,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(Xe,{as:sr.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",r),scrollbarClassName:t??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:s})}function yc({...r}){return e.jsx(sr.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...r})}function pr({className:r,...s}){return e.jsx(sr.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",r),...s})}function On({className:r,...s}){return e.jsx(sr.Separator,{"data-slot":"command-separator",className:T("bg-border -mx-1 h-px",r),...s})}function Ft({className:r,...s}){return e.jsx(sr.Item,{"data-slot":"command-item",className:T("hover:bg-accent hover:text-accent-foreground [&_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",r),...s})}function Ys({className:r,...s}){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(wr,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(Gr,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof s.children=="string"?s.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",r),...s,children:o.length>0?o.map((a,i)=>e.jsxs(le.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):s.children})}const mh=()=>{const{isCommandPaletteOpen:r,setCommandPaletteOpen:s,setHelpDialogOpen:t,setSessionCreateDialogOpen:n,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,toggleSidebar:c}=Pe(),{createSession:d,setCurrentSession:u,getSessionsByDirectory:p,initializeNewOpenChamberSession:m}=me(),{currentDirectory:f}=St(),{agents:h}=kt(),{themeMode:g,setThemeMode:b}=kr(),x=()=>{s(!1)},w=async()=>{const W=await d();W&&m(W.id,h),x()},S=W=>{u(W),x()},v=W=>{b(W),x()},j=()=>{t(!0),x()},k=()=>{n(!0),x()},{isMobile:y}=Dt(),A=()=>{if(y){const{isSessionSwitcherOpen:W}=Pe.getState();i(!W)}else c();x()},D=()=>{o("git"),x()},N=()=>{o("terminal"),x()},C=()=>{a(!0),x()},M=()=>{Fm(),x()},E=p(f??""),F=l.useMemo(()=>E.slice(0,5),[E]);return e.jsxs(uh,{open:r,onOpenChange:s,children:[e.jsx(gc,{placeholder:"Type a command or search..."}),e.jsxs(xc,{children:[e.jsx(yc,{children:"No results found."}),e.jsxs(pr,{heading:"Actions",children:[e.jsxs(Ft,{onSelect:A,children:[e.jsx(Hn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsx(Ys,{children:"Ctrl + L"})]}),e.jsxs(Ft,{onSelect:w,children:[e.jsx(os,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Ys,{children:"Ctrl + N"})]}),e.jsxs(Ft,{onSelect:k,children:[e.jsx(Yt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Ys,{children:"Shift + Ctrl + N"})]}),e.jsxs(Ft,{onSelect:j,children:[e.jsx(Or,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsx(Ys,{children:"Ctrl + H"})]}),e.jsxs(Ft,{onSelect:D,children:[e.jsx(Yt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsx(Ys,{children:"Ctrl + G"})]}),e.jsxs(Ft,{onSelect:N,children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsx(Ys,{children:"Ctrl + T"})]}),e.jsxs(Ft,{onSelect:C,children:[e.jsx(hr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsx(Ys,{children:"Ctrl + ,"})]}),e.jsxs(Ft,{onSelect:M,children:[e.jsx(Ds,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(On,{}),e.jsxs(pr,{heading:"Theme",children:[e.jsxs(Ft,{onSelect:()=>v("light"),children:[e.jsx(Ud,{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(Ft,{onSelect:()=>v("dark"),children:[e.jsx(Vd,{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(Ft,{onSelect:()=>v("system"),children:[e.jsx(vl,{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"})]})]}),F.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(On,{}),e.jsx(pr,{heading:"Recent Sessions",children:F.map(W=>e.jsxs(Ft,{onSelect:()=>S(W.id),children:[e.jsx(qo,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:W.title||"Untitled Session"})]},W.id))})]})]})]})},fh=(r,s)=>{const t=r.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Vr,{className:"h-3.5 w-3.5"},`ctrl-${s}`):t==="shift"||t==="⇧"?e.jsx(qd,{className:"h-3.5 w-3.5"},`shift-${s}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(wr,{className:"h-3.5 w-3.5"},`cmd-${s}`):e.jsx("span",{className:"text-xs font-medium",children:r.trim()},`key-${s}`)},ph=r=>{const s=r.split("+").map(t=>t.trim()).filter(Boolean);return s.length===0?r.trim():s.map((t,n)=>e.jsxs(l.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),fh(t,n)]},`${t}-${n}`))},hh=()=>{const{isHelpDialogOpen:r,setHelpDialogOpen:s}=Pe(),t=[{category:"Navigation & Commands",items:[{keys:["Ctrl + X"],description:"Open Command Palette",icon:wr},{keys:["Ctrl + H"],description:"Show Keyboard Shortcuts (this dialog)",icon:Or},{keys:["Ctrl + L"],description:"Toggle Session Sidebar",icon:Hn}]},{category:"Session Management",items:[{keys:["Ctrl + N"],description:"Create New Session",icon:os},{keys:["Shift + Ctrl + N"],description:"Open Session Creator (worktree support)",icon:Yt},{keys:["Ctrl + I"],description:"Focus Chat Input",icon:jl},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:gr}]},{category:"Interface",items:[{keys:["⌘ + /","Ctrl + /"],description:"Cycle Theme (Light → Dark → System)",icon:Gd},{keys:["Ctrl + G"],description:"Open Git Panel",icon:Yt},{keys:["Ctrl + T"],description:"Open Terminal",icon:Ws},{keys:["Ctrl + ,"],description:"Open Settings",icon:hr}]}];return e.jsx(Is,{open:r,onOpenChange:s,children:e.jsxs(Fs,{className:"max-w-2xl",children:[e.jsxs(Ps,{children:[e.jsxs(Rs,{className:"flex items-center gap-2",children:[e.jsx(hr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(nr,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsx("div",{className:"space-y-4 mt-3",children:t.map(n=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:n.category}),e.jsx("div",{className:"space-y-1",children:n.items.map((o,a)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[o.icon&&e.jsx(o.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:o.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(o.keys)?o.keys:o.keys.split(" / ")).map((i,c)=>e.jsxs(l.Fragment,{children:[c>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:ph(i)})]},`${i}-${c}`))})]},a))})]},n.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Or,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsx("li",{children:"• Use Command Palette (Ctrl + X) to quickly access all actions"}),e.jsx("li",{children:"• The 5 most recent sessions appear in the Command Palette"}),e.jsx("li",{children:"• Theme cycling remembers your preference across sessions"})]})]})]})})]})})},uo=new Set,mo=new Set,fo=new Set,cr={onDeleteRequest(r){return uo.add(r),()=>{uo.delete(r)}},requestDelete(r){r.sessions.length&&uo.forEach(s=>s(r))},onCreateRequest(r){return mo.add(r),()=>{mo.delete(r)}},requestCreate(r){const s=r??{};mo.forEach(t=>t(s))},onDirectoryRequest(r){return fo.add(r),()=>{fo.delete(r)}},requestDirectoryDialog(){fo.forEach(r=>r())}},gh=".openchamber",ki="oc.sessions.groupCollapse",Ni="oc.sessions.expandedParents",Ci=r=>{const s=new Date(r),t=new Date,n=(i,c)=>i.getFullYear()===c.getFullYear()&&i.getMonth()===c.getMonth()&&i.getDate()===c.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),n(s,t)?"Today":n(s,o)?"Yesterday":s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},js=r=>{if(!r)return null;const s=r.replace(/\\/g,"/").replace(/\/+$/,"");return s.length===0?"/":s},xh=(r,s)=>{const t=js(r),n=Array.from(s.values())[0];if(n?.projectDirectory)return js(n.projectDirectory);if(!t)return null;const o=`/${gh}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},Lo=({mobileVariant:r=!1,onSessionSelected:s,allowReselect:t=!1,hideDirectoryControls:n=!1})=>{const[o,a]=l.useState(null),[i,c]=l.useState(""),[d,u]=l.useState(null),p=l.useRef(null),[m,f]=l.useState(new Set),[h,g]=l.useState(()=>new Map),b=l.useRef(new Set),x=l.useMemo(()=>ts(),[]),[w,S]=l.useState(!1),[v,j]=l.useState(new Set),[k,y]=l.useState(null),[A,D]=l.useState(new Set),[N,C]=l.useState(null),M=St(R=>R.currentDirectory),E=St(R=>R.homeDirectory),F=St(R=>R.setDirectory),W=kt(R=>R.agents),L=me(R=>R.getSessionsByDirectory),K=me(R=>R.currentSessionId),X=me(R=>R.setCurrentSession),z=me(R=>R.updateSessionTitle),G=me(R=>R.shareSession),H=me(R=>R.unshareSession),oe=me(R=>R.sessionMemoryState),ve=me(R=>R.sessionActivityPhase),Ee=me(R=>R.worktreeMetadata),Ie=me(R=>R.availableWorktrees),ge=me(R=>R.createSession),de=me(R=>R.initializeNewOpenChamberSession),we=me(R=>R.setSessionDirectory),[De,_e]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const R=x.getItem(ki);if(R){const re=JSON.parse(R);Array.isArray(re)&&j(new Set(re.filter(ce=>typeof ce=="string")))}const Q=x.getItem(Ni);if(Q){const re=JSON.parse(Q);Array.isArray(re)&&f(new Set(re.filter(ce=>typeof ce=="string")))}}catch{}},[x]),l.useEffect(()=>{typeof window>"u"||_e(typeof window.opencodeDesktop<"u")},[]);const Ne=L(M),Fe=l.useMemo(()=>[...Ne].sort((R,Q)=>(Q.time?.created||0)-(R.time?.created||0)),[Ne]);l.useEffect(()=>{if(!M){y(null);return}let R=!1;return aa(M).then(Q=>{R||y(Q)}).catch(()=>{R||y(null)}),()=>{R=!0}},[M]);const $=l.useMemo(()=>new Map(Fe.map(R=>[R.id,R])),[Fe]),B=l.useMemo(()=>{const R=new Map;return Fe.forEach(Q=>{const re=Q.parentID;re&&R.set(Q.id,re)}),R},[Fe]),J=l.useMemo(()=>{const R=new Map;return Fe.forEach(Q=>{const re=Q.parentID;if(!re)return;const ce=R.get(re)??[];ce.push(Q),R.set(re,ce)}),R.forEach(Q=>Q.sort((re,ce)=>(ce.time?.created||0)-(re.time?.created||0))),R},[Fe]);l.useEffect(()=>{K&&f(R=>{const Q=new Set(R);let re=B.get(K)||null,ce=!1;for(;re;)Q.has(re)||(Q.add(re),ce=!0),re=B.get(re)||null;return ce?Q:R})},[K,B]);const I=l.useMemo(()=>xh(M,Ee),[M,Ee]);l.useEffect(()=>{const R=new Set;Fe.forEach(Q=>{const re=js(Q.directory??null);re&&R.add(re)}),I&&R.add(I),R.forEach(Q=>{const re=h.get(Q);re&&re!=="unknown"||b.current.has(Q)||(b.current.add(Q),Ce.listLocalDirectory(Q).then(()=>{g(ce=>{const Z=new Map(ce);return Z.get(Q)==="exists"?ce:(Z.set(Q,"exists"),Z)})}).catch(()=>{g(ce=>{const Z=new Map(ce);return Z.get(Q)==="missing"?ce:(Z.set(Q,"missing"),Z)})}).finally(()=>{b.current.delete(Q)}))})},[Fe,I,h]),l.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const _=l.useMemo(()=>Jn(M,E),[M,E]),U=l.useMemo(()=>Gt(M,E),[M,E]),xe=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."})]}),ye=l.useCallback((R,Q)=>{if(!Q){if(!t&&R===K){s?.(R);return}X(R),s?.(R)}},[t,K,s,X]),se=l.useCallback(async()=>{o&&i.trim()&&(await z(o,i.trim()),a(null),c(""))},[o,i,z]),O=l.useCallback(()=>{a(null),c("")},[]),V=l.useCallback(async R=>{const Q=await G(R.id);Q&&Q.share?.url?be.success("Session shared",{description:"You can copy the link from the menu."}):be.error("Unable to share session")},[G]),P=l.useCallback((R,Q)=>{navigator.clipboard.writeText(R).then(()=>{u(Q),p.current&&clearTimeout(p.current),p.current=window.setTimeout(()=>{u(null),p.current=null},2e3)}).catch(()=>{be.error("Failed to copy URL")})},[]),te=l.useCallback(async R=>{await H(R)?be.success("Session unshared"):be.error("Unable to unshare session")},[H]),je=l.useCallback(R=>{const Q=[],re=ce=>{(J.get(ce)??[]).forEach(ne=>{Q.push(ne),re(ne.id)})};return re(R),Q},[J]),ke=me(R=>R.deleteSession),$e=me(R=>R.deleteSessions),ct=l.useCallback(async R=>{const Q=je(R.id);if(Q.length===0)await ke(R.id)?be.success("Session deleted"):be.error("Failed to delete session");else{const re=[R.id,...Q.map(ne=>ne.id)],{deletedIds:ce,failedIds:Z}=await $e(re);ce.length>0&&be.success(`Deleted ${ce.length} session${ce.length===1?"":"s"}`),Z.length>0&&be.error(`Failed to delete ${Z.length} session${Z.length===1?"":"s"}`)}},[je,ke,$e]),ht=l.useCallback(async R=>{if(!R){be.error("No directory available for session creation");return}if(!w)try{S(!0);const Q=await ge(void 0,R);if(!Q){be.error("Failed to create session");return}de(Q.id,W),we(Q.id,R)}catch(Q){const re=Q instanceof Error?Q.message:"Failed to create session";be.error(re)}finally{S(!1)}},[ge,de,we,W,w]),mt=l.useCallback(()=>{cr.requestCreate({worktreeMode:"create"})},[]),dt=l.useCallback(()=>{De&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(R=>{R.success&&R.path?F(R.path,{showOverlay:!0}):R.error&&R.error!=="Directory selection cancelled"&&be.error("Failed to select directory",{description:R.error})}).catch(R=>{console.error("Desktop: Error selecting directory:",R),be.error("Failed to select directory")}):cr.requestDirectoryDialog()},[De,F]),Ge=l.useCallback(R=>{f(Q=>{const re=new Set(Q);re.has(R)?re.delete(R):re.add(R);try{x.setItem(Ni,JSON.stringify(Array.from(re)))}catch{}return re})},[x]),tt=l.useCallback(R=>{const Q=J.get(R.id)??[];return{session:R,children:Q.map(re=>tt(re))}},[J]),Ue=l.useMemo(()=>{const R=new Map,Q=js(I??null),re=new Map,ce=new Set;Ie.forEach(ae=>{if(ae.path){const Me=js(ae.path)??ae.path;ce.add(Me),re.set(Me,ae)}});const Z=ae=>{const Me=js(ae.directory??null),at=Ee.get(ae.id),xt=((at?.path?ce.has(js(at.path)??at.path):!1)?at:null)??(Me?re.get(Me)??null:null),Nt=!xt&&(Me&&Q?Me===Q:!Me&&!!Q),Ct=Nt?"main":xt?.path??Me??ae.id,yt=xt?.path??Me??Q??null;if(!R.has(Ct)){const jt=Nt?"Main workspace":xt?.label||xt?.branch||Jn(yt||"",E)||"Worktree",Se=xt?.relativePath?Gt(xt.relativePath,E):yt?Gt(yt,E):null;R.set(Ct,{id:Ct,label:jt,description:Se,isMain:Nt,worktree:xt,directory:yt,sessions:[]})}return R.get(Ct)};return Fe.filter(ae=>{const Me=ae.parentID;return Me?!$.has(Me):!0}).forEach(ae=>{const Me=Z(ae),at=tt(ae);Me.sessions.push(at)}),R.has("main")||R.set("main",{id:"main",label:"Main workspace",description:Q?Gt(Q,E):null,isMain:!0,worktree:null,directory:Q,sessions:[]}),re.forEach((ae,Me)=>{const at=ae.path;R.has(at)||R.set(at,{id:at,label:ae.label||ae.branch||Jn(Me,E)||"Worktree",description:ae.relativePath?Gt(ae.relativePath,E):Gt(Me,E),isMain:!1,worktree:ae,directory:Me,sessions:[]})}),R.forEach(ae=>{ae.sessions.sort((Me,at)=>(at.session.time?.created||0)-(Me.session.time?.created||0))}),Array.from(R.values()).sort((ae,Me)=>ae.isMain!==Me.isMain?ae.isMain?-1:1:(ae.label||"").localeCompare(Me.label||""))},[Fe,Ee,Ie,I,E,tt,$]),Ke=l.useCallback(R=>{j(Q=>{const re=new Set(Q);re.has(R)?re.delete(R):re.add(R);try{x.setItem(ki,JSON.stringify(Array.from(re)))}catch{}return re})},[x]),Je=l.useCallback(R=>{D(Q=>{const re=new Set(Q);return re.has(R)?re.delete(R):re.add(R),re})},[]),fe=l.useCallback((R,Q=0,re)=>{const ce=R.session,Z=js(ce.directory??null)??js(re??null),ae=(Z?h.get(Z):null)==="missing",Me=oe.get(ce.id),at=K===ce.id,zt=ce.title||"Untitled Session",xt=R.children.length>0,Nt=m.has(ce.id),Ct=ce.summary?.additions,yt=ce.summary?.deletions,jt=typeof Ct=="number"||typeof yt=="number";if(o===ce.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",Q>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",onSubmit:Le=>{Le.preventDefault(),se()},children:[e.jsx("input",{value:i,onChange:Le=>c(Le.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:Le=>{Le.key==="Escape"&&O()}}),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:O,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(ds,{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:[xt?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Nt?e.jsx(vt,{className:"h-3 w-3"}):e.jsx(us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Ci(ce.time?.created||Date.now())}),ce.share?e.jsx(Yn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,jt&&((Ct??0)!==0||(yt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Ct??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,yt??0)]})]}):null,xt?e.jsxs("span",{className:"truncate",children:[R.children.length," ",R.children.length===1?"task":"tasks"]}):null]})]})},ce.id);const Se=ve?.get(ce.id)??"idle",Be=Se==="busy"||Se==="cooldown",Ve=Me&&Me.isZombie?e.jsx(ko,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(l.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",ae?"opacity-75":"",Q>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:ae,onClick:()=>ye(ce.id,ae),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.jsx("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",Be&&"animate-pulse [animation-duration:1.8s]"),children:zt})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[xt?e.jsx("span",{role:"button",tabIndex:0,onClick:Le=>{Le.stopPropagation(),Ge(ce.id)},onKeyDown:Le=>{(Le.key==="Enter"||Le.key===" ")&&(Le.preventDefault(),Le.stopPropagation(),Ge(ce.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":Nt?"Collapse subsessions":"Expand subsessions",children:Nt?e.jsx(vt,{className:"h-3 w-3"}):e.jsx(us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Ci(ce.time?.created||Date.now())}),ce.share?e.jsx(Yn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,jt&&((Ct??0)!==0||(yt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Ct??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,yt??0)]})]}):null,xt?e.jsxs("span",{className:"truncate",children:[R.children.length," ",R.children.length===1?"task":"tasks"]}):null,ae?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(ko,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Ve,e.jsxs(Xt,{children:[e.jsx(Jt,{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 opacity-0 group-hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"),"aria-label":"Session menu",onClick:Le=>Le.stopPropagation(),onKeyDown:Le=>Le.stopPropagation(),children:e.jsx(Un,{className:r?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Zt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(gt,{onClick:()=>{a(ce.id),c(zt)},className:"[&>svg]:mr-1",children:[e.jsx(Cs,{className:"mr-1 h-4 w-4"}),"Rename"]}),ce.share?e.jsxs(e.Fragment,{children:[e.jsx(gt,{onClick:()=>{ce.share?.url&&P(ce.share.url,ce.id)},className:"[&>svg]:mr-1",children:d===ce.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(Ls,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(gt,{onClick:()=>te(ce.id),className:"[&>svg]:mr-1",children:[e.jsx(Kd,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(gt,{onClick:()=>V(ce),className:"[&>svg]:mr-1",children:[e.jsx(Yn,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(gt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>ct(ce),children:[e.jsx(Us,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),xt&&Nt?R.children.map(Le=>fe(Le,Q+1,Z??re)):null]},ce.id)},[h,oe,ve,K,m,o,i,se,O,Ge,ye,V,P,te,ct,d,r]);return e.jsxs("div",{className:T("flex h-full flex-col text-foreground overflow-x-hidden",r?"":De?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-14 select-none px-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center gap-0",children:[e.jsxs("button",{type:"button",onClick:dt,className:T("group flex min-w-0 flex-1 items-center gap-2 rounded-md px-0 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!De&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:U||"/",children:[e.jsx("span",{className:T("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!De&&"bg-sidebar/60"),children:e.jsx(is,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}),e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("p",{className:"truncate whitespace-nowrap typography-ui font-semibold text-muted-foreground group-hover:text-foreground",children:_||"/"})})]}),k?e.jsx("button",{type:"button",onClick:mt,className:T("inline-flex h-10 w-7 flex-shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!De&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",children:e.jsx(Yd,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}):null]})}),e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:T("space-y-1 pb-1 pl-2.5 pr-1",""),children:Ue.length===0?xe:n&&Ue.length===1&&Ue[0].isMain?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:Ue[0].sessions.length===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."}):Ue[0].sessions.map(R=>fe(R,0,Ue[0].directory))}):Ue.map(R=>e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>Ke(R.id),className:T("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b",!De&&"bg-sidebar"),style:{borderColor:N===R.id?"var(--color-border)":v.has(R.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>C(R.id),onMouseLeave:()=>C(null),"aria-label":v.has(R.id)?"Expand group":"Collapse group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1",children:[e.jsx("span",{className:"typography-micro font-medium text-muted-foreground truncate group-hover/header:text-foreground",children:R.label}),!n&&e.jsx("span",{role:"button",tabIndex:0,"aria-disabled":w,className:T("inline-flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",w&&"opacity-40 cursor-default"),"aria-label":"Create session in this group",onClick:Q=>{w||(Q.stopPropagation(),ht(R.directory))},onKeyDown:Q=>{w||(Q.key==="Enter"||Q.key===" ")&&(Q.stopPropagation(),ht(R.directory))},children:e.jsx(os,{className:"h-4.5 w-4.5"})})]})}),v.has(R.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const Q=A.has(R.id),re=7,ce=R.sessions.length,Z=Q?R.sessions:R.sessions.slice(0,re),ne=ce-Z.length;return e.jsxs(e.Fragment,{children:[Z.map(ae=>fe(ae,0,R.directory)),ce===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,ne>0&&!Q?e.jsxs("button",{type:"button",onClick:()=>Je(R.id),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",ne," more ",ne===1?"session":"sessions"]}):null,Q&&ce>re?e.jsx("button",{type:"button",onClick:()=>Je(R.id),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})})()})]},R.id))})]})},yh=hl("inline-flex items-center justify-center gap-2 rounded-xl typography-ui-label font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-none hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}});function bh({className:r,variant:s,size:t,...n}){return e.jsx(Xd,{"data-slot":"toggle",className:T(yh({variant:s,size:t,className:r})),...n})}const bc=()=>{const[r,s]=le.useState(!1);le.useEffect(()=>{s(es())},[]);const t=le.useCallback(async a=>r?await pm(a):{success:!0,path:a},[r]),n=le.useCallback(async a=>r?await hm(a):{success:!0},[r]),o=le.useCallback(async a=>r?await gm(a):{success:!0},[r]);return{isDesktop:r,requestAccess:t,startAccessing:n,stopAccessing:o}},wh=({currentPath:r,onSelectPath:s,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:u})=>{const p=l.useMemo(()=>es(),[]),[m,f]=l.useState([]),[h,g]=l.useState(new Set),[b,x]=l.useState(!0),[w,S]=l.useState(!1),[v,j]=l.useState(""),[k,y]=l.useState(new Set),[A,D]=l.useState(null),[N,C]=l.useState(""),M=l.useRef(null),{requestAccess:E,startAccessing:F,isDesktop:W}=bc(),L=l.useRef(c),K=l.useCallback(I=>{if(!I)return I;if(I==="/"||I.length===0)return"/";let _=I;for(;_.length>1&&_.endsWith("/");)_=_.slice(0,-1);return _.length===0?"/":_},[]),X=l.useMemo(()=>{if(!v)return null;const I=v.replace(/\\/g,"/");return K(I)},[v,K]),z=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const I=d.replace(/\\/g,"/"),_=K(I);if(_&&_!=="/")return _}return X&&X!=="/"?X:null},[d,X,K]),G=l.useMemo(()=>typeof u=="boolean"?!!(u&&z):!!z,[u,z]);l.useEffect(()=>{G||(x(!0),f([]))},[G]);const H=l.useCallback(I=>{if(!I||!G||!z)return!1;const _=I.replace(/\\/g,"/"),U=K(_)??_;if(U===z)return!0;const xe=`${z}/`;return U.startsWith(xe)},[G,z,K]),oe=async I=>{if(G){if(a==="deferred"){s(I);return}if(W){const _=await E(I);_.success&&_.path?(await F(_.path),s(_.path)):(console.error("Failed to get directory access:",_.error),s(I))}else s(I)}};l.useEffect(()=>{let I=!1;const _=ye=>{if(!ye)return!1;const se=K(ye.replace(/\\/g,"/"));return!se||se==="/"?!1:(j(typeof se=="string"?se:ye.replace(/\\/g,"/")),!0)};return(d?_(d):!1)||(async()=>{try{const ye=await Ce.getFilesystemHome();if(!I&&_(ye))return}catch(ye){console.warn("Failed to resolve filesystem home directory:",ye)}try{const ye=await Ce.getSystemInfo();if(!I&&_(ye?.homeDirectory))return}catch(ye){console.warn("Failed to resolve home directory from system info:",ye)}})(),()=>{I=!0}},[d,K]),l.useEffect(()=>{let I=!1;const _=se=>{if(I)return;const O=se.filter(V=>typeof V=="string"&&V.length>0).map(V=>{const P=V.replace(/\\/g,"/");return K(P)??P});y(new Set(O))},U=()=>{try{const se=localStorage.getItem("pinnedDirectories");if(!se)return;const O=JSON.parse(se);Array.isArray(O)&&_(O)}catch(se){console.warn("Failed to load pinned directories from local storage:",se)}},xe=async()=>{try{let se=[];if(p){const O=await Al();se=Array.isArray(O?.pinnedDirectories)?O.pinnedDirectories:[]}else{const O=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(O.ok){const V=await O.json();se=Array.isArray(V?.pinnedDirectories)?V.pinnedDirectories:[]}}if(I)return;_(se)}catch(se){console.warn("Failed to load pinned directories:",se)}};U();const ye=se=>{const O=se.detail;O&&Array.isArray(O.pinnedDirectories)&&_(O.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",ye),xe(),()=>{I=!0,window.removeEventListener("openchamber:settings-synced",ye)}},[p,K]);const ve=l.useRef(!0);l.useEffect(()=>{if(ve.current){ve.current=!1;return}const I={pinnedDirectories:Array.from(k)};Ns(I)},[k]),l.useEffect(()=>{z&&y(I=>{const _=Array.from(I).map(U=>K(U.replace(/\\/g,"/"))??U).filter(U=>H(U));return new Set(_)})},[z,H,K]),l.useEffect(()=>{L.current!==c&&(L.current=c,g(new Set))},[c]);const Ee=I=>{y(_=>{if(!H(I))return _;const U=K(I.replace(/\\/g,"/"))??I.replace(/\\/g,"/"),xe=new Set(_);return xe.has(U)?xe.delete(U):xe.add(U),xe})},Ie=l.useMemo(()=>Array.from(k).map(I=>K(I.replace(/\\/g,"/"))??I).filter(I=>H(I)).map(I=>({path:I,name:I.split("/").pop()||I})).sort((I,_)=>I.name.localeCompare(_.name)),[k,H,K]),ge=l.useCallback(async I=>{const _=O=>c||!O.startsWith("."),U=z;if(!G||!U)return[];const xe=I&&I.length>0?I:U,ye=xe?xe.replace(/\\/g,"/"):null,se=ye?K(ye)??ye:null;if(se){const O=`${U}/`;if(!(se===U||se.startsWith(O)))return[]}try{return(await Ce.listLocalDirectory(I)).filter(V=>{if(!V.isDirectory||!_(V.name))return!1;const P=V.path.replace(/\\/g,"/"),te=K(P)??P,je=te===U?U:`${U}/`;return te===U||te.startsWith(je)}).map(V=>({name:V.name,path:V.path.replace(/\\/g,"/"),isDirectory:!0})).sort((V,P)=>V.name.localeCompare(P.name))}catch{try{const V=await Ce.getApiClient().file.list({query:{path:".",directory:I}});return V.data?V.data.filter(P=>{if(P.type!=="directory"||!P.name||!_(P.name))return!1;const te=String(P.absolute||P.path||P.name).replace(/\\/g,"/"),je=K(te)??te,ke=je===U?U:`${U}/`;return je===U||je.startsWith(ke)}).map(P=>({name:P.name||"",path:String(P.absolute||P.path||P.name).replace(/\\/g,"/"),isDirectory:!0})).filter(P=>P.name!=="").sort((P,te)=>P.name.localeCompare(te.name)):[]}catch{return[]}}},[c,z,K,G]),de=l.useCallback(async()=>{if(!G||!z){x(!0),f([]);return}x(!0);try{const I=await ge(z);f(I)}catch{}finally{x(!1)}},[G,z,ge]);l.useEffect(()=>{G&&(n==="inline"||w)&&de()},[n,w,G,de]);const we=async I=>{if(!G)return;const _=h.has(I.path),U=new Set(h);if(_){U.delete(I.path),g(U);return}U.add(I.path),g(U);const xe=await ge(I.path),ye=se=>se.map(O=>O.path===I.path?{...O,children:xe}:O.children?{...O,children:ye(O.children)}:O);f(se=>ye(se))};l.useEffect(()=>{A&&M.current&&(M.current.focus(),M.current.select())},[A]);const De=(I,_=[])=>{const U="new_directory",xe=_.map(V=>V.name);if(!xe.includes(U))return U;let ye=1;const se=new RegExp(`^${U}(\\d+)$`);for(const V of xe){const P=V.match(se);if(P){const te=parseInt(P[1],10);te>ye&&(ye=te)}}let O=2;for(;xe.includes(`${U}${O}`);)O++;return`${U}${Math.max(O,ye+1)}`},_e=async I=>{if(G){if(h.has(I.path)){const _=De(I.path,I.children);C(_)}else{const _=new Set(h);if(_.add(I.path),g(_),I.children){const U=De(I.path,I.children);C(U)}else{const U=await ge(I.path),xe=se=>se.map(O=>O.path===I.path?{...O,children:U}:O.children?{...O,children:xe(O.children)}:O);f(se=>xe(se));const ye=De(I.path,U);C(ye)}}D(I.path)}},Ne=async()=>{if(!A||!G)return;const I=N.trim()||"new_directory",_=`${A}/${I}`;try{await Ce.createDirectory(_);const U=await ge(A),xe=ye=>ye.map(se=>se.path===A?{...se,children:U}:se.children?{...se,children:xe(se.children)}:se);f(ye=>xe(ye)),D(null),C("")}catch(U){console.error("Failed to create directory:",U)}},Fe=()=>{D(null),C("")},$=(I,_=0)=>{const U=h.has(I.path),xe=I.isDirectory,ye=k.has(I.path),se=r===I.path,O=n==="inline",V=e.jsxs(e.Fragment,{children:[xe&&e.jsx("button",{onClick:P=>{P.stopPropagation(),we(I)},className:"p-0.5 hover:bg-accent rounded",children:U?e.jsx(vt,{className:"h-3 w-3"}):e.jsx(us,{className:"h-3 w-3"})}),!xe&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:P=>{P.stopPropagation(),oe(I.path),n==="dropdown"&&a==="immediate"&&S(!1)},onDoubleClick:P=>{P.stopPropagation(),i&&i(I.path)},className:T("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",O&&se?"text-primary":"text-foreground"),children:[U?e.jsx(is,{className:T("h-3.5 w-3.5 text-muted-foreground",O&&se&&"text-primary")}):e.jsx(is,{className:T("h-3.5 w-3.5 text-muted-foreground",O&&se&&"text-primary")}),e.jsx("span",{className:T("typography-ui-label font-medium truncate",O&&se?"text-primary":"text-foreground"),children:I.name})]}),e.jsx("button",{onClick:P=>{P.stopPropagation(),_e(I)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Create new directory",children:e.jsx(os,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:P=>{P.stopPropagation(),Ee(I.path)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:ye?"Unpin directory":"Pin directory",children:ye?e.jsx(Xn,{className:"h-3 w-3 text-primary"}):e.jsx(Jd,{className:"h-3 w-3 text-muted-foreground"})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:T("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",se?"text-primary":"text-foreground"),style:{paddingLeft:`${_*12+8}px`},children:V}),U&&e.jsxs(e.Fragment,{children:[A===I.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(_+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Pt,{ref:M,value:N,onChange:P=>C(P.target.value),onKeyDown:P=>{P.key==="Enter"?(P.preventDefault(),P.stopPropagation(),Ne()):P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),Fe())},onBlur:Ne,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),Ne()},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:P=>{P.preventDefault(),P.stopPropagation(),Fe()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"})})]}),I.children&&I.children.map(P=>$(P,_+1))]})]},I.path):e.jsxs("div",{children:[e.jsxs(gt,{className:T("flex items-center gap-1 cursor-pointer group",r===I.path&&"bg-accent"),style:{paddingLeft:`${_*12+8}px`},onSelect:P=>{P.preventDefault()},children:[xe&&e.jsx("button",{onClick:P=>{P.stopPropagation(),we(I)},className:"p-0.5 hover:bg-accent rounded",children:U?e.jsx(vt,{className:"h-3 w-3"}):e.jsx(us,{className:"h-3 w-3"})}),!xe&&e.jsx("div",{className:"w-4"}),V]}),U&&e.jsxs("div",{children:[A===I.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(_+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Pt,{ref:M,value:N,onChange:P=>C(P.target.value),onKeyDown:P=>{P.key==="Enter"?(P.preventDefault(),P.stopPropagation(),Ne()):P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),Fe())},onBlur:Ne,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),Ne()},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:P=>{P.preventDefault(),P.stopPropagation(),Fe()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"})})]}),I.children&&I.children.map(P=>$(P,_+1))]})]},I.path)},B=(I,_)=>{if(n==="inline"){const U=r===_;return e.jsxs("div",{className:T("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>oe(_),onDoubleClick:xe=>{xe.stopPropagation(),i&&i(_)},className:T("flex flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",U?"text-primary":"text-foreground"),children:[e.jsx(is,{className:T("h-3.5 w-3.5 text-muted-foreground",U&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",U?"text-primary":"text-foreground"),children:I}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:Gt(_,v)})]})]}),e.jsx("button",{onClick:()=>Ee(_),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Xn,{className:"h-3 w-3 text-primary"})})]},_)}return e.jsxs(gt,{onSelect:U=>{U.preventDefault(),oe(_),a==="immediate"&&S(!1)},className:T("flex items-start gap-2 cursor-pointer group py-2",r===_&&"bg-accent"),children:[e.jsx(is,{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:I}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Gt(_,v)})]}),e.jsx("button",{onClick:U=>{U.stopPropagation(),U.preventDefault(),Ee(_)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Xn,{className:"h-3 w-3 text-primary"})})]},_)},J=e.jsx(e.Fragment,{children:G?e.jsxs(e.Fragment,{children:[Ie.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground",children:"Pinned"}),Ie.map(({name:I,path:_})=>B(I,_)),n==="dropdown"&&e.jsx(zr,{})]}),e.jsx("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground",children:"Browse"}),b?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):m.map(I=>$(I)),!b&&m.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 rounded-xl border border-border/40 bg-sidebar/70",o),children:e.jsx(Xe,{outerClassName:"max-h-full",className:"w-full",children:J})}):e.jsxs(Xt,{open:w,onOpenChange:S,children:[e.jsx(Jt,{asChild:!0,children:e.jsxs(Ae,{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(is,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:r,children:Gt(r,v)})]}),e.jsx(vt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Zt,{align:"start",className:"w-[350px]",children:e.jsx(Xe,{outerClassName:"h-full",className:"w-full",children:J})})]})},Mi="directoryTreeShowHidden",vh=({open:r,onOpenChange:s})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=St(),[i,c]=l.useState(null),[d,u]=l.useState(!1),[p,m]=l.useState(!1),[f,h]=l.useState(()=>{if(typeof window>"u")return!1;try{const M=window.localStorage.getItem(Mi);if(M==="true")return!0;if(M==="false")return!1}catch{}return!1}),{isDesktop:g,requestAccess:b,startAccessing:x}=bc(),{isMobile:w}=Dt();l.useEffect(()=>{r&&(c(null),u(!1),m(!1))},[r]),l.useEffect(()=>{r&&!d&&!i&&n&&a&&(c(n),u(!0))},[r,d,i,n,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Mi,f?"true":"false")}catch{}},[f]);const S=l.useMemo(()=>i?Gt(i,n):"Select a directory",[i,n]),v=l.useCallback(()=>{s(!1)},[s]),j=l.useCallback(async M=>{if(!(!M||p)){if(M===t){v();return}m(!0);try{let E=M;if(g){const F=await b(M);if(!F.success){be.error("Unable to access directory",{description:F.error||"Desktop denied directory access."});return}E=F.path??M;const W=await x(E);if(!W.success){be.error("Failed to open directory",{description:W.error||"Desktop could not grant file access."});return}}o(E),v()}catch(E){be.error("Failed to select directory",{description:E instanceof Error?E.message:"Unknown error occurred."})}finally{m(!1)}}},[t,v,g,b,o,x,p]),k=l.useCallback(async()=>{i&&await j(i)},[j,i]),y=l.useCallback(M=>{c(M),u(!0)},[]),A=l.useCallback(async M=>{c(M),u(!0),await j(M)},[j]),D=e.jsxs(Ps,{className:"flex-shrink-0 px-4 pb-3 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-4 sm:pt-[calc(var(--oc-safe-area-top,0px)+0px)]",children:[e.jsx(Rs,{children:"Select project directory"}),e.jsx(nr,{className:"hidden sm:block",children:"Choose the working directory used for sessions, commands, and OpenCode operations."})]}),N=e.jsxs(Xe,{outerClassName:"flex-1 min-h-0 overflow-hidden",className:"directory-dialog-body px-2.5 pb-2.5 sm:px-0 sm:pb-0",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 px-3 py-2 sm:px-4 sm:py-3",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Currently selected"}),e.jsx("div",{className:"typography-ui-label font-medium text-foreground truncate",title:Gt(t,n),children:Gt(t,n)})]}),e.jsxs("div",{className:"directory-grid mt-2 grid gap-2 grid-cols-1 sm:mt-4 sm:gap-4 sm:grid-cols-[minmax(260px,340px)_minmax(0,1fr)]",children:[e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/70 p-1.5 sm:p-2 sm:h-auto",children:e.jsx(wh,{variant:"inline",currentPath:i??t,onSelectPath:y,onDoubleClickPath:A,className:"min-h-[280px] h-[55vh] sm:h-[440px]",selectionBehavior:"deferred",showHidden:f,rootDirectory:a?n:null,isRootReady:a})}),e.jsxs("div",{className:"flex flex-col gap-2.5 sm:gap-3",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 px-3 py-2 sm:px-4 sm:py-3",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Selected directory"}),e.jsx("div",{className:"typography-ui-label font-medium text-foreground truncate",title:i?S:void 0,children:S})]}),e.jsxs(bh,{pressed:f,onPressedChange:M=>h(!!M),variant:"outline",className:"w-full justify-start gap-2 rounded-xl border-border/40 bg-sidebar/60 px-3 py-2 text-foreground min-w-0 h-auto sm:px-4 sm:py-3",children:[f?e.jsx(Qo,{className:"h-4 w-4"}):e.jsx(ea,{className:"h-4 w-4"}),"Show hidden directories"]}),e.jsx("div",{className:"hidden rounded-xl border border-dashed border-border/40 bg-sidebar/40 px-3 py-2 sm:block sm:px-4 sm:py-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Use the tree to browse, pin frequently used locations, or create a new directory. Select a folder, then confirm to update the working directory for OpenChamber."})})]})]})]}),C=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ae,{variant:"ghost",onClick:v,disabled:p,className:"w-full sm:w-auto",children:"Cancel"}),e.jsx(Ae,{onClick:k,disabled:p||!d||!i,className:"w-full sm:w-auto",children:p?"Applying...":"Use Selected Directory"})]});return w?e.jsx(Kt,{open:r,onClose:()=>s(!1),title:"Select project directory",className:"max-w-full",footer:e.jsx("div",{className:"flex flex-col gap-2",children:C()}),children:N}):e.jsx(Is,{open:r,onOpenChange:s,children:e.jsxs(Fs,{className:T("flex w-full max-w-[min(640px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-4xl sm:p-6"),children:[D,N,e.jsx(Hr,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-col gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:flex-row sm:justify-end sm:gap-2 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0",children:C()})]})})},Bn=".openchamber",nn=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,jh=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),wc=r=>r.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),vc=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},on=(r,s)=>{const t=vc(r),n=wc(s),o=!t||t==="/"?`/${Bn}`:`${t}/${Bn}`;return n?`${o}/${n}`:o},Sh=()=>{const[r,s]=l.useState(!1),[t,n]=l.useState(!1),[o,a]=l.useState(""),[i,c]=l.useState([]),[d,u]=l.useState(!1),[p,m]=l.useState(null),[f,h]=l.useState(!1),[g,b]=l.useState(null),[x,w]=l.useState(!1),S=l.useRef(new Set),[v,j]=l.useState(null),[k,y]=l.useState([]),[A,D]=l.useState(!1),[N,C]=l.useState(!1),{sessions:M,createSession:E,deleteSession:F,deleteSessions:W,loadSessions:L,initializeNewOpenChamberSession:K,setWorktreeMetadata:X,setSessionDirectory:z,getWorktreeMetadata:G,isLoading:H}=me(),{currentDirectory:oe,homeDirectory:ve,hasPersistedDirectory:Ee,isHomeReady:Ie}=St(),{agents:ge}=kt(),{isSessionCreateDialogOpen:de,setSessionCreateDialogOpen:we}=Pe(),{isMobile:De,isTablet:_e,hasTouchInput:Ne}=Dt(),Fe=De||_e||Ne,$=l.useMemo(()=>vc(oe),[oe]),B=l.useMemo(()=>jh(o),[o]),J=l.useMemo(()=>wc(B),[B]),I=l.useMemo(()=>!$||!J?"":on($,J),[$,J]),_=g===!0,U=l.useMemo(()=>(v?.worktree?.status?.isDirty??!1)||k.some(fe=>fe.metadata.status?.isDirty),[v?.worktree?.status?.isDirty,k]),xe=l.useMemo(()=>{const fe=v?.worktree;return fe&&typeof fe.branch=="string"&&fe.branch.trim().length>0?!0:k.length>0&&k.every(({metadata:R})=>typeof R.branch=="string"&&R.branch.trim().length>0)},[v?.worktree,k]),ye=v?.mode==="worktree",se=ye,O=N||!ye||!xe;l.useEffect(()=>{$&&(S.current.has($)||Ym($).then(()=>S.current.add($)).catch(fe=>{console.warn("Failed to ensure .openchamber directory is ignored:",fe),S.current.delete($)}))},[$]),l.useEffect(()=>{L()},[L,oe]),l.useEffect(()=>{!t&&Ie&&!Ee&&(s(!0),n(!0))},[Ee,t,Ie]),l.useEffect(()=>{if(!de){a(""),c([]),m(null),u(!1),h(!1),b(null),w(!1);return}if(!$){c([]),b(null),h(!1);return}let fe=!1;return u(!0),h(!0),m(null),(async()=>{try{const R=await aa($);if(fe)return;if(b(R),!R)c([]),m(null);else{const Q=await Tn($);if(fe)return;const re=Q.map(ae=>In($,ae)),Z=`${on($,"")}/`,ne=re.filter(ae=>ae.path.startsWith(Z));c(ne)}}catch(R){if(fe)return;const Q=R instanceof Error?R.message:"Failed to load worktrees";m(Q)}finally{fe||(u(!1),h(!1))}})(),()=>{fe=!0}},[de,$]);const V=l.useCallback(fe=>{j({sessions:fe.sessions,dateLabel:fe.dateLabel,mode:fe.mode??"session",worktree:fe.worktree??null})},[]),P=l.useCallback(()=>{j(null),y([]),D(!1),C(!1)},[]);l.useEffect(()=>cr.onDeleteRequest(fe=>{V(fe)}),[V]),l.useEffect(()=>cr.onDirectoryRequest(()=>{s(!0)}),[]),l.useEffect(()=>cr.onCreateRequest(()=>{a(""),we(!0)}),[we]),l.useEffect(()=>{if(!v){y([]),D(!1);return}const fe=v.sessions.map(Q=>{const re=G(Q.id);return re?{session:Q,metadata:re}:null}).filter(Q=>!!Q);if(y(fe),D(!1),fe.length===0)return;let R=!1;return(async()=>{const Q=await Promise.all(fe.map(async({metadata:re})=>{if(re.status&&typeof re.status.isDirty=="boolean")return re.status;try{return await gn(re.path)}catch{return re.status}})).catch(re=>(console.warn("Failed to inspect worktree status before deletion:",re),fe.map(({metadata:ce})=>ce.status)));R||!Array.isArray(Q)||y(re=>re.map((ce,Z)=>({session:ce.session,metadata:{...ce.metadata,status:Q[Z]??ce.metadata.status}})))})(),()=>{R=!0}},[v,G]),l.useEffect(()=>{xe||D(!1)},[xe]);const te=l.useCallback(fe=>{a(fe),m(null)},[]),je=l.useCallback(async()=>{if(!(!$||!g))try{const R=(await Tn($)).map(Z=>In($,Z)),re=`${on($,"")}/`,ce=R.filter(Z=>Z.path.startsWith(re));c(ce)}catch{}},[$,g]),ke=l.useRef(null);l.useEffect(()=>{ke.current?.mode==="worktree"&&!v&&je(),ke.current=v},[v,je]);const $e=l.useCallback(()=>{if(!$){const re="Select a project directory first.";return m(re),be.error(re),!1}const fe=B,R=J;if(!fe){const re="Provide a branch name for the new worktree.";return m(re),be.error(re),!1}if(!R){const re="Provide a branch name that can be used as a folder.";return m(re),be.error(re),!1}const Q=on($,R);if(i.some(re=>re.path===Q)){const re="A worktree with this folder already exists.";return m(re),be.error(re),!1}return m(null),!0},[$,B,J,i]),ct=async()=>{if(x||H||!$e())return;w(!0),m(null);let fe=null;try{const R=B,re=await of({projectDirectory:$,worktreeSlug:J,branch:R,createBranch:!0});fe=re;let ce=await gn(re.path).catch(()=>{});try{await Xm(re.path,{remote:"origin",branch:R,options:["--set-upstream"]}),ce=await gn(re.path).catch(()=>ce),be.success(`Configured upstream for ${R}`)}catch(ae){const Me=ae instanceof Error?ae.message:"Unable to push new worktree branch.";be.warning("Worktree created locally",{description:nn(`Upstream setup failed: ${Me}`)})}const Z=ce?{...re,status:ce}:re,ne=await E(void 0,re.path);if(!ne){await Ba({projectDirectory:$,path:re.path,force:!0}).catch(()=>{});const ae="Failed to create session for worktree";m(ae),be.error(ae);return}K(ne.id,ge),z(ne.id,re.path),X(ne.id,Z),await je(),a(""),be.success("Worktree created")}catch(R){fe&&await Ba({projectDirectory:$,path:fe.path,force:!0}).catch(()=>{});const Q=R instanceof Error?R.message:"Failed to create worktree";m(Q),be.error(Q)}finally{w(!1)}},ht=l.useCallback(fe=>{const R=M.filter(Q=>G(Q.id)?.path===fe.path);cr.requestDelete({sessions:R,mode:"worktree",worktree:fe})},[M,G]),mt=l.useCallback(async()=>{if(v){C(!0);try{const fe=se,R=fe&&A;if(v.sessions.length===1){const Q=v.sessions[0];if(!await F(Q.id,{archiveWorktree:fe,deleteRemoteBranch:R})){be.error("Failed to delete session"),C(!1);return}const ce=fe?R?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;be.success("Session deleted",{description:nn(ce)})}else{const Q=v.sessions.map(Z=>Z.id),{deletedIds:re,failedIds:ce}=await W(Q,{archiveWorktree:fe,deleteRemoteBranch:R});if(re.length>0){const Z=fe?R?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,ae=[ce.length>0?`${ce.length} session${ce.length===1?"":"s"} could not be deleted.`:v.dateLabel?`Removed all sessions from ${v.dateLabel}.`:void 0,Z].filter(Boolean).join(" ");be.success(`Deleted ${re.length} session${re.length===1?"":"s"}`,{description:nn(ae||void 0)})}if(ce.length>0&&(be.error(`Failed to delete ${ce.length} session${ce.length===1?"":"s"}`,{description:nn("Please try again in a moment.")}),re.length===0)){C(!1);return}}P()}finally{C(!1)}}},[v,A,F,W,P,se]),dt=e.jsxs("div",{className:"space-y-4 w-full min-w-0",children:[e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Create worktree"}),e.jsxs("p",{className:"typography-meta text-muted-foreground/80",children:["Branch-specific directory under ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:Bn}),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-branch-input",children:"Branch name"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Pt,{id:"worktree-branch-input",value:o,onChange:fe=>te(fe.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!_||f,onKeyDown:fe=>{fe.key==="Enter"&&!x&&ct()}}),e.jsx(Ae,{onClick:ct,disabled:x||H||!_||!B,className:"h-8",children:x?"Creating…":"Create"})]}),B&&e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Creates branch"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:B})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:Gt(I,ve)})]})]}),p&&e.jsx("p",{className:"typography-meta text-destructive",children:p}),!_&&!f&&e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Current directory is not a Git repository."})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3 overflow-hidden min-w-0",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Existing worktrees"})}),d?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading worktrees…"}):i.length===0?e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["No worktrees found under ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:Bn}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:i.map(fe=>{const R=fe.relativePath||(fe.path.startsWith($+"/")?fe.path.slice($.length+1):fe.path);return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/30 bg-sidebar-accent/20 px-3 py-2 min-w-0",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-meta font-medium text-foreground",children:fe.label||fe.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:R})]}),e.jsx("button",{type:"button",onClick:()=>ht(fe),className:"flex-shrink-0 flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete worktree ${fe.branch||fe.label}`,children:e.jsx(Us,{className:"h-4 w-4"})})]},fe.path)})})]})]}),Ge=e.jsx(Ae,{variant:"ghost",onClick:()=>we(!1),disabled:x,children:"Close"}),tt=v?.worktree??k[0]?.metadata??null,Ue=v?v.mode==="worktree"?`This removes the selected worktree and ${v.sessions.length===1?"1 linked session":`${v.sessions.length} linked sessions`}.`:`This action permanently removes ${v.sessions.length===1?"1 session":`${v.sessions.length} sessions`}${v.dateLabel?` from ${v.dateLabel}`:""}.`:"",Ke=v?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsxs("ul",{className:"space-y-0.5",children:[v.sessions.slice(0,3).map(fe=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:fe.title||"Untitled Session"},fe.id)),v.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",v.sessions.length-3," more"]})]})}),ye?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"}),tt?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:tt.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:tt?Gt(tt.path,ve):"Worktree path unavailable."}),U&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),xe?e.jsxs("button",{type:"button",onClick:()=>{O||D(fe=>!fe)},disabled:O,className:T("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",O?"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:A?e.jsx(Qo,{className:"size-4 text-primary"}):e.jsx(ea,{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:A?"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,Je=e.jsxs(e.Fragment,{children:[e.jsx(Ae,{variant:"ghost",onClick:P,disabled:N,children:"Cancel"}),e.jsx(Ae,{variant:"destructive",onClick:mt,disabled:N,children:N?"Deleting…":ye?"Delete worktree":v?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[Fe?e.jsx(Kt,{open:de,onClose:()=>we(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Ge}),children:e.jsx("div",{className:"space-y-2 pb-2",children:dt})}):e.jsx(Is,{open:de,onOpenChange:we,children:e.jsxs(Fs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2 overflow-hidden",children:[e.jsx(Ps,{children:e.jsx(Rs,{children:"Worktree Manager"})}),dt,e.jsx(Hr,{className:"mt-2 gap-2 pt-1 pb-1",children:Ge})]})}),Fe?e.jsx(Kt,{open:!!v,onClose:()=>{N||P()},title:v?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Je}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[Ue&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:Ue}),Ke]})}):e.jsx(Is,{open:!!v,onOpenChange:fe=>{if(!fe){if(N)return;P()}},children:e.jsxs(Fs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(Ps,{children:[e.jsx(Rs,{children:v?.sessions.length===1?"Delete session":"Delete sessions"}),Ue&&e.jsx(nr,{children:Ue})]}),Ke,e.jsx(Hr,{className:"mt-2 gap-2 pt-1 pb-1",children:Je})]})}),e.jsx(vh,{open:r,onOpenChange:s})]})};function kh(){return new Worker(Zd,{type:"module"})}const Nh=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Ch(r,s,t){const n=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${r}:${s.length}:${t.length}:${n.length}:${o.length}`}function Ai(r){if(typeof window>"u")return()=>{};const s=window.setTimeout(()=>r(void 0),0);return()=>window.clearTimeout(s)}const Mh=({children:r})=>{const s=eu(),t=Mt(c=>c.activeDirectory),n=Mt(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=Mt(c=>t?c.directories.get(t)?.diffCache.size??0:0),a=le.useRef(!1),i=le.useRef(new Map);return le.useEffect(()=>{if(!s||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=So(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(u,d)},[s]),le.useEffect(()=>{if(!s||!t||!n||o===0)return;const c=Mt.getState().directories.get(t);if(!c||c.diffCache.size===0||(i.current.get(t)??0)>=c.lastStatusChange)return;i.current.set(t,c.lastStatusChange);let u=!1,p=null;const m=Array.from(c.diffCache.entries());let f=0;const h=g=>{if(u)return;const b=Date.now();for(;f<m.length&&!(g&&g.timeRemaining()<8||!g&&Date.now()-b>8);){const[x,w]=m[f];f+=1,qr(x);const S=Ch(x,w.original,w.modified),v={name:x,contents:w.original,cacheKey:`old-${S}`},j={name:x,contents:w.modified,cacheKey:`new-${S}`},k=So(v,j),y={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(y,k)}f<m.length&&(p=Ai(h))};return h(void 0),f<m.length&&(p=Ai(h)),()=>{u=!0,p?.()}},[s,t,n,o]),e.jsx(e.Fragment,{children:r})},Ah=({children:r})=>{const t=pa()?.currentTheme?.metadata?.variant==="dark";tc();const n=le.useMemo(()=>({theme:{dark:yr.dark,light:yr.light},themeType:t?"dark":"light",langs:Nh}),[t]);return e.jsx(Qd,{poolOptions:{workerFactory:kh,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Mh,{children:r})})},Dh=(r={})=>{const{edgeThreshold:s=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=r,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=Pe(),d=le.useRef(null),u=le.useRef(null);return le.useEffect(()=>{if(!o||!a)return;const p=g=>{const b=g.touches[0];if(!b){d.current=null;return}b.clientX<=s?d.current={x:b.clientX,y:b.clientY,time:Date.now()}:d.current=null},m=g=>{if(!d.current)return;const b=g.touches[0];if(!b)return;b.clientX-d.current.x>10&&g.preventDefault()},f=g=>{if(!d.current)return;const b=g.changedTouches[0];if(!b){d.current=null,u.current=null;return}u.current={x:b.clientX,y:b.clientY,time:Date.now()};const{x,y:w,time:S}=d.current,{x:v,y:j,time:k}=u.current,y=v-x,A=j-w,D=k-S,N=Math.abs(A)<Math.abs(y),C=D<=n,M=Math.abs(A)<t;y>=t&&N&&C&&M&&!c&&i(!0),d.current=null,u.current=null},h=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",p,{passive:!0,capture:!0}),document.addEventListener("touchmove",m,{passive:!1,capture:!0}),document.addEventListener("touchend",f,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",p,{capture:!0}),document.removeEventListener("touchmove",m,{capture:!0}),document.removeEventListener("touchend",f,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,s,t,n,i,c]),null},Ir=r=>r==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:r==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;le.memo(()=>{const r=le.useRef(null),{addAttachedFile:s}=me(),{isMobile:t}=Pe(),n=ma(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",i=async u=>{let p=0;for(let m=0;m<u.length;m++){const f=u[m],h=me.getState().attachedFiles.length;try{await s(f),me.getState().attachedFiles.length>h&&p++}catch(g){console.error("File attach failed",g),be.error(g instanceof Error?g.message:"Failed to attach file")}}p>0&&be.success(`Attached ${p} file${p>1?"s":""}`)},c=async u=>{const p=u.target.files;p&&(await i(p),r.current&&(r.current.value=""))},d=async()=>{try{const p=await(await fetch("/api/vscode/pick-files")).json(),m=Array.isArray(p?.files)?p.files:[],f=Array.isArray(p?.skipped)?p.skipped:[];if(f.length>0){const g=f.map(b=>`${b?.name||"file"}: ${b?.reason||"skipped"}`).join(`
65
- `);be.error(`Some files were skipped:
66
- ${g}`)}const h=m.map(g=>{if(!g?.dataUrl)return null;try{const[b,x]=g.dataUrl.split(","),w=g.mimeType||b?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!x)return null;const S=atob(x),v=new Uint8Array(S.length);for(let k=0;k<S.length;k++)v[k]=S.charCodeAt(k);const j=new Blob([v],{type:w});return new File([j],g.name||"file",{type:w})}catch(b){return console.error("Failed to decode VS Code picked file",b),null}}).filter(Boolean);h.length>0&&await i(h)}catch(u){console.error("VS Code file pick failed",u),be.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:r,type:"file",multiple:!0,className:"hidden",onChange:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():r.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(Co,{className:T(a,"text-current")})})]})});const Eh=le.memo(({file:r,onRemove:s})=>{const t=()=>r.mimeType.startsWith("image/")?e.jsx(xr,{className:"h-3.5 w-3.5"}):r.mimeType.includes("text")||r.mimeType.includes("code")?e.jsx(Qs,{className:"h-3.5 w-3.5"}):r.mimeType.includes("json")||r.mimeType.includes("xml")?e.jsx(Gn,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{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})(r.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:r.source==="server"?"Server file":"Local file",children:r.source==="server"?e.jsx(tu,{className:"h-3 w-3 text-primary"}):e.jsx(vl,{className:"h-3 w-3 text-muted-foreground"})}),t(),e.jsx("span",{title:r.serverPath||a,children:a}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",n(r.size),")"]}),e.jsx("button",{onClick:s,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(ds,{className:"h-3 w-3"})})]})}),Th=le.memo(()=>{const{attachedFiles:r,removeAttachedFile:s}=me();return r.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:"}),r.map(t=>e.jsx(Eh,{file:t,onRemove:()=>s(t.id)},t.id))]})})}),jc=le.memo(({files:r,onShowPopup:s})=>{const t=r.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const p=d.replace(/\\/g,"/").split("/");return p[p.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(xr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(Qs,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Gn,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),c=l.useCallback(d=>{if(!s||!d?.url)return;const u=n(d.filename)||"Image",p={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}};s(p)},[s]);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 p=n(d.filename)||"Image";return e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>c(d),className:"relative flex-none w-32 sm:w-36 md:w-40 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":p,children:[d.url?e.jsx("img",{src:d.url,alt:p,className:"h-full w-full object-cover",loading:"lazy",onError:m=>{const f=m.target;f.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(xr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:p})]})}),e.jsx(ut,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:p})]},`img-${u}`)})})})]})}),Sc=(r,s=200)=>{const[t,n]=le.useState(r);return le.useEffect(()=>{const o=window.setTimeout(()=>{n(r)},s);return()=>{window.clearTimeout(o)}},[r,s]),t},Ih=l.forwardRef(({searchQuery:r,onFileSelect:s,onClose:t},n)=>{const{currentDirectory:o}=St(),{addServerFile:a}=me(),i=ia(k=>k.searchFiles),c=Sc(r,180),[d,u]=l.useState([]),[p,m]=l.useState(!1),[f,h]=l.useState(0),[g,b]=l.useState(null),x=l.useRef([]),w=l.useRef(null),S=l.useCallback((k,y)=>{const A=k.trim().toLowerCase();if(!A)return 0;const D=y.toLowerCase();let N=0,C=-1,M=0;for(let E=0;E<A.length;E+=1){const F=A[E];if(!F||F===" ")continue;const W=D.indexOf(F,C+1);if(W===-1)return null;const L=W-C-1;if(L===0?M+=1:M=0,N+=10,N+=Math.max(0,18-W),N-=Math.max(0,L),W===0)N+=12;else{const K=D[W-1];(K==="/"||K==="_"||K==="-"||K==="."||K===" ")&&(N+=10)}N+=M>0?12:0,C=W}return N+=Math.max(0,24-Math.round(D.length/3)),N},[]);l.useEffect(()=>{const k=y=>{const A=y.target;!A||!w.current||w.current.contains(A)||t()};return document.addEventListener("pointerdown",k,!0),()=>{document.removeEventListener("pointerdown",k,!0)}},[t]),l.useEffect(()=>{if(!o){u([]);return}const y=(c??"").trim().toLowerCase();let A=!1;return m(!0),i(o,y,80).then(D=>{if(A)return;const N=y?D.map(C=>{const M=C.relativePath||C.name||C.path,E=S(y,M);return E===null?null:{file:C,score:E,labelLength:M.length}}).filter(Boolean):D.map(C=>({file:C,score:0,labelLength:(C.relativePath||C.name||C.path).length}));N.sort((C,M)=>M.score-C.score||C.labelLength-M.labelLength||C.file.path.localeCompare(M.file.path)),u(N.slice(0,15).map(C=>C.file))}).catch(()=>{A||u([])}).finally(()=>{A||m(!1)}),()=>{A=!0}},[o,c,S,i]),l.useEffect(()=>{h(0),b(null)},[d]),l.useEffect(()=>{x.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]);const v=l.useCallback(async k=>{await a(k.path,k.name),s(k)},[a,s]);l.useImperativeHandle(n,()=>({handleKeyDown:k=>{if(k==="Escape"){t();return}const y=d.length;if(y!==0){if(k==="ArrowDown"){h(A=>(A+1)%y);return}if(k==="ArrowUp"){h(A=>(A-1+y)%y);return}if(k==="Enter"||k==="Tab"){const A=(f%y+y)%y,D=d[A];D&&v(D)}}}}),[d,f,t,v]);const j=k=>{switch(k.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(zs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(zs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(xr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Gn,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:w,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:"px-0",children:p?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(qn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((k,y)=>{const A=k.relativePath||k.name,D=Nl(A,{maxLength:45}),N=f===y,M=N||g===y,E=e.jsxs("div",{ref:F=>{x.current[y]=F},className:T("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",N&&"bg-accent"),onClick:()=>v(k),onMouseEnter:()=>h(y),children:[j(k),e.jsx("span",{className:"flex-1 truncate max-w-[360px]","aria-label":A,children:D})]});return e.jsxs(ft,{open:M,delayDuration:M?0:120,onOpenChange:F=>{b(W=>!F&&W===y?null:F?y:W)},children:[e.jsx(pt,{asChild:!0,children:E}),e.jsx(ut,{side:"right",align:"center",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:A})})]},k.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"})]})}),kc=l.forwardRef(({searchQuery:r,onCommandSelect:s,onClose:t},n)=>{const{hasMessagesInCurrentSession:o}=me(ta(g=>{const b=g.currentSessionId;return{hasMessagesInCurrentSession:(b?g.messages.get(b)?.length??0:0)>0}})),[a,i]=l.useState([]),[c,d]=l.useState(!1),[u,p]=l.useState(0),m=l.useRef([]),f=l.useRef(null);l.useEffect(()=>{const g=b=>{const x=b.target;!x||!f.current||f.current.contains(x)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),l.useEffect(()=>{(async()=>{d(!0);try{const x=(await Ce.listCommands()).map(y=>({name:y.name,description:y.description,agent:y.agent,model:y.model,isBuiltIn:!1})),w=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],S=new Map;w.forEach(y=>S.set(y.name,y)),x.forEach(y=>S.set(y.name,y));const v=Array.from(S.values()),j=!o,k=(r?v.filter(y=>y.name.toLowerCase().includes(r.toLowerCase())||y.description&&y.description.toLowerCase().includes(r.toLowerCase())):v).filter(y=>j||y.name!=="init");k.sort((y,A)=>{const D=y.name.toLowerCase().startsWith(r.toLowerCase()),N=A.name.toLowerCase().startsWith(r.toLowerCase());return D&&!N?-1:!D&&N?1:y.name.localeCompare(A.name)}),i(k)}catch{const b=!o,x=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],w=(r?x.filter(S=>S.name.toLowerCase().includes(r.toLowerCase())||S.description&&S.description.toLowerCase().includes(r.toLowerCase())):x).filter(S=>b||S.name!=="init");i(w)}finally{d(!1)}})()},[r,o]),l.useEffect(()=>{p(0)},[a]),l.useEffect(()=>{m.current[u]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[u]),l.useImperativeHandle(n,()=>({handleKeyDown:g=>{const b=a.length;if(g==="Escape"){t();return}if(b!==0){if(g==="ArrowDown"){p(x=>(x+1)%b);return}if(g==="ArrowUp"){p(x=>(x-1+b)%b);return}if(g==="Enter"||g==="Tab"){const x=(u%b+b)%b,w=a[x];w&&s(w)}}}}),[a,u,t,s]);const h=g=>{switch(g.name){case"init":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-green-500"});case"summarize":return e.jsx(ru,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Ws,{className:"h-3.5 w-3.5 text-cyan-500"});default:return g.isBuiltIn?e.jsx(su,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(wr,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:f,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(qn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[a.map((g,b)=>e.jsxs("div",{ref:x=>{m.current[b]=x},className:T("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",b===u&&"bg-accent"),onClick:()=>s(g),onMouseEnter:()=>p(b),children:[e.jsx("div",{className:"mt-0.5",children:h(g)}),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:["/",g.name]}),g.agent&&e.jsx("span",{className:"typography-meta text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:g.agent})]}),g.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:g.description})]})]},g.name)),a.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});kc.displayName="CommandAutocomplete";const Fh=r=>r?r!=="primary":!1,Nc=l.forwardRef(({searchQuery:r,onAgentSelect:s,onClose:t},n)=>{const o=l.useRef(null),[a,i]=l.useState(0),[c,d]=l.useState([]),{getVisibleAgents:u}=kt();l.useEffect(()=>{const f=u().filter(b=>Fh(b.mode)).map(b=>({name:b.name,description:b.description,mode:b.mode??void 0})),h=r.trim().toLowerCase(),g=h.length?f.filter(b=>b.name.toLowerCase().includes(h)):f;g.sort((b,x)=>b.name.localeCompare(x.name)),d(g),i(0)},[u,r]),l.useEffect(()=>{const m=f=>{const h=f.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",m,!0),()=>{document.removeEventListener("pointerdown",m,!0)}},[t]),l.useImperativeHandle(n,()=>({handleKeyDown:m=>{if(m==="Escape"){t();return}if(c.length){if(m==="ArrowDown"){i(f=>(f+1)%c.length);return}if(m==="ArrowUp"){i(f=>(f-1+c.length)%c.length);return}if(m==="Enter"||m==="Tab"){const f=c[(a+c.length)%c.length];f&&s(f.name)}}}}),[c,s,t,a]);const p=(m,f)=>e.jsx("div",{className:T("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",f===a&&"bg-accent"),onClick:()=>s(m.name),onMouseEnter:()=>i(f),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["#",m.name]})}),m.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:m.description})]})},m.name);return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c.length?e.jsx("div",{children:c.map((m,f)=>p(m,f))}):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"})]})});Nc.displayName="AgentMentionAutocomplete";function Ph({className:r,children:s,...t}){return e.jsxs(nu,{"data-slot":"scroll-area",className:T("relative",r),...t,children:[e.jsx(ou,{"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:s}),e.jsx(Rh,{}),e.jsx(au,{})]})}function Rh({className:r,orientation:s="vertical",...t}){return e.jsx(iu,{"data-slot":"scroll-area-scrollbar",orientation:s,className:T("flex touch-none p-px select-none",s==="vertical"&&"h-full w-2.5 border-l border-l-transparent",s==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",r),...t,children:e.jsx(lu,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Lh=({onFilesSelected:r,multiSelect:s=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Dt(),c=ma(),d=i||c,{currentDirectory:u}=St(),p=ia(O=>O.searchFiles),[m,f]=l.useState(!1),[h,g]=l.useState(!1),[b,x]=l.useState(""),w=Sc(b,200),[S,v]=l.useState(new Set),[j,k]=l.useState(new Set),[y,A]=l.useState({}),D=l.useRef(new Set),N=l.useRef(new Set),[C,M]=l.useState([]),[E,F]=l.useState(!1),[W,L]=l.useState(!1),[K,X]=l.useState(!1),[z,G]=l.useState(null),H=n??m,oe=o??f,ve=l.useCallback(O=>O.slice().sort((V,P)=>V.type!==P.type?V.type==="directory"?-1:1:V.name.localeCompare(P.name)),[]),Ee=l.useCallback((O,V)=>ve(V.filter(P=>!P.name.startsWith(".")).map(P=>{const te=P.name,je=!P.isDirectory&&te.includes(".")?te.split(".").pop()?.toLowerCase():void 0;return{name:te,path:P.path||`${O}/${te}`,type:P.isDirectory?"directory":"file",size:0,extension:je}})),[ve]),Ie=l.useCallback(async O=>{L(!0),G(null);try{const V=await Ce.listLocalDirectory(O),P=Ee(O,V.map(te=>({name:te.name,path:te.path,isDirectory:te.isDirectory})));D.current=new Set([O]),N.current=new Set,A({[O]:P}),k(new Set)}catch{G("Failed to load directory contents"),D.current=new Set([O]),N.current=new Set,A({[O]:[]}),k(new Set)}finally{L(!1)}},[Ee]),ge=l.useCallback(async O=>{const V=O.trim();if(V&&!D.current.has(V)&&!N.current.has(V)){N.current=new Set(N.current),N.current.add(V);try{const P=await Ce.listLocalDirectory(V),te=Ee(V,P.map(je=>({name:je.name,path:je.path,isDirectory:je.isDirectory})));D.current=new Set(D.current),D.current.add(V),A(je=>({...je,[V]:te}))}catch{A(P=>P[V]?P:{...P,[V]:[]})}finally{N.current=new Set(N.current),N.current.delete(V)}}},[Ee]);l.useEffect(()=>{(H||h)&&u&&Ie(u)},[H,h,u,Ie]),l.useEffect(()=>{if(!(H||h)||!u){M([]),F(!1);return}const O=w.trim();if(!O){M([]),F(!1);return}let V=!1;return F(!0),p(u,O,150).then(P=>{if(V)return;const te=P.map(je=>({name:je.name,path:je.path,type:"file",extension:je.extension,relativePath:je.relativePath,size:0}));M(te)}).catch(()=>{V||M([])}).finally(()=>{V||F(!1)}),()=>{V=!0}},[H,h,u,w,p]),l.useEffect(()=>{!H&&!h&&(v(new Set),x(""),M([]),F(!1))},[H,h]);const de=O=>{if(O.type==="directory")return j.has(O.path)?e.jsx(is,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(is,{className:"h-3.5 w-3.5 text-primary/60"});switch(O.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(zs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(zs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Mo,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(xr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Mo,{className:"h-3.5 w-3.5 text-muted-foreground"})}},we=async O=>{j.has(O)?k(P=>{const te=new Set(P);return te.delete(O),te}):(k(P=>{const te=new Set(P);return te.add(O),te}),await ge(O))},De=O=>{v(s?V=>{const P=new Set(V);return P.has(O)?P.delete(O):P.add(O),P}:new Set([O]))},_e=async()=>{const O=new Map;Object.values(y).forEach(te=>{te.forEach(je=>{je.type==="file"&&O.set(je.path,je)})});const V=new Map(C.map(te=>[te.path,te])),P=Array.from(S).map(te=>O.get(te)??V.get(te)).filter(te=>!!te);X(!0);try{await r(P),v(new Set),oe(!1),g(!1)}finally{X(!1)}},Ne=l.useMemo(()=>u?y[u]??[]:[],[y,u]),Fe=b.trim().length>0,$=O=>y[O]??[],B=O=>{if(u&&O.startsWith(u)){const V=O.substring(u.length);return V.startsWith("/")?V.substring(1):V}return O.split("/").pop()||O},J=(O,V)=>{const P=Fe?O.relativePath||B(O.path):O.name,te=Fe&&P.includes("/")&&P.length>45,je=te?Nl(P,{maxLength:d?42:48}):P,ke=e.jsxs("div",{className:T("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-accent cursor-pointer typography-ui-label text-foreground text-left",O.type==="file"&&S.has(O.path)&&"bg-primary/10"),style:{paddingLeft:`${V*12}px`},onClick:$e=>{$e.preventDefault(),$e.stopPropagation(),O.type==="file"&&De(O.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:de(O)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":P,children:je})]}),O.type==="file"&&S.has(O.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return te?e.jsxs(ft,{delayDuration:120,children:[e.jsx(pt,{asChild:!0,children:ke}),e.jsx(ut,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:P})})]},O.path):l.cloneElement(ke,{key:O.path})},I=(O,V)=>{const P=O.type==="directory",te=P?$(O.path):[],je=j.has(O.path),ke=P&&je&&N.current.has(O.path)&&te.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",!P&&S.has(O.path)&&"bg-primary/10"),style:{paddingLeft:`${V*12}px`},onClick:$e=>{$e.preventDefault(),$e.stopPropagation(),P?we(O.path):De(O.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:de(O)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:O.name}),!P&&S.has(O.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),P&&je&&te.length>0&&e.jsx("div",{children:te.map($e=>I($e,V+1))}),P&&je&&ke&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(V+1)*12}px`},children:"Loading…"})]},O.path)},_=S.size>0?`${S.size} file${S.size!==1?"s":""} selected`:"No files selected",U=e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 shrink-0",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:_}),e.jsx(Ae,{size:"sm",onClick:_e,disabled:S.size===0||K,className:"h-6 typography-meta",children:K?"Attaching...":"Attach Files"})]}),xe=d?"flex-1 min-h-[240px]":"h-[300px]",ye=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(Zo,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Pt,{value:b,onChange:O=>x(O.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:O=>O.stopPropagation()}),b&&e.jsx("button",{onClick:O=>{O.stopPropagation(),x("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-accent rounded",children:e.jsx(ds,{className:"h-3 w-3"})})]})}),e.jsxs(Ph,{className:xe,children:[W&&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..."})}),z&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:z})}),!W&&!z&&e.jsxs("div",{className:"py-1 px-2",children:[Fe?E?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):C.map(O=>J(O,0)):Ne.map(O=>I(O,0)),!Fe&&Ne.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),Fe&&!E&&C.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),se=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:O=>{O.preventDefault(),O.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:O=>{O.preventDefault(),O.stopPropagation(),oe(!0)},children:t}):null,e.jsx(Kt,{open:H,onClose:()=>oe(!1),title:"Select Project Files",footer:U,children:e.jsx("div",{className:"flex flex-col gap-0",children:ye})})]}):d?e.jsxs(e.Fragment,{children:[se,e.jsx(Kt,{open:h,onClose:()=>g(!1),title:"Select Project Files",footer:U,children:e.jsx("div",{className:"flex flex-col gap-0",children:ye})})]}):e.jsxs(Xt,{open:H,onOpenChange:oe,children:[e.jsx(Jt,{asChild:!0,children:t}),e.jsxs(Zt,{className:T("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[ye,e.jsx(zr,{}),U]})]})},an=[{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 _s(r){if(!r||r==="build")return an[0];let s=0;for(let n=0;n<r.length;n++){const o=r.charCodeAt(n);s=(s<<5)-s+o,s=s&s}const t=1+Math.abs(s)%(an.length-1);return an[t]}const _h=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Cc=r=>_h(r),Oh=r=>r?typeof r=="string"?r==="ask":Cc(r)?Object.values(r).some(s=>s==="ask"):!1:!1,Bh=r=>r?typeof r=="string"?r==="deny":Cc(r)?Object.values(r).some(s=>s==="deny"):!1:!1,Mc=({agentDefaultEditMode:r,webfetchPermission:s,bashPermission:t})=>{const n=Oh(t),o=Bh(t),a=!n&&!o,i=s==="allow",c=s!=="deny",d=r==="allow"||r==="full",u=r==="ask";let p=r;d&&i&&a?p="full":d&&n?p="allow":u&&(p="ask");const m={ask:u,allow:u||d&&n,full:r!=="deny"&&c&&n,deny:!1},f=m.allow||m.full;return{cascadeDefaultMode:p,modeAvailability:m,autoApproveAvailable:f,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:c}},ln=r=>r==="primary"||r==="all"||r===void 0||r===null,$h=[{key:"tool_call",icon:sa,label:"Tool calling",isActive:r=>r?.tool_call===!0},{key:"reasoning",icon:Wn,label:"Reasoning",isActive:r=>r?.reasoning===!0}],zh={text:{icon:jl,label:"Text"},image:{icon:xr,label:"Image"},video:{icon:du,label:"Video"},audio:{icon:cu,label:"Audio"},pdf:{icon:Gn,label:"PDF"}},Hh=r=>r.trim().toLowerCase(),ws=(r,s)=>{const t=s==="input"?r?.modalities?.input:r?.modalities?.output;return!Array.isArray(t)||t.length===0?[]:Array.from(new Set(t.map(o=>Hh(o)))).map(o=>{const a=zh[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Wh=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Uh=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Lt=r=>{if(typeof r!="number"||Number.isNaN(r))return"—";if(r===0)return"0";const s=Wh.format(r);return s.endsWith(".0")?s.slice(0,-2):s},cn=r=>typeof r!="number"||!Number.isFinite(r)?"—":Uh.format(r),Er=r=>$h.filter(s=>s.isActive(r)).map(s=>({key:s.key,icon:s.icon,label:s.label})),Di=r=>{if(!r)return"—";const s=r.match(/^(\d{4})-(\d{2})$/);if(s){const t=Number.parseInt(s[1],10),n=Number.parseInt(s[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 r},Ei=r=>{if(!r)return"—";const s=new Date(r);return Number.isNaN(s.getTime())?r:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(s)},Ti=({className:r})=>{const{providers:s,currentProviderId:t,currentModelId:n,currentAgentName:o,setProvider:a,setModel:i,setAgent:c,getCurrentProvider:d,getModelMetadata:u,getCurrentAgent:p,getVisibleAgents:m}=kt(),f=m(),{currentSessionId:h,messages:g,saveSessionAgentSelection:b,getSessionAgentSelection:x,saveAgentModelForSession:w,getAgentModelForSession:S,analyzeAndSaveExternalSessionChoices:v,getSessionAgentEditMode:j,setSessionAgentEditMode:k}=me(),y=bt(q=>q.hasHydrated),{toggleFavoriteModel:A,isFavoriteModel:D,addRecentModel:N}=Pe(),{favoriteModelsList:C,recentModelsList:M}=uc(),{isMobile:E}=Dt(),F=up(),W=ma(),L=E||W,[K,X]=l.useState(null),[z,G]=l.useState(null),[H,oe]=l.useState(""),ve=l.useCallback(()=>X(null),[]),Ee=l.useCallback(()=>G(null),[]),Ie=l.useRef(void 0),[ge,de]=l.useState(()=>{const q=new Set;return t&&q.add(t),q}),[we,De]=l.useState(!1),[_e,Ne]=l.useState(!1),[Fe,$]=l.useState(!1),B=l.useId();l.useEffect(()=>{K==="model"&&de(()=>{const q=new Set;return t&&q.add(t),q})},[K,t]),l.useEffect(()=>{K!=="agent"&&De(!1),K!=="model"&&oe("")},[K]),l.useEffect(()=>{_e||$(!1)},[_e]);const J=p?.(),I=J?.permission?.edit;let _="ask";(I==="allow"||I==="ask"||I==="deny"||I==="full")&&(_=I);const U=J?J.tools?.edit!==!1:!1;(!J||!U)&&(_="deny");const xe=J?.permission?.webfetch,ye=J?.permission?.bash,se=l.useMemo(()=>Mc({agentDefaultEditMode:_,webfetchPermission:xe,bashPermission:ye}),[_,xe,ye]),{cascadeDefaultMode:O,modeAvailability:V,autoApproveAvailable:P}=se,te=!!(h&&o),je=te&&h&&o?j(h,o,O):O,ke={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},$e=l.useCallback(q=>!V[q],[V]),ct=l.useMemo(()=>!te||$e(je)&&je!==O?O:je,[O,$e,te,je]),ht=[{mode:"ask",label:ke.ask,disabled:$e("ask")},{mode:"allow",label:ke.allow,disabled:$e("allow")},{mode:"full",label:ke.full,disabled:$e("full")}],mt=l.useMemo(()=>Ir(ct),[ct]),dt=!te||!P;l.useEffect(()=>{dt&&(De(!1),$(!1))},[dt]);const Ge=E?"mobile":W?"vscode":"default",tt=Ge==="mobile"?"h-9":Ge==="vscode"?"h-6":"h-8",Ue=Ge==="mobile"?"h-5 w-5":"h-4 w-4",Ke=Ge==="mobile"?"h-5 w-5":"h-4 w-4",Je=L?"typography-micro":"typography-meta",fe=Ge==="mobile"?"gap-x-2":Ge==="vscode"?"gap-x-1":"gap-x-3",R=ke[ct],Q=l.useCallback((q,ie=Ue)=>{const ee=T(ie,"flex-shrink-0"),ue=Ir(q),et={color:ue?ue.text:"var(--foreground)"};return q==="full"?e.jsx(Cs,{className:ee,style:et}):q==="allow"?e.jsx(fn,{className:ee,style:et}):q==="deny"?e.jsx(gr,{className:ee,style:et}):e.jsx(Or,{className:ee,style:et})},[Ue]),re=l.useCallback(q=>{dt||!h||!o||$e(q)||(k(h,o,q,O),Ne(!1),De(!1),$(!1))},[O,dt,h,o,k,Ne,$,$e]),ce=d(),Z=Array.isArray(ce?.models)?ce.models:[],ne=t&&n?u(t,n):void 0,ae=Er(ne),Me=ws(ne,"input"),at=ws(ne,"output"),zt=[{label:"Input",value:cn(ne?.cost?.input)},{label:"Output",value:cn(ne?.cost?.output)},{label:"Cache read",value:cn(ne?.cost?.cache_read)},{label:"Cache write",value:cn(ne?.cost?.cache_write)}],xt=[{label:"Context",value:Lt(ne?.limit?.context)},{label:"Output",value:Lt(ne?.limit?.output)}],Nt=l.useRef(void 0),Ct=h?g.get(h)?.length??-1:-1,yt=l.useRef(null),jt=l.useCallback((q,ie,ee)=>{if(!q||!ie)return"model-missing";const ue=s.find(he=>he.id===q);return ue?(Array.isArray(ue.models)?ue.models:[]).find(he=>he.id===ie)?(a(q),i(ie),h&&ee&&w(h,ee,q,ie),"applied"):"model-missing":"provider-missing"},[s,a,i,h,w]);l.useEffect(()=>{if(!h){yt.current=null;return}if(!y||s.length===0||f.length===0)return;(!yt.current||yt.current.sessionId!==h)&&(yt.current={sessionId:h,resolved:!1,inFlight:!1});const q=yt.current;if(!q||q.resolved||q.inFlight)return;let ie=!1;const ee=()=>{if(ie)return;const he=yt.current;he&&he.sessionId===h&&(he.resolved=!0,he.inFlight=!1)},ue=()=>{const he=x(h);if(he){o!==he&&c(he);const qe=S(h,he);if(qe){const ot=jt(qe.providerId,qe.modelId,he);if(ot==="applied")return"resolved";if(ot==="provider-missing")return"waiting"}else return"resolved"}for(const qe of f){const ot=S(h,qe.name);if(!ot)continue;o!==qe.name&&c(qe.name),b(h,qe.name);const Ut=jt(ot.providerId,ot.modelId,qe.name);if(Ut==="applied")return"resolved";if(Ut==="provider-missing")return"waiting"}return"continue"},Qe=()=>{if(f.length===0)return;const he=f.filter(ot=>ln(ot.mode)),qe=f.find(ot=>ot.name==="build")||he[0]||f[0];qe&&(b(h,qe.name),o!==qe.name&&c(qe.name),qe.model?.providerID&&qe.model?.modelID&&jt(qe.model.providerID,qe.model.modelID,qe.name))};return(async()=>{try{const he=ue();if(he==="resolved"){ee();return}if(he==="waiting"||Ct===-1)return;if(Ct>0){q.inFlight=!0;try{const qe=await v(h,f);if(ie)return;if(qe.size>0){let ot=null,Ut=-1/0;for(const[We,Rt]of qe)Rt.timestamp>Ut&&(Ut=Rt.timestamp,ot=We);if(ot){b(h,ot),o!==ot&&c(ot);const We=qe.get(ot);if(We){const Rt=jt(We.providerId,We.modelId,ot);if(Rt==="applied"){ee();return}if(Rt==="provider-missing")return}else{ee();return}}}}catch(qe){ie||console.error("[ModelControls] Error resolving session from messages:",qe)}finally{const qe=yt.current;!ie&&qe&&qe.sessionId===h&&(qe.inFlight=!1)}}Qe(),ee()}catch(he){ie||console.error("[ModelControls] Error in session switch:",he)}})(),()=>{ie=!0}},[h,Ct,f,o,x,S,c,jt,v,b,y,s]),l.useEffect(()=>{if(!y||!h||s.length===0||f.length===0)return;const ie=x(h)||o;if(!ie)return;const ee=S(h,ie);if(!ee)return;const ue=s.find(qe=>qe.id===ee.providerId);if(!ue||!(Array.isArray(ue.models)?ue.models.some(qe=>qe.id===ee.modelId):!1))return;const et=t===ee.providerId,he=n===ee.modelId;et&&he||(ie!==o&&c(ie),jt(ee.providerId,ee.modelId,ie))},[y,h,o,t,n,s,f,x,S,jt,c]),l.useEffect(()=>{if(!y)return;(async()=>{try{if(o!==Nt.current&&(Nt.current=o,o&&h)){await new Promise(ue=>setTimeout(ue,50));const ie=S(h,o);if(ie){const ue=jt(ie.providerId,ie.modelId,o);if(ue==="applied"||ue==="provider-missing")return}const ee=f.find(ue=>ue.name===o);if(ee?.model?.providerID&&ee?.model?.modelID&&jt(ee.model.providerID,ee.model.modelID,o)==="provider-missing")return}}catch(ie){console.error("[ModelControls] Agent change error:",ie)}})()},[o,h,S,jt,f,y]);const Se=q=>{try{c(q),Ne(!1),h&&b(h,q),L&&ve()}catch(ie){console.error("[ModelControls] Handle agent change error:",ie)}},Be=(q,ie)=>{try{const ee=jt(q,ie,o||void 0);if(ee!=="applied"){ee==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",q):ee==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:q,modelId:ie});return}N(q,ie),Ne(!1),L&&ve()}catch(ee){console.error("[ModelControls] Handle model change error:",ee)}},Ve=q=>{const ie=typeof q?.name=="string"?q.name:typeof q?.id=="string"?q.id:"";return ie.length>40?ie.substring(0,37)+"...":ie},Le=()=>s.find(ie=>ie.id===t)?.name||t,pe=()=>{if(!t||!n||Z.length===0)return"Not selected";const q=Z.find(ie=>ie.id===n);return Ve(q)},Re=()=>{if(!o){const ie=f.filter(Qe=>ln(Qe.mode)),ue=ie.find(Qe=>Qe.name==="build")||ie[0];return ue?Oe(ue.name):"Select Agent"}const q=f.find(ie=>ie.name===o);return Oe(q?q.name:o)},Oe=q=>q.charAt(0).toUpperCase()+q.slice(1),Ye=(q,ie,ee)=>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(q,{className:"h-3.5 w-3.5"})},ee),At=l.useCallback(q=>{de(ie=>{const ee=new Set(ie);return ee.has(q)?ee.delete(q):ee.add(q),ee})},[]),nt=l.useCallback(q=>{Ie.current&&clearTimeout(Ie.current),Ie.current=setTimeout(()=>{G(q)},500)},[]),wt=l.useCallback(()=>{Ie.current&&clearTimeout(Ie.current)},[]);l.useEffect(()=>()=>{Ie.current&&clearTimeout(Ie.current)},[]);const It=()=>!L||z!=="model"?null:e.jsx(Kt,{open:!0,onClose:Ee,title:ne?.name||pe(),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:Le()})]}),ae.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:ae.map(({key:q,icon:ie,label:ee})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ye(ie,ee,`cap-${q}`),e.jsx("span",{className:"typography-meta text-foreground",children:ee})]},q))})]}),(Me.length>0||at.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:[Me.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:Me.map(({key:q,icon:ie,label:ee})=>Ye(ie,`${ee} input`,`input-${q}`))})]}),at.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:at.map(({key:q,icon:ie,label:ee})=>Ye(ie,`${ee} output`,`output-${q}`))})]})]})]}),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:Lt(ne?.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:Lt(ne?.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:Di(ne?.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:Ei(ne?.release_date)})]})]})]})]})}),Et=()=>{if(!L||z!=="agent"||!J)return null;const q=Object.entries(J.tools||{}).filter(([,he])=>he).map(([he])=>he).sort(),ie=!!(J.prompt&&J.prompt.trim().length>0),ee=J.model?.providerID&&J.model?.modelID,ue=J.temperature!==void 0||J.topP!==void 0,Qe=he=>Q(he==="full"||he==="allow"||he==="deny"?he:"ask","h-3.5 w-3.5"),et=he=>he==="full"?"Full":he==="allow"?"Allow":he==="deny"?"Deny":"Ask";return e.jsx(Kt,{open:!0,onClose:Ee,title:Oe(J.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[J.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:J.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:J.mode==="primary"?"Primary":J.mode==="subagent"?"Subagent":J.mode==="all"?"All":"—"})]}),(ee||ue)&&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"}),ee&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[J.model.providerID," / ",J.model.modelID]}),ue&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[J.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:J.temperature})]}),J.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:J.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Tools"}),q.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:q.map(he=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:he},he))}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qe(J.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:et(J.permission?.edit)})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qe(typeof J.permission?.bash=="string"?J.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:et(typeof J.permission?.bash=="string"?J.permission.bash:void 0)})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qe(J.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:et(J.permission?.webfetch)})]})]})]})]}),ie&&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(fn,{className:"h-4 w-4 text-foreground"})]})})]})})},Y=()=>{if(!L)return null;const q=H.trim().toLowerCase(),ie=s.map(ee=>{const ue=Array.isArray(ee.models)?ee.models:[],Qe=q.length===0?!0:ee.name.toLowerCase().includes(q)||ee.id.toLowerCase().includes(q),et=q.length===0?ue:ue.filter(he=>{const qe=Ve(he).toLowerCase(),ot=typeof he.id=="string"?he.id.toLowerCase():"";return qe.includes(q)||ot.includes(q)});return{provider:ee,providerModels:et,matchesProvider:Qe}}).filter(({matchesProvider:ee,providerModels:ue})=>ee||ue.length>0);return e.jsx(Kt,{open:K==="model",onClose:ve,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"px-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Zo,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Pt,{value:H,onChange:ee=>oe(ee.target.value),placeholder:"Search providers or models",className:"pl-7 h-8 typography-meta"}),H&&e.jsx("button",{type:"button",onClick:()=>oe(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(gr,{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."}),!H&&C.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(hs,{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:C.map(({model:ee,providerID:ue,modelID:Qe})=>{const et=ue===t&&Qe===n,he=u(ue,Qe);return e.jsxs("button",{type:"button",onClick:()=>Be(ue,Qe),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",et?"bg-primary/15 text-primary":"hover:bg-accent/40"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Vt,{providerId:ue,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ve(ee)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(he?.limit?.context||he?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[he?.limit?.context?`${Lt(he?.limit?.context)} ctx`:"",he?.limit?.context&&he?.limit?.output?" • ":"",he?.limit?.output?`${Lt(he?.limit?.output)} out`:""]})})]},`fav-mobile-${ue}-${Qe}`)})})]}),!H&&M.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(Nn,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:M.map(({model:ee,providerID:ue,modelID:Qe})=>{const et=ue===t&&Qe===n,he=u(ue,Qe);return e.jsxs("button",{type:"button",onClick:()=>Be(ue,Qe),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",et?"bg-primary/15 text-primary":"hover:bg-accent/40"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Vt,{providerId:ue,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ve(ee)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(he?.limit?.context||he?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[he?.limit?.context?`${Lt(he?.limit?.context)} ctx`:"",he?.limit?.context&&he?.limit?.output?" • ":"",he?.limit?.output?`${Lt(he?.limit?.output)} out`:""]})})]},`recent-mobile-${ue}-${Qe}`)})})]}),ie.map(({provider:ee,providerModels:ue})=>{if(ue.length===0&&!q.length)return null;const Qe=ee.id===t,et=ge.has(ee.id)||q.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",onClick:()=>At(ee.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":et,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{providerId:ee.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ee.name}),Qe&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),et?e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(us,{className:"h-3 w-3 text-muted-foreground"})]}),et&&ue.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:ue.map(he=>{const qe=Qe&&he.id===n,ot=u(ee.id,he.id),Ut=Er(ot).slice(0,3),We=ws(ot,"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",qe?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Be(ee.id,he.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",!qe&&"hover:bg-accent/40"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ve(he)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(ot?.limit?.context||ot?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[ot?.limit?.context?e.jsxs("span",{children:[Lt(ot?.limit?.context)," ctx"]}):null,ot?.limit?.context&&ot?.limit?.output?e.jsx("span",{children:"•"}):null,ot?.limit?.output?e.jsxs("span",{children:[Lt(ot?.limit?.output)," out"]}):null]}),(Ut.length>0||We.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Ut,...We].map(({key:Rt,icon:ms,label:Ca})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Ca,"aria-label":Ca,children:e.jsx(ms,{className:"h-3 w-3"})},`meta-${ee.id}-${he.id}-${Rt}`))})]})]}),e.jsx("button",{type:"button",onClick:Rt=>{Rt.preventDefault(),Rt.stopPropagation(),A(ee.id,he.id)},className:T("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",D(ee.id,he.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":D(ee.id,he.id)?"Unfavorite":"Favorite",title:D(ee.id,he.id)?"Remove from favorites":"Add to favorites",children:D(ee.id,he.id)?e.jsx(hs,{className:"h-4 w-4"}):e.jsx(Zs,{className:"h-4 w-4"})})]},he.id)})})]},ee.id)})]})})},Te=()=>{if(!L)return null;const q=f.filter(ie=>ln(ie.mode));return e.jsx(Kt,{open:K==="agent",onClose:ve,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[q.map(ie=>{const ee=ie.name===o,ue=_s(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",ue.class,ee?"active":"border-border/40"),onClick:()=>Se(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",ue.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:ee?{color:`var(${ue.var})`}:void 0,children:Oe(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:dt,onClick:()=>{dt||De(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",dt?"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:mt?mt.text:"var(--foreground)",mixBlendMode:"normal"},children:R})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!mt&&"text-muted-foreground"),style:mt?{color:mt.text}:void 0,children:Q(ct,Ue)}),e.jsx(vt,{className:T("h-4 w-4 text-muted-foreground transition-transform",we?"rotate-180":"")})]})]}),we&&!dt&&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:ht.map(ie=>{const ee=ie.mode===ct,ue=Ir(ie.mode);return e.jsxs("button",{type:"button",disabled:ie.disabled,onClick:()=>re(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",ee?"bg-primary/10":void 0),style:ee&&ue?{backgroundColor:ue.background??void 0}:void 0,children:[Q(ie.mode,Ue),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:ue?ue.text:"var(--foreground)"},children:ie.label})})]},ie.mode)})})})]})]})})},ze=()=>e.jsx(ut,{align:"start",sideOffset:8,className:"max-w-[320px]",children:ne?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:ne.name||pe()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Le()})]}),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:ae.length>0?ae.map(({key:q,icon:ie,label:ee})=>Ye(ie,ee,`cap-${q}`)):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:Me.length>0?Me.map(({key:q,icon:ie,label:ee})=>Ye(ie,`${ee} input`,`input-${q}`)):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:at.length>0?at.map(({key:q,icon:ie,label:ee})=>Ye(ie,`${ee} output`,`output-${q}`)):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)"}),zt.map(q=>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:q.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:q.value})]},q.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"}),xt.map(q=>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:q.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:q.value})]},q.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:Di(ne.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:Ei(ne.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),it=()=>e.jsxs(ft,{delayDuration:1e3,children:[L?e.jsxs("button",{type:"button",onClick:()=>X("model"),onTouchStart:()=>nt("model"),onTouchEnd:wt,onTouchCancel:wt,className:T("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",E&&"flex-1","cursor-pointer hover:opacity-70",tt),children:[t?e.jsx(Vt,{providerId:t,className:T(Ke,"flex-shrink-0")}):e.jsx(Cs,{className:T(Ke,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label typography-micro font-medium truncate min-w-0",E?"flex-1":"max-w-[220px]"),children:pe()})]}):e.jsxs(Xt,{open:_e,onOpenChange:Ne,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Jt,{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",tt),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{providerId:t,className:T(Ke,"flex-shrink-0")}),e.jsx(Cs,{className:T(Ke,"text-primary/60 hidden")})]}):e.jsx(Cs,{className:T(Ke,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label",Je,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:pe()},`${t}-${n}`)]})})}),e.jsxs(Zt,{className:"max-w-[300px]",children:[C.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(hs,{className:"h-3 w-3 flex-shrink-0 mr-2 text-primary"}),"Favorites"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Xe,{outerClassName:"max-h-[320px] min-w-[200px]",children:C.map(({model:q,providerID:ie,modelID:ee})=>{const ue=u(ie,ee),Qe=Er(ue).map(We=>({...We,id:`cap-${We.key}`})),et=[...ws(ue,"input"),...ws(ue,"output")],he=Array.from(new Map(et.map(We=>[We.key,We])).values()).map(We=>({...We,id:`mod-${We.key}`})),qe=[...Qe,...he],ot=Lt(ue?.limit?.context),Ut=Lt(ue?.limit?.output);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{Be(ie,ee)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:Ve(q)}),ue?.limit?.context||ue?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue?.limit?.context?`${ot} ctx`:"",ue?.limit?.context&&ue?.limit?.output?" • ":"",ue?.limit?.output?`${Ut} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[qe.map(({id:We,icon:Rt,label:ms})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":ms,role:"img",title:ms,children:e.jsx(Rt,{className:"h-3 w-3"})},We)),e.jsx("button",{onClick:We=>{We.preventDefault(),We.stopPropagation(),A(ie,ee)},className:"model-favorite-button flex h-4 w-4 items-center justify-center text-yellow-500 hover:text-yellow-600","aria-label":"Unfavorite",title:"Remove from favorites",children:e.jsx(hs,{className:"h-3.5 w-3.5"})})]})]})},`fav-${ie}-${ee}`)})})})]}),M.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(Nn,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Xe,{outerClassName:"max-h-[320px] min-w-[200px]",children:M.map(({model:q,providerID:ie,modelID:ee})=>{const ue=u(ie,ee),Qe=Er(ue).map(We=>({...We,id:`cap-${We.key}`})),et=[...ws(ue,"input"),...ws(ue,"output")],he=Array.from(new Map(et.map(We=>[We.key,We])).values()).map(We=>({...We,id:`mod-${We.key}`})),qe=[...Qe,...he],ot=Lt(ue?.limit?.context),Ut=Lt(ue?.limit?.output);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{Be(ie,ee)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:Ve(q)}),ue?.limit?.context||ue?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue?.limit?.context?`${ot} ctx`:"",ue?.limit?.context&&ue?.limit?.output?" • ":"",ue?.limit?.output?`${Ut} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[qe.map(({id:We,icon:Rt,label:ms})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":ms,role:"img",title:ms,children:e.jsx(Rt,{className:"h-3 w-3"})},We)),e.jsx("button",{onClick:We=>{We.preventDefault(),We.stopPropagation(),A(ie,ee)},className:"model-favorite-button flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-yellow-600","aria-label":"Favorite",title:"Add to favorites",children:e.jsx(Zs,{className:"h-3.5 w-3.5"})})]})]})},`recent-${ie}-${ee}`)})})})]}),(C.length>0||M.length>0)&&e.jsx(zr,{}),s.map(q=>{const ie=Array.isArray(q.models)?q.models:[];return ie.length===0?e.jsxs(gt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Vt,{providerId:q.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),q.name," (No models)"]},q.id):e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(Vt,{providerId:q.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),q.name]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Xe,{outerClassName:"max-h-[320px] min-w-[200px]",children:ie.map(ee=>{const ue=u(q.id,ee.id),Qe=Er(ue).map(We=>({...We,id:`cap-${We.key}`})),et=[...ws(ue,"input"),...ws(ue,"output")],he=Array.from(new Map(et.map(We=>[We.key,We])).values()).map(We=>({...We,id:`mod-${We.key}`})),qe=[...Qe,...he],ot=Lt(ue?.limit?.context),Ut=Lt(ue?.limit?.output);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{Be(q.id,ee.id)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:Ve(ee)}),ue?.limit?.context||ue?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue?.limit?.context?`${ot} ctx`:"",ue?.limit?.context&&ue?.limit?.output?" • ":"",ue?.limit?.output?`${Ut} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[qe.map(({id:We,icon:Rt,label:ms})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":ms,role:"img",title:ms,children:e.jsx(Rt,{className:"h-3 w-3"})},We)),e.jsx("button",{onClick:We=>{We.preventDefault(),We.stopPropagation(),A(q.id,ee.id)},className:T("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",D(q.id,ee.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":D(q.id,ee.id)?"Unfavorite":"Favorite",title:D(q.id,ee.id)?"Remove from favorites":"Add to favorites",children:D(q.id,ee.id)?e.jsx(hs,{className:"h-3.5 w-3.5"}):e.jsx(Zs,{className:"h-3.5 w-3.5"})})]})]})},ee.id)})})})]},q.id)})]})]}),ze()]}),rt=()=>{if(!J)return e.jsx(ut,{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 q=Object.entries(J.tools||{}).filter(([,he])=>he).map(([he])=>he).sort(),ie=!!(J.prompt&&J.prompt.trim().length>0),ee=J.model?.providerID&&J.model?.modelID,ue=J.temperature!==void 0||J.topP!==void 0,Qe=he=>Q(he==="full"||he==="allow"||he==="deny"?he:"ask","h-3.5 w-3.5"),et=he=>he==="full"?"Full":he==="allow"?"Allow":he==="deny"?"Deny":"Ask";return e.jsx(ut,{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:Oe(J.name)}),J.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:J.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:J.mode==="primary"?"Primary":J.mode==="subagent"?"Subagent":J.mode==="all"?"All":"—"})]}),(ee||ue)&&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"}),ee?e.jsxs("span",{className:"typography-meta text-foreground",children:[J.model.providerID," / ",J.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),ue&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[J.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:J.temperature})]}),J.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:J.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Tools"}),q.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:q.map(he=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:he},he))}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qe(J.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:et(J.permission?.edit)})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qe(typeof J.permission?.bash=="string"?J.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:et(typeof J.permission?.bash=="string"?J.permission.bash:void 0)})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qe(J.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:et(J.permission?.webfetch)})]})]})]}),ie&&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(fn,{className:"h-4 w-4 text-foreground"})]})]})})},He=()=>L?e.jsxs("button",{type:"button",onClick:()=>X("agent"),onTouchStart:()=>nt("agent"),onTouchEnd:wt,onTouchCancel:wt,className:T("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",tt,"cursor-pointer hover:opacity-70",L&&"ml-1"),children:[e.jsx(_r,{className:T(Ke,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${_s(o).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",Je,"font-medium truncate min-w-0"),style:o?{color:`var(${_s(o).var})`}:void 0,children:Re()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(ft,{delayDuration:1e3,children:[e.jsxs(Xt,{children:[e.jsx(pt,{asChild:!0,children:e.jsx(Jt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",tt),children:[e.jsx(_r,{className:T(Ke,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${_s(o).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",Je,"font-medium min-w-0 truncate",F?"max-w-[220px]":void 0),style:o?{color:`var(${_s(o).var})`}:void 0,children:Re()})]})})}),e.jsxs(Zt,{align:"end",children:[f.filter(q=>ln(q.mode)).map(q=>e.jsx(gt,{className:"typography-meta",onSelect:()=>Se(q.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",_s(q.name).class)}),e.jsx("span",{className:"font-medium",children:Oe(q.name)})]}),q.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:q.description})]})},q.name)),e.jsx(zr,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:dt,onClick:()=>{dt||$(q=>!q)},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",dt?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Fe,"aria-controls":B,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:mt?mt.text:"var(--foreground)"},children:R})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!mt&&"text-muted-foreground"),style:mt?{color:mt.text}:void 0,children:Q(ct)}),e.jsx(vt,{className:T("h-3.5 w-3.5 transition-transform text-muted-foreground",Fe?"rotate-180":"")})]})]}),Fe&&!dt&&e.jsx("div",{id:B,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:ht.map(q=>{const ie=q.mode===ct,ee=Ir(q.mode);return e.jsxs("button",{type:"button",disabled:q.disabled,onClick:()=>re(q.mode),className:T("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",q.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",ie?"bg-primary/10":void 0),style:ie&&ee?{backgroundColor:ee.background??void 0}:void 0,children:[Q(q.mode,Ue),e.jsx("span",{className:"typography-meta font-medium",style:{color:ee?ee.text:"var(--foreground)"},children:q.label})]},q.mode)})})]})]})]}),rt()]})}),Ze=T("@container/model-controls flex items-center min-w-0",fe,E&&"w-full",r);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Ze,children:[e.jsx("div",{className:T("flex items-center min-w-0",E?"flex-1 min-w-0 overflow-hidden":"flex-1 min-w-0 justify-end"),children:it()}),e.jsx("div",{className:T("flex items-center min-w-0",fe,E&&"flex-shrink-0"),children:He()})]}),Y(),Te(),It(),Et()]})},Vh=r=>r?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(r):!0,Gh=(r,s)=>{if(typeof r!="string"||r.length===0)return{sanitizedText:r,mention:null};const t=s.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!r.includes("#"))return{sanitizedText:r,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(r))!==null;){const c=i.index,d=c+i[0].length,u=c>0?r[c-1]:null;if(!Vh(u))continue;const p={name:o.name,source:{value:i[0],start:c,end:d}};n||(n=p)}}return n?{sanitizedText:r,mention:n}:{sanitizedText:r,mention:null}},Ac=r=>({id:r.id,content:r.content,status:r.status||"pending",priority:r.priority||"medium"}),_o=$t()(Wt((r,s)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){r({isLoading:!0});try{const o=(await Ce.getSessionTodos(t)).map(Ac);r(a=>{const i=new Map(a.sessionTodos);return i.set(t,o),{sessionTodos:i,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),r({isLoading:!1})}}},updateTodos:(t,n)=>{r(o=>{const a=new Map(o.sessionTodos);return a.set(t,n),{sessionTodos:a}})},getTodosForSession:t=>s().sessionTodos.get(t)||[],clearTodos:t=>{r(n=>{const o=new Map(n.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),qh=(r,s)=>{const t=s.map(Ac);_o.getState().updateTodos(r,t)},Ii=[{variant:"shine",component:({children:r,className:s,...t})=>e.jsx(Nr.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",s),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:r})},{variant:"generate-effect",component:({children:r,className:s,...t})=>typeof r!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:r.split("").map((n,o)=>le.createElement(Nr.span,{...t,key:n+String(o),className:T("inline-block whitespace-pre text-primary-foreground",s),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:r,className:s,...t})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...t,className:T("invisible",s),children:r}),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",s),children:r}),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",s),children:r})]})},{variant:"hover-enter",component:({children:r,className:s,...t})=>{if(typeof r!="string")return null;const n=.25,o=.025,a=r.split("").map(i=>i===" "?" ":i);return e.jsxs(Nr.span,{...t,className:T("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",s),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((i,c)=>e.jsx(Nr.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))}),e.jsx("div",{className:T("absolute inset-0"),children:a.map((i,c)=>e.jsx(Nr.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))})]})}},{variant:"shake",component:({children:r,className:s,...t})=>e.jsx("span",{...t,className:T("text-primary-muted hover:animate-text-shake",s),children:r})},{variant:"hover-decoration",component:({children:r,className:s,...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",s),children:r})})}];function po({variant:r="shine",className:s,...t}){const a=Ii.find(i=>i.variant===r)?.component||Ii[0].component;return e.jsx(pl,{children:e.jsx(a,{...t,className:s})})}const Kh=2e3,Yh=1500;function Xh({statusText:r,isWaitingForPermission:s,wasAborted:t,completionId:n,isComplete:o}){const[a,i]=le.useState(null),[c,d]=le.useState(!1),[u,p]=le.useState(!1),[m,f]=le.useState(!1),[h,g]=le.useState(null),[b,x]=le.useState(!1),w=le.useRef(0),S=le.useRef([]),v=le.useRef(!1),j=le.useRef(null),k=le.useRef(null),y=le.useRef(null),A=le.useRef(null),D=le.useRef(0),N=le.useRef(null),C=le.useRef(!1),M=le.useRef(!1),E=le.useRef(!1),F=le.useRef(!0),W=le.useRef(null),L=le.useRef(null),K=(H,oe)=>{if(j.current&&(clearTimeout(j.current),j.current=null),k.current&&(clearTimeout(k.current),k.current=null),y.current&&(clearTimeout(y.current),y.current=null),H==="aborted"){i(null),d(!1),f(!1),g("aborted"),x(!1),N.current="aborted",C.current=!0,M.current=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p(!0)):p(!0);return}g(null),f(!1),N.current=H,C.current=!0,a!==null&&a!==H&&(x(!0),y.current=setTimeout(()=>{x(!1),y.current=null},150)),i(H),d(oe),u||(typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{p(!0)}):p(!0))};if(le.useEffect(()=>{const H=Date.now();r?(v.current=!1,a?(r!==a||!!s!==c)&&S.current.push({status:r,permission:!!s}):(K(r,!!s),w.current=H,S.current=[])):v.current=!0},[r,s,a,c,t]),le.useEffect(()=>{t&&(M.current=!0)},[t]),le.useEffect(()=>{E.current=!!o},[o]),le.useEffect(()=>{o&&(v.current=!0)},[o]),le.useEffect(()=>{const H=Ie=>{if(m)return;const ge=N.current!==null||C.current;Ie&&ge?(f(!1),p(!0),i(null),d(!1),g(Ie),N.current=null,x(!1),Ie==="success"&&n&&(W.current=n),L.current=Date.now(),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{p(!1),g(null),C.current=!1,k.current=null},Yh)):(f(!0),p(!1),g(null),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{i(null),d(!1),f(!1),C.current=!1,N.current=null,j.current=null},180)),M.current=!1};if(!!!(r||a||h!==null||v.current||S.current.length>0||M.current||E.current)){A.current!==null&&(cancelAnimationFrame(A.current),A.current=null);return}const Ee=Ie=>{if(Ie-D.current<150){A.current=requestAnimationFrame(Ee);return}D.current=Ie;const ge=Date.now(),de=ge-w.current,we=v.current&&E.current;if(!we&&S.current.length>0&&de<Kh){A.current=requestAnimationFrame(Ee);return}if(v.current&&M.current)v.current=!1,S.current=[],H("aborted");else if(!we&&S.current.length>0){const Ne=S.current[S.current.length-1];K(Ne.status,Ne.permission),w.current=ge,S.current=[]}else if(v.current){v.current=!1,S.current.length>0&&(C.current=!0),S.current=[];let Ne=null;if(M.current?Ne="aborted":E.current&&(Ne="success",C.current=!0),Ne==="success"&&n&&W.current===n){i(null),d(!1),f(!1),p(!1),g(null),S.current=[],C.current=!1,N.current=null,v.current=!1,M.current=!1,A.current=null;return}H(Ne)}!!(a||h!==null||S.current.length>0||v.current||M.current||E.current)?A.current=requestAnimationFrame(Ee):A.current=null};return A.current=requestAnimationFrame(Ee),()=>{A.current!==null&&(cancelAnimationFrame(A.current),A.current=null)}},[r,a,h,o,t,m]),le.useEffect(()=>()=>{j.current&&clearTimeout(j.current),k.current&&clearTimeout(k.current),y.current&&clearTimeout(y.current)},[]),le.useEffect(()=>{if(typeof window>"u")return;F.current=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0;const H=()=>{F.current=!0},oe=()=>{F.current=!1};return window.addEventListener("focus",H),window.addEventListener("blur",oe),()=>{window.removeEventListener("focus",H),window.removeEventListener("blur",oe)}},[]),le.useEffect(()=>{const H=()=>{if(typeof document>"u"||typeof Date>"u"||document.visibilityState!=="visible")return;const oe=L.current;(h!==null||a!==null)&&oe&&Date.now()-oe>500&&(i(null),d(!1),f(!1),p(!1),g(null),S.current=[],C.current=!1,N.current=null,v.current=!1,M.current=!1)};return document.addEventListener("visibilitychange",H),window.addEventListener("focus",H),()=>{document.removeEventListener("visibilitychange",H),window.removeEventListener("focus",H)}},[a,h]),!a&&h===null)return null;let X;h==="success"?X="Done":h==="aborted"?X="Aborted":a?X=a.charAt(0).toUpperCase()+a.slice(1):X="Working";const z=c?"assertive":"polite",G=h===null?`${X}...`:X;return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${u&&!m?"opacity-100":"opacity-0"}`,role:"status","aria-live":z,"aria-label":X,"data-waiting":c?"true":void 0,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[h===null&&e.jsx(po,{variant:"shine",className:"typography-ui-header transition-opacity duration-150",style:{opacity:b?.6:1},children:G}),h==="success"&&e.jsx(po,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150",style:{opacity:b?.6:1},children:"Done"}),h==="aborted"&&e.jsx(po,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150 text-status-error",style:{opacity:b?.6:1},children:"Aborted"})]})})}const Fi={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Jh=({todo:r})=>{const s=Fi[r.status]||Fi.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",s.textClassName),children:r.content})})},Pi=[],Zh=({isWorking:r,statusText:s,isWaitingForPermission:t,wasAborted:n,abortActive:o,completionId:a,isComplete:i,showAbort:c,onAbort:d,showAbortStatus:u})=>{const[p,m]=l.useState(!1),f=me(M=>M.currentSessionId),h=_o(M=>f?M.sessionTodos.get(f)??Pi:Pi),g=_o(M=>M.loadTodos),{isMobile:b}=Pe(),x=b||rs();l.useEffect(()=>{f&&g(f)},[f,g]);const w=l.useMemo(()=>{const M={in_progress:0,pending:1,completed:2,cancelled:3};return[...h].filter(E=>E.status!=="cancelled").sort((E,F)=>M[E.status]-M[F.status])},[h]),S=l.useMemo(()=>w.find(M=>M.status==="in_progress")||w.find(M=>M.status==="pending")||null,[w]),v=l.useMemo(()=>{const M=h.filter(F=>F.status!=="cancelled").length;return{completed:h.filter(F=>F.status==="completed").length,total:M}},[h]),j=w.length>0,k=!u&&(n||!o),y=r||j||u,A=l.useRef(null);if(l.useEffect(()=>{if(!p)return;const M=E=>{A.current&&!A.current.contains(E.target)&&m(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[p]),!y)return null;const D=()=>m(M=>!M),N=c&&d?e.jsx("button",{type:"button",onClick:d,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(gr,{size:18,"aria-hidden":"true"})}):null,C=j?e.jsxs("button",{type:"button",onClick:D,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!x&&S?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:S.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[v.completed,"/",v.total]}),p?e.jsx(Vr,{className:"h-3.5 w-3.5"}):e.jsx(vt,{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:u?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(gr,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(Xh,{statusText:s,isWaitingForPermission:t,wasAborted:n,completionId:a??null,isComplete:i},f??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:A,children:[N,C,p&&j&&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-muted 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:[v.completed,"/",v.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:w.map(M=>e.jsx(Jh,{todo:M},M.id))})]})]})]})})},Qh=r=>!r||typeof r!="object"?!1:!!r.synthetic,Oo=r=>!Array.isArray(r)||r.length===0?!1:r.every(s=>Qh(s)),eg={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function tg(r){const s=me(t=>!r||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(r)??"idle");return l.useMemo(()=>{if(s==="idle")return eg;const t=s==="busy",n=s==="cooldown";return{phase:s,isWorking:t||n,isBusy:t,isCooldown:n}},[s])}function Dc(){const r=me(s=>s.currentSessionId);return tg(r)}const sg={activity:"idle",hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1},Ri=r=>r.role==="assistant",rg=r=>r.type==="reasoning",Ec=r=>r.type==="text",Li=r=>{if(Ec(r))return r.text;const s=r;if(typeof s.text=="string")return s.text;if(typeof s.content=="string")return s.content;if(typeof s.value=="string")return s.value},_i=r=>(Ec(r)||rg(r),r.time),ng=r=>{if(r.tool)return r.tool;const s=r;return typeof s.name=="string"?s.name:"tool"};function Tc(){const{currentSessionId:r,messages:s,permissions:t,sessionAbortFlags:n}=me(ta(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=Dc(),c=l.useMemo(()=>r?s.get(r)??[]:[],[r,s]),d=l.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const h=c.filter(j=>Ri(j.info)&&!Oo(j.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const g=[...h].sort((j,k)=>{const y=typeof j.info.time?.created=="number"?j.info.time.created:null,A=typeof k.info.time?.created=="number"?k.info.time.created:null;return y!==null&&A!==null&&y!==A?y-A:j.info.id.localeCompare(k.info.id)}),b=g[g.length-1];let x,w;const S=new Set(["edit","write"]);for(let j=(b.parts??[]).length-1;j>=0;j-=1){const k=b.parts?.[j];if(k)switch(k.type){case"reasoning":{const y=k.time??_i(k);(!y||typeof y.end>"u")&&!x&&(x="reasoning");break}case"tool":{const y=k.state?.status;if((y==="running"||y==="pending")&&!x){const A=ng(k);S.has(A)?x="editing":(x="tool",w=A)}break}case"text":{const y=Li(k)??"";if(typeof y=="string"&&y.trim().length>0){const A=_i(k);(!A||typeof A.end>"u")&&!x&&(x="text")}break}}}const v=x==="editing"?"editing":x==="tool"&&w?`using ${w}`:x==="reasoning"?"thinking":x==="text"?"composing":"working";return{activePartType:x,activeToolName:w,statusText:v}},[c]),u=l.useMemo(()=>{const h=r,g=h?n?.get(h)??null:null,b=!!(g&&!g.acknowledged);return{wasAborted:b,abortActive:b}},[r,n]),p=l.useMemo(()=>{if(u.wasAborted)return{...sg,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,g=o==="busy",b=i;let x="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?x="tooling":x=b?"cooldown":"streaming"),{activity:x,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:g,isCooldown:b,lifecyclePhase:g?"streaming":b?"cooldown":null,statusText:h?d.statusText:null,isWaitingForPermission:!1,canAbort:h,compactionDeadline:null,activePartType:h?d.activePartType:void 0,activeToolName:h?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:b}},[o,a,i,d,u]),m=l.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const g=c.filter(w=>Ri(w.info)&&!Oo(w.parts));if(g.length===0)return{isActive:h,characterCount:0};const b=g[g.length-1];let x=0;return(b.parts??[]).forEach(w=>{if(w.type!=="text")return;const S=Li(w)??"";typeof S=="string"&&S.trim().length>0&&(x+=S.length)}),{isActive:h,characterCount:x}},[c,a,d.activePartType]),f=l.useMemo(()=>{if(p.wasAborted||p.abortActive)return p;const h=r;return(h?t?.get(h)??[]:[]).length>0?{...p,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:p},[r,t,p]);return{forming:m,working:f}}const og=8,ag=r=>r==="primary"||r==="all"||r===void 0||r===null,ho=({onOpenSettings:r,scrollToBottom:s})=>{const[t,n]=l.useState(""),[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(""),[p,m]=l.useState(!1),[f,h]=l.useState(""),[g,b]=l.useState(!1),[x,w]=l.useState(""),[S,v]=l.useState(null),j=l.useRef(null),k=l.useRef(null),y=l.useRef(null),A=l.useRef(null),D=l.useRef(null),N=me(Y=>Y.sendMessage),C=me(Y=>Y.currentSessionId),M=me(Y=>Y.abortCurrentOperation),E=me(Y=>Y.acknowledgeSessionAbort),F=me(Y=>Y.abortPromptSessionId),W=me(Y=>Y.abortPromptExpiresAt),L=me(Y=>Y.clearAbortPrompt),K=me(Y=>Y.attachedFiles),X=me(Y=>Y.addAttachedFile),z=me(Y=>Y.addServerFile),G=me(Y=>Y.clearAttachedFiles),H=me(Y=>Y.saveSessionAgentSelection),{currentProviderId:oe,currentModelId:ve,currentAgentName:Ee,setAgent:Ie,getVisibleAgents:ge}=kt(),de=ge(),{isMobile:we}=Pe(),{working:De}=Tc(),[_e,Ne]=l.useState(!1),Fe=l.useRef(null),$=l.useRef(!1),B=l.useRef(!1),J=l.useCallback(Y=>{if(!we||Y.pointerType!=="touch")return;const Te=j.current;if(!Te||document.activeElement===Te)return;Y.preventDefault(),Y.stopPropagation();const ze=document.scrollingElement;ze&&ze.scrollTop!==0&&(ze.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Te.focus({preventScroll:!0})}catch{Te.focus()}const it=Te.value.length;try{Te.setSelectionRange(it,it)}catch{}},[we]),I=l.useMemo(()=>{if(Ee)return de.find(Y=>Y.name===Ee)},[de,Ee]),_=l.useMemo(()=>{const Y=I?.permission?.edit;let Te="ask";(Y==="allow"||Y==="ask"||Y==="deny"||Y==="full")&&(Te=Y);const ze=I?I.tools?.edit!==!1:!1;return(!I||!ze)&&(Te="deny"),Te},[I]),U=me(l.useCallback(Y=>!C||!Ee?void 0:Y.sessionAgentEditModes.get(C)?.get(Ee),[C,Ee])),xe=I?.permission?.webfetch,ye=I?.permission?.bash,se=l.useMemo(()=>Mc({agentDefaultEditMode:_,webfetchPermission:xe,bashPermission:ye}),[_,xe,ye]),O=!!(C&&Ee),V=l.useMemo(()=>O&&U&&se.modeAvailability[U]?U:se.cascadeDefaultMode,[se,O,U]),P=l.useMemo(()=>Ir(V),[V]),te=l.useCallback(Y=>rs()?`color-mix(in srgb, ${Y} 55%, transparent)`:Y,[]),je=l.useMemo(()=>{const Y=rs()?1:2;if(!P)return{borderWidth:Y};const Te=P.border??P.text;return{borderColor:te(Te),borderWidth:Y}},[P,te]),ke=t.trim()||K.length>0,$e=De.isWorking,ct=l.useMemo(()=>C?F===C&&!!W:!1,[F,W,C]),ht=async Y=>{if(Y?.preventDefault(),!ke||!C)return;const Te=t.replace(/^\n+|\n+$/g,"");s?.({instant:!0,force:!0});const ze=Te.trimStart();if(ze.startsWith("/")&&ze.slice(1).trim().split(/\s+/)[0]?.toLowerCase()==="summarize"&&s?.({instant:!0,force:!0}),!oe||!ve){console.warn("Cannot send message: provider or model not selected");return}const{sanitizedText:it,mention:rt}=Gh(Te,de),He=rt?.name,Ze=K.map(q=>({...q}));Ze.length>0&&G(),n(""),we&&j.current?.blur(),await N(it,oe,ve,Ee,Ze,He).catch(q=>{const ie=q instanceof Error?q.message:typeof q=="string"?q:String(q??""),ee=ie.toLowerCase();console.error("Message send failed:",ie||q),!(ee.includes("timeout")||ee.includes("timed out")||ee.includes("may still be processing")||ee.includes("being processed")||ee.includes("failed to fetch")||ee.includes("networkerror")||ee.includes("network error")||ee.includes("gateway timeout")||ee==="failed to send message")&&(Ze.length>0&&Os.setState({attachedFiles:Ze}),be.error(ie||"Message failed to send. Attachments restored."))}),we||j.current?.focus()},mt=Y=>{if(p&&A.current&&(Y.key==="Enter"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="Escape"||Y.key==="Tab")){Y.preventDefault(),A.current.handleKeyDown(Y.key);return}if(g&&D.current&&(Y.key==="Enter"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="Escape"||Y.key==="Tab")){Y.preventDefault(),D.current.handleKeyDown(Y.key);return}if(i&&y.current&&(Y.key==="Enter"||Y.key==="ArrowUp"||Y.key==="ArrowDown"||Y.key==="Escape"||Y.key==="Tab")){Y.preventDefault(),y.current.handleKeyDown(Y.key);return}if(Y.key==="Tab"&&!p&&!i){Y.preventDefault(),tt();return}Y.key==="Enter"&&!Y.shiftKey&&!we&&(Y.preventDefault(),ht())},dt=l.useCallback(()=>{Fe.current&&(clearTimeout(Fe.current),Fe.current=null),Ne(!0),Fe.current=setTimeout(()=>{Ne(!1),Fe.current=null},1800)},[]),Ge=l.useCallback(()=>{L(),dt(),M()},[M,L,dt]),tt=()=>{const Y=de.filter(rt=>ag(rt.mode));if(Y.length<=1)return;const ze=(Y.findIndex(rt=>rt.name===Ee)+1)%Y.length,it=Y[ze];Ie(it.name),C&&H(C,it.name)},Ue=l.useCallback(()=>{const Y=j.current;if(!Y)return;Y.style.height="auto";const Te=Y.ownerDocument?.defaultView,ze=Te?Te.getComputedStyle(Y):null,it=ze?parseFloat(ze.lineHeight):NaN,rt=ze?parseFloat(ze.paddingTop):NaN,He=ze?parseFloat(ze.paddingBottom):NaN,Ze=22,ie=Number.isNaN(rt)||Number.isNaN(He)?16:rt+He,ue=(Number.isNaN(it)?Ze:it)*og+ie,Qe=Y.scrollHeight||Y.offsetHeight,et=Math.min(Qe,ue);Y.style.height=`${et}px`,Y.style.maxHeight=`${ue}px`,v(he=>he&&he.height===et&&he.maxHeight===ue?he:{height:et,maxHeight:ue})},[]);l.useLayoutEffect(()=>{Ue()},[Ue,t,we]);const Ke=l.useCallback((Y,Te)=>{if(Y.startsWith("/")){const He=Y.indexOf(" "),Ze=Y.indexOf(`
67
- `),q=Math.min(He===-1?Y.length:He,Ze===-1?Y.length:Ze);if(Te<=q&&He===-1){const ie=Y.substring(1,q);h(ie),m(!0),c(!1),b(!1)}else m(!1);return}m(!1);const ze=Y.substring(0,Te),it=ze.lastIndexOf("#");if(it!==-1){const He=it>0?ze[it-1]:null,Ze=ze.substring(it+1),q=Ze.includes(" ")||Ze.includes(`
68
- `);if((!He||/\s/.test(He))&&!q){w(Ze),b(!0),c(!1);return}}b(!1),w("");const rt=ze.lastIndexOf("@");if(rt!==-1){const He=ze.substring(rt+1);!He.includes(" ")&&!He.includes(`
69
- `)?(u(He),c(!0)):c(!1)}else c(!1)},[w,h,u,b,m,c]),Je=l.useCallback(Y=>{if(!Y)return;const Te=j.current;if(!Te){const Ze=t+Y;n(Ze),Ke(Ze,Ze.length),requestAnimationFrame(()=>Ue());return}const ze=Te.selectionStart??t.length,it=Te.selectionEnd??t.length,rt=`${t.substring(0,ze)}${Y}${t.substring(it)}`;n(rt);const He=ze+Y.length;requestAnimationFrame(()=>{const Ze=j.current;Ze&&(Ze.selectionStart=He,Ze.selectionEnd=He),Ue()}),Ke(rt,He)},[Ue,t,Ke]),fe=Y=>{const Te=Y.target.value,ze=Y.target.selectionStart??Te.length;n(Te),Ue(),Ke(Te,ze)},R=l.useCallback(async Y=>{const Te=new Map;Array.from(Y.clipboardData.files||[]).forEach(He=>{He.type.startsWith("image/")&&Te.set(`${He.name}-${He.size}`,He)}),Array.from(Y.clipboardData.items||[]).forEach(He=>{if(He.kind==="file"&&He.type.startsWith("image/")){const Ze=He.getAsFile();Ze&&Te.set(`${Ze.name}-${Ze.size}`,Ze)}});const ze=Array.from(Te.values());if(ze.length===0||!C)return;Y.preventDefault();const it=Y.clipboardData.getData("text");it&&Je(it);let rt=0;for(const He of ze){const Ze=me.getState().attachedFiles.length;try{await X(He),me.getState().attachedFiles.length>Ze&&(rt+=1)}catch(q){console.error("Clipboard image attach failed",q),be.error(q instanceof Error?q.message:"Failed to attach image from clipboard")}}rt>0&&be.success(`Attached ${rt} image${rt>1?"s":""} from clipboard`)},[X,C,Je]),Q=Y=>{const Te=j.current?.selectionStart||0,it=t.substring(0,Te).lastIndexOf("@");if(it!==-1){const rt=t.substring(0,it)+Y.name+t.substring(Te);n(rt)}c(!1),u(""),j.current?.focus()},re=Y=>{const ze=j.current?.selectionStart??t.length,rt=t.substring(0,ze).lastIndexOf("#");if(rt!==-1){const He=t.substring(0,rt)+`#${Y} `+t.substring(ze);n(He);const Ze=rt+Y.length+2;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Ze,j.current.selectionEnd=Ze),Ue(),Ke(He,Ze)})}b(!1),w(""),j.current?.focus()},ce=Y=>{n(`/${Y.name} `);const Te=j.current;Te&&(Te._commandMetadata=Y),m(!1),h(""),setTimeout(()=>{j.current&&(j.current.focus(),j.current.setSelectionRange(j.current.value.length,j.current.value.length))},0)};l.useEffect(()=>{C&&j.current&&!we&&j.current.focus()},[C,we]),l.useEffect(()=>{F&&F!==C&&L()},[F,C,L]);const Z=Y=>{Y.preventDefault(),Y.stopPropagation(),C&&!o&&a(!0)},ne=Y=>{Y.preventDefault(),Y.stopPropagation(),Y.currentTarget===Y.target&&a(!1)},ae=async Y=>{if(Y.preventDefault(),Y.stopPropagation(),a(!1),!C)return;const Te=Array.from(Y.dataTransfer.files);let ze=0;for(const it of Te){const rt=me.getState().attachedFiles.length;try{await X(it),me.getState().attachedFiles.length>rt&&(ze+=1)}catch(He){console.error("File attach failed",He),be.error(He instanceof Error?He.message:"Failed to attach file")}}ze>0&&be.success(`Attached ${ze} file${ze>1?"s":""}`)},Me=l.useCallback(async Y=>{let Te=0;for(const ze of Y){const it=me.getState().attachedFiles.length;try{await z(ze.path,ze.name),me.getState().attachedFiles.length>it&&(Te+=1)}catch(rt){console.error("Server file attach failed",rt),be.error(rt instanceof Error?rt.message:"Failed to attach file")}}Te>0&&be.success(`Attached ${Te} file${Te>1?"s":""}`)},[z]),at=l.useRef(null),[zt,xt]=l.useState(!1),Nt=l.useCallback(async Y=>{let Te=0;const ze=Array.isArray(Y)?Y:Array.from(Y);for(const it of ze){const rt=me.getState().attachedFiles.length;try{await X(it),me.getState().attachedFiles.length>rt&&(Te+=1)}catch(He){console.error("File attach failed",He),be.error(He instanceof Error?He.message:"Failed to attach file")}}Te>0&&be.success(`Attached ${Te} file${Te>1?"s":""}`)},[X]),Ct=l.useCallback(async()=>{try{const Te=await(await fetch("/api/vscode/pick-files")).json(),ze=Array.isArray(Te?.files)?Te.files:[],it=Array.isArray(Te?.skipped)?Te.skipped:[];if(it.length>0){const He=it.map(Ze=>`${Ze?.name||"file"}: ${Ze?.reason||"skipped"}`).join(`
70
- `);be.error(`Some files were skipped:
71
- ${He}`)}const rt=ze.map(He=>{if(!He?.dataUrl)return null;try{const[Ze,q]=He.dataUrl.split(","),ie=He.mimeType||Ze?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!q)return null;const ee=atob(q),ue=new Uint8Array(ee.length);for(let et=0;et<ee.length;et++)ue[et]=ee.charCodeAt(et);const Qe=new Blob([ue],{type:ie});return new File([Qe],He.name||"file",{type:ie})}catch(Ze){return console.error("Failed to decode VS Code picked file",Ze),null}}).filter(Boolean);rt.length>0&&await Nt(rt)}catch(Y){console.error("VS Code file pick failed",Y),be.error(Y instanceof Error?Y.message:"Failed to pick files in VS Code")}},[Nt]),yt=l.useCallback(()=>{if(rs()){Ct();return}at.current?.click()},[Ct]),jt=l.useCallback(async Y=>{const Te=Y.target.files;Te&&(await Nt(Te),Y.target.value="")},[Nt]),Se="gap-x-1.5 gap-y-0",Be=rs(),Ve=we?"px-1.5 py-1.5":Be?"px-1.5 py-1":"px-2.5 py-1.5",Le=we?"h-9 w-9":Be?"h-[22px] w-[22px]":"h-7 w-7",pe=we?"h-5 w-5":Be?"h-4 w-4":"h-[18px] w-[18px]",Re=T(Le,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Ye=!we&&ct&&$e?e.jsx("button",{type:"button",onClick:Ge,className:T(Re,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(gr,{className:T(pe)})}):e.jsx("button",{type:we?"button":"submit",disabled:!ke||!C,onPointerDownCapture:Y=>{!we||Y.pointerType!=="touch"||!ke||!C||(B.current=!0,Y.preventDefault(),Y.stopPropagation(),ht())},onClick:Y=>{if(we){if(B.current){B.current=!1;return}Y.preventDefault(),ht()}},className:T(Re,ke&&C?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(uu,{className:T(pe)})}),At=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:at,type:"file",multiple:!0,className:"hidden",onChange:jt,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(Lh,{onFilesSelected:Me,multiSelect:!0,presentation:we||Be?"modal":"dropdown",open:zt,onOpenChange:xt,children:we||Be?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Xt,{children:[e.jsx(Jt,{asChild:!0,children:e.jsx("button",{type:"button",className:Re,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(mu,{className:T(pe,"text-current")})})}),e.jsxs(Zt,{align:"start",children:[e.jsxs(gt,{onSelect:()=>{requestAnimationFrame(()=>yt())},children:[e.jsx(Co,{}),"Attach files"]}),e.jsxs(gt,{onSelect:()=>{requestAnimationFrame(()=>{xt(!0)})},children:[e.jsx(fu,{}),"Attach from project"]})]})]})]})]}),nt=r?e.jsx("button",{type:"button",onClick:r,className:Re,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(_r,{className:T(pe,"text-current")})}):null,wt=e.jsxs(e.Fragment,{children:[At,nt]}),It=De.statusText;l.useEffect(()=>{const Y=!!De.wasAborted;!$.current&&Y&&!_e&&(dt(),C&&E(C)),$.current=Y},[E,C,_e,dt,De.wasAborted]),l.useEffect(()=>()=>{Fe.current&&(clearTimeout(Fe.current),Fe.current=null)},[]);const Et=we&&$e;return e.jsxs("form",{onSubmit:ht,className:"pt-0 pb-4 bottom-safe-area",children:[e.jsx(Zh,{isWorking:De.isWorking,statusText:It,isWaitingForPermission:De.isWaitingForPermission,wasAborted:De.wasAborted,abortActive:De.abortActive,completionId:De.lastCompletionId,isComplete:De.isComplete,showAbort:Et,onAbort:Ge,showAbortStatus:_e}),e.jsxs("div",{ref:k,className:T("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Z,onDragLeave:ne,onDrop:ae,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:Re,onClick:()=>yt(),title:"Attach files","aria-label":"Attach files",children:e.jsx(Co,{className:T(pe,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Th,{}),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:je,children:[p&&e.jsx(kc,{ref:A,searchQuery:f,onCommandSelect:ce,onClose:()=>m(!1)}),g&&e.jsx(Nc,{ref:D,searchQuery:x,onAgentSelect:re,onClose:()=>b(!1)}),i&&e.jsx(Ih,{ref:y,searchQuery:d,onFileSelect:Q,onClose:()=>c(!1)}),e.jsx(tr,{ref:j,"data-chat-input":"true",value:t,onChange:fe,onKeyDown:mt,onPaste:R,onPointerDownCapture:J,placeholder:C?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!C,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",we?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:S?`${S.height}px`:void 0,maxHeight:S?`${S.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:T("rounded-b-xl bg-transparent",Ve,we?"flex items-center gap-x-1.5":T("flex items-center justify-between",Se)),"data-chat-input-footer":"true",children:we?e.jsxs("div",{className:"flex w-full items-center gap-x-1.5",children:[e.jsx("div",{className:"flex items-center flex-shrink-0 gap-x-1",children:wt}),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(Ti,{className:T("w-full flex items-center justify-end min-w-0")})}),Ye]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("flex items-center flex-shrink-0",Se),children:wt}),e.jsxs("div",{className:T("flex items-center flex-1 justify-end",Se,"md:gap-x-3"),children:[e.jsx(Ti,{className:T("flex-1 min-w-0 justify-end")}),Ye]})]})})]})]})]})};function go({className:r,...s}){return e.jsx("div",{"data-slot":"skeleton",className:T("bg-accent animate-pulse rounded-xl",r),...s})}const Oi=({className:r="",width:s=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",c="shimmer-gradient";return e.jsxs("svg",{width:s,height:t,viewBox:"0 0 70 70",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:r,role:"img","aria-label":"OpenChamber logo",children:[n&&e.jsx("defs",{children:e.jsxs("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:i,stopOpacity:"1"}),e.jsx("stop",{offset:"50%",stopColor:i,stopOpacity:"0.7"}),e.jsx("stop",{offset:"100%",stopColor:i,stopOpacity:"1"}),e.jsx("animate",{attributeName:"x1",from:"-100%",to:"200%",dur:"4s",repeatCount:"indefinite"}),e.jsx("animate",{attributeName:"y1",from:"-100%",to:"200%",dur:"4s",repeatCount:"indefinite"}),e.jsx("animate",{attributeName:"x2",from:"0%",to:"300%",dur:"4s",repeatCount:"indefinite"}),e.jsx("animate",{attributeName:"y2",from:"0%",to:"300%",dur:"4s",repeatCount:"indefinite"})]})}),e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M0 13H35V58H0V13ZM26.25 22.1957H8.75V48.701H26.25V22.1957Z",fill:n?`url(#${c})`:i}),e.jsx("path",{d:"M43.75 13H70V22.1957H52.5V48.701H70V57.8967H43.75V13Z",fill:n?`url(#${c})`:i})]})},ig={'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"}},lg={'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 Bs{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Bs.instance||(Bs.instance=new Bs),Bs.instance}recordSessionStart(s){this.sessionStartTimes.set(s,Date.now())}getSessionStartTime(s){return this.sessionStartTimes.get(s)}shouldAnimateMessage(s,t){if(s.role!=="assistant"||this.seenMessageIds.has(s.id))return!1;const n=this.sessionStartTimes.get(t);if(!n)return this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created),!1;const o=s.time.created>n-5e3;return o||(this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created)),o}clearSession(s){this.sessionStartTimes.delete(s)}hasSessionTiming(s){return this.sessionStartTimes.has(s)}hasBeenAnimated(s){return this.seenMessageIds.has(s)}markMessageAsAnimated(s,t){this.seenMessageIds.add(s),this.messageCreationTimes.set(s,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 Ic(r){const s=r.colors.syntax,t=r.colors.surface;return{'code[class*="language-"]':{color:s.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:s.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:s.base.comment,fontStyle:"italic"},prolog:{color:s.base.comment},doctype:{color:s.base.comment},cdata:{color:s.base.comment},punctuation:{color:s.tokens?.punctuation||t.mutedForeground},property:{color:s.tokens?.variableProperty||s.base.variable},tag:{color:s.tokens?.tag||s.base.keyword},"attr-name":{color:s.tokens?.tagAttribute||s.base.variable},"attr-value":{color:s.tokens?.tagAttributeValue||s.base.string},boolean:{color:s.tokens?.boolean||s.base.number},number:{color:s.base.number},constant:{color:s.tokens?.constant||s.base.number},symbol:{color:s.tokens?.constant||s.base.number},string:{color:s.base.string},char:{color:s.base.string},function:{color:s.base.function},builtin:{color:s.tokens?.functionBuiltin||s.base.function},"class-name":{color:s.tokens?.className||s.base.type},namespace:{color:s.tokens?.namespace||s.base.type,opacity:.8},keyword:{color:s.base.keyword},atrule:{color:s.base.keyword},selector:{color:s.base.function},operator:{color:s.base.operator},variable:{color:s.base.variable},regex:{color:s.tokens?.regex||s.base.string},url:{color:s.base.function,textDecoration:"underline"},entity:{color:s.base.function,cursor:"help"},".language-css .token.string":{color:s.base.string},".style .token.string":{color:s.base.string},deleted:{color:r.colors.status.error,backgroundColor:r.colors.status.errorBackground},inserted:{color:r.colors.status.success,backgroundColor:r.colors.status.successBackground},title:{color:r.colors.primary.base,fontWeight:"bold"},"code-block":{color:s.base.string},"code-snippet":{color:s.base.string},list:{color:s.base.variable},hr:{color:t.mutedForeground},table:{color:s.base.function},blockquote:{color:t.mutedForeground,fontStyle:"italic"},important:{color:s.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:s.tokens?.decorator||s.base.function},annotation:{color:s.tokens?.decorator||s.base.function}}}const qt=({children:r,className:s})=>{const[t,n]=l.useState(!1);return l.useEffect(()=>{let o=null;const a=()=>n(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:T("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",s),children:r})},cg=({isUser:r,providerID:s,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=dc(s);return e.jsx(qt,{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:r?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Vn,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:c&&a?e.jsx("img",{src:a,alt:`${s} logo`,className:"h-4 w-4",style:{filter:o?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:i}):e.jsx(Wn,{className:"h-4 w-4",style:{color:`var(${_s(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",r?"text-primary":"text-foreground"),children:r?"You":n||"Assistant"}),!r&&t&&e.jsx("div",{className:T("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",_s(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},dg=l.memo(cg),Bi=(r,s)=>{const t=r[Symbol.toPrimitive];if(typeof t=="function")try{if(t()===s)return r}catch{}try{Object.defineProperty(r,"toString",{value:()=>s,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(r,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0})}catch{}return r},$i=()=>{if(!rs()||typeof window>"u")return ai;const r=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(r?.light&&r?.dark){const s=Bi({...r.light},`vscode-shiki-light:${String(r.light?.name??"theme")}`),t=Bi({...r.dark},`vscode-shiki-dark:${String(r.dark?.name??"theme")}`);return[s,t]}return ai},Fc=()=>{const[r,s]=l.useState($i);return l.useEffect(()=>{if(!rs()||typeof window>"u")return;const t=n=>{s($i())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),r},Pc=r=>{const s=[],t=[],n=r.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>s.push(i.innerText.trim()));const o=r.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const c=i.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:s,rows:t}},Rc=({headers:r,rows:s})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
72
- `)?`"${o.replace(/"/g,'""')}"`:o,n=[];return r.length>0&&n.push(r.map(t).join(",")),s.forEach(o=>n.push(o.map(t).join(","))),n.join(`
73
- `)},ug=({headers:r,rows:s})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return r.length>0&&n.push(r.map(t).join(" ")),s.forEach(o=>n.push(o.map(t).join(" "))),n.join(`
74
- `)},mg=({headers:r,rows:s})=>{if(r.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${r.map(t).join(" | ")} |`),n.push(`| ${r.map(()=>"---").join(" | ")} |`),s.forEach(o=>{const a=r.map((i,c)=>t(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
75
- `)},fg=(r,s,t)=>{const n=new Blob([s],{type:t}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=r,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},pg=({tableRef:r})=>{const[s,t]=l.useState(!1),[n,o]=l.useState(!1),a=l.useRef(null);l.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const i=async c=>{const d=r.current?.querySelector("table");if(d)try{const u=Pc(d),p=c==="csv"?Rc(u):ug(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([p],{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:s?e.jsx(Tt,{className:"size-3.5"}):e.jsx(Ls,{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"})]})]})},hg=({tableRef:r})=>{const[s,t]=l.useState(!1),n=l.useRef(null);l.useEffect(()=>{const a=i=>{n.current&&!n.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=r.current?.querySelector("table");if(i)try{const c=Pc(i),d=a==="csv"?Rc(c):mg(c);fg(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(c){console.error("Failed to download table:",c)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>t(!s),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(Go,{className:"size-3.5"})}),s&&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"})]})]})},gg=({children:r,className:s})=>{const t=l.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:t,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(pg,{tableRef:t}),e.jsx(hg,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:T("w-full border-collapse border border-border",s),"data-streamdown":"table",children:r})})]})},xg=({children:r,className:s,style:t,...n})=>{const[o,a]=l.useState(!1),i=l.useRef(null),c=l.useMemo(()=>{if(!t)return t;const p={...t},m=g=>{if(typeof g!="string")return{value:void 0,vars:{}};const[b,...x]=g.split(";").map(S=>S.trim()).filter(Boolean),w={};for(const S of x){const v=S.indexOf(":");if(v===-1)continue;const j=S.slice(0,v).trim(),k=S.slice(v+1).trim();!j.startsWith("--")||k.length===0||(w[j]=k)}return{value:b,vars:w}},f=m(t.backgroundColor);f.value&&(p.backgroundColor=f.value,p["--shiki-light-bg"]=f.value);for(const[g,b]of Object.entries(f.vars))p[g]=b;const h=m(t.color);h.value&&(p.color=h.value,p["--shiki-light"]=h.value);for(const[g,b]of Object.entries(h.vars))p[g]=b;return p},[t]),d=()=>i.current&&i.current.querySelector("code")?.innerText||"",u=async()=>{const p=d();if(p)try{await navigator.clipboard.writeText(p),a(!0),setTimeout(()=>a(!1),2e3)}catch(m){console.error("Failed to copy:",m)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:T(s),style:c,children:r}),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(Ls,{className:"size-3.5"})})})]})},Lc={pre:xg,table:gg},yg=({content:r,part:s,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const c=Fc(),d=l.useMemo(()=>`markdown-${s?.id?`part-${s.id}`:`message-${t}`}`,[t,s?.id]),u=i==="tool"?"streamdown-content streamdown-tool":"streamdown-content",p=e.jsx("div",{className:T("break-words",o),children:e.jsx(Sl,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:Lc,children:r})});return n?e.jsx(qt,{children:p},d):p},Wr=({content:r,className:s,variant:t="assistant"})=>{const n=Fc(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:T("break-words",s),children:e.jsx(Sl,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:Lc,children:r})})},bg={thinking:{label:"Thinking",Icon:Wn},justification:{label:"Justification",Icon:qo}},_c=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
76
- `).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
77
- `).trim(),wg=r=>{if(!r)return"";const s=r.trim(),t=s.indexOf(`
78
- `),n=s.indexOf("."),o=[t>=0?t:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?s.substring(0,a).trim():s},wa=({text:r,variant:s,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>wg(r),[r]),{label:c,Icon:d}=bg[s];return l.useEffect(()=>{r.trim().length!==0&&t?.("structural")},[t,o,r]),!r||r.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(vt,{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:c})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className: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(Xe,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:r})})]})},Oc=({part:r,onContentChange:s,messageId:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>_c(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(wa,{text:a,variant:"thinking",onContentChange:s,blockId:r.id||`${t}-reasoning`}):null},vg=r=>_c(r),jg=({part:r,messageId:s,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=r,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",u=l.useMemo(()=>a?vg(d):d,[d,a]),p=t==="streaming",m=t==="cooldown",f=l.useRef(p);if(p||m)return f.current=!0,null;const h=i.time;return!(h&&typeof h.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(wa,{text:u,variant:"justification",onContentChange:o,blockId:r.id||`${s}-reasoning-text`},r.id||`${s}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(yg,{content:u,part:r,messageId:s,isAnimated:n,isStreaming:!1})},r.id||`${s}-text`)},Sg=r=>`https://opencode.ai/docs/agents/#${encodeURIComponent(r)}`,kg=({part:r,messageId:s,agentMention:t})=>{const n=r,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,c]=l.useState(!1),[d,u]=l.useState(!1),p=l.useRef(null);l.useEffect(()=>{const h=p.current;h&&!i&&u(h.scrollHeight>h.clientHeight)},[a,i]);const m=l.useCallback(()=>{(d||i)&&c(h=>!h)},[d,i]);if(!a||a.trim().length===0)return null;const f=()=>{if(!t?.token||!a.includes(t.token))return a;const h=a.indexOf(t.token),g=a.slice(0,h),b=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[g,e.jsx("a",{href:Sg(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:x=>x.stopPropagation(),children:t.token}),b]})};return e.jsx("div",{className:T("break-words whitespace-pre-wrap font-sans typography-markdown",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:p,onClick:m,children:f()},r.id||`${s}-user-text`)},Ng=l.memo(kg),Cg=r=>{let s=r.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},Bc=r=>r?r.includes("<file_diagnostics>")||r.includes("This file has errors")||r.includes("please fix"):!1,Mg=r=>r?r.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",zi=(r,s)=>!r||typeof r!="object"?String(r):dp(r,s||""),xo=(r,s,t)=>{let n=Cg(r);if((s==="edit"||s==="multiedit")&&Bc(n)&&(n=Mg(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Ag=(r,s)=>{try{const t=r.trim().split(`
79
- `).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,c]=a,d=Math.floor(i.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:T("w-full min-w-0 font-mono space-y-0.5",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Ms.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}},Dg=(r,s,t)=>{try{const n=r.trim().split(`
80
- `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,c,d,u]=i,p=u!==void 0?d:"",m=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:p,content:m})}}),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:Ms.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",s?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:T("flex items-start gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},Eg=(r,s,t)=>{try{const n=r.trim().split(`
81
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",u=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Ms.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",s?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:T("pl-4 grid gap-1",s?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:T("flex items-center gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},i))]})}catch{return null}},Tg=(r,s)=>{try{const t=JSON.parse(r);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",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Ms.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}},Ig=(r,s,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:Ms.tool.popup,children:e.jsx(Wr,{content:r,variant:"tool"})})}catch{return null}},Fg=r=>{const s=r.split(`
82
- `);let t="";const n=[];let o=0;for(;o<s.length;){const a=s[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let p=d,m=o+1;for(;m<s.length&&!s[m].startsWith("@@")&&!s[m].startsWith("Index:");){const f=s[m];f.startsWith("+")?(u.push({type:"added",lineNumber:p,content:f.substring(1)}),p++):f.startsWith("-")?u.push({type:"removed",lineNumber:null,content:f.substring(1)}):f.startsWith(" ")&&(u.push({type:"context",lineNumber:p,content:f.substring(1)}),p++),m++}n.push({file:t,oldStart:c,newStart:d,lines:u}),o=m;continue}o++}return n},Bo=(r,s,t)=>ip(s,r,t),$c=r=>{const s="h-3.5 w-3.5 flex-shrink-0",t=r.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(pu,{className:s}):t==="write"||t==="create"||t==="file_write"?e.jsx(hu,{className:s}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(Mo,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Ws,{className:s}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(is,{className:s}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(gu,{className:s}):t==="glob"?e.jsx(xu,{className:s}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(Ao,{className:s}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(Ao,{className:s}):t==="todowrite"||t==="todoread"?e.jsx(yu,{className:s}):t.startsWith("git")?e.jsx(Yt,{className:s}):e.jsx(sa,{className:s})},Pg=(r,s,t=Date.now())=>{const o=(s?s-r:t-r)/1e3;return`${(o<.05&&s!==void 0?.1:o).toFixed(1)}s`},Rg=({start:r,end:s,active:t})=>{const[n,o]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:Pg(r,s,n)})},Lg=r=>{if(!r?.diff||typeof r.diff!="string")return null;const s=r.diff.split(`
83
- `);let t=0,n=0;for(const o of s)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&n++;return t===0&&n===0?null:{added:t,removed:n}},$o=(r,s,t)=>{if(t)return r.split("/").pop()||r;if(r.startsWith(s)){const n=r.substring(s.length);return n.startsWith("/")?n.substring(1):n}return r},_g=(r,s,t,n)=>{const o=s,a=o.metadata,i=o.input;if((r.tool==="edit"||r.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return $o(d,n,t)}if((r.tool==="read"||r.tool==="write")&&i){const d=i?.filePath||i?.file_path||i?.path;if(typeof d=="string")return $o(d,n,t)}if(r.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
84
- `)[0];return t?d.substring(0,50):d.substring(0,100)}if(r.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);const c=i?.description||a?.description||"title"in s&&s.title||"";return typeof c=="string"?c:""},zo=({children:r,maxHeightClass:s="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(Xe,{outerClassName:T("w-full min-w-0 flex-none overflow-hidden",s,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:r})}),Og=r=>{const s=r.state?.title;return typeof s=="string"&&s.trim().length>0?s:typeof r.tool=="string"&&r.tool.trim().length>0?r.tool:"tool"},Bg=r=>r.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),$g=({entries:r,isExpanded:s,hasPrevTool:t,hasNextTool:n,output:o})=>{const a=l.useMemo(()=>r.filter(f=>f.state?.status==="completed"),[r]),i=typeof o=="string"?Bg(o):"",c=i.length>0,[d,u]=l.useState(!1);if(a.length===0&&!c)return null;const p=s?a:a.slice(-6),m=Math.max(0,a.length-p.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:[a.length>0?e.jsx(zo,{maxHeightClass:s?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[m>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",m," more…"]}):null,p.map((f,h)=>{const g=typeof f.tool=="string"&&f.tool.trim().length>0?f.tool:"tool",b=Og(f),x=da(g).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:$c(g)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:x}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:b})]},f.id??`${g}-${h}`)})]})}):null,c?e.jsxs("div",{className:T("space-y-1",a.length>0&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:f=>f.stopPropagation(),onClick:f=>{f.stopPropagation(),u(h=>!h)},children:[d?e.jsx(vt,{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"})]}),d?e.jsx(zo,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Wr,{content:i,variant:"tool"})})}):null]}):null]})},zg=({diff:r,syntaxTheme:s,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Fg(r).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(ks,{style:s,language:qr(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))}),Hg=({content:r,syntaxTheme:s,filePath:t,displayPath:n})=>{const o=r.split(`
85
- `),a=qr(t??"")||Bo(r,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),c=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ks,{style:s,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))})]})},Wg=({content:r,filePath:s,displayPath:t})=>{const n=cp(s),o=s.toLowerCase().endsWith(".svg"),a=l.useMemo(()=>o&&!r.startsWith("data:")?`data:image/svg+xml;base64,${btoa(r)}`:r.startsWith("data:")?r:`data:${n};base64,${r}`,[r,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"}})})]})},Ug=({part:r,state:s,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const c=s,d=c.metadata,u=c.input,p=c.output,m=typeof p=="string"&&p.length>0,f=typeof p=="string"?p:"",h=typeof d?.diff=="string"?d.diff:null,g=r.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,b=r.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,x=r.tool==="write"&&!!b,w=g?Jl(g):!1,S=x?g?$o(g,o,n):"New file":null,v=l.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&r.tool==="bash"?zi(u,r.tool):typeof u.content=="string"?u.content??"":zi(u,r.tool),[u,r.tool]),j=v.trim().length>0,k=(A,D)=>e.jsx(zo,{maxHeightClass:D?.maxHeightClass,className:D?.className,disableHorizontal:D?.disableHorizontal,outerClassName:D?.outerClassName,children:A}),y=()=>{if(r.tool==="todowrite"||r.tool==="todoread"){if(s.status==="completed"&&m){const A=Tg(f,{unstyled:!0});return k(A??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return s.status==="error"&&"error"in s?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:s.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(r.tool==="list"&&m){const A=Ag(f,{unstyled:!0});return k(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(r.tool==="grep"&&m){const A=Dg(f,n,{unstyled:!0});return k(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(r.tool==="glob"&&m){const A=Eg(f,n,{unstyled:!0});return k(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(r.tool==="task"&&m)return k(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Wr,{content:f,variant:"tool"})}));if((r.tool==="web-search"||r.tool==="websearch"||r.tool==="search_web")&&m){const A=Ig(f,t,{unstyled:!0});return k(A??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(r.tool==="codesearch"&&m)return k(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Wr,{content:f,variant:"tool"})}));if((r.tool==="edit"||r.tool==="multiedit")&&(!m&&h||f.trim().length===0||Bc(f))&&h)return k(e.jsx(zg,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(m&&f.trim()){if(r.tool==="read"){const A=xo(f,r.tool,d),D=A.split(`
86
- `),N=typeof u?.offset=="number"?u.offset:0,C=typeof u?.limit=="number"?u.limit:void 0,M=E=>E.trim().startsWith("(");return k(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:D.map((E,F)=>{const W=M(E),L=N+F+1,K=!W&&(C===void 0||F<C);return e.jsxs("div",{className:T("typography-code font-mono flex w-full min-w-0",W&&"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:K?L:""}),e.jsx("div",{className:"flex-1 min-w-0",children:W?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(ks,{style:t,language:Bo(A,r.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})})]},F)})}),{className:"p-1"})}return k(e.jsx(ks,{style:t,language:Bo(xo(f,r.tool,d),r.tool,u),PreTag:"div",customStyle:{...pn.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:xo(f,r.tool,d)}),{className:"p-1"})}return k(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:r.tool==="todowrite"||r.tool==="todoread"?y():e.jsxs(e.Fragment,{children:[x&&w?e.jsx("div",{className:"my-1",children:k(e.jsx(Wg,{content:b,filePath:g,displayPath:S??"New file"}))}):x?e.jsx("div",{className:"my-1",children:k(e.jsx(Hg,{content:b,syntaxTheme:t,filePath:g,displayPath:S??"New file"}))}):j?e.jsx("div",{className:"my-1",children:k(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,r.tool!=="write"&&s.status==="completed"&&"output"in s&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),y()]}),s.status==="error"&&"error"in s&&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:s.error})]})]})})},vn=({part:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=r.state,u=St(W=>W.currentDirectory),p=r.tool.toLowerCase()==="task",m=d.status==="completed"||d.status==="error",f=d.status==="running"||d.status==="pending",h=d.status==="error",g=l.useRef(s);l.useEffect(()=>{!m&&!p||g.current!==s&&(g.current=s,typeof s=="boolean"&&a?.("structural"))},[s,m,p,a]);const b=d,x=b.metadata,w=b.input,S=b.time,v=l.useRef({}),j=l.useRef(r.id);if(j.current!==r.id&&(j.current=r.id,v.current={}),p){if(typeof S?.start=="number"){const W=v.current.start;(typeof W!="number"||S.start<W)&&(v.current.start=S.start)}typeof S?.end=="number"&&(v.current.end=S.end)}const k=p?v.current.start??S?.start:S?.start,y=p?v.current.end??S?.end:S?.end,A=l.useMemo(()=>{if(!p)return[];const W=x?.summary;return Array.isArray(W)?W.filter(L=>typeof L=="object"&&L!==null):[]},[p,x]),D=l.useRef(A.length);l.useEffect(()=>{p&&D.current!==A.length&&(D.current=A.length,a?.("structural"))},[p,a,A.length]);const N=r.tool==="edit"||r.tool==="multiedit"?Lg(x):null,C=_g(r,d,o,u),M=da(r.tool).displayName,E=l.useContext(ua),F=W=>{if(p||!E?.editor){t(r.id);return}let L;if((r.tool==="edit"||r.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(r.tool))&&(L=w?.filePath||w?.file_path||w?.path||x?.filePath||x?.file_path||x?.path),typeof L=="string"){W.stopPropagation();let K=L;L.startsWith("/")||(K=u.endsWith("/")?u+L:u+"/"+L),E.editor.openFile(K)}else t(r.id)};return!m&&!p?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:F,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:W=>{W.stopPropagation(),t(r.id)},children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:!p&&h?{color:"var(--status-error)"}:{},children:$c(r.tool)}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(vt,{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:!p&&h?{color:"var(--status-error)"}:{},children:M})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[C&&e.jsx("span",{className:T("truncate",o&&"max-w-[120px]"),children:C}),N&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",N.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",N.removed]})]}),typeof k=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(Rg,{start:k,end:typeof y=="number"?y:void 0,active:!!(p&&f&&typeof y!="number")})})]})]}),p&&(A.length>0||f||m)?e.jsx($g,{entries:A,isExpanded:s,hasPrevTool:i,hasNextTool:c,output:typeof b.output=="string"?b.output:void 0}):null,!p&&s?e.jsx(Ug,{part:r,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c}):null]})},Vg=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
87
- `).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
88
- `).trim(),Gg=({part:r,messageId:s,onContentChange:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>Vg(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(wa,{text:a,variant:"justification",onContentChange:t,blockId:r.id||`${s}-justification`}):null},qg=l.memo(Gg),Kg=r=>{const s={tools:r.filter(n=>n.kind==="tool").length,reasoning:r.filter(n=>n.kind==="reasoning").length,justifications:r.filter(n=>n.kind==="justification").length},t=[];return s.tools>0&&t.push(`${s.tools} tool${s.tools>1?"s":""}`),s.reasoning>0&&t.push(`${s.reasoning} reasoning`),s.justifications>0&&t.push(`${s.justifications} justification${s.justifications>1?"s":""}`),t.join(", ")},Hi=r=>[...r].sort((s,t)=>{const n=typeof s.endedAt=="number"?s.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}),Yg=r=>{const s={},t=r.filter(n=>n.kind==="tool");return t.forEach((n,o)=>{const a=n.part.id;a&&(s[a]={hasPrev:o>0,hasNext:o<t.length-1})}),s},Xg=({parts:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:p})=>{const m=l.useRef(s),[f,h]=l.useState(0);l.useEffect(()=>{if(m.current===s)return;const w=m.current===!1;m.current=s,c?.("structural"),s&&w&&h(S=>S+1)},[s,c]);const g=l.useMemo(()=>Hi(d?r.filter(w=>w.part.id&&u.has(w.id)):r),[r,d,u]),b=Kg(g),x=Yg(g);return g.length===0?null:e.jsx(qt,{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",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(xl,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(vt,{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"})]}),(b||p)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[b&&e.jsx("span",{className:"truncate block",children:b}),p&&(p.additions>0||p.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,p.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,p.deletions)]})]})]})]}),s&&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:g.map((w,S)=>{const v=w.part.id||`group-part-${S}`,j=x[v],k=`${v}-exp${f}`;switch(w.kind){case"tool":return e.jsx(qt,{children:e.jsx(vn,{part:w.part,isExpanded:a.has(v),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:j?.hasPrev??!1,hasNextTool:j?.hasNext??!1})},k);case"reasoning":return e.jsx(qt,{children:e.jsx(Oc,{part:w.part,messageId:w.messageId,onContentChange:c})},k);case"justification":return e.jsx(qt,{children:e.jsx(qg,{part:w.part,messageId:w.messageId,onContentChange:c})},k);default:return null}})})]})})},Jg=l.memo(Xg),Zg=({isMigrating:r,children:s,className:t})=>e.jsx("div",{className:T("w-full overflow-hidden",r&&"pointer-events-none",t),style:r?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:s}),yo=l.memo(Zg),zc=r=>{const s=r,t=s.text;return typeof t=="string"?t:s.content||s.value||""},Hc=r=>{if(r.type!=="text")return!1;const s=zc(r);return!s||s.trim().length===0},Qg=(r,s={})=>{const{includeReasoning:t=!0}=s;return r.filter(n=>!!n.synthetic||!t&&n.type==="reasoning"?!1:!(n.type==="patch"))},ex=(r,s)=>{const t=l.useRef(null),n=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(r);i.current=r;const c=l.useRef(s);c.current=s;const d=l.useRef(!1),u=s.size>0;return l.useEffect(()=>{r&&r.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 p=i.current;if(!p)return;const m=Array.from(c.current);m.length>0&&p.markPartsPreviewed(m)},300)},1e3)))},[u,r]),l.useEffect(()=>{r&&(!r.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,r]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},tx=new Set(["task"]),lr=r=>typeof r=="string"&&tx.has(r.toLowerCase()),sx=({messageId:r,parts:s,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d})=>{const[u,p]=l.useState(!1),m=l.useRef(null),f=l.useMemo(()=>s.filter(y=>y.type!=="text"?!1:!Hc(y)),[s]),h=d?.token;let g=!1;const b=!!a,x=!!i,w=!!(n??t),S=!!o,v=l.useCallback(()=>{m.current!==null&&typeof window<"u"&&(window.clearTimeout(m.current),m.current=null)},[]),j=l.useCallback(()=>{!w||!b||!S||typeof window>"u"||(v(),p(!0),m.current=window.setTimeout(()=>{p(!1),m.current=null},1800))},[b,v,S,w]);l.useEffect(()=>{S||(p(!1),v())},[v,S]);const k=l.useCallback(y=>{!a||!S||(y.stopPropagation(),y.preventDefault(),a(),w&&j())},[S,w,a,j]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:w&&b&&S?j:void 0,children:[b&&e.jsx(Ae,{type:"button",variant:"ghost",size:"icon","data-visible":u||x?"true":void 0,className:T("absolute z-10 flex h-7 w-7 items-center justify-center rounded-full border border-border/40 shadow-none bg-background/95 supports-[backdrop-filter]:bg-background/80 hover:bg-accent duration-150","opacity-0 pointer-events-none disabled:opacity-30 disabled:text-muted-foreground/40",S&&"group-hover/message:opacity-60 group-hover/message:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",(u||x)&&"opacity-100 pointer-events-auto"),style:{insetInlineEnd:"0.32rem",insetBlockStart:"-0.28rem"},disabled:!S,"aria-label":"Copy message text","aria-hidden":!S,onPointerDown:y=>y.stopPropagation(),onClick:k,onFocus:()=>{S&&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(Ls,{className:"h-3.5 w-3.5 text-foreground hover:text-primary focus-visible:text-primary"})}),e.jsxs("div",{className:"px-3",children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/90",children:f.map((y,A)=>{let D;return d&&h&&!g&&zc(y).includes(h)&&(D=d,g=!0),e.jsx(qt,{children:e.jsx(Ng,{part:y,messageId:r,isMobile:t,agentMention:D})},`user-text-${A}`)})}),e.jsx(jc,{files:s,onShowPopup:c})]})]})},rx=({messageId:r,parts:s,isMessageCompleted:t,syntaxTheme:n,isMobile:o,hasTouchInput:a,copiedCode:i,onCopyCode:c,expandedTools:d,onToggleTool:u,onShowPopup:p,streamPhase:m,allowAnimation:f,onContentChange:h,shouldShowHeader:g=!0,hasTextContent:b=!1,onCopyMessage:x,copiedMessage:w=!1,onAuxiliaryContentComplete:S,showReasoningTraces:v=!1,turnGroupingContext:j})=>{const[k,y]=l.useState(!1),A=l.useRef(null),D=!!x,N=!!w,C=!!(a??o),M=!t,E=l.useMemo(()=>s.filter(Se=>!Hc(Se)).filter(Se=>Se.type!=="compaction"),[s]),F=l.useMemo(()=>E.filter(Se=>Se.type==="tool"),[E]),W=l.useMemo(()=>E.filter(Se=>Se.type==="text"),[E]),L=me(Se=>Se.createSessionFromAssistantMessage),K=j?.isLastAssistantInTurn??!1,X=l.useMemo(()=>s.some(Se=>Se.type==="step-finish"&&Se.reason==="stop"),[s]),z=F.length>0,G=l.useMemo(()=>F.some(Se=>{const Ve=(Se.state??{})?.status;return Ve==="pending"||Ve==="running"||Ve==="started"}),[F]),H=l.useCallback(Se=>{const Be=Se.state??{},Ve=Be?.status;if(Ve==="pending"||Ve==="running"||Ve==="started")return!1;const Le=Be?.time??{},pe=typeof Le?.end=="number"?Le.end:void 0,Re=typeof Le?.start=="number"?Le.start:void 0;return!(typeof pe!="number"||typeof Re=="number"&&pe<Re)},[]),oe=l.useMemo(()=>F.length===0?!0:G?!1:F.every(Se=>H(Se)),[F,G,H]),ve=l.useMemo(()=>W.length===0?!0:W.every(Se=>typeof Se.time?.end=="number"),[W]),Ee=l.useMemo(()=>E.filter(Se=>Se.type==="reasoning"),[E]),Ie=l.useMemo(()=>Ee.length===0?!0:Ee.every(Se=>typeof Se.time?.end=="number"),[Ee]),de=l.useMemo(()=>{let Se=0,Be=0;return E.forEach(Ve=>{Ve.type==="step-start"?Se+=1:Ve.type==="step-finish"&&(Be+=1)}),{stepStarts:Se,stepFinishes:Be,hasOpenStep:Se>Be}},[E]).hasOpenStep,we=Ee.length>0&&z&&(G||de||!oe),De=l.useMemo(()=>z?W.length===0?de||G||!oe:!0:W.length>0?we:!1,[W.length,de,G,z,we,oe]),_e=M||De&&(!ve||!oe||G||de)||we,Ne=M||z&&(G||de||!oe),Fe=M||we,$=z||Ee.length>0,B=W.length===0,J=$&&B&&!Ne&&!Fe&&oe&&Ie,I=l.useRef(!1),_=l.useRef(!1);l.useEffect(()=>{_.current=!1},[r]),l.useEffect(()=>{if(!J){I.current=!1;return}I.current||(I.current=!0,S?.())},[J,S]),l.useEffect(()=>{if(M){_.current=!1;return}if(z){_.current=!1;return}Ee.length!==0&&(Fe||!Ie||_.current||(_.current=!0,h?.("structural")))},[M,z,h,Ie,Ee.length,Fe]);const U=!!b&&!M,xe=l.useCallback(()=>{A.current!==null&&typeof window<"u"&&(window.clearTimeout(A.current),A.current=null)},[]),ye=l.useCallback(()=>{!C||!D||!U||typeof window>"u"||(xe(),y(!0),A.current=window.setTimeout(()=>{y(!1),A.current=null},1800))},[D,xe,U,C]);l.useEffect(()=>{U||(y(!1),xe())},[xe,U]);const se=l.useCallback(Se=>{!x||!U||(Se.stopPropagation(),Se.preventDefault(),x(),C&&ye())},[U,C,x,ye]),O=l.useCallback(Se=>{Se.stopPropagation(),Se.preventDefault(),L&&L(r)},[L,r]);l.useEffect(()=>()=>{xe()},[xe]);const V=l.useMemo(()=>{const Se={},Be=F.filter(Ve=>lr(Ve.tool)||Ne?!1:H(Ve));return Be.forEach((Ve,Le)=>{Se[Ve.id]={hasPrev:Le>0,hasNext:Le<Be.length-1}}),Se},[F,Ne,H]),P=l.useMemo(()=>j?.activityParts??[],[j]),te=l.useMemo(()=>j?P.filter(Se=>Se.messageId===r):[],[P,r,j]),je=l.useMemo(()=>{const Se=new Map;return te.forEach(Be=>{Se.set(Be.part,Be)}),Se},[te]),ke=l.useMemo(()=>j?(v?P:P.filter(Be=>Be.kind==="tool")).filter(Be=>{if(Be.kind!=="tool")return!0;const Ve=Be.part.tool;return!lr(Ve)}):[],[P,v,j]),[$e,ct]=l.useState(!1);l.useEffect(()=>{j&&ke.length>1&&ct(!0)},[j,ke.length]);const ht=!!(j&&$e),mt=l.useMemo(()=>{if(!j)return[];if(!ht)return[];if(!j.isWorking)return[];const Se=[];return te.forEach(Be=>{if(j.previewedPartIds.has(Be.id)||!v&&Be.kind!=="tool")return;const Ve=Be.part;if(Be.kind==="tool"){const Le=Ve;if(lr(Le.tool)||Ne||!H(Le))return}else if(Be.kind==="reasoning"){if(!v||Fe||typeof Ve.time?.end!="number")return}else if(Be.kind==="justification"&&(!v||_e||typeof Ve.time?.end!="number"))return;Se.push(Be)}),Se},[te,H,_e,Fe,Ne,v,ht,j]),dt=l.useMemo(()=>{const Se=new Set;return mt.forEach(Be=>{Se.add(Be.id)}),Se},[mt]),{isAnimating:Ge}=ex(j,dt),tt=!!(j&&j.activityGroupAnchorMessageId===r&&ht&&ke.length>0),Ue=l.useMemo(()=>F.filter(Se=>lr(Se.tool)),[F]),Ke=l.useMemo(()=>{if(!j||!tt)return!1;if(!j.isWorking)return!0;const Se=j.previewedPartIds;return ke.some(Be=>Se.has(Be.id))},[tt,j,ke]),Je=l.useRef(null),fe=l.useRef(null);l.useEffect(()=>{Je.current=null,fe.current=null},[r]);const R=Date.now();Ue.length>0&&Je.current===null&&(Je.current=R),Ke&&fe.current===null&&(fe.current=R);const Q=!!(Ue.length>0&&Ke&&typeof Je.current=="number"&&typeof fe.current=="number"&&fe.current>Je.current),re=l.useMemo(()=>{const Se=[],Be=()=>{!j||!tt||Se.push(e.jsx(Jg,{parts:ke,isExpanded:j.isGroupExpanded,onToggle:j.toggleGroup,syntaxTheme:n,isMobile:o,expandedTools:d,onToggleTool:u,onShowPopup:p,onContentChange:h,isWorking:j.isWorking,previewedPartIds:j.previewedPartIds,diffStats:j.diffStats},"progressive-group"))};Q||Be(),Ue.forEach(Le=>{Se.push(e.jsx(qt,{children:e.jsx(vn,{part:Le,isExpanded:d.has(Le.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Le.id}`))}),Q&&Be();const Ve=[];return E.forEach((Le,pe)=>{const Re=je.get(Le);if(!Re||!j)return;let Oe=null,Ye=null;if(!ht){if(Re.kind==="tool"){const nt=Le;if(lr(nt.tool))return;const It=nt.state?.time,Et=H(nt);if(!(!Ne&&Et))return;const Te=V[nt.id];Ye=e.jsx(qt,{children:e.jsx(vn,{part:nt,isExpanded:d.has(nt.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:Te?.hasPrev??!1,hasNextTool:Te?.hasNext??!1})},`tool-${nt.id}`),Oe=Et&&typeof It?.end=="number"?It.end:null}Ye&&Ve.push({part:Le,index:pe,endTime:Oe,element:Ye});return}if(!j.isWorking||j.isGroupExpanded||j.previewedPartIds.has(Re.id)||!v&&Re.kind!=="tool")return;const At=dt.has(Re.id);switch(Re.kind){case"tool":{const nt=Le;if(lr(nt.tool))break;const It=nt.state?.time,Et=H(nt);if(!(!Ne&&Et))break;const Te=V[nt.id],ze=e.jsx(qt,{children:e.jsx(vn,{part:nt,isExpanded:d.has(nt.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:Te?.hasPrev??!1,hasNextTool:Te?.hasNext??!1})},`tool-${nt.id}`);Ye=At?e.jsx(yo,{isMigrating:Ge,children:ze},`migrating-tool-${nt.id}`):ze,Oe=Et&&typeof It?.end=="number"?It.end:null;break}case"reasoning":{if(!v)break;const nt=Le.time,wt=typeof nt?.end=="number";if(!(wt&&!Fe))break;const Et=e.jsx(qt,{children:e.jsx(Oc,{part:Le,messageId:r,onContentChange:h})},`reasoning-${pe}`);Ye=At?e.jsx(yo,{isMigrating:Ge,children:Et},`migrating-reasoning-${pe}`):Et,Oe=wt?nt?.end??null:null;break}case"justification":{if(!v)break;const nt=Le.time,wt=typeof nt?.end=="number";if(!(wt&&!_e))break;const Et=e.jsx(qt,{children:e.jsx(jg,{part:Le,messageId:r,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${pe}`);Ye=At?e.jsx(yo,{isMigrating:Ge,children:Et},`migrating-text-${pe}`):Et,Oe=wt?nt?.end??null:null;break}}Ye&&Ve.push({part:Le,index:pe,endTime:Oe,element:Ye})}),Ve.sort((Le,pe)=>Le.endTime===null&&pe.endTime===null?Le.index-pe.index:Le.endTime===null?1:pe.endTime===null?-1:Le.endTime-pe.endTime),Ve.forEach(({element:Le})=>{Se.push(Le)}),Se},[je,i,w,d,b,Ge,o,H,r,h,c,x,p,u,dt,_e,Fe,Ne,ht,g,v,n,V,j,ke,E,F,Ue,tt,Q]),ce=j?.turnId,Z=me(Se=>Se.currentSessionId),ne=lt(Se=>{if(!ce||!Z)return;const Be=Se.messages.get(Z);if(!Be)return;const Ve=Be.find(Re=>Re.info?.id===ce);if(!Ve)return;const pe=Ve.info.summary?.body;return typeof pe=="string"&&pe.trim().length>0?pe:void 0}),ae=typeof j?.summaryBody=="string"&&j.summaryBody.trim().length>0?j.summaryBody:ne,Me=l.useRef(void 0);ae&&ae.trim().length>0&&(Me.current=ae);const at=l.useRef(ce);at.current!==ce&&(at.current=ce,Me.current=void 0);const zt=Me.current,xt=j?.isLastAssistantInTurn&&zt&&zt.trim().length>0,Nt=b&&W.length>0&&X&&K,[Ct,yt]=l.useState(!1),jt=e.jsxs(e.Fragment,{children:[x&&e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Ae,{type:"button",variant:"ghost",size:"icon","data-visible":k||N?"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",!U&&"opacity-50",(k||N)&&"text-primary"),disabled:!U,"aria-label":"Copy message text","aria-hidden":!U,onPointerDown:Se=>Se.stopPropagation(),onClick:se,onFocus:()=>{U&&y(!0)},onBlur:()=>{N||y(!1)},children:N?e.jsx(Tt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ls,{className:"h-3.5 w-3.5"})})}),e.jsx(ut,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Ae,{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:Se=>Se.stopPropagation(),onClick:O,children:e.jsx(bu,{className:"h-4 w-4"})})}),e.jsx(ut,{sideOffset:6,children:"Start new session from this answer"})]})]});return e.jsx("div",{className:T("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:C&&D&&U?ye: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:[re,xt&&e.jsx(qt,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>yt(!0),onMouseLeave:()=>yt(!1),children:[e.jsx(Wr,{content:zt}),Nt&&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",Ct&&"opacity-100 pointer-events-auto"),children:jt})]})},"summary-body")]}),e.jsx(jc,{files:s,onShowPopup:p}),!xt&&Nt&&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})]})})},nx=({isUser:r,...s})=>r?e.jsx(sx,{messageId:s.messageId,parts:s.parts,isMobile:s.isMobile,hasTouchInput:s.hasTouchInput,hasTextContent:s.hasTextContent,onCopyMessage:s.onCopyMessage,copiedMessage:s.copiedMessage,onShowPopup:s.onShowPopup,agentMention:s.agentMention}):e.jsx(rx,{...s}),Wi=l.memo(nx),bo=r=>{const s=r,t=s?.clientRole,n=s?.role;return s?.userMessageMarker===!0||t==="user"||n==="user"||s?.origin==="user"||s?.source==="user"?{role:"user",isUser:!0}:{role:t||n||"assistant",isUser:!1}},ox=l.lazy(()=>Lr(()=>import("./ToolOutputDialog-BK6SvVkC.js"),__vite__mapDeps([2,0,1,3,4]))),ax=new Set(["task","edit","multiedit","write","bash"]),Ui=r=>typeof r=="string"&&ax.has(r.toLowerCase());function wo(r){const s=l.useRef({hasValue:!1,value:void 0});return!s.current.hasValue&&r!==void 0&&r!==null&&(s.current={hasValue:!0,value:r}),s.current.hasValue?s.current.value:r}const vs=(r,s)=>{if(typeof r=="object"&&r!==null)return r[s]},ix=({message:r,previousMessage:s,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=Dt(),{currentTheme:u}=kr(),p=l.useRef(null),m=me(ta(pe=>({lifecyclePhase:pe.messageStreamStates.get(r.info.id)?.phase??null,isStreamingMessage:(()=>{const Re=r.info.sessionID??pe.currentSessionId??null;return Re?(pe.streamingMessageIds.get(Re)??null)===r.info.id:!1})(),currentSessionId:pe.currentSessionId,getCurrentAgent:pe.getCurrentAgent,getSessionAgentSelection:pe.getSessionAgentSelection,getAgentModelForSession:pe.getAgentModelForSession,getSessionModelSelection:pe.getSessionModelSelection}))),{lifecyclePhase:f,isStreamingMessage:h,currentSessionId:g,getCurrentAgent:b,getSessionAgentSelection:x,getAgentModelForSession:w,getSessionModelSelection:S}=m,v=kt(pe=>pe.providers),j=Pe(pe=>pe.showReasoningTraces),k=Pe(pe=>pe.toolCallExpansion);l.useEffect(()=>{g&&Bs.getInstance().recordSessionStart(g)},[g]);const[y,A]=l.useState(null),[D,N]=l.useState(!1),[C,M]=l.useState(new Set),[E,F]=l.useState({open:!1,title:"",content:""});l.useEffect(()=>{M(new Set)},[r.info.id,k]);const L=l.useMemo(()=>bo(r.info),[r.info]).isUser,K=l.useMemo(()=>L?r.parts.map(pe=>pe.type==="compaction"?{type:"text",text:"/summarize"}:pe):r.parts,[L,r.parts]),X=l.useMemo(()=>{if(L||!s)return null;const pe=vs(s.info,"clientRole"),Re=vs(s.info,"role");if((typeof pe=="string"?pe:typeof Re=="string"?Re:void 0)!=="user")return null;const Ye=vs(s.info,"mode"),At=vs(s.info,"providerID"),nt=vs(s.info,"modelID"),wt=typeof Ye=="string"&&Ye.trim().length>0?Ye:void 0,It=typeof At=="string"&&At.trim().length>0?At:void 0,Et=typeof nt=="string"&&nt.trim().length>0?nt:void 0;return!wt&&!It&&!Et?null:{agentName:wt,providerId:It,modelId:Et}},[L,s]),z=l.useMemo(()=>{if(L)return;const pe=vs(r.info,"mode");if(typeof pe=="string"&&pe.trim().length>0)return pe;if(X?.agentName)return X.agentName;const Re=r.info.sessionID;if(!Re)return;const Oe=b(Re);return Oe||(x(Re)??void 0)},[L,r.info,X,b,x]),G=r.info.sessionID,H=L?null:vs(r.info,"providerID"),oe=L?null:vs(r.info,"modelID"),ve=l.useMemo(()=>{if(L||!G)return null;if(X?.providerId&&X?.modelId)return{providerId:X.providerId,modelId:X.modelId};if(z){const Re=w(G,z);if(Re?.providerId&&Re?.modelId)return Re}const pe=S(G);return pe?.providerId&&pe?.modelId?pe:null},[L,G,z,X,w,S]),Ee=l.useMemo(()=>L?null:typeof H=="string"&&H.trim().length>0?H:ve?.providerId??null,[L,H,ve]),Ie=l.useMemo(()=>L?null:typeof oe=="string"&&oe.trim().length>0?oe:ve?.modelId??null,[L,oe,ve]),ge=l.useMemo(()=>{if(!L&&Ee&&Ie&&v.length>0){const pe=v.find(Re=>Re.id===Ee);if(pe?.models&&Array.isArray(pe.models)){const Ye=pe.models.find(At=>At.id===Ie)?.name;return typeof Ye=="string"?Ye:void 0}}},[L,Ee,Ie,v]),de=wo(z),we=wo(Ee??void 0),De=wo(ge),_e=de??void 0,Ne=we??null,Fe=De??void 0,$=l.useMemo(()=>{const pe=r.info.time;return typeof pe?.completed=="number"?pe.completed:null},[r.info.time]),B=l.useMemo(()=>L?!0:!!($&&$>0),[L,$]),J=l.useMemo(()=>Qg(K,{includeReasoning:j}),[K,j]),I=l.useMemo(()=>L||B?J:[],[L,B,J]),_=l.useMemo(()=>L?[]:J.filter(pe=>pe.type==="text"),[L,J]),U=l.useMemo(()=>L?[]:J.filter(Re=>Re.type==="tool"),[L,J]),xe=l.useMemo(()=>{if(k==="collapsed"||k==="activity")return C;const pe=new Set;for(const Oe of U){const Ye=Oe.tool;Oe.id&&Ui(Ye)&&pe.add(Oe.id)}if(i?.isFirstAssistantInTurn)for(const Oe of i.activityParts){if(Oe.kind!=="tool")continue;const Ye=Oe.part;Ye.id&&Ui(Ye.tool)&&pe.add(Ye.id)}const Re=new Set(pe);for(const Oe of C)Re.has(Oe)?Re.delete(Oe):Re.add(Oe);return Re},[C,k,U,i]),ye=l.useMemo(()=>{if(!L)return;const pe=r.parts.find(At=>At.type==="agent");if(!pe)return;const Re=pe,Oe=typeof Re.name=="string"?Re.name:void 0;if(!Oe)return;const Ye=Re.source&&typeof Re.source.value=="string"&&Re.source.value.trim().length>0?Re.source.value:`#${Oe}`;return{name:Oe,token:Ye}},[L,r.parts]),O=l.useMemo(()=>{let pe=0,Re=0;return J.forEach(Oe=>{Oe.type==="step-start"?pe+=1:Oe.type==="step-finish"&&(Re+=1)}),{hasOpenStep:pe>Re}},[J]).hasOpenStep,V=l.useMemo(()=>L?!1:_.length===0||U.length===0?O:!0,[_.length,U.length,O,L]),P=u?.metadata.variant,te=l.useMemo(()=>P?P==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[P]),je=l.useMemo(()=>u?Ic(u):te?ig:lg,[u,te]),ke=l.useMemo(()=>L?!1:Bs.getInstance().shouldAnimateMessage(r.info,g||r.info.sessionID),[r.info,g,L]),$e=l.useMemo(()=>s?bo(s.info):null,[s]),ct=l.useMemo(()=>t?bo(t.info):null,[t]),ht=l.useMemo(()=>L||!$e?!0:$e.isUser,[L,$e]),mt=l.useMemo(()=>L||!ct?!1:!ct.isUser&&ct.role==="assistant",[L,ct]),dt=l.useMemo(()=>B?"completed":f||(h?"streaming":"completed"),[B,f,h]),Ge=l.useCallback(pe=>{navigator.clipboard.writeText(pe),A(pe),setTimeout(()=>A(null),2e3)},[]),tt=i?.turnId,Ue=lt(pe=>{if(!tt)return;const Re=r.info.sessionID;if(!Re)return;const Oe=pe.messages.get(Re);if(!Oe)return;const Ye=Oe.find(wt=>wt.info?.id===tt);if(!Ye)return;const nt=Ye.info.summary?.body;return typeof nt=="string"&&nt.trim().length>0?nt:void 0}),Ke=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:Ue,Je=l.useRef(void 0);Ke&&Ke.trim().length>0&&(Je.current=Ke);const fe=l.useRef(tt);fe.current!==tt&&(fe.current=tt,Je.current=void 0);const R=Je.current,Q=l.useMemo(()=>L?I.filter(Oe=>Oe.type==="text").map(Oe=>(Oe.text||Oe.content||"").trim()).filter(Oe=>Oe.length>0).join(`
89
- `).replace(/\n\s*\n+/g,`
90
- `):R&&R.trim().length>0?R:ql(I),[R,I,L]),re=Q.length>0,ce=l.useCallback(()=>{navigator.clipboard.writeText(Q),N(!0),setTimeout(()=>N(!1),2e3)},[Q]),Z=l.useCallback(pe=>{M(Re=>{const Oe=new Set(Re);return Oe.has(pe)?Oe.delete(pe):Oe.add(pe),Oe})},[]),ne=o??null,ae=l.useRef(!1),Me=l.useRef(!1),at=l.useRef(!1),zt=l.useRef(!1),xt=l.useRef(!1);l.useEffect(()=>{Me.current=!1,at.current=!1,zt.current=!1,xt.current=!1,ae.current=!1},[r.info.id]);const Nt=l.useCallback(()=>{L||ae.current||(ae.current=!0,n?.("structural"))},[L,n]),Ct=l.useCallback(pe=>{pe.image&&F(pe)},[]),yt=l.useCallback(pe=>{F(Re=>({...Re,open:pe}))},[]),jt=!!vs(r.info,"animationSettled"),Se=dt==="streaming",Be=l.useMemo(()=>L?!1:J.some(pe=>pe.type==="reasoning"),[L,J]),Ve=ke&&!jt&&!Se,Le=!L&&ke&&_.length>0&&!V;return l.useEffect(()=>{if(ne?.onStreamingCandidate){if(!Le){at.current&&(Be&&ne?.onReasoningBlock?ne.onReasoningBlock():ne?.onReservationCancelled&&ne.onReservationCancelled(),at.current=!1);return}xt.current||(xt.current=!0,ne.onStreamingCandidate(),at.current=!0)}},[ne,Le,Be]),l.useEffect(()=>{ne?.onAnimationStart&&Ve&&(zt.current||(ne.onAnimationStart(),zt.current=!0))},[ne,Ve]),l.useEffect(()=>{if(L)return;const pe=ne?.onAnimatedHeightChange;if(!pe||!(Ve||Le))return;const Oe=p.current;if(!Oe)return;if(typeof window>"u"||typeof ResizeObserver>"u"){pe(Oe.getBoundingClientRect().height);return}let Ye=null;const At=wt=>{if(typeof window>"u"){pe(wt);return}Ye!==null&&window.cancelAnimationFrame(Ye),Ye=window.requestAnimationFrame(()=>{pe(wt)})},nt=new ResizeObserver(wt=>{const It=wt[0];It&&At(It.contentRect.height)});return nt.observe(Oe),At(Oe.getBoundingClientRect().height),()=>{Ye!==null&&(window.cancelAnimationFrame(Ye),Ye=null),nt.disconnect()}},[Ve,L,ne,Le]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("group w-full",ht?"pt-2":"pt-0",L?"pb-2":mt?"pb-0":"pb-2"),"data-message-id":r.info.id,ref:p,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:L?e.jsx(qt,{children:e.jsx("div",{className:T("rounded-xl border bg-input/10 dark:bg-input/30 pt-2 pb-2.5 relative"),style:{borderColor:"color-mix(in srgb, var(--primary-muted, var(--primary)) 40%, var(--interactive-border, transparent))"},children:e.jsx(Wi,{messageId:r.info.id,parts:J,isUser:L,isMessageCompleted:B,syntaxTheme:je,isMobile:c,hasTouchInput:d,copiedCode:y,onCopyCode:Ge,expandedTools:C,onToggleTool:Z,onShowPopup:Ct,streamPhase:dt,allowAnimation:Ve,onContentChange:n,shouldShowHeader:!1,hasTextContent:re,onCopyMessage:ce,copiedMessage:D,showReasoningTraces:j,onAuxiliaryContentComplete:Nt,agentMention:ye})})}):e.jsxs("div",{children:[ht&&e.jsx(dg,{isUser:L,providerID:Ne,agentName:_e,modelName:Fe,isDarkTheme:te}),e.jsx(Wi,{messageId:r.info.id,parts:J,isUser:L,isMessageCompleted:B,syntaxTheme:je,isMobile:c,hasTouchInput:d,copiedCode:y,onCopyCode:Ge,expandedTools:xe,onToggleTool:Z,onShowPopup:Ct,streamPhase:dt,allowAnimation:Ve,onContentChange:n,shouldShowHeader:ht,hasTextContent:re,onCopyMessage:ce,copiedMessage:D,onAuxiliaryContentComplete:Nt,showReasoningTraces:j,agentMention:ye,turnGroupingContext:i})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(ox,{popup:E,onOpenChange:yt,syntaxTheme:je,isMobile:c})})]})},lx=l.memo(ix),cx=r=>{const s="h-3 w-3",t=r.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(Cs,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Ws,{className:s}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(Ao,{className:s}):e.jsx(sa,{className:s})},dx=r=>{const s=r.toLowerCase();return s==="edit"||s==="multiedit"||s==="str_replace"||s==="str_replace_based_edit_tool"?"edit":s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?"bash":s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?"webfetch":r},ux=({permission:r,onResponse:s})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=me(),{currentTheme:c}=kr(),d=l.useMemo(()=>Ic(c),[c]),u=async w=>{n(!0);try{await i(r.sessionID,r.id,w),a(!0),s?.(w)}catch{}finally{n(!1)}};if(o)return null;const p=r.type||"Unknown Tool",m=p.toLowerCase(),f=(w,S="")=>{const v=r.metadata[w];return typeof v=="string"?v:typeof v=="number"?String(v):S},h=w=>{const S=r.metadata[w];return typeof S=="number"?S:void 0},g=w=>!!r.metadata[w],b=dx(p),x=()=>{if(m==="bash"||m==="shell"||m==="shell_command"){const v=f("command")||f("cmd")||f("script"),j=f("description"),k=f("cwd")||f("working_directory")||f("directory")||f("path"),y=h("timeout"),A=r.title===v;return e.jsxs(e.Fragment,{children:[j&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:j}),k&&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:k})]}),y&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",y,"ms"]}),v&&!A&&e.jsx("div",{children:e.jsx(ks,{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(m==="edit"||m==="multiedit"||m==="str_replace"||m==="str_replace_based_edit_tool"){const v=f("path")||f("file_path")||f("filename")||f("filePath"),j=f("old_str")||f("oldString")||f("old_content")||f("before"),k=f("new_str")||f("newString")||f("new_content")||f("after"),y=f("changes")||f("diff"),A=g("replace_all")||g("replaceAll");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:"File Path:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:v})]}),A&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),y?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Changes:"}),e.jsx(Xe,{outerClassName:"max-h-64",className:"overflow-x-auto p-0",children:e.jsx(ks,{language:"diff",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:!1,children:y})})]}):e.jsxs(e.Fragment,{children:[j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Remove:"}),e.jsx(Xe,{outerClassName:"max-h-32 border border-red-500/20 rounded bg-red-500/5 p-2",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono text-red-600 dark:text-red-400 whitespace-pre-wrap break-all",children:j.length>500?j.substring(0,500)+"...":j})})]}),k&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Replace with:"}),e.jsx(Xe,{outerClassName:"max-h-32 border border-green-500/20 rounded bg-green-500/5 p-2",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono text-green-600 dark:text-green-400 whitespace-pre-wrap break-all",children:k.length>500?k.substring(0,500)+"...":k})})]})]})]})}if(m==="webfetch"||m==="fetch"||m==="curl"||m==="wget"){const v=f("url")||f("uri")||f("endpoint"),j=f("method")||"GET",k=r.metadata.headers&&typeof r.metadata.headers=="object"?r.metadata.headers:void 0,y=f("body")||f("data")||f("payload"),A=h("timeout"),D=f("format")||f("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:j}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:v})]})]}),k&&Object.keys(k).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(Xe,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(ks,{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(k,null,2)})})]}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(Xe,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(ks,{language:typeof y=="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 y=="object"?JSON.stringify(y,null,2):String(y)})})]}),(A||D)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[A&&e.jsxs("span",{children:["Timeout: ",A,"ms"]}),A&&D&&e.jsx("span",{children:" • "}),D&&e.jsxs("span",{children:["Response format: ",D]})]})]})}const w=f("command")||f("content")||f("action")||f("operation"),S=f("description");return e.jsxs(e.Fragment,{children:[S&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:S}),w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(Xe,{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(w)})})]}),Object.keys(r.metadata).length>0&&!w&&!S&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(Xe,{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(r.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(Or,{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:[cx(p),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:b})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[(()=>{let w="",S="text",v=!1;m==="bash"||m==="shell"||m==="shell_command"?(w=f("command")||f("cmd")||f("script"),S="bash",v=!0):m==="edit"||m==="multiedit"||m==="str_replace"||m==="str_replace_based_edit_tool"?(w=f("path")||f("file_path")||f("filename")||f("filePath"),v=!1):(m==="webfetch"||m==="fetch")&&(w=f("url")||f("uri")||f("endpoint"),v=!1);const j=r.title===w;return j&&w&&v?e.jsx("div",{className:"mb-3",children:e.jsx(ks,{language:S,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:w})}):j&&w&&!v?e.jsx("div",{className:"mb-3",children:e.jsx("code",{className:"typography-ui-label px-2 py-1 bg-muted/30 rounded block break-all",children:w})}):r.title?e.jsx("div",{className:T("typography-ui-label text-foreground mb-3",(v||w)&&"font-mono"),children:r.title}):null})(),x()]}),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:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Tt,{className:"h-3 w-3"}),"Allow Once"]}),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:w=>{w.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Nn,{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:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(ds,{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"})})]})]})})})},mx=new Set(["task"]),fx=r=>typeof r=="string"&&mx.has(r.toLowerCase()),px=r=>{const s=[];let t=null;return r.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(t={turnId:n.info.id,userMessage:n,assistantMessages:[]},s.push(t)):o==="assistant"&&t&&t.assistantMessages.push(n)}),s},hx=r=>{for(const s of r.assistantMessages)for(const t of s.parts)if(t.type==="step-finish"){const n=t.reason,o=s.info.finish;if(n==="stop"||o==="stop"){const a=s.parts.find(i=>i.type==="text");if(a){const i=a.text??a.content;if(typeof i=="string"&&i.trim().length>0)return i}}}},gx=r=>{const s=hx(r);let t;const o=r.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let f=0,h=0,g=0;o.forEach(b=>{if(!b)return;const x=typeof b.additions=="number"?b.additions:0,w=typeof b.deletions=="number"?b.deletions:0;(x!==0||w!==0)&&(g+=1),f+=x,h+=w}),g>0&&(t={additions:f,deletions:h,files:g})}let a=!1,i=!1;r.assistantMessages.forEach(f=>{f.parts.forEach(h=>{h.type==="tool"?a=!0:h.type==="reasoning"&&(i=!0)})});const c=[];let d=0;r.assistantMessages.forEach(f=>{const h=f.info.id;f.parts.forEach(g=>{const b=typeof g.id=="string"&&g.id.trim().length>0?g.id:`${h}-activity-${d++}`;if(g.type==="tool"){const w=g.state?.time,S=typeof w?.end=="number"?w.end:void 0;c.push({id:b,turnId:r.turnId,messageId:h,kind:"tool",part:g,endedAt:S});return}if(g.type==="reasoning"){const x=g.text??g.content;if(typeof x!="string"||x.trim().length===0)return;const w=g.time,S=typeof w?.end=="number"?w.end:void 0;c.push({id:b,turnId:r.turnId,messageId:h,kind:"reasoning",part:g,endedAt:S});return}})});const u=new Map;c.forEach(f=>{if(f.kind==="tool"){const h=f.part.tool;if(fx(h))return}u.set(f.messageId,(u.get(f.messageId)??0)+1)});let p,m=0;for(const f of r.assistantMessages)if(m+=u.get(f.info.id)??0,m>=2){p=f.info.id;break}return{activityParts:c,hasTools:a,hasReasoning:i,summaryBody:s,diffStats:t,activityGroupAnchorMessageId:p}},xx=r=>{const{isWorking:s}=Dc(),t=l.useMemo(()=>px(r),[r]),n=l.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=l.useMemo(()=>{const b=new Map;return t.forEach(x=>{b.set(x.userMessage.info.id,x),x.assistantMessages.forEach(w=>{b.set(w.info.id,x)})}),b},[t]),a=l.useMemo(()=>{const b=new Map;return t.forEach(x=>{b.set(x.turnId,gx(x))}),b},[t]),[i,c]=l.useState(()=>new Map),d=Pe(b=>b.toolCallExpansion),u=d==="activity"||d==="detailed",p=l.useCallback(b=>{const x=i.get(b);return x||{isExpanded:u,previewedPartIds:new Set}},[i,u]),m=l.useCallback(b=>{c(x=>{const w=new Map(x),S=w.get(b)??{isExpanded:u,previewedPartIds:new Set};return w.set(b,{...S,isExpanded:!S.isExpanded}),w})},[u]),f=l.useCallback((b,x)=>{x.length!==0&&c(w=>{const S=new Map(w),v=S.get(b)??{isExpanded:u,previewedPartIds:new Set},j=new Set(v.previewedPartIds);return x.forEach(k=>{k&&k.trim().length>0&&j.add(k)}),S.set(b,{...v,previewedPartIds:j}),S})},[]),h=l.useCallback(b=>o.get(b),[o]),g=l.useCallback(b=>{const x=o.get(b);if(!x||!x.assistantMessages.some(W=>W.info.id===b))return;const S=a.get(x.turnId),v=S?.activityParts??[],j=!!S?.hasTools,k=!!S?.hasReasoning,y=S?.summaryBody,A=S?.diffStats,D=x.assistantMessages[0]?.info.id,N=b===D,C=x.assistantMessages[x.assistantMessages.length-1]?.info.id,M=b===C,E=p(x.turnId),F=s&&n===x.turnId;return{turnId:x.turnId,isFirstAssistantInTurn:N,isLastAssistantInTurn:M,summaryBody:y,activityParts:v,hasTools:j,hasReasoning:k,diffStats:A,activityGroupAnchorMessageId:S?.activityGroupAnchorMessageId,isWorking:F,isGroupExpanded:E.isExpanded,previewedPartIds:E.previewedPartIds,toggleGroup:()=>m(x.turnId),markPartsPreviewed:W=>f(x.turnId,W)}},[p,n,f,o,s,m,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:g}},yx=({messages:r,permissions:s,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:c,pendingAnchorId:d})=>{l.useEffect(()=>{s.length!==0&&t("permission")},[s,t]);const u=l.useMemo(()=>r.filter(m=>!Oo(m.parts)),[r]),{getContextForMessage:p}=xx(u);return e.jsxs("div",{children:[o&&e.jsx("div",{className:"flex justify-center py-3",children:a?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:i,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((m,f)=>e.jsx(lx,{message:m,previousMessage:f>0?u[f-1]:void 0,nextMessage:f<u.length-1?u[f+1]:void 0,onContentChange:t,animationHandlers:n(m.info.id),scrollToBottom:c,isPendingAnchor:d===m.info.id,turnGroupingContext:p(m.info.id)},m.info.id))}),s.length>0&&e.jsx("div",{children:s.map(m=>e.jsx(ux,{permission:m},m.id))})]})},bx=l.memo(yx);function wx(...r){return s=>{r.forEach(t=>{typeof t=="function"?t(s):t&&typeof t=="object"&&(t.current=s)})}}const Wc=l.forwardRef(({orientation:r="vertical",offset:s=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:c,children:d,...u},p)=>{const m=l.useRef(null),f=l.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const g=l.useMemo(()=>{const S={...i};return S["--scroll-shadow-size"]=`${t}px`,S},[t,i]),b=l.useCallback((S,v,j,k,y)=>{const A=`${k}${y.charAt(0).toUpperCase()}${y.slice(1)}Scroll`;v&&j?(S.dataset[A]="true",S.removeAttribute(`data-${k}-scroll`),S.removeAttribute(`data-${y}-scroll`)):(S.dataset[`${k}Scroll`]=String(v),S.dataset[`${y}Scroll`]=String(j),S.removeAttribute(`data-${k}-${y}-scroll`))},[]),x=l.useCallback(S=>{["top","bottom","top-bottom","left","right","left-right"].forEach(v=>{S.removeAttribute(`data-${v}-scroll`)})},[]),w=l.useCallback(()=>{const S=m.current;if(!S)return;if(!n){x(S);return}const v=r==="vertical"?S.scrollTop>s:S.scrollLeft>s;let j=r==="vertical"?S.scrollTop+S.clientHeight+s<S.scrollHeight:S.scrollLeft+S.clientWidth+s<S.scrollWidth;o&&r==="vertical"&&(j=!1),b(S,v,j,r==="vertical"?"top":"left",r==="vertical"?"bottom":"right");const k=v&&j?"both":v?r==="vertical"?"top":"left":j?r==="vertical"?"bottom":"right":"none";k!==f.current&&(f.current=k,a?.(k))},[x,o,n,s,a,r,b]);return l.useEffect(()=>{const S=m.current;if(!S)return;const v=()=>w(),j=typeof ResizeObserver<"u"?new ResizeObserver(()=>w()):null,k=typeof MutationObserver<"u"?new MutationObserver(()=>w()):null;return w(),S.addEventListener("scroll",v,{passive:!0}),j?.observe(S),k?.observe(S,{childList:!0,subtree:!0,characterData:!0}),()=>{S.removeEventListener("scroll",v),j?.disconnect(),k?.disconnect()}},[w]),e.jsx("div",{...u,ref:wx(m,p),className:c,"data-orientation":r,"data-scroll-shadow":h??!0,style:g,children:d})});Wc.displayName="ScrollShadow";const vx=160,jx=({containerRef:r})=>{const[s,t]=l.useState(!0),n=l.useRef(!0),o=l.useRef(!1),a=l.useRef(null),i=l.useRef(null),c=l.useRef(0),d=l.useRef(0),u=l.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),p=l.useCallback(v=>{const j=r.current;if(!j){u();return}i.current===null&&(i.current=v);const k=Math.min(1,(v-i.current)/vx),y=1-Math.pow(1-k,3),A=c.current,D=d.current,N=A+(D-A)*y;if(j.scrollTop=N,k<1){a.current=window.requestAnimationFrame(p);return}j.scrollTop=D,u(),n.current&&(n.current=!1,t(!1))},[u,r,t]),m=l.useCallback((v,j)=>{const k=r.current;if(!k)return;const y=Math.max(0,v),A=j?.instant??!1;if(o.current=!1,typeof window>"u"||A){u(),k.scrollTop=y;const N=y<=1;n.current!==N&&(n.current=N,t(N));return}if(u(),Math.abs(y-k.scrollTop)<=.5){k.scrollTop=y;const N=y<=1;n.current!==N&&(n.current=N,t(N));return}c.current=k.scrollTop,d.current=y,i.current=null,a.current=window.requestAnimationFrame(p)},[u,r,p,t]),f=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),g=l.useCallback(()=>o.current,[]),b=l.useCallback(()=>r.current?.scrollTop??0,[r]),x=l.useCallback(()=>r.current?.scrollHeight??0,[r]),w=l.useCallback(()=>r.current?.clientHeight??0,[r]),S=l.useCallback(()=>{const v=r.current;if(!v)return;o.current&&a.current!==null&&u();const j=v.scrollTop<=1;n.current!==j&&(n.current=j,t(j))},[u,r]);return l.useEffect(()=>{const v=r.current;if(v)return v.addEventListener("wheel",h,{passive:!0}),v.addEventListener("touchstart",h,{passive:!0}),()=>{v.removeEventListener("wheel",h),v.removeEventListener("touchstart",h)}},[r,h]),l.useEffect(()=>()=>{u()},[u]),l.useMemo(()=>({handleScroll:S,scrollToPosition:m,forceManualMode:f,isAtTop:s,isManualOverrideActive:g,getScrollTop:b,getScrollHeight:x,getClientHeight:w}),[S,m,f,s,g,b,x,w])},Vi=typeof window<"u"?l.useLayoutEffect:l.useEffect,Gi=50,qi=40,Sx=.2,kx=.1,Nx=150,as=r=>{const s=r.info;return typeof s?.id=="string"?s.id:null},Cx=r=>{const s=r.info;if(s?.userMessageMarker===!0)return!0;const t=s?.clientRole,n=s?.role;return t==="user"||n==="user"},Mx=({currentSessionId:r,sessionMessages:s,updateViewportAnchor:t,isSyncing:n,isMobile:o,sessionActivityPhase:a})=>{const i=l.useRef(null),c=jx({containerRef:i}),[d,u]=l.useState(null),[p,m]=l.useState(0),[f,h]=l.useState(!1),[g,b]=l.useState(null),x=l.useRef(null),w=l.useRef(null),S=l.useRef(s.length),v=l.useRef(s.length>0?as(s[0]):null),j=l.useRef(s.length>0?as(s[s.length-1]):null),k=l.useRef(0),y=l.useRef(0),A=l.useRef(void 0),D=l.useRef(null),N=l.useRef(!1),C=l.useRef(!1),M=r?a?.get(r)??"idle":"idle",E=l.useCallback(ge=>{const de=Math.max(0,ge);k.current!==de&&(k.current=de,m(de))},[]),F=l.useCallback(()=>{const ge=i.current;ge&&(y.current=ge.clientHeight)},[]),W=l.useCallback(()=>{if(!d)return null;const ge=i.current;return ge?ge.querySelector(`[data-message-id="${d}"]`):null},[d]),L=l.useCallback(()=>{const ge=i.current,de=k.current;if(!ge||de<=0)return!0;const we=ge.scrollHeight-de;return ge.scrollTop+ge.clientHeight<we},[]),K=l.useCallback((ge,de)=>{const we=ge.offsetHeight,De=ge.offsetTop;if(we>de*Sx){const Ne=de*kx;return De+we-Ne}else return De-Gi},[]),X=l.useCallback(()=>{const ge=i.current;if(!ge||!D.current)return;const de=W();if(!de)return;const we=ge.clientHeight,De=ge.scrollHeight,Ne=K(de,we)+we,Fe=k.current,$=De-Fe;if(!N.current&&$<Ne){const B=Ne-$;B>Fe&&E(B)}},[K,W,E]),z=l.useCallback(()=>{const ge=i.current;if(!ge){h(!1);return}if(g){h(!1);return}if(!(ge.scrollHeight>ge.clientHeight)){h(!1);return}const we=ge.scrollHeight-ge.scrollTop-ge.clientHeight,De=k.current;if(De>0){const _e=ge.scrollHeight-De,Ne=ge.scrollTop+ge.clientHeight;h(Ne<_e)}else h(we>qi)},[g]),G=l.useCallback(ge=>{const de=i.current;if(!de)return;const we=de.scrollHeight-de.scrollTop-de.clientHeight;if(C.current&&M==="idle"&&!n&&!ge?.force&&we>qi)return;ge?.force&&(C.current=!1);const _e=de.scrollHeight-de.clientHeight;c.scrollToPosition(Math.max(0,_e),ge)},[M,n,c]),H=l.useCallback(ge=>{if(x.current===ge)return;x.current=ge,b(ge);const de=i.current;if(!de){b(null);return}const we=de.scrollHeight,De=k.current,_e=we-De,Ne=y.current>0?y.current:de.clientHeight,$=_e-Gi,B=$+Ne;let J=0;_e<B&&(J=B-_e),J!==De&&E(J),N.current=!0,window.requestAnimationFrame(()=>{c.scrollToPosition($,{instant:!0}),window.requestAnimationFrame(()=>{b(null)})})},[c,E]),oe=l.useCallback(ge=>{const de=i.current;if(!de||!r)return;ge?.isTrusted&&(C.current=!0),c.handleScroll(),z(),M==="idle"&&k.current>0&&L()&&(E(0),D.current=null,u(null));const{scrollTop:we,scrollHeight:De,clientHeight:_e}=de,Ne=(we+_e/2)/Math.max(De,1),Fe=Math.floor(Ne*s.length);t(r,Fe)},[r,M,L,c,s.length,z,E,t]);l.useEffect(()=>{const ge=i.current;if(ge)return ge.addEventListener("scroll",oe,{passive:!0}),()=>{ge.removeEventListener("scroll",oe)}},[oe]),Vi(()=>{if(typeof window>"u")return;F();const ge=()=>{A.current!==void 0&&window.clearTimeout(A.current),A.current=window.setTimeout(()=>{F()},Nx)};return window.addEventListener("resize",ge),()=>{window.removeEventListener("resize",ge),A.current!==void 0&&window.clearTimeout(A.current)}},[F]),l.useEffect(()=>{r&&r!==w.current&&(w.current=r,Bs.getInstance().recordSessionStart(r),S.current=s.length,v.current=s.length>0?as(s[0]):null,j.current=s.length>0?as(s[s.length-1]):null,x.current=null,D.current=null,N.current=!1,u(null),k.current=0,m(0),b(null),h(!1),C.current=!1)},[r,s.length]),Vi(()=>{if(n){S.current=s.length,v.current=s.length>0?as(s[0]):null,j.current=s.length>0?as(s[s.length-1]):null;return}if(w.current!==r)return;const ge=S.current,de=s.length;if(de>ge&&ge>0){const we=v.current,De=as(s[0]),_e=as(s[de-1]),Ne=j.current,Fe=we!==null&&De!==we,$=Ne!==null&&_e!==Ne,B=Fe&&!$,J=$&&!Fe;if(B){D.current=null,N.current=!1,u(null),E(0),S.current=de,v.current=De,j.current=_e;return}if(J){const _=s.slice(ge,de).find(Cx);if(_){const U=as(_);U&&(D.current=U,u(U),H(U))}else X()}}S.current=de,v.current=s.length>0?as(s[0]):null,j.current=s.length>0?as(s[s.length-1]):null},[r,n,X,H,s]),l.useEffect(()=>{const ge=i.current;if(!ge||typeof ResizeObserver>"u")return;const de=new ResizeObserver(()=>{X(),z()});return de.observe(ge),()=>{de.disconnect()}},[X,z]),l.useEffect(()=>{if(typeof window>"u"){z();return}const ge=window.requestAnimationFrame(()=>{z()});return()=>{window.cancelAnimationFrame(ge)}},[r,s.length,z]),l.useEffect(()=>{d&&(X(),z())},[d,X,z]),l.useEffect(()=>{M==="idle"&&k.current>0&&L()&&(E(0),D.current=null,N.current=!1,u(null))},[M,L,E]),l.useEffect(()=>{z()},[p,z]);const ve=l.useRef(new Map),Ee=l.useCallback(()=>{X(),z()},[X,z]),Ie=l.useCallback(ge=>{const de=ve.current.get(ge);if(de)return de;const we={onChunk:()=>{X()},onComplete:()=>{X()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{X()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return ve.current.set(ge,we),we},[X]);return{scrollRef:i,handleMessageContentChange:Ee,getAnimationHandlers:Ie,showScrollButton:f,scrollToBottom:G,spacerHeight:p,pendingAnchorId:g,hasActiveAnchor:d!==null}},Ax=()=>{const{currentSessionId:r,messages:s,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,sessionMemoryState:d,isSyncing:u,messageStreamStates:p,trimToViewportWindow:m,sessionActivityPhase:f}=me(),h=l.useMemo(()=>r?n.get(r)??null:null,[r,n]),{isMobile:g}=Dt(),b=l.useMemo(()=>r?s.get(r)||[]:[],[r,s]),x=l.useMemo(()=>r?t.get(r)||[]:[],[r,t]),{scrollRef:w,handleMessageContentChange:S,getAnimationHandlers:v,showScrollButton:j,scrollToBottom:k,spacerHeight:y,pendingAnchorId:A,hasActiveAnchor:D}=Mx({currentSessionId:r,sessionMessages:b,updateViewportAnchor:c,isSyncing:u,isMobile:g,sessionActivityPhase:f}),C=!!l.useMemo(()=>r?d.get(r)??null:null,[r,d])?.hasMoreAbove,[M,E]=l.useState(!1);l.useEffect(()=>{E(!1)},[r]);const F=l.useRef(null);l.useLayoutEffect(()=>{if(!r||r===F.current)return;F.current=r;const L=w.current;L&&(L.scrollTop=L.scrollHeight-L.clientHeight)},[r,w]);const W=l.useCallback(async()=>{if(!r||M)return;const L=w.current,K=L?.scrollHeight??null,X=L?.scrollTop??null;E(!0);try{if(await i(r,"up"),L&&K!==null&&X!==null){const z=L.scrollHeight-K;L.scrollTop=X+z}}finally{E(!1)}},[r,M,i,w]);return l.useEffect(()=>{if(!r||(s.has(r)?s.get(r)??[]:[]).length>0)return;(async()=>{try{await a(r)}finally{typeof window>"u"?k():window.requestAnimationFrame(()=>{k()})}})()},[r,a,s,k]),r?o&&b.length===0&&!h&&!s.has(r)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:g?{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(K=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(go,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(go,{className:"h-4 w-24"}),e.jsx(go,{className:"h-20 w-full"})]})]},K))})}),e.jsx(ho,{scrollToBottom:k})]}):b.length===0&&!h?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:g?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Oi,{width:140,height:140,className:"opacity-20",isAnimated:!0})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(ho,{scrollToBottom:k})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:g?{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(Wc,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:w,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!A,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(bx,{messages:b,permissions:x,onMessageContentChange:S,getAnimationHandlers:v,hasMoreAbove:C,isLoadingOlder:M,onLoadOlder:W,scrollToBottom:k,pendingAnchorId:A}),y>0&&D&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:y},"aria-hidden":"true"})]})}),e.jsx(ca,{containerRef:w})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[j&&b.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ae,{variant:"outline",size:"sm",onClick:()=>k({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(vr,{className:"h-4 w-4"})})}),e.jsx(ho,{scrollToBottom:k})]})]}):e.jsx("div",{className:"flex flex-col h-full bg-background",style:g?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Oi,{width:140,height:140,className:"opacity-20",isAnimated:!0})})})};class Dx extends l.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,t){this.setState({error:s,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(ba,{className:"w-full max-w-md",children:[e.jsx(sc,{className:"text-center",children:e.jsxs(rc,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(wu,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(nc,{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(Ae,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ds,{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 Ho=()=>{const r=me(s=>s.currentSessionId);return e.jsx(Dx,{sessionId:r||void 0,children:e.jsx(Ax,{})})},Ki=12,Ex=[{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"}],Tx=({isActive:r,burstKey:s=0,className:t,durationMs:n=900,bursts:o=Ex,onComplete:a})=>{const i=le.useRef(!1);le.useEffect(()=>{!r&&i.current&&a?.(),r&&(i.current=!0)},[r,a]);const c=le.useMemo(()=>Array.from({length:Ki},(d,u)=>{const p=Math.PI*2*u/Ki;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return r?e.jsx("div",{className:T("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:c.map((p,m)=>{const f=p.x*d.radius,h=p.y*d.radius,g={"--translate-x":`${f}px`,"--translate-y":`${h}px`,"--particle-delay":`${p.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:g},`${d.id}-${m}-${s}`)})},`${d.id}-${s}`)})}):null},Ix=({durationMs:r=3400}={})=>{const[s,t]=le.useState({isActive:!1,cycle:0}),n=le.useRef(null),o=le.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=le.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=le.useCallback(()=>{o(),t(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{t(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},r)},[o,r]);return le.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:i,dismissFireworks:a}},Uc=l.createContext(void 0),Yi=({children:r})=>{const{isActive:s,burstKey:t,triggerFireworks:n,dismissFireworks:o}=Ix(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Uc.Provider,{value:a,children:[r,e.jsx(Tx,{isActive:s,burstKey:t})]})},Fx=()=>{const r=l.useContext(Uc);if(!r)throw new Error("useFireworksCelebration must be used within FireworksProvider");return r},Px=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Rx=({currentBranch:r,localBranches:s,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:i=!1})=>{const[c,d]=l.useState(!1),[u,p]=l.useState(""),[m,f]=l.useState(!1),[h,g]=l.useState(""),[b,x]=l.useState(!1),w=l.useRef(null),S=l.useMemo(()=>Px(h),[h]),v=l.useMemo(()=>{const N=u.toLowerCase();return N?s.filter(C=>C.toLowerCase().includes(N)):s},[u,s]),j=l.useMemo(()=>{const N=u.toLowerCase();return N?t.filter(C=>C.toLowerCase().includes(N)):t},[u,t]),k=N=>{if(N===r){d(!1);return}o(N),d(!1),p("")},y=()=>{f(!0),setTimeout(()=>w.current?.focus(),50)},A=async()=>{if(!(!S||b)){x(!0);try{await a(S),g(""),f(!1),d(!1)}finally{x(!1)}}},D=()=>{g(""),f(!1)};return l.useEffect(()=>{c||(p(""),f(!1),g(""))},[c]),e.jsxs(Xt,{open:c,onOpenChange:d,children:[e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Jt,{asChild:!0,children:e.jsxs(Ae,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx(Yt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:r||"Detached HEAD"}),e.jsx(vt,{className:"size-4 opacity-60"})]})})}),e.jsxs(ut,{sideOffset:8,children:["Switch branch (",s.length," local · ",t.length," remote)"]})]}),e.jsx(Zt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(hc,{className:"h-full min-h-0",children:[e.jsx(gc,{placeholder:"Search branches...",value:u,onValueChange:p}),e.jsxs(xc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(yc,{children:"No branches found."}),e.jsx(pr,{children:m?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:w,placeholder:"New branch name",value:h,onChange:N=>g(N.target.value),onKeyDown:N=>{N.key==="Enter"?(N.preventDefault(),A()):N.key==="Escape"&&(N.preventDefault(),D())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:A,disabled:!S||b,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:b?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(os,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:D,disabled:b,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(ds,{className:"size-4"})})]}):e.jsxs(Ft,{onSelect:y,children:[e.jsx(os,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(On,{}),e.jsxs(pr,{heading:"Local branches",children:[v.map(N=>e.jsxs(Ft,{onSelect:()=>k(N),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:N}),(n?.[N]?.ahead||n?.[N]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[N].ahead||0," ahead ·"," ",n[N].behind||0," behind"]})]}),r===N&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${N}`)),v.length===0&&e.jsx(Ft,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(On,{}),e.jsxs(pr,{heading:"Remote branches",children:[j.map(N=>e.jsx(Ft,{onSelect:()=>k(N),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:N})},`remote-${N}`)),j.length===0&&e.jsx(Ft,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},Lx=({syncAction:r,onFetch:s,onPull:t,onPush:n,disabled:o})=>{const a=o||r!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsxs(Ae,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[r==="fetch"?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(qn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(ut,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsxs(Ae,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[r==="pull"?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(vr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(ut,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsxs(Ae,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[r==="push"?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(Gr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(ut,{sideOffset:8,children:"Push changes"})]})]})},_x={branch:Yt,briefcase:Jo,house:Xo,graduation:Yo,code:zs,heart:wl,user:Vn},Ox={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 Vc(r){return r&&Ox[r]||"var(--primary)"}const Xi=({icon:r,className:s,colorToken:t})=>{const n=_x[r??"branch"]??Vn;return e.jsx(n,{className:s,style:{color:Vc(t)}})},Bx=({activeProfile:r,identities:s,onSelect:t,isApplying:n})=>{const o=n||s.length===0;return e.jsxs(Xt,{children:[e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Jt,{asChild:!0,children:e.jsxs(Ae,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:Vc(r?.color)},disabled:o,children:[n?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(Xi,{icon:r?.icon,colorToken:r?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:r?.name||"No identity"}),e.jsx(vt,{className:"size-4 opacity-60"})]})})}),e.jsxs(ut,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:r?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:r?.userEmail||"No email configured"})]})]}),e.jsx(Zt,{align:"end",className:"w-64",children:s.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."})}):s.map(a=>e.jsx(gt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Xi,{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))})]})},$x=({status:r,localBranches:s,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:i,onPush:c,onCheckoutBranch:d,onCreateBranch:u,activeIdentityProfile:p,availableIdentities:m,onSelectIdentity:f,isApplyingIdentity:h,isWorktreeMode:g})=>r?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[!g&&e.jsx(Rx,{currentBranch:r.current,localBranches:s,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),r.tracking&&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(Gr,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:r.ahead})]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(vr,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:r.behind})]})]}),e.jsx(Lx,{syncAction:o,onFetch:a,onPull:i,onPush:c,disabled:!r}),e.jsx("div",{className:"flex-1"}),e.jsx(Bx,{activeProfile:p,identities:m,onSelect:f,isApplying:h})]}):null,zx=({behind:r,onPull:s,isPulling:t})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(Vo,{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"}),r>0&&e.jsxs(Ae,{variant:"outline",onClick:s,disabled:t,children:[t?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(vr,{className:"size-4"}),"Pull ",r," commit",r===1?"":"s"]})]});function Hx(r){const s=r.index&&r.index.trim()&&r.index.trim()!=="?"?r.index.trim():r.working_dir&&r.working_dir.trim()?r.working_dir.trim():r.index||r.working_dir||" ";switch(s.trim().charAt(0)||s.trim()||"·"){case"?":return{code:"?",color:"var(--status-info)",description:"Untracked file"};case"A":return{code:"A",color:"var(--status-success)",description:"New file"};case"D":return{code:"D",color:"var(--status-error)",description:"Deleted file"};case"R":return{code:"R",color:"var(--status-info)",description:"Renamed file"};case"C":return{code:"C",color:"var(--status-info)",description:"Copied file"};default:return{code:"M",color:"var(--status-warning)",description:"Modified file"}}}const Wx=({file:r,checked:s,onToggle:t,onViewDiff:n,onRevert:o,isReverting:a,stats:i})=>{const c=l.useMemo(()=>Hx(r),[r]),d=c.description??c.code,u=i?.insertions??0,p=i?.deletions??0;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:n,onKeyDown:m=>{m.key===" "?(m.preventDefault(),t()):m.key==="Enter"&&(m.preventDefault(),n())},children:[e.jsx("button",{type:"button",onClick:m=>{m.preventDefault(),m.stopPropagation(),t()},"aria-pressed":s,"aria-label":`Select ${r.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s?e.jsx(Qo,{className:"size-4 text-primary"}):e.jsx(ea,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:c.color},title:d,"aria-label":d,children:c.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:["+",u]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",p]})]}),e.jsxs(ft,{delayDuration:200,children:[e.jsx(pt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:m=>{m.preventDefault(),m.stopPropagation(),o()},disabled:a,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50 transition-opacity","aria-label":`Revert changes for ${r.path}`,children:a?e.jsx(Bt,{className:"size-3.5 animate-spin"}):e.jsx(qn,{className:"size-3.5"})})}),e.jsx(ut,{sideOffset:8,children:"Revert changes"})]})]})})},Ux=({changeEntries:r,selectedPaths:s,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:i,onViewDiff:c,onRevertFile:d})=>{const u=s.size,p=r.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,"/",p]}),p>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ae,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Ae,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(Xe,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:r.map(m=>e.jsx(Wx,{file:m,checked:s.has(m.path),stats:t?.[m.path],onToggle:()=>o(m.path),onViewDiff:()=>c(m.path),onRevert:()=>d(m.path),isReverting:n.has(m.path)},m.path))})})]})},Gc=vu,Vx=({className:r,...s})=>e.jsx(Su,{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",r),...s}),qc=({className:r,...s})=>e.jsx(ju,{className:T("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",r),...s}),Gx=({value:r,onChange:s,placeholder:t="Commit message",disabled:n=!1})=>{const[o,a]=l.useState(!1),i=r.includes(`
91
- `),c=l.useRef(null),d=o||i,u=()=>{a(!0)},p=()=>{!i&&!r.trim()&&a(!1)};return l.useEffect(()=>{if(d&&c.current){c.current.focus();const m=c.current.value.length;c.current.setSelectionRange(m,m)}},[d]),d?e.jsx(tr,{ref:c,value:r,onChange:m=>s(m.target.value),onBlur:p,placeholder:t,rows:4,disabled:n,className:T("rounded-lg bg-background/80 resize-none min-h-[100px]",n&&"opacity-50")}):e.jsx(Pt,{value:r,onChange:m=>s(m.target.value),onFocus:u,placeholder:t,disabled:n,className:T("rounded-lg bg-background/80",n&&"opacity-50")})},qx=({highlights:r,onInsert:s,onClear:t})=>{if(r.length===0)return null;const n=()=>{s(),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(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Ae,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(vr,{className:"size-4"})})}),e.jsx(ut,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:r.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},Kx=({selectedCount:r,commitMessage:s,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:p,isBusy:m})=>{const f=r>0,h=s.trim()&&f&&p===null;return e.jsxs(Gc,{open:f,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",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:f?`${r} file${r===1?"":"s"} selected`:"No files selected"})]}),e.jsx(qc,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(qx,{highlights:n,onInsert:o,onClear:a}),e.jsx(Gx,{value:s,onChange:t,placeholder:"Commit message",disabled:p!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ft,{delayDuration:1e3,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Ae,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:c||p!==null||r===0||m,"aria-label":"Generate commit message",children:c?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(ku,{className:"size-4 text-primary"})})}),e.jsx(ut,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(_n,{variant:"outline",onClick:d,disabled:!h||c,children:p==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Bt,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vo,{className:"size-4"}),"Commit"]})}),e.jsx(_n,{variant:"default",onClick:u,disabled:!h||c,children:p==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Bt,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Gr,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function Yx({...r}){return e.jsx(Nu,{"data-slot":"select",...r})}function Xx({...r}){return e.jsx(Au,{"data-slot":"select-value",...r})}function Jx({className:r,size:s="default",children:t,...n}){return e.jsxs(Cu,{"data-slot":"select-trigger","data-size":s,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-accent hover:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 *: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",r),...n,children:[t,e.jsx(Mu,{asChild:!0,children:e.jsx(vt,{className:"size-4 opacity-50"})})]})}function Zx({className:r,children:s,position:t="popper",...n}){return e.jsx(Du,{children:e.jsxs(Eu,{"data-slot":"select-content",className:T("bg-popover text-popover-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",r),position:t,...n,children:[e.jsx(ey,{}),e.jsx(Xe,{as:Tu,outerClassName:"max-h-[var(--radix-select-content-available-height)] w-full",className:T("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:s}),e.jsx(ty,{})]})})}function Qx({className:r,children:s,...t}){return e.jsxs(Iu,{"data-slot":"select-item",className:T("hover:bg-accent hover:text-accent-foreground [&_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",r),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(Fu,{children:e.jsx(Tt,{className:"size-4"})})}),e.jsx(Pu,{children:s})]})}function ey({className:r,...s}){return e.jsx(Ru,{"data-slot":"select-scroll-up-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(Vr,{className:"size-4"})})}function ty({className:r,...s}){return e.jsx(Lu,{"data-slot":"select-scroll-down-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(vt,{className:"size-4"})})}function Ji(r){const s=new Date(r);return Number.isNaN(s.getTime())?r:s.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function sy(r){switch(r){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 ry=({entry:r,isExpanded:s,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",s?"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:r.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:r.author_name,children:r.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:Ji(r.date),children:Ji(r.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:r.hash.slice(0,8)}),e.jsxs(ft,{delayDuration:500,children:[e.jsx(pt,{asChild:!0,children:e.jsx(Ae,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(r.hash)},children:e.jsx(Ls,{className:"size-3"})})}),e.jsx(ut,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),s&&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(Bt,{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",sy(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))})})]}),ny=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],oy=({log:r,isLogLoading:s,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:c,onCopyHash:d})=>{const[u,p]=l.useState(!0);return r?e.jsxs(Gc,{open:u,onOpenChange:p,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Vx,{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:m=>m.stopPropagation(),onPointerDown:m=>m.stopPropagation(),children:e.jsxs(Yx,{value:String(t),onValueChange:m=>n(Number(m)),disabled:s,children:[e.jsx(Jx,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:s,children:e.jsx(Xx,{placeholder:"Commits"})}),e.jsx(Zx,{children:ny.map(m=>e.jsx(Qx,{value:String(m.value),children:m.label},m.value))})]})}),u?e.jsx(Vr,{className:"size-4 text-muted-foreground"}):e.jsx(vt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(qc,{children:e.jsx(Xe,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:r.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:r.all.map(m=>e.jsx(ry,{entry:m,isExpanded:o.has(m.hash),onToggle:()=>a(m.hash),files:i.get(m.hash)??[],isLoadingFiles:c.has(m.hash),onCopyHash:d},m.hash))})})})]}):null};let Tr=null;const ay=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=me(),{currentDirectory:n}=St(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},iy=()=>{const{git:r}=rr(),s=ay(),{currentSessionId:t,worktreeMetadata:n}=me(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=Kn(),u=Xl(s??null),p=Yl(s??null),m=ep(s??null),f=tp(s??null),h=sp(s??null),g=Mt(Z=>Z.isLoadingStatus),b=Mt(Z=>Z.isLoadingLog),{setActiveDirectory:x,fetchAll:w,fetchStatus:S,fetchBranches:v,fetchLog:j,fetchIdentity:k,setLogMaxCount:y}=Mt(),A=l.useMemo(()=>!Tr||Tr.directory!==s?null:Tr,[s]),[D,N]=l.useState(A?.commitMessage??""),[C,M]=l.useState(null),[E,F]=l.useState(null),[W,L]=l.useState(25),[K,X]=l.useState(!1),{triggerFireworks:z}=Fx(),[G,H]=l.useState(()=>new Set(A?.selectedPaths??[])),[oe,ve]=l.useState(!1),[Ee,Ie]=l.useState(new Set),[ge,de]=l.useState(!1),[we,De]=l.useState([]),_e=l.useCallback(()=>{De([])},[]),[Ne,Fe]=l.useState(new Set),[$,B]=l.useState(new Map),[J,I]=l.useState(new Set),_=l.useCallback(Z=>{navigator.clipboard.writeText(Z).then(()=>{be.success("Commit hash copied")}).catch(()=>{be.error("Failed to copy")})},[]),U=l.useCallback(Z=>{Fe(ne=>{const ae=new Set(ne);return ae.has(Z)?ae.delete(Z):ae.add(Z),ae})},[]);l.useEffect(()=>{if(!s||!r)return;const Z=Array.from(Ne).filter(ne=>!$.has(ne)&&!J.has(ne));Z.length!==0&&(I(ne=>{const ae=new Set(ne);return Z.forEach(Me=>ae.add(Me)),ae}),Z.forEach(ne=>{r.getCommitFiles(s,ne).then(ae=>{B(Me=>new Map(Me).set(ne,ae.files))}).catch(ae=>{console.error("Failed to fetch commit files:",ae),B(Me=>new Map(Me).set(ne,[]))}).finally(()=>{I(ae=>{const Me=new Set(ae);return Me.delete(ne),Me})})}))},[Ne,s,r,$,J]),l.useEffect(()=>()=>{if(!s){Tr=null;return}Tr={directory:s,selectedPaths:Array.from(G),commitMessage:D}},[D,s,G]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{s&&(x(s),Mt.getState().directories.get(s)?.status||w(s,r,{force:!0}))},[s,x,w,r]);const xe=l.useCallback(async(Z=!0)=>{if(s)try{await Promise.all([S(s,r),v(s,r)])}catch(ne){if(Z){const ae=ne instanceof Error?ne.message:"Failed to refresh repository state";be.error(ae)}}},[s,r,S,v]),ye=l.useCallback(async()=>{s&&await j(s,r,W)},[s,r,j,W]),se=l.useCallback(async()=>{s&&await k(s,r)},[s,r,k]),O=l.useMemo(()=>{if(!p)return[];const Z=p.files??[],ne=new Map;return Z.forEach(ae=>{ne.set(ae.path,ae)}),Array.from(ne.values()).sort((ae,Me)=>ae.path.localeCompare(Me.path))},[p]);l.useEffect(()=>{if(!p||O.length===0){H(new Set),ve(!1);return}H(Z=>{const ne=new Set,ae=Z??new Set;return O.forEach(Me=>{ae.has(Me.path)?ne.add(Me.path):oe||ne.add(Me.path)}),ne})},[p,O,oe]);const V=async Z=>{if(s){M(Z);try{if(Z==="fetch")await r.gitFetch(s),be.success("Fetched latest updates");else if(Z==="pull"){const ne=await r.gitPull(s);be.success(`Pulled ${ne.files.length} file${ne.files.length===1?"":"s"}`)}else Z==="push"&&(await r.gitPush(s),be.success("Pushed to remote"));await xe(!1),await ye()}catch(ne){const ae=ne instanceof Error?ne.message:`Failed to ${Z==="pull"?"pull":Z}`;be.error(ae)}finally{M(null)}}},P=async(Z={})=>{if(!s)return;if(!D.trim()){be.error("Please enter a commit message");return}const ne=Array.from(G).sort();if(ne.length===0){be.error("Select at least one file to commit");return}const ae=Z.pushAfter?"commitAndPush":"commit";F(ae);try{await r.createGitCommit(s,D.trim(),{files:ne}),be.success("Commit created successfully"),N(""),H(new Set),ve(!1),_e(),await xe(),Z.pushAfter?(await r.gitPush(s),be.success("Pushed to remote"),z(),await xe(!1)):await xe(!1),await ye()}catch(Me){const at=Me instanceof Error?Me.message:"Failed to create commit";be.error(at)}finally{F(null)}},te=l.useCallback(async()=>{if(s){if(G.size===0){be.error("Select at least one file to describe");return}de(!0);try{const{message:Z}=await r.generateCommitMessage(s,Array.from(G)),ne=Z.subject?.trim()??"",ae=Array.isArray(Z.highlights)?Z.highlights:[];ne&&N(ne),De(ae),be.success("Commit message generated")}catch(Z){const ne=Z instanceof Error?Z.message:"Failed to generate commit message";be.error(ne)}finally{de(!1)}}},[s,G,r]),je=async Z=>{if(!s||!p)return;const ne=p.current??null;try{await r.createBranch(s,Z,ne??"HEAD"),be.success(`Created branch ${Z}`);let ae=!1;try{await r.checkoutBranch(s,Z),await r.gitPush(s,{remote:"origin",branch:Z,options:["--set-upstream"]}),ae=!0}catch(Me){const at=Me instanceof Error?Me.message:"Unable to push new branch to origin.";be.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",at]})})}finally{if(ne)try{await r.checkoutBranch(s,ne)}catch(Me){console.warn("Failed to restore original branch after creation:",Me)}}await xe(),await ye(),ae&&be.success(`Upstream set for ${Z}`)}catch(ae){const Me=ae instanceof Error?ae.message:"Failed to create branch";throw be.error(Me),ae}},ke=async Z=>{if(!s)return;const ne=Z.replace(/^remotes\//,"");if(p?.current!==ne)try{await r.checkoutBranch(s,ne),be.success(`Checked out ${ne}`),await xe(),await ye()}catch(ae){const Me=ae instanceof Error?ae.message:`Failed to checkout ${ne}`;be.error(Me)}},$e=async Z=>{if(s){X(!0);try{await r.setGitIdentity(s,Z.id),be.success(`Applied "${Z.name}" to repository`),await se()}catch(ne){const ae=ne instanceof Error?ne.message:"Failed to apply git identity";be.error(ae)}finally{X(!1)}}},ct=l.useMemo(()=>m?.all?m.all.filter(Z=>!Z.startsWith("remotes/")).sort():[],[m]),ht=l.useMemo(()=>m?.all?m.all.filter(Z=>Z.startsWith("remotes/")).map(Z=>Z.replace(/^remotes\//,"")).sort():[],[m]),mt=l.useMemo(()=>{const Z=new Map;i&&Z.set(i.id,i);for(const ne of a)Z.set(ne.id,ne);return Array.from(Z.values())},[a,i]),dt=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const Z=a.find(ne=>ne.userName===h.userName&&ne.userEmail===h.userEmail);return Z||(i&&i.userName===h.userName&&i.userEmail===h.userEmail?i:{id:"local-config",name:h.userName,userName:h.userName,userEmail:h.userEmail,sshKey:h.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[h,a,i]),Ge=O.length,tt=G.size,Ue=g||C!==null||E!==null,Ke=Ge>0,Je=Z=>{H(ne=>{const ae=new Set(ne);return ae.has(Z)?ae.delete(Z):ae.add(Z),ae}),ve(!0)},fe=()=>{const Z=new Set(O.map(ne=>ne.path));H(Z),ve(!0)},R=()=>{H(new Set),ve(!0)},Q=l.useCallback(async Z=>{if(s){Ie(ne=>{const ae=new Set(ne);return ae.add(Z),ae});try{await r.revertGitFile(s,Z),be.success(`Reverted ${Z}`),await xe(!1)}catch(ne){const ae=ne instanceof Error?ne.message:"Failed to revert changes";be.error(ae)}finally{Ie(ne=>{const ae=new Set(ne);return ae.delete(Z),ae})}}},[s,xe,r]),re=l.useCallback(()=>{if(we.length===0)return;const Z=we.map(ne=>ne.trim()).filter(Boolean);if(Z.length===0){_e();return}N(ne=>{const ae=ne.trim(),Me=ae.length>0?`
92
-
93
- `:"";return`${ae}${Me}${Z.join(`
94
- `)}`.trim()})},[we,_e]),ce=l.useCallback(Z=>{L(Z),s&&(y(s,Z),j(s,r,Z))},[s,y,j,r]);return s?g&&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(Bt,{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(Yt,{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",children:[e.jsx($x,{status:p,localBranches:ct,remoteBranches:ht,branchInfo:m?.branches,syncAction:C,onFetch:()=>V("fetch"),onPull:()=>V("pull"),onPush:()=>V("push"),onCheckoutBranch:ke,onCreateBranch:je,activeIdentityProfile:dt,availableIdentities:mt,onSelectIdentity:$e,isApplyingIdentity:K,isWorktreeMode:!!o}),e.jsx(Xe,{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:[Ke?e.jsx(Ux,{changeEntries:O,selectedPaths:G,diffStats:p?.diffStats,revertingPaths:Ee,onToggleFile:Je,onSelectAll:fe,onClearSelection:R,onViewDiff:Z=>Pe.getState().navigateToDiff(Z),onRevertFile:Q}):e.jsx(zx,{behind:p?.behind??0,onPull:()=>V("pull"),isPulling:C==="pull"}),e.jsx(Kx,{selectedCount:tt,commitMessage:D,onCommitMessageChange:N,generatedHighlights:we,onInsertHighlights:re,onClearHighlights:_e,onGenerateMessage:te,isGeneratingMessage:ge,onCommit:()=>P({pushAfter:!1}),onCommitAndPush:()=>P({pushAfter:!0}),commitAction:E,isBusy:Ue})]}),e.jsx(oy,{log:f,isLogLoading:b,logMaxCount:W,onLogMaxCountChange:ce,expandedCommitHashes:Ne,onToggleCommit:U,commitFilesMap:$,loadingCommitHashes:J,onCopyHash:_})]})})]}):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."})})},ly=256e3;function Xs(r){let s=r.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const dn=r=>({directory:r,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Zi=$t((r,s)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=Xs(t);return s().sessions.get(n)},setTerminalSession:(t,n)=>{const o=Xs(t);r(a=>{const i=new Map(a.sessions),c=i.get(o),u=!c||c.terminalSessionId!==n.sessionId?dn(o):c??dn(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=Xs(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??dn(o);return i.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=Xs(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??dn(o),d=a.nextChunkId,u={id:d,data:n},p=[...c.bufferChunks,u];let m=c.bufferLength+n.length;for(;m>ly&&p.length>1;){const h=p.shift();if(!h)break;m-=h.data.length}const f=p.map(h=>h.data).join("");return i.set(o,{...c,buffer:f,bufferChunks:p,bufferLength:m,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=Xs(t);r(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=Xs(t);r(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=Xs(t);r(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{r({sessions:new Map,nextChunkId:1})}})),Kc=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),cy=[{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'}],dy=[{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'}],Yc=r=>Object.fromEntries(r.map(s=>[s.id,s])),Qi=Yc(cy),Js=Yc(dy),uy="ibm-plex-sans",jn="ibm-plex-mono";function my(r){const{colors:s}=r,t=s.syntax.base;return{background:s.surface.background,foreground:t.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:t.function,magenta:t.keyword,cyan:t.type,white:t.foreground,brightBlack:t.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:t.function,brightMagenta:t.keyword,brightCyan:t.type,brightWhite:s.surface.elevatedForeground}}function el(r,s,t){return{fontFamily:`${r}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`,fontSize:s,lineHeight:1,cursorBlink:!0,cursorStyle:"block",theme:t,allowTransparency:!1,scrollback:1e4,minimumContrastRatio:1,fastScrollModifier:"shift",fastScrollSensitivity:5,scrollSensitivity:3,macOptionIsMeta:!0,macOptionClickForcesSelection:!1,rightClickSelectsWord:!0}}const Wo=l.forwardRef(({sessionKey:r,chunks:s,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:c,enableTouchScroll:d},u)=>{const p=l.useRef(null),m=l.useRef(null),f=l.useRef(null),h=l.useRef(null),g=l.useRef(t),b=l.useRef(n),x=l.useRef([]),w=l.useRef(!1),S=l.useRef(0),v=l.useRef(null),j=l.useRef(null),[,k]=l.useReducer(M=>M+1,0);g.current=t,b.current=n;const y=l.useCallback(()=>{x.current=[],w.current=!1,S.current=0,v.current=null},[]),A=l.useCallback(()=>{const M=h.current,E=f.current,F=p.current;if(!M||!E||!F)return;const W=F.getBoundingClientRect();if(!(W.width<24||W.height<24))try{M.fit(),b.current(E.cols,E.rows)}catch{}},[]),D=l.useCallback(()=>{if(w.current)return;const M=()=>{const E=f.current;if(!E){y();return}const F=x.current.shift();if(F===void 0){w.current=!1;return}w.current=!0,E.write(F,()=>{w.current=!1,x.current.length>0&&(typeof window<"u"?window.setTimeout(M,0):M())})};M()},[y]),N=l.useCallback(M=>{M&&(x.current=[M],w.current=!1,D())},[D]),C=l.useCallback(()=>{if(j.current?.(),j.current=null,!d)return;const M=p.current;if(!M)return;const E=M.querySelector(".xterm-viewport");if(!E)return;const F=2.2,W=2.8,L=25,K=.25,X=8,z=.05,G=.015,H={lastY:null,lastTime:null,velocity:0,rafId:null},oe=()=>typeof performance<"u"?performance.now():Date.now(),ve=()=>Math.max(0,E.scrollHeight-E.clientHeight),Ee=$=>{const B=ve();E.scrollTop=Math.max(0,Math.min(B,$))},Ie=$=>{if(!$)return;const B=E.scrollTop;return Ee(B+$),E.scrollTop!==B},ge=()=>{H.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(H.rafId),H.rafId=null},de={passive:!1,capture:!0};if(typeof window<"u"&&"PointerEvent"in window){const $=Object.assign(H,{pointerId:null}),B=U=>{if(U.pointerType==="touch"){ge(),$.pointerId=U.pointerId,$.lastY=U.clientY,$.lastTime=oe(),$.velocity=0;try{M.setPointerCapture(U.pointerId)}catch{}}},J=U=>{if(U.pointerType!=="touch"||$.pointerId!==U.pointerId)return;if($.lastY===null){$.lastY=U.clientY,$.lastTime=oe();return}const xe=$.lastY,ye=$.lastTime??oe(),se=oe();$.lastY=U.clientY,$.lastTime=se;const O=xe-U.clientY;if(Math.abs(O)<1)return;const V=Math.max(se-ye,8),P=F+Math.min(W,Math.abs(O)/L),te=O*P,je=te/V;$.velocity=$.velocity*(1-K)+je*K,$.velocity>X?$.velocity=X:$.velocity<-X&&($.velocity=-X),U.cancelable&&U.preventDefault(),U.stopPropagation(),Ie(te)},I=U=>{if(U.pointerType!=="touch"||$.pointerId!==U.pointerId)return;$.pointerId=null,$.lastY=null,$.lastTime=null;try{M.releasePointerCapture(U.pointerId)}catch{}if(typeof window>"u")return;if(Math.abs($.velocity)<z){$.velocity=0;return}let xe=oe();const ye=()=>{const se=oe(),O=Math.max(se-xe,8);xe=se;const V=Ie($.velocity*O)??!1,P=Math.sign($.velocity),te=Math.max(0,Math.abs($.velocity)-G*O);if($.velocity=te*P,!V||te<=z){ge(),$.velocity=0;return}$.rafId=window.requestAnimationFrame(ye)};$.rafId=window.requestAnimationFrame(ye)};M.addEventListener("pointerdown",B,de),M.addEventListener("pointermove",J,de),M.addEventListener("pointerup",I,de),M.addEventListener("pointercancel",I,de);const _=M.style.touchAction;M.style.touchAction="none",j.current=()=>{ge(),M.removeEventListener("pointerdown",B,de),M.removeEventListener("pointermove",J,de),M.removeEventListener("pointerup",I,de),M.removeEventListener("pointercancel",I,de),M.style.touchAction=_};return}const De=$=>{$.touches.length===1&&(ge(),H.lastY=$.touches[0].clientY,H.lastTime=oe(),H.velocity=0)},_e=$=>{if($.touches.length!==1){H.lastY=null,H.lastTime=null,H.velocity=0,ge();return}const B=$.touches[0].clientY;if(H.lastY===null){H.lastY=B,H.lastTime=oe();return}const J=H.lastY,I=H.lastTime??oe(),_=oe();H.lastY=B,H.lastTime=_;const U=J-B;if(Math.abs(U)<1)return;const xe=Math.max(_-I,8),ye=F+Math.min(W,Math.abs(U)/L),se=U*ye,O=se/xe;H.velocity=H.velocity*(1-K)+O*K,H.velocity>X?H.velocity=X:H.velocity<-X&&(H.velocity=-X),$.preventDefault(),$.stopPropagation(),Ie(se)},Ne=()=>{if(H.lastY=null,H.lastTime=null,typeof window>"u")return;if(Math.abs(H.velocity)<z){H.velocity=0;return}let $=oe();const B=()=>{const J=oe(),I=Math.max(J-$,8);$=J;const _=Ie(H.velocity*I)??!1,U=Math.sign(H.velocity),xe=Math.max(0,Math.abs(H.velocity)-G*I);if(H.velocity=xe*U,!_||xe<=z){ge(),H.velocity=0;return}H.rafId=window.requestAnimationFrame(B)};H.rafId=window.requestAnimationFrame(B)};M.addEventListener("touchstart",De,de),M.addEventListener("touchmove",_e,de),M.addEventListener("touchend",Ne,de),M.addEventListener("touchcancel",Ne,de);const Fe=M.style.touchAction;M.style.touchAction="none",j.current=()=>{ge(),M.removeEventListener("touchstart",De,de),M.removeEventListener("touchmove",_e,de),M.removeEventListener("touchend",Ne,de),M.removeEventListener("touchcancel",Ne,de),M.style.touchAction=Fe}},[d]);return l.useEffect(()=>{const M=new _u.Terminal(el(a,i,o)),E=new Ou.FitAddon;f.current=M,h.current=E,M.loadAddon(E);const F=p.current;if(F){M.open(F);const K=F.querySelector(".xterm-viewport");K&&(K.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),m.current=K,k()),A(),M.focus()}const W=[M.onData(K=>{g.current(K)})],L=new ResizeObserver(()=>{A()});return F&&L.observe(F),()=>{j.current?.(),j.current=null,W.forEach(K=>K.dispose()),L.disconnect(),M.dispose(),f.current=null,h.current=null,y()}},[A,a,i,o,y]),l.useEffect(()=>{const M=f.current;if(!M)return;const E=el(a,i,o);Object.assign(M.options,E),A()},[A,a,i,o]),l.useEffect(()=>{const M=f.current;M&&(M.reset(),y(),A(),M.focus())},[r,A,y]),l.useEffect(()=>(C(),()=>{j.current?.(),j.current=null}),[C,r]),l.useEffect(()=>{const M=f.current;if(!M)return;if(s.length===0){S.current!==0&&(M.reset(),y(),A());return}const E=s[0].id;if(v.current===null&&(v.current=E),(v.current!==E||S.current>s.length)&&(M.reset(),y(),v.current=E),S.current<s.length){const W=s.slice(S.current);N(W.map(L=>L.data).join("")),S.current=s.length}},[s,N,A,y]),l.useImperativeHandle(u,()=>({focus:()=>{f.current?.focus()},clear:()=>{const M=f.current;M&&(M.reset(),y(),A())},fit:()=>{A()}}),[A,y]),e.jsx("div",{ref:p,className:T("relative h-full w-full",c),children:m.current?e.jsx(ca,{containerRef:m,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null})});Wo.displayName="TerminalViewport";const tl=13,fy={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},un={ctrl:"5",cmd:"3"},py={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},hy=(r,s)=>{if(s)switch(r){case"arrow-up":return`\x1B[1;${un[s]}A`;case"arrow-down":return`\x1B[1;${un[s]}B`;case"arrow-right":return`\x1B[1;${un[s]}C`;case"arrow-left":return`\x1B[1;${un[s]}D`}return fy[r]??null},gy=()=>{const{terminal:r}=rr(),{currentTheme:s}=kr(),{monoFont:t}=Kc(),{isMobile:n,hasTouchInput:o}=Dt(),{currentSessionId:a,sessions:i,worktreeMetadata:c}=me(),d=a?c.get(a)??void 0:void 0,u=l.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const V=i.find(te=>te.id===a),P=typeof V?.directory=="string"?V.directory:null;return P&&P.length>0?P:null},[a,i,d]),{currentDirectory:p,homeDirectory:m}=St(),f=u||p||null,h=l.useMemo(()=>f?m?f===m?"~":f.startsWith(m+"/")?"~"+f.slice(m.length):f:f:"",[f,m]),g=Zi(),b=g.sessions,x=g.setTerminalSession,w=g.setConnecting,S=g.appendToBuffer,v=g.clearTerminalSession,j=g.removeTerminalSession,k=g.clearBuffer,y=l.useMemo(()=>{if(f)return b.get(f)},[b,f]),A=y?.terminalSessionId??null,D=y?.bufferChunks??[],N=y?.bufferLength??0,C=y?.isConnecting??!1,M=A,[E,F]=l.useState(null),[W,L]=l.useState(!1),[K,X]=l.useState(null),[z,G]=l.useState(!1),H=l.useRef(null),oe=l.useRef(null),ve=l.useRef(M),Ee=l.useRef(f),Ie=l.useRef(null),de=Pe(V=>V.activeMainTab)==="terminal";l.useEffect(()=>{ve.current=M},[M]),l.useEffect(()=>{Ee.current=f},[f]),l.useEffect(()=>{!n&&K!==null&&X(null)},[n,K,X]),l.useEffect(()=>{!M&&K!==null&&X(null)},[M,K,X]);const we=l.useCallback(()=>{H.current?.(),H.current=null,oe.current=null},[]);l.useEffect(()=>()=>{we(),ve.current=null},[we]);const De=l.useCallback(V=>{if(oe.current===V)return;we();const P=r.connect(V,{onEvent:te=>{const je=Ee.current;if(je)switch(te.type){case"connected":{w(je,!1),F(null),L(!1),Ie.current?.focus();break}case"reconnecting":{const ke=te.attempt??0,$e=te.maxAttempts??3;F(`Reconnecting (${ke}/${$e})...`),L(!1);break}case"data":{te.data&&S(je,te.data);break}case"exit":{const ke=typeof te.exitCode=="number"?te.exitCode:null,$e=typeof te.signal=="number"?te.signal:null;S(je,`\r
95
- [Process exited${ke!==null?` with code ${ke}`:""}${$e!==null?` (signal ${$e})`:""}]\r
96
- `),v(je),w(je,!1),F("Terminal session ended"),L(!1),we();break}}},onError:(te,je)=>{const ke=Ee.current;if(!ke)return;const $e=je?`Connection failed: ${te.message}`:te.message||"Terminal stream connection error";F($e),L(!!je),je&&(w(ke,!1),we(),j(ke))}},py);H.current=()=>{P.close(),oe.current=null},oe.current=V},[S,v,we,j,w,r,F]);l.useEffect(()=>{let V=!1;if(!f){F(a?"No working directory available for terminal.":"Select a session to open the terminal."),we();return}return(async()=>{const te=f;if(!Ee.current||Ee.current!==te)return;let ke=Zi.getState().getTerminalSession(te)?.terminalSessionId??null;if(!ke){F(null),L(!1),w(te,!0);try{const $e=await r.createSession({cwd:te});if(V){try{await r.close($e.sessionId)}catch{}return}x(te,$e),ke=$e.sessionId}catch($e){V||(F($e instanceof Error?$e.message:"Failed to start terminal session"),L(!0),w(te,!1));return}}!ke||V||(ve.current=ke,De(ke))})(),()=>{V=!0,ve.current=null,we()}},[a,f,M,j,w,x,De,we,r]);const _e=l.useCallback(async()=>{if(!f||z)return;G(!0),F(null),L(!1),we();const V=ve.current;try{if(r.restartSession&&V){const P=await r.restartSession(V,{cwd:f});x(f,P),ve.current=P.sessionId,De(P.sessionId)}else{if(V)try{await r.close(V)}catch{}j(f)}}catch(P){F(P instanceof Error?P.message:"Failed to restart terminal"),L(!0)}finally{G(!1)}},[f,z,we,r,x,De,j]),Ne=l.useCallback(async()=>{if(f&&!z){G(!0),F(null),L(!1),we();try{r.forceKill&&await r.forceKill({cwd:f})}catch{}j(f),k(f),Ie.current?.clear(),await new Promise(V=>setTimeout(V,100));try{w(f,!0);const V=await r.createSession({cwd:f});x(f,V),ve.current=V.sessionId,De(V.sessionId)}catch(V){F(V instanceof Error?V.message:"Failed to create terminal"),L(!0),w(f,!1)}finally{G(!1)}}},[f,z,we,r,j,k,w,x,De]),Fe=l.useCallback(()=>{if(!f)return;k(f),Ie.current?.clear(),Ie.current?.focus();const V=ve.current;V&&r.sendInput(V,"\f").catch(P=>{F(P instanceof Error?P.message:"Failed to refresh prompt")})},[k,f,F,r]),$=l.useCallback(V=>{if(!V)return;let P=V,te=!1;if(K&&V.length>0){const ke=V[0];if(ke.length===1&&/[a-zA-Z]/.test(ke)){const $e=ke.toUpperCase();(K==="ctrl"||K==="cmd")&&(P=String.fromCharCode($e.charCodeAt(0)&31),te=!0)}te||(te=!0)}const je=ve.current;je&&(r.sendInput(je,P).catch(ke=>{F(ke instanceof Error?ke.message:"Failed to send input")}),te&&(X(null),Ie.current?.focus()))},[K,X,r]),B=l.useCallback((V,P)=>{const te=ve.current;te&&r.resize({sessionId:te,cols:V,rows:P}).catch(()=>{})},[r]),J=l.useCallback(V=>{X(P=>P===V?null:V),Ie.current?.focus()},[X]),I=l.useCallback(V=>{const P=hy(V,K);P&&($(P),X(null),Ie.current?.focus())},[K,$,X]);l.useEffect(()=>{if(!n||!K||!M)return;const V=P=>{if(P.repeat)return;const te=P.key;if(!te||te==="Control"||te==="Meta"||te==="Alt"||te==="Shift")return;const je=te.length===1?te.toLowerCase():te,ke=P.code??"",$e=ke.startsWith("Key")&&ke.length===4?ke.slice(3).toUpperCase():null,ct=te.length===1&&/[a-zA-Z]/.test(te)?te.toUpperCase():$e,ht={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc",tab:"tab",enter:"enter",arrowup:"arrow-up",arrowdown:"arrow-down",arrowleft:"arrow-left",arrowright:"arrow-right",escape:"esc"};if(je in ht){P.preventDefault(),P.stopPropagation(),I(ht[je]);return}if(K==="ctrl"&&ct&&ct.length===1&&ct>="A"&&ct<="Z"){const mt=String.fromCharCode(ct.charCodeAt(0)&31);P.preventDefault(),P.stopPropagation(),$(mt),X(null),Ie.current?.focus()}};return window.addEventListener("keydown",V),()=>{window.removeEventListener("keydown",V)}},[K,I,$,n,X,M]);const _=l.useMemo(()=>{const V=Js[jn].stack;if(typeof window>"u")return(Js[t]??Js[jn]).stack;const te=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return te&&te.trim().length>0?te.trim():(Js[t]??Js[jn]).stack??V},[t]),U=l.useMemo(()=>my(s),[s]),xe=l.useMemo(()=>`${f??"no-dir"}::${M??"pending"}`,[f,M]);l.useEffect(()=>{if(!de)return;const V=Ie.current;if(!V)return;const P=()=>{V.fit()};if(typeof window<"u"){const te=window.requestAnimationFrame(()=>{P(),V.focus()}),je=[220,400].map(ke=>window.setTimeout(P,ke));return()=>{window.cancelAnimationFrame(te),je.forEach(ke=>window.clearTimeout(ke))}}P()},[de,xe,M]);const ye=E?.includes("Reconnecting"),se=E?ye?e.jsx($u,{size:20,className:"text-amber-400"}):e.jsx(ds,{size:20,className:"text-destructive"}):M&&!C&&!z?e.jsx(fn,{size:20,className:"text-emerald-400"}):C||z?e.jsx(Ta,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Ta,{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(!f)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:_e,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const O=!M||C||z;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[se,e.jsxs(Ae,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Fe,disabled:!N,title:"Clear output",type:"button",children:[e.jsx(Us,{size:16}),"Clear"]}),e.jsxs(Ae,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:_e,disabled:z,title:"Restart terminal session",type:"button",children:[e.jsx(Ds,{size:16,className:T((C||z)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Ae,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>I("esc"),disabled:O,children:"Esc"}),e.jsxs(Ae,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>I("tab"),disabled:O,children:[e.jsx(Ea,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ae,{type:"button",size:"sm",variant:K==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>J("ctrl"),disabled:O,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Ae,{type:"button",size:"sm",variant:K==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>J("cmd"),disabled:O,children:[e.jsx(wr,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Ae,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>I("arrow-up"),disabled:O,children:[e.jsx(Gr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ae,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>I("arrow-left"),disabled:O,children:[e.jsx(kl,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ae,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>I("arrow-down"),disabled:O,children:[e.jsx(vr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ae,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>I("arrow-right"),disabled:O,children:[e.jsx(Ea,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ae,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>I("enter"),disabled:O,children:[e.jsx(Bu,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:U.background},children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:de?n?e.jsx(Wo,{ref:V=>{Ie.current=V},sessionKey:xe,chunks:D,onInput:$,onResize:B,theme:U,fontFamily:_,fontSize:tl,enableTouchScroll:o},xe):e.jsx(Xe,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Wo,{ref:V=>{Ie.current=V},sessionKey:xe,chunks:D,onInput:$,onResize:B,theme:U,fontFamily:_,fontSize:tl,enableTouchScroll:o},xe)}):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}),W&&e.jsx(Ae,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Ne,disabled:z,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},xy=()=>{const{isSidebarOpen:r,activeMainTab:s,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i}=Pe(),{isMobile:c}=Dt(),[d,u]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||u(typeof window.opencodeDesktop<"u")},[]),Dh({enabled:!0}),l.useEffect(()=>{Pe.getState().isMobile!==c&&t(c)},[c,t]),l.useEffect(()=>{if(typeof window>"u")return;let f;const h=()=>{f!==void 0&&window.clearTimeout(f),f=window.setTimeout(()=>{Pe.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",h),()=>{window.removeEventListener("resize",h),f!==void 0&&window.clearTimeout(f)}},[]),l.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const f=document.documentElement;let h=0,g=!1,b=0;const x=()=>{h=0,g=!0,f.style.setProperty("--oc-keyboard-inset","0px")},w=()=>{const j=window.visualViewport,k=j?Math.round(j.height):window.innerHeight,y=j?Math.max(0,Math.round(j.offsetTop)):0;f.style.setProperty("--oc-visual-viewport-offset-top",`${y}px`);const A=document.activeElement,D=A?.tagName,C=D==="INPUT"||D==="TEXTAREA"||D==="SELECT"||!!A?.isContentEditable,M=Math.round(f.clientHeight||window.innerHeight),E=k+y,F=Math.max(0,M-E),L=F>=(C?120:180)?F:0;if(g)L===0&&(g=!1),h=0;else if(h===0)L>0&&C&&(h=L);else{const K=k>b+6;L===0?h=0:K?x():L>h&&(h=L)}if(f.style.setProperty("--oc-keyboard-inset",`${h}px`),b=k,c&&C){const K=document.scrollingElement;K&&K.scrollTop!==0&&(K.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};w();const S=window.visualViewport;S?.addEventListener("resize",w),S?.addEventListener("scroll",w),window.addEventListener("resize",w),window.addEventListener("orientationchange",w),document.addEventListener("focusin",w,!0);const v=j=>{const k=j.target;if(!k)return;const y=k.tagName;(y==="INPUT"||y==="TEXTAREA"||y==="SELECT"||k.isContentEditable)&&x()};return document.addEventListener("focusout",v,!0),()=>{S?.removeEventListener("resize",w),S?.removeEventListener("scroll",w),window.removeEventListener("resize",w),window.removeEventListener("orientationchange",w),document.removeEventListener("focusin",w,!0),document.removeEventListener("focusout",v,!0)}},[c]);const p=l.useMemo(()=>{switch(s){case"git":return e.jsx(iy,{});case"diff":return e.jsx(Rp,{});case"terminal":return e.jsx(gy,{});default:return null}},[s]),m=s==="chat";return e.jsx(Ah,{children:e.jsxs("div",{className:T("main-content-safe-area h-[100dvh]",c?"flex flex-col":"flex",d?"bg-transparent":"bg-background"),children:[e.jsx(mh,{}),e.jsx(hh,{}),e.jsx(Sh,{}),e.jsx(dh,{isOpen:a,onClose:()=>i(!1)}),c?e.jsxs(e.Fragment,{children:[e.jsx(di,{}),e.jsx("div",{className:"flex flex-1 overflow-hidden bg-background",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",!m&&"invisible"),children:e.jsx(ls,{children:e.jsx(Ho,{})})}),p&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:p})})]})}),e.jsx(Kt,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Lo,{mobileVariant:!0})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Hp,{isOpen:r,isMobile:c,children:e.jsx(Lo,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(di,{}),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",!m&&"invisible"),children:e.jsx(ls,{children:e.jsx(Ho,{})})}),p&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:p})})]})})]})]}),e.jsx(_p,{})]})})},yy=()=>{const[r,s]=l.useState("sessions"),t=me(W=>W.currentSessionId),n=me(W=>W.sessions),o=me(W=>W.createSession),a=me(W=>W.setCurrentSession),[i,c]=l.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),[d,u]=l.useState(()=>typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.error:void 0),[p,m]=l.useState(()=>i==="connected"),[f,h]=l.useState(()=>i!=="connected"),g=l.useRef(null),b=kt(W=>W.isInitialized),x=kt(W=>W.initializeApp),w=me(W=>W.loadSessions),S=me(W=>W.loadMessages),v=me(W=>W.messages),[j,k]=l.useState(()=>b),[y,A]=l.useState(!1),D=l.useRef(!1),N=l.useRef(!1);l.useEffect(()=>{t&&s("chat")},[t]),l.useEffect(()=>{!t&&r==="chat"&&s("sessions")},[t,r]);const C=l.useCallback(()=>{s("sessions")},[]),M=l.useCallback(async()=>{(await o())?.id&&s("chat")},[o]);l.useEffect(()=>{const W=L=>{const K=L.detail,X=K?.status;(X==="connected"||X==="connecting"||X==="error"||X==="disconnected")&&(c(X),u(K?.error),X==="connected"&&m(!0))};return window.addEventListener("openchamber:connection-status",W),()=>window.removeEventListener("openchamber:connection-status",W)},[]);const E=l.useMemo(()=>j&&i==="connected"&&!y?!1:j?i==="error":i!=="connected"||y,[i,j,y]),F=p?800:250;return l.useEffect(()=>(g.current&&(window.clearTimeout(g.current),g.current=null),E?g.current=window.setTimeout(()=>h(!0),F):h(!1),()=>{g.current&&(window.clearTimeout(g.current),g.current=null)}),[F,E]),l.useEffect(()=>{(async()=>{if(!(y||j||i!=="connected")){A(!0);try{b||await x(),await w(),k(!0)}catch{}finally{A(!1)}}})()},[i,b,j,x,y,w]),l.useEffect(()=>{(async()=>{if(!j||i!=="connected"||r!=="chat")return;const L=t||n[0]?.id;if(!L)return;if(!(v.has(L)&&(v.get(L)?.length||0)>0)){t||a(L);try{await S(L)}catch{}}})()},[i,t,r,j,S,v,n,a]),l.useEffect(()=>{!j||D.current||!t&&n.length>0&&(a(n[0].id),D.current=!0)},[t,j,n,a]),l.useEffect(()=>{(async()=>{if(i!=="connected"||!j||N.current)return;const L=n.find(X=>X.id===t),K=L?.title?.toLowerCase()?.startsWith("new session");if(L&&K)a(L.id);else{const X=n.find(z=>z.title?.toLowerCase()?.startsWith("new session"));if(X)a(X.id);else{const z=await o();z?.id&&a(z.id)}}N.current=!0})()},[i,o,t,j,n,a]),e.jsxs("div",{className:"h-full w-full bg-background text-foreground flex flex-col",children:[r==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(vo,{title:"Sessions",onNewSession:M,onSettings:()=>s("settings")}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Lo,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>s("chat"),hideDirectoryControls:!0})})]}):r==="settings"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(vo,{title:"Settings",showBack:!0,onBack:C}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(by,{})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(vo,{title:n.find(W=>W.id===t)?.title||"Chat",showBack:!0,onBack:C,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:e.jsx(Ho,{})})})]}),f&&e.jsxs("div",{className:"absolute inset-0 z-50 bg-background/90 backdrop-blur-sm flex flex-col items-center justify-center gap-3 text-center px-4",children:[e.jsx(Bt,{className:"h-7 w-7 animate-spin text-muted-foreground"}),e.jsx("div",{className:"text-sm font-medium",children:i==="connecting"?p?"Reconnecting to OpenCode…":"Starting OpenCode API…":"Lost connection to OpenCode"}),d&&e.jsx("div",{className:"text-xs text-muted-foreground max-w-md",children:d})]})]})},vo=({title:r,showBack:s,onBack:t,onNewSession:n,onSettings:o,showContextUsage:a})=>{const{getCurrentModel:i}=kt(),c=me(h=>h.getContextUsage),d=i(),u=d?.limit&&typeof d.limit=="object"?d.limit:null,p=typeof u?.context=="number"?u.context:0,m=typeof u?.output=="number"?u.output:0,f=c(p,m);return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border bg-background shrink-0",children:[s&&t&&e.jsx("button",{onClick:t,className:"p-1 rounded hover:bg-muted transition-colors","aria-label":"Back to sessions",children:e.jsx(kl,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:r,children:r}),n&&e.jsx("button",{onClick:n,className:"p-1 rounded hover:bg-muted transition-colors","aria-label":"New session",children:e.jsx(os,{className:"h-5 w-5"})}),o&&e.jsx("button",{onClick:o,className:"p-1 rounded hover:bg-muted transition-colors","aria-label":"Settings",children:e.jsx(hr,{className:"h-5 w-5"})}),a&&f&&f.totalTokens>0&&e.jsx(Io,{totalTokens:f.totalTokens,percentage:f.percentage,contextLimit:f.contextLimit,outputLimit:f.outputLimit??0,size:"compact"})]})},by=()=>e.jsx("div",{className:"flex flex-col h-full",children:e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(pc,{})})}),sl=({...r})=>{const{theme:s="system"}=zu();return e.jsx(Hu,{theme:s,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)"},...r})},wy=(r=5e3)=>{const[s,t]=le.useState(null);return le.useEffect(()=>{if(!es())return;let n=!1,o=null;const a=async()=>{const i=await um();n||(t(i),o=setTimeout(a,r))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[r]),s},vy=({onClose:r})=>{const{sessions:s,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=me(),c=wy(4e3),d=l.useMemo(()=>{let m=0;return t.forEach(f=>{m+=f.length}),m},[t]),u=l.useMemo(()=>s.map(m=>{const f=t.get(m.id)?.length||0,h=n.get(m.id);return{id:m.id,title:m.title||"Untitled",messageCount:f,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:m.id===o}}).sort((m,f)=>f.lastAccessed-m.lastAccessed),[s,t,n,o]),p=t.size;return e.jsxs(ba,{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(Wu,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),r&&e.jsx(Ae,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:r,children:e.jsx(ds,{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:[p," / ",Ot.MAX_SESSIONS]})]})]}),c&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:c.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[c.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:c.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[Ot.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:[Ot.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:[Ot.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(Xe,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(m=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${m.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:m.title}),m.isStreaming&&e.jsx(Uu,{className:"h-3 w-3 text-primary animate-pulse"}),m.isZombie&&e.jsx("span",{className:"text-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${m.messageCount>Ot.VIEWPORT_MESSAGES?"text-warning":""}`,children:[m.messageCount," msgs"]}),m.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",m.backgroundCount]})]})]},m.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(Ae,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Us,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]}),e.jsx(Ae,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"}),e.jsx(Ae,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{},children:"Log State"})]})]})]})},jy="openchamber-message-cursors",br="cursors",Sy=1,Xc="openchamber.messageCursors",va=()=>typeof window<"u",ja=()=>va()&&typeof indexedDB<"u",Jc=()=>ja()?new Promise((r,s)=>{const t=indexedDB.open(jy,Sy);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(br)||n.createObjectStore(br)},t.onerror=()=>{s(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{r(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),Zc=()=>{if(!va())return{};try{const r=window.localStorage.getItem(Xc);if(!r)return{};const s=JSON.parse(r);return s&&typeof s=="object"?s:{}}catch{return{}}},ky=r=>{if(va())try{window.localStorage.setItem(Xc,JSON.stringify(r))}catch{}},Ny=async(r,s,t)=>{if(!r||!s)return;if(ja())try{const o=await Jc();await new Promise((a,i)=>{const c=o.transaction(br,"readwrite");c.objectStore(br).put({messageId:s,completedAt:t},r),c.oncomplete=()=>a(),c.onerror=()=>i(c.error??new Error("Cursor write failed")),c.onabort=()=>i(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=Zc();n[r]={messageId:s,completedAt:t},ky(n)},Cy=async r=>{if(!r)return null;if(ja())try{const t=await Jc(),n=await new Promise((o,a)=>{const i=t.transaction(br,"readonly"),d=i.objectStore(br).get(r);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 Zc()[r]??null},Ht=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},My=50,rl=new WeakMap,nl=r=>{if(!r||!Array.isArray(r))return 0;const s=rl.get(r);if(s!==void 0)return s;let t=0;for(let n=0;n<r.length;n++){const o=r[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(t+=a.length)}}return rl.set(r,t),t},Ay=10,ol=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.indexOf("_"),n=t>=0?s.slice(t+1):s;return!n||n.length<Ay?null:n},al=(r,s)=>{const t=ol(r),n=ol(s);return!t||!n||t.length!==n.length?!0:t>n},Uo=new Map,il=(r,s)=>{const t=`${r}:${s}`,n=Uo.get(t);if(n&&n.sessionId===r)return n.message;const i=(me.getState().messages.get(r)||[]).find(c=>c.info.id===s)||null;return Uo.set(t,{sessionId:r,message:i}),i},Dy=()=>{const{addStreamingPart:r,completeStreamingMessage:s,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:p}=me(),{checkConnection:m}=kt(),f=St($=>$.currentDirectory),h=l.useMemo(()=>{if(!a)return;try{const B=d?.(a);if(B?.path)return B.path}catch(B){console.warn("Failed to inspect worktree metadata for session directory:",B)}const $=c.find(B=>B.id===a);if($&&typeof $.directory=="string"&&$.directory.trim().length>0)return $.directory.trim()},[a,d,c]),g=l.useMemo(()=>{if(h&&h.length>0)return h;if(typeof f=="string"&&f.trim().length>0)return f.trim()},[h,f]),b=Pe($=>$.setEventStreamStatus),x=l.useRef(null),w=l.useCallback(($,B)=>{const J=B??null,I=x.current;if(!(I&&I.status===$&&I.hint===J)){if(x.current={status:$,hint:J},Ht()){const U={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[$]??"[INFO]",xe=J?`${U} SSE ${$}: ${J}`:`${U} SSE ${$}`;console.info(xe)}b($,J)}},[b]),S=l.useCallback(async $=>{Ht()&&console.info("[useEventStream] Bootstrapping state:",$);try{await Promise.all([p(),a?u(a):Promise.resolve()])}catch(B){console.warn("[useEventStream] Bootstrap failed:",$,B)}},[a,u,p]),v=l.useCallback(($,B,J)=>{Ht()&&console.debug(`[MessageTracker] ${$}: ${B}`,J)},[]),j=l.useCallback($=>{Ht()&&console.debug(`[MessageTracker] ${$}: reported`)},[]),k=l.useRef(null),y=l.useRef(null),A=l.useRef(0);l.useRef(new Set);const D=l.useRef(new Map),N=l.useRef(null),C=l.useRef(!1),M=l.useCallback(()=>{if(typeof document>"u")return"visible";const $=document.visibilityState;return $==="hidden"&&document.hasFocus()?"visible":$},[]),E=l.useRef(M()),F=l.useRef(typeof navigator>"u"?!0:navigator.onLine),W=l.useRef(!1),L=l.useRef(null),K=l.useRef(null),X=l.useRef(Date.now()),z=l.useRef(!1),G=l.useCallback($=>{const B=Date.now();B-X.current>25e3&&(S($),X.current=B)},[S]);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(z.current=!0)},[]);const H=l.useRef(new Map),oe=l.useRef(new Map),ve=l.useCallback($=>{if(!$)return;const B=Date.now(),J=D.current,I=J.get($);I&&B-I<3e3||(J.set($,B),setTimeout(async()=>{try{const _=await Ce.getSession($);if(_){const U={};typeof _.title=="string"&&_.title.length>0&&(U.title=_.title),_.summary!==void 0&&(U.summary=_.summary),Object.keys(U).length>0&&i($,U)}}catch(_){console.warn("Failed to refresh session metadata:",_)}},100))},[i]),Ee=l.useCallback(()=>{N.current||(N.current=setTimeout(()=>{N.current=null;try{p()}catch($){console.warn("Failed to refresh sessions after stream completion:",$)}},500))},[p]),Ie=l.useCallback(($,B)=>{if(oe.current.get($)===B)return;const I=H.current.get($);if(I&&(clearTimeout(I),H.current.delete($)),oe.current.set($,B),me.setState({sessionActivityPhase:new Map(oe.current)}),B==="cooldown"){const _=setTimeout(()=>{H.current.delete($),oe.current.get($)==="cooldown"&&(oe.current.set($,"idle"),me.setState({sessionActivityPhase:new Map(oe.current)}))},2e3);H.current.set($,_)}},[]),ge=l.useCallback($=>{if(X.current=Date.now(),Ht()&&console.debug("[useEventStream] Received event:",$.type,$.properties),!$.properties)return;const B=$.properties;if(!new Set(["session.abort","session.error"]).has($.type)){const I=(typeof B.session=="object"&&B.session!==null?B.session:null)||(typeof B.sessionInfo=="object"&&B.sessionInfo!==null?B.sessionInfo:null);if(I){const _=I,U=typeof _.id=="string"&&_.id.length>0?_.id:typeof _.sessionID=="string"&&_.sessionID.length>0?_.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof B.id=="string"&&B.id.length>0?B.id:void 0;if(U){const xe=typeof _.title=="string"?_.title:typeof B.title=="string"?B.title:void 0,ye=typeof _.summary=="object"&&_.summary!==null?_.summary:typeof B.summary=="object"&&B.summary!==null?B.summary:void 0;if(xe!==void 0||ye!==void 0){const se={};xe!==void 0&&(se.title=xe),ye!==void 0&&(se.summary=ye),i(U,se)}}}}switch($.type){case"server.connected":m();break;case"global.disposed":case"server.instance.disposed":{S("server_disposed_event");break}case"openchamber:session-activity":{if(!z.current)break;const I=typeof B.sessionId=="string"?B.sessionId:null,_=typeof B.phase=="string"?B.phase:null;I&&(_==="idle"||_==="busy"||_==="cooldown")&&(Ie(I,_),Ee());break}case"session.status":if(z.current)break;{const I=typeof B.sessionID=="string"?B.sessionID:null,_=typeof B.status=="object"&&B.status!==null?B.status:null,U=typeof _?.type=="string"?_.type:null;I&&U&&(Ie(I,U==="busy"||U==="retry"?"busy":"idle"),Ee())}break;case"message.part.updated":{const I=typeof B.part=="object"&&B.part!==null?B.part:null;if(!I)break;const _=I,U=typeof B.info=="object"&&B.info!==null?B.info:B,xe=typeof U.sessionID=="string"?U.sessionID:null,ye=typeof _.sessionID=="string"&&_.sessionID.length>0?_.sessionID:typeof xe=="string"&&xe.length>0?xe:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,se=typeof U.id=="string"?U.id:null,O=typeof _.messageID=="string"&&_.messageID.length>0?_.messageID:typeof se=="string"&&se.length>0?se:typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;if(!ye||!O){Ht()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:_.sessionID??xe??B.sessionID,messageID:_.messageID??se??B.messageID});break}const V=ye,P=O,te=me.getState().sessionMemoryState.get(V)?.trimmedHeadMaxId;if(te&&!al(P,te)){Ht()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:V,messageId:P,trimmedHeadMaxId:te});break}let je="assistant";if(U&&typeof U.role=="string")je=U.role;else{const $e=il(V,P);if($e){const ct=$e.info.role;typeof ct=="string"&&(je=ct)}}if(v(P,"part_received",{role:je}),je==="user"&&_.synthetic===!0){v(P,"skipped_synthetic_user_part");break}const ke={...I,type:I.type||"text"};v(P,"addStreamingPart_called"),r(V,P,ke,je);break}case"message.updated":{const I=typeof B.info=="object"&&B.info!==null?B.info:B,_=I,U=typeof _.sessionID=="string"&&_.sessionID.length>0?_.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,xe=typeof _.id=="string"&&_.id.length>0?_.id:typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;if(!U||!xe){Ht()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:_.sessionID??B.sessionID,messageID:_.id??B.messageID});break}const ye=U,se=xe,O=me.getState().sessionMemoryState.get(ye)?.trimmedHeadMaxId;if(O&&!al(se,O)){Ht()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:ye,messageId:se,trimmedHeadMaxId:O});break}if(z.current&&Ht())try{const Ge=B.parts||_.parts||[],Ue=(Array.isArray(Ge)?Ge.filter(Ke=>Ke?.type==="text"):[]).map(Ke=>{const Je=Ke;return typeof Je?.text=="string"?Je.text:typeof Je?.content=="string"?Je.content:""}).join(`
97
- `);console.info("[STREAM-TRACE] message.updated",{messageId:se,role:_.role,status:_.status,textLen:Ue.length,textPreview:Ue.slice(0,120),partsCount:Array.isArray(Ge)?Ge.length:0})}catch{}if(v(se,"message_updated",{role:_.role}),_.role==="user"){const Ge=B.parts||_.parts,tt=Array.isArray(Ge)?Ge:[],Ue={...I,userMessageMarker:!0,clientRole:"user"};if(t(ye,se,Ue),tt.length>0)for(let Ke=0;Ke<tt.length;Ke++){const Je=tt[Ke];if(Je.synthetic===!0)continue;const fe={...Je,type:Je?.type||"text",sessionID:Je?.sessionID||ye,messageID:Je?.messageID||se};r(ye,se,fe,"user")}v(se,"user_message_created_from_event",{partsCount:tt.length});break}const V=il(ye,se),P=nl(V?.parts||[]),te=V?.parts?.some(Ge=>Ge?.type==="step-finish"&&Ge.reason==="stop")??!1,je=B.parts||_.parts,ke=Array.isArray(je)?je:[],$e=ke.length>0,ht=typeof(_.time||{})?.completed=="number";if(!$e&&!ht)break;if(_.role==="assistant"&&$e){const Ge=nl(ke),tt=P>0&&Ge+My<P,Ue=ke.some(Ke=>Ke?.type==="step-finish"&&Ke.reason==="stop");if(tt&&!Ue){v(se,"skipped_shrinking_update",{incomingLen:Ge,existingLen:P});break}if(z.current){const Ke=P>0&&Ge<P,Je=ke.some(R=>{if(!R||R.type!=="text")return!1;const Q=R;return typeof Q.text=="string"&&Q.text.length>0});if(Ke&&!(Ue&&Je)){v(se,"desktop_shrinking_update_suppressed",{incomingLen:Ge,existingLen:P});break}}}if(t(ye,se,I),$e&&_.role!=="user"){const Ue=(me.getState().messages.get(ye)||[]).find(fe=>fe.info.id===se),Ke=!Ue||Ue.parts.length===0;v(se,Ke?"server_parts_injected":"server_parts_refreshed",{count:ke.length});const Je=z.current&&_.role==="assistant"?ke.filter(fe=>fe?.type!=="text"):ke;for(let fe=0;fe<Je.length;fe++){const R=Je[fe],Q={...R,type:R?.type||"text",sessionID:R?.sessionID||ye,messageID:R?.messageID||se};r(ye,se,Q,_.role),v(se,`server_part_${fe}`)}}const mt=I.time;if(I.role==="assistant"&&mt?.completed!==void 0&&I.role==="assistant"){const tt=me.getState().messages.get(ye)||[];let Ue=null,Ke="";for(let ce=0;ce<tt.length;ce++){const Z=tt[ce];Z.info.role==="assistant"&&Z.info.id>Ke&&(Ke=Z.info.id,Ue=Z.info.id)}if(se!==Ue)break;if(!(ke.some(ce=>ce?.type==="step-finish"&&ce.reason==="stop")||te)&&z.current){v(se,"desktop_completion_without_stop");break}const fe=mt?.completed!==void 0?mt?.completed:Date.now();if(mt?.completed||t(ye,se,{...I,time:{...mt??{},completed:fe}}),v(se,"completed",{timeCompleted:fe}),j(se),Ny(ye,se,fe),s(ye,se),!z.current){const ce=I.sessionID,Z=typeof ce=="string"&&ce.length>0?ce:ye;oe.current.get(Z)==="busy"&&Ie(Z,"cooldown")}const R=I.sessionID,Q=typeof R=="string"&&R.length>0?R:ye;ve(Q),I.summary&&typeof Q=="string"&&n(Q,null)}break}case"session.updated":{const I=typeof B.info=="object"&&B.info!==null?B.info:typeof B.sessionInfo=="object"&&B.sessionInfo!==null?B.sessionInfo:typeof B.session=="object"&&B.session!==null?B.session:B,_=typeof I.id=="string"&&I.id.length>0?I.id:typeof I.sessionID=="string"&&I.sessionID.length>0?I.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof B.id=="string"&&B.id.length>0?B.id:void 0;if(_){const U=typeof I.time=="object"&&I.time!==null?I.time:typeof B.time=="object"&&B.time!==null?B.time:null,xe=U&&typeof U.compacting=="number"?U.compacting:null;n(_,xe)}break}case"session.abort":{const I=typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,_=typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;I&&_&&s(I,_);break}case"permission.updated":a===B.sessionID&&o(B);break;case"permission.replied":break;case"todo.updated":{const I=typeof B.sessionID=="string"?B.sessionID:null,_=Array.isArray(B.todos)?B.todos:[];I&&_.length>0&&qh(I,_);break}}},[a,r,s,t,o,m,ve,Ee,n,i,v,j,Ie,S]),de=l.useCallback(()=>{const $=M();return E.current=$,$==="visible"&&F.current},[M]),we=l.useCallback(()=>{Ht()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:z.current,hasUnsubscribe:!!k.current,currentSessionId:a,effectiveDirectory:g,onlineStatus:F.current,visibilityState:E.current,lastEventTimestamp:X.current,reconnectAttempts:A.current})},[a,g]),De=l.useCallback(async()=>!0,[]),_e=l.useCallback(()=>{if(C.current){Ht()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(C.current=!0,y.current&&(clearTimeout(y.current),y.current=null),k.current){const $=k.current;k.current=null;try{$()}catch(B){console.warn("[useEventStream] Error during unsubscribe:",B)}}C.current=!1},[]),Ne=l.useCallback(async $=>{if(we(),!de()){W.current=!0,F.current?w("paused","Paused while hidden"):w("offline","Waiting for network");return}z.current&&(await De()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),$?.resetAttempts&&(A.current=0),_e(),X.current=Date.now(),w("connecting",null),Ht()&&console.info("[useEventStream] Starting event stream...");const B=I=>{console.warn("Event stream error:",I)},J=()=>{const I=W.current;A.current=0,W.current=!1,X.current=Date.now(),w("connected",null),m(),I?S("sse_reconnected"):a&&setTimeout(()=>{u(a).then(()=>ve(a)).catch(_=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",_)})},0)};if(Ht()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:g,isCleaningUp:C.current}),C.current){Ht()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const I=Ce.subscribeToEvents(ge,B,J,g),_=()=>{try{I()}catch(U){console.warn("[useEventStream] Error during unsubscribe:",U)}};C.current?_():k.current=_}catch(I){console.error("[useEventStream] Error during subscription:",I),B(I)}},[de,_e,w,m,a,u,ve,Ee,s,ge,g,Ie,De,we,S]),Fe=l.useCallback($=>{if(!de()){W.current=!0,_e(),F.current?w("paused","Paused while hidden"):w("offline","Waiting for network");return}const B=A.current+1;A.current=B;const J=$??`Retrying (${B})`;w("reconnecting",J);const I=B<=3?Math.min(1e3*Math.pow(2,B-1),8e3):Math.min(2e3*Math.pow(2,B-3),32e3),_=Math.floor(Math.random()*250),U=I+_;y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{Ne({resetAttempts:!1})},U)},[de,_e,w,Ne]);l.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=v);let $=null;z.current&&typeof window<"u"&&($=se=>{const O=typeof se.detail?.sessionId=="string"?se.detail.sessionId:null,V=typeof se.detail?.phase=="string"?se.detail.phase:null;O&&(V==="idle"||V==="busy"||V==="cooldown")&&(Ie(O,V),Ee())},window.addEventListener("openchamber:session-activity",$));const B=()=>{L.current&&(clearTimeout(L.current),L.current=null)},J=()=>{L.current||(L.current=setTimeout(()=>{const se=M();E.current=se,se!=="visible"?(_e(),W.current=!0,w("paused","Paused while hidden")):B()},5e3))},I=()=>{E.current=M(),E.current==="visible"?(B(),G("visibility_restore"),(W.current||!k.current)&&(console.info("[useEventStream] Visibility restored, triggering soft refresh..."),z.current||oe.current.clear(),a&&(u(a).catch(()=>{}),ve(a)),p(),w("connecting","Resuming stream"),Ne({resetAttempts:!0}))):(w("paused","Paused while hidden"),J())},_=()=>{E.current=M(),E.current==="visible"&&(B(),G("window_focus"),(W.current||!k.current)&&(console.info("[useEventStream] Window focused after pause, triggering soft refresh..."),z.current||oe.current.clear(),a&&(ve(a),u(a).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(se=>console.warn("[useEventStream] Failed to refresh messages:",se))),p(),w("connecting","Resuming stream"),Ne({resetAttempts:!0})))},U=()=>{F.current=!0,G("network_restored"),(W.current||!k.current)&&(w("connecting","Network restored"),Ne({resetAttempts:!0}))},xe=()=>{F.current=!1,W.current=!0,w("offline","Waiting for network"),_e()};typeof document<"u"&&document.addEventListener("visibilitychange",I),typeof window<"u"&&(window.addEventListener("online",U),window.addEventListener("offline",xe),window.addEventListener("focus",_));const ye=setTimeout(()=>{Ne({resetAttempts:!0})},100);return K.current&&clearInterval(K.current),K.current=setInterval(()=>{if(!de())return;Date.now()-X.current>25e3&&Promise.resolve().then(async()=>{try{await Ce.checkHealth()?X.current=Date.now():Fe("Refreshing stalled stream")}catch(O){console.warn("Health check after stale stream failed:",O),Fe("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(ye),$&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",$),typeof document<"u"&&document.removeEventListener("visibilitychange",I),typeof window<"u"&&(window.removeEventListener("online",U),window.removeEventListener("offline",xe),window.removeEventListener("focus",_)),B(),K.current&&(clearInterval(K.current),K.current=null);const se=H.current,O=oe.current;se.forEach(V=>clearTimeout(V)),se.clear(),O.clear(),Uo.clear(),W.current=!1,E.current=M(),F.current=typeof navigator>"u"?!0:navigator.onLine,_e(),N.current&&(clearTimeout(N.current),N.current=null),w("idle",null)}},[a,g,v,M,_e,w,Ne,Fe,u,ve,Ie,de])},Ey=()=>{const{createSession:r,abortCurrentOperation:s,initializeNewOpenChamberSession:t,armAbortPrompt:n,clearAbortPrompt:o,currentSessionId:a}=me(),{toggleCommandPalette:i,toggleHelpDialog:c,toggleSidebar:d,setSessionSwitcherOpen:u,setSessionCreateDialogOpen:p,setActiveMainTab:m,setSettingsDialogOpen:f}=Pe(),{agents:h}=kt(),{themeMode:g,setThemeMode:b}=kr(),{working:x}=Tc(),w=l.useRef(null),S=l.useRef(null),v=l.useRef(!1),j=l.useCallback(()=>{S.current&&(clearTimeout(S.current),S.current=null),w.current=null,o()},[o]);l.useEffect(()=>{const k=y=>{if(y.ctrlKey&&y.key==="x"&&(y.preventDefault(),i()),y.ctrlKey&&y.shiftKey&&y.key.toLowerCase()==="l"){const D=Rl()?.diagnostics;if(!D||(y.preventDefault(),v.current))return;v.current=!0,D.downloadLogs().then(({fileName:N,content:C})=>{const M=new Blob([C],{type:"text/plain;charset=utf-8"}),E=URL.createObjectURL(M),F=document.createElement("a");F.href=E,F.download=N||"desktop.log",document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(E)}).finally(()=>{v.current=!1});return}if(y.ctrlKey&&y.key==="h"&&(y.preventDefault(),c()),y.ctrlKey&&!y.metaKey&&y.key.toLowerCase()==="n"){if(y.preventDefault(),y.shiftKey){p(!0);return}r().then(A=>{A&&t(A.id,h)})}if((y.metaKey||y.ctrlKey)&&y.key==="/"){y.preventDefault();const A=["light","dark","system"],N=(A.indexOf(g)+1)%A.length;b(A[N])}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="g"){y.preventDefault();const{activeMainTab:A}=Pe.getState();m(A==="git"?"chat":"git");return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="t"){y.preventDefault();const{activeMainTab:A}=Pe.getState();m(A==="terminal"?"chat":"terminal");return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key===","){y.preventDefault();const{isSettingsDialogOpen:A}=Pe.getState();f(!A);return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="l"){y.preventDefault();const{isMobile:A,isSessionSwitcherOpen:D}=Pe.getState();A?u(!D):d();return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="i"){y.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(y.key==="Escape"){const A=a;if(!(x.canAbort&&!!A)){j();return}const N=Date.now(),C=w.current;if(C&&N<C){y.preventDefault(),j(),s();return}y.preventDefault();const M=n(3e3)??N+3e3;w.current=M,S.current&&clearTimeout(S.current);const E=Math.max(M-N,0);S.current=setTimeout(()=>{w.current&&Date.now()>=w.current&&j()},E||0);return}};return window.addEventListener("keydown",k),()=>{window.removeEventListener("keydown",k)}},[r,s,i,c,d,u,p,m,f,b,g,t,h,x,n,j,a]),l.useEffect(()=>()=>{j()},[j])},Ty=r=>r.role==="assistant",ll=r=>{const s=r.info;if(!Ty(s))return;const t=s.time?.completed;return typeof t=="number"?t:void 0},Sn=r=>{if(!r)return!1;if(r.role==="user")return!0;const s=r;return s.clientRole==="user"?!0:!!s.userMessageMarker},cl=r=>(Array.isArray(r?.parts)?r.parts:[]).map(n=>Rr(n)).join(" ").replace(/\s+/g," ").trim(),Iy=(r,s)=>{if(!r||!Sn(r.info))return-1;const t=cl(r),n=typeof r.info?.time?.created=="number"?r.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return s.forEach((i,c)=>{if(!Sn(i.info))return;const d=cl(i),u=!!(t&&d&&d===t),p=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,m=typeof n=="number"&&typeof p=="number"?Math.abs(p-n):null;if(u){const f=typeof m=="number"?m:0;f<a&&(o=c,a=f);return}!t&&!d&&typeof m=="number"&&m<1500&&m<a&&(o=c,a=m)}),o!==-1?o:typeof n=="number"?s.findIndex(i=>{if(!Sn(i.info))return!1;const c=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},Fy=()=>{const{currentSessionId:r,messages:s,streamingMessageIds:t}=me(),n=l.useMemo(()=>r?t.get(r)??null:null,[r,t]),o=l.useRef(void 0),a=l.useRef(0),i=l.useCallback(async()=>{if(!r||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=s.get(r)||[],u=await Ce.getSessionMessages(r),p=await Cy(r);if(!u)return;const m=d[d.length-1];if(m){const f=u.findIndex(b=>b.info.id===m.info.id),g=f===-1?Iy(m,u):f;if(g!==-1)if(g<u.length-1){const b=u.slice(g+1);console.log(`[SYNC] Found ${b.length} new messages to append`);const x=[...d,...b],{syncMessages:w}=me.getState();w(r,x)}else{const b=u[g],x=d[d.length-1],w=ll(b),S=ll(x);if(w&&!S){console.log("[SYNC] Last message completed on server");const v=[...d.slice(0,-1),b],{syncMessages:j}=me.getState();j(r,v)}}else if(Sn(m.info)){const b=u.slice(-Ot.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:x}=me.getState();x(r,b)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(p){const f=u.findIndex(h=>h.info.id===p.messageId);if(f!==-1){if(f<u.length-1){const g=u.slice(f+1).slice(-Ot.VIEWPORT_MESSAGES);if(g.length>0){console.log(`[SYNC] Restoring ${g.length} messages after cursor`);const{syncMessages:b}=me.getState();b(r,g)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-Ot.VIEWPORT_MESSAGES),{syncMessages:g}=me.getState();g(r,h)}}else if(u.length>0){const f=u.slice(-Ot.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${f.length} messages`);const{syncMessages:h}=me.getState();h(r,f)}}catch(d){console.debug("Background sync failed:",d)}}},[r,s,n]);l.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[i]),l.useEffect(()=>{if(!r||n)return;const c=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[r,n,i]),l.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[i])},Py=()=>{l.useEffect(()=>{let r=!1;return(async()=>{try{const t=await Ce.getSessionStatus();if(r||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,c=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&me.setState({sessionActivityPhase:n})}catch{}})(),()=>{r=!0}},[])};function Ry(){const{git:r}=rr(),s=St(i=>i.currentDirectory),{setActiveDirectory:t,startPolling:n,stopPolling:o,fetchAll:a}=Mt();l.useEffect(()=>{if(!s||!r){o();return}return t(s),a(s,r),n(r),()=>{o()}},[s,r,t,n,o,a])}function Ly({children:r}){return Ry(),e.jsx(e.Fragment,{children:r})}const _y=()=>{const[{isUpdating:r,message:s},t]=l.useState(()=>Cm());return l.useEffect(()=>Nm(t),[]),r?e.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-background/80 backdrop-blur-md",children:e.jsx("div",{className:"w-full max-w-sm rounded-xl border border-border/40 bg-card/90 px-6 py-8 text-center shadow-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full border-2 border-primary/30 border-t-transparent text-primary",children:e.jsx(Ds,{className:"h-7 w-7 animate-spin"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"typography-h3 font-semibold text-foreground",children:"Updating OpenCode"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:s})]})]})})}):null};function dl({apis:r,children:s}){return e.jsx(ua.Provider,{value:r,children:s})}const Oy="curl -fsSL https://opencode.ai/install | bash",By=3e3;function $y({onCopy:r}){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:r,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Ls,{className:"h-4 w-4"})})]})}const zy=3e4;function Hy({onCliAvailable:r}){const[s,t]=l.useState(!1),[n,o]=l.useState(!1),[a,i]=l.useState(!1);l.useEffect(()=>{const p=setTimeout(()=>o(!0),zy);return()=>clearTimeout(p)},[]),l.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const c=l.useCallback(async p=>{if(!p.target.closest("button, a, input, select, textarea, code")&&p.button===0&&a)try{const{getCurrentWindow:m}=await Lr(async()=>{const{getCurrentWindow:h}=await import("./vendor-.pnpm-B7ko08Tb.js").then(g=>g.b$);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await m().startDragging()}catch(m){console.error("Failed to start window dragging:",m)}},[a]),d=l.useCallback(async()=>{try{const p=await fetch("/health");return p.ok?(await p.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=l.useCallback(async()=>{try{await navigator.clipboard.writeText(Oy),t(!0),setTimeout(()=>t(!1),2e3)}catch(p){console.error("Failed to copy:",p)}},[]);return l.useEffect(()=>{const p=async()=>{await d()&&r?.()},m=setInterval(p,By);return p(),()=>clearInterval(m)},[d,r]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(No,{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:s?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($y,{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(No,{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."]})]})]})}function Wy({apis:r}){const{initializeApp:s,loadProviders:t,isInitialized:n}=kt(),{error:o,clearError:a,loadSessions:i}=me(),c=St(j=>j.currentDirectory),d=St(j=>j.isSwitchingDirectory),[u,p]=l.useState(!1),{uiFont:m,monoFont:f}=Kc(),[h,g]=l.useState(()=>r.runtime.isDesktop),[b,x]=l.useState(()=>r.runtime.isVSCode),[w,S]=l.useState(()=>r.runtime.isDesktop?mm():!0);l.useEffect(()=>{g(r.runtime.isDesktop),x(r.runtime.isVSCode)},[r.runtime.isDesktop,r.runtime.isVSCode]),l.useEffect(()=>(za(r),()=>za(null)),[r]),l.useEffect(()=>{if(typeof document>"u")return;const j=document.documentElement,k=Qi[m]?.stack??Qi[uy].stack,y=Js[f]?.stack??Js[jn].stack;j.style.setProperty("--font-sans",k),j.style.setProperty("--font-heading",k),j.style.setProperty("--font-family-sans",k),j.style.setProperty("--font-mono",y),j.style.setProperty("--font-family-mono",y),j.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[m,f]),l.useEffect(()=>{if(n){const k=setTimeout(()=>{const y=document.getElementById("initial-loading");y&&(y.classList.add("fade-out"),setTimeout(()=>{y.remove()},300))},150);return()=>clearTimeout(k)}},[n]),l.useEffect(()=>{const j=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!n&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},5e3);return()=>clearTimeout(j)},[n]),l.useEffect(()=>{(async()=>{await s(),await t()})()},[s,t]),l.useEffect(()=>{if(d)return;(async()=>{Ce.setDirectory(c),await i()})()},[c,d,i]),Dy(),Ey(),Fy(),Py(),l.useEffect(()=>{const j=k=>{(k.metaKey||k.ctrlKey)&&k.shiftKey&&k.key==="M"&&(k.preventDefault(),p(y=>!y))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[]),l.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const v=l.useCallback(()=>{S(!0),window.location.reload()},[]);return h&&!w?e.jsx(ls,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(Hy,{onCliAvailable:v})})}):b?e.jsx(ls,{children:e.jsx(dl,{apis:r,children:e.jsx(Yi,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(yy,{}),e.jsx(sl,{})]})})})}):e.jsx(ls,{children:e.jsx(dl,{apis:r,children:e.jsx(Ly,{children:e.jsx(Yi,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(xy,{}),e.jsx(sl,{}),e.jsx(_y,{}),u&&e.jsx(vy,{onClose:()=>p(!1)})]})})})})})}const Qc=async()=>{if(typeof window>"u")return;let r=null,s=null;try{r=window.localStorage.getItem("homeDirectory"),s=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const t=St.getState();r&&t.homeDirectory!==r&&t.synchronizeHomeDirectory(r),s&&t.setDirectory(s,{showOverlay:!1})},ed="/auth/session",Uy=async()=>fetch(ed,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Vy=async r=>fetch(ed,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:r})}),Sa=({children:r})=>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:r})]}),Gy=({message:r="Preparing workspace…"})=>e.jsx(Sa,{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:r})})}),qy=({onRetry:r})=>e.jsx(Sa,{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(Ae,{type:"button",onClick:r,className:"w-full max-w-xs",children:"Retry"})]})}),Ky=({children:r})=>{const s=l.useMemo(()=>es(),[]),t=l.useMemo(()=>rs(),[]),n=s||t,[o,a]=l.useState(()=>n?"authenticated":"pending"),[i,c]=l.useState(""),[d,u]=l.useState(!1),[p,m]=l.useState(""),f=l.useRef(null),h=l.useRef(n),g=l.useCallback(async()=>{if(n){a("authenticated");return}a(x=>x==="authenticated"?x:"pending");try{const x=await Uy();if(x.ok){a("authenticated"),m("");return}if(x.status===401){a("locked");return}a("error")}catch(x){console.warn("Failed to check session status:",x),a("error")}},[n]);l.useEffect(()=>{n||g()},[g,n]),l.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),l.useEffect(()=>{o==="locked"&&f.current&&(f.current.focus(),f.current.select())},[o]),l.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await Ol(),await Bl(),await Qc()))())},[n,o]);const b=async x=>{if(x.preventDefault(),!(!i||d)){u(!0),m("");try{const w=await Vy(i);if(w.ok){c(""),a("authenticated");return}if(w.status===401){m("Incorrect password. Try again."),a("locked");return}m("Unexpected response from server."),a("error")}catch(w){console.warn("Failed to submit UI password:",w),m("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(Gy,{}):o==="error"?e.jsx(qy,{onRetry:()=>void g()}):o==="locked"?e.jsx(Sa,{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:b,className:"w-full space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Vu,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(Pt,{id:"openchamber-ui-password",ref:f,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:x=>{c(x.target.value),p&&m("")},className:"pl-10","aria-invalid":!!p||void 0,"aria-describedby":p?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(Ae,{type:"submit",size:"icon",disabled:!i||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(Bt,{className:"h-4 w-4 animate-spin"}):e.jsx(Gu,{className:"h-4 w-4"})})]}),p&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:p})]})]})}):e.jsx(e.Fragment,{children:r})},jo=r=>{if(!r||typeof r!="string")return null;const s=r.trim();if(!s.startsWith("#"))return null;let t=s.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(c=>c+c).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,i=n&255;return`${o} ${a} ${i}`};class Yy{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(s){const t=[];return t.push(...this.generateTailwindVariables(s)),t.push(...this.generatePrimaryColors(s.colors.primary)),t.push(...this.generateSurfaceColors(s.colors.surface)),t.push(...this.generateInteractiveColors(s.colors.interactive)),t.push(...this.generateStatusColors(s.colors.status)),t.push(...this.generateSyntaxColors(s.colors.syntax)),t.push(...this.generateComponentColors(s.colors,s)),t.push(...this.generateTypographyVariables()),s.config&&t.push(...this.generateConfigVariables(s.config)),t.join(`
98
- `)}generateTailwindVariables(s){const t=[];t.push(` --background: ${s.colors.surface.background} !important;`),t.push(` --foreground: ${s.colors.surface.foreground} !important;`),t.push(` --muted: ${s.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${s.colors.surface.mutedForeground} !important;`),t.push(` --card: ${s.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${s.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${s.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${s.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${s.colors.interactive.border} !important;`),t.push(` --input: ${s.colors.interactive.border} !important;`),t.push(` --primary: ${s.colors.primary.base} !important;`),t.push(` --primary-foreground: ${s.colors.primary.foreground} !important;`),t.push(` --secondary: ${s.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${s.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${s.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${s.colors.surface.foreground} !important;`),t.push(` --destructive: ${s.colors.status.error} !important;`),t.push(` --destructive-foreground: ${s.colors.status.errorForeground} !important;`),t.push(` --ring: ${s.colors.interactive.focusRing} !important;`),s.config?.radius?.md&&t.push(` --radius: ${s.config.radius.md} !important;`);const n=jo(s.colors.surface.muted),o=jo(s.colors.surface.subtle),a=jo(s.colors.interactive.border);t.push(` --sidebar-base: ${s.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${s.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${s.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${s.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${s.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: ${s.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${s.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${s.colors.interactive.focusRing} !important;`);const i=s.metadata.variant==="dark",c=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=s.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return s.colors.charts?.series&&Array.isArray(s.colors.charts.series)&&s.colors.charts.series.forEach((u,p)=>{t.push(` --chart-${p+1}: ${u};`)}),s.colors.loading?(t.push(` --loading-spinner: ${s.colors.loading.spinner||s.colors.primary.base};`),t.push(` --loading-spinner-track: ${s.colors.loading.spinnerTrack||s.colors.surface.muted};`)):(t.push(` --loading-spinner: ${s.colors.primary.base};`),t.push(` --loading-spinner-track: ${s.colors.surface.muted};`)),t}apply(s){const t=this.generate(s),n=document.createElement("style");n.id="opencode-theme-variables";let o="";s.metadata.variant==="dark"?(o=`:root {
99
- ${t}
100
- }
101
-
102
- .dark {
103
- ${t}
104
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
105
- ${t}
106
- }
107
-
108
- :root:not(.dark) {
109
- ${t}
110
- }`,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",s.metadata.variant)}generatePrimaryColors(s){const t=[];return t.push(` --primary-base: ${s.base};`),t.push(` --primary-hover: ${s.hover||this.darken(s.base,10)};`),t.push(` --primary-active: ${s.active||this.darken(s.base,20)};`),t.push(` --primary-foreground: ${s.foreground||"#ffffff"};`),t.push(` --primary-muted: ${s.muted||this.opacity(s.base,.5)};`),t.push(` --primary-emphasis: ${s.emphasis||this.lighten(s.base,10)};`),t}generateSurfaceColors(s){const t=[];return t.push(` --surface-background: ${s.background};`),t.push(` --surface-foreground: ${s.foreground};`),t.push(` --surface-muted: ${s.muted};`),t.push(` --surface-muted-foreground: ${s.mutedForeground};`),t.push(` --surface-elevated: ${s.elevated};`),t.push(` --surface-elevated-foreground: ${s.elevatedForeground};`),t.push(` --surface-overlay: ${s.overlay};`),t.push(` --surface-subtle: ${s.subtle};`),t}generateInteractiveColors(s){const t=[];return t.push(` --interactive-border: ${s.border};`),t.push(` --interactive-border-hover: ${s.borderHover};`),t.push(` --interactive-border-focus: ${s.borderFocus};`),t.push(` --interactive-selection: ${s.selection};`),t.push(` --interactive-selection-foreground: ${s.selectionForeground};`),t.push(` --interactive-focus: ${s.focus};`),t.push(` --interactive-focus-ring: ${s.focusRing};`),t.push(` --interactive-cursor: ${s.cursor};`),t.push(` --interactive-hover: ${s.hover};`),t.push(` --interactive-active: ${s.active};`),t}generateStatusColors(s){const t=[];return t.push(` --status-error: ${s.error};`),t.push(` --status-error-foreground: ${s.errorForeground};`),t.push(` --status-error-background: ${s.errorBackground};`),t.push(` --status-error-border: ${s.errorBorder};`),t.push(` --status-warning: ${s.warning};`),t.push(` --status-warning-foreground: ${s.warningForeground};`),t.push(` --status-warning-background: ${s.warningBackground};`),t.push(` --status-warning-border: ${s.warningBorder};`),t.push(` --status-success: ${s.success};`),t.push(` --status-success-foreground: ${s.successForeground};`),t.push(` --status-success-background: ${s.successBackground};`),t.push(` --status-success-border: ${s.successBorder};`),t.push(` --status-info: ${s.info};`),t.push(` --status-info-foreground: ${s.infoForeground};`),t.push(` --status-info-background: ${s.infoBackground};`),t.push(` --status-info-border: ${s.infoBorder};`),t}generateSyntaxColors(s){const t=[];t.push(` --syntax-background: ${s.base.background};`),t.push(` --syntax-foreground: ${s.base.foreground};`),t.push(` --syntax-comment: ${s.base.comment};`),t.push(` --syntax-keyword: ${s.base.keyword};`),t.push(` --syntax-string: ${s.base.string};`),t.push(` --syntax-number: ${s.base.number};`),t.push(` --syntax-function: ${s.base.function};`),t.push(` --syntax-variable: ${s.base.variable};`),t.push(` --syntax-type: ${s.base.type};`),t.push(` --syntax-operator: ${s.base.operator};`);const n=this.generateSyntaxTokens(s);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(s){const t=s.base,n=s.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(s,t){const n=[];return s.markdown?n.push(...this.generateMarkdownColors(s.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),s.chat?n.push(...this.generateChatColors(s.chat,t)):n.push(...this.generateDefaultChatColors(t)),s.tools?n.push(...this.generateToolColors(s.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(s,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${s.heading1||o};`),n.push(` --markdown-heading2: ${s.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${s.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${s.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${s.link||o};`),n.push(` --markdown-link-hover: ${s.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${s.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${s.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${s.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${s.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${s.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${s.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${s.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${s.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${s.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(s){const t=[],n=s.colors.primary.base,o=s.colors.chat?.background||s.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: ${s.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${s.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${s.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${s.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${s.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${s.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(s.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${s.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${s.colors.interactive.border};`),t}generateChatColors(s,t){const n=[],o=s.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${s.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${s.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${s.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${s.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${s.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${s.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${s.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(s){const t=[];return t.push(` --chat-background: ${s.colors.surface.background};`),t.push(` --chat-user-message: ${s.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${s.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${s.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${s.colors.surface.muted};`),t.push(` --chat-timestamp: ${s.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${s.colors.interactive.border};`),t.push(` --chat-typing: ${s.colors.surface.mutedForeground};`),t}generateToolColors(s,t){const n=[];return n.push(` --tools-background: ${s?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${s?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${s?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${s?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${s?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${s?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),s?.edit?(n.push(` --tools-edit-added: ${s.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${s.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${s.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${s.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${s.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${s.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${s.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(s){const t=[];return t.push(` --tools-background: ${this.opacity(s.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(s.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(s.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${s.colors.surface.mutedForeground};`),t.push(` --tools-title: ${s.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${s.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${s.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${s.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(s){const t=[];return s&&(s.fonts&&(s.fonts.sans&&(t.push(` --font-sans: ${s.fonts.sans};`),t.push(` --font-family-sans: ${s.fonts.sans};`)),s.fonts.mono&&(t.push(` --font-mono: ${s.fonts.mono};`),t.push(` --font-family-mono: ${s.fonts.mono};`)),s.fonts.heading&&t.push(` --font-heading: ${s.fonts.heading};`)),s.radius&&(s.radius.none&&t.push(` --radius-none: ${s.radius.none};`),s.radius.sm&&t.push(` --radius-sm: ${s.radius.sm};`),s.radius.md&&t.push(` --radius-md: ${s.radius.md};`),s.radius.lg&&t.push(` --radius-lg: ${s.radius.lg};`),s.radius.xl&&t.push(` --radius-xl: ${s.radius.xl};`),s.radius.full&&t.push(` --radius-full: ${s.radius.full};`)),s.transitions&&(s.transitions.fast&&t.push(` --transition-fast: ${s.transitions.fast};`),s.transitions.normal&&t.push(` --transition-normal: ${s.transitions.normal};`),s.transitions.slow&&t.push(` --transition-slow: ${s.transitions.slow};`))),t}generateTypographyVariables(){const s=[],t=rs()?dm:ra;return s.push(" /* Semantic Typography Variables */"),s.push(" --ui-regular-font-weight: 400;"),s.push(" /* Markdown content - all markdown elements use same size */"),s.push(` --text-markdown: ${t.markdown};`),s.push(" /* Code content - all code elements use same size */"),s.push(` --text-code: ${t.code};`),s.push(" /* UI headers - dialog titles, panel headers */"),s.push(` --text-ui-header: ${t.uiHeader};`),s.push(" /* UI labels - buttons, menus, navigation */"),s.push(` --text-ui-label: ${t.uiLabel};`),s.push(" /* Metadata - timestamps, status, helper text */"),s.push(` --text-meta: ${t.meta};`),s.push(" /* Micro text - badges, shortcuts, indicators */"),s.push(` --text-micro: ${t.micro};`),s.push(" /* Heading line height and letter spacing */"),s.push(" --h1-line-height: 1.25rem;"),s.push(" --h2-line-height: 1.25rem;"),s.push(" --h3-line-height: 1.5rem;"),s.push(" --h4-line-height: 1.5rem;"),s.push(" --h5-line-height: 1.5rem;"),s.push(" --h6-line-height: 1.5rem;"),s.push(" --h1-letter-spacing: -0.025em;"),s.push(" --h2-letter-spacing: -0.02em;"),s.push(" --h3-letter-spacing: -0.015em;"),s.push(" --h4-letter-spacing: -0.01em;"),s.push(" --h5-letter-spacing: 0;"),s.push(" --h6-letter-spacing: 0.01em;"),s.push(" /* UI element line height and letter spacing */"),s.push(" --ui-button-line-height: 1.375rem;"),s.push(" --ui-button-letter-spacing: 0.02em;"),s.push(" --ui-button-font-weight: 500;"),s.push(" --ui-label-line-height: 1rem;"),s.push(" --ui-label-letter-spacing: 0.03em;"),s.push(" --ui-label-font-weight: 500;"),s.push(" --ui-caption-line-height: 1rem;"),s.push(" --ui-caption-letter-spacing: 0.025em;"),s.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Markdown line height and letter spacing */"),s.push(" --markdown-body-line-height: 1.5rem;"),s.push(" --markdown-body-letter-spacing: 0;"),s.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-h1-line-height: 1.25rem;"),s.push(" --markdown-h1-letter-spacing: -0.025em;"),s.push(" --markdown-h2-line-height: 1.25rem;"),s.push(" --markdown-h2-letter-spacing: -0.02em;"),s.push(" --markdown-h3-line-height: 1.5rem;"),s.push(" --markdown-h3-letter-spacing: -0.015em;"),s.push(" --markdown-h4-line-height: 1.5rem;"),s.push(" --markdown-h4-letter-spacing: -0.01em;"),s.push(" --markdown-h5-line-height: 1.5rem;"),s.push(" --markdown-h5-letter-spacing: 0;"),s.push(" --markdown-h6-line-height: 1.5rem;"),s.push(" --markdown-h6-letter-spacing: 0.01em;"),s.push(" --markdown-list-line-height: 1.375rem;"),s.push(" --markdown-code-block-line-height: 1rem;"),s.push(" --ui-button-small-line-height: 1.25rem;"),s.push(" --ui-button-small-letter-spacing: 0.02em;"),s.push(" --ui-button-small-font-weight: 500;"),s.push(" --markdown-body-small-line-height: 1.375rem;"),s.push(" --markdown-body-small-letter-spacing: 0;"),s.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-button-large-line-height: 1.5rem;"),s.push(" --ui-button-large-letter-spacing: 0.02em;"),s.push(" --ui-button-large-font-weight: 500;"),s.push(" --markdown-body-large-line-height: 1.625rem;"),s.push(" --markdown-body-large-letter-spacing: 0;"),s.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Code line height and letter spacing */"),s.push(" --code-inline-line-height: 1rem;"),s.push(" --code-inline-letter-spacing: 0;"),s.push(" --code-inline-font-weight: 400;"),s.push(" --code-block-line-height: 1.4rem;"),s.push(" --code-block-letter-spacing: 0;"),s.push(" --code-block-font-weight: 400;"),s.push(" --code-line-numbers-line-height: 1.25rem;"),s.push(" --code-line-numbers-letter-spacing: 0;"),s.push(" --code-line-numbers-font-weight: 400;"),s.push(" /* Additional UI element line height and letter spacing */"),s.push(" --ui-badge-line-height: 1rem;"),s.push(" --ui-badge-letter-spacing: 0.025em;"),s.push(" --ui-badge-font-weight: 500;"),s.push(" --ui-tooltip-line-height: 1rem;"),s.push(" --ui-tooltip-letter-spacing: 0.025em;"),s.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-input-line-height: 1.375rem;"),s.push(" --ui-input-letter-spacing: 0.02em;"),s.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-helper-text-line-height: 1rem;"),s.push(" --ui-helper-text-letter-spacing: 0.025em;"),s.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Additional markdown line height and letter spacing */"),s.push(" --markdown-blockquote-line-height: 1.5rem;"),s.push(" --markdown-blockquote-letter-spacing: 0;"),s.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-list-letter-spacing: 0;"),s.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-link-line-height: 1.5rem;"),s.push(" --markdown-link-letter-spacing: 0;"),s.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-code-line-height: 1.35;"),s.push(" --markdown-code-letter-spacing: 0;"),s.push(" --markdown-code-font-weight: 400;"),s.push(" --markdown-code-block-letter-spacing: 0;"),s.push(" --markdown-code-block-font-weight: 400;"),s}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(s,t){return s.startsWith("#")?`${s}${Math.round(t*255).toString(16).padStart(2,"0")}`:s.startsWith("rgb")?s.replace("rgb","rgba").replace(")",`, ${t})`):s}removeTransparency(s){return s.startsWith("#")?s.length===9?s.slice(0,7):s.length===5?s.slice(0,4):s:s.startsWith("rgba")?s.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):s}addTransparency(s,t){if(s.startsWith("#")){const n=s.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 s.startsWith("rgb")?s.replace("rgb","rgba").replace(")",`, ${t})`):s}darken(s,t){if(s.startsWith("#")){const n=parseInt(s.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,i=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return s}lighten(s,t){if(s.startsWith("#")){const n=parseInt(s.slice(1),16),o=Math.round(2.55*t),a=(n>>16)+o,i=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return s}adjustHue(s,t){return this.lighten(s,t/10)}emphasize(s){return this.lighten(s,15)}kebabCase(s){return s.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const ka={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"}}},Na={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"}}},Ur=[ka,Na];function $n(r){return Ur.find(s=>s.metadata.id===r)}const td=ka.metadata.id,sd=Na.metadata.id,Xy=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,rd=r=>r==="dark"?Na:ka,Jy=r=>(Ur.find(t=>t.metadata.variant===r)??rd(r)).metadata.id,mn=(r,s)=>{const t=$n(r);return t&&t.metadata.variant===s?t:Ur.find(o=>o.metadata.variant===s)??rd(s)},Zy=typeof window<"u"?l.useLayoutEffect:l.useEffect,zn=(r,s)=>{if(!r)return s==="light"?td:sd;const t=$n(r);return t&&t.metadata.variant===s?t.metadata.id:Jy(s)},Qy=r=>{let s=td,t=sd,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const m=$n(d);m&&(n=m.metadata.variant==="dark"?"dark":"light",m.metadata.variant==="dark"?t=m.metadata.id:s=m.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);s=zn(a,"light"),t=zn(i,"dark")}if(r){const o=$n(r);o&&(o.metadata.variant==="light"?s=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:s,darkThemeId:t}};function eb({children:r,defaultThemeId:s}){const t=le.useMemo(()=>new Yy,[]),[n,o]=le.useState(()=>Qy(s)),[a,i]=le.useState(()=>Xy()),[c,d]=le.useState(()=>typeof window>"u"||!rs()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=le.useMemo(()=>rs(),[]),p=le.useMemo(()=>u&&c?c:n.themeMode==="light"?mn(n.lightThemeId,"light"):n.themeMode==="dark"||a?mn(n.darkThemeId,"dark"):mn(n.lightThemeId,"light"),[u,n,a,c]),m=le.useMemo(()=>u&&c?[c,...Ur]:Ur,[u,c]);le.useEffect(()=>{if(!u)return;const j=A=>{d(A);const D=A.metadata.variant==="dark"?"dark":"light",N=Pe.getState();N.theme!==D&&N.setTheme(D)},k=A=>{const D=A.detail;D?.theme&&j(D.theme)},y=window.__OPENCHAMBER_VSCODE_THEME__;return y&&j(y),window.addEventListener("openchamber:vscode-theme",k),()=>window.removeEventListener("openchamber:vscode-theme",k)},[u]);const f=le.useCallback(j=>{if(typeof document>"u")return;const k=j.colors.surface.background;es()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=k;let y=document.querySelector('meta[name="theme-color"]');y||(y=document.createElement("meta"),y.setAttribute("name","theme-color"),document.head.appendChild(y)),y.setAttribute("content",k);const A=j.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let D=document.querySelector(`meta[name="theme-color"][media="${A}"]`);D||(D=document.createElement("meta"),D.setAttribute("name","theme-color"),D.setAttribute("media",A),document.head.appendChild(D)),D.setAttribute("content",k)},[]),h=le.useCallback(j=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",j)},[]);Zy(()=>{if(typeof window>"u")return;t.apply(p),h(u),f(p);const j=document.documentElement;j.classList.remove("light","dark"),j.classList.add(p.metadata.variant)},[h,t,p,u,f]),le.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const j=window.matchMedia("(prefers-color-scheme: dark)"),k=y=>{i(y.matches)};return i(j.matches),j.addEventListener("change",k),()=>j.removeEventListener("change",k)},[n.themeMode]),le.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",p.metadata.id),localStorage.setItem("selectedThemeVariant",p.metadata.variant==="light"?"light":"dark"))},[n,p]),le.useEffect(()=>{Ns({themeId:p.metadata.id,themeVariant:p.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[p.metadata.id,p.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),le.useEffect(()=>{if(typeof window>"u")return;const j=k=>{const y=k.detail;y&&o(A=>{let D=A.themeMode;y.useSystemTheme===!0?D="system":y.useSystemTheme===!1&&(y.themeVariant==="dark"||y.themeVariant==="light")&&(D=y.themeVariant);let N=A.lightThemeId;typeof y.lightThemeId=="string"&&y.lightThemeId.length>0&&(N=zn(y.lightThemeId,"light"));let C=A.darkThemeId;return typeof y.darkThemeId=="string"&&y.darkThemeId.length>0&&(C=zn(y.darkThemeId,"dark")),D===A.themeMode&&N===A.lightThemeId&&C===A.darkThemeId?A:{themeMode:D,lightThemeId:N,darkThemeId:C}})};return window.addEventListener("openchamber:settings-synced",j),()=>window.removeEventListener("openchamber:settings-synced",j)},[]);const g=le.useCallback(j=>{const k=m.find(y=>y.metadata.id===j);k&&o(y=>k.metadata.variant==="dark"?y.darkThemeId===k.metadata.id&&y.themeMode==="dark"?y:{...y,darkThemeId:k.metadata.id,themeMode:"dark"}:y.lightThemeId===k.metadata.id&&y.themeMode==="light"?y:{...y,lightThemeId:k.metadata.id,themeMode:"light"})},[m]),b=le.useCallback(j=>{o(k=>k.themeMode===j?k:{...k,themeMode:j})},[]),x=le.useCallback(j=>{if(j){o(y=>y.themeMode==="system"?y:{...y,themeMode:"system"});return}const k=p.metadata.variant==="dark"?"dark":"light";o(y=>y.themeMode===k?y:{...y,themeMode:k})},[p.metadata.variant]),w=le.useCallback(j=>{const k=m.find(y=>y.metadata.id===j&&y.metadata.variant==="light");k&&o(y=>y.lightThemeId===k.metadata.id?y:{...y,lightThemeId:k.metadata.id})},[m]),S=le.useCallback(j=>{const k=m.find(y=>y.metadata.id===j&&y.metadata.variant==="dark");k&&o(y=>y.darkThemeId===k.metadata.id?y:{...y,darkThemeId:k.metadata.id})},[m]),v={currentTheme:p,availableThemes:m,setTheme:g,isSystemPreference:n.themeMode==="system",setSystemPreference:x,themeMode:n.themeMode,setThemeMode:b,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:w,setDarkThemePreference:S};return e.jsx(fa.Provider,{value:v,children:r})}const tb=({children:r})=>{const{theme:s,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=Pe();return l.useLayoutEffect(()=>{t(),o(),i()},[s,t,n,o,a,i]),l.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{s==="system"&&t()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[s,t]),e.jsx(e.Fragment,{children:r})},sb={getLastAssistantMessage(){const r=me.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const t=r.messages.get(s);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(f=>{const h={id:f.id,type:f.type};return f.type==="text"?(h.text=f.text,h.textLength=f.text?.length||0):f.type==="tool"?(h.tool=f.tool,h.state=f.state?.status):(f.type==="step-start"||f.type==="step-finish")&&(h.isStepMarker=!0),h}),i=a.some(f=>f.type==="text"&&f.text&&f.text.trim().length>0),c=a.some(f=>f.type==="tool"),d=a.some(f=>f.type==="step-start"||f.type==="step-finish"),u=a.length===0,p=!i&&!c&&(!u||d),m={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:p,raw:o};return console.log("[INSPECT] Last Assistant Message:",m),console.log("[SUMMARY] Summary:",{messageId:m.messageId,partsCount:m.partsCount,isEmpty:m.isEmpty,isEmptyResponse:m.isEmptyResponse,hasText:i,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!c}),m.isEmpty&&console.warn("[WARNING] Message has NO parts!"),m.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!c&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),m}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(r,s=80){return!r||typeof r!="string"||r.length<=s?r:r.substring(0,s)+"…"},truncateMessages(r){return r.map(s=>({...s,parts:(s.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(r=!1){const s=me.getState(),t=s.currentSessionId;if(!t)return console.log("[ERROR] No active session"),[];const n=s.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`)}),r?this.truncateMessages(n):n},checkLastMessage(){const r=this.getLastAssistantMessage();if(!r)return!1;const s=r.isEmpty||r.isEmptyResponse;return s?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:r.messageId,isEmpty:r.isEmpty,isEmptyResponse:r.isEmptyResponse,partsCount:r.partsCount}),r.parts.length>0&&console.log("Parts:",r.parts)):console.log("[OK] Last message looks good!"),s},getStreamingState(){const r=me.getState(),s=r.currentSessionId?r.streamingMessageIds.get(r.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:s,streamingMessageIds:Array.from(r.streamingMessageIds.entries()),messageStreamStates:Array.from(r.messageStreamStates.entries())}),{streamingMessageId:s,streamingMessageIds:r.streamingMessageIds,streamStates:r.messageStreamStates}},findEmptyMessages(){const r=me.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),[];const n=(r.messages.get(s)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!i&&!c});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
111
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
112
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
113
- `),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)
114
- `),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(r={}){const{includeNonAssistant:s=!1,verbose:t=!0,maxTableRows:n=25}=r,o=me.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],c=s?i:i.filter(f=>f.info.role==="assistant"),d={totalMessages:i.length,analyzedMessages:c.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=f=>typeof f=="number"&&Number.isFinite(f)?f:null,p=f=>{const h=f.filter(g=>typeof g=="number");return h.length>0?Math.max(...h):null},m=c.map((f,h)=>{const g=f.info??{},b=Array.isArray(f.parts)?f.parts:[],x=g.time??{},w=u(x.completed),S=w!==null,v=b.filter(E=>E.type==="tool"),j=b.filter(E=>E.type==="reasoning"),k=p(v.map(E=>u(E.state?.time?.end??E.state?.time?.start))),y=p(j.map(E=>u(E.time?.end??E.time?.start))),A=p([k,y].filter(E=>E!==null)),D=v.some(E=>["pending","running","started"].includes(E.state?.status)),N=j.some(E=>typeof E.time?.end!="number");v.length>0&&(d.withTools+=1),j.length>0&&(d.withReasoning+=1),S||(d.completedMissing+=1);const C=!!(S&&typeof k=="number"&&w<k);C&&(d.completedBeforeTool+=1);const M=!!(S&&typeof y=="number"&&w<y);return M&&(d.completedBeforeReasoning+=1),S&&D&&(d.runningToolsWhenCompleted+=1),S&&N&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:w,latestToolTimestamp:k,latestReasoningTimestamp:y,latestPartTimestamp:A,completed_missing:!S,completed_before_tool:C,completed_before_reasoning:M,running_tools_when_completed:!!(S&&D),reasoning_open_when_completed:!!(S&&N),has_tools:v.length>0,has_reasoning:j.length>0}});return t&&(console.table(m.slice(0,n)),m.length>n&&console.log(`Displayed first ${n} rows out of ${m.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:m}},checkCompletionStatus(){const r=me.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const n=(r.messages.get(s)||[]).filter(x=>x.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(x=>x.type==="step-finish"),i=o.parts.some(x=>x.type==="step-finish"&&x.reason==="stop"),d=o.info.time?.completed,u=o.info.status,p=typeof d=="number"&&d>0||u==="completed",m=!!(p&&i),f=r.messageStreamStates,h=o.info.sessionID?r.streamingMessageIds.get(o.info.sessionID)??null:null,g=f.get(o.info.id),b=o.info.id===h;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",p),console.log("hasStopReason:",i),console.log("messageIsComplete:",m),console.log("lifecycle phase:",g?.phase),console.log("isStreamingCandidate:",b),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:p,hasStopReason:i,messageIsComplete:m,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=sb,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.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",r=>{try{const s=r.message||"",t=r.filename||"";typeof s=="string"&&s.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&r.preventDefault()}catch{}}));let ul=!1;const rb=()=>{if(ul||typeof window>"u")return;ul=!0;let r={showReasoningTraces:Pe.getState().showReasoningTraces},s=null,t=null;const n=()=>{const a=s;s=null,t=null,a&&Object.keys(a).length>0&&Ns(a)},o=a=>{s={...s??{},...a},!t&&(t=setTimeout(n,150))};Pe.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces},c={};i.showReasoningTraces!==r.showReasoningTraces&&(c.showReasoningTraces=i.showReasoningTraces),r=i,Object.keys(c).length>0&&o(c)})};let ml=!1;const fl="openchamber-typography-base",nb=()=>{if(typeof document>"u")return;const s=`:root {
115
- ${Object.entries(ra).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
116
- `)}
117
- }
118
- `,t=document.getElementById(fl);if(t){t.textContent=s;return}const n=document.createElement("style");n.id=fl,n.textContent=s,document.head.appendChild(n)},ob=()=>{ml||typeof window>"u"||(ml=!0,nb())},ab=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Ol();await Bl();rb();ob();await Qc();typeof window<"u"&&(window.debugContextTokens=()=>{const r=window.__zustand_session_store__;if(!r)return;const s=r.getState(),t=s.currentSessionId;if(!t)return;const o=(s.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}),s.sessionContextUsage.get(t);const c=window.__zustand_config_store__;if(c){const d=c.getState().getCurrentModel(),u=d?.limit?.context||0,p=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&s.getContextUsage(u,p)}});const nd=document.getElementById("root");if(!nd)throw new Error("Root element not found");qu.createRoot(nd).render(e.jsx(le.StrictMode,{children:e.jsx(eb,{children:e.jsx(tb,{children:e.jsx(Ky,{children:e.jsx(Wy,{apis:ab})})})})}));if(typeof window<"u"){const r=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(s){console.warn("Failed to notify desktop runtime that renderer is ready:",s)}};r(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&r()})}const cb=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{Is as D,Wr as S,Fs as a,fp as b,T as c,Ag as d,Dg as e,zi as f,qr as g,Eg as h,Ig as i,cb as m,Fg as p,Tg as r,pn as t};