@openchamber/web 1.3.0 → 1.3.1
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.
- package/README.md +23 -6
- package/dist/apple-touch-icon-120x120.png +0 -0
- package/dist/apple-touch-icon-152x152.png +0 -0
- package/dist/apple-touch-icon-167x167.png +0 -0
- package/dist/apple-touch-icon-180x180.png +0 -0
- package/dist/apple-touch-icon.png +0 -0
- package/dist/apple-touch-icon.svg +15 -17
- package/dist/assets/{ToolOutputDialog-BK2tPtZM.js → ToolOutputDialog-ByonTRPM.js} +1 -1
- package/dist/assets/{index-CgsQ3Lpw.js → index-BleCEZso.js} +2 -2
- package/dist/assets/index-a7wSdHza.css +1 -0
- package/dist/assets/main-BI96Ha1h.js +118 -0
- package/dist/assets/{vendor-.pnpm-BcYW6LTb.js → vendor-.pnpm-CFPpXnpS.js} +353 -345
- package/dist/favicon-16.png +0 -0
- package/dist/favicon-32.png +0 -0
- package/dist/favicon.png +0 -0
- package/dist/favicon.svg +15 -0
- package/dist/index.html +86 -45
- package/dist/logo-dark.svg +15 -3
- package/dist/logo-light.svg +15 -3
- package/dist/site.webmanifest +14 -8
- package/package.json +1 -1
- package/public/apple-touch-icon-120x120.png +0 -0
- package/public/apple-touch-icon-152x152.png +0 -0
- package/public/apple-touch-icon-167x167.png +0 -0
- package/public/apple-touch-icon-180x180.png +0 -0
- package/public/apple-touch-icon.png +0 -0
- package/public/apple-touch-icon.svg +15 -17
- package/public/favicon-16.png +0 -0
- package/public/favicon-32.png +0 -0
- package/public/favicon.png +0 -0
- package/public/favicon.svg +15 -0
- package/public/logo-dark.svg +15 -3
- package/public/logo-light.svg +15 -3
- package/public/site.webmanifest +14 -8
- package/dist/assets/index-CEcDq5uz.css +0 -1
- package/dist/assets/main-DK0zXRq7.js +0 -118
|
@@ -1,118 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.pnpm-BcYW6LTb.js","assets/vendor--B3aGWKBE.css","assets/ToolOutputDialog-BK2tPtZM.js","assets/index-CgsQ3Lpw.js","assets/index-CEcDq5uz.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{t as Cd,c as Md,j as e,R as Ad,T as Dd,P as Ed,C as Td,A as Id,a as Fd,b as Pt,d as Wt,p as Ss,e as ks,f as Pd,g as l,r as Rd,h as us,I as Ld,i as _d,k as Od,l as Bd,m as $d,n as zd,o as Hd,q as Wd,s as Tt,u as Ud,S as Vd,v as Gd,w as qd,x as ns,y as Kd,z as Ml,B as Yd,D as Xd,E as Jd,F as ue,G as _a,H as Po,J as Zd,K as yt,L as ta,M as Qd,U as Bt,_ as br,Z as eu,Y as ws,Q as Vs,W as Yt,O as qn,N as tu,V as wr,X as rr,$ as vr,a0 as Ro,a1 as Is,a2 as Al,a3 as su,a4 as ru,a5 as nu,a6 as ou,a7 as au,a8 as iu,a9 as lu,aa as cu,ab as pn,ac as du,ad as uu,ae as Lo,af as $r,ag as xe,ah as qt,ai as sa,aj as Kn,ak as Dl,al as mu,am as as,an as Cn,ao as Yn,ap as _s,aq as Gs,ar as El,as as Tl,at as zr,au as Ds,av as gs,aw as Mn,ax as $s,ay as Oa,az as ra,aA as Il,aB as na,aC as oa,aD as aa,aE as Xn,aF as Kr,aG as Fl,aH as Pl,aI as Ba,aJ as ia,aK as nr,aL as Yr,aM as fu,aN as pu,aO as Rl,aP as Ll,aQ as jr,aR as hu,aS as gu,aT as to,aU as xu,aV as ss,aW as yu,aX as so,aY as bu,aZ as la,a_ as ca,a$ as wu,b0 as vu,b1 as ju,b2 as _o,b3 as Su,b4 as Sr,b5 as er,b6 as Jn,b7 as Zn,b8 as da,b9 as ku,ba as Nu,bb as Cu,bc as Mu,bd as Au,be as Du,bf as Eu,bg as Oo,bh as hn,bi as ua,bj as Tu,bk as Iu,bl as Dr,bm as Fu,bn as Pu,bo as Ru,bp as _l,bq as Lu,br as Ol,bs as _u,bt as Ou,bu as Bo,bv as Bu,bw as ys,bx as Bl,by as $u,bz as Cr,bA as zu,bB as Hu,bC as Wu,bD as Uu,bE as Vu,bF as Gu,bG as qu,bH as Ku,bI as Yu,bJ as Xu,bK as Ju,bL as Zu,bM as Qu,bN as em,bO as tm,bP as sm,bQ as rm,bR as nm,bS as om,bT as $a,bU as $l,bV as am,bW as za,bX as im,bY as lm,bZ as cm,b_ as dm,b$ as um,c0 as mm,c1 as fm}from"./vendor-.pnpm-BcYW6LTb.js";import{c as pm,l as hm,g as gm,r as xm,d as ym,a as bm,b as wm,u as vm,e as jm,f as Sm,h as km,i as Nm,j as Cm,k as Mm}from"./index-CgsQ3Lpw.js";function I(...r){return Cd(Md(r))}const zl=(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}`},An=r=>r?r==="/"?"/":r.replace(/\/+$/,""):"";function rs(r,s){if(!r)return"";const t=An(r);if(t==="/")return"/";const n=s?An(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 ro(r,s){if(!r)return"/";const t=An(r);if(!t||t==="/")return"/";const n=s?An(s):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Am({delayDuration:r=0,...s}){return e.jsx(Fd,{"data-slot":"tooltip-provider",delayDuration:r,...s})}function st({delayDuration:r=0,...s}){return e.jsx(Am,{delayDuration:r,children:e.jsx(Ad,{"data-slot":"tooltip",...s})})}function rt({...r}){return e.jsx(Dd,{"data-slot":"tooltip-trigger",...r})}function et({className:r,sideOffset:s=0,children:t,...n}){return e.jsx(Ed,{children:e.jsxs(Td,{"data-slot":"tooltip-content",sideOffset:s,className:I("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(Id,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let no=null;const Ha=()=>{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}}},Dm=()=>{if(typeof window>"u"||!window.localStorage)return Ha();const r=window.localStorage,s=Ha();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=()=>(no||(no=Dm()),no),ma={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Em={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Wa(r){return`--text-${r.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Es={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)"}}},gn={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Es.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:gn.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Es.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:gn.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Es.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:gn.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Es.tool.inline})},we=Pt()(Wt(Ss((r,s)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",pendingDiffFile:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,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})},setAboutDialogOpen:t=>{r({isAboutDialogOpen: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})},setAutoDeleteEnabled:t=>{r({autoDeleteEnabled:t})},setAutoDeleteAfterDays:t=>{const n=Math.max(1,Math.min(365,t));r({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:t=>{r({autoDeleteLastRunAt: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(ma);if(o===1){for(const[i]of a)n.style.removeProperty(Wa(i));return}for(const[i,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Wa(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:ks(()=>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,autoDeleteEnabled:r.autoDeleteEnabled,autoDeleteAfterDays:r.autoDeleteAfterDays,autoDeleteLastRunAt:r.autoDeleteLastRunAt,toolCallExpansion:r.toolCallExpansion,fontSize:r.fontSize,padding:r.padding,favoriteModels:r.favoriteModels,recentModels:r.recentModels,diffLayoutPreference:r.diffLayoutPreference,diffWrapLines:r.diffWrapLines})}),{name:"ui-store"})),is=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",es=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Hl=()=>typeof window>"u"?!1:!is()&&!es(),qs=()=>is()?window.opencodeDesktop??null:null,Wl=()=>{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},Ul=async()=>{const r=qs();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},Tm=async()=>{const r=qs();if(!r)return null;try{return await r.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},Im=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Vl=async()=>{const r=Wl();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=Wl();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=qs();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)}}},Rm=async r=>{const s=qs();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)}}},Lm=async r=>{const s=qs();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)}}},_m=async()=>{const r=qs();if(!r||!r.checkForUpdates)return null;try{return await r.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},Om=async r=>{const s=qs();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=qs();if(!r||!r.restartToUpdate)return!1;try{return await r.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}};async function $m(){try{const r=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const s=await r.json();return{available:s.available??!1,version:s.version,currentVersion:s.currentVersion??"unknown",body:s.body,packageManager:s.packageManager,updateCommand:s.updateCommand}}catch(r){return console.warn("Failed to check for web updates:",r),null}}function zm(){return is()?"desktop":Hl()?"web":null}const Ua={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Qn=Pt()((r,s)=>({...Ua,checkForUpdates:async()=>{const t=zm();if(t){r({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await _m():t==="web"&&(n=await $m()),r({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){r({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:t,runtimeType:n}=s();if(!(n!=="desktop"||!t)){r({downloading:!0,error:null,progress:null});try{await Om(o=>{r({progress:o})}),r({downloading:!1,downloaded:!0})}catch(o){r({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:t,runtimeType:n}=s();if(!(n!=="desktop"||!t))try{await Bm()}catch(o){r({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{r({available:!1,downloaded:!1,info:null})},reset:()=>{r(Ua)}})),Hm="/api",Wm=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Um=r=>{const s=typeof r=="string"&&r.trim().length>0?r.trim():"/api";if(Wm.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}},Vm=()=>{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},Xr=r=>r.replace(/\\/g,"/"),oo=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_RUNTIME_APIS__;return r&&r.runtime?.isDesktop&&r.files?r.files:null};class Gm{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=Hm){const n=Vm()||s;this.baseUrl=Um(n),this.client=Pd({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 revertSession(s,t,n){const o=await this.client.session.revert({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{messageID:t,partID:n}});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(s){const t=await this.client.session.unrevert({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!t.data)throw new Error("Failed to unrevert session");return t.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=oo();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=oo();if(t)try{const n=await t.listDirectory(s||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:Xr(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=oo(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Xr(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=Xr(m.path),h=f.split("/").filter(Boolean).pop()||f,g=m.preview&&m.preview.length>0&&typeof m.preview[0]=="string"?Xr(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 Ul();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 ke=new Gm,$o=new Set;function fa(r){return $o.add(r),()=>{$o.delete(r)}}function Fs(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 $o)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 Dn(r,s){return r.scopes.includes("all")||r.scopes.includes(s)}const pa="Updating OpenCode configuration...";let bs=0,Us=pa;const zo=new Set;function En(){const r={isUpdating:bs>0,message:Us};zo.forEach(s=>s(r))}function Ws(r){bs+=1,bs===1?(Us=r||pa,En()):r&&(Us=r,En())}function os(){bs!==0&&(bs-=1,bs===0&&(Us=pa,En()))}function ds(r){Us===r&&bs>0||(Us=r,bs>0&&En())}function qm(r){return zo.add(r),r({isUpdating:bs>0,message:Us}),()=>{zo.delete(r)}}function Km(){return{isUpdating:bs>0,message:Us}}const xn=r=>r.builtIn||r.native===!0,Gl=r=>r.hidden===!0,ql=r=>r.filter(s=>!Gl(s)),_r="useAgentsStore",Tn=r=>new Promise(s=>setTimeout(s,r)),Ym=2e4,Va=300,Ga=4,Xm=800,Jm=200,Zm=2e3,Mr=Pt()(Wt(Ss((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 ke.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=>{Ws("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 pr({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadAgents();return d&&Fs("agents",{source:_r}),d}catch(o){return console.error("[AgentsStore] Failed to create agent:",o),!1}finally{n||os()}},updateAgent:async(t,n)=>{Ws("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 pr({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadAgents();return u&&Fs("agents",{source:_r}),u}catch(a){return console.error("[AgentsStore] Failed to update agent:",a),!1}finally{o||os()}},deleteAgent:async t=>{Ws("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 pr({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadAgents();return c&&Fs("agents",{source:_r}),s().selectedAgentName===t&&r({selectedAgentName:null}),c}catch(o){return console.error("Failed to delete agent:",o),!1}finally{n||os()}},getAgentByName:t=>{const{agents:n}=s();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=s();return ql(t)}}),{name:"agents-store",storage:ks(()=>ts()),partialize:r=>({selectedAgentName:r.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Mr);async function Qm(r){const s=typeof r=="number"&&r>0?Math.min(r,Va):0;s>0&&await Tn(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Ym;){n+=1,ds(`Waiting for OpenCode… (attempt ${n})`);try{if(await ke.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=Ga&&a<1200?Va:Math.min(Xm+Math.max(0,n-Ga)*Jm,Zm);await Tn(i)}throw o||new Error("OpenCode did not become ready in time")}async function pr(r={}){const{message:s,delayMs:t}=r;try{ds(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 Qm(t),ds("Refreshing providers and agents…");const n=St.getState(),o=Mr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),Fs("agents",{source:_r})}catch(n){console.error("[AgentsStore] Failed to refresh configuration after OpenCode restart:",n),ds("OpenCode reload failed. Please retry refreshing configuration manually."),await Tn(1500)}finally{os()}}async function ef(r){await pr(r)}async function tf(r){Ws("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 pr({message:t.message,delayMs:t.reloadDelayMs}):await pr(r)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),ds("Failed to reload configuration. Please try again."),await Tn(2e3),os(),s}}let qa=null;qa||(qa=fa(r=>{if(r.source!==_r&&Dn(r,"agents")){const{loadAgents:s}=Mr.getState();s()}}));const sf="https://models.dev/api.json",rf="/api/openchamber/models-metadata",nf=r=>r?.toLowerCase?.()??"",of=r=>r==="primary"||r==="all"||r===void 0||r===null,Hr=r=>typeof r=="object"&&r!==null,In=r=>Array.isArray(r)&&r.every(s=>typeof s=="string"),af=r=>{if(!Hr(r))return!1;const s=r;if(s.modalities){const{input:t,output:n}=s.modalities;if(t&&!In(t)||n&&!In(n))return!1}return!0},lf=r=>{if(!Hr(r))return!1;const s=r;return s.models===void 0||Hr(s.models)},Kl=(r,s)=>{const t=nf(r);return!t||!s?"":`${t}/${s}`},cf=r=>{const s=new Map;if(!Hr(r))return s;for(const[t,n]of Object.entries(r)){if(!lf(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!Hr(a)))for(const[i,c]of Object.entries(a)){if(!af(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:In(c.modalities.input)?c.modalities.input:void 0,output:In(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=Kl(o,d);p&&s.set(p,u)}}return s},df=async()=>{if(typeof fetch!="function")return new Map;const r=[rf,sf];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 cf(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},uf=r=>new Promise(s=>setTimeout(s,r)),St=Pt()(Wt(Ss((r,s)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,loadProviders:async()=>{try{const t=df(),n=await ke.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 ke.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=>of(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 ke.checkHealth();return r({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await uf(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 ke.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=Kl(t,n);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=s();return ql(t)}}),{name:"config-store",storage:ks(()=>ts()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=St);let Ka=null;Ka||(Ka=fa(async r=>{const s=[];if(Dn(r,"agents")){const{loadAgents:t}=St.getState();s.push(t().then(()=>{}))}if(Dn(r,"providers")){const{loadProviders:t}=St.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},mf=180,Qt=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function ha(r){const s=Qt();return s?s.checkIsGitRepository(r):pm(r)}async function ff(r){const s=Qt();return s?s.getGitStatus(r):gm(r)}async function pf(r,s){const t=Qt();return t?t.deleteGitBranch(r,s):ym(r,s)}async function hf(r,s){const t=Qt();return t?t.deleteRemoteBranch(r,s):bm(r,s)}async function gf(r){const s=Qt();return s?s.listGitWorktrees(r):hm(r)}async function xf(r,s){const t=Qt();return t?t.addGitWorktree(r,s):Mm(r,s)}async function Yl(r,s){const t=Qt();return t?t.removeGitWorktree(r,s):xm(r,s)}async function yf(r){const s=Qt();return s?s.ensureOpenChamberIgnored(r):Nm(r)}async function bf(r,s={}){const t=Qt();return t?t.gitPush(r,s):Cm(r,s)}async function wf(){const r=Qt();return r?r.getGitIdentities():km()}async function vf(r){const s=Qt();return s?s.createGitIdentity(r):jm(r)}async function jf(r,s){const t=Qt();return t?t.updateGitIdentity(r,s):vm(r,s)}async function Sf(r){const s=Qt();return s?s.deleteGitIdentity(r):wm(r)}async function kf(r){const s=Qt();return s?s.getCurrentGitIdentity(r):Sm(r)}const Nf=".openchamber",Ps=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ya=(r,s)=>{const t=Ps(r),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Xl=r=>r?r.startsWith("refs/heads/")?r.substring(11):r.startsWith("heads/")?r.substring(6):r.startsWith("refs/")?r.substring(5):r:"",Cf=async r=>{try{await ke.createDirectory(r)}catch(s){if(s instanceof Error&&/exist/i.test(s.message))return;throw s}};async function Mf(r,s){const t=Ps(r),n=Ya(t,Nf);return await Cf(n),Ya(n,s)}async function Af(r){const{projectDirectory:s,worktreeSlug:t,branch:n,createBranch:o}=r,a=Ps(s),i=await Mf(a,t);return await xf(a,{path:i,branch:n,createBranch:!!o}),{path:i,branch:n,label:Xl(n),projectDirectory:a,relativePath:i.startsWith(`${a}/`)?i.slice(a.length+1):i}}async function Xa(r){const{projectDirectory:s,path:t,force:n}=r,o=Ps(s);await Yl(o,{path:t,force:n})}async function Df(r){const{projectDirectory:s,path:t,branch:n,force:o,deleteRemote:a,remote:i}=r,c=Ps(s),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Yl(c,{path:t,force:o}),d&&(await pf(c,{branch:d,force:!0}),a))try{await hf(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Fn(r){const s=Ps(r);return gf(s)}async function yn(r){const s=Ps(r),t=await ff(s);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function Pn(r,s){const t=Ps(r),n=Ps(s.worktree);return{path:n,branch:s.branch??"",label:Xl(s.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const Ja=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},Ef=r=>!r||typeof r!="object"?null:{showReasoningTraces:r.showReasoningTraces},Tf=r=>{const s=we.getState();typeof r.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(r.showReasoningTraces)},If=async()=>{if(typeof window>"u")return null;if(is()){const s=window.opencodeAppearance;if(!s||typeof s.load!="function")return null;try{const t=await s.load();return Ja(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=Ef(s);return Ja(t)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let Jl=null;const Za=r=>{Jl=r},ga=()=>Jl,bn=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"))},Zl=()=>{const r=we.persist;if(r&&typeof r=="object")return r},Ql=()=>ga()?.settings??null,wn=r=>{const s=we.getState();if(typeof r.showReasoningTraces=="boolean"&&r.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&r.autoDeleteEnabled!==s.autoDeleteEnabled&&s.setAutoDeleteEnabled(r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)){const t=Math.max(1,Math.min(365,r.autoDeleteAfterDays));t!==s.autoDeleteAfterDays&&s.setAutoDeleteAfterDays(t)}},Qa=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),typeof s.autoDeleteEnabled=="boolean"&&(t.autoDeleteEnabled=s.autoDeleteEnabled),typeof s.autoDeleteAfterDays=="number"&&Number.isFinite(s.autoDeleteAfterDays)&&(t.autoDeleteAfterDays=s.autoDeleteAfterDays),t},Ff=async()=>{const r=Ql();if(r)try{const s=await r.load();return Qa(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 Qa(t)}catch(s){return console.warn("Failed to load shared settings from server:",s),null}},ec=async()=>{if(typeof window>"u")return;const r=Zl(),s=t=>{bn(t);const n=()=>wn(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=is()?await Vl():await Ff();t&&s(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},As=async r=>{if(typeof window>"u")return;if(is()){try{const t=await Fm(r);t&&(bn(t),wn(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const s=Ql();if(s)try{const t=await s.save(r);t&&(bn(t),wn(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&&(bn(n),wn(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},tc=async()=>{if(typeof window>"u")return;const r=Zl();try{const s=await If();if(!s)return;const t=()=>Tf(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)}},Or="useCommandsStore",Ho=r=>new Promise(s=>setTimeout(s,r)),Pf=2e4,ei=300,ti=4,Rf=800,Lf=200,_f=2e3,Ar=Pt()(Wt(Ss((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 ke.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=>{Ws("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 ao({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadCommands();return d&&Fs("commands",{source:Or}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||os()}},updateCommand:async(t,n)=>{Ws("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 ao({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadCommands();return u&&Fs("commands",{source:Or}),u}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||os()}},deleteCommand:async t=>{Ws("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 ao({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadCommands();return c&&Fs("commands",{source:Or}),s().selectedCommandName===t&&r({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||os()}},getCommandByName:t=>{const{commands:n}=s();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:ks(()=>ts()),partialize:r=>({selectedCommandName:r.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Ar);async function Of(r){const s=typeof r=="number"&&r>0?Math.min(r,ei):0;s>0&&await Ho(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Pf;){n+=1,ds(`Waiting for OpenCode… (attempt ${n})`);try{if(await ke.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=ti&&a<1200?ei:Math.min(Rf+Math.max(0,n-ti)*Lf,_f);await Ho(i)}throw o||new Error("OpenCode did not become ready in time")}async function ao(r={}){const{message:s,delayMs:t}=r;try{ds(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 Of(t),ds("Refreshing providers and commands…");const n=St.getState(),o=Ar.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),Fs("commands",{source:Or})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),ds("OpenCode reload failed. Please retry refreshing configuration manually."),await Ho(1500)}finally{os()}}let si=null;si||(si=fa(r=>{if(r.source!==Or&&Dn(r,"commands")){const{loadCommands:s}=Ar.getState();s()}}));const Bf=3e4,$f=40,zf=60,Hf=(r,s,t)=>{const n=r.trim(),o=s.trim().toLowerCase();return`${n}::${o}::${t}`},xa=Pt()(Wt((r,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=zf){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=Hf(a,i,o),d=Date.now(),u=s().cache[c];if(u&&d-u.timestamp<Bf)return u.files;const p=s().inFlight[c];if(p)return p;const m=ke.searchFiles(i,{directory:a,limit:o}).then(f=>(r(h=>{const g={...h.cache,[c]:{files:f,timestamp:Date.now()}},x=h.cacheKeys.filter(y=>y!==c);for(x.push(c);x.length>$f;){const y=x.shift();y&&delete g[y]}return{cache:g,cacheKeys:x}}),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 Wf={};let Ts=null;const xs=ts(),ri=xs.getItem("lastDirectory"),Uf=typeof ri=="string"&&ri.length>0,Jr=(r,s)=>((s?.showOverlay??!0)&&Ws("Switching project directory…"),ke.setOpenCodeWorkingDirectory(r).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),Zr=(r,s,t)=>{const{showOverlay:n}=s,o=()=>{try{fe.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&&(ds("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),os()),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 ef({message:"Refreshing OpenCode configuration…"});try{await Ar.getState().loadCommands();try{Fs("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&&os()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(ds("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),os())}finally{t?.(a),o()}})()},Qr=r=>{try{xa.getState().invalidateDirectory(r)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},Rn=()=>{if(typeof window<"u"){const s=xs.getItem("lastDirectory");if(s)return s;if(Ts)return Ts;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 Ts=t,xs.setItem("homeDirectory",t),t;const n=xs.getItem("homeDirectory");if(n)return Ts=n,n}const r=typeof process<"u"&&Wf?.HOME;return r||process?.cwd?.()||"/"},Vf=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},Gf=r=>(Ts=r,typeof window<"u"&&xs.setItem("homeDirectory",r),As({homeDirectory:r}),r),sc=async()=>{const r=n=>{const o=Vf(n);return o?Gf(o):null};try{const n=await ke.getFilesystemHome(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await ke.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 Ul(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const s=Rn(),t=r(s);return t||s},tr=Rn();tr&&ke.setDirectory(tr);const qf=!!(tr&&tr!=="/"),jt=Pt()(Wt((r,s)=>({currentDirectory:tr,directoryHistory:[tr],historyIndex:0,homeDirectory:tr,hasPersistedDirectory:Uf,isHomeReady:qf,isSwitchingDirectory:!1,setDirectory:(t,n)=>{console.log("[DirectoryStore] setDirectory called with path:",t);const o=n?.showOverlay??!0;ke.setDirectory(t),Qr();const a=Jr(t,{showOverlay:o});console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),r(i=>{const c=[...i.directoryHistory.slice(0,i.historyIndex+1),t];return xs.setItem("lastDirectory",t),As({lastDirectory:t}),{currentDirectory:t,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),Zr(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];ke.setDirectory(o),Qr();const a=Jr(o);xs.setItem("lastDirectory",o),As({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Zr(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];ke.setDirectory(o),Qr();const a=Jr(o);xs.setItem("lastDirectory",o),As({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Zr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=s(),o=Ts||s().homeDirectory||Rn();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=Ts||Rn();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=Ts||s().homeDirectory||await sc();s().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=s(),o=t;Ts=o;const a=n.homeDirectory!==o,i=xs.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){ke.setDirectory(o),Qr(),xs.setItem("lastDirectory",o),As({lastDirectory:o});const m=Jr(o,{showOverlay:!1});Zr(m,{showOverlay:!1},()=>{r(f=>f.currentDirectory!==o?{}:f.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}As({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&sc().then(r=>{jt.getState().synchronizeHomeDirectory(r)});const rc=ts(),nc="oc.sessionSelectionByDirectory",ni=".openchamber",Kf=()=>{try{const r=rc.getItem(nc);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 vn=null;const ya=()=>(vn||(vn=Kf()),vn),oc=r=>{vn=r;try{rc.setItem(nc,JSON.stringify(r))}catch{}},ac=r=>{if(!r)return null;const t=ya()[r];return typeof t=="string"?t:null},Ks=(r,s)=>{if(!r)return;const t={...ya()};s?t[r]=s:delete t[r],oc(t)},Yf=(r,s)=>{if(!r)return;const t=ac(r);if(!t)return;if(!new Set(s).has(t)){const o={...ya()};delete o[r],oc(o)}},oi=async(r,s)=>{const t=r.status??await yn(r.path).catch(()=>{});await Df({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},cr=(r,s)=>{const t=r.find(n=>n.id===s);return t?_t(t.directory??null):null},Xf=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 Fn(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=Pn(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},Ye=Pt()(Wt(Ss((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=jt.getState().currentDirectory??ke.getDirectory()??null,o=ke.getApiClient(),a=async M=>{const N=await o.session.list({query:M?{directory:M}:void 0});return Array.isArray(N.data)?N.data:[]},i=_t(n),c=i?await ha(i).catch(()=>!1):!1,d=await a(i||null),u=[];let p=[];if(n&&c&&i){const M=`${i}/${ni}`;try{const N=new Set;M&&(await ke.listLocalDirectory(M)).filter(D=>D.isDirectory).forEach(D=>{const O=/^([A-Za-z]:)?\//.test(D.path)?D.path:`${M}/${D.name}`;N.add(_t(O)??O)});const A=await Fn(i);Array.isArray(A)&&(p=A.map(C=>Pn(i,C)).filter(C=>C.path.includes(`/${ni}/`)),p.forEach(C=>N.add(C.path))),N.size>0&&(await Promise.allSettled(Array.from(N).map(D=>a(D)))).forEach(D=>{D.status==="fulfilled"&&Array.isArray(D.value)&&u.push(...D.value)})}catch{p=[]}}const m=new Set;i&&m.add(i),p.forEach(M=>{const N=_t(M.path);N&&m.add(N)});const f=[...d,...u].filter(M=>{const N=M.directory??i??null,A=_t(N);return A?m.has(A):!1}),h=s(),g=h.lastLoadedDirectory??null,x=n!==g;let y=[...f],b=h.currentSessionId;const v=M=>{y=[M,...y.filter(N=>N.id!==M.id)]};if(x)b=y.length>0?y[0].id:null;else if(b){if(!y.some(N=>N.id===b)){const N=h.sessions.find(A=>A.id===b);if(N)v(N);else try{const A=await ke.getSession(b);v(A)}catch{b=y.length>0?y[0].id:null}}}else b=y.length>0?y[0].id:null;const k=y.reduce((M,N)=>(M.some(A=>A.id===N.id)||M.push(N),M),[]);b&&!k.some(M=>M.id===b)&&(b=k.length>0?k[0].id:null);const j=new Set(k.map(M=>M.id));if(n){Yf(n,j);const M=ac(n);M&&j.has(M)&&(b=M)}let S=null;try{S=await Xf(k,n,h.worktreeMetadata)}catch(M){console.debug("Failed to refresh worktree metadata during session load:",M)}const w=(()=>{const M=S??h.worktreeMetadata;if(!x||!i)return M;const N=new Map;return M.forEach((A,C)=>{_t(A.projectDirectory)===i&&N.set(C,A)}),N})(),T=(()=>{if(!b)return i??null;const M=w.get(b)?.path;if(M)return _t(M)??M;const N=cr(k,b);return N||(i??null)})();try{ke.setDirectory(T??void 0)}catch(M){console.warn("Failed to sync OpenCode directory after session load:",M)}r({sessions:k,currentSessionId:b,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:w,availableWorktrees:p}),Ks(T??n,b)}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=jt.getState(),i=_t(a.currentDirectory),c=_t(n??ke.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{ke.setDirectory(c)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const f=g=>{r(x=>({sessions:x.sessions.map(b=>b.id===d?g:b),currentSessionId:g.id,webUICreatedSessions:new Set([...Array.from(x.webUICreatedSessions).filter(b=>b!==d),g.id])})),Ks(c??null,g.id)},h=async()=>{const g=ke.getApiClient(),x=20;for(let y=0;y<x;y+=1){try{const b=await g.session.list({query:c?{directory:c}:void 0}),k=(Array.isArray(b.data)?b.data:[]).find(j=>!(p.has(j.id)||t&&j.title&&j.title!==t));if(k)return k}catch(b){console.debug("Session poll attempt failed:",b)}await new Promise(b=>setTimeout(b,2e3))}return null};try{const g=()=>ke.createSession({title:t,parentID:o??void 0});let x=null;try{x=c?await ke.withDirectory(c,g):await g()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return x||(x=await h()),x?(f(x),x):(r(y=>({sessions:y.sessions.filter(b=>b.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(b=>b!==d)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return r(x=>({sessions:x.sessions.filter(y=>y.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(x.webUICreatedSessions).filter(y=>y!==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=cr(s().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await oi(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>ke.deleteSession(t);if(!(i?await ke.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(y=>y.id!==t);p=f.currentSessionId===t?null:f.currentSessionId;const g=new Map(f.worktreeMetadata);g.delete(t);const x=n?.archiveWorktree&&o?f.availableWorktrees.filter(y=>_t(y.path)!==_t(o.path)):f.availableWorktrees;return{sessions:h,currentSessionId:p,isLoading:!1,worktreeMetadata:g,availableWorktrees:x}});const m=i??ke.getDirectory()??null;return Ks(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(y=>typeof y=="string"&&y.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||r({isLoading:!0,error:null});const i=[],c=[],d=new Set,u=[],p=new Set;for(const y of o)try{const b=s().worktreeMetadata.get(y),v=cr(s().sessions,y),k=b?.path??v;b&&n?.archiveWorktree&&!p.has(b.path)&&(await oi(b,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(y),u.push({path:b.path,projectDirectory:b.projectDirectory}),p.add(b.path));const j=()=>ke.deleteSession(y);(k?await ke.withDirectory(k,j):await j())?(i.push(y),b?.path&&!u.some(w=>w.path===b.path)&&u.push({path:b.path,projectDirectory:b.projectDirectory})):c.push(y)}catch{c.push(y)}const m=jt.getState();u.forEach(({path:y,projectDirectory:b})=>{m.currentDirectory===y&&m.setDirectory(b,{showOverlay:!1})});const f=new Set(i),h=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let g=null;r(y=>{const b=y.sessions.filter(S=>!f.has(S.id));y.currentSessionId&&f.has(y.currentSessionId)?g=b.length>0?b[0].id:null:g=y.currentSessionId;const v=new Map(y.worktreeMetadata);for(const S of f)v.delete(S);for(const S of d)v.delete(S);const k=new Set(u.map(S=>_t(S.path)).filter(S=>!!S)),j=k.size>0?y.availableWorktrees.filter(S=>!k.has(_t(S.path)??S.path)):y.availableWorktrees;return{sessions:b,currentSessionId:g,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:j}});const x=ke.getDirectory()??null;return Ks(x,g),{deletedIds:i,failedIds:c}},updateSessionTitle:async(t,n)=>{try{const o=cr(s().sessions,t),a=s().worktreeMetadata.get(t),i=()=>ke.updateSession(t,n),c=a?.path??o,d=c?await ke.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=cr(s().sessions,t),o=ke.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??ke.getDirectory();return o.session.share({path:{id:t},query:u?{directory:u}:void 0})},d=i?await ke.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=cr(s().sessions,t),o=ke.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??ke.getDirectory();return o.session.unshare({path:{id:t},query:u?{directory:u}:void 0})},d=i?await ke.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=ke.getDirectory()??null;Ks(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&&Ks(c,null),n&&Ks(n,t))},updateSession:t=>{r(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:ks(()=>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"})),ic="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.",io=r=>typeof r=="string"&&r.trim()===ic.trim(),lo=(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},Er=(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},ai=new Map,lc=r=>{const s=ai.get(r);s&&(clearTimeout(s),ai.delete(r))},Ys=r=>{for(const s of r)lc(s)},Wr=r=>{if(!r)return"";if(typeof r=="string")return r;if(Array.isArray(r))return r.map(s=>Wr(s)).join("");if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(Array.isArray(r.content))return r.content.map(s=>Wr(s)).join("")}return""},Br=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:Br(n)).join("");const t=Wr(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||Wr(o.delta)||""}return""}).join(""):"")},Tr=(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=Wr(r.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},ii=10*1024*1024,Jf=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"}},Zf=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"}},Qf=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},ep=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},zs=Pt()(Wt(Ss((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=ii;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=Zf(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,x)=>{u.onload=()=>g(u.result),u.onerror=x,u.readAsDataURL(t)}),m=p.startsWith("data:")?p.replace(/^data:[^;]*/,`data:${c}`):p,f=g=>{const x=g.replace(/\\/g,"/").split("/");return x[x.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(b=>b.serverPath===t&&b.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,u;if(!c)try{const b=ke.getApiClient(),v=t.lastIndexOf("/"),k=v>0?t.substring(0,v):"/",j=v>0?t.substring(v+1):t,S=await b.file.read({query:{path:j,directory:k}});S.data&&"content"in S.data?(c=S.data.content,d=S.data.encoding??void 0,u=S.data.mimeType??void 0):c=""}catch(b){console.error("Failed to read server file:",b),c=`[File: ${n}]`}const p=u||Jf(n),m=p&&p.trim().length>0?p:"application/octet-stream",f=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return ep(v)})(),h=d==="base64"?Qf(f):new TextEncoder().encode(c||"").length;if(h>ii)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const g=new File([],n,{type:m}),x=`data:${m};base64,${f}`,y={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:g,dataUrl:x,mimeType:m,filename:n,size:h,source:"server",serverPath:t};r(b=>({attachedFiles:[...b.attachedFiles,y]}))},removeAttachedFile:t=>{r(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{r({attachedFiles:[]})}}),{name:"file-store",storage:ks(()=>ts()),partialize:r=>({attachedFiles:r.attachedFiles})}),{name:"file-store"}));let co=[],uo=null;const tp=50,sp=3e4,Xs=new Map,en=new Map,dr=new Map,rp=10,Ln=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<rp?null:n},tn=(r,s)=>{const t=Ln(r),n=Ln(s);return!t||!n||t.length!==n.length?!0:t>n},np=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},fr=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),_n=r=>Array.isArray(r)?r.some(s=>s?.type==="step-finish"&&s?.reason==="stop"):!1,li=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??""}`}}},ci=new Set,On=(r=[],s=[])=>{if(!s.length)return[...r];const t=[...r],n=new Set(r.map(li).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=li(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},op=(r,s)=>{const t=Array.isArray(r.parts)?r.parts:[],n=Array.isArray(s.parts)?s.parts:[],o=fr(t),a=fr(n),i=_n(t),c=_n(n);let d=n;return i&&o>=a?d=On(t,n):c&&a>=o?d=On(n,t):o>=a&&(d=t),{...s,info:{...r.info,...s.info},parts:d}},mo=r=>{const s=[],t=new Map;for(const n of r){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){s.push(n);continue}const a=t.get(o);if(a===void 0){t.set(o,s.length),s.push(n);continue}s[a]=op(s[a],n)}return s},ap=(r,s)=>{let t=s,n=s?Ln(s):null;for(const o of r){const a=o?.info?.id,i=Ln(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},ur=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return o.set(s,t),o},sn=(r,s)=>{const t=new Map(r);let n=!1;for(const o of s)t.delete(o)&&(n=!0);return n?t:r},ip=(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},di=(r,s,t)=>r.streamingMessageIds.get(s)===t?!0:r.messageSessionIndex.get(t)===s&&r.messageStreamStates.has(t),lp=async r=>{if(r)try{const s=Ye.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}},ui=r=>{if(!r)return null;try{return Ye.getState().sessions.find(n=>n.id===r)?.revert?.messageID??null}catch{return null}},mi=(r,s)=>{if(!s)return r;const t=r.findIndex(n=>n.info.id===s);return t===-1?r:r.slice(0,t)},fo=async(r,s)=>{const t=await lp(r);return t?ke.withDirectory(t,s):s()},nt=Pt()(Wt(Ss((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 fo(t,()=>ke.getSessionMessages(t)),a=ui(t),i=mi(o,a),c=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(c?i.filter(p=>{const m=p?.info?.id;return m?tn(m,c):!0}):i).slice(-n);r(p=>{const m=new Map(p.messages),f=p.messages.get(t)||[],h=new Map(f.filter(N=>typeof N.info?.id=="string").map(N=>[N.info.id,N])),g=u.map(N=>{const A={...N.info,clientRole:N.info?.clientRole??N.info.role,userMessageMarker:N.info.role==="user"?!0:N.info?.userMessageMarker},C=(Array.isArray(N.parts)?N.parts:[]).map(P=>{if(P?.type==="text"){const O=P.text??P.content??"";if(io(O))return{...P,synthetic:!0}}return P}),D=A?.id?h.get(A.id):void 0;if(D&&D.info.role==="assistant"){const P=Array.isArray(D.parts)?D.parts:[],O=fr(P),W=fr(C);if(_n(P)&&O>W){const V=On(P,C);return{...N,info:A,parts:V}}}return{...N,info:A,parts:C}}),x=mo(g),y=new Set(f.map(N=>N.info.id)),b=new Set(x.map(N=>N.info.id)),v=[];y.forEach(N=>{b.has(N)||v.push(N)}),m.set(t,x);const k=new Map(p.sessionMemoryState),j=p.sessionMemoryState.get(t);k.set(t,{viewportAnchor:x.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:j?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const S={messages:m,sessionMemoryState:k};Ys(v);const w=Er(p.messageStreamStates,v);if(w!==p.messageStreamStates&&(S.messageStreamStates=w),v.length>0){const N=p.streamingMessageIds.get(t);N&&v.includes(N)&&(S.streamingMessageIds=fs(S.streamingMessageIds??p.streamingMessageIds,t,null))}if(v.length>0){const N=sn(S.messageSessionIndex??p.messageSessionIndex,v);N!==(S.messageSessionIndex??p.messageSessionIndex)&&(S.messageSessionIndex=N)}if(v.length>0){const N=new Map(p.pendingAssistantParts);let A=!1;v.forEach(C=>{N.delete(C)&&(A=!0)}),A&&(S.pendingAssistantParts=N)}const T=S.messageSessionIndex??p.messageSessionIndex;let M=T;return x.forEach(N=>{const A=N?.info?.id;typeof A=="string"&&A.length>0&&(M=ur(M,A,t))}),M!==T&&(S.messageSessionIndex=M),S})},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 fo(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(),x=ke.getApiClient(),y=ke.getDirectory();if(h==="init"){const b=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await x.session.init({path:{id:u},body:{messageID:b,providerID:n,modelID:o},query:y?{directory:y}:void 0});return}if(h==="summarize"){await x.session.summarize({path:{id:u},body:{providerID:n,modelID:o},query:y?{directory:y}:void 0});return}try{const b=await ke.getCommandDetails(h);b?.template?p=b.template.replace(/\$ARGUMENTS/g,g):p=t}catch(b){console.error("Command template resolution failed:",b),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=dr.get(u);g&&(clearTimeout(g),dr.delete(u));const x=new Map(f.sessionMemoryState);return x.set(u,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:x}});try{const f=new AbortController;r(g=>{const x=new Map(g.abortControllers);return x.set(u,f),{abortControllers:x}});const h=(c??[]).map(g=>({type:"file",mime:g.mimeType,filename:g.filename,url:g.dataUrl}));if(await ke.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{zs.getState().clearAttachedFiles()}catch(g){console.error("Failed to clear attached files after send",g)}r(g=>{const x=new Map(g.abortControllers);return x.delete(u),{abortControllers:x}})}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 x=new Map(g.abortControllers);return x.delete(u),{abortControllers:x}});return}else f.message&&(h=f.message);throw r(g=>{const x=new Map(g.abortControllers);return x.delete(u),{abortControllers:x}}),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=ip(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=Xs.get(u);p&&(clearTimeout(p),Xs.delete(u),en.delete(u))}c.size>0&&Ys(c);const d=Date.now();r(u=>{const p=Er(u.messageStreamStates,c),m=u.messages.get(t)??[];let f=!1,h=u.messages;if(m.length>0&&c.size>0){const b=m.map(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const k=(v.parts??[]).map(j=>{if(j.type==="reasoning"){const S=j,w={...S.time??{}};return typeof w.end!="number"&&(w.end=d),{...S,time:w}}if(j.type==="tool"){const S=j,w={...S.state??{}};return(w.status==="running"||w.status==="pending")&&(w.status="aborted"),{...S,state:w}}return j.type==="step-start"?{...j,type:"step-finish",aborted:!0}:j});return f=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:k}});f&&(h=new Map(u.messages),h.set(t,b))}const g=u.sessionMemoryState.get(t);let x=u.sessionMemoryState;if(g){const b=new Map(u.sessionMemoryState);b.set(t,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),x=b}const y=new Map(u.sessionAbortFlags);return y.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:p,sessionMemoryState:x,sessionAbortFlags:y,abortControllers:(()=>{const b=new Map(u.abortControllers);return b.delete(t),b})(),streamingMessageIds:fs(u.streamingMessageIds,t,null),...f?{messages:h}:{}}}),ke.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=s();if(ci.has(n))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!tn(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.messages.get(t)||[],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(x=>{const y=new Map(x.sessionMemoryState);return y.set(t,{...f,isZombie:!0}),{sessionMemoryState:y}}),setTimeout(()=>{s().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}r(g=>{const y=[...g.messages.get(t)||[]],b={},v=ur(g.messageSessionIndex,n,t);v!==g.messageSessionIndex&&(b.messageSessionIndex=v);const k=A=>{if(!((m==="assistant"||m==="user")&&g.sessionAbortFlags.has(t)))return A;const D=new Map(g.sessionAbortFlags);return D.delete(t),{...A,sessionAbortFlags:D}},j=A=>{const C=A||"",D=en.get(n);if(C&&D===C){const W=s();if(di(W,t,n)){const R=Xs.get(n);R&&(clearTimeout(R),Xs.delete(n)),setTimeout(()=>{const V=s();typeof V.forceCompleteMessage=="function"&&V.forceCompleteMessage(t,n,"timeout"),V.completeStreamingMessage(t,n)},100)}}en.set(n,C);const P=Xs.get(n);P&&clearTimeout(P);const O=setTimeout(()=>{const W=s();typeof W.forceCompleteMessage=="function"&&W.forceCompleteMessage(t,n,"timeout"),di(W,t,n)&&W.completeStreamingMessage(t,n),Xs.delete(n),en.delete(n)},8e3);Xs.set(n,O)},S=t!==i,w=g.sessionMemoryState.get(t);if(S&&w?.isStreaming){y.length>=Ot.BACKGROUND_STREAMING_BUFFER&&y.shift();const A=new Map(g.sessionMemoryState);A.set(t,{...w,backgroundMessageCount:(w.backgroundMessageCount||0)+1}),g.sessionMemoryState=A}if(m==="assistant"){const A=g.sessionMemoryState.get(t);if(A){const C=Date.now(),D=new Map(g.sessionMemoryState);D.set(t,{...A,isStreaming:!0,streamStartTime:A.streamStartTime??C,lastAccessedAt:C,isZombie:!1}),g.sessionMemoryState=D}}const T=Br(o);if(io(T)&&(o.synthetic=!0),np()&&m==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:m,type:o?.type||"text",textLen:T.length,snapshotParts:u.length})}catch{}const M=b.streamingMessageIds??g.streamingMessageIds;if(m==="assistant"){const A=fs(M,t,n);A!==M&&(b.streamingMessageIds=A,window.__messageTracker?.(n,"streamingId_set_latest"))}const N=y.findIndex(A=>A.info.id===n);if(N!==-1&&m==="user"){const A=y[N],C=A.parts.findIndex(R=>R.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),g;const D=Tr(o,C!==-1?A.parts[C]:void 0);window.__messageTracker?.(n,`user_part_type:${D.type||"unknown"}`);const P={...A};C!==-1?P.parts=P.parts.map((R,V)=>V===C?D:R):P.parts=[...P.parts,D];const O=[...y];O[N]=P;const W=new Map(g.messages);return W.set(t,O),k({messages:W})}if(m==="assistant"&&N!==-1){const A=y[N],C=A.parts.findIndex(V=>V.id===o.id),D=Tr(o,C!==-1?A.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${D.type||"unknown"}`);const P={...A};C!==-1?P.parts=P.parts.map((V,ae)=>ae===C?D:V):P.parts=[...P.parts,D];const O=[...y];O[N]=P;const W=new Map(g.messages);W.set(t,O),b.messageStreamStates=lo(g.messageStreamStates,n);const R=fs(b.streamingMessageIds??g.streamingMessageIds,t,n);return R!==(b.streamingMessageIds??g.streamingMessageIds)&&(b.streamingMessageIds=R,window.__messageTracker?.(n,"streamingId_set")),D.type==="text"?j(D.text||""):j(""),k({messages:W,...b})}if(N===-1){if(m==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),g;const K=Tr(o);window.__messageTracker?.(n,`new_user_part_type:${K.type||"unknown"}`);const B={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,time:{created:Date.now()}},parts:[K]},L=[...y,B];L.sort((Se,Ne)=>{const de=Se.info?.time?.created||0,ge=Ne.info?.time?.created||0;return de-ge});const ne=new Map(g.messages);return ne.set(t,L),k({messages:ne})}if(o?.type==="text"){const K=Br(o).trim();if(K.length>0){const B=[...y].reverse().find(L=>L.info.role==="user");if(B){const L=B.parts.map(ne=>Br(ne)).join("").trim();if(L.length>0&&L===K)return ci.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),g}}}const A=Tr(o);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`),A.type==="text"?j(A.text||""):j("");const C=g.pendingAssistantParts.get(n),D=C?[...C.parts]:[],P=D.findIndex(K=>K.id===A.id);P!==-1?D[P]=A:D.push(A);const O=new Map(g.pendingAssistantParts);O.set(n,{sessionId:t,parts:D});const R={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:D},V=[...y,R],ae=new Map(g.messages);if(ae.set(t,V),m==="assistant"){b.messageStreamStates=lo(g.messageStreamStates,n);const K=fs(b.streamingMessageIds??g.streamingMessageIds,t,n);K!==(b.streamingMessageIds??g.streamingMessageIds)&&(b.streamingMessageIds=K,window.__messageTracker?.(n,"streamingId_set"))}return k({messages:ae,pendingAssistantParts:O,...b})}else{const A=y[N],C=A.parts.findIndex(R=>R.id===o.id),D=Tr(o,C!==-1?A.parts[C]:void 0);window.__messageTracker?.(n,`part_type:${D.type||"unknown"}`);const P={...A};C!==-1?P.parts=P.parts.map((R,V)=>V===C?D:R):P.parts=[...P.parts,D];const O=[...y];O[N]=P;const W=new Map(g.messages);if(W.set(t,O),P.info.role==="assistant"){b.messageStreamStates=lo(g.messageStreamStates,n);const R=fs(b.streamingMessageIds??g.streamingMessageIds,t,n);R!==(b.streamingMessageIds??g.streamingMessageIds)&&(b.streamingMessageIds=R,window.__messageTracker?.(n,"streamingId_set"))}return D.type==="text"?j(D.text||""):j(""),k({messages:W,...b})}}),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}co.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),uo||(uo=setTimeout(()=>{const c=[...co];co=[],uo=null;const d=s();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},tp))},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(S=>S.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 x={...f};h||(x.time={...f.time??{},completed:m},g=!0),x.status!=="completed"&&(x.status="completed",g=!0),x.streaming&&(x.streaming=!1,g=!0);let y=!1;const b=p.parts.map(S=>{if(!S)return S;if(S.type==="tool"){const w=S.state;if(!w)return S;const T=w.status,M=T==="running"||T==="pending"||T==="started",N=!w.time||typeof w.time?.end!="number";if(M||N){const A={...w};return M&&(A.status="completed"),N&&(A.time={...w.time??{},end:m}),y=!0,{...S,state:A}}return S}if(S.type==="reasoning"){const w=S.time;return!w||typeof w.end!="number"?(y=!0,{...S,time:{...w??{},end:m}}):S}if(S.type==="text"){const w=S.time;return w&&typeof w.end!="number"?(y=!0,{...S,time:{...w,end:m}}):S}return S});if(!g&&!y)return i;window.__messageTracker?.(n,`force_complete:${o}`);const v={...p,info:x,parts:y?b:p.parts},k=[...d];k[u]=v;const j=new Map(i.messages);return j.set(c,k),{messages:j}})},markMessageStreamSettled:t=>{r(n=>{lc(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(x=>x.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}:{}}}),Ys([t])},updateMessageInfo:(t,n,o)=>{r(a=>{const i=a.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(i&&!tn(n,i))return window.__messageTracker?.(n,"ignored_trimmed_update"),a;const d=[...a.messages.get(t)??[]],u=d.findIndex(w=>w.info.id===n),p=a.pendingAssistantParts.get(n),m=(w=[],T=[])=>{if(!T.length)return w;const M=[...w];return T.forEach(N=>{const A=M.findIndex(C=>C.id===N.id);A===-1?M.push(N):M[A]=N}),M},f=w=>{if(!w)return w;const T=w.clientRole??w.role,M=T==="user"?!0:w.userMessageMarker;return{...w,clientRole:T,...M?{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 O=d[0]?.info,W=typeof O?.time?.created=="number"?O.time.created:null,R=typeof O?.id=="string"?O.id:null,V=o,ae=typeof V?.time?.created=="number"?V.time.created:null,K=typeof V?.id=="string"?V.id:n;let B=!1;if(ae!==null&&W!==null&&(B=ae<W),!B&&K&&R&&(B=K.localeCompare(R)<0),B)return window.__messageTracker?.(n,"skipped_evicted_message_update"),a}const w=f(o);if(w&&w.role==="user"){const P=p?.parts??[],O={info:{...w,userMessageMarker:!0,clientRole:"user"},parts:P.length>0?[...P]:[]},W=new Map(a.messages),R=[...d,O];R.sort((K,B)=>{const L=K.info?.time?.created||0,ne=B.info?.time?.created||0;return L-ne}),W.set(t,R);const V={messages:W},ae=ur(V.messageSessionIndex??a.messageSessionIndex,n,t);if(ae!==(V.messageSessionIndex??a.messageSessionIndex)&&(V.messageSessionIndex=ae),p){const K=new Map(a.pendingAssistantParts);K.delete(n),V.pendingAssistantParts=K}return V}if(!w||w.role!=="assistant")return a;const T=p?.parts??[],M={info:{...w,animationSettled:w?.animationSettled??!1},parts:T.length>0?[...T]:[]},N=new Map(a.messages),A=[...d,M];N.set(t,A);const C={messages:N},D=ur(C.messageSessionIndex??a.messageSessionIndex,n,t);if(D!==(C.messageSessionIndex??a.messageSessionIndex)&&(C.messageSessionIndex=D),p){const P=new Map(a.pendingAssistantParts);P.delete(n),C.pendingAssistantParts=P}return C}const h=d[u],g=h.info;if(g.userMessageMarker===!0||g.clientRole==="user"||g.role==="user"){const w={...h.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:g.providerID||void 0,modelID:g.modelID||void 0},T={...h,info:w},M=new Map(a.messages),N=[...d];return N[u]=T,M.set(t,N),{messages:M}}const y={...h.info,...o};o.role&&o.role!==h.info.role&&(y.role=h.info.role),y.clientRole=y.clientRole??h.info.clientRole??h.info.role,y.clientRole==="user"&&(y.userMessageMarker=!0);const b=p?.parts?m(h.parts,p.parts):h.parts,v={...h,info:y,parts:b},k=new Map(a.messages),j=[...d];j[u]=v,k.set(t,j);const S={messages:k};if(p){const w=new Map(a.pendingAssistantParts);w.delete(n),S.pendingAssistantParts=w}return S})},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}}),Ys([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=dr.get(t);d&&(clearTimeout(d),dr.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}}),dr.delete(t)},2e3);dr.set(t,u)}},syncMessages:(t,n)=>{const o=ui(t),a=mi(n,o),i=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=i?a.filter(d=>{const u=d?.info?.id;return u?tn(u,i):!0}):a;r(d=>{const u=new Map(d.messages),p=d.messages.get(t)||[],m=new Map(p.filter(S=>typeof S.info?.id=="string").map(S=>[S.info.id,S])),f=c.map(S=>{const w={...S.info,clientRole:S.info?.clientRole??S.info.role,userMessageMarker:S.info.role==="user"?!0:S.info?.userMessageMarker,animationSettled:S.info.role==="assistant"?S.info?.animationSettled??!0:S.info?.animationSettled},T=(Array.isArray(S.parts)?S.parts:[]).map(A=>{if(A?.type==="text"){const C=A.text??A.content??"";if(io(C))return{...A,synthetic:!0}}return A}),M=typeof w?.id=="string"?w.id:void 0,N=M?m.get(M):void 0;if(N&&N.info.role==="assistant"){const A=Array.isArray(N.parts)?N.parts:[],C=fr(A),D=fr(T);if(_n(A)&&C>D){const O=On(A,T);return{...S,info:w,parts:O}}}return{...S,info:w,parts:T}}),h=mo(f),g=new Set(p.map(S=>S.info.id)),x=new Set(h.map(S=>S.info.id)),y=[];g.forEach(S=>{x.has(S)||y.push(S)}),u.set(t,h);const b={messages:u,isSyncing:!0};Ys(y);const v=Er(d.messageStreamStates,y);if(v!==d.messageStreamStates&&(b.messageStreamStates=v),y.length>0){const S=d.streamingMessageIds.get(t);S&&y.includes(S)&&(b.streamingMessageIds=fs(b.streamingMessageIds??d.streamingMessageIds,t,null))}if(y.length>0){const S=sn(b.messageSessionIndex??d.messageSessionIndex,y);S!==(b.messageSessionIndex??d.messageSessionIndex)&&(b.messageSessionIndex=S)}if(y.length>0){const S=new Map(d.pendingAssistantParts);let w=!1;y.forEach(T=>{S.delete(T)&&(w=!0)}),w&&(b.pendingAssistantParts=S)}const k=b.messageSessionIndex??d.messageSessionIndex;let j=k;return h.forEach(S=>{const w=S?.info?.id;typeof w=="string"&&w.length>0&&(j=ur(j,w,t))}),j!==k&&(b.messageSessionIndex=j),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+sp;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(x=>x.info.id)),g=i.filter(x=>!h.has(x.info.id)).map(x=>x.info.id);r(x=>{const y=new Map(x.messages);y.set(t,m);const b=new Map(x.sessionMemoryState),v={...c,viewportAnchor:d-u,trimmedHeadMaxId:ap(f,c.trimmedHeadMaxId)};b.set(t,v);const k={messages:y,sessionMemoryState:b};Ys(g);const j=Er(x.messageStreamStates,g);if(j!==x.messageStreamStates&&(k.messageStreamStates=j),g.length>0){const T=x.streamingMessageIds.get(t);T&&g.includes(T)&&(k.streamingMessageIds=fs(k.streamingMessageIds??x.streamingMessageIds,t,null))}if(g.length>0){const T=sn(k.messageSessionIndex??x.messageSessionIndex,g);T!==(k.messageSessionIndex??x.messageSessionIndex)&&(k.messageSessionIndex=T)}const S=k.messageSessionIndex??x.messageSessionIndex;let w=S;return m.forEach(T=>{const M=T?.info?.id;typeof M=="string"&&M.length>0&&(w=ur(w,M,t))}),w!==S&&(k.messageSessionIndex=w),k})},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 x=!1;g.forEach((j,S)=>{j.sessionId===c&&(g.delete(S),x=!0)}),x&&(h.pendingAssistantParts=g);const y=new Map(d.sessionCompactionUntil);y.delete(c)&&(h.sessionCompactionUntil=y),Ys(p);const b=Er(d.messageStreamStates,p);b!==d.messageStreamStates&&(h.messageStreamStates=b);const v=sn(h.messageSessionIndex??d.messageSessionIndex,p);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const k=fs(d.streamingMessageIds,c,null);if(k!==d.streamingMessageIds&&(h.streamingMessageIds=k),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 fo(t,()=>ke.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=mo(h),x=new Map(f.messages);x.set(t,g);const y=Math.max(0,g.length-a.length),b=new Map(f.sessionMemoryState);return b.set(t,{...i,viewportAnchor:i.viewportAnchor+y,hasMoreAbove:u-p>0,totalAvailableMessages:c.length}),{messages:x,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:ks(()=>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"})),cp=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),dp=r=>r?cp.has(r.toLowerCase()):!1,up=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},mp=r=>{if(r)try{const s=up();if(s?.getState)return s.getState().agents?.find?.(n=>n.name===r)}catch{}},jn=r=>{const s=mp(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"},fi=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},po=r=>{const s=r.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return fi(s);const t=r.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:fi(t.tokens)},ho=(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}},Ir=["ask","allow","full"],xt=Pt()(Wt(Ss((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(y=>y.name===m.mode))return m.mode;if(m.providerID&&m.modelID){const x=n.find(y=>y.model?.providerID===m.providerID&&y.model?.modelID===m.modelID);if(x)return x.name}const{currentAgentContext:h}=s(),g=h.get(t);if(g&&n.find(x=>x.name===g))return g;if(f>0&&m.providerID&&m.modelID){const y=(o.get(t)||[]).filter(b=>b.info.role==="assistant").sort((b,v)=>b.info.time.created-v.info.time.created);for(let b=f-1;b>=0;b--){const k=y[b].info;if(k.providerID===m.providerID&&k.modelID===m.modelID){if(k.mode&&typeof k.mode=="string"&&n.find(w=>w.name===k.mode))return k.mode;const j=n.find(S=>S.model?.providerID===k.providerID&&S.model?.modelID===k.modelID);if(j)return j.name}}}return m.providerID&&m.modelID&&n.find(y=>y.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 x=c(g,p.indexOf(f));if(x&&n.find(y=>y.name===x)){const y={providerId:g.providerID,modelId:g.modelID,timestamp:h.time.created},b=i.get(x);(!b||y.timestamp>b.timestamp)&&i.set(x,y)}}}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=ho(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(k=>k.info.role==="assistant");if(m.length===0)return null;const f=m[m.length-1],h=f.info.id,g=k=>{const j=()=>{r(S=>{const w=S.sessionContextUsage.get(t);if(w&&w.totalTokens===k.totalTokens&&w.percentage===k.percentage&&w.contextLimit===k.contextLimit&&(w.outputLimit??0)===(k.outputLimit??0)&&(w.normalizedOutput??0)===(k.normalizedOutput??0)&&w.thresholdLimit===k.thresholdLimit&&w.lastMessageId===k.lastMessageId)return S;const T=new Map(S.sessionContextUsage);return T.set(t,k),{sessionContextUsage:T}})};typeof queueMicrotask=="function"?queueMicrotask(j):typeof window<"u"?window.setTimeout(j,0):setTimeout(j,0)},x=s().sessionContextUsage.get(t);if(x&&x.lastMessageId===h){const k=x.normalizedOutput??x.outputLimit??0,j=x.contextLimit!==c||k!==d||x.thresholdLimit!==u;if(j&&x.totalTokens>0){const S=x.totalTokens/u*100,w={totalTokens:x.totalTokens,percentage:Math.min(S,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(w),w}if(!j&&x.totalTokens>0)return x}const y=po(f);if(y===0)return x||null;const b=ho(y,n,o),v={totalTokens:y,percentage:b.percentage,contextLimit:b.contextLimit,outputLimit:b.outputLimit,normalizedOutput:b.normalizedOutput,thresholdLimit:b.thresholdLimit,lastMessageId:h};return g(v),v},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=po(d);if(u===0)return;const p=ho(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"&&po(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=jn(n))=>!t||!n?o:s().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=jn(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||Ir.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=jn(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=s().getSessionAgentEditMode(t,n,a),c=Ir.indexOf(i),d=Ir.indexOf(a),p=((c>=0?c:d>=0?d:0)+1)%Ir.length,m=Ir[p];s().setSessionAgentEditMode(t,n,m,a)}}),{name:"context-store",storage:ks(()=>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"})),fp=r=>typeof r=="object"&&r!==null,pp=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},hp=async(r,s)=>{try{const t=Ye.getState(),n=t.getWorktreeMetadata(r);if(n?.path)return ke.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 ke.withDirectory(a,s)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return s()},Bn=Pt()(Wt(Ss((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=jn(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&dp(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 hp(t,()=>ke.respondToPermission(t,n,o)),o==="reject"&&await nt.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:ks(()=>ts()),partialize:r=>({permissions:Array.from(r.permissions.entries())}),merge:(r,s)=>{if(!fp(r))return s;const t=pp(r.permissions);return{...s,permissions:new Map(t)}}}),{name:"permission-store"})),cc=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
|
-
`),pi=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},hi=(r,s,t)=>{if(!s)return null;const n=t(s)?.path;if(typeof n=="string"&&n.trim().length>0)return pi(n);const o=r.find(a=>a.id===s);return o?pi(o.directory??null):null},fe=Pt()(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,pendingInputText:null,getSessionAgentEditMode:(t,n,o)=>xt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>xt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>xt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>Ye.getState().loadSessions(),createSession:async(t,n,o)=>{const a=await Ye.getState().createSession(t,n,o);return a?.id&&await s().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=nt.getState(),{messages:o,lastUsedProvider:a}=n;let i,c;if(o.forEach((b,v)=>{const k=b.find(j=>j.info?.id===t);k&&!i&&(i=k,c=v)}),!i||i.info.role!=="assistant")return;const d=cc(i.parts);if(!d.trim())return;const u=Ye.getState(),p=hi(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}=St.getState(),x=f||a?.providerID,y=h||a?.modelID;!x||!y||await ke.sendMessage({id:m.id,providerID:x,modelID:y,text:d,prefaceText:ic,agent:g??void 0})},deleteSession:(t,n)=>Ye.getState().deleteSession(t,n),deleteSessions:(t,n)=>Ye.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>Ye.getState().updateSessionTitle(t,n),shareSession:t=>Ye.getState().shareSession(t),unshareSession:t=>Ye.getState().unshareSession(t),setCurrentSession:async t=>{const n=s().currentSessionId,o=hi(Ye.getState().sessions,t,Ye.getState().getWorktreeMetadata),a=ke.getDirectory()??jt.getState().currentDirectory??null,i=o??a;try{ke.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)}Ye.getState().setCurrentSession(t),t&&(s().messages.get(t)||await s().loadMessages(t),s().trimToViewportWindow(t,mf)),s().evictLeastRecentlyUsed()},loadMessages:t=>nt.getState().loadMessages(t),sendMessage:(t,n,o,a,i,c)=>{const d=Ye.getState().currentSessionId;return nt.getState().sendMessage(t,n,o,a,d||void 0,i,c)},abortCurrentOperation:()=>{const t=Ye.getState().currentSessionId;return nt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=Ye.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&&nt.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=Ye.getState().currentSessionId||t;return nt.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>nt.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>nt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>nt.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>nt.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:xt.getState().currentAgentContext,sessionAgentSelections:xt.getState().sessionAgentSelections,getSessionAgentEditMode:xt.getState().getSessionAgentEditMode};return Bn.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>Bn.getState().respondToPermission(t,n,o),clearError:()=>Ye.getState().clearError(),getSessionsByDirectory:t=>Ye.getState().getSessionsByDirectory(t),getLastMessageModel:t=>nt.getState().getLastMessageModel(t),getCurrentAgent:t=>xt.getState().getCurrentAgent(t),syncMessages:(t,n)=>nt.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>Ye.getState().applySessionMetadata(t,n),addAttachedFile:t=>zs.getState().addAttachedFile(t),addServerFile:(t,n,o)=>zs.getState().addServerFile(t,n,o),removeAttachedFile:t=>zs.getState().removeAttachedFile(t),clearAttachedFiles:()=>zs.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>nt.getState().updateViewportAnchor(t,n),trimToViewportWindow:(t,n)=>{const o=Ye.getState().currentSessionId;return nt.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=Ye.getState().currentSessionId;return nt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>nt.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>xt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>xt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>xt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>xt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>xt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>xt.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=nt.getState().messages;return xt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>Ye.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>Ye.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>Ye.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>Ye.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>Ye.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>Ye.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{const o=Ye.getState().currentSessionId;if(!o)return null;const a=nt.getState().messages;return xt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=nt.getState().messages;return xt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=nt.getState().messages;return xt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=nt.getState().messages.get(t)||[],o=Ye.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=nt.getState().messages;return xt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>Ye.getState().updateSession(t),revertToMessage:async(t,n)=>{const a=(nt.getState().messages.get(t)||[]).find(p=>p.info.id===n);let i="";a&&a.info.role==="user"&&(i=a.parts.filter(m=>m.type==="text").map(m=>{const f=m;return f.text||f.content||""}).join(`
|
|
6
|
-
`).trim());const c=await ke.revertSession(t,n);Ye.getState().updateSession(c);const d=nt.getState().messages.get(t)||[],u=c.revert?.messageID;if(u){const p=d.findIndex(m=>m.info.id===u);if(p!==-1){const m=d.slice(0,p);nt.getState().syncMessages(t,m)}}i&&r({pendingInputText:i})},setPendingInputText:t=>{r({pendingInputText:t})},consumePendingInputText:()=>{const t=s().pendingInputText;return t!==null&&r({pendingInputText:null}),t}}),{name:"composed-session-store"}));Ye.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||fe.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})});nt.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}}}}}),fe.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})});zs.subscribe((r,s)=>{r.attachedFiles!==s.attachedFiles&&fe.setState({attachedFiles:r.attachedFiles})});xt.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||fe.setState({sessionModelSelections:r.sessionModelSelections,sessionAgentSelections:r.sessionAgentSelections,sessionAgentModelSelections:r.sessionAgentModelSelections,currentAgentContext:r.currentAgentContext,sessionContextUsage:r.sessionContextUsage,sessionAgentEditModes:r.sessionAgentEditModes})});Bn.subscribe((r,s)=>{r.permissions!==s.permissions&&fe.setState({permissions:r.permissions})});fe.setState({sessions:Ye.getState().sessions,currentSessionId:Ye.getState().currentSessionId,lastLoadedDirectory:Ye.getState().lastLoadedDirectory,isLoading:Ye.getState().isLoading,error:Ye.getState().error,webUICreatedSessions:Ye.getState().webUICreatedSessions,worktreeMetadata:Ye.getState().worktreeMetadata,availableWorktrees:Ye.getState().availableWorktrees,messages:nt.getState().messages,sessionMemoryState:nt.getState().sessionMemoryState,messageStreamStates:nt.getState().messageStreamStates,sessionCompactionUntil:nt.getState().sessionCompactionUntil,sessionAbortFlags:nt.getState().sessionAbortFlags,streamingMessageIds:nt.getState().streamingMessageIds,abortControllers:nt.getState().abortControllers,lastUsedProvider:nt.getState().lastUsedProvider,isSyncing:nt.getState().isSyncing,permissions:Bn.getState().permissions,attachedFiles:zs.getState().attachedFiles,sessionModelSelections:xt.getState().sessionModelSelections,sessionAgentSelections:xt.getState().sessionAgentSelections,sessionAgentModelSelections:xt.getState().sessionAgentModelSelections,currentAgentContext:xt.getState().currentAgentContext,sessionContextUsage:xt.getState().sessionContextUsage,sessionAgentEditModes:xt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=fe);const ba=({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}),x=l.useRef(null),y=l.useCallback(()=>{const N=r.current;if(!N)return;const{scrollHeight:A,clientHeight:C,scrollTop:D,scrollWidth:P,clientWidth:O,scrollLeft:W}=N,R=8;if(A>C){const V=Math.max(C-R*2,0),ae=C/A*V,K=Math.max(s,Math.min(V,ae)),B=Math.max(V-K,0),L=Math.max(A-C,1),ne=D/L*B;d({length:K,offset:ne})}else d({length:0,offset:0});if(!o&&P>O){const V=Math.max(O-R*2,0),ae=O/P*V,K=Math.max(s,Math.min(V,ae)),B=Math.max(V-K,0),L=Math.max(P-O,1),ne=W/L*B;p({length:K,offset:ne})}else p({length:0,offset:0})},[r,s,o]),b=l.useCallback(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(()=>i(!1),t)},[t]),v=l.useCallback(()=>{f.current&&cancelAnimationFrame(f.current),f.current=requestAnimationFrame(()=>{y(),i(!0),b()})},[b,y]);l.useEffect(()=>{const N=r.current;if(!N)return;y(),i(!0),b(),N.addEventListener("scroll",v,{passive:!0});const A=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null;A?.observe(N);const C=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return C?.observe(N,{childList:!0,subtree:!0,characterData:!0}),()=>{N.removeEventListener("scroll",v),A?.disconnect(),C?.disconnect(),m.current&&clearTimeout(m.current),f.current&&cancelAnimationFrame(f.current)}},[r,v,b,y]);const k=(N,A)=>{const C=r.current;C&&(h.current=!0,g.current={pointerX:N.clientX,pointerY:N.clientY,scrollTop:C.scrollTop,scrollLeft:C.scrollLeft},x.current=A,i(!0),m.current&&clearTimeout(m.current),N.currentTarget.setPointerCapture(N.pointerId))},j=N=>{if(!h.current)return;const A=r.current;if(!A)return;const C=x.current;if(C==="vertical"){const{pointerY:D,scrollTop:P}=g.current,O=N.clientY-D,W=A.clientHeight,R=Math.max(W-c.length,1),V=Math.max(A.scrollHeight-A.clientHeight,1),ae=O/R*V;A.scrollTop=P+ae}else if(C==="horizontal"){const{pointerX:D,scrollLeft:P}=g.current,O=N.clientX-D,W=A.clientWidth,R=Math.max(W-u.length,1),V=Math.max(A.scrollWidth-A.clientWidth,1),ae=O/R*V;A.scrollLeft=P+ae}},S=N=>{h.current&&(h.current=!1,N.currentTarget.releasePointerCapture(N.pointerId),b())},w=c.length>0,T=u.length>0;if(!w&&!T)return null;const M=8;return e.jsxs("div",{className:I("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[w&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${M+c.offset}px`,right:`${M/2}px`},onPointerDown:N=>k(N,"vertical"),onPointerMove:j,onPointerUp:S,onPointerCancel:S}),T&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${M+u.offset}px`,bottom:`${M/2}px`},onPointerDown:N=>k(N,"horizontal"),onPointerMove:j,onPointerUp:S,onPointerCancel:S})]})},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:I("relative flex flex-col min-h-0 w-full overflow-hidden",s),children:[e.jsx(i,{ref:f,className:I("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(ba,{containerRef:f,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});Xe.displayName="ScrollableOverlay";const gi="mobile-overlay-root",gp=()=>{if(typeof document>"u")return null;let r=document.getElementById(gi);return r||(r=document.createElement("div"),r.id=gi,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=gp()),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:I("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(us,{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 Rd.createPortal(p,d.current)},Wo=({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=y=>y>=1e6?`${(y/1e6).toFixed(1)}M`:y>=1e3?`${(y/1e3).toFixed(1)}K`:y.toFixed(1).replace(/\.0$/,""),p=y=>y>=90?"text-status-error":y>=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 x=e.jsxs("div",{className:I("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(Ld,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:I(p(s),"font-medium"),children:[Math.min(s,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[x,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:I("typography-meta font-semibold",p(s)),children:[Math.min(s,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:x}),e.jsx(et,{children:e.jsx("div",{className:"space-y-0.5",children:f.map(y=>e.jsx("p",{className:"typography-micro leading-tight",children:y},y))})})]})},Fr={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},dc=(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 go(){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>Fr.md&&r<=Fr.lg,p=r<=Fr.md;let m=d&&p,f=d&&!m&&u,h=!d||r>Fr.lg,g="desktop";c?(m=!1,f=!1,h=!0,g="desktop"):m?g="mobile":f?g="tablet":(h=!0,g="desktop"),dc(c,g,d);let x="xs";for(const[y,b]of Object.entries(Fr))r>=b&&(x=y);return{isMobile:m,isTablet:f,isDesktop:h,deviceType:g,screenWidth:r,breakpoint:x,hasTouchInput:d}}function Et(){const[r,s]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:go());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{s(go())};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(go())},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;dc(t,r.deviceType,u)},[r.deviceType,r.hasTouchInput]),r}const rn=5e3,xp=1e4,yp=5e3,bp=1e4,ps=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),wp=(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},vp=(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!!wp(r.diffStats,s.diffStats)},jp=(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},At=Pt()(Wt((r,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:rn,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(vp(c.status,p)){d=!0;const m=new Map(s().directories),f=m.get(t)??ps(),h=jp(f.status,p),g=new Set((f.status?.files??[]).map(v=>v.path)),x=new Set((p.files??[]).map(v=>v.path)),y=new Map(f.diffCache);for(const v of g)x.has(v)||y.delete(v);for(const v of h)y.delete(v);const b=h.size>0;m.set(t,{...f,isGitRepo:!0,status:p,diffCache:y,lastStatusFetch:Date.now(),lastStatusChange:b?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>bp||!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:rn});else{const p=Math.min(a+yp,xp);r({currentPollInterval:p})}const{pollIntervalId:u}=s();u!==null&&r({pollIntervalId:o()})},a)};r({pollIntervalId:o(),currentPollInterval:rn})},stopPolling:()=>{const{pollIntervalId:t}=s();t&&(clearTimeout(t),r({pollIntervalId:null,currentPollInterval:rn}))},refresh:async(t,n={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,t,n)}}),{name:"git-store"})),uc=r=>At(s=>r?s.directories.get(r)?.status??null:null),Sp=r=>At(s=>r?s.directories.get(r)?.branches??null:null),kp=r=>At(s=>r?s.directories.get(r)?.log??null:null),Np=r=>At(s=>r?s.directories.get(r)?.identity??null:null),mc=r=>At(s=>r?s.directories.get(r)?.isGitRepo??null:null),Cp=r=>At(s=>r?s.directories.get(r)?.status?.files?.length??0:0);function Xt({...r}){return e.jsx(_d,{"data-slot":"dropdown-menu",...r})}function Jt({...r}){return e.jsx(Od,{"data-slot":"dropdown-menu-trigger",...r})}function Zt({className:r,sideOffset:s=4,...t}){return e.jsx(Bd,{children:e.jsx($d,{"data-slot":"dropdown-menu-content",sideOffset:s,className:I("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...t})})}function gt({className:r,inset:s,variant:t="default",...n}){return e.jsx(Ud,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":t,className:I("hover:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),...n})}function Mp({...r}){return e.jsx(zd,{"data-slot":"dropdown-menu-radio-group",...r})}function Ap({className:r,children:s,...t}){return e.jsxs(Hd,{"data-slot":"dropdown-menu-radio-item",className:I("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",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(Wd,{children:e.jsx(Tt,{className:"size-3"})})}),s]})}function Ur({className:r,...s}){return e.jsx(Vd,{"data-slot":"dropdown-menu-separator",className:I("bg-border -mx-1 my-0.5 h-px",r),...s})}function hr({...r}){return e.jsx(Gd,{"data-slot":"dropdown-menu-sub",...r})}function gr({className:r,inset:s,children:t,...n}){return e.jsxs(qd,{"data-slot":"dropdown-menu-sub-trigger","data-inset":s,className:I("hover:bg-muted 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(ns,{className:"ml-auto size-3.5"})]})}function xr({className:r,...s}){return e.jsx(Kd,{"data-slot":"dropdown-menu-sub-content",className:I("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...s})}const Dp={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 wa(r){return Dp[r]||{displayName:r.charAt(0).toUpperCase()+r.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Ep(r,s,t){const n=wa(r);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=or(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 or(r){const s=r.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",jsonc:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",cc:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",dart:"dart",r:"r",lua:"lua",vim:"vim",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",md:"markdown",mdx:"markdown",rst:"text",txt:"text",dockerfile:"dockerfile",makefile:"makefile",gitignore:"text",env:"text",conf:"text",cfg:"text",ini:"ini",sql:"sql",diff:"diff",patch:"diff"}[s||""]||null}const Tp=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function fc(r){const s=r.split(".").pop()?.toLowerCase();return Tp.includes(s||"")}function Ip(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 Fp(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(`
|
|
7
|
-
`):String(r)}const va=l.createContext(null),ar=()=>{const r=l.useContext(va);if(!r)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return r},pc=r=>{const s=ar();return r(s)},Pp=()=>pc(r=>r.runtime.isDesktop),ja=()=>pc(r=>r.runtime.isVSCode),Rp=Yd("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg typography-ui-label font-medium transition-[background-color,border-color,color,box-shadow,opacity] duration-150 ease-in-out disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-none hover:bg-primary/90",destructive:"bg-destructive text-white shadow-none hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-none hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-none hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-lg gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-lg px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function De({className:r,variant:s,size:t,asChild:n=!1,...o}){const a=n?Ml:"button";return e.jsx(a,{"data-slot":"button",className:I(Rp({variant:s,size:t,className:r})),...o})}const Lp=({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(De,{size:"sm",variant:"ghost",className:I("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(Xd,{className:"h-3 w-3"}):e.jsx(Jd,{className:"h-3 w-3"})})},Sa=ue.createContext(void 0);function ir(){const r=ue.useContext(Sa);if(!r)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return r}function ka(){return ue.useContext(Sa)}const _p="Flexoki",Op="dark",Bp={"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"},$p=[{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"}}],zp={name:_p,type:Op,colors:Bp,tokenColors:$p},Hp="Flexoki",Wp="light",Up={"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"},Vp=[{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"}}],Gp={name:Hp,type:Wp,colors:Up,tokenColors:Vp},Na="flexoki-dark",Ca="flexoki-light",qp=zp,Kp=Gp;function hc(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 gc(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 Ma=gc(qp,Na,"dark"),Aa=gc(Kp,Ca,"light");hc(Ma,Na);hc(Aa,Ca);const kr={dark:Na,light:Ca},xi=[Aa,Ma];let yi=!1;function xc(){yi||(_a(kr.dark,async()=>Ma),_a(kr.light,async()=>Aa),yi=!0)}const Yp=`
|
|
8
|
-
:host {
|
|
9
|
-
font-family: var(--font-mono);
|
|
10
|
-
font-size: var(--text-code);
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
:host, pre, [data-diffs], [data-code] {
|
|
14
|
-
transform: translateZ(0);
|
|
15
|
-
-webkit-transform: translateZ(0);
|
|
16
|
-
-webkit-backface-visibility: hidden;
|
|
17
|
-
backface-visibility: hidden;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
pre, [data-code] {
|
|
21
|
-
font-family: var(--font-mono);
|
|
22
|
-
font-size: var(--text-code);
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
[data-code] {
|
|
26
|
-
-webkit-overflow-scrolling: touch;
|
|
27
|
-
}
|
|
28
|
-
/* Reduce hunk separator height */
|
|
29
|
-
[data-separator-content] {
|
|
30
|
-
height: 24px !important;
|
|
31
|
-
}
|
|
32
|
-
[data-expand-button] {
|
|
33
|
-
height: 24px !important;
|
|
34
|
-
width: 24px !important;
|
|
35
|
-
}
|
|
36
|
-
[data-separator-multi-button] {
|
|
37
|
-
row-gap: 0 !important;
|
|
38
|
-
}
|
|
39
|
-
[data-expand-up] {
|
|
40
|
-
height: 12px !important;
|
|
41
|
-
min-height: 12px !important;
|
|
42
|
-
max-height: 12px !important;
|
|
43
|
-
margin: 0 !important;
|
|
44
|
-
margin-top: 3px !important;
|
|
45
|
-
padding: 0 !important;
|
|
46
|
-
border-radius: 4px 4px 0 0 !important;
|
|
47
|
-
}
|
|
48
|
-
[data-expand-down] {
|
|
49
|
-
height: 12px !important;
|
|
50
|
-
min-height: 12px !important;
|
|
51
|
-
max-height: 12px !important;
|
|
52
|
-
margin: 0 !important;
|
|
53
|
-
margin-top: -3px !important;
|
|
54
|
-
padding: 0 !important;
|
|
55
|
-
border-radius: 0 0 4px 4px !important;
|
|
56
|
-
}
|
|
57
|
-
`;function Xp(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 bi=({original:r,modified:s,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=ka()?.currentTheme?.metadata?.variant==="dark";xc();const d=ue.useRef(null),u=ue.useMemo(()=>{const m=Xp(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=Po(f,h);return d.current={key:m,fileDiff:g},g},[n,r,s,t]),p=ue.useMemo(()=>({theme:{dark:kr.dark,light:kr.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:Yp}),[c,o,a]);return typeof window>"u"?null:e.jsx(Xe,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(Zd,{fileDiff:u,options:p})})},Jp=1100,Zp=r=>{const{index:s,working_dir:t}=r;return s==="A"||t==="A"||s==="?"||t==="?"},wi=(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]})},Qp=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)}),wi(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(yt,{className:"size-4 opacity-50"})]})}),e.jsx(Zt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Mp,{value:s??"",onValueChange:n,children:r.map(i=>e.jsx(Ap,{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:wi(i.insertions,i.deletions)})]})},i.path))})})]})}),eh=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"}})]})]})})}),th=l.memo(({filePath:r,diff:s,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=l.useMemo(()=>or(r)||"text",[r]);return fc(r)?e.jsx(eh,{filePath:r,diff:s,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(bi,{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(bi,{original:s.original,modified:s.modified,language:a,fileName:r,renderSideBySide:n,wrapLines:o})})}),sh=l.memo(({directory:r,filePath:s,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=At(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(th,{filePath:s,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),rh=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=fe(),{currentDirectory:n}=jt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},nh=()=>{const{git:r}=ar(),s=rh(),{screenWidth:t,isMobile:n}=Et(),o=mc(s??null),a=uc(s??null),i=At(D=>D.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d}=At(),[u,p]=l.useState(null),m=we(D=>D.pendingDiffFile),f=we(D=>D.setPendingDiffFile),h=we(D=>D.diffLayoutPreference),g=we(D=>D.diffFileLayout),x=we(D=>D.setDiffFileLayout),y=we(D=>D.diffWrapLines),b=we(D=>D.setDiffWrapLines),v=l.useMemo(()=>{if(!a?.files)return[];const D=a.diffStats??{};return a.files.map(P=>({...P,insertions:D[P.path]?.insertions??0,deletions:D[P.path]?.deletions??0,isNew:Zp(P)})).sort((P,O)=>P.path.localeCompare(O.path))},[a]),k=l.useMemo(()=>u?v.find(D=>D.path===u)??null:null,[v,u]),j=l.useMemo(()=>{if(!k)return null;const D=g[k.path];if(D)return D;if(h==="inline")return"inline";if(h==="side-by-side")return"side-by-side";const P=t<Jp;return k.isNew||P?"inline":"side-by-side"},[k,g,h,t]);l.useEffect(()=>{s&&(c(s),At.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&&v.length>0&&p(v[0].path)},[v,u,m]),l.useEffect(()=>{u&&v.length>0&&(v.some(P=>P.path===u)||p(v[0]?.path??null))},[v,u]);const S=l.useCallback(D=>{p(D)},[]),w=(j??"side-by-side")==="side-by-side",M=!!At(l.useCallback(D=>!s||!u?null:D.directories.get(s)?.diffCache.get(u)??null,[s,u])),N=!!u&&!M,A=()=>!s||v.length===0?null:v.map(D=>e.jsx(sh,{directory:s,filePath:D.path,isVisible:D.path===u,renderSideBySide:w,wrapLines:y},D.path)),C=()=>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."}):v.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Working tree clean — no changes to display"}):e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[A(),N&&!M&&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(ta,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${v.length} ${v.length===1?"file":"files"} changed`})]}),e.jsx(Qp,{changedFiles:v,selectedFile:u,selectedFileEntry:k,onSelectFile:S,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),k&&e.jsx("button",{type:"button",onClick:()=>b(!y),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${y?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:y?"Disable line wrap":"Enable line wrap",children:e.jsx(Qd,{className:"size-4"})}),k&&j&&e.jsx(Lp,{mode:j==="side-by-side"?"side-by-side":"unified",onModeChange:D=>{if(!k)return;const P=D==="side-by-side"?"side-by-side":"inline";x(k.path,P)}})]}),C()]})},oh=()=>{const{git:r}=ar(),{currentSessionId:s,sessions:t,worktreeMetadata:n}=fe(),{currentDirectory:o}=jt(),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}=At(),m=Cp(d??null);return l.useEffect(()=>{d&&(u(d),At.getState().directories.get(d)?.status||p(d,r))},[d,u,p,r]),m},ah=()=>{const r=we(d=>d.setSessionSwitcherOpen),s=we(d=>d.toggleSidebar),{isMobile:t}=Et(),[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(qn,{className:"h-5 w-5"})})})},vi=()=>{const r=we(L=>L.setSessionSwitcherOpen),s=we(L=>L.toggleSidebar),t=we(L=>L.setSettingsDialogOpen),n=we(L=>L.toggleCommandPalette),o=we(L=>L.toggleHelpDialog),a=we(L=>L.isSidebarOpen),i=we(L=>L.sidebarWidth),c=we(L=>L.activeMainTab),d=we(L=>L.setActiveMainTab),{getCurrentModel:u}=St(),p=fe(L=>L.getContextUsage),{isMobile:m}=Et(),f=oh(),h=Qn(L=>L.available),g=l.useRef(null),[x,y]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);ue.useEffect(()=>{if(typeof window>"u")return;const L=typeof window.opencodeDesktop<"u";y(L)},[]);const v=u(),k=v&&typeof v.limit=="object"&&v.limit!==null?v.limit:null,j=k&&typeof k.context=="number"?k.context:0,S=k&&typeof k.output=="number"?k.output:0,w=p(j,S),T=we(L=>L.isSessionSwitcherOpen),M=l.useCallback(()=>{if(typeof document>"u")return;const L=document.activeElement;if(!L)return;const ne=L.tagName;(ne==="INPUT"||ne==="TEXTAREA"||ne==="SELECT"||L.isContentEditable)&&L.blur()},[]),N=l.useCallback(()=>{if(m){M(),r(!T);return}s()},[M,m,T,r,s]),A=l.useCallback(()=>{m&&M(),r(!1),t(!0)},[M,m,r,t]),C="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground",D=l.useMemo(()=>x&&b?a?"pl-0":"pl-[8.0rem]":"pl-3",[x,b,a]),P=l.useCallback(()=>{if(typeof document>"u")return;const L=g.current?.getBoundingClientRect().height;L&&document.documentElement.style.setProperty("--oc-header-height",`${L}px`)},[]);ue.useEffect(()=>{if(typeof window>"u")return;P();const L=g.current;if(!L||typeof ResizeObserver>"u")return()=>{};const ne=new ResizeObserver(()=>{P()});return ne.observe(L),window.addEventListener("resize",P),window.addEventListener("orientationchange",P),()=>{ne.disconnect(),window.removeEventListener("resize",P),window.removeEventListener("orientationchange",P)}},[P]),ue.useEffect(()=>{P()},[P,m]);const O=l.useCallback(async L=>{if(!L.target.closest("button, a, input, select, textarea")&&L.button===0&&x)try{const{getCurrentWindow:ne}=await br(async()=>{const{getCurrentWindow:Ne}=await import("./vendor-.pnpm-BcYW6LTb.js").then(de=>de.c2);return{getCurrentWindow:Ne}},__vite__mapDeps([0,1]));await ne().startDragging()}catch(ne){console.error("Failed to start window dragging:",ne)}},[x]),W=l.useCallback(async L=>{if(L.button===0&&x)try{const{getCurrentWindow:ne}=await br(async()=>{const{getCurrentWindow:Ne}=await import("./vendor-.pnpm-BcYW6LTb.js").then(de=>de.c2);return{getCurrentWindow:Ne}},__vite__mapDeps([0,1]));await ne().startDragging()}catch(ne){console.error("Failed to start window dragging:",ne)}},[x]),R=l.useMemo(()=>[{id:"chat",label:"Chat",icon:eu},{id:"diff",label:"Diff",icon:ws,badge:!m&&f>0?f:void 0},{id:"terminal",label:"Terminal",icon:Vs},{id:"git",label:"Git",icon:Yt}],[f,m]);ue.useEffect(()=>{const L=ne=>{if((ne.metaKey||ne.ctrlKey)&&!ne.shiftKey&&!ne.altKey){const Se=parseInt(ne.key,10);Se>=1&&Se<=R.length&&(ne.preventDefault(),d(R[Se-1].id))}};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[R,d]);const V=(L,ne)=>{const Se=c===L.id,Ne=L.icon,de=L.id==="chat",ge=L.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(L.id),onMouseDown:Se?W:void 0,className:I("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",Se?"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",Se?"text-foreground":"text-muted-foreground",Se&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",Se&&de&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",de&&!(x&&b&&a)&&"border-l",ge&&"border-r",de&&!m&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...Se&&de&&a?{"--sidebar-w":x&&b?`${i}px`:"64px"}:{},...de&&!(x&&b&&a)||ge?{borderColor:"var(--interactive-border)"}:{}},"aria-label":L.label,"aria-selected":Se,role:"tab",children:[m?e.jsx(Ne,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(Ne,{size:16}),e.jsx("span",{className:"header-tab-label",children:L.label})]}),de&&!m&&w&&w.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Wo,{totalTokens:w.totalTokens,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.outputLimit??0,size:"compact"})}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:L.badge})]}),!ne&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},L.id)},ae=()=>e.jsxs("div",{onMouseDown:O,className:I("app-region-drag relative flex h-12 select-none items-center",D),role:"tablist","aria-label":"Main navigation",children:[!(x&&b)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:N,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(qn,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:R.map((L,ne)=>V(L,ne===R.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(st,{delayDuration:500,children:[e.jsx(rt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:C,children:e.jsx(rr,{className:"h-5 w-5"})})}),e.jsx(et,{children:e.jsx("p",{children:"Command Palette (Ctrl+X)"})})]}),e.jsxs(st,{delayDuration:500,children:[e.jsx(rt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:C,children:e.jsx(vr,{className:"h-5 w-5"})})}),e.jsx(et,{children:e.jsx("p",{children:"Keyboard Shortcuts (Ctrl+H)"})})]})]})]}),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:N,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(tu,{className:"h-5 w-5"})}),w&&w.totalTokens>0&&c==="chat"&&e.jsx(Wo,{totalTokens:w.totalTokens,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.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:R.map(L=>{const ne=c===L.id,Se=L.icon;return e.jsxs(st,{delayDuration:500,children:[e.jsx(rt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{m&&M(),d(L.id)},"aria-label":L.label,"aria-selected":ne,role:"tab",className:I(C,ne&&"text-foreground"),children:[e.jsx(Se,{className:"h-5 w-5"}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:L.badge})]})}),e.jsx(et,{children:e.jsx("p",{children:L.label})})]},L.id)})}),e.jsxs(st,{delayDuration:500,children:[e.jsx(rt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:A,"aria-label":"Open settings",className:I(C,"relative"),children:[e.jsx(wr,{className:"h-5 w-5"}),h&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Update available"})]})}),e.jsx(et,{children:e.jsx("p",{children:h?"Settings (Update available)":"Settings"})})]})]})]}),B=I("header-safe-area border-b relative z-10",x?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:g,className:B,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:m?K():ae()})};function Da({className:r,...s}){return e.jsx("div",{"data-slot":"card",className:I("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",r),...s})}function yc({className:r,...s}){return e.jsx("div",{"data-slot":"card-header",className:I("@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 bc({className:r,...s}){return e.jsx("div",{"data-slot":"card-title",className:I("leading-none font-semibold",r),...s})}function wc({className:r,...s}){return e.jsx("div",{"data-slot":"card-content",className:I("px-6",r),...s})}class cs 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(Da,{className:"w-full max-w-md",children:[e.jsx(yc,{className:"text-center",children:e.jsxs(bc,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Ro,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(wc,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The application encountered an unexpected error. This has been logged for debugging."}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let nn=0;function vs({...r}){return e.jsx(su,{"data-slot":"dialog",...r})}function vc({...r}){return e.jsx(lu,{"data-slot":"dialog-trigger",...r})}function ih({...r}){return e.jsx(ou,{"data-slot":"dialog-portal",...r})}const jc=ue.forwardRef(({className:r,...s},t)=>(ue.useEffect(()=>(nn+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{nn=Math.max(0,nn-1),nn===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Al,{ref:t,"data-slot":"dialog-overlay",className:I("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",r),...s})));jc.displayName=Al.displayName;function js({className:r,children:s,showCloseButton:t=!0,...n}){return e.jsxs(ih,{"data-slot":"dialog-portal",children:[e.jsx(jc,{className:"rounded-none"}),e.jsxs(ru,{"data-slot":"dialog-content",className:I("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(nu,{"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(us,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Rs({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:I("flex flex-col gap-2 text-center sm:text-left",r),...s})}function Vr({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-footer",className:I("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",r),...s})}function Ls({className:r,...s}){return e.jsx(au,{"data-slot":"dialog-title",className:I("typography-markdown leading-none font-semibold text-foreground",r),...s})}function lr({className:r,...s}){return e.jsx(iu,{"data-slot":"dialog-description",className:I("text-muted-foreground typography-ui-label",r),...s})}const ji="https://github.com/btriapitsyn/openchamber/releases";async function lh(){try{const r=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return r.ok?{success:!0}:{success:!1,error:(await r.json().catch(()=>({}))).error||`Server error: ${r.status}`}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to install update"}}}async function ch(r=30,s=2e3){for(let t=0;t<r;t++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,s))}return!1}const Sc=({open:r,onOpenChange:s,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[p,m]=ue.useState(!1),[f,h]=ue.useState("idle"),[g,x]=ue.useState(null),y=t?.version?`${ji}/tag/v${t.version}`:ji,b=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",k=t?.updateCommand||"openchamber update";ue.useEffect(()=>{r||(h("idle"),x(null))},[r]);const j=async()=>{try{await navigator.clipboard.writeText(k),m(!0),setTimeout(()=>m(!1),2e3)}catch{}},S=ue.useCallback(async()=>{h("updating"),x(null);const T=await lh();if(!T.success){h("error"),x(T.error||"Update failed");return}h("restarting"),await new Promise(N=>setTimeout(N,2e3)),h("reconnecting"),await ch()?window.location.reload():(h("error"),x("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),w=f!=="idle"&&f!=="error";return e.jsx(vs,{open:r,onOpenChange:w?void 0:s,children:e.jsxs(js,{className:"max-w-md",children:[e.jsx(Rs,{children:e.jsxs(Ls,{className:"flex items-center gap-2",children:[e.jsx(cu,{className:"h-5 w-5 text-primary"}),f==="restarting"||f==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(t?.currentVersion||t?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t?.currentVersion&&e.jsx("span",{className:"font-mono",children:t.currentVersion}),t?.currentVersion&&t?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),t?.version&&e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),v&&w&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(pn,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[f==="updating"&&"Installing update...",f==="restarting"&&"Server restarting...",f==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),t?.body&&!w&&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((T,M)=>/^\d+\.\d+\.\d+$/.test(T.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",T.trim(),`
|
|
58
|
-
`]},M):T.replace(/^- /gm,"• ").trim()+`
|
|
59
|
-
|
|
60
|
-
`)})}),v&&f==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(du,{className:"h-4 w-4"}),e.jsx("span",{children:"Or update via terminal:"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-2 bg-muted rounded-md font-mono text-sm text-foreground overflow-x-auto",children:k}),e.jsx("button",{onClick:j,className:I("flex items-center justify-center p-2 rounded-md","text-muted-foreground hover:text-foreground hover:bg-accent","transition-colors",p&&"text-primary"),title:p?"Copied!":"Copy command",children:p?e.jsx(Tt,{className:"h-4 w-4"}):e.jsx(uu,{className:"h-4 w-4"})})]})]}),!v&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[b,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${b}%`}})})]}),(i||g)&&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||g})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:I("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(Lo,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:c,className:I("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($r,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:I("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(pn,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:I("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Is,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!w&&e.jsxs("button",{onClick:S,className:I("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($r,{className:"h-4 w-4"}),"Update Now"]}),v&&w&&e.jsxs("button",{disabled:!0,className:I("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(pn,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},$n=264,Si=200,ki=500,dh=40,Ni="openchamber:check-for-updates",uh=({isOpen:r,isMobile:s,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=we(),[c,d]=l.useState(!1),u=l.useRef(0),p=l.useRef(n||$n),[m,f]=l.useState(!1),h=Qn(),g=l.useRef(!1),x=h.checkForUpdates,{available:y,downloaded:b,checking:v}=h,[k,j]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),S=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const A=typeof window.opencodeDesktop<"u";j(A)},[]),l.useEffect(()=>{if(typeof window>"u")return;const A=()=>{typeof window.opencodeDesktop<"u"&&(g.current=!0,x())};return window.addEventListener(Ni,A),()=>{window.removeEventListener(Ni,A)}},[x]),l.useEffect(()=>{g.current&&(v||(y||b?f(!0):xe.success("No updates available",{description:"You are running the latest version."}),g.current=!1))},[y,b,v]),l.useEffect(()=>{if(s||!c)return;const A=D=>{const P=D.clientX-u.current,O=Math.min(ki,Math.max(Si,p.current+P));o(O)},C=()=>{d(!1)};return window.addEventListener("pointermove",A),window.addEventListener("pointerup",C,{once:!0}),()=>{window.removeEventListener("pointermove",A),window.removeEventListener("pointerup",C)}},[s,c,o]),l.useEffect(()=>{s&&c&&d(!1)},[s,c]);const w=l.useCallback(async A=>{if(A.button===0&&k)try{const{getCurrentWindow:C}=await br(async()=>{const{getCurrentWindow:P}=await import("./vendor-.pnpm-BcYW6LTb.js").then(O=>O.c2);return{getCurrentWindow:P}},__vite__mapDeps([0,1]));await C().startDragging()}catch(C){console.error("Failed to start window dragging from sidebar:",C)}},[k]);if(s)return null;const T=r?Math.min(ki,Math.max(Si,n||$n)):0,M=k&&S,N=A=>{r&&(d(!0),u.current=A.clientX,p.current=T,A.preventDefault())};return e.jsxs("aside",{className:I("relative flex h-full overflow-hidden border-r",k?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",c?"transition-none":"",!r&&"border-r-0"),style:{width:`${T}px`,minWidth:`${T}px`,maxWidth:`${T}px`,pointerEvents:r?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!r||T===0,children:[r&&e.jsx("div",{className:I("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",c?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:N,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:I("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:`${T}px`,overflowX:"hidden"},"aria-hidden":!r,children:[M&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${dh}px`},onMouseDown:w,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(cs,{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:I("flex items-center gap-2 rounded-md px-3 py-2","text-sm font-semibold text-muted-foreground","hover:text-foreground","transition-colors"),children:[e.jsx(wr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),y||b?e.jsxs("button",{onClick:()=>f(!0),className:I("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($r,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!k&&e.jsxs(st,{children:[e.jsx(rt,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:I("flex items-center justify-center rounded-md p-1.5","text-muted-foreground","hover:text-foreground hover:bg-muted/50","transition-colors"),children:e.jsx(qt,{className:"h-4 w-4"})})}),e.jsx(et,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Sc,{open:m,onOpenChange:f,info:h.info,downloading:h.downloading,downloaded:h.downloaded,progress:h.progress,error:h.error,onDownload:h.downloadUpdate,onRestart:h.restartToUpdate,runtimeType:h.runtimeType})]})]})},kc=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:sa},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Kn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:rr},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:Dl},{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:mu}],mh={},Nc={},Cc={};kc.forEach(r=>{mh[r.id]=r.label,Nc[r.id]=r.description,Cc[r.id]=r});const Ci=Nc,fh=Cc;function zn({className:r,variant:s,...t}){return e.jsx(De,{variant:s,size:"sm",className:I("h-7 px-2 py-0",r),...t})}function Ft({className:r,type:s,...t}){return e.jsx("input",{type:s,"data-slot":"input",className:I("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 ph=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedAgentName:o,agents:a,setSelectedAgent:i,deleteAgent:c,loadAgents:d}=Mr(),{setSidebarOpen:u}=we(),{isMobile:p}=Et();l.useEffect(()=>{d()},[d]);const m=()=>{if(!r.trim()){xe.error("Agent name is required");return}if(a.some(v=>v.name===r)){xe.error("An agent with this name already exists");return}i(r),s(""),n(!1),p&&u(!1)},f=async v=>{if(xn(v)){xe.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${v.name}"?`)&&(await c(v.name)?xe.success(`Agent "${v.name}" deleted successfully`):xe.error("Failed to delete agent"))},h=v=>{const k=v.name;let j=1,S=`${k} Copy`;for(;a.some(w=>w.name===S);)j++,S=`${k} Copy ${j}`;i(S),n(!1),p&&u(!1)},g=v=>{switch(v){case"primary":return e.jsx(zr,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Tl,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(El,{className:"h-3 w-3 text-primary"});default:return null}},x=a.filter(v=>!Gl(v)),y=x.filter(xn),b=x.filter(v=>!xn(v));return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(vs,{open:t,onOpenChange:n,children:[e.jsx("div",{className:I("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:x.length}),e.jsx(vc,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(as,{className:"size-4"})})})]})]})}),e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:x.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Cn,{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:[y.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"}),y.map(v=>e.jsx(Mi,{agent:v,isSelected:o===v.name,onSelect:()=>{i(v.name),p&&u(!1)},onDuplicate:()=>h(v),getAgentModeIcon:g},v.name))]}),b.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"}),b.map(v=>e.jsx(Mi,{agent:v,isSelected:o===v.name,onSelect:()=>{i(v.name),p&&u(!1)},onDelete:()=>f(v),onDuplicate:()=>h(v),getAgentModeIcon:g},v.name))]})]})}),e.jsxs(js,{children:[e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Create New Agent"}),e.jsx(lr,{children:"Enter a unique name for your new agent"})]}),e.jsx(Ft,{value:r,onChange:v=>s(v.target.value),placeholder:"Agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:v=>{v.key==="Enter"&&m()}}),e.jsxs(Vr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(zn,{onClick:m,children:"Create"})]})]})]})})},Mi=({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:I("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(De,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Yn,{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(_s,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),!xn(r)&&n&&e.jsxs(gt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})});function hs({className:r,variant:s,...t}){return e.jsx(De,{variant:s,size:"sm",className:I("h-6 px-2 text-xs",r),...t})}const sr=ue.forwardRef(({className:r,...s},t)=>e.jsx(Xe,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:I("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}));sr.displayName="Textarea";const hh="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",gh="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",xh=Object.assign({"../assets/provider-logos/gocode.svg":hh,"../assets/provider-logos/kimi-for-coding.svg":gh}),Uo=new Map;for(const[r,s]of Object.entries(xh)){const t=r.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&s&&Uo.set(t[1].toLowerCase(),s)}function Mc(r){const s=r?.toLowerCase()??null,t=s?Uo.has(s):!1,n=s?Uo.get(s)??null:null,[o,a]=ue.useState(t?"local":"remote");ue.useEffect(()=>{a(t?"local":"remote")},[t,s]);const i=ue.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}=Mc(r),c=l.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:s||`${r} logo`,className:I("dark:invert",t),onError:c})},Ac=()=>{const{providers:r}=St(),{favoriteModels:s,recentModels:t}=we(),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}},Dc=({providerId:r,modelId:s,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=St(),i=we(M=>M.isMobile),{toggleFavoriteModel:c,isFavoriteModel:d,addRecentModel:u}=we(),{favoriteModelsList:p,recentModelsList:m}=Ac(),{isMobile:f}=Et(),h=i||f,[g,x]=l.useState(!1),[y,b]=l.useState(new Set),v=()=>x(!1),k=M=>{b(N=>{const A=new Set(N);return A.has(M)?A.delete(M):A.add(M),A})},j=M=>{const N=M?.name||M?.id||"",A=String(N);return A.length>40?A.substring(0,37)+"...":A},S=(M,N)=>{const A=`${M}/${N}`;return a.get(A)},w=(M,N)=>{t(M,N),u(M,N)},T=()=>h?e.jsx(Kt,{open:g,onClose:v,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:M,providerID:N,modelID:A})=>{const C=N===r&&A===s,D=S(N,A);return e.jsxs("div",{className:I("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",C?"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:()=>{w(N,A),v()},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(M)})]}),typeof D?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:D.description})]}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),c(N,A)},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(gs,{className:"h-4 w-4"})})]},`fav-mobile-${N}-${A}`)})})]}),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:M,providerID:N,modelID:A})=>{const C=N===r&&A===s,D=S(N,A);return e.jsxs("div",{className:I("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",C?"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:()=>{w(N,A),v()},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(M)})]}),typeof D?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:D.description})]}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),c(N,A)},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($s,{className:"h-4 w-4"})})]},`recent-mobile-${N}-${A}`)})})]}),o.map(M=>{const N=Array.isArray(M.models)?M.models:[];if(N.length===0)return null;const A=M.id===r,C=y.has(M.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:()=>k(M.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{providerId:M.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:M.name}),A&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),C?e.jsx(yt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ns,{className:"h-3 w-3 text-muted-foreground"})]}),C&&e.jsx("div",{className:"border-t border-border/20",children:N.map(D=>{const P=M.id===r&&D.id===s,O=S(M.id,D.id);return e.jsxs("div",{className:I("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",P?"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:()=>{w(M.id,D.id),v()},children:[e.jsx("span",{className:"font-medium truncate",children:j(D)}),typeof O?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:O.description})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:W=>{W.preventDefault(),W.stopPropagation(),c(M.id,D.id)},className:I("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(M.id,D.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(M.id,D.id)?"Unfavorite":"Favorite",children:d(M.id,D.id)?e.jsx(gs,{className:"h-4 w-4"}):e.jsx($s,{className:"h-4 w-4"})}),P&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},D.id)})})]},M.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:()=>{w("",""),v()},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:()=>x(!0),className:I("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(Ds,{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(yt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Xt,{children:[e.jsx(Jt,{asChild:!0,children:e.jsxs("div",{className:I("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(Ds,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Ds,{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(yt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Zt,{className:"max-w-[300px]",children:[p.length>0&&e.jsxs(hr,{children:[e.jsxs(gr,{className:"typography-meta",children:[e.jsx(gs,{className:"h-3 w-3 flex-shrink-0 mr-2 text-yellow-500"}),"Favorites"]}),e.jsx(xr,{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:M,providerID:N,modelID:A})=>{const C=S(N,A);return e.jsx(gt,{className:"typography-meta",onSelect:D=>{D.preventDefault(),w(N,A)},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(M)}),typeof C?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:C.description})]}),e.jsx("button",{onClick:D=>{D.preventDefault(),D.stopPropagation(),c(N,A)},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(gs,{className:"h-3.5 w-3.5"})})]})},`fav-${N}-${A}`)})})})]}),m.length>0&&e.jsxs(hr,{children:[e.jsxs(gr,{className:"typography-meta",children:[e.jsx(Mn,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(xr,{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:M,providerID:N,modelID:A})=>{const C=S(N,A);return e.jsx(gt,{className:"typography-meta",onSelect:D=>{D.preventDefault(),w(N,A)},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(M)}),typeof C?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:C.description})]}),e.jsx("button",{onClick:D=>{D.preventDefault(),D.stopPropagation(),c(N,A)},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($s,{className:"h-3.5 w-3.5"})})]})},`recent-${N}-${A}`)})})})]}),(p.length>0||m.length>0)&&e.jsx(Ur,{}),o.map(M=>{const N=Array.isArray(M.models)?M.models:[];return N.length===0?e.jsxs(gt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Vt,{providerId:M.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),M.name," (No models)"]},M.id):e.jsxs(hr,{children:[e.jsxs(gr,{className:"typography-meta",children:[e.jsx(Vt,{providerId:M.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),M.name]}),e.jsx(xr,{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(A=>{const C=S(M.id,A.id);return e.jsx(gt,{className:"typography-meta",onSelect:D=>{D.preventDefault(),w(M.id,A.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(A)}),typeof C?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:C.description})]}),e.jsx("button",{onClick:D=>{D.preventDefault(),D.stopPropagation(),c(M.id,A.id)},className:I("flex h-4 w-4 items-center justify-center hover:text-yellow-600",d(M.id,A.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":d(M.id,A.id)?"Unfavorite":"Favorite",children:d(M.id,A.id)?e.jsx(gs,{className:"h-3.5 w-3.5"}):e.jsx($s,{className:"h-3.5 w-3.5"})})]})},A.id)})})})]},M.id)}),e.jsx(gt,{className:"typography-meta",onSelect:()=>w("",""),children:e.jsx("span",{className:"text-muted-foreground",children:"No model (optional)"})})]})]}),T()]})},yh=()=>{const{tools:r}=ar(),[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}},bh=()=>{const{selectedAgentName:r,getAgentByName:s,createAgent:t,updateAgent:n,agents:o}=Mr();St();const{tools:a}=yh(),i=r?s(r):null,c=r&&!i,[d,u]=l.useState(""),[p,m]=l.useState(""),[f,h]=l.useState("subagent"),[g,x]=l.useState(""),[y,b]=l.useState(void 0),[v,k]=l.useState(void 0),[j,S]=l.useState(""),[w,T]=l.useState({}),[M,N]=l.useState("allow"),[A,C]=l.useState("allow"),[D,P]=l.useState("ask"),[O,W]=l.useState(!1);l.useEffect(()=>{if(c)u(r||""),m(""),h("subagent"),x(""),b(void 0),k(void 0),S(""),T({}),N("allow"),C("allow"),P("ask");else if(i&&(u(i.name),m(i.description||""),h(i.mode||"subagent"),i.model?.providerID&&i.model?.modelID?x(`${i.model.providerID}/${i.model.modelID}`):x(""),b(i.temperature),k(i.topP),S(i.prompt||""),T(i.tools||{}),i.permission)){const K=i.permission.edit;(K==="allow"||K==="ask"||K==="deny"||K==="full")&&N(K),i.permission.webfetch&&C(i.permission.webfetch),typeof i.permission.bash=="string"&&P(i.permission.bash)}},[i,c,r,o]);const R=async()=>{if(!d.trim()){xe.error("Agent name is required");return}W(!0);try{const K=g.trim(),B={name:d.trim(),description:p.trim()||void 0,mode:f,model:K===""?null:K,temperature:y,top_p:v,prompt:j.trim()||void 0,tools:Object.keys(w).length>0?w:void 0,permission:{edit:M,webfetch:A,bash:D}};let L;c?L=await t(B):L=await n(d,B),L?xe.success(c?"Agent created successfully":"Agent updated successfully"):xe.error(c?"Failed to create agent":"Failed to update agent")}catch(K){console.error("Error saving agent:",K),xe.error("An error occurred while saving")}finally{W(!1)}},V=K=>{T(B=>({...B,[K]:!B[K]}))},ae=K=>{const B={};a.forEach(L=>{B[L]=K}),T(B)};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(Ft,{value:d,onChange:K=>u(K.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(sr,{value:p,onChange:K=>m(K.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(hs,{variant:f==="primary"?"default":"outline",onClick:()=>h("primary"),className:I("gap-2",f==="primary"?void 0:"text-foreground"),children:[e.jsx(zr,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(hs,{variant:f==="subagent"?"default":"outline",onClick:()=>h("subagent"),className:I("gap-2",f==="subagent"?void 0:"text-foreground"),children:[e.jsx(El,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(hs,{variant:f==="all"?"default":"outline",onClick:()=>h("all"),className:I("gap-2",f==="all"?void 0:"text-foreground"),children:[e.jsx(Tl,{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(Dc,{providerId:g?g.split("/")[0]:"",modelId:g?g.split("/")[1]:"",onChange:(K,B)=>{x(K&&B?`${K}/${B}`:"")}})]}),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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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 B=Math.max(0,(y!==void 0?y:.7)-.1);b(parseFloat(B.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(Oa,{className:"h-3.5 w-3.5"})}),e.jsx(Ft,{type:"text",inputMode:"decimal",value:y!==void 0?y:"",onChange:K=>{const B=K.target.value;if(B===""){b(void 0);return}const L=parseFloat(B);!isNaN(L)&&L>=0&&L<=2&&b(L)},onBlur:K=>{const B=K.target.value;if(B!==""){const L=parseFloat(B);if(!isNaN(L)){const ne=Math.max(0,Math.min(2,L));b(parseFloat(ne.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 B=Math.min(2,(y!==void 0?y:.7)+.1);b(parseFloat(B.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(as,{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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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 B=Math.max(0,(v!==void 0?v:.9)-.1);k(parseFloat(B.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(Oa,{className:"h-3.5 w-3.5"})}),e.jsx(Ft,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:K=>{const B=K.target.value;if(B===""){k(void 0);return}const L=parseFloat(B);!isNaN(L)&&L>=0&&L<=1&&k(L)},onBlur:K=>{const B=K.target.value;if(B!==""){const L=parseFloat(B);if(!isNaN(L)){const ne=Math.max(0,Math.min(1,L));k(parseFloat(ne.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 B=Math.min(1,(v!==void 0?v:.9)+.1);k(parseFloat(B.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(as,{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(sr,{value:j,onChange:K=>S(K.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(De,{variant:"outline",size:"sm",onClick:()=>ae(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(De,{variant:"outline",size:"sm",onClick:()=>ae(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(K=>e.jsx("button",{type:"button",onClick:()=>V(K),className:I("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",w[K]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:K},K))})]}),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(De,{size:"sm",variant:M==="full"?"default":"outline",onClick:()=>N("full"),className:"h-6 px-2 text-xs",children:"Full"}),e.jsx(De,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>N("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>N("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:M==="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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(et,{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(De,{size:"sm",variant:D==="allow"?"default":"outline",onClick:()=>P("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:D==="ask"?"default":"outline",onClick:()=>P("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:D==="deny"?"default":"outline",onClick:()=>P("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Permission for running bash commands"}),e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(et,{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(De,{size:"sm",variant:A==="allow"?"default":"outline",onClick:()=>C("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:A==="ask"?"default":"outline",onClick:()=>C("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:A==="deny"?"default":"outline",onClick:()=>C("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Permission for fetching web content"}),e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(et,{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(De,{size:"sm",variant:"default",onClick:R,disabled:O,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ra,{className:"h-3 w-3"}),O?"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(Cn,{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"})]})})},wh=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedCommandName:o,commands:a,setSelectedCommand:i,deleteCommand:c,loadCommands:d}=Ar(),{setSidebarOpen:u}=we(),{isMobile:p}=Et();l.useEffect(()=>{d()},[d]);const m=()=>{if(!r.trim()){xe.error("Command name is required");return}const g=r.trim().replace(/\s+/g,"-");if(a.some(x=>x.name===g)){xe.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)?xe.success(`Command "${g.name}" deleted successfully`):xe.error("Failed to delete command"))},h=g=>{const x=g.name;let y=1,b=`${x}-copy`;for(;a.some(v=>v.name===b);)y++,b=`${x}-copy-${y}`;i(b),n(!1),p&&u(!1)};return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(vs,{open:t,onOpenChange:n,children:[e.jsx("div",{className:I("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(vc,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(as,{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(Vs,{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,x)=>g.name.localeCompare(x.name)).map(g=>e.jsx(vh,{command:g,isSelected:o===g.name,onSelect:()=>{i(g.name),p&&u(!1)},onDelete:()=>f(g),onDuplicate:()=>h(g)},g.name))})}),e.jsxs(js,{children:[e.jsxs(Rs,{children:[e.jsx(Ls,{children:"Create New Command"}),e.jsx(lr,{children:"Enter a unique name for your new slash command"})]}),e.jsx(Ft,{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(Vr,{children:[e.jsx(De,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(zn,{onClick:m,children:"Create"})]})]})]})})},vh=({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:I("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(De,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Yn,{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(_s,{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(Gs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})}),jh=({agentName:r,onChange:s,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=Mr(),a=o(),i=we(g=>g.isMobile),{isMobile:c}=Et(),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 x=g.name===r;return e.jsxs("button",{type:"button",className:I("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",x?"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})]}),x&&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:I("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(Cn,{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(yt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Xt,{children:[e.jsx(Jt,{asChild:!0,children:e.jsxs("div",{className:I("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(Cn,{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(yt,{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()]})},Sh=()=>{const{selectedCommandName:r,getCommandByName:s,createCommand:t,updateCommand:n,commands:o}=Ar(),a=r?s(r):null,i=r&&!a,[c,d]=l.useState(""),[u,p]=l.useState(""),[m,f]=l.useState(""),[h,g]=l.useState(""),[x,y]=l.useState(""),[b,v]=l.useState(!1),[k,j]=l.useState(!1);l.useEffect(()=>{i?(d(r||""),p(""),f(""),g(""),y(""),v(!1)):a&&(d(a.name),p(a.description||""),f(a.agent||""),g(a.model||""),y(a.template||""),v(a.subtask||!1))},[a,i,r,o]);const S=async()=>{if(!c.trim()){xe.error("Command name is required");return}if(!x.trim()){xe.error("Command template is required");return}j(!0);try{const w=m.trim(),T=h.trim(),M=x.trim(),N={name:c.trim(),description:u.trim()||void 0,agent:w===""?null:w,model:T===""?null:T,template:M,subtask:b};let A;i?A=await t(N):A=await n(c,N),A?xe.success(i?"Command created successfully":"Command updated successfully"):xe.error(i?"Failed to create command":"Failed to update command")}catch(w){console.error("Error saving command:",w),xe.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(Ft,{value:c,onChange:w=>d(w.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(sr,{value:u,onChange:w=>p(w.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(jh,{agentName:m,onChange:w=>f(w)}),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(Dc,{providerId:h?h.split("/")[0]:"",modelId:h?h.split("/")[1]:"",onChange:(w,T)=>{g(w&&T?`${w}/${T}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:w=>v(w.target.checked),className:"sr-only"}),e.jsx("div",{className:I("w-5 h-5 rounded border-2 flex items-center justify-center",b?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:b&&e.jsx(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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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(sr,{value:x,onChange:w=>y(w.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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{sideOffset:8,className:"max-w-xs",children:["Replaces with the full contents of the specified file.",e.jsx("br",{}),"Example: @package.json includes the package.json content in the prompt"]})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(De,{size:"sm",variant:"default",onClick:S,disabled:k,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ra,{className:"h-3 w-3"}),k?"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(Vs,{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"})]})})},Ec=({sectionId:r,variant:s})=>{const t=fh[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:Ci[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:Ci[r]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60",children:"Coming soon..."})]})},kh=()=>e.jsx(Xe,{outerClassName:"h-full",className:"px-3 py-2",children:e.jsx(Ec,{sectionId:"providers",variant:"sidebar"})}),Nh=()=>e.jsx(Xe,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:e.jsx(Ec,{sectionId:"providers",variant:"page"})}),eo=Pt()(Wt(Ss((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 wf();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 kf("");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 vf(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 jf(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 Sf(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:ks(()=>ts()),partialize:r=>({selectedProfileId:r.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=eo);const Ch={branch:Yt,briefcase:aa,house:oa,graduation:na,code:ws,heart:Il},Mh={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Ah=()=>{const{selectedProfileId:r,profiles:s,globalIdentity:t,setSelectedProfile:n,deleteProfile:o,loadProfiles:a,loadGlobalIdentity:i}=eo(),{setSidebarOpen:c}=we(),{isMobile:d}=Et();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)?xe.success(`Profile "${m.name}" deleted successfully`):xe.error("Failed to delete profile"))};return e.jsxs("div",{className:"flex h-full flex-col bg-sidebar",children:[e.jsx("div",{className:I("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(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",onClick:u,children:e.jsx(as,{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(Ai,{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(Ai,{profile:m,isSelected:r===m.id,onSelect:()=>{n(m.id),d&&c(!1)},onDelete:()=>p(m)},m.id))})]})]})},Ai=({profile:r,isSelected:s,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=Ch[r.icon||"branch"]||Yt,i=Mh[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:I("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(De,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Yn,{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(Gs,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})})},Di=[{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)"}],Dh=[{key:"branch",Icon:Yt,label:"Branch"},{key:"briefcase",Icon:aa,label:"Work"},{key:"house",Icon:oa,label:"Personal"},{key:"graduation",Icon:na,label:"School"},{key:"code",Icon:ws,label:"Code"}],Eh=()=>{const{selectedProfileId:r,getProfileById:s,createProfile:t,updateProfile:n,deleteProfile:o}=eo(),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,x]=l.useState(""),[y,b]=l.useState("keyword"),[v,k]=l.useState("branch"),[j,S]=l.useState(!1);l.useEffect(()=>{i?(u(""),m(""),h(""),x(""),b("keyword"),k("branch")):a&&(u(a.name),m(a.userName),h(a.userEmail),x(a.sshKey||""),b(a.color||"keyword"),k(a.icon||"branch"))},[a,i,r]);const w=async()=>{if(!p.trim()||!f.trim()){xe.error("User name and email are required");return}S(!0);try{const N={name:d.trim()||p.trim(),userName:p.trim(),userEmail:f.trim(),sshKey:g.trim()||null,color:y,icon:v};let A;if(i)A=await t(N);else if(r)A=await n(r,N);else return;A?xe.success(i?"Profile created successfully":"Profile updated successfully"):xe.error(i?"Failed to create profile":"Failed to update profile")}catch(N){console.error("Error saving profile:",N),xe.error("An error occurred while saving")}finally{S(!1)}},T=async()=>{if(!(!r||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(r)?xe.success("Profile deleted successfully"):xe.error("Failed to delete profile")}catch(N){console.error("Error deleting profile:",N),xe.error("An error occurred while deleting")}},M=l.useMemo(()=>Di.find(A=>A.key===y)?.cssVar||"var(--syntax-keyword)",[y]);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(Ft,{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:Di.map(N=>e.jsx("button",{onClick:()=>b(N.key),className:I("w-8 h-8 rounded-lg border-2 transition-all",y===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:Dh.map(N=>{const A=N.Icon;return e.jsx("button",{onClick:()=>k(N.key),className:I("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",v===N.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:N.label,children:e.jsx(A,{className:"w-4 h-4",style:{color:M}})},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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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(Ft,{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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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(Ft,{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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{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(Ft,{value:g,onChange:N=>x(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(De,{size:"sm",variant:"destructive",onClick:T,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Gs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:I("flex gap-2",i&&"ml-auto"),children:e.jsxs(De,{size:"sm",variant:"default",onClick:w,disabled:j,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(ra,{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(Xn,{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 xo(r,s,t){return Math.min(t,Math.max(s,r))}const Hn=ue.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=ue.useRef(null);ue.useImperativeHandle(m,()=>f.current);const[h,g]=ue.useState(()=>String(r));ue.useEffect(()=>{document.activeElement!==f.current&&g(String(r))},[r]);const x=ue.useCallback(()=>{f.current?.focus()},[]),y=ue.useCallback(A=>{const C=xo(A,t,n);s(C),g(String(C))},[n,t,s]),b=ue.useCallback(()=>{const A=Number(h);return Number.isFinite(A)?A:r},[h,r]),v=ue.useCallback(()=>{y(b()+o),x()},[y,b,x,o]),k=ue.useCallback(()=>{y(b()-o),x()},[y,b,x,o]),j=A=>{const C=A.target.value;g(C);const D=Number(C);Number.isFinite(D)&&s(xo(D,t,n))},S=A=>{const C=Number(h);if(!Number.isFinite(C))g(String(r));else{const D=xo(C,t,n);D!==C&&s(D),g(String(D))}c?.(A)},w=A=>{if(A.key==="ArrowUp"){A.preventDefault(),v();return}if(A.key==="ArrowDown"){A.preventDefault(),k();return}d?.(A)},T=b(),M=u||T<=t,N=u||T>=n;return e.jsxs("div",{className:I("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:S,onKeyDown:w,disabled:u,className:I("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:v,className:I("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(Kr,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:M,onClick:k,className:I("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(yt,{className:"h-3.5 w-3.5"})})]})]})});Hn.displayName="NumberInput";const Th=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Ei=[{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"}],Ti=[{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."}],Ih=()=>{const{isMobile:r}=Et(),s=we(h=>h.showReasoningTraces),t=we(h=>h.setShowReasoningTraces),n=we(h=>h.toolCallExpansion),o=we(h=>h.setToolCallExpansion),a=we(h=>h.fontSize),i=we(h=>h.setFontSize),c=we(h=>h.padding),d=we(h=>h.setPadding),u=we(h=>h.diffLayoutPreference),p=we(h=>h.setDiffLayoutPreference),{themeMode:m,setThemeMode:f}=ir();return e.jsxs("div",{className:"w-full space-y-8",children:[!es()&&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:Th.map(h=>e.jsx(hs,{variant:m===h.value?"default":"outline",className:I(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(Hn,{value:a,onValueChange:i,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(hs,{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(Is,{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(hs,{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(Is,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value: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(Hn,{value:c,onValueChange:d,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(hs,{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(Is,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Tool Output"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:Ei.find(h=>h.value===n)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Ei.map(h=>e.jsx(hs,{variant:n===h.value?"default":"outline",className:I(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:Ti.map(h=>e.jsx(hs,{variant:u===h.id?"default":"outline",className:I(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:Ti.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"})]})]})},Fh="https://github.com/btriapitsyn/openchamber",Ph=()=>{const[r,s]=l.useState(!1),t=Qn(),n=t.info?.currentVersion||"unknown";return e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:n})]}),t.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(pn,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!t.checking&&t.available&&e.jsxs("button",{onClick:()=>s(!0),className:I("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx($r,{className:"h-4 w-4"}),"Update to ",t.info?.version]}),!t.checking&&!t.available&&!t.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"})]}),t.error&&e.jsx("p",{className:"typography-meta text-destructive",children:t.error}),e.jsx("button",{onClick:()=>t.checkForUpdates(),disabled:t.checking,className:I("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:"Check for updates"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("a",{href:Fh,target:"_blank",rel:"noopener noreferrer",className:I("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Fl,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:I("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Pl,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Sc,{open:r,onOpenChange:s,info:t.info,downloading:t.downloading,downloaded:t.downloaded,progress:t.progress,error:t.error,onDownload:t.downloadUpdate,onRestart:t.restartToUpdate,runtimeType:t.runtimeType})]})},Rh=1440*60*1e3,Tc=5,Ii=1440*60*1e3,yo=r=>r.time?.updated??r.time?.created??0,Fi=({sessions:r,currentSessionId:s,cutoffDays:t,keepRecent:n=Tc,now:o=Date.now()})=>{if(!Array.isArray(r)||t<=0)return[];const a=o-t*Rh,i=[...r].sort((d,u)=>yo(u)-yo(d)),c=new Set(i.slice(0,n).map(d=>d.id));return i.filter(d=>{if(!d?.id||c.has(d.id)||d.id===s||d.share)return!1;const u=yo(d);return u?u<a:!1}).map(d=>d.id)},Ic=r=>{const s=r?.autoRun!==!1,t=fe(x=>x.sessions),n=fe(x=>x.currentSessionId),o=fe(x=>x.isLoading),a=fe(x=>x.deleteSessions),i=we(x=>x.autoDeleteEnabled),c=we(x=>x.autoDeleteAfterDays),d=we(x=>x.autoDeleteLastRunAt),u=we(x=>x.setAutoDeleteLastRunAt),[p,m]=l.useState(!1),f=l.useRef(!1),h=l.useMemo(()=>c<=0?[]:Fi({sessions:t,currentSessionId:n,cutoffDays:c}),[c,n,t]),g=l.useCallback(async({force:x=!1}={})=>{if(f.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!i||c<=0)&&!x)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const y=Date.now();if(!x&&d&&y-d<Ii)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const b=Fi({sessions:t,currentSessionId:n,cutoffDays:c,now:y});if(b.length===0)return u(y),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};f.current=!0,m(!0);try{return await a(b,{silent:!0})}finally{f.current=!1,m(!1),u(Date.now())}},[c,i,d,n,a,o,t,u]);return l.useEffect(()=>{if(!s||!i||c<=0||o||t.length===0)return;const x=Date.now();d&&x-d<Ii||g()},[c,i,d,s,o,g]),{candidates:h,isRunning:p,runCleanup:g,keepRecentCount:Tc}},bo=1,wo=365,Lh=()=>{const{isMobile:r}=Et(),s=we(f=>f.autoDeleteEnabled),t=we(f=>f.autoDeleteAfterDays),n=we(f=>f.setAutoDeleteEnabled),o=we(f=>f.setAutoDeleteAfterDays),[a,i]=l.useState(String(t));l.useEffect(()=>{i(String(t))},[t]);const{candidates:c,isRunning:d,runCleanup:u}=Ic({autoRun:!1}),p=c.length,m=l.useCallback(async()=>{const f=await u({force:!0});if(f.deletedIds.length===0&&f.failedIds.length===0){xe.message("No sessions eligible for deletion");return}f.deletedIds.length>0&&xe.success(`Deleted ${f.deletedIds.length} session${f.deletedIds.length===1?"":"s"}`),f.failedIds.length>0&&xe.error(`Failed to delete ${f.failedIds.length} session${f.failedIds.length===1?"":"s"}`)},[u]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session retention"}),e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(qt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(et,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:s,onChange:f=>n(f.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[r?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:f=>{const h=f.target.value;if(i(h),h.trim()==="")return;const g=Number(h);if(!Number.isFinite(g))return;const x=Math.min(wo,Math.max(bo,Math.round(g)));o(x)},onBlur:()=>{if(a.trim()===""){i(String(t));return}const f=Number(a);if(!Number.isFinite(f)){i(String(t));return}const h=Math.min(wo,Math.max(bo,Math.round(f)));o(h),i(String(h))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(Hn,{value:t,onValueChange:o,min:bo,max:wo,step:1,"aria-label":"Retention period in days"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days since last activity"})]}),e.jsx(hs,{type:"button",variant:"outline",onClick:m,disabled:d,children:d?"Cleaning up...":"Run cleanup now"})]}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Eligible for deletion right now: ",p]})]})},Fc=()=>{const{isMobile:r}=Et(),s=r&&Hl();return e.jsxs(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(Ih,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Lh,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Ph,{})})]})},Pi=(()=>{const r=kc.filter(n=>n.id!=="sessions"),s=r.find(n=>n.id==="settings"),t=r.filter(n=>n.id!=="settings");return s?[s,...t]:r})(),_h=({isOpen:r,onClose:s})=>{const[t,n]=l.useState("settings"),[o,a]=l.useState(!1),{isMobile:i}=Et();l.useEffect(()=>{r&&(n("settings"),a(!1))},[r]);const c=l.useCallback(y=>{n(y),i&&a(!1)},[i]),d=l.useCallback(()=>{i&&a(!0)},[i]),u=()=>{if(t==="settings")return null;const y=(()=>{switch(t){case"agents":return e.jsx(ph,{});case"commands":return e.jsx(wh,{});case"providers":return e.jsx(kh,{});case"git-identities":return e.jsx(Ah,{});default:return null}})();return i?e.jsx("div",{onClick:d,children:y}):y},p=()=>{switch(t){case"agents":return e.jsx(bh,{});case"commands":return e.jsx(Sh,{});case"providers":return e.jsx(Nh,{});case"git-identities":return e.jsx(Eh,{});case"settings":return e.jsx(Fc,{});default:return null}},m=Pi.find(y=>y.id===t),f=i,h=e.jsxs(Rs,{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(De,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(Ba,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx(Ls,{className:"typography-ui-header",children:"Settings"})]}),m&&e.jsx(lr,{className:"typography-meta text-muted-foreground hidden sm:block",children:m.description})]}),g=e.jsxs("div",{className:I("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:Pi.map(({id:y,label:b,icon:v})=>{const k=t===y,j=v;return e.jsxs("button",{onClick:()=>c(y),className:I("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",k?"text-primary":"text-muted-foreground hover:text-foreground"),"aria-pressed":k,"aria-label":b,children:[e.jsx(j,{className:I("h-5 w-5 sm:h-4 sm:w-4"),weight:"regular"}),e.jsx("span",{className:"hidden sm:inline",children:b})]},y)})}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[t!=="settings"&&(!i||!o)&&e.jsx("div",{className:I("overflow-hidden border-r bg-sidebar",i&&"w-full border-r-0"),style:i?void 0:{width:`${$n}px`,minWidth:`${$n}px`},children:e.jsx(cs,{children:u()})}),(t==="settings"||!i||o)&&e.jsx("div",{className:I("flex-1 overflow-hidden bg-background",i&&"w-full"),children:e.jsx(cs,{children:p()})})]})]}),x=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:y=>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(De,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(Ba,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx("span",{className:"typography-ui-header",children:"Settings"})]}),y]}),children:g}):e.jsx(vs,{open:r,onOpenChange:y=>!y&&s(),children:e.jsx(js,{className:I("flex flex-col gap-0 p-0","h-[88vh] w-[65vw] max-w-[900px]"),children:x})})};function Pc({className:r,...s}){return e.jsx(nr,{"data-slot":"command",className:I("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",r),...s})}function Oh({title:r="Command Palette",description:s="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(vs,{...a,children:[e.jsxs(Rs,{className:"sr-only",children:[e.jsx(Ls,{children:r}),e.jsx(lr,{children:s})]}),e.jsx(js,{className:I("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Pc,{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 Rc({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(ia,{className:"size-4 shrink-0 opacity-50"}),e.jsx(nr.Input,{"data-slot":"command-input",className:I("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 Lc({className:r,children:s,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(Xe,{as:nr.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:I("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 _c({...r}){return e.jsx(nr.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...r})}function yr({className:r,...s}){return e.jsx(nr.Group,{"data-slot":"command-group",className:I("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 Wn({className:r,...s}){return e.jsx(nr.Separator,{"data-slot":"command-separator",className:I("bg-border -mx-1 h-px",r),...s})}function It({className:r,...s}){return e.jsx(nr.Item,{"data-slot":"command-item",className:I("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",r),...s})}function Os({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(rr,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(Yr,{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:I("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",r),...s,children:o.length>0?o.map((a,i)=>e.jsxs(ue.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):s.children})}const Bh=()=>{const{isCommandPaletteOpen:r,setCommandPaletteOpen:s,setHelpDialogOpen:t,setSessionCreateDialogOpen:n,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,toggleSidebar:c}=we(),{createSession:d,setCurrentSession:u,getSessionsByDirectory:p,initializeNewOpenChamberSession:m}=fe(),{currentDirectory:f}=jt(),{agents:h}=St(),{themeMode:g,setThemeMode:x}=ir(),y=()=>{s(!1)},b=async()=>{const W=await d();W&&m(W.id,h),y()},v=W=>{u(W),y()},k=W=>{x(W),y()},j=()=>{t(!0),y()},S=()=>{n(!0),y()},{isMobile:w}=Et(),T=()=>{if(w){const{isSessionSwitcherOpen:W}=we.getState();i(!W)}else c();y()},M=()=>{o("diff"),y()},N=()=>{o("git"),y()},A=()=>{o("terminal"),y()},C=()=>{a(!0),y()},D=()=>{tf(),y()},P=p(f??""),O=l.useMemo(()=>P.slice(0,5),[P]);return e.jsxs(Oh,{open:r,onOpenChange:s,children:[e.jsx(Rc,{placeholder:"Type a command or search..."}),e.jsxs(Lc,{children:[e.jsx(_c,{children:"No results found."}),e.jsxs(yr,{heading:"Actions",children:[e.jsxs(It,{onSelect:T,children:[e.jsx(qn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsx(Os,{children:"Ctrl + L"})]}),e.jsxs(It,{onSelect:b,children:[e.jsx(as,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Os,{children:"Ctrl + N"})]}),e.jsxs(It,{onSelect:S,children:[e.jsx(Yt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Os,{children:"Shift + Ctrl + N"})]}),e.jsxs(It,{onSelect:j,children:[e.jsx(vr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsx(Os,{children:"Ctrl + H"})]}),e.jsxs(It,{onSelect:M,children:[e.jsx(ws,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsx(Os,{children:"Ctrl + E"})]}),e.jsxs(It,{onSelect:N,children:[e.jsx(Yt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsx(Os,{children:"Ctrl + G"})]}),e.jsxs(It,{onSelect:A,children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsx(Os,{children:"Ctrl + T"})]}),e.jsxs(It,{onSelect:C,children:[e.jsx(wr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsx(Os,{children:"Ctrl + ,"})]}),e.jsxs(It,{onSelect:D,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Wn,{}),e.jsxs(yr,{heading:"Theme",children:[e.jsxs(It,{onSelect:()=>k("light"),children:[e.jsx(fu,{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(It,{onSelect:()=>k("dark"),children:[e.jsx(pu,{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(It,{onSelect:()=>k("system"),children:[e.jsx(Rl,{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"})]})]}),O.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Wn,{}),e.jsx(yr,{heading:"Recent Sessions",children:O.map(W=>e.jsxs(It,{onSelect:()=>v(W.id),children:[e.jsx(sa,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:W.title||"Untitled Session"})]},W.id))})]})]})]})},$h=(r,s)=>{const t=r.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Kr,{className:"h-3.5 w-3.5"},`ctrl-${s}`):t==="shift"||t==="⇧"?e.jsx(gu,{className:"h-3.5 w-3.5"},`shift-${s}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(rr,{className:"h-3.5 w-3.5"},`cmd-${s}`):e.jsx("span",{className:"text-xs font-medium",children:r.trim()},`key-${s}`)},zh=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:"+"}),$h(t,n)]},`${t}-${n}`))},Hh=()=>{const{isHelpDialogOpen:r,setHelpDialogOpen:s}=we(),t=[{category:"Navigation & Commands",items:[{keys:["Ctrl + X"],description:"Open Command Palette",icon:rr},{keys:["Ctrl + H"],description:"Show Keyboard Shortcuts (this dialog)",icon:vr},{keys:["Ctrl + L"],description:"Toggle Session Sidebar",icon:qn}]},{category:"Session Management",items:[{keys:["Ctrl + N"],description:"Create New Session",icon:as},{keys:["Shift + Ctrl + N"],description:"Open Worktree Creator",icon:Yt},{keys:["Ctrl + I"],description:"Focus Chat Input",icon:Ll},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:jr}]},{category:"Interface",items:[{keys:["⌘ + /","Ctrl + /"],description:"Cycle Theme (Light → Dark → System)",icon:hu},{keys:["Ctrl + E"],description:"Open Diff Panel",icon:ws},{keys:["Ctrl + G"],description:"Open Git Panel",icon:Yt},{keys:["Ctrl + T"],description:"Open Terminal",icon:Vs},{keys:["Ctrl + ,"],description:"Open Settings",icon:wr}]}];return e.jsx(vs,{open:r,onOpenChange:s,children:e.jsxs(js,{className:"max-w-2xl",children:[e.jsxs(Rs,{children:[e.jsxs(Ls,{className:"flex items-center gap-2",children:[e.jsx(wr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(lr,{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:zh(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(vr,{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"})]})]})]})})]})})},vo=new Set,jo=new Set,So=new Set,Qs={onDeleteRequest(r){return vo.add(r),()=>{vo.delete(r)}},requestDelete(r){r.sessions.length&&vo.forEach(s=>s(r))},onCreateRequest(r){return jo.add(r),()=>{jo.delete(r)}},requestCreate(r){const s=r??{};jo.forEach(t=>t(s))},onDirectoryRequest(r){return So.add(r),()=>{So.delete(r)}},requestDirectoryDialog(){So.forEach(r=>r())}},Wh=".openchamber",Ri="oc.sessions.groupCollapse",Li="oc.sessions.expandedParents",_i=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(",","")},Ms=r=>{if(!r)return null;const s=r.replace(/\\/g,"/").replace(/\/+$/,"");return s.length===0?"/":s},Uh=(r,s)=>{const t=Ms(r),n=Array.from(s.values())[0];if(n?.projectDirectory)return Ms(n.projectDirectory);if(!t)return null;const o=`/${Wh}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},Vo=({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),x=l.useRef(new Set),y=l.useMemo(()=>ts(),[]),[b,v]=l.useState(!1),[k,j]=l.useState(new Set),[S,w]=l.useState(null),[T,M]=l.useState(new Set),[N,A]=l.useState(null),C=jt(_=>_.currentDirectory),D=jt(_=>_.homeDirectory),P=jt(_=>_.setDirectory),O=St(_=>_.agents),W=fe(_=>_.getSessionsByDirectory),R=fe(_=>_.currentSessionId),V=fe(_=>_.setCurrentSession),ae=fe(_=>_.updateSessionTitle),K=fe(_=>_.shareSession),B=fe(_=>_.unshareSession),L=fe(_=>_.sessionMemoryState),ne=fe(_=>_.sessionActivityPhase),Se=fe(_=>_.worktreeMetadata),Ne=fe(_=>_.availableWorktrees),de=fe(_=>_.createSession),ge=fe(_=>_.initializeNewOpenChamberSession),ve=fe(_=>_.setSessionDirectory),[Ae,Te]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const _=y.getItem(Ri);if(_){const ee=JSON.parse(_);Array.isArray(ee)&&j(new Set(ee.filter(me=>typeof me=="string")))}const se=y.getItem(Li);if(se){const ee=JSON.parse(se);Array.isArray(ee)&&f(new Set(ee.filter(me=>typeof me=="string")))}}catch{}},[y]),l.useEffect(()=>{typeof window>"u"||Te(typeof window.opencodeDesktop<"u")},[]);const Pe=W(C),Re=l.useMemo(()=>[...Pe].sort((_,se)=>(se.time?.created||0)-(_.time?.created||0)),[Pe]);l.useEffect(()=>{if(!C){w(null);return}let _=!1;return ha(C).then(se=>{_||w(se)}).catch(()=>{_||w(null)}),()=>{_=!0}},[C]);const ce=l.useMemo(()=>new Map(Re.map(_=>[_.id,_])),[Re]),Ie=l.useMemo(()=>{const _=new Map;return Re.forEach(se=>{const ee=se.parentID;ee&&_.set(se.id,ee)}),_},[Re]),ie=l.useMemo(()=>{const _=new Map;return Re.forEach(se=>{const ee=se.parentID;if(!ee)return;const me=_.get(ee)??[];me.push(se),_.set(ee,me)}),_.forEach(se=>se.sort((ee,me)=>(me.time?.created||0)-(ee.time?.created||0))),_},[Re]);l.useEffect(()=>{R&&f(_=>{const se=new Set(_);let ee=Ie.get(R)||null,me=!1;for(;ee;)se.has(ee)||(se.add(ee),me=!0),ee=Ie.get(ee)||null;return me?se:_})},[R,Ie]);const Ce=l.useMemo(()=>Uh(C,Se),[C,Se]);l.useEffect(()=>{const _=new Set;Re.forEach(se=>{const ee=Ms(se.directory??null);ee&&_.add(ee)}),Ce&&_.add(Ce),_.forEach(se=>{const ee=h.get(se);ee&&ee!=="unknown"||x.current.has(se)||(x.current.add(se),ke.listLocalDirectory(se).then(()=>{g(me=>{const Q=new Map(me);return Q.get(se)==="exists"?me:(Q.set(se,"exists"),Q)})}).catch(()=>{g(me=>{const Q=new Map(me);return Q.get(se)==="missing"?me:(Q.set(se,"missing"),Q)})}).finally(()=>{x.current.delete(se)}))})},[Re,Ce,h]),l.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const qe=l.useMemo(()=>ro(C,D),[C,D]),J=l.useMemo(()=>rs(C,D),[C,D]),E=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."})]}),re=l.useCallback((_,se)=>{if(!se){if(!t&&_===R){s?.(_);return}V(_),s?.(_)}},[t,R,s,V]),q=l.useCallback(async()=>{o&&i.trim()&&(await ae(o,i.trim()),a(null),c(""))},[o,i,ae]),F=l.useCallback(()=>{a(null),c("")},[]),$=l.useCallback(async _=>{const se=await K(_.id);se&&se.share?.url?xe.success("Session shared",{description:"You can copy the link from the menu."}):xe.error("Unable to share session")},[K]),U=l.useCallback((_,se)=>{navigator.clipboard.writeText(_).then(()=>{u(se),p.current&&clearTimeout(p.current),p.current=window.setTimeout(()=>{u(null),p.current=null},2e3)}).catch(()=>{xe.error("Failed to copy URL")})},[]),H=l.useCallback(async _=>{await B(_)?xe.success("Session unshared"):xe.error("Unable to unshare session")},[B]),X=l.useCallback(_=>{const se=[],ee=me=>{(ie.get(me)??[]).forEach(oe=>{se.push(oe),ee(oe.id)})};return ee(_),se},[ie]),Y=fe(_=>_.deleteSession),Ee=fe(_=>_.deleteSessions),Be=l.useCallback(async _=>{const se=X(_.id);if(se.length===0)await Y(_.id)?xe.success("Session deleted"):xe.error("Failed to delete session");else{const ee=[_.id,...se.map(oe=>oe.id)],{deletedIds:me,failedIds:Q}=await Ee(ee);me.length>0&&xe.success(`Deleted ${me.length} session${me.length===1?"":"s"}`),Q.length>0&&xe.error(`Failed to delete ${Q.length} session${Q.length===1?"":"s"}`)}},[X,Y,Ee]),ct=l.useCallback(async _=>{if(!_){xe.error("No directory available for session creation");return}if(!b)try{v(!0);const se=await de(void 0,_);if(!se){xe.error("Failed to create session");return}ge(se.id,O),ve(se.id,_)}catch(se){const ee=se instanceof Error?se.message:"Failed to create session";xe.error(ee)}finally{v(!1)}},[de,ge,ve,O,b]),ot=l.useCallback(()=>{Qs.requestCreate({worktreeMode:"create"})},[]),Je=l.useCallback(()=>{Ae&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(_=>{_.success&&_.path?P(_.path,{showOverlay:!0}):_.error&&_.error!=="Directory selection cancelled"&&xe.error("Failed to select directory",{description:_.error})}).catch(_=>{console.error("Desktop: Error selecting directory:",_),xe.error("Failed to select directory")}):Qs.requestDirectoryDialog()},[Ae,P]),it=l.useCallback(_=>{f(se=>{const ee=new Set(se);ee.has(_)?ee.delete(_):ee.add(_);try{y.setItem(Li,JSON.stringify(Array.from(ee)))}catch{}return ee})},[y]),dt=l.useCallback(_=>{const se=ie.get(_.id)??[];return{session:_,children:se.map(ee=>dt(ee))}},[ie]),at=l.useMemo(()=>{const _=new Map,se=Ms(Ce??null),ee=new Map,me=new Set;Ne.forEach(le=>{if(le.path){const Me=Ms(le.path)??le.path;me.add(Me),ee.set(Me,le)}});const Q=le=>{const Me=Ms(le.directory??null),$e=Se.get(le.id),bt=(($e?.path?me.has(Ms($e.path)??$e.path):!1)?$e:null)??(Me?ee.get(Me)??null:null),Dt=!bt&&(Me&&se?Me===se:!Me&&!!se),Nt=Dt?"main":bt?.path??Me??le.id,mt=bt?.path??Me??se??null;if(!_.has(Nt)){const wt=Dt?"Main workspace":bt?.label||bt?.branch||ro(mt||"",D)||"Worktree",je=bt?.relativePath?rs(bt.relativePath,D):mt?rs(mt,D):null;_.set(Nt,{id:Nt,label:wt,description:je,isMain:Dt,worktree:bt,directory:mt,sessions:[]})}return _.get(Nt)};return Re.filter(le=>{const Me=le.parentID;return Me?!ce.has(Me):!0}).forEach(le=>{const Me=Q(le),$e=dt(le);Me.sessions.push($e)}),_.has("main")||_.set("main",{id:"main",label:"Main workspace",description:se?rs(se,D):null,isMain:!0,worktree:null,directory:se,sessions:[]}),ee.forEach((le,Me)=>{const $e=le.path;_.has($e)||_.set($e,{id:$e,label:le.label||le.branch||ro(Me,D)||"Worktree",description:le.relativePath?rs(le.relativePath,D):rs(Me,D),isMain:!1,worktree:le,directory:Me,sessions:[]})}),_.forEach(le=>{le.sessions.sort((Me,$e)=>($e.session.time?.created||0)-(Me.session.time?.created||0))}),Array.from(_.values()).sort((le,Me)=>le.isMain!==Me.isMain?le.isMain?-1:1:(le.label||"").localeCompare(Me.label||""))},[Re,Se,Ne,Ce,D,dt,ce]),pt=l.useCallback(_=>{j(se=>{const ee=new Set(se);ee.has(_)?ee.delete(_):ee.add(_);try{y.setItem(Ri,JSON.stringify(Array.from(ee)))}catch{}return ee})},[y]),ut=l.useCallback(_=>{M(se=>{const ee=new Set(se);return ee.has(_)?ee.delete(_):ee.add(_),ee})},[]),pe=l.useCallback((_,se=0,ee)=>{const me=_.session,Q=Ms(me.directory??null)??Ms(ee??null),le=(Q?h.get(Q):null)==="missing",Me=L.get(me.id),$e=R===me.id,kt=me.title||"Untitled Session",bt=_.children.length>0,Dt=m.has(me.id),Nt=me.summary?.additions,mt=me.summary?.deletions,wt=typeof Nt=="number"||typeof mt=="number";if(o===me.id)return e.jsx("div",{className:I("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",se>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(),q()},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"&&F()}}),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:F,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(us,{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:[bt?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Dt?e.jsx(yt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:_i(me.time?.created||Date.now())}),me.share?e.jsx(to,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,wt&&((Nt??0)!==0||(mt??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,Nt??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,mt??0)]})]}):null,bt?e.jsxs("span",{className:"truncate",children:[_.children.length," ",_.children.length===1?"task":"tasks"]}):null]})]})},me.id);const je=ne?.get(me.id)??"idle",ze=je==="busy"||je==="cooldown",Ge=Me&&Me.isZombie?e.jsx(Ro,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(l.Fragment,{children:[e.jsx("div",{className:I("group relative flex items-center rounded-md px-1.5 py-1",$e?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",le?"opacity-75":"",se>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:le,onClick:()=>re(me.id,le),className:I("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:I("truncate typography-ui-label font-normal text-foreground",ze&&"animate-pulse [animation-duration:1.8s]"),children:kt})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[bt?e.jsx("span",{role:"button",tabIndex:0,onClick:Le=>{Le.stopPropagation(),it(me.id)},onKeyDown:Le=>{(Le.key==="Enter"||Le.key===" ")&&(Le.preventDefault(),Le.stopPropagation(),it(me.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":Dt?"Collapse subsessions":"Expand subsessions",children:Dt?e.jsx(yt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:_i(me.time?.created||Date.now())}),me.share?e.jsx(to,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,wt&&((Nt??0)!==0||(mt??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,Nt??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,mt??0)]})]}):null,bt?e.jsxs("span",{className:"truncate",children:[_.children.length," ",_.children.length===1?"task":"tasks"]}):null,le?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Ro,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[Ge,e.jsxs(Xt,{children:[e.jsx(Jt,{asChild:!0,children:e.jsx("button",{type:"button",className:I("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",r?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:Le=>Le.stopPropagation(),onKeyDown:Le=>Le.stopPropagation(),children:e.jsx(Yn,{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(me.id),c(kt)},className:"[&>svg]:mr-1",children:[e.jsx(Ds,{className:"mr-1 h-4 w-4"}),"Rename"]}),me.share?e.jsxs(e.Fragment,{children:[e.jsx(gt,{onClick:()=>{me.share?.url&&U(me.share.url,me.id)},className:"[&>svg]:mr-1",children:d===me.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(_s,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(gt,{onClick:()=>H(me.id),className:"[&>svg]:mr-1",children:[e.jsx(xu,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(gt,{onClick:()=>$(me),className:"[&>svg]:mr-1",children:[e.jsx(to,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(gt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Be(me),children:[e.jsx(Gs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),bt&&Dt?_.children.map(Le=>pe(Le,se+1,Q??ee)):null]},me.id)},[h,L,ne,R,m,o,i,q,F,it,re,$,U,H,Be,d,r]);return e.jsxs("div",{className:I("flex h-full flex-col text-foreground overflow-x-hidden",r?"":Ae?"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:Je,className:I("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",!Ae&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:J||"/",children:[e.jsx("span",{className:I("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!Ae&&"bg-sidebar/60"),children:e.jsx(ss,{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:qe||"/"})})]}),S?e.jsx("button",{type:"button",onClick:ot,className:I("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",!Ae&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",children:e.jsx(yu,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}):null]})}),e.jsx(Xe,{outerClassName:"flex-1 min-h-0",className:I("space-y-1 pb-1 pl-2.5 pr-1",""),children:at.length===0?E:n&&at.length===1&&at[0].isMain?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:at[0].sessions.length===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."}):at[0].sessions.map(_=>pe(_,0,at[0].directory))}):at.map(_=>e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>pt(_.id),className:I("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b",!Ae&&"bg-sidebar"),style:{borderColor:N===_.id?"var(--color-border)":k.has(_.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>A(_.id),onMouseLeave:()=>A(null),"aria-label":k.has(_.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:_.label}),!n&&e.jsx("span",{role:"button",tabIndex:0,"aria-disabled":b,className:I("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",b&&"opacity-40 cursor-default"),"aria-label":"Create session in this group",onClick:se=>{b||(se.stopPropagation(),ct(_.directory))},onKeyDown:se=>{b||(se.key==="Enter"||se.key===" ")&&(se.stopPropagation(),ct(_.directory))},children:e.jsx(as,{className:"h-4.5 w-4.5"})})]})}),k.has(_.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const se=T.has(_.id),ee=7,me=_.sessions.length,Q=se?_.sessions:_.sessions.slice(0,ee),oe=me-Q.length;return e.jsxs(e.Fragment,{children:[Q.map(le=>pe(le,0,_.directory)),me===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,oe>0&&!se?e.jsxs("button",{type:"button",onClick:()=>ut(_.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 ",oe," more ",oe===1?"session":"sessions"]}):null,se&&me>ee?e.jsx("button",{type:"button",onClick:()=>ut(_.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]})})()})]},_.id))})]})},Oc=()=>{const[r,s]=ue.useState(!1);ue.useEffect(()=>{s(is())},[]);const t=ue.useCallback(async a=>r?await Pm(a):{success:!0,path:a},[r]),n=ue.useCallback(async a=>r?await Rm(a):{success:!0},[r]),o=ue.useCallback(async a=>r?await Lm(a):{success:!0},[r]);return{isDesktop:r,requestAccess:t,startAccessing:n,stopAccessing:o}},Oi=({currentPath:r,onSelectPath:s,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:p=!1})=>{const m=l.useMemo(()=>is(),[]),[f,h]=l.useState([]),[g,x]=l.useState(new Set),[y,b]=l.useState(!0),[v,k]=l.useState(!1),[j,S]=l.useState(""),[w,T]=l.useState(new Set),[M,N]=l.useState(null),[A,C]=l.useState(""),[D,P]=l.useState(!0),O=l.useRef(null),{requestAccess:W,startAccessing:R,isDesktop:V}=Oc(),ae=l.useRef(c),K=l.useCallback(E=>{if(!E)return E;if(E==="/"||E.length===0)return"/";let re=E;for(;re.length>1&&re.endsWith("/");)re=re.slice(0,-1);return re.length===0?"/":re},[]),B=l.useMemo(()=>{if(!j)return null;const E=j.replace(/\\/g,"/");return K(E)},[j,K]),L=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const E=d.replace(/\\/g,"/"),re=K(E);if(re&&re!=="/")return re}return B&&B!=="/"?B:null},[d,B,K]),ne=l.useMemo(()=>typeof u=="boolean"?!!(u&&L):!!L,[u,L]);l.useEffect(()=>{ne||(b(!0),h([]))},[ne]);const Se=l.useCallback(E=>{if(!E||!ne||!L)return!1;const re=E.replace(/\\/g,"/"),q=K(re)??re;if(q===L)return!0;const F=`${L}/`;return q.startsWith(F)},[ne,L,K]),Ne=async E=>{if(ne){if(a==="deferred"){s(E);return}if(V){const re=await W(E);re.success&&re.path?(await R(re.path),s(re.path)):(console.error("Failed to get directory access:",re.error),s(E))}else s(E)}};l.useEffect(()=>{let E=!1;const re=$=>{if(!$)return!1;const U=K($.replace(/\\/g,"/"));return!U||U==="/"?!1:(S(typeof U=="string"?U:$.replace(/\\/g,"/")),!0)};return(d?re(d):!1)||(async()=>{try{const $=await ke.getFilesystemHome();if(!E&&re($))return}catch($){console.warn("Failed to resolve filesystem home directory:",$)}try{const $=await ke.getSystemInfo();if(!E&&re($?.homeDirectory))return}catch($){console.warn("Failed to resolve home directory from system info:",$)}})(),()=>{E=!0}},[d,K]),l.useEffect(()=>{let E=!1;const re=U=>{if(E)return;const H=U.filter(X=>typeof X=="string"&&X.length>0).map(X=>{const Y=X.replace(/\\/g,"/");return K(Y)??Y});T(new Set(H))},q=()=>{try{const U=localStorage.getItem("pinnedDirectories");if(!U)return;const H=JSON.parse(U);Array.isArray(H)&&re(H)}catch(U){console.warn("Failed to load pinned directories from local storage:",U)}},F=async()=>{try{let U=[];if(m){const H=await Vl();U=Array.isArray(H?.pinnedDirectories)?H.pinnedDirectories:[]}else{const H=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(H.ok){const X=await H.json();U=Array.isArray(X?.pinnedDirectories)?X.pinnedDirectories:[]}}if(E)return;re(U)}catch(U){console.warn("Failed to load pinned directories:",U)}};q();const $=U=>{const H=U.detail;H&&Array.isArray(H.pinnedDirectories)&&re(H.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",$),F(),()=>{E=!0,window.removeEventListener("openchamber:settings-synced",$)}},[m,K]);const de=l.useRef(!0);l.useEffect(()=>{if(de.current){de.current=!1;return}const E={pinnedDirectories:Array.from(w)};As(E)},[w]),l.useEffect(()=>{L&&T(E=>{const re=Array.from(E).map(q=>K(q.replace(/\\/g,"/"))??q).filter(q=>Se(q));return new Set(re)})},[L,Se,K]),l.useEffect(()=>{ae.current!==c&&(ae.current=c,x(new Set))},[c]);const ge=E=>{T(re=>{if(!Se(E))return re;const q=K(E.replace(/\\/g,"/"))??E.replace(/\\/g,"/"),F=new Set(re);return F.has(q)?F.delete(q):F.add(q),F})},ve=l.useMemo(()=>Array.from(w).map(E=>K(E.replace(/\\/g,"/"))??E).filter(E=>Se(E)).map(E=>({path:E,name:E.split("/").pop()||E})).sort((E,re)=>E.name.localeCompare(re.name)),[w,Se,K]),Ae=l.useCallback(async E=>{const re=H=>c||!H.startsWith("."),q=L;if(!ne||!q)return[];const F=E&&E.length>0?E:q,$=F?F.replace(/\\/g,"/"):null,U=$?K($)??$:null;if(U){const H=`${q}/`;if(!(U===q||U.startsWith(H)))return[]}try{return(await ke.listLocalDirectory(E)).filter(X=>{if(!X.isDirectory||!re(X.name))return!1;const Y=X.path.replace(/\\/g,"/"),Ee=K(Y)??Y,Be=Ee===q?q:`${q}/`;return Ee===q||Ee.startsWith(Be)}).map(X=>({name:X.name,path:X.path.replace(/\\/g,"/"),isDirectory:!0})).sort((X,Y)=>X.name.localeCompare(Y.name))}catch{try{const X=await ke.getApiClient().file.list({query:{path:".",directory:E}});return X.data?X.data.filter(Y=>{if(Y.type!=="directory"||!Y.name||!re(Y.name))return!1;const Ee=String(Y.absolute||Y.path||Y.name).replace(/\\/g,"/"),Be=K(Ee)??Ee,ct=Be===q?q:`${q}/`;return Be===q||Be.startsWith(ct)}).map(Y=>({name:Y.name||"",path:String(Y.absolute||Y.path||Y.name).replace(/\\/g,"/"),isDirectory:!0})).filter(Y=>Y.name!=="").sort((Y,Ee)=>Y.name.localeCompare(Ee.name)):[]}catch{return[]}}},[c,L,K,ne]),Te=l.useCallback(async()=>{if(!ne||!L){b(!0),h([]);return}b(!0);try{const E=await Ae(L);h(E)}catch{}finally{b(!1)}},[ne,L,Ae]);l.useEffect(()=>{ne&&(n==="inline"||v)&&Te()},[n,v,ne,Te]);const Pe=async E=>{if(!ne)return;const re=g.has(E.path),q=new Set(g);if(re){q.delete(E.path),x(q);return}q.add(E.path),x(q);const F=await Ae(E.path),$=U=>U.map(H=>H.path===E.path?{...H,children:F}:H.children?{...H,children:$(H.children)}:H);h(U=>$(U))};l.useEffect(()=>{M&&O.current&&(O.current.focus(),O.current.select())},[M]);const Re=(E,re=[])=>{const q="new_directory",F=re.map(X=>X.name);if(!F.includes(q))return q;let $=1;const U=new RegExp(`^${q}(\\d+)$`);for(const X of F){const Y=X.match(U);if(Y){const Ee=parseInt(Y[1],10);Ee>$&&($=Ee)}}let H=2;for(;F.includes(`${q}${H}`);)H++;return`${q}${Math.max(H,$+1)}`},ce=async E=>{if(ne){if(g.has(E.path)){const re=Re(E.path,E.children);C(re)}else{const re=new Set(g);if(re.add(E.path),x(re),E.children){const q=Re(E.path,E.children);C(q)}else{const q=await Ae(E.path),F=U=>U.map(H=>H.path===E.path?{...H,children:q}:H.children?{...H,children:F(H.children)}:H);h(U=>F(U));const $=Re(E.path,q);C($)}}N(E.path)}},Ie=async()=>{if(!M||!ne)return;const E=A.trim()||"new_directory",re=`${M}/${E}`;try{await ke.createDirectory(re);const q=await Ae(M),F=$=>$.map(U=>U.path===M?{...U,children:q}:U.children?{...U,children:F(U.children)}:U);h($=>F($)),N(null),C("")}catch(q){console.error("Failed to create directory:",q)}},ie=()=>{N(null),C("")},Ce=(E,re=0)=>{const q=g.has(E.path),F=E.isDirectory,$=w.has(E.path),U=r===E.path,H=n==="inline",X=e.jsxs(e.Fragment,{children:[F&&e.jsx("button",{onClick:Y=>{Y.stopPropagation(),Pe(E)},className:"p-0.5 hover:bg-accent rounded",children:q?e.jsx(yt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}),!F&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:Y=>{Y.stopPropagation(),Ne(E.path),n==="dropdown"&&a==="immediate"&&k(!1)},onDoubleClick:Y=>{Y.stopPropagation(),i&&i(E.path)},className:I("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",H&&U?"text-primary":"text-foreground"),children:[q?e.jsx(ss,{className:I("h-3.5 w-3.5 text-muted-foreground",H&&U&&"text-primary")}):e.jsx(ss,{className:I("h-3.5 w-3.5 text-muted-foreground",H&&U&&"text-primary")}),e.jsx("span",{className:I("typography-ui-label font-medium truncate",H&&U?"text-primary":"text-foreground"),children:E.name})]}),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),ce(E)},className:I("p-1 hover:bg-accent rounded transition-opacity",p?"opacity-70":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(as,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),ge(E.path)},className:I("p-1 hover:bg-accent rounded transition-opacity",p?"opacity-70":"opacity-0 group-hover:opacity-100"),title:$?"Unpin directory":"Pin directory",children:$?e.jsx(so,{className:"h-3 w-3 text-primary"}):e.jsx(bu,{className:"h-3 w-3 text-muted-foreground"})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:I("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",U?"text-primary":"text-foreground"),style:{paddingLeft:`${re*12+8}px`},children:X}),q&&e.jsxs(e.Fragment,{children:[M===E.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(re+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ft,{ref:O,value:A,onChange:Y=>C(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"?(Y.preventDefault(),Y.stopPropagation(),Ie()):Y.key==="Escape"&&(Y.preventDefault(),Y.stopPropagation(),ie())},onBlur:Ie,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),Ie()},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:Y=>{Y.preventDefault(),Y.stopPropagation(),ie()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(us,{className:"h-3 w-3 text-muted-foreground"})})]}),E.children&&E.children.map(Y=>Ce(Y,re+1))]})]},E.path):e.jsxs("div",{children:[e.jsxs(gt,{className:I("flex items-center gap-1 cursor-pointer group",r===E.path&&"bg-accent"),style:{paddingLeft:`${re*12+8}px`},onSelect:Y=>{Y.preventDefault()},children:[F&&e.jsx("button",{onClick:Y=>{Y.stopPropagation(),Pe(E)},className:"p-0.5 hover:bg-accent rounded",children:q?e.jsx(yt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}),!F&&e.jsx("div",{className:"w-4"}),X]}),q&&e.jsxs("div",{children:[M===E.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(re+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ft,{ref:O,value:A,onChange:Y=>C(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"?(Y.preventDefault(),Y.stopPropagation(),Ie()):Y.key==="Escape"&&(Y.preventDefault(),Y.stopPropagation(),ie())},onBlur:Ie,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:Y=>{Y.preventDefault(),Y.stopPropagation(),Ie()},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:Y=>{Y.preventDefault(),Y.stopPropagation(),ie()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(us,{className:"h-3 w-3 text-muted-foreground"})})]}),E.children&&E.children.map(Y=>Ce(Y,re+1))]})]},E.path)},qe=(E,re)=>{if(n==="inline"){const q=r===re;return e.jsxs("div",{className:I("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>Ne(re),onDoubleClick:F=>{F.stopPropagation(),i&&i(re)},className:I("flex flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",q?"text-primary":"text-foreground"),children:[e.jsx(ss,{className:I("h-3.5 w-3.5 text-muted-foreground",q&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:I("typography-ui-label font-medium truncate",q?"text-primary":"text-foreground"),children:E}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:rs(re,j)})]})]}),e.jsx("button",{onClick:()=>ge(re),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(so,{className:"h-3 w-3 text-primary"})})]},re)}return e.jsxs(gt,{onSelect:q=>{q.preventDefault(),Ne(re),a==="immediate"&&k(!1)},className:I("flex items-start gap-2 cursor-pointer group py-2",r===re&&"bg-accent"),children:[e.jsx(ss,{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:E}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:rs(re,j)})]}),e.jsx("button",{onClick:q=>{q.stopPropagation(),q.preventDefault(),ge(re)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(so,{className:"h-3 w-3 text-primary"})})]},re)},J=e.jsx(e.Fragment,{children:ne?e.jsxs(e.Fragment,{children:[ve.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>P(E=>!E),className:"flex w-full items-center gap-1.5 px-2 py-1.5 typography-meta font-semibold text-muted-foreground hover:bg-accent/30 rounded transition-colors",children:[D?e.jsx(yt,{className:"h-3.5 w-3.5"}):e.jsx(ns,{className:"h-3.5 w-3.5"}),e.jsx($s,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/70",children:ve.length})]}),D&&ve.map(({name:E,path:re})=>qe(E,re)),n==="dropdown"&&e.jsx(Ur,{}),n==="inline"&&D&&e.jsx("div",{className:"mx-2 my-1.5 border-t border-border/30"})]}),e.jsxs("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground flex items-center gap-1.5",children:[e.jsx(ss,{className:"h-3.5 w-3.5"}),"Browse"]}),y?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):f.map(E=>Ce(E)),!y&&f.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:I("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:v,onOpenChange:k,children:[e.jsx(Jt,{asChild:!0,children:e.jsxs(De,{variant:"ghost",className:I("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(ss,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:r,children:rs(r,j)})]}),e.jsx(yt,{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})})]})},Bi="directoryTreeShowHidden",Vh=({open:r,onOpenChange:s})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=jt(),[i,c]=l.useState(null),[d,u]=l.useState(""),[p,m]=l.useState(!1),[f,h]=l.useState(!1),[g,x]=l.useState(()=>{if(typeof window>"u")return!1;try{const B=window.localStorage.getItem(Bi);if(B==="true")return!0;if(B==="false")return!1}catch{}return!1}),{isDesktop:y,requestAccess:b,startAccessing:v}=Oc(),{isMobile:k}=Et(),j=l.useCallback(B=>B?rs(B,n):"",[n]);l.useEffect(()=>{if(r){m(!1),h(!1);const B=t||n||"";c(B),u(j(B))}},[r,t,n,j]),l.useEffect(()=>{!r||p||i||n&&a&&(c(n),m(!0),u("~"))},[r,p,i,n,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Bi,g?"true":"false")}catch{}},[g]);const S=l.useCallback(()=>{s(!1)},[s]),w=l.useCallback(async B=>{if(!(!B||f)){if(B===t){S();return}h(!0);try{let L=B;if(y){const ne=await b(B);if(!ne.success){xe.error("Unable to access directory",{description:ne.error||"Desktop denied directory access."});return}L=ne.path??B;const Se=await v(L);if(!Se.success){xe.error("Failed to open directory",{description:Se.error||"Desktop could not grant file access."});return}}o(L),S()}catch(L){xe.error("Failed to select directory",{description:L instanceof Error?L.message:"Unknown error occurred."})}finally{h(!1)}}},[t,S,y,b,o,v,f]),T=l.useCallback(async()=>{const B=d.trim()||i;B&&await w(B)},[w,d,i]),M=l.useCallback(B=>{c(B),m(!0),u(j(B))},[j]),N=l.useCallback(async B=>{c(B),m(!0),u(j(B)),await w(B)},[w,j]),A=l.useCallback(B=>{const L=B.target.value;if(u(L),m(!0),L.startsWith("/")||L.startsWith("~")){const ne=L.startsWith("~")&&n?L.replace(/^~/,n):L;c(ne)}},[n]),C=l.useCallback(B=>{B.key==="Enter"&&(B.preventDefault(),T())},[T]),D=l.useCallback(()=>{x(B=>!B)},[]),P=e.jsxs(Rs,{className:"flex-shrink-0 px-4 pb-2 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-3 sm:pt-0",children:[e.jsx(Ls,{children:"Select project directory"}),e.jsx(lr,{className:"hidden sm:block",children:"Choose the working directory for sessions and OpenCode operations."})]}),O=e.jsx(Ft,{value:d,onChange:A,onKeyDown:C,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),W=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 sm:p-2 sm:flex-none",children:e.jsx(Oi,{variant:"inline",currentPath:i??t,onSelectPath:M,onDoubleClickPath:N,className:"h-full sm:min-h-[280px] sm:h-[380px]",selectionBehavior:"deferred",showHidden:g,rootDirectory:a?n:null,isRootReady:a})}),R=e.jsxs("button",{type:"button",onClick:D,className:"flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground",children:[g?e.jsx(la,{className:"h-4 w-4 text-primary"}):e.jsx(ca,{className:"h-4 w-4"}),"Show hidden"]}),V=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:O}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:R}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 p-1.5 overflow-hidden",children:e.jsx(Oi,{variant:"inline",currentPath:i??t,onSelectPath:M,onDoubleClickPath:N,className:"h-full",selectionBehavior:"deferred",showHidden:g,rootDirectory:a?n:null,isRootReady:a,alwaysShowActions:!0})})]}),ae=e.jsxs(Xe,{outerClassName:"flex-1 min-h-0 overflow-hidden",className:"directory-dialog-body sm:px-0 sm:pb-0 flex flex-col gap-3",children:[O,e.jsx("div",{className:"flex items-center justify-end",children:R}),W]}),K=()=>e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:S,disabled:f,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(De,{onClick:T,disabled:f||!p||!i&&!d.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:f?"Applying...":"Open Directory"})]});return k?e.jsx(Kt,{open:r,onClose:()=>s(!1),title:"Select project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:e.jsx("div",{className:"flex flex-row gap-2",children:K()}),children:V}):e.jsx(vs,{open:r,onOpenChange:s,children:e.jsxs(js,{className:I("flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6"),onOpenAutoFocus:B=>{B.preventDefault()},children:[P,ae,e.jsx(Vr,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-3",children:K()})]})})},Un=".openchamber",on=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,Gh=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Bc=r=>r.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),$c=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},an=(r,s)=>{const t=$c(r),n=Bc(s),o=!t||t==="/"?`/${Un}`:`${t}/${Un}`;return n?`${o}/${n}`:o},qh=()=>{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,x]=l.useState(null),[y,b]=l.useState(!1),v=l.useRef(new Set),[k,j]=l.useState(null),[S,w]=l.useState([]),[T,M]=l.useState(!1),[N,A]=l.useState(!1),{sessions:C,createSession:D,deleteSession:P,deleteSessions:O,loadSessions:W,initializeNewOpenChamberSession:R,setWorktreeMetadata:V,setSessionDirectory:ae,getWorktreeMetadata:K,isLoading:B}=fe(),{currentDirectory:L,homeDirectory:ne,hasPersistedDirectory:Se,isHomeReady:Ne}=jt(),{agents:de}=St(),{isSessionCreateDialogOpen:ge,setSessionCreateDialogOpen:ve}=we(),{isMobile:Ae,isTablet:Te,hasTouchInput:Pe}=Et(),Re=Ae||Te||Pe,ce=l.useMemo(()=>$c(L),[L]),Ie=l.useMemo(()=>Gh(o),[o]),ie=l.useMemo(()=>Bc(Ie),[Ie]),Ce=l.useMemo(()=>!ce||!ie?"":an(ce,ie),[ce,ie]),qe=g===!0,J=l.useMemo(()=>(k?.worktree?.status?.isDirty??!1)||S.some(pe=>pe.metadata.status?.isDirty),[k?.worktree?.status?.isDirty,S]),E=l.useMemo(()=>{const pe=k?.worktree;return pe&&typeof pe.branch=="string"&&pe.branch.trim().length>0?!0:S.length>0&&S.every(({metadata:_})=>typeof _.branch=="string"&&_.branch.trim().length>0)},[k?.worktree,S]),re=k?.mode==="worktree",q=re,F=N||!re||!E;l.useEffect(()=>{ce&&(v.current.has(ce)||yf(ce).then(()=>v.current.add(ce)).catch(pe=>{console.warn("Failed to ensure .openchamber directory is ignored:",pe),v.current.delete(ce)}))},[ce]),l.useEffect(()=>{W()},[W,L]),l.useEffect(()=>{!t&&Ne&&!Se&&(s(!0),n(!0))},[Se,t,Ne]),l.useEffect(()=>{if(!ge){a(""),c([]),m(null),u(!1),h(!1),x(null),b(!1);return}if(!ce){c([]),x(null),h(!1);return}let pe=!1;return u(!0),h(!0),m(null),(async()=>{try{const _=await ha(ce);if(pe)return;if(x(_),!_)c([]),m(null);else{const se=await Fn(ce);if(pe)return;const ee=se.map(le=>Pn(ce,le)),Q=`${an(ce,"")}/`,oe=ee.filter(le=>le.path.startsWith(Q));c(oe)}}catch(_){if(pe)return;const se=_ instanceof Error?_.message:"Failed to load worktrees";m(se)}finally{pe||(u(!1),h(!1))}})(),()=>{pe=!0}},[ge,ce]);const $=l.useCallback(pe=>{j({sessions:pe.sessions,dateLabel:pe.dateLabel,mode:pe.mode??"session",worktree:pe.worktree??null})},[]),U=l.useCallback(()=>{j(null),w([]),M(!1),A(!1)},[]);l.useEffect(()=>Qs.onDeleteRequest(pe=>{$(pe)}),[$]),l.useEffect(()=>Qs.onDirectoryRequest(()=>{s(!0)}),[]),l.useEffect(()=>Qs.onCreateRequest(()=>{a(""),ve(!0)}),[ve]),l.useEffect(()=>{if(!k){w([]),M(!1);return}const pe=k.sessions.map(se=>{const ee=K(se.id);return ee?{session:se,metadata:ee}:null}).filter(se=>!!se);if(w(pe),M(!1),pe.length===0)return;let _=!1;return(async()=>{const se=await Promise.all(pe.map(async({metadata:ee})=>{if(ee.status&&typeof ee.status.isDirty=="boolean")return ee.status;try{return await yn(ee.path)}catch{return ee.status}})).catch(ee=>(console.warn("Failed to inspect worktree status before deletion:",ee),pe.map(({metadata:me})=>me.status)));_||!Array.isArray(se)||w(ee=>ee.map((me,Q)=>({session:me.session,metadata:{...me.metadata,status:se[Q]??me.metadata.status}})))})(),()=>{_=!0}},[k,K]),l.useEffect(()=>{E||M(!1)},[E]);const H=l.useCallback(pe=>{a(pe),m(null)},[]),X=l.useCallback(async()=>{if(!(!ce||!g))try{const _=(await Fn(ce)).map(Q=>Pn(ce,Q)),ee=`${an(ce,"")}/`,me=_.filter(Q=>Q.path.startsWith(ee));c(me)}catch{}},[ce,g]),Y=l.useRef(null);l.useEffect(()=>{Y.current?.mode==="worktree"&&!k&&X(),Y.current=k},[k,X]);const Ee=l.useCallback(()=>{if(!ce){const ee="Select a project directory first.";return m(ee),xe.error(ee),!1}const pe=Ie,_=ie;if(!pe){const ee="Provide a branch name for the new worktree.";return m(ee),xe.error(ee),!1}if(!_){const ee="Provide a branch name that can be used as a folder.";return m(ee),xe.error(ee),!1}const se=an(ce,_);if(i.some(ee=>ee.path===se)){const ee="A worktree with this folder already exists.";return m(ee),xe.error(ee),!1}return m(null),!0},[ce,Ie,ie,i]),Be=async()=>{if(y||B||!Ee())return;b(!0),m(null);let pe=null;try{const _=Ie,ee=await Af({projectDirectory:ce,worktreeSlug:ie,branch:_,createBranch:!0});pe=ee;let me=await yn(ee.path).catch(()=>{});try{await bf(ee.path,{remote:"origin",branch:_,options:["--set-upstream"]}),me=await yn(ee.path).catch(()=>me),xe.success(`Configured upstream for ${_}`)}catch(le){const Me=le instanceof Error?le.message:"Unable to push new worktree branch.";xe.warning("Worktree created locally",{description:on(`Upstream setup failed: ${Me}`)})}const Q=me?{...ee,status:me}:ee,oe=await D(void 0,ee.path);if(!oe){await Xa({projectDirectory:ce,path:ee.path,force:!0}).catch(()=>{});const le="Failed to create session for worktree";m(le),xe.error(le);return}R(oe.id,de),ae(oe.id,ee.path),V(oe.id,Q),await X(),a(""),xe.success("Worktree created")}catch(_){pe&&await Xa({projectDirectory:ce,path:pe.path,force:!0}).catch(()=>{});const se=_ instanceof Error?_.message:"Failed to create worktree";m(se),xe.error(se)}finally{b(!1)}},ct=l.useCallback(pe=>{const _=C.filter(se=>K(se.id)?.path===pe.path);Qs.requestDelete({sessions:_,mode:"worktree",worktree:pe})},[C,K]),ot=l.useCallback(async()=>{if(k){A(!0);try{const pe=q,_=pe&&T;if(k.sessions.length===1){const se=k.sessions[0];if(!await P(se.id,{archiveWorktree:pe,deleteRemoteBranch:_})){xe.error("Failed to delete session"),A(!1);return}const me=pe?_?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;xe.success("Session deleted",{description:on(me)})}else{const se=k.sessions.map(Q=>Q.id),{deletedIds:ee,failedIds:me}=await O(se,{archiveWorktree:pe,deleteRemoteBranch:_});if(ee.length>0){const Q=pe?_?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,le=[me.length>0?`${me.length} session${me.length===1?"":"s"} could not be deleted.`:k.dateLabel?`Removed all sessions from ${k.dateLabel}.`:void 0,Q].filter(Boolean).join(" ");xe.success(`Deleted ${ee.length} session${ee.length===1?"":"s"}`,{description:on(le||void 0)})}if(me.length>0&&(xe.error(`Failed to delete ${me.length} session${me.length===1?"":"s"}`,{description:on("Please try again in a moment.")}),ee.length===0)){A(!1);return}}U()}finally{A(!1)}}},[k,T,P,O,U,q]),Je=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:Un}),"."]})]}),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(Ft,{id:"worktree-branch-input",value:o,onChange:pe=>H(pe.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!qe||f,onKeyDown:pe=>{pe.key==="Enter"&&!y&&Be()}}),e.jsx(De,{onClick:Be,disabled:y||B||!qe||!Ie,className:"h-8",children:y?"Creating…":"Create"})]}),Ie&&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:Ie})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:rs(Ce,ne)})]})]}),p&&e.jsx("p",{className:"typography-meta text-destructive",children:p}),!qe&&!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:Un}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:i.map(pe=>{const _=pe.relativePath||(pe.path.startsWith(ce+"/")?pe.path.slice(ce.length+1):pe.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:pe.label||pe.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:_})]}),e.jsx("button",{type:"button",onClick:()=>ct(pe),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 ${pe.branch||pe.label}`,children:e.jsx(Gs,{className:"h-4 w-4"})})]},pe.path)})})]})]}),it=e.jsx(De,{variant:"ghost",onClick:()=>ve(!1),disabled:y,children:"Close"}),dt=k?.worktree??S[0]?.metadata??null,at=k?k.mode==="worktree"?`This removes the selected worktree and ${k.sessions.length===1?"1 linked session":`${k.sessions.length} linked sessions`}.`:`This action permanently removes ${k.sessions.length===1?"1 session":`${k.sessions.length} sessions`}${k.dateLabel?` from ${k.dateLabel}`:""}.`:"",pt=k?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:[k.sessions.slice(0,3).map(pe=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:pe.title||"Untitled Session"},pe.id)),k.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",k.sessions.length-3," more"]})]})}),re?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"}),dt?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:dt.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:dt?rs(dt.path,ne):"Worktree path unavailable."}),J&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),E?e.jsxs("button",{type:"button",onClick:()=>{F||M(pe=>!pe)},disabled:F,className:I("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",F?"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:T?e.jsx(la,{className:"size-4 text-primary"}):e.jsx(ca,{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:T?"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,ut=e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:U,disabled:N,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:ot,disabled:N,children:N?"Deleting…":re?"Delete worktree":k?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[Re?e.jsx(Kt,{open:ge,onClose:()=>ve(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:it}),children:e.jsx("div",{className:"space-y-2 pb-2",children:Je})}):e.jsx(vs,{open:ge,onOpenChange:ve,children:e.jsxs(js,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2 overflow-hidden",children:[e.jsx(Rs,{children:e.jsx(Ls,{children:"Worktree Manager"})}),Je,e.jsx(Vr,{className:"mt-2 gap-2 pt-1 pb-1",children:it})]})}),Re?e.jsx(Kt,{open:!!k,onClose:()=>{N||U()},title:k?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:ut}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[at&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:at}),pt]})}):e.jsx(vs,{open:!!k,onOpenChange:pe=>{if(!pe){if(N)return;U()}},children:e.jsxs(js,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(Rs,{children:[e.jsx(Ls,{children:k?.sessions.length===1?"Delete session":"Delete sessions"}),at&&e.jsx(lr,{children:at})]}),pt,e.jsx(Vr,{className:"mt-2 gap-2 pt-1 pb-1",children:ut})]})}),e.jsx(Vh,{open:r,onOpenChange:s})]})};function Kh(){return new Worker(wu,{type:"module"})}const Yh=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Xh(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 $i(r){if(typeof window>"u")return()=>{};const s=window.setTimeout(()=>r(void 0),0);return()=>window.clearTimeout(s)}const Jh=({children:r})=>{const s=ju(),t=At(c=>c.activeDirectory),n=At(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=At(c=>t?c.directories.get(t)?.diffCache.size??0:0),a=ue.useRef(!1),i=ue.useRef(new Map);return ue.useEffect(()=>{if(!s||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Po(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(u,d)},[s]),ue.useEffect(()=>{if(!s||!t||!n||o===0)return;const c=At.getState().directories.get(t);if(!c||c.diffCache.size===0||(i.current.get(t)??0)>=c.lastStatusChange)return;i.current.set(t,c.lastStatusChange);let u=!1,p=null;const m=Array.from(c.diffCache.entries());let f=0;const h=g=>{if(u)return;const x=Date.now();for(;f<m.length&&!(g&&g.timeRemaining()<8||!g&&Date.now()-x>8);){const[y,b]=m[f];f+=1,or(y);const v=Xh(y,b.original,b.modified),k={name:y,contents:b.original,cacheKey:`old-${v}`},j={name:y,contents:b.modified,cacheKey:`new-${v}`},S=Po(k,j),w={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(w,S)}f<m.length&&(p=$i(h))};return h(void 0),f<m.length&&(p=$i(h)),()=>{u=!0,p?.()}},[s,t,n,o]),e.jsx(e.Fragment,{children:r})},Zh=({children:r})=>{const t=ka()?.currentTheme?.metadata?.variant==="dark";xc();const n=ue.useMemo(()=>({theme:{dark:kr.dark,light:kr.light},themeType:t?"dark":"light",langs:Yh}),[t]);return e.jsx(vu,{poolOptions:{workerFactory:Kh,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Jh,{children:r})})},Qh=(r={})=>{const{edgeThreshold:s=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=r,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=we(),d=ue.useRef(null),u=ue.useRef(null);return ue.useEffect(()=>{if(!o||!a)return;const p=g=>{const x=g.touches[0];if(!x){d.current=null;return}x.clientX<=s?d.current={x:x.clientX,y:x.clientY,time:Date.now()}:d.current=null},m=g=>{if(!d.current)return;const x=g.touches[0];if(!x)return;x.clientX-d.current.x>10&&g.preventDefault()},f=g=>{if(!d.current)return;const x=g.changedTouches[0];if(!x){d.current=null,u.current=null;return}u.current={x:x.clientX,y:x.clientY,time:Date.now()};const{x:y,y:b,time:v}=d.current,{x:k,y:j,time:S}=u.current,w=k-y,T=j-b,M=S-v,N=Math.abs(T)<Math.abs(w),A=M<=n,C=Math.abs(T)<t;w>=t&&N&&A&&C&&!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},Lr=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;ue.memo(()=>{const r=ue.useRef(null),{addAttachedFile:s}=fe(),{isMobile:t}=we(),n=ja(),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=fe.getState().attachedFiles.length;try{await s(f),fe.getState().attachedFiles.length>h&&p++}catch(g){console.error("File attach failed",g),xe.error(g instanceof Error?g.message:"Failed to attach file")}}p>0&&xe.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(x=>`${x?.name||"file"}: ${x?.reason||"skipped"}`).join(`
|
|
65
|
-
`);xe.error(`Some files were skipped:
|
|
66
|
-
${g}`)}const h=m.map(g=>{if(!g?.dataUrl)return null;try{const[x,y]=g.dataUrl.split(","),b=g.mimeType||x?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!y)return null;const v=atob(y),k=new Uint8Array(v.length);for(let S=0;S<v.length;S++)k[S]=v.charCodeAt(S);const j=new Blob([k],{type:b});return new File([j],g.name||"file",{type:b})}catch(x){return console.error("Failed to decode VS Code picked file",x),null}}).filter(Boolean);h.length>0&&await i(h)}catch(u){console.error("VS Code file pick failed",u),xe.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:I(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(_o,{className:I(a,"text-current")})})]})});const eg=ue.memo(({file:r,onRemove:s})=>{const t=()=>r.mimeType.startsWith("image/")?e.jsx(Sr,{className:"h-3.5 w-3.5"}):r.mimeType.includes("text")||r.mimeType.includes("code")?e.jsx(er,{className:"h-3.5 w-3.5"}):r.mimeType.includes("json")||r.mimeType.includes("xml")?e.jsx(Jn,{className:"h-3.5 w-3.5"}):e.jsx(er,{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(Su,{className:"h-3 w-3 text-primary"}):e.jsx(Rl,{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(us,{className:"h-3 w-3"})})]})}),tg=ue.memo(()=>{const{attachedFiles:r,removeAttachedFile:s}=fe();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(eg,{file:t,onRemove:()=>s(t.id)},t.id))]})})}),zc=ue.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(Sr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(er,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Jn,{className:"h-3.5 w-3.5"}):e.jsx(er,{className:"h-3.5 w-3.5"}):e.jsx(er,{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(st,{delayDuration:1e3,children:[e.jsx(rt,{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(Sr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:p})]})}),e.jsx(et,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:p})]},`img-${u}`)})})})]})}),Hc=(r,s=200)=>{const[t,n]=ue.useState(r);return ue.useEffect(()=>{const o=window.setTimeout(()=>{n(r)},s);return()=>{window.clearTimeout(o)}},[r,s]),t},sg=l.forwardRef(({searchQuery:r,onFileSelect:s,onClose:t},n)=>{const{currentDirectory:o}=jt(),{addServerFile:a}=fe(),i=xa(C=>C.searchFiles),c=Hc(r,180),[d,u]=l.useState([]),[p,m]=l.useState(!1),[f,h]=l.useState(0),[g,x]=l.useState(360),[y,b]=l.useState({}),[v,k]=l.useState({}),j=l.useRef([]),S=l.useRef([]),w=l.useRef([]),T=l.useRef(null),M=l.useCallback((C,D)=>{const P=C.trim().toLowerCase();if(!P)return 0;const O=D.toLowerCase();let W=0,R=-1,V=0;for(let ae=0;ae<P.length;ae+=1){const K=P[ae];if(!K||K===" ")continue;const B=O.indexOf(K,R+1);if(B===-1)return null;const L=B-R-1;if(L===0?V+=1:V=0,W+=10,W+=Math.max(0,18-B),W-=Math.max(0,L),B===0)W+=12;else{const ne=O[B-1];(ne==="/"||ne==="_"||ne==="-"||ne==="."||ne===" ")&&(W+=10)}W+=V>0?12:0,R=B}return W+=Math.max(0,24-Math.round(O.length/3)),W},[]);l.useEffect(()=>{const C=D=>{const P=D.target;!P||!T.current||T.current.contains(P)||t()};return document.addEventListener("pointerdown",C,!0),()=>{document.removeEventListener("pointerdown",C,!0)}},[t]),l.useEffect(()=>{if(!o){u([]);return}const D=(c??"").trim().toLowerCase();let P=!1;return m(!0),i(o,D,80).then(O=>{if(P)return;const W=D?O.map(R=>{const V=R.relativePath||R.name||R.path,ae=M(D,V);return ae===null?null:{file:R,score:ae,labelLength:V.length}}).filter(Boolean):O.map(R=>({file:R,score:0,labelLength:(R.relativePath||R.name||R.path).length}));W.sort((R,V)=>V.score-R.score||R.labelLength-V.labelLength||R.file.path.localeCompare(V.file.path)),u(W.slice(0,15).map(R=>R.file))}).catch(()=>{P||u([])}).finally(()=>{P||m(!1)}),()=>{P=!0}},[o,c,M,i]),l.useEffect(()=>{h(0),b({}),k({})},[d]),l.useEffect(()=>{j.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),l.useEffect(()=>{let C=null;const D=()=>{C!==null&&cancelAnimationFrame(C),C=requestAnimationFrame(()=>{const P={},O={};S.current.forEach((W,R)=>{if(!W)return;const ae=w.current[R]?.offsetWidth??W.scrollWidth,K=Math.max(0,ae-W.clientWidth),B=K>8;if(P[R]=B,B){const L=Math.max(.6,K/110);O[R]=L}}),b(P),k(O)})};return D(),window.addEventListener("resize",D),()=>{C!==null&&cancelAnimationFrame(C),window.removeEventListener("resize",D)}},[d]),l.useEffect(()=>{const C=S.current[f];if(!C)return;const D=()=>{const O=C.clientWidth;O>0&&x(O)};if(D(),typeof ResizeObserver>"u")return;const P=new ResizeObserver(D);return P.observe(C),()=>{P.disconnect()}},[f]);const N=l.useCallback(async C=>{await a(C.path,C.name),s(C)},[a,s]);l.useImperativeHandle(n,()=>({handleKeyDown:C=>{if(C==="Escape"){t();return}const D=d.length;if(D!==0){if(C==="ArrowDown"){h(P=>(P+1)%D);return}if(C==="ArrowUp"){h(P=>(P-1+D)%D);return}if(C==="Enter"||C==="Tab"){const P=(f%D+D)%D,O=d[P];O&&N(O)}}}}),[d,f,t,N]);const A=C=>{switch(C.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(ws,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(ws,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(er,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Sr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Jn,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:T,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(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(Zn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((C,D)=>{const P=C.relativePath||C.name,O=zl(P,{maxLength:45}),W=f===D,R=y[D]??!1,V=v[D]??2.6,ae=e.jsxs("div",{ref:K=>{j.current[D]=K},className:I("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",W&&"bg-muted"),onClick:()=>N(C),onMouseEnter:()=>h(D),children:[A(C),e.jsxs("span",{ref:K=>{S.current[D]=K},className:"relative flex-1 overflow-hidden max-w-[360px] file-mention-marquee-container",style:W?{"--file-mention-marquee-width":`${g}px`,"--file-mention-marquee-duration":`${V}s`}:void 0,"aria-label":P,children:[e.jsx("span",{ref:K=>{w.current[D]=K},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:P}),R&&W?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:P}):e.jsx("span",{className:"block truncate",children:O})]})]});return e.jsx(l.Fragment,{children:ae},C.path)}),d.length>0&&e.jsx("div",{className:"h-2"}),d.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),Wc=l.forwardRef(({searchQuery:r,onCommandSelect:s,onClose:t},n)=>{const{hasMessagesInCurrentSession:o}=fe(da(g=>{const x=g.currentSessionId;return{hasMessagesInCurrentSession:(x?g.messages.get(x)?.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=x=>{const y=x.target;!y||!f.current||f.current.contains(y)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),l.useEffect(()=>{(async()=>{d(!0);try{const y=(await ke.listCommands()).map(w=>({name:w.name,description:w.description,agent:w.agent,model:w.model,isBuiltIn:!1})),b=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],v=new Map;b.forEach(w=>v.set(w.name,w)),y.forEach(w=>v.set(w.name,w));const k=Array.from(v.values()),j=!o,S=(r?k.filter(w=>w.name.toLowerCase().includes(r.toLowerCase())||w.description&&w.description.toLowerCase().includes(r.toLowerCase())):k).filter(w=>j||w.name!=="init");S.sort((w,T)=>{const M=w.name.toLowerCase().startsWith(r.toLowerCase()),N=T.name.toLowerCase().startsWith(r.toLowerCase());return M&&!N?-1:!M&&N?1:w.name.localeCompare(T.name)}),i(S)}catch{const x=!o,y=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],b=(r?y.filter(v=>v.name.toLowerCase().includes(r.toLowerCase())||v.description&&v.description.toLowerCase().includes(r.toLowerCase())):y).filter(v=>x||v.name!=="init");i(b)}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 x=a.length;if(g==="Escape"){t();return}if(x!==0){if(g==="ArrowDown"){p(y=>(y+1)%x);return}if(g==="ArrowUp"){p(y=>(y-1+x)%x);return}if(g==="Enter"||g==="Tab"){const y=(u%x+x)%x,b=a[y];b&&s(b)}}}}),[a,u,t,s]);const h=g=>{switch(g.name){case"init":return e.jsx(er,{className:"h-3.5 w-3.5 text-green-500"});case"summarize":return e.jsx(Nu,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Vs,{className:"h-3.5 w-3.5 text-cyan-500"});default:return g.isBuiltIn?e.jsx(ku,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(rr,{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-background 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(Zn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[a.map((g,x)=>e.jsxs("div",{ref:y=>{m.current[x]=y},className:I("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",x===u&&"bg-muted"),onClick:()=>s(g),onMouseEnter:()=>p(x),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"})]})});Wc.displayName="CommandAutocomplete";const rg=r=>r?r!=="primary":!1,Uc=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}=St();l.useEffect(()=>{const f=u().filter(x=>rg(x.mode)).map(x=>({name:x.name,description:x.description,mode:x.mode??void 0})),h=r.trim().toLowerCase(),g=h.length?f.filter(x=>x.name.toLowerCase().includes(h)):f;g.sort((x,y)=>x.name.localeCompare(y.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:I("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",f===a&&"bg-muted"),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-background 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"})]})});Uc.displayName="AgentMentionAutocomplete";function ng({className:r,children:s,...t}){return e.jsxs(Cu,{"data-slot":"scroll-area",className:I("relative",r),...t,children:[e.jsx(Mu,{"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(og,{}),e.jsx(Au,{})]})}function og({className:r,orientation:s="vertical",...t}){return e.jsx(Du,{"data-slot":"scroll-area-scrollbar",orientation:s,className:I("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(Eu,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const ag=({onFilesSelected:r,multiSelect:s=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Et(),c=ja(),d=i||c,{currentDirectory:u}=jt(),p=xa(F=>F.searchFiles),[m,f]=l.useState(!1),[h,g]=l.useState(!1),[x,y]=l.useState(""),b=Hc(x,200),[v,k]=l.useState(new Set),[j,S]=l.useState(new Set),[w,T]=l.useState({}),M=l.useRef(new Set),N=l.useRef(new Set),[A,C]=l.useState([]),[D,P]=l.useState(!1),[O,W]=l.useState(!1),[R,V]=l.useState(!1),[ae,K]=l.useState(null),B=n??m,L=o??f,ne=l.useCallback(F=>F.slice().sort(($,U)=>$.type!==U.type?$.type==="directory"?-1:1:$.name.localeCompare(U.name)),[]),Se=l.useCallback((F,$)=>ne($.filter(U=>!U.name.startsWith(".")).map(U=>{const H=U.name,X=!U.isDirectory&&H.includes(".")?H.split(".").pop()?.toLowerCase():void 0;return{name:H,path:U.path||`${F}/${H}`,type:U.isDirectory?"directory":"file",size:0,extension:X}})),[ne]),Ne=l.useCallback(async F=>{W(!0),K(null);try{const $=await ke.listLocalDirectory(F),U=Se(F,$.map(H=>({name:H.name,path:H.path,isDirectory:H.isDirectory})));M.current=new Set([F]),N.current=new Set,T({[F]:U}),S(new Set)}catch{K("Failed to load directory contents"),M.current=new Set([F]),N.current=new Set,T({[F]:[]}),S(new Set)}finally{W(!1)}},[Se]),de=l.useCallback(async F=>{const $=F.trim();if($&&!M.current.has($)&&!N.current.has($)){N.current=new Set(N.current),N.current.add($);try{const U=await ke.listLocalDirectory($),H=Se($,U.map(X=>({name:X.name,path:X.path,isDirectory:X.isDirectory})));M.current=new Set(M.current),M.current.add($),T(X=>({...X,[$]:H}))}catch{T(U=>U[$]?U:{...U,[$]:[]})}finally{N.current=new Set(N.current),N.current.delete($)}}},[Se]);l.useEffect(()=>{(B||h)&&u&&Ne(u)},[B,h,u,Ne]),l.useEffect(()=>{if(!(B||h)||!u){C([]),P(!1);return}const F=b.trim();if(!F){C([]),P(!1);return}let $=!1;return P(!0),p(u,F,150).then(U=>{if($)return;const H=U.map(X=>({name:X.name,path:X.path,type:"file",extension:X.extension,relativePath:X.relativePath,size:0}));C(H)}).catch(()=>{$||C([])}).finally(()=>{$||P(!1)}),()=>{$=!0}},[B,h,u,b,p]),l.useEffect(()=>{!B&&!h&&(k(new Set),y(""),C([]),P(!1))},[B,h]);const ge=F=>{if(F.type==="directory")return j.has(F.path)?e.jsx(ss,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(ss,{className:"h-3.5 w-3.5 text-primary/60"});switch(F.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(ws,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(ws,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Oo,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Sr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Oo,{className:"h-3.5 w-3.5 text-muted-foreground"})}},ve=async F=>{j.has(F)?S(U=>{const H=new Set(U);return H.delete(F),H}):(S(U=>{const H=new Set(U);return H.add(F),H}),await de(F))},Ae=F=>{k(s?$=>{const U=new Set($);return U.has(F)?U.delete(F):U.add(F),U}:new Set([F]))},Te=async()=>{const F=new Map;Object.values(w).forEach(H=>{H.forEach(X=>{X.type==="file"&&F.set(X.path,X)})});const $=new Map(A.map(H=>[H.path,H])),U=Array.from(v).map(H=>F.get(H)??$.get(H)).filter(H=>!!H);V(!0);try{await r(U),k(new Set),L(!1),g(!1)}finally{V(!1)}},Pe=l.useMemo(()=>u?w[u]??[]:[],[w,u]),Re=x.trim().length>0,ce=F=>w[F]??[],Ie=F=>{if(u&&F.startsWith(u)){const $=F.substring(u.length);return $.startsWith("/")?$.substring(1):$}return F.split("/").pop()||F},ie=(F,$)=>{const U=Re?F.relativePath||Ie(F.path):F.name,H=Re&&U.includes("/")&&U.length>45,X=H?zl(U,{maxLength:d?42:48}):U,Y=e.jsxs("div",{className:I("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-muted cursor-pointer typography-ui-label text-foreground text-left",F.type==="file"&&v.has(F.path)&&"bg-primary/10"),style:{paddingLeft:`${$*12}px`},onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation(),F.type==="file"&&Ae(F.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ge(F)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":U,children:X})]}),F.type==="file"&&v.has(F.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return H?e.jsxs(st,{delayDuration:120,children:[e.jsx(rt,{asChild:!0,children:Y}),e.jsx(et,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:U})})]},F.path):l.cloneElement(Y,{key:F.path})},Ce=(F,$)=>{const U=F.type==="directory",H=U?ce(F.path):[],X=j.has(F.path),Y=U&&X&&N.current.has(F.path)&&H.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:I("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!U&&v.has(F.path)&&"bg-primary/10"),style:{paddingLeft:`${$*12}px`},onClick:Ee=>{Ee.preventDefault(),Ee.stopPropagation(),U?ve(F.path):Ae(F.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ge(F)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:F.name}),!U&&v.has(F.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),U&&X&&H.length>0&&e.jsx("div",{children:H.map(Ee=>Ce(Ee,$+1))}),U&&X&&Y&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${($+1)*12}px`},children:"Loading…"})]},F.path)},qe=v.size>0?`${v.size} file${v.size!==1?"s":""} selected`:"No files selected",J=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:qe}),e.jsx(De,{size:"sm",onClick:Te,disabled:v.size===0||R,className:"h-6 typography-meta",children:R?"Attaching...":"Attach Files"})]}),E=d?"flex-1 min-h-[240px]":"h-[300px]",re=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(ia,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ft,{value:x,onChange:F=>y(F.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:F=>F.stopPropagation()}),x&&e.jsx("button",{onClick:F=>{F.stopPropagation(),y("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(us,{className:"h-3 w-3"})})]})}),e.jsxs(ng,{className:E,children:[O&&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..."})}),ae&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:ae})}),!O&&!ae&&e.jsxs("div",{className:"py-1 px-2",children:[Re?D?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):A.map(F=>ie(F,0)):Pe.map(F=>Ce(F,0)),!Re&&Pe.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),Re&&!D&&A.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),q=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:F=>{F.preventDefault(),F.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:F=>{F.preventDefault(),F.stopPropagation(),L(!0)},children:t}):null,e.jsx(Kt,{open:B,onClose:()=>L(!1),title:"Select Project Files",footer:J,children:e.jsx("div",{className:"flex flex-col gap-0",children:re})})]}):d?e.jsxs(e.Fragment,{children:[q,e.jsx(Kt,{open:h,onClose:()=>g(!1),title:"Select Project Files",footer:J,children:e.jsx("div",{className:"flex flex-col gap-0",children:re})})]}):e.jsxs(Xt,{open:B,onOpenChange:L,children:[e.jsx(Jt,{asChild:!0,children:t}),e.jsxs(Zt,{className:I("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[re,e.jsx(Ur,{}),J]})]})},ln=[{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 Bs(r){if(!r||r==="build")return ln[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)%(ln.length-1);return ln[t]}const ig=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Vc=r=>ig(r),lg=r=>r?typeof r=="string"?r==="ask":Vc(r)?Object.values(r).some(s=>s==="ask"):!1:!1,cg=r=>r?typeof r=="string"?r==="deny":Vc(r)?Object.values(r).some(s=>s==="deny"):!1:!1,Gc=({agentDefaultEditMode:r,webfetchPermission:s,bashPermission:t})=>{const n=lg(t),o=cg(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}},cn=r=>r==="primary"||r==="all"||r===void 0||r===null,dg=[{key:"tool_call",icon:ua,label:"Tool calling",isActive:r=>r?.tool_call===!0},{key:"reasoning",icon:Kn,label:"Reasoning",isActive:r=>r?.reasoning===!0}],ug={text:{icon:Ll,label:"Text"},image:{icon:Sr,label:"Image"},video:{icon:Iu,label:"Video"},audio:{icon:Tu,label:"Audio"},pdf:{icon:Jn,label:"PDF"}},mg=r=>r.trim().toLowerCase(),Ns=(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=>mg(o)))).map(o=>{const a=ug[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},fg=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),pg=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=fg.format(r);return s.endsWith(".0")?s.slice(0,-2):s},dn=r=>typeof r!="number"||!Number.isFinite(r)?"—":pg.format(r),Pr=r=>dg.filter(s=>s.isActive(r)).map(s=>({key:s.key,icon:s.icon,label:s.label})),zi=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},Hi=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)},Wi=({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}=St(),f=m(),{currentSessionId:h,messages:g,saveSessionAgentSelection:x,getSessionAgentSelection:y,saveAgentModelForSession:b,getAgentModelForSession:v,analyzeAndSaveExternalSessionChoices:k,getSessionAgentEditMode:j,setSessionAgentEditMode:S}=fe(),w=xt(z=>z.hasHydrated),{toggleFavoriteModel:T,isFavoriteModel:M,addRecentModel:N}=we(),{favoriteModelsList:A,recentModelsList:C}=Ac(),{isMobile:D}=Et(),P=Pp(),O=ja(),W=D||O,[R,V]=l.useState(null),[ae,K]=l.useState(null),[B,L]=l.useState(""),ne=l.useCallback(()=>V(null),[]),Se=l.useCallback(()=>K(null),[]),Ne=l.useRef(void 0),[de,ge]=l.useState(()=>{const z=new Set;return t&&z.add(t),z}),[ve,Ae]=l.useState(!1),[Te,Pe]=l.useState(!1),[Re,ce]=l.useState(!1),Ie=l.useId();l.useEffect(()=>{R==="model"&&ge(()=>{const z=new Set;return t&&z.add(t),z})},[R,t]),l.useEffect(()=>{R!=="agent"&&Ae(!1),R!=="model"&&L("")},[R]),l.useEffect(()=>{Te||ce(!1)},[Te]);const ie=p?.(),Ce=ie?.permission?.edit;let qe="ask";(Ce==="allow"||Ce==="ask"||Ce==="deny"||Ce==="full")&&(qe=Ce);const J=ie?ie.tools?.edit!==!1:!1;(!ie||!J)&&(qe="deny");const E=ie?.permission?.webfetch,re=ie?.permission?.bash,q=l.useMemo(()=>Gc({agentDefaultEditMode:qe,webfetchPermission:E,bashPermission:re}),[qe,E,re]),{cascadeDefaultMode:F,modeAvailability:$,autoApproveAvailable:U}=q,H=!!(h&&o),X=H&&h&&o?j(h,o,F):F,Y={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Ee=l.useCallback(z=>!$[z],[$]),Be=l.useMemo(()=>!H||Ee(X)&&X!==F?F:X,[F,Ee,H,X]),ct=[{mode:"ask",label:Y.ask,disabled:Ee("ask")},{mode:"allow",label:Y.allow,disabled:Ee("allow")},{mode:"full",label:Y.full,disabled:Ee("full")}],ot=l.useMemo(()=>Lr(Be),[Be]),Je=!H||!U;l.useEffect(()=>{Je&&(Ae(!1),ce(!1))},[Je]);const it=D?"mobile":O?"vscode":"default",dt=it==="mobile"?"h-9":it==="vscode"?"h-6":"h-8",at=it==="mobile"?"h-5 w-5":"h-4 w-4",pt=it==="mobile"?"h-5 w-5":"h-4 w-4",ut=W?"typography-micro":"typography-meta",pe=it==="mobile"?"gap-x-2":it==="vscode"?"gap-x-1":"gap-x-3",_=Y[Be],se=l.useCallback((z,Z=at)=>{const te=I(Z,"flex-shrink-0"),he=Lr(z),Qe={color:he?he.text:"var(--foreground)"};return z==="full"?e.jsx(Ds,{className:te,style:Qe}):z==="allow"?e.jsx(hn,{className:te,style:Qe}):z==="deny"?e.jsx(jr,{className:te,style:Qe}):e.jsx(vr,{className:te,style:Qe})},[at]),ee=l.useCallback(z=>{Je||!h||!o||Ee(z)||(S(h,o,z,F),Pe(!1),Ae(!1),ce(!1))},[F,Je,h,o,S,Pe,ce,Ee]),me=d(),Q=Array.isArray(me?.models)?me.models:[],oe=t&&n?u(t,n):void 0,le=Pr(oe),Me=Ns(oe,"input"),$e=Ns(oe,"output"),kt=[{label:"Input",value:dn(oe?.cost?.input)},{label:"Output",value:dn(oe?.cost?.output)},{label:"Cache read",value:dn(oe?.cost?.cache_read)},{label:"Cache write",value:dn(oe?.cost?.cache_write)}],bt=[{label:"Context",value:Lt(oe?.limit?.context)},{label:"Output",value:Lt(oe?.limit?.output)}],Dt=l.useRef(void 0),Nt=h?g.get(h)?.length??-1:-1,mt=l.useRef(null),wt=l.useCallback((z,Z,te)=>{if(!z||!Z)return"model-missing";const he=s.find(ye=>ye.id===z);return he?(Array.isArray(he.models)?he.models:[]).find(ye=>ye.id===Z)?(a(z),i(Z),h&&te&&b(h,te,z,Z),"applied"):"model-missing":"provider-missing"},[s,a,i,h,b]);l.useEffect(()=>{if(!h){mt.current=null;return}if(!w||s.length===0||f.length===0)return;(!mt.current||mt.current.sessionId!==h)&&(mt.current={sessionId:h,resolved:!1,inFlight:!1});const z=mt.current;if(!z||z.resolved||z.inFlight)return;let Z=!1;const te=()=>{if(Z)return;const ye=mt.current;ye&&ye.sessionId===h&&(ye.resolved=!0,ye.inFlight=!1)},he=()=>{const ye=y(h);if(ye){o!==ye&&c(ye);const Oe=v(h,ye);if(Oe){const Ke=wt(Oe.providerId,Oe.modelId,ye);if(Ke==="applied")return"resolved";if(Ke==="provider-missing")return"waiting"}else return"resolved"}for(const Oe of f){const Ke=v(h,Oe.name);if(!Ke)continue;o!==Oe.name&&c(Oe.name),x(h,Oe.name);const Ut=wt(Ke.providerId,Ke.modelId,Oe.name);if(Ut==="applied")return"resolved";if(Ut==="provider-missing")return"waiting"}return"continue"},He=()=>{if(f.length===0)return;const ye=f.filter(Ke=>cn(Ke.mode)),Oe=f.find(Ke=>Ke.name==="build")||ye[0]||f[0];Oe&&(x(h,Oe.name),o!==Oe.name&&c(Oe.name),Oe.model?.providerID&&Oe.model?.modelID&&wt(Oe.model.providerID,Oe.model.modelID,Oe.name))};return(async()=>{try{const ye=he();if(ye==="resolved"){te();return}if(ye==="waiting"||Nt===-1)return;if(Nt>0){z.inFlight=!0;try{const Oe=await k(h,f);if(Z)return;if(Oe.size>0){let Ke=null,Ut=-1/0;for(const[Ue,Rt]of Oe)Rt.timestamp>Ut&&(Ut=Rt.timestamp,Ke=Ue);if(Ke){x(h,Ke),o!==Ke&&c(Ke);const Ue=Oe.get(Ke);if(Ue){const Rt=wt(Ue.providerId,Ue.modelId,Ke);if(Rt==="applied"){te();return}if(Rt==="provider-missing")return}else{te();return}}}}catch(Oe){Z||console.error("[ModelControls] Error resolving session from messages:",Oe)}finally{const Oe=mt.current;!Z&&Oe&&Oe.sessionId===h&&(Oe.inFlight=!1)}}He(),te()}catch(ye){Z||console.error("[ModelControls] Error in session switch:",ye)}})(),()=>{Z=!0}},[h,Nt,f,o,y,v,c,wt,k,x,w,s]),l.useEffect(()=>{if(!w||!h||s.length===0||f.length===0)return;const Z=y(h)||o;if(!Z)return;const te=v(h,Z);if(!te)return;const he=s.find(Oe=>Oe.id===te.providerId);if(!he||!(Array.isArray(he.models)?he.models.some(Oe=>Oe.id===te.modelId):!1))return;const Qe=t===te.providerId,ye=n===te.modelId;Qe&&ye||(Z!==o&&c(Z),wt(te.providerId,te.modelId,Z))},[w,h,o,t,n,s,f,y,v,wt,c]),l.useEffect(()=>{if(!w)return;(async()=>{try{if(o!==Dt.current&&(Dt.current=o,o&&h)){await new Promise(he=>setTimeout(he,50));const Z=v(h,o);if(Z){const he=wt(Z.providerId,Z.modelId,o);if(he==="applied"||he==="provider-missing")return}const te=f.find(he=>he.name===o);if(te?.model?.providerID&&te?.model?.modelID&&wt(te.model.providerID,te.model.modelID,o)==="provider-missing")return}}catch(Z){console.error("[ModelControls] Agent change error:",Z)}})()},[o,h,v,wt,f,w]);const je=z=>{try{c(z),Pe(!1),h&&x(h,z),W&&ne()}catch(Z){console.error("[ModelControls] Handle agent change error:",Z)}},ze=(z,Z)=>{try{const te=wt(z,Z,o||void 0);if(te!=="applied"){te==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",z):te==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:z,modelId:Z});return}N(z,Z),Pe(!1),W&&ne()}catch(te){console.error("[ModelControls] Handle model change error:",te)}},Ge=z=>{const Z=typeof z?.name=="string"?z.name:typeof z?.id=="string"?z.id:"";return Z.length>40?Z.substring(0,37)+"...":Z},Le=()=>s.find(Z=>Z.id===t)?.name||t,ft=()=>{if(!t||!n||Q.length===0)return"Not selected";const z=Q.find(Z=>Z.id===n);return Ge(z)},Ct=()=>{if(!o){const Z=f.filter(He=>cn(He.mode)),he=Z.find(He=>He.name==="build")||Z[0];return he?vt(he.name):"Select Agent"}const z=f.find(Z=>Z.name===o);return vt(z?z.name:o)},vt=z=>z.charAt(0).toUpperCase()+z.slice(1),be=(z,Z,te)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:Z,"aria-label":Z,role:"img",children:e.jsx(z,{className:"h-3.5 w-3.5"})},te),We=l.useCallback(z=>{ge(Z=>{const te=new Set(Z);return te.has(z)?te.delete(z):te.add(z),te})},[]),Fe=l.useCallback(z=>{Ne.current&&clearTimeout(Ne.current),Ne.current=setTimeout(()=>{K(z)},500)},[]),Ze=l.useCallback(()=>{Ne.current&&clearTimeout(Ne.current)},[]);l.useEffect(()=>()=>{Ne.current&&clearTimeout(Ne.current)},[]);const Mt=()=>!W||ae!=="model"?null:e.jsx(Kt,{open:!0,onClose:Se,title:oe?.name||ft(),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()})]}),le.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:le.map(({key:z,icon:Z,label:te})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[be(Z,te,`cap-${z}`),e.jsx("span",{className:"typography-meta text-foreground",children:te})]},z))})]}),(Me.length>0||$e.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:z,icon:Z,label:te})=>be(Z,`${te} input`,`input-${z}`))})]}),$e.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:$e.map(({key:z,icon:Z,label:te})=>be(Z,`${te} output`,`output-${z}`))})]})]})]}),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(oe?.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(oe?.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:zi(oe?.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:Hi(oe?.release_date)})]})]})]})]})}),ht=()=>{if(!W||ae!=="agent"||!ie)return null;const z=Object.entries(ie.tools||{}).filter(([,ye])=>ye).map(([ye])=>ye).sort(),Z=!!(ie.prompt&&ie.prompt.trim().length>0),te=ie.model?.providerID&&ie.model?.modelID,he=ie.temperature!==void 0||ie.topP!==void 0,He=ye=>se(ye==="full"||ye==="allow"||ye==="deny"?ye:"ask","h-3.5 w-3.5"),Qe=ye=>ye==="full"?"Full":ye==="allow"?"Allow":ye==="deny"?"Deny":"Ask";return e.jsx(Kt,{open:!0,onClose:Se,title:vt(ie.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ie.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:ie.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:ie.mode==="primary"?"Primary":ie.mode==="subagent"?"Subagent":ie.mode==="all"?"All":"—"})]}),(te||he)&&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"}),te&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ie.model.providerID," / ",ie.model.modelID]}),he&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[ie.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:ie.temperature})]}),ie.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:ie.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"}),z.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:z.map(ye=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:ye},ye))}):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:[He(ie.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Qe(ie.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:[He(typeof ie.permission?.bash=="string"?ie.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Qe(typeof ie.permission?.bash=="string"?ie.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:[He(ie.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Qe(ie.permission?.webfetch)})]})]})]})]}),Z&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(hn,{className:"h-4 w-4 text-foreground"})]})})]})})},$t=()=>{if(!W)return null;const z=B.trim().toLowerCase(),Z=s.map(te=>{const he=Array.isArray(te.models)?te.models:[],He=z.length===0?!0:te.name.toLowerCase().includes(z)||te.id.toLowerCase().includes(z),Qe=z.length===0?he:he.filter(ye=>{const Oe=Ge(ye).toLowerCase(),Ke=typeof ye.id=="string"?ye.id.toLowerCase():"";return Oe.includes(z)||Ke.includes(z)});return{provider:te,providerModels:Qe,matchesProvider:He}}).filter(({matchesProvider:te,providerModels:he})=>te||he.length>0);return e.jsx(Kt,{open:R==="model",onClose:ne,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"relative",children:[e.jsx(ia,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Ft,{value:B,onChange:te=>L(te.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),B&&e.jsx("button",{type:"button",onClick:()=>L(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(jr,{className:"h-4 w-4"})})]})}),Z.length===0&&e.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),!B&&A.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(gs,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:A.map(({model:te,providerID:he,modelID:He})=>{const Qe=he===t&&He===n,ye=u(he,He);return e.jsxs("button",{type:"button",onClick:()=>ze(he,He),className:I("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",Qe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Vt,{providerId:he,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ge(te)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(ye?.limit?.context||ye?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[ye?.limit?.context?`${Lt(ye?.limit?.context)} ctx`:"",ye?.limit?.context&&ye?.limit?.output?" • ":"",ye?.limit?.output?`${Lt(ye?.limit?.output)} out`:""]})})]},`fav-mobile-${he}-${He}`)})})]}),!B&&C.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(Mn,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:C.map(({model:te,providerID:he,modelID:He})=>{const Qe=he===t&&He===n,ye=u(he,He);return e.jsxs("button",{type:"button",onClick:()=>ze(he,He),className:I("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",Qe?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Vt,{providerId:he,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ge(te)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(ye?.limit?.context||ye?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[ye?.limit?.context?`${Lt(ye?.limit?.context)} ctx`:"",ye?.limit?.context&&ye?.limit?.output?" • ":"",ye?.limit?.output?`${Lt(ye?.limit?.output)} out`:""]})})]},`recent-mobile-${he}-${He}`)})})]}),Z.map(({provider:te,providerModels:he})=>{if(he.length===0&&!z.length)return null;const He=te.id===t,Qe=de.has(te.id)||z.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>We(te.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Qe,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{providerId:te.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:te.name}),He&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Qe?e.jsx(yt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ns,{className:"h-3 w-3 text-muted-foreground"})]}),Qe&&he.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:he.map(ye=>{const Oe=He&&ye.id===n,Ke=u(te.id,ye.id),Ut=Pr(Ke).slice(0,3),Ue=Ns(Ke,"input");return e.jsxs("div",{className:I("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 last:border-b-0","rounded-lg transition-colors",!Oe&&"hover:bg-muted",Oe?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>ze(te.id,ye.id),className:I("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ge(ye)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Ke?.limit?.context||Ke?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Ke?.limit?.context?e.jsxs("span",{children:[Lt(Ke?.limit?.context)," ctx"]}):null,Ke?.limit?.context&&Ke?.limit?.output?e.jsx("span",{children:"•"}):null,Ke?.limit?.output?e.jsxs("span",{children:[Lt(Ke?.limit?.output)," out"]}):null]}),(Ut.length>0||Ue.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Ut,...Ue].map(({key:Rt,icon:ms,label:La})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:La,"aria-label":La,children:e.jsx(ms,{className:"h-3 w-3"})},`meta-${te.id}-${ye.id}-${Rt}`))})]})]}),e.jsx("button",{type:"button",onClick:Rt=>{Rt.preventDefault(),Rt.stopPropagation(),T(te.id,ye.id)},className:I("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",M(te.id,ye.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":M(te.id,ye.id)?"Unfavorite":"Favorite",title:M(te.id,ye.id)?"Remove from favorites":"Add to favorites",children:M(te.id,ye.id)?e.jsx(gs,{className:"h-4 w-4"}):e.jsx($s,{className:"h-4 w-4"})})]},ye.id)})})]},te.id)})]})})},zt=()=>{if(!W)return null;const z=f.filter(Z=>cn(Z.mode));return e.jsx(Kt,{open:R==="agent",onClose:ne,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[z.map(Z=>{const te=Z.name===o,he=Bs(Z.name);return e.jsxs("button",{type:"button",className:I("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",he.class,te?"active":"border-border/40"),onClick:()=>je(Z.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:I("h-2 w-2 rounded-full",he.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:te?{color:`var(${he.var})`}:void 0,children:vt(Z.name)})]}),Z.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:Z.description})]},Z.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:Je,onClick:()=>{Je||Ae(Z=>!Z)},className:I("flex w-full items-center justify-between gap-2 px-2 py-1.5 text-left bg-transparent","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-t-xl",Je?"cursor-not-allowed opacity-60":void 0),children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:ot?ot.text:"var(--foreground)",mixBlendMode:"normal"},children:_})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:I("flex items-center justify-center p-1",!ot&&"text-muted-foreground"),style:ot?{color:ot.text}:void 0,children:se(Be,at)}),e.jsx(yt,{className:I("h-4 w-4 text-muted-foreground transition-transform",ve?"rotate-180":"")})]})]}),ve&&!Je&&e.jsx("div",{className:"border-t border-border/40 bg-transparent px-2 py-1.5",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:ct.map(Z=>{const te=Z.mode===Be,he=Lr(Z.mode);return e.jsxs("button",{type:"button",disabled:Z.disabled,onClick:()=>ee(Z.mode),className:I("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",Z.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",te?"bg-primary/10":void 0),style:te&&he?{backgroundColor:he.background??void 0}:void 0,children:[se(Z.mode,at),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:he?he.text:"var(--foreground)"},children:Z.label})})]},Z.mode)})})})]})]})})},G=()=>e.jsx(et,{align:"start",sideOffset:8,className:"max-w-[320px]",children:oe?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:oe.name||ft()}),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:le.length>0?le.map(({key:z,icon:Z,label:te})=>be(Z,te,`cap-${z}`)):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:z,icon:Z,label:te})=>be(Z,`${te} input`,`input-${z}`)):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:$e.length>0?$e.map(({key:z,icon:Z,label:te})=>be(Z,`${te} output`,`output-${z}`)):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)"}),kt.map(z=>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:z.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:z.value})]},z.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"}),bt.map(z=>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:z.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:z.value})]},z.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:zi(oe.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:Hi(oe.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),_e=()=>e.jsxs(st,{delayDuration:1e3,children:[W?e.jsxs("button",{type:"button",onClick:()=>V("model"),onTouchStart:()=>Fe("model"),onTouchEnd:Ze,onTouchCancel:Ze,className:I("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",D&&"flex-1","cursor-pointer hover:opacity-70",dt),children:[t?e.jsx(Vt,{providerId:t,className:I(pt,"flex-shrink-0")}):e.jsx(Ds,{className:I(pt,"text-muted-foreground")}),e.jsx("span",{className:I("model-controls__model-label typography-micro font-medium truncate min-w-0",D?"flex-1":"max-w-[220px]"),children:ft()})]}):e.jsxs(Xt,{open:Te,onOpenChange:Pe,children:[e.jsx(rt,{asChild:!0,children:e.jsx(Jt,{asChild:!0,children:e.jsxs("div",{className:I("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",dt),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{providerId:t,className:I(pt,"flex-shrink-0")}),e.jsx(Ds,{className:I(pt,"text-primary/60 hidden")})]}):e.jsx(Ds,{className:I(pt,"text-muted-foreground")}),e.jsx("span",{className:I("model-controls__model-label",ut,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:ft()},`${t}-${n}`)]})})}),e.jsxs(Zt,{className:"max-w-[300px]",children:[A.length>0&&e.jsxs(hr,{children:[e.jsxs(gr,{className:"typography-meta",children:[e.jsx(gs,{className:"h-3 w-3 flex-shrink-0 mr-2 text-primary"}),"Favorites"]}),e.jsx(xr,{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:A.map(({model:z,providerID:Z,modelID:te})=>{const he=u(Z,te),He=Pr(he).map(Ue=>({...Ue,id:`cap-${Ue.key}`})),Qe=[...Ns(he,"input"),...Ns(he,"output")],ye=Array.from(new Map(Qe.map(Ue=>[Ue.key,Ue])).values()).map(Ue=>({...Ue,id:`mod-${Ue.key}`})),Oe=[...He,...ye],Ke=Lt(he?.limit?.context),Ut=Lt(he?.limit?.output);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{ze(Z,te)},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:Ge(z)}),he?.limit?.context||he?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[he?.limit?.context?`${Ke} ctx`:"",he?.limit?.context&&he?.limit?.output?" • ":"",he?.limit?.output?`${Ut} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Oe.map(({id:Ue,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"})},Ue)),e.jsx("button",{onClick:Ue=>{Ue.preventDefault(),Ue.stopPropagation(),T(Z,te)},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(gs,{className:"h-3.5 w-3.5"})})]})]})},`fav-${Z}-${te}`)})})})]}),C.length>0&&e.jsxs(hr,{children:[e.jsxs(gr,{className:"typography-meta",children:[e.jsx(Mn,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(xr,{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:z,providerID:Z,modelID:te})=>{const he=u(Z,te),He=Pr(he).map(Ue=>({...Ue,id:`cap-${Ue.key}`})),Qe=[...Ns(he,"input"),...Ns(he,"output")],ye=Array.from(new Map(Qe.map(Ue=>[Ue.key,Ue])).values()).map(Ue=>({...Ue,id:`mod-${Ue.key}`})),Oe=[...He,...ye],Ke=Lt(he?.limit?.context),Ut=Lt(he?.limit?.output);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{ze(Z,te)},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:Ge(z)}),he?.limit?.context||he?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[he?.limit?.context?`${Ke} ctx`:"",he?.limit?.context&&he?.limit?.output?" • ":"",he?.limit?.output?`${Ut} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Oe.map(({id:Ue,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"})},Ue)),e.jsx("button",{onClick:Ue=>{Ue.preventDefault(),Ue.stopPropagation(),T(Z,te)},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($s,{className:"h-3.5 w-3.5"})})]})]})},`recent-${Z}-${te}`)})})})]}),(A.length>0||C.length>0)&&e.jsx(Ur,{}),s.map(z=>{const Z=Array.isArray(z.models)?z.models:[];return Z.length===0?e.jsxs(gt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Vt,{providerId:z.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),z.name," (No models)"]},z.id):e.jsxs(hr,{children:[e.jsxs(gr,{className:"typography-meta",children:[e.jsx(Vt,{providerId:z.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),z.name]}),e.jsx(xr,{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:Z.map(te=>{const he=u(z.id,te.id),He=Pr(he).map(Ue=>({...Ue,id:`cap-${Ue.key}`})),Qe=[...Ns(he,"input"),...Ns(he,"output")],ye=Array.from(new Map(Qe.map(Ue=>[Ue.key,Ue])).values()).map(Ue=>({...Ue,id:`mod-${Ue.key}`})),Oe=[...He,...ye],Ke=Lt(he?.limit?.context),Ut=Lt(he?.limit?.output);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{ze(z.id,te.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:Ge(te)}),he?.limit?.context||he?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[he?.limit?.context?`${Ke} ctx`:"",he?.limit?.context&&he?.limit?.output?" • ":"",he?.limit?.output?`${Ut} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Oe.map(({id:Ue,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"})},Ue)),e.jsx("button",{onClick:Ue=>{Ue.preventDefault(),Ue.stopPropagation(),T(z.id,te.id)},className:I("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",M(z.id,te.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":M(z.id,te.id)?"Unfavorite":"Favorite",title:M(z.id,te.id)?"Remove from favorites":"Add to favorites",children:M(z.id,te.id)?e.jsx(gs,{className:"h-3.5 w-3.5"}):e.jsx($s,{className:"h-3.5 w-3.5"})})]})]})},te.id)})})})]},z.id)})]})]}),G()]}),Ve=()=>{if(!ie)return e.jsx(et,{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 z=Object.entries(ie.tools||{}).filter(([,ye])=>ye).map(([ye])=>ye).sort(),Z=!!(ie.prompt&&ie.prompt.trim().length>0),te=ie.model?.providerID&&ie.model?.modelID,he=ie.temperature!==void 0||ie.topP!==void 0,He=ye=>se(ye==="full"||ye==="allow"||ye==="deny"?ye:"ask","h-3.5 w-3.5"),Qe=ye=>ye==="full"?"Full":ye==="allow"?"Allow":ye==="deny"?"Deny":"Ask";return e.jsx(et,{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:vt(ie.name)}),ie.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:ie.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:ie.mode==="primary"?"Primary":ie.mode==="subagent"?"Subagent":ie.mode==="all"?"All":"—"})]}),(te||he)&&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"}),te?e.jsxs("span",{className:"typography-meta text-foreground",children:[ie.model.providerID," / ",ie.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),he&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[ie.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:ie.temperature})]}),ie.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:ie.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"}),z.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:z.map(ye=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:ye},ye))}):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:[He(ie.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Qe(ie.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:[He(typeof ie.permission?.bash=="string"?ie.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Qe(typeof ie.permission?.bash=="string"?ie.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:[He(ie.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Qe(ie.permission?.webfetch)})]})]})]}),Z&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(hn,{className:"h-4 w-4 text-foreground"})]})]})})},lt=()=>W?e.jsxs("button",{type:"button",onClick:()=>V("agent"),onTouchStart:()=>Fe("agent"),onTouchEnd:Ze,onTouchCancel:Ze,className:I("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",dt,"cursor-pointer hover:opacity-70",W&&"ml-1"),children:[e.jsx(zr,{className:I(pt,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${Bs(o).var})`}:void 0}),e.jsx("span",{className:I("model-controls__agent-label",ut,"font-medium truncate min-w-0"),style:o?{color:`var(${Bs(o).var})`}:void 0,children:Ct()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(st,{delayDuration:1e3,children:[e.jsxs(Xt,{children:[e.jsx(rt,{asChild:!0,children:e.jsx(Jt,{asChild:!0,children:e.jsxs("div",{className:I("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",dt),children:[e.jsx(zr,{className:I(pt,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${Bs(o).var})`}:void 0}),e.jsx("span",{className:I("model-controls__agent-label",ut,"font-medium min-w-0 truncate",P?"max-w-[220px]":void 0),style:o?{color:`var(${Bs(o).var})`}:void 0,children:Ct()})]})})}),e.jsxs(Zt,{align:"end",children:[f.filter(z=>cn(z.mode)).map(z=>e.jsx(gt,{className:"typography-meta",onSelect:()=>je(z.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:I("h-1 w-1 rounded-full agent-dot",Bs(z.name).class)}),e.jsx("span",{className:"font-medium",children:vt(z.name)})]}),z.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:z.description})]})},z.name)),e.jsx(Ur,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:Je,onClick:()=>{Je||ce(z=>!z)},className:I("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",Je?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Re,"aria-controls":Ie,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:ot?ot.text:"var(--foreground)"},children:_})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:I("flex items-center justify-center p-1",!ot&&"text-muted-foreground"),style:ot?{color:ot.text}:void 0,children:se(Be)}),e.jsx(yt,{className:I("h-3.5 w-3.5 transition-transform text-muted-foreground",Re?"rotate-180":"")})]})]}),Re&&!Je&&e.jsx("div",{id:Ie,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:ct.map(z=>{const Z=z.mode===Be,te=Lr(z.mode);return e.jsxs("button",{type:"button",disabled:z.disabled,onClick:()=>ee(z.mode),className:I("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",z.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",Z?"bg-primary/10":void 0),style:Z&&te?{backgroundColor:te.background??void 0}:void 0,children:[se(z.mode,at),e.jsx("span",{className:"typography-meta font-medium",style:{color:te?te.text:"var(--foreground)"},children:z.label})]},z.mode)})})]})]})]}),Ve()]})}),tt=I("@container/model-controls flex items-center min-w-0",pe,D&&"w-full",r);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:tt,children:[e.jsx("div",{className:I("flex items-center min-w-0",D?"flex-1 min-w-0 overflow-hidden":"flex-1 min-w-0 justify-end"),children:_e()}),e.jsx("div",{className:I("flex items-center min-w-0",pe,D&&"flex-shrink-0"),children:lt()})]}),$t(),zt(),Mt(),ht()]})},hg=r=>r?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(r):!0,gg=(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(!hg(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}},qc=r=>({id:r.id,content:r.content,status:r.status||"pending",priority:r.priority||"medium"}),Go=Pt()(Wt((r,s)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){r({isLoading:!0});try{const o=(await ke.getSessionTodos(t)).map(qc);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"})),xg=(r,s)=>{const t=s.map(qc);Go.getState().updateTodos(r,t)},Ui=[{variant:"shine",component:({children:r,className:s,...t})=>e.jsx(Dr.span,{...t,className:I("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)=>ue.createElement(Dr.span,{...t,key:n+String(o),className:I("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:I("invisible",s),children:r}),e.jsx("span",{...t,className:I("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:I("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(Dr.span,{...t,className:I("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(Dr.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:I("absolute inset-0"),children:a.map((i,c)=>e.jsx(Dr.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:I("text-primary-muted hover:animate-text-shake",s),children:r})},{variant:"hover-decoration",component:({children:r,className:s,...t})=>e.jsx("div",{className:I("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:I("text-primary-muted",s),children:r})})}];function ko({variant:r="shine",className:s,...t}){const a=Ui.find(i=>i.variant===r)?.component||Ui[0].component;return e.jsx(Ml,{children:e.jsx(a,{...t,className:s})})}const yg=2e3,bg=1500;function wg({statusText:r,isWaitingForPermission:s,wasAborted:t,completionId:n,isComplete:o}){const[a,i]=ue.useState(null),[c,d]=ue.useState(!1),[u,p]=ue.useState(!1),[m,f]=ue.useState(!1),[h,g]=ue.useState(null),x=ue.useRef(0),y=ue.useRef([]),b=ue.useRef(!1),v=ue.useRef(null),k=ue.useRef(null),j=ue.useRef(null),S=ue.useRef(0),w=ue.useRef(null),T=ue.useRef(!1),M=ue.useRef(!1),N=ue.useRef(!1),A=ue.useRef(!0),C=ue.useRef(null),D=ue.useRef(null),P=(V,ae)=>{if(v.current&&(clearTimeout(v.current),v.current=null),k.current&&(clearTimeout(k.current),k.current=null),V==="aborted"){i(null),d(!1),f(!1),g("aborted"),w.current="aborted",T.current=!0,M.current=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p(!0)):p(!0);return}g(null),f(!1),w.current=V,T.current=!0,i(V),d(ae),u||(typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{p(!0)}):p(!0))};if(ue.useEffect(()=>{const V=Date.now();r?(b.current=!1,a?(r!==a||!!s!==c)&&y.current.push({status:r,permission:!!s}):(P(r,!!s),x.current=V,y.current=[])):b.current=!0},[r,s,a,c,t]),ue.useEffect(()=>{t&&(M.current=!0)},[t]),ue.useEffect(()=>{N.current=!!o},[o]),ue.useEffect(()=>{o&&(b.current=!0)},[o]),ue.useEffect(()=>{const V=L=>{if(m)return;const ne=w.current!==null||T.current;L&&ne?(f(!1),p(!0),i(null),d(!1),g(L),w.current=null,L==="success"&&n&&(C.current=n),D.current=Date.now(),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{p(!1),g(null),T.current=!1,k.current=null},bg)):(f(!0),p(!1),g(null),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{i(null),d(!1),f(!1),T.current=!1,w.current=null,v.current=null},180)),M.current=!1};if(!!!(r||a||h!==null||b.current||y.current.length>0||M.current||N.current)){j.current!==null&&(cancelAnimationFrame(j.current),j.current=null);return}const B=L=>{if(L-S.current<150){j.current=requestAnimationFrame(B);return}S.current=L;const ne=Date.now(),Se=ne-x.current,Ne=b.current&&N.current;if(!Ne&&y.current.length>0&&Se<yg){j.current=requestAnimationFrame(B);return}if(b.current&&M.current)b.current=!1,y.current=[],V("aborted");else if(!Ne&&y.current.length>0){const ve=y.current[y.current.length-1];P(ve.status,ve.permission),x.current=ne,y.current=[]}else if(b.current){b.current=!1,y.current.length>0&&(T.current=!0),y.current=[];let ve=null;if(M.current?ve="aborted":N.current&&(ve="success",T.current=!0),ve==="success"&&n&&C.current===n){i(null),d(!1),f(!1),p(!1),g(null),y.current=[],T.current=!1,w.current=null,b.current=!1,M.current=!1,j.current=null;return}V(ve)}!!(a||h!==null||y.current.length>0||b.current||M.current||N.current)?j.current=requestAnimationFrame(B):j.current=null};return j.current=requestAnimationFrame(B),()=>{j.current!==null&&(cancelAnimationFrame(j.current),j.current=null)}},[r,a,h,o,t,m]),ue.useEffect(()=>()=>{v.current&&clearTimeout(v.current),k.current&&clearTimeout(k.current)},[]),ue.useEffect(()=>{if(typeof window>"u")return;A.current=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0;const V=()=>{A.current=!0},ae=()=>{A.current=!1};return window.addEventListener("focus",V),window.addEventListener("blur",ae),()=>{window.removeEventListener("focus",V),window.removeEventListener("blur",ae)}},[]),ue.useEffect(()=>{const V=()=>{if(typeof document>"u"||typeof Date>"u"||document.visibilityState!=="visible")return;const ae=D.current;(h!==null||a!==null)&&ae&&Date.now()-ae>500&&(i(null),d(!1),f(!1),p(!1),g(null),y.current=[],T.current=!1,w.current=null,b.current=!1,M.current=!1)};return document.addEventListener("visibilitychange",V),window.addEventListener("focus",V),()=>{document.removeEventListener("visibilitychange",V),window.removeEventListener("focus",V)}},[a,h]),!a&&h===null)return null;let O;h==="success"?O="Done":h==="aborted"?O="Aborted":a?O=a.charAt(0).toUpperCase()+a.slice(1):O="Working";const W=c?"assertive":"polite",R=h===null?`${O}...`:O;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":W,"aria-label":O,"data-waiting":c?"true":void 0,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[h===null&&e.jsx(ko,{variant:"shine",className:"typography-ui-header",children:R}),h==="success"&&e.jsx(ko,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}),h==="aborted"&&e.jsx(ko,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"})]})})}const Vi={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},vg=({todo:r})=>{const s=Vi[r.status]||Vi.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:I("flex-1 typography-ui-label",s.textClassName),children:r.content})})},Gi=[],jg=({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=fe(C=>C.currentSessionId),h=Go(C=>f?C.sessionTodos.get(f)??Gi:Gi),g=Go(C=>C.loadTodos),{isMobile:x}=we(),y=x||es();l.useEffect(()=>{f&&g(f)},[f,g]);const b=l.useMemo(()=>{const C={in_progress:0,pending:1,completed:2,cancelled:3};return[...h].filter(D=>D.status!=="cancelled").sort((D,P)=>C[D.status]-C[P.status])},[h]),v=l.useMemo(()=>b.find(C=>C.status==="in_progress")||b.find(C=>C.status==="pending")||null,[b]),k=l.useMemo(()=>{const C=h.filter(P=>P.status!=="cancelled").length;return{completed:h.filter(P=>P.status==="completed").length,total:C}},[h]),j=b.length>0,S=!u&&(n||!o),w=r||j||u,T=l.useRef(null);if(l.useEffect(()=>{if(!p)return;const C=D=>{T.current&&!T.current.contains(D.target)&&m(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[p]),!w)return null;const M=()=>m(C=>!C),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(jr,{size:18,"aria-hidden":"true"})}):null,A=j?e.jsxs("button",{type:"button",onClick:M,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!y&&v?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:v.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[k.completed,"/",k.total]}),p?e.jsx(Kr,{className:"h-3.5 w-3.5"}):e.jsx(yt,{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(jr,{size:16,"aria-hidden":"true"}),"Aborted"]})}):S?e.jsx(wg,{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:T,children:[N,A,p&&j&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:I("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[k.completed,"/",k.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:b.map(C=>e.jsx(vg,{todo:C},C.id))})]})]})]})})},Sg=r=>!r||typeof r!="object"?!1:!!r.synthetic,qo=r=>!Array.isArray(r)||r.length===0?!1:r.every(s=>Sg(s)),kg={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Ng(r){const s=fe(t=>!r||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(r)??"idle");return l.useMemo(()=>{if(s==="idle")return kg;const t=s==="busy",n=s==="cooldown";return{phase:s,isWorking:t||n,isBusy:t,isCooldown:n}},[s])}function Kc(){const r=fe(s=>s.currentSessionId);return Ng(r)}const Cg={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},qi=r=>r.role==="assistant",Mg=r=>r.type==="reasoning",Yc=r=>r.type==="text",Ki=r=>{if(Yc(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},Yi=r=>(Yc(r)||Mg(r),r.time),Ag=r=>{if(r.tool)return r.tool;const s=r;return typeof s.name=="string"?s.name:"tool"};function Xc(){const{currentSessionId:r,messages:s,permissions:t,sessionAbortFlags:n}=fe(da(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=Kc(),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(M=>qi(M.info)&&!qo(M.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const g=[...h].sort((M,N)=>{const A=typeof M.info.time?.created=="number"?M.info.time.created:null,C=typeof N.info.time?.created=="number"?N.info.time.created:null;return A!==null&&C!==null&&A!==C?A-C:M.info.id.localeCompare(N.info.id)}),x=g[g.length-1];let y,b;const v=new Set(["edit","write"]);for(let M=(x.parts??[]).length-1;M>=0;M-=1){const N=x.parts?.[M];if(N)switch(N.type){case"reasoning":{const A=N.time??Yi(N);(!A||typeof A.end>"u")&&!y&&(y="reasoning");break}case"tool":{const A=N.state?.status;if((A==="running"||A==="pending")&&!y){const C=Ag(N);v.has(C)?y="editing":(y="tool",b=C)}break}case"text":{const A=Ki(N)??"";if(typeof A=="string"&&A.trim().length>0){const C=Yi(N);(!C||typeof C.end>"u")&&!y&&(y="text")}break}}}const k={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos"},j=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],S=M=>k[M]??`using ${M}`,w=()=>j[Math.floor(Math.random()*j.length)],T=y==="editing"?"editing file":y==="tool"&&b?S(b):y==="reasoning"?"thinking":y==="text"?"composing":w();return{activePartType:y,activeToolName:b,statusText:T}},[c]),u=l.useMemo(()=>{const h=r,g=h?n?.get(h)??null:null,x=!!(g&&!g.acknowledged);return{wasAborted:x,abortActive:x}},[r,n]),p=l.useMemo(()=>{if(u.wasAborted)return{...Cg,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",x=i;let y="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?y="tooling":y=x?"cooldown":"streaming"),{activity:y,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:g,isCooldown:x,lifecyclePhase:g?"streaming":x?"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:x}},[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(b=>qi(b.info)&&!qo(b.parts));if(g.length===0)return{isActive:h,characterCount:0};const x=g[g.length-1];let y=0;return(x.parts??[]).forEach(b=>{if(b.type!=="text")return;const v=Ki(b)??"";typeof v=="string"&&v.trim().length>0&&(y+=v.length)}),{isActive:h,characterCount:y}},[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 Dg=8,Eg=r=>r==="primary"||r==="all"||r===void 0||r===null,No=({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,x]=l.useState(!1),[y,b]=l.useState(""),[v,k]=l.useState(null),j=l.useRef(null),S=l.useRef(null),w=l.useRef(null),T=l.useRef(null),M=l.useRef(null),N=fe(G=>G.sendMessage),A=fe(G=>G.currentSessionId),C=fe(G=>G.abortCurrentOperation),D=fe(G=>G.acknowledgeSessionAbort),P=fe(G=>G.abortPromptSessionId),O=fe(G=>G.abortPromptExpiresAt),W=fe(G=>G.clearAbortPrompt),R=fe(G=>G.attachedFiles),V=fe(G=>G.addAttachedFile),ae=fe(G=>G.addServerFile),K=fe(G=>G.clearAttachedFiles),B=fe(G=>G.saveSessionAgentSelection),L=fe(G=>G.consumePendingInputText),ne=fe(G=>G.pendingInputText),{currentProviderId:Se,currentModelId:Ne,currentAgentName:de,setAgent:ge,getVisibleAgents:ve}=St(),Ae=ve(),{isMobile:Te}=we(),{working:Pe}=Xc(),[Re,ce]=l.useState(!1),Ie=l.useRef(null),ie=l.useRef(!1),Ce=l.useRef(!1),qe=l.useCallback(G=>{if(!Te||G.pointerType!=="touch")return;const _e=j.current;if(!_e||document.activeElement===_e)return;G.preventDefault(),G.stopPropagation();const Ve=document.scrollingElement;Ve&&Ve.scrollTop!==0&&(Ve.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{_e.focus({preventScroll:!0})}catch{_e.focus()}const lt=_e.value.length;try{_e.setSelectionRange(lt,lt)}catch{}},[Te]);l.useEffect(()=>{if(ne!==null){const G=L();G&&(n(G),setTimeout(()=>{j.current?.focus()},0))}},[ne,L]);const J=l.useMemo(()=>{if(de)return Ae.find(G=>G.name===de)},[Ae,de]),E=l.useMemo(()=>{const G=J?.permission?.edit;let _e="ask";(G==="allow"||G==="ask"||G==="deny"||G==="full")&&(_e=G);const Ve=J?J.tools?.edit!==!1:!1;return(!J||!Ve)&&(_e="deny"),_e},[J]),re=fe(l.useCallback(G=>!A||!de?void 0:G.sessionAgentEditModes.get(A)?.get(de),[A,de])),q=J?.permission?.webfetch,F=J?.permission?.bash,$=l.useMemo(()=>Gc({agentDefaultEditMode:E,webfetchPermission:q,bashPermission:F}),[E,q,F]),U=!!(A&&de),H=l.useMemo(()=>U&&re&&$.modeAvailability[re]?re:$.cascadeDefaultMode,[$,U,re]),X=l.useMemo(()=>Lr(H),[H]),Y=l.useCallback(G=>es()?`color-mix(in srgb, ${G} 55%, transparent)`:G,[]),Ee=l.useMemo(()=>{const G=es()?1:2;if(!X)return{borderWidth:G};const _e=X.border??X.text;return{borderColor:Y(_e),borderWidth:G}},[X,Y]),Be=t.trim()||R.length>0,ct=Pe.isWorking,ot=l.useMemo(()=>A?P===A&&!!O:!1,[P,O,A]),Je=async G=>{if(G?.preventDefault(),!Be||!A)return;const _e=t.replace(/^\n+|\n+$/g,"");s?.({instant:!0,force:!0});const Ve=_e.trimStart();if(Ve.startsWith("/")&&Ve.slice(1).trim().split(/\s+/)[0]?.toLowerCase()==="summarize"&&s?.({instant:!0,force:!0}),!Se||!Ne){console.warn("Cannot send message: provider or model not selected");return}const{sanitizedText:lt,mention:tt}=gg(_e,Ae),z=tt?.name,Z=R.map(te=>({...te}));Z.length>0&&K(),n(""),Te&&j.current?.blur(),await N(lt,Se,Ne,de,Z,z).catch(te=>{const he=te instanceof Error?te.message:typeof te=="string"?te:String(te??""),He=he.toLowerCase();console.error("Message send failed:",he||te),!(He.includes("timeout")||He.includes("timed out")||He.includes("may still be processing")||He.includes("being processed")||He.includes("failed to fetch")||He.includes("networkerror")||He.includes("network error")||He.includes("gateway timeout")||He==="failed to send message")&&(Z.length>0&&zs.setState({attachedFiles:Z}),xe.error(he||"Message failed to send. Attachments restored."))}),Te||j.current?.focus()},it=G=>{if(p&&T.current&&(G.key==="Enter"||G.key==="ArrowUp"||G.key==="ArrowDown"||G.key==="Escape"||G.key==="Tab")){G.preventDefault(),T.current.handleKeyDown(G.key);return}if(g&&M.current&&(G.key==="Enter"||G.key==="ArrowUp"||G.key==="ArrowDown"||G.key==="Escape"||G.key==="Tab")){G.preventDefault(),M.current.handleKeyDown(G.key);return}if(i&&w.current&&(G.key==="Enter"||G.key==="ArrowUp"||G.key==="ArrowDown"||G.key==="Escape"||G.key==="Tab")){G.preventDefault(),w.current.handleKeyDown(G.key);return}if(G.key==="Tab"&&!p&&!i){G.preventDefault(),pt();return}G.key==="Enter"&&!G.shiftKey&&!Te&&(G.preventDefault(),Je())},dt=l.useCallback(()=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null),ce(!0),Ie.current=setTimeout(()=>{ce(!1),Ie.current=null},1800)},[]),at=l.useCallback(()=>{W(),dt(),C()},[C,W,dt]),pt=()=>{const G=Ae.filter(tt=>Eg(tt.mode));if(G.length<=1)return;const Ve=(G.findIndex(tt=>tt.name===de)+1)%G.length,lt=G[Ve];ge(lt.name),A&&B(A,lt.name)},ut=l.useCallback(()=>{const G=j.current;if(!G)return;G.style.height="auto";const _e=G.ownerDocument?.defaultView,Ve=_e?_e.getComputedStyle(G):null,lt=Ve?parseFloat(Ve.lineHeight):NaN,tt=Ve?parseFloat(Ve.paddingTop):NaN,z=Ve?parseFloat(Ve.paddingBottom):NaN,Z=22,he=Number.isNaN(tt)||Number.isNaN(z)?16:tt+z,Qe=(Number.isNaN(lt)?Z:lt)*Dg+he,ye=G.scrollHeight||G.offsetHeight,Oe=Math.min(ye,Qe);G.style.height=`${Oe}px`,G.style.maxHeight=`${Qe}px`,k(Ke=>Ke&&Ke.height===Oe&&Ke.maxHeight===Qe?Ke:{height:Oe,maxHeight:Qe})},[]);l.useLayoutEffect(()=>{ut()},[ut,t,Te]);const pe=l.useCallback((G,_e)=>{if(G.startsWith("/")){const z=G.indexOf(" "),Z=G.indexOf(`
|
|
67
|
-
`),te=Math.min(z===-1?G.length:z,Z===-1?G.length:Z);if(_e<=te&&z===-1){const he=G.substring(1,te);h(he),m(!0),c(!1),x(!1)}else m(!1);return}m(!1);const Ve=G.substring(0,_e),lt=Ve.lastIndexOf("#");if(lt!==-1){const z=lt>0?Ve[lt-1]:null,Z=Ve.substring(lt+1),te=Z.includes(" ")||Z.includes(`
|
|
68
|
-
`);if((!z||/\s/.test(z))&&!te){b(Z),x(!0),c(!1);return}}x(!1),b("");const tt=Ve.lastIndexOf("@");if(tt!==-1){const z=Ve.substring(tt+1);!z.includes(" ")&&!z.includes(`
|
|
69
|
-
`)?(u(z),c(!0)):c(!1)}else c(!1)},[b,h,u,x,m,c]),_=l.useCallback(G=>{if(!G)return;const _e=j.current;if(!_e){const Z=t+G;n(Z),pe(Z,Z.length),requestAnimationFrame(()=>ut());return}const Ve=_e.selectionStart??t.length,lt=_e.selectionEnd??t.length,tt=`${t.substring(0,Ve)}${G}${t.substring(lt)}`;n(tt);const z=Ve+G.length;requestAnimationFrame(()=>{const Z=j.current;Z&&(Z.selectionStart=z,Z.selectionEnd=z),ut()}),pe(tt,z)},[ut,t,pe]),se=G=>{const _e=G.target.value,Ve=G.target.selectionStart??_e.length;n(_e),ut(),pe(_e,Ve)},ee=l.useCallback(async G=>{const _e=new Map;Array.from(G.clipboardData.files||[]).forEach(z=>{z.type.startsWith("image/")&&_e.set(`${z.name}-${z.size}`,z)}),Array.from(G.clipboardData.items||[]).forEach(z=>{if(z.kind==="file"&&z.type.startsWith("image/")){const Z=z.getAsFile();Z&&_e.set(`${Z.name}-${Z.size}`,Z)}});const Ve=Array.from(_e.values());if(Ve.length===0||!A)return;G.preventDefault();const lt=G.clipboardData.getData("text");lt&&_(lt);let tt=0;for(const z of Ve){const Z=fe.getState().attachedFiles.length;try{await V(z),fe.getState().attachedFiles.length>Z&&(tt+=1)}catch(te){console.error("Clipboard image attach failed",te),xe.error(te instanceof Error?te.message:"Failed to attach image from clipboard")}}tt>0&&xe.success(`Attached ${tt} image${tt>1?"s":""} from clipboard`)},[V,A,_]),me=G=>{const _e=j.current?.selectionStart||0,lt=t.substring(0,_e).lastIndexOf("@");if(lt!==-1){const tt=t.substring(0,lt)+G.name+t.substring(_e);n(tt)}c(!1),u(""),j.current?.focus()},Q=G=>{const Ve=j.current?.selectionStart??t.length,tt=t.substring(0,Ve).lastIndexOf("#");if(tt!==-1){const z=t.substring(0,tt)+`#${G} `+t.substring(Ve);n(z);const Z=tt+G.length+2;requestAnimationFrame(()=>{j.current&&(j.current.selectionStart=Z,j.current.selectionEnd=Z),ut(),pe(z,Z)})}x(!1),b(""),j.current?.focus()},oe=G=>{n(`/${G.name} `);const _e=j.current;_e&&(_e._commandMetadata=G),m(!1),h(""),setTimeout(()=>{j.current&&(j.current.focus(),j.current.setSelectionRange(j.current.value.length,j.current.value.length))},0)};l.useEffect(()=>{A&&j.current&&!Te&&j.current.focus()},[A,Te]),l.useEffect(()=>{P&&P!==A&&W()},[P,A,W]);const le=G=>{G.preventDefault(),G.stopPropagation(),A&&!o&&a(!0)},Me=G=>{G.preventDefault(),G.stopPropagation(),G.currentTarget===G.target&&a(!1)},$e=async G=>{if(G.preventDefault(),G.stopPropagation(),a(!1),!A)return;const _e=Array.from(G.dataTransfer.files);let Ve=0;for(const lt of _e){const tt=fe.getState().attachedFiles.length;try{await V(lt),fe.getState().attachedFiles.length>tt&&(Ve+=1)}catch(z){console.error("File attach failed",z),xe.error(z instanceof Error?z.message:"Failed to attach file")}}Ve>0&&xe.success(`Attached ${Ve} file${Ve>1?"s":""}`)},kt=l.useCallback(async G=>{let _e=0;for(const Ve of G){const lt=fe.getState().attachedFiles.length;try{await ae(Ve.path,Ve.name),fe.getState().attachedFiles.length>lt&&(_e+=1)}catch(tt){console.error("Server file attach failed",tt),xe.error(tt instanceof Error?tt.message:"Failed to attach file")}}_e>0&&xe.success(`Attached ${_e} file${_e>1?"s":""}`)},[ae]),bt=l.useRef(null),[Dt,Nt]=l.useState(!1),mt=l.useCallback(async G=>{let _e=0;const Ve=Array.isArray(G)?G:Array.from(G);for(const lt of Ve){const tt=fe.getState().attachedFiles.length;try{await V(lt),fe.getState().attachedFiles.length>tt&&(_e+=1)}catch(z){console.error("File attach failed",z),xe.error(z instanceof Error?z.message:"Failed to attach file")}}_e>0&&xe.success(`Attached ${_e} file${_e>1?"s":""}`)},[V]),wt=l.useCallback(async()=>{try{const _e=await(await fetch("/api/vscode/pick-files")).json(),Ve=Array.isArray(_e?.files)?_e.files:[],lt=Array.isArray(_e?.skipped)?_e.skipped:[];if(lt.length>0){const z=lt.map(Z=>`${Z?.name||"file"}: ${Z?.reason||"skipped"}`).join(`
|
|
70
|
-
`);xe.error(`Some files were skipped:
|
|
71
|
-
${z}`)}const tt=Ve.map(z=>{if(!z?.dataUrl)return null;try{const[Z,te]=z.dataUrl.split(","),he=z.mimeType||Z?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!te)return null;const He=atob(te),Qe=new Uint8Array(He.length);for(let Oe=0;Oe<He.length;Oe++)Qe[Oe]=He.charCodeAt(Oe);const ye=new Blob([Qe],{type:he});return new File([ye],z.name||"file",{type:he})}catch(Z){return console.error("Failed to decode VS Code picked file",Z),null}}).filter(Boolean);tt.length>0&&await mt(tt)}catch(G){console.error("VS Code file pick failed",G),xe.error(G instanceof Error?G.message:"Failed to pick files in VS Code")}},[mt]),je=l.useCallback(()=>{if(es()){wt();return}bt.current?.click()},[wt]),ze=l.useCallback(async G=>{const _e=G.target.files;_e&&(await mt(_e),G.target.value="")},[mt]),Ge="gap-x-1.5 gap-y-0",Le=es(),ft=Te?"px-1.5 py-1.5":Le?"px-1.5 py-1":"px-2.5 py-1.5",Ct=Te?"h-9 w-9":Le?"h-[22px] w-[22px]":"h-7 w-7",vt=Te?"h-5 w-5":Le?"h-4 w-4":"h-[18px] w-[18px]",be=I(Ct,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Fe=!Te&&ot&&ct?e.jsx("button",{type:"button",onClick:at,className:I(be,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(jr,{className:I(vt)})}):e.jsx("button",{type:Te?"button":"submit",disabled:!Be||!A,onPointerDownCapture:G=>{!Te||G.pointerType!=="touch"||!Be||!A||(Ce.current=!0,G.preventDefault(),G.stopPropagation(),Je())},onClick:G=>{if(Te){if(Ce.current){Ce.current=!1;return}G.preventDefault(),Je()}},className:I(be,Be&&A?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Fu,{className:I(vt)})}),Ze=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:bt,type:"file",multiple:!0,className:"hidden",onChange:ze,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(ag,{onFilesSelected:kt,multiSelect:!0,presentation:Te||Le?"modal":"dropdown",open:Dt,onOpenChange:Nt,children:Te||Le?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:be,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(Pu,{className:I(vt,"text-current")})})}),e.jsxs(Zt,{align:"start",children:[e.jsxs(gt,{onSelect:()=>{requestAnimationFrame(()=>je())},children:[e.jsx(_o,{}),"Attach files"]}),e.jsxs(gt,{onSelect:()=>{requestAnimationFrame(()=>{Nt(!0)})},children:[e.jsx(Ru,{}),"Attach from project"]})]})]})]})]}),Mt=r?e.jsx("button",{type:"button",onClick:r,className:be,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(zr,{className:I(vt,"text-current")})}):null,ht=e.jsxs(e.Fragment,{children:[Ze,Mt]}),$t=Pe.statusText;l.useEffect(()=>{const G=!!Pe.wasAborted;!ie.current&&G&&!Re&&(dt(),A&&D(A)),ie.current=G},[D,A,Re,dt,Pe.wasAborted]),l.useEffect(()=>()=>{Ie.current&&(clearTimeout(Ie.current),Ie.current=null)},[]);const zt=Te&&ct;return e.jsxs("form",{onSubmit:Je,className:"pt-0 pb-4 bottom-safe-area",children:[e.jsx(jg,{isWorking:Pe.isWorking,statusText:$t,isWaitingForPermission:Pe.isWaitingForPermission,wasAborted:Pe.wasAborted,abortActive:Pe.abortActive,completionId:Pe.lastCompletionId,isComplete:Pe.isComplete,showAbort:zt,onAbort:at,showAbortStatus:Re}),e.jsxs("div",{ref:S,className:I("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:le,onDragLeave:Me,onDrop:$e,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:be,onClick:()=>je(),title:"Attach files","aria-label":"Attach files",children:e.jsx(_o,{className:I(vt,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(tg,{}),e.jsxs("div",{className:I("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Ee,children:[p&&e.jsx(Wc,{ref:T,searchQuery:f,onCommandSelect:oe,onClose:()=>m(!1)}),g&&e.jsx(Uc,{ref:M,searchQuery:y,onAgentSelect:Q,onClose:()=>x(!1)}),i&&e.jsx(sg,{ref:w,searchQuery:d,onFileSelect:me,onClose:()=>c(!1)}),e.jsx(sr,{ref:j,"data-chat-input":"true",value:t,onChange:se,onKeyDown:it,onPaste:ee,onPointerDownCapture:qe,placeholder:A?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!A,className:I("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",Te?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:v?`${v.height}px`:void 0,maxHeight:v?`${v.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:I("rounded-b-xl bg-transparent",ft,Te?"flex items-center gap-x-1.5":I("flex items-center justify-between",Ge)),"data-chat-input-footer":"true",children:Te?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:ht}),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(Wi,{className:I("w-full flex items-center justify-end min-w-0")})}),Fe]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:I("flex items-center flex-shrink-0",Ge),children:ht}),e.jsxs("div",{className:I("flex items-center flex-1 justify-end",Ge,"md:gap-x-3"),children:[e.jsx(Wi,{className:I("flex-1 min-w-0 justify-end")}),Fe]})]})})]})]})]})};function Co({className:r,...s}){return e.jsx("div",{"data-slot":"skeleton",className:I("bg-accent animate-pulse rounded-xl",r),...s})}const Ko=({className:r="",width:s=70,height:t=70,isAnimated:n=!1})=>{const o=ka();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})]})},Tg={'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"}},Ig={'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 Hs{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Hs.instance||(Hs.instance=new Hs),Hs.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 Jc(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 Gt=({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:I("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",s),children:r})},Fg=({isUser:r,providerID:s,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=Mc(s);return e.jsx(Gt,{children:e.jsx("div",{className:I("pl-3","mb-2"),children:e.jsx("div",{className:I("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(Xn,{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(Kn,{className:"h-4 w-4",style:{color:`var(${Bs(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:I("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:I("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",Bs(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},Pg=l.memo(Fg),Xi=(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},Ji=()=>{if(!es()||typeof window>"u")return xi;const r=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(r?.light&&r?.dark){const s=Xi({...r.light},`vscode-shiki-light:${String(r.light?.name??"theme")}`),t=Xi({...r.dark},`vscode-shiki-dark:${String(r.dark?.name??"theme")}`);return[s,t]}return xi},Zc=()=>{const[r,s]=l.useState(Ji);return l.useEffect(()=>{if(!es()||typeof window>"u")return;const t=n=>{s(Ji())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),r},Qc=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}},ed=({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
|
-
`)},Rg=({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
|
-
`)},Lg=({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
|
-
`)},_g=(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)},Og=({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=Qc(d),p=c==="csv"?ed(u):Rg(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(_s,{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"})]})]})},Bg=({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=Qc(i),d=a==="csv"?ed(c):Lg(c);_g(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($r,{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"})]})]})},$g=({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(Og,{tableRef:t}),e.jsx(Bg,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:I("w-full border-collapse border border-border",s),"data-streamdown":"table",children:r})})]})},zg=({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[x,...y]=g.split(";").map(v=>v.trim()).filter(Boolean),b={};for(const v of y){const k=v.indexOf(":");if(k===-1)continue;const j=v.slice(0,k).trim(),S=v.slice(k+1).trim();!j.startsWith("--")||S.length===0||(b[j]=S)}return{value:x,vars:b}},f=m(t.backgroundColor);f.value&&(p.backgroundColor=f.value,p["--shiki-light-bg"]=f.value);for(const[g,x]of Object.entries(f.vars))p[g]=x;const h=m(t.color);h.value&&(p.color=h.value,p["--shiki-light"]=h.value);for(const[g,x]of Object.entries(h.vars))p[g]=x;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:I(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(_s,{className:"size-3.5"})})})]})},td={pre:zg,table:$g},Hg=({content:r,part:s,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const c=Zc(),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:I("break-words",o),children:e.jsx(_l,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:td,children:r})});return n?e.jsx(Gt,{children:p},d):p},Gr=({content:r,className:s,variant:t="assistant"})=>{const n=Zc(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:I("break-words",s),children:e.jsx(_l,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:td,children:r})})},Wg={thinking:{label:"Thinking",Icon:Kn},justification:{label:"Justification",Icon:sa}},sd=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(),Ug=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},Ea=({text:r,variant:s,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>Ug(r),[r]),{label:c,Icon:d}=Wg[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:I("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:I("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:I("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(yt,{className:"h-3.5 w-3.5"}):e.jsx(ns,{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:I("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})})]})},rd=({part:r,onContentChange:s,messageId:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>sd(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Ea,{text:a,variant:"thinking",onContentChange:s,blockId:r.id||`${t}-reasoning`}):null},Vg=r=>sd(r),Gg=({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(Ea,{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(Hg,{content:u,part:r,messageId:s,isAnimated:n,isStreaming:!1})},r.id||`${s}-text`)},qg=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;if(!h||i)return;const g=()=>{u(h.scrollHeight>h.clientHeight)};g();const x=new ResizeObserver(g);return x.observe(h),()=>x.disconnect()},[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),x=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[g,e.jsx("a",{href:qg(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:y=>y.stopPropagation(),children:t.token}),x]})};return e.jsx("div",{className:I("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`)},Yg=l.memo(Kg),Xg=r=>{let s=r.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},nd=r=>r?r.includes("<file_diagnostics>")||r.includes("This file has errors")||r.includes("please fix"):!1,Jg=r=>r?r.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Zi=(r,s)=>!r||typeof r!="object"?String(r):Fp(r,s||""),Mo=(r,s,t)=>{let n=Xg(r);if((s==="edit"||s==="multiedit")&&nd(n)&&(n=Jg(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Zg=(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:I("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:Es.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}},Qg=(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:I("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Es.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:I("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:I("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}},ex=(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:I("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Es.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:I("font-medium text-muted-foreground",s?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:I("pl-4 grid gap-1",s?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:I("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}},tx=(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:I("space-y-3 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Es.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}},sx=(r,s,t)=>{try{return e.jsx("div",{className:I("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:Es.tool.popup,children:e.jsx(Gr,{content:r,variant:"tool"})})}catch{return null}},od=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},Yo=(r,s,t)=>Ep(s,r,t),ad=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(Lu,{className:s}):t==="write"||t==="create"||t==="file_write"?e.jsx(Ol,{className:s}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(Oo,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Vs,{className:s}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(ss,{className:s}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(_u,{className:s}):t==="glob"?e.jsx(Ou,{className:s}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(Bo,{className:s}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(Bo,{className:s}):t==="todowrite"||t==="todoread"?e.jsx(Bu,{className:s}):t.startsWith("git")?e.jsx(Yt,{className:s}):e.jsx(ua,{className:s})},rx=(r,s,t=Date.now())=>{const o=(s?s-r:t-r)/1e3;return`${(o<.05&&s!==void 0?.1:o).toFixed(1)}s`},nx=({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:rx(r,s,n)})},ox=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}},Xo=(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},ax=(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 Xo(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 Xo(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:""},Jo=({children:r,maxHeightClass:s="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(Xe,{outerClassName:I("w-full min-w-0 flex-none overflow-hidden",s,n),className:I("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})}),ix=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"},lx=r=>r.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),cx=({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"?lx(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:I("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(Jo,{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",x=ix(f),y=wa(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:ad(g)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:y}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:x})]},f.id??`${g}-${h}`)})]})}):null,c?e.jsxs("div",{className:I("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(yt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(ns,{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(Jo,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:i,variant:"tool"})})}):null]}):null]})},dx=({diff:r,syntaxTheme:s,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:od(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:I("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(ys,{style:s,language:or(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))}),ux=({content:r,syntaxTheme:s,filePath:t,displayPath:n})=>{const o=r.split(`
|
|
85
|
-
`),a=or(t??"")||Yo(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(ys,{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))})]})},mx=({content:r,filePath:s,displayPath:t})=>{const n=Ip(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"}})})]})},fx=({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,x=r.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,y=r.tool==="write"&&!!x,b=g?fc(g):!1,v=y?g?Xo(g,o,n):"New file":null,k=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=k.trim().length>0,S=(T,M)=>e.jsx(Jo,{maxHeightClass:M?.maxHeightClass,className:M?.className,disableHorizontal:M?.disableHorizontal,outerClassName:M?.outerClassName,children:T}),w=()=>{if(r.tool==="todowrite"||r.tool==="todoread"){if(s.status==="completed"&&m){const T=tx(f,{unstyled:!0});return S(T??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 T=Zg(f,{unstyled:!0});return S(T??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 T=Qg(f,n,{unstyled:!0});return S(T??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 T=ex(f,n,{unstyled:!0});return S(T??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 S(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:f,variant:"tool"})}));if((r.tool==="web-search"||r.tool==="websearch"||r.tool==="search_web")&&m){const T=sx(f,t,{unstyled:!0});return S(T??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 S(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:f,variant:"tool"})}));if((r.tool==="edit"||r.tool==="multiedit")&&(!m&&h||f.trim().length===0||nd(f))&&h)return S(e.jsx(dx,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(m&&f.trim()){if(r.tool==="read"){const T=Mo(f,r.tool,d),M=T.split(`
|
|
86
|
-
`),N=typeof u?.offset=="number"?u.offset:0,A=typeof u?.limit=="number"?u.limit:void 0,C=D=>D.trim().startsWith("(");return S(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:M.map((D,P)=>{const O=C(D),W=N+P+1,R=!O&&(A===void 0||P<A);return e.jsxs("div",{className:I("typography-code font-mono flex w-full min-w-0",O&&"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:R?W:""}),e.jsx("div",{className:"flex-1 min-w-0",children:O?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:D}):e.jsx(ys,{style:t,language:Yo(T,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:D})})]},P)})}),{className:"p-1"})}return S(e.jsx(ys,{style:t,language:Yo(Mo(f,r.tool,d),r.tool,u),PreTag:"div",customStyle:{...gn.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Mo(f,r.tool,d)}),{className:"p-1"})}return S(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:I("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"?w():e.jsxs(e.Fragment,{children:[y&&b?e.jsx("div",{className:"my-1",children:S(e.jsx(mx,{content:x,filePath:g,displayPath:v??"New file"}))}):y?e.jsx("div",{className:"my-1",children:S(e.jsx(ux,{content:x,syntaxTheme:t,filePath:g,displayPath:v??"New file"}))}):j?e.jsx("div",{className:"my-1",children:S(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:k}),{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:"}),w()]}),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})]})]})})},Sn=({part:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=r.state,u=jt(O=>O.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 x=d,y=x.metadata,b=x.input,v=x.time,k=l.useRef({}),j=l.useRef(r.id);if(j.current!==r.id&&(j.current=r.id,k.current={}),p){if(typeof v?.start=="number"){const O=k.current.start;(typeof O!="number"||v.start<O)&&(k.current.start=v.start)}typeof v?.end=="number"&&(k.current.end=v.end)}const S=p?k.current.start??v?.start:v?.start,w=p?k.current.end??v?.end:v?.end,T=l.useMemo(()=>{if(!p)return[];const O=y?.summary;return Array.isArray(O)?O.filter(W=>typeof W=="object"&&W!==null):[]},[p,y]),M=l.useRef(T.length);l.useEffect(()=>{p&&M.current!==T.length&&(M.current=T.length,a?.("structural"))},[p,a,T.length]);const N=r.tool==="edit"||r.tool==="multiedit"?ox(y):null,A=ax(r,d,o,u),C=wa(r.tool).displayName,D=l.useContext(va),P=O=>{if(p||!D?.editor){t(r.id);return}let W;if((r.tool==="edit"||r.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(r.tool))&&(W=b?.filePath||b?.file_path||b?.path||y?.filePath||y?.file_path||y?.path),typeof W=="string"){O.stopPropagation();let R=W;W.startsWith("/")||(R=u.endsWith("/")?u+W:u+"/"+W),D.editor.openFile(R)}else t(r.id)};return!m&&!p?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:I("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:P,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:O=>{O.stopPropagation(),t(r.id)},children:[e.jsx("div",{className:I("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:!p&&h?{color:"var(--status-error)"}:{},children:ad(r.tool)}),e.jsx("div",{className:I("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(yt,{className:"h-3.5 w-3.5"}):e.jsx(ns,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!p&&h?{color:"var(--status-error)"}:{},children:C})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[A&&e.jsx("span",{className:I("truncate",o&&"max-w-[120px]"),children:A}),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 S=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(nx,{start:S,end:typeof w=="number"?w:void 0,active:!!(p&&f&&typeof w!="number")})})]})]}),p&&(T.length>0||f||m)?e.jsx(cx,{entries:T,isExpanded:s,hasPrevTool:i,hasNextTool:c,output:typeof x.output=="string"?x.output:void 0}):null,!p&&s?e.jsx(fx,{part:r,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c}):null]})},px=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(),hx=({part:r,messageId:s,onContentChange:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>px(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Ea,{text:a,variant:"justification",onContentChange:t,blockId:r.id||`${s}-justification`}):null},gx=l.memo(hx),xx=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(", ")},Qi=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}),yx=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},bx=({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 b=m.current===!1;m.current=s,c?.("structural"),s&&b&&h(v=>v+1)},[s,c]);const g=l.useMemo(()=>Qi(d?r.filter(b=>b.part.id&&u.has(b.id)):r),[r,d,u]),x=xx(g),y=yx(g);return g.length===0?null:e.jsx(Gt,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:I("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:I("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(Dl,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:I("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(yt,{className:"h-3.5 w-3.5"}):e.jsx(ns,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(x||p)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[x&&e.jsx("span",{className:"truncate block",children:x}),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:I("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((b,v)=>{const k=b.part.id||`group-part-${v}`,j=y[k],S=`${k}-exp${f}`;switch(b.kind){case"tool":return e.jsx(Gt,{children:e.jsx(Sn,{part:b.part,isExpanded:a.has(k),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:j?.hasPrev??!1,hasNextTool:j?.hasNext??!1})},S);case"reasoning":return e.jsx(Gt,{children:e.jsx(rd,{part:b.part,messageId:b.messageId,onContentChange:c})},S);case"justification":return e.jsx(Gt,{children:e.jsx(gx,{part:b.part,messageId:b.messageId,onContentChange:c})},S);default:return null}})})]})})},wx=l.memo(bx),vx=({isMigrating:r,children:s,className:t})=>e.jsx("div",{className:I("w-full overflow-hidden",r&&"pointer-events-none",t),style:r?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:s}),Ao=l.memo(vx),id=r=>{const s=r,t=s.text;return typeof t=="string"?t:s.content||s.value||""},ld=r=>{if(r.type!=="text")return!1;const s=id(r);return!s||s.trim().length===0},jx=(r,s={})=>{const{includeReasoning:t=!0}=s;return r.filter(n=>!!n.synthetic||!t&&n.type==="reasoning"?!1:!(n.type==="patch"))},Sx=(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}},kx=new Set(["task"]),mr=r=>typeof r=="string"&&kx.has(r.toLowerCase()),Nx=({messageId:r,parts:s,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d,onRevert:u,isFirstMessage:p})=>{const[m,f]=l.useState(!1),h=l.useRef(null),g=l.useMemo(()=>s.filter(M=>M.type!=="text"?!1:!ld(M)),[s]),x=d?.token;let y=!1;const b=!!a,v=!!i,k=!!(n??t),j=!!o,S=l.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),w=l.useCallback(()=>{!k||!b||!j||typeof window>"u"||(S(),f(!0),h.current=window.setTimeout(()=>{f(!1),h.current=null},1800))},[b,S,j,k]);l.useEffect(()=>{j||(f(!1),S())},[S,j]);const T=l.useCallback(M=>{!a||!j||(M.stopPropagation(),M.preventDefault(),a(),k&&w())},[j,k,a,w]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:k&&b&&j?w:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:g.map((M,N)=>{let A;return d&&x&&!y&&id(M).includes(x)&&(A=d,y=!0),e.jsx(Gt,{children:e.jsx(Yg,{part:M,messageId:r,isMobile:t,agentMention:A})},`user-text-${N}`)})}),e.jsx(zc,{files:s,onShowPopup:c}),b&&j||u&&!p?e.jsxs("div",{className:I("mt-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",m&&"opacity-100 pointer-events-auto"),children:[u&&!p&&e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Revert to this message",onPointerDown:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),u()},children:e.jsx(Bl,{className:"h-3.5 w-3.5"})})}),e.jsx(et,{sideOffset:6,children:"Revert from here"})]}),b&&j&&e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":m||v?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:M=>M.stopPropagation(),onClick:T,onFocus:()=>f(!0),onBlur:()=>{v||f(!1)},children:v?e.jsx(Tt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(_s,{className:"h-3.5 w-3.5"})})}),e.jsx(et,{sideOffset:6,children:"Copy message"})]})]}):null]})},Cx=({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:x=!1,onCopyMessage:y,copiedMessage:b=!1,onAuxiliaryContentComplete:v,showReasoningTraces:k=!1,turnGroupingContext:j})=>{const[S,w]=l.useState(!1),T=l.useRef(null),M=!!y,N=!!b,A=!!(a??o),C=!t,D=l.useMemo(()=>s.filter(je=>!ld(je)).filter(je=>je.type!=="compaction"),[s]),P=l.useMemo(()=>D.filter(je=>je.type==="tool"),[D]),O=l.useMemo(()=>D.filter(je=>je.type==="text"),[D]),W=fe(je=>je.createSessionFromAssistantMessage),R=j?.isLastAssistantInTurn??!1,V=l.useMemo(()=>s.some(je=>je.type==="step-finish"&&je.reason==="stop"),[s]),ae=P.length>0,K=l.useMemo(()=>P.some(je=>{const Ge=(je.state??{})?.status;return Ge==="pending"||Ge==="running"||Ge==="started"}),[P]),B=l.useCallback(je=>{const ze=je.state??{},Ge=ze?.status;if(Ge==="pending"||Ge==="running"||Ge==="started")return!1;const Le=ze?.time??{},ft=typeof Le?.end=="number"?Le.end:void 0,Ct=typeof Le?.start=="number"?Le.start:void 0;return!(typeof ft!="number"||typeof Ct=="number"&&ft<Ct)},[]),L=l.useMemo(()=>P.length===0?!0:K?!1:P.every(je=>B(je)),[P,K,B]),ne=l.useMemo(()=>O.length===0?!0:O.every(je=>typeof je.time?.end=="number"),[O]),Se=l.useMemo(()=>D.filter(je=>je.type==="reasoning"),[D]),Ne=l.useMemo(()=>Se.length===0?!0:Se.every(je=>typeof je.time?.end=="number"),[Se]),ge=l.useMemo(()=>{let je=0,ze=0;return D.forEach(Ge=>{Ge.type==="step-start"?je+=1:Ge.type==="step-finish"&&(ze+=1)}),{stepStarts:je,stepFinishes:ze,hasOpenStep:je>ze}},[D]).hasOpenStep,ve=Se.length>0&&ae&&(K||ge||!L),Ae=l.useMemo(()=>ae?O.length===0?ge||K||!L:!0:O.length>0?ve:!1,[O.length,ge,K,ae,ve,L]),Te=C||Ae&&(!ne||!L||K||ge)||ve,Pe=C||ae&&(K||ge||!L),Re=C||ve,ce=ae||Se.length>0,Ie=O.length===0,ie=ce&&Ie&&!Pe&&!Re&&L&&Ne,Ce=l.useRef(!1),qe=l.useRef(!1);l.useEffect(()=>{qe.current=!1},[r]),l.useEffect(()=>{if(!ie){Ce.current=!1;return}Ce.current||(Ce.current=!0,v?.())},[ie,v]),l.useEffect(()=>{if(C){qe.current=!1;return}if(ae){qe.current=!1;return}Se.length!==0&&(Re||!Ne||qe.current||(qe.current=!0,h?.("structural")))},[C,ae,h,Ne,Se.length,Re]);const J=!!x&&!C,E=l.useCallback(()=>{T.current!==null&&typeof window<"u"&&(window.clearTimeout(T.current),T.current=null)},[]),re=l.useCallback(()=>{!A||!M||!J||typeof window>"u"||(E(),w(!0),T.current=window.setTimeout(()=>{w(!1),T.current=null},1800))},[M,E,J,A]);l.useEffect(()=>{J||(w(!1),E())},[E,J]);const q=l.useCallback(je=>{!y||!J||(je.stopPropagation(),je.preventDefault(),y(),A&&re())},[J,A,y,re]),F=l.useCallback(je=>{je.stopPropagation(),je.preventDefault(),W&&W(r)},[W,r]);l.useEffect(()=>()=>{E()},[E]);const $=l.useMemo(()=>{const je={},ze=P.filter(Ge=>mr(Ge.tool)||Pe?!1:B(Ge));return ze.forEach((Ge,Le)=>{je[Ge.id]={hasPrev:Le>0,hasNext:Le<ze.length-1}}),je},[P,Pe,B]),U=l.useMemo(()=>j?.activityParts??[],[j]),H=l.useMemo(()=>j?U.filter(je=>je.messageId===r):[],[U,r,j]),X=l.useMemo(()=>{const je=new Map;return H.forEach(ze=>{je.set(ze.part,ze)}),je},[H]),Y=l.useMemo(()=>j?(k?U:U.filter(ze=>ze.kind==="tool")).filter(ze=>{if(ze.kind!=="tool")return!0;const Ge=ze.part.tool;return!mr(Ge)}):[],[U,k,j]),[Ee,Be]=l.useState(!1);l.useEffect(()=>{j&&Y.length>1&&Be(!0)},[j,Y.length]);const ct=!!(j&&Ee),ot=l.useMemo(()=>{if(!j)return[];if(!ct)return[];if(!j.isWorking)return[];const je=[];return H.forEach(ze=>{if(j.previewedPartIds.has(ze.id)||!k&&ze.kind!=="tool")return;const Ge=ze.part;if(ze.kind==="tool"){const Le=Ge;if(mr(Le.tool)||Pe||!B(Le))return}else if(ze.kind==="reasoning"){if(!k||Re||typeof Ge.time?.end!="number")return}else if(ze.kind==="justification"&&(!k||Te||typeof Ge.time?.end!="number"))return;je.push(ze)}),je},[H,B,Te,Re,Pe,k,ct,j]),Je=l.useMemo(()=>{const je=new Set;return ot.forEach(ze=>{je.add(ze.id)}),je},[ot]),{isAnimating:it}=Sx(j,Je),dt=!!(j&&j.activityGroupAnchorMessageId===r&&ct&&Y.length>0),at=l.useMemo(()=>P.filter(je=>mr(je.tool)),[P]),pt=l.useMemo(()=>{if(!j||!dt)return!1;if(!j.isWorking)return!0;const je=j.previewedPartIds;return Y.some(ze=>je.has(ze.id))},[dt,j,Y]),ut=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{ut.current=null,pe.current=null},[r]);const _=Date.now();at.length>0&&ut.current===null&&(ut.current=_),pt&&pe.current===null&&(pe.current=_);const se=!!(at.length>0&&pt&&typeof ut.current=="number"&&typeof pe.current=="number"&&pe.current>ut.current),ee=l.useMemo(()=>{const je=[],ze=()=>{!j||!dt||je.push(e.jsx(wx,{parts:Y,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"))};se||ze(),at.forEach(Le=>{je.push(e.jsx(Gt,{children:e.jsx(Sn,{part:Le,isExpanded:d.has(Le.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Le.id}`))}),se&&ze();const Ge=[];return D.forEach((Le,ft)=>{const Ct=X.get(Le);if(!Ct||!j)return;let vt=null,be=null;if(!ct){if(Ct.kind==="tool"){const Fe=Le;if(mr(Fe.tool))return;const Mt=Fe.state?.time,ht=B(Fe);if(!(!Pe&&ht))return;const zt=$[Fe.id];be=e.jsx(Gt,{children:e.jsx(Sn,{part:Fe,isExpanded:d.has(Fe.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:zt?.hasPrev??!1,hasNextTool:zt?.hasNext??!1})},`tool-${Fe.id}`),vt=ht&&typeof Mt?.end=="number"?Mt.end:null}be&&Ge.push({part:Le,index:ft,endTime:vt,element:be});return}if(!j.isWorking||j.isGroupExpanded||j.previewedPartIds.has(Ct.id)||!k&&Ct.kind!=="tool")return;const We=Je.has(Ct.id);switch(Ct.kind){case"tool":{const Fe=Le;if(mr(Fe.tool))break;const Mt=Fe.state?.time,ht=B(Fe);if(!(!Pe&&ht))break;const zt=$[Fe.id],G=e.jsx(Gt,{children:e.jsx(Sn,{part:Fe,isExpanded:d.has(Fe.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:zt?.hasPrev??!1,hasNextTool:zt?.hasNext??!1})},`tool-${Fe.id}`);be=We?e.jsx(Ao,{isMigrating:it,children:G},`migrating-tool-${Fe.id}`):G,vt=ht&&typeof Mt?.end=="number"?Mt.end:null;break}case"reasoning":{if(!k)break;const Fe=Le.time,Ze=typeof Fe?.end=="number";if(!(Ze&&!Re))break;const ht=e.jsx(Gt,{children:e.jsx(rd,{part:Le,messageId:r,onContentChange:h})},`reasoning-${ft}`);be=We?e.jsx(Ao,{isMigrating:it,children:ht},`migrating-reasoning-${ft}`):ht,vt=Ze?Fe?.end??null:null;break}case"justification":{if(!k)break;const Fe=Le.time,Ze=typeof Fe?.end=="number";if(!(Ze&&!Te))break;const ht=e.jsx(Gt,{children:e.jsx(Gg,{part:Le,messageId:r,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${ft}`);be=We?e.jsx(Ao,{isMigrating:it,children:ht},`migrating-text-${ft}`):ht,vt=Ze?Fe?.end??null:null;break}}be&&Ge.push({part:Le,index:ft,endTime:vt,element:be})}),Ge.sort((Le,ft)=>Le.endTime===null&&ft.endTime===null?Le.index-ft.index:Le.endTime===null?1:ft.endTime===null?-1:Le.endTime-ft.endTime),Ge.forEach(({element:Le})=>{je.push(Le)}),je},[X,i,b,d,x,it,o,B,r,h,c,y,p,u,Je,Te,Re,Pe,ct,g,k,n,$,j,Y,D,P,at,dt,se]),me=j?.turnId,Q=fe(je=>je.currentSessionId),oe=nt(je=>{if(!me||!Q)return;const ze=je.messages.get(Q);if(!ze)return;const Ge=ze.find(Ct=>Ct.info?.id===me);if(!Ge)return;const ft=Ge.info.summary?.body;return typeof ft=="string"&&ft.trim().length>0?ft:void 0}),le=typeof j?.summaryBody=="string"&&j.summaryBody.trim().length>0?j.summaryBody:oe,Me=l.useRef(void 0);le&&le.trim().length>0&&(Me.current=le);const $e=l.useRef(me);$e.current!==me&&($e.current=me,Me.current=void 0);const kt=Me.current,bt=j?.isLastAssistantInTurn&&kt&&kt.trim().length>0,Dt=x&&O.length>0&&V&&R,[Nt,mt]=l.useState(!1),wt=e.jsxs(e.Fragment,{children:[e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:je=>je.stopPropagation(),onClick:F,children:e.jsx($u,{className:"h-4 w-4"})})}),e.jsx(et,{sideOffset:6,children:"Start new session from this answer"})]}),y&&e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":S||N?"true":void 0,className:I("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",!J&&"opacity-50"),disabled:!J,"aria-label":"Copy message text","aria-hidden":!J,onPointerDown:je=>je.stopPropagation(),onClick:q,onFocus:()=>{J&&w(!0)},onBlur:()=>{N||w(!1)},children:N?e.jsx(Tt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(_s,{className:"h-3.5 w-3.5"})})}),e.jsx(et,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:I("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:A&&M&&J?re: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:[ee,bt&&e.jsx(Gt,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>mt(!0),onMouseLeave:()=>mt(!1),children:[e.jsx(Gr,{content:kt}),Dt&&e.jsx("div",{className:I("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",Nt&&"opacity-100 pointer-events-auto"),children:wt})]})},"summary-body")]}),e.jsx(zc,{files:s,onShowPopup:p}),!bt&&Dt&&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:wt})]})})},Mx=({isUser:r,...s})=>r?e.jsx(Nx,{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,onRevert:s.onRevert,isFirstMessage:s.isFirstMessage}):e.jsx(Cx,{...s}),el=l.memo(Mx),Do=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}},Ax=l.lazy(()=>br(()=>import("./ToolOutputDialog-BK2tPtZM.js"),__vite__mapDeps([2,0,1,3,4]))),Dx=new Set(["task","edit","multiedit","write","bash"]),tl=r=>typeof r=="string"&&Dx.has(r.toLowerCase());function Eo(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 Cs=(r,s)=>{if(typeof r=="object"&&r!==null)return r[s]},Ex=({message:r,previousMessage:s,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i,isFirstMessage:c=!1})=>{const{isMobile:d,hasTouchInput:u}=Et(),{currentTheme:p}=ir(),m=l.useRef(null),f=fe(da(be=>({lifecyclePhase:be.messageStreamStates.get(r.info.id)?.phase??null,isStreamingMessage:(()=>{const We=r.info.sessionID??be.currentSessionId??null;return We?(be.streamingMessageIds.get(We)??null)===r.info.id:!1})(),currentSessionId:be.currentSessionId,getCurrentAgent:be.getCurrentAgent,getSessionAgentSelection:be.getSessionAgentSelection,getAgentModelForSession:be.getAgentModelForSession,getSessionModelSelection:be.getSessionModelSelection}))),{lifecyclePhase:h,isStreamingMessage:g,currentSessionId:x,getCurrentAgent:y,getSessionAgentSelection:b,getAgentModelForSession:v,getSessionModelSelection:k}=f,j=St(be=>be.providers),S=we(be=>be.showReasoningTraces),w=we(be=>be.toolCallExpansion);l.useEffect(()=>{x&&Hs.getInstance().recordSessionStart(x)},[x]);const[T,M]=l.useState(null),[N,A]=l.useState(!1),[C,D]=l.useState(new Set),[P,O]=l.useState({open:!1,title:"",content:""});l.useEffect(()=>{D(new Set)},[r.info.id,w]);const R=l.useMemo(()=>Do(r.info),[r.info]).isUser,V=l.useMemo(()=>R?r.parts.map(be=>be.type==="compaction"?{type:"text",text:"/summarize"}:be):r.parts,[R,r.parts]),ae=l.useMemo(()=>{if(R||!s)return null;const be=Cs(s.info,"clientRole"),We=Cs(s.info,"role");if((typeof be=="string"?be:typeof We=="string"?We:void 0)!=="user")return null;const Ze=Cs(s.info,"mode"),Mt=Cs(s.info,"providerID"),ht=Cs(s.info,"modelID"),$t=typeof Ze=="string"&&Ze.trim().length>0?Ze:void 0,zt=typeof Mt=="string"&&Mt.trim().length>0?Mt:void 0,G=typeof ht=="string"&&ht.trim().length>0?ht:void 0;return!$t&&!zt&&!G?null:{agentName:$t,providerId:zt,modelId:G}},[R,s]),K=l.useMemo(()=>{if(R)return;const be=Cs(r.info,"mode");if(typeof be=="string"&&be.trim().length>0)return be;if(ae?.agentName)return ae.agentName;const We=r.info.sessionID;if(!We)return;const Fe=y(We);return Fe||(b(We)??void 0)},[R,r.info,ae,y,b]),B=r.info.sessionID,L=R?null:Cs(r.info,"providerID"),ne=R?null:Cs(r.info,"modelID"),Se=l.useMemo(()=>{if(R||!B)return null;if(ae?.providerId&&ae?.modelId)return{providerId:ae.providerId,modelId:ae.modelId};if(K){const We=v(B,K);if(We?.providerId&&We?.modelId)return We}const be=k(B);return be?.providerId&&be?.modelId?be:null},[R,B,K,ae,v,k]),Ne=l.useMemo(()=>R?null:typeof L=="string"&&L.trim().length>0?L:Se?.providerId??null,[R,L,Se]),de=l.useMemo(()=>R?null:typeof ne=="string"&&ne.trim().length>0?ne:Se?.modelId??null,[R,ne,Se]),ge=l.useMemo(()=>{if(!R&&Ne&&de&&j.length>0){const be=j.find(We=>We.id===Ne);if(be?.models&&Array.isArray(be.models)){const Ze=be.models.find(Mt=>Mt.id===de)?.name;return typeof Ze=="string"?Ze:void 0}}},[R,Ne,de,j]),ve=Eo(K),Ae=Eo(Ne??void 0),Te=Eo(ge),Pe=ve??void 0,Re=Ae??null,ce=Te??void 0,Ie=l.useMemo(()=>{const be=r.info.time;return typeof be?.completed=="number"?be.completed:null},[r.info.time]),ie=l.useMemo(()=>R?!0:!!(Ie&&Ie>0),[R,Ie]),Ce=l.useMemo(()=>jx(V,{includeReasoning:S}),[V,S]),qe=l.useMemo(()=>R||ie?Ce:[],[R,ie,Ce]),J=l.useMemo(()=>R?[]:Ce.filter(be=>be.type==="text"),[R,Ce]),E=l.useMemo(()=>R?[]:Ce.filter(We=>We.type==="tool"),[R,Ce]),re=l.useMemo(()=>{if(w==="collapsed"||w==="activity")return C;const be=new Set;for(const Fe of E){const Ze=Fe.tool;Fe.id&&tl(Ze)&&be.add(Fe.id)}if(i?.isFirstAssistantInTurn)for(const Fe of i.activityParts){if(Fe.kind!=="tool")continue;const Ze=Fe.part;Ze.id&&tl(Ze.tool)&&be.add(Ze.id)}const We=new Set(be);for(const Fe of C)We.has(Fe)?We.delete(Fe):We.add(Fe);return We},[C,w,E,i]),q=l.useMemo(()=>{if(!R)return;const be=r.parts.find(Mt=>Mt.type==="agent");if(!be)return;const We=be,Fe=typeof We.name=="string"?We.name:void 0;if(!Fe)return;const Ze=We.source&&typeof We.source.value=="string"&&We.source.value.trim().length>0?We.source.value:`#${Fe}`;return{name:Fe,token:Ze}},[R,r.parts]),$=l.useMemo(()=>{let be=0,We=0;return Ce.forEach(Fe=>{Fe.type==="step-start"?be+=1:Fe.type==="step-finish"&&(We+=1)}),{hasOpenStep:be>We}},[Ce]).hasOpenStep,U=l.useMemo(()=>R?!1:J.length===0||E.length===0?$:!0,[J.length,E.length,$,R]),H=p?.metadata.variant,X=l.useMemo(()=>H?H==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[H]),Y=l.useMemo(()=>p?Jc(p):X?Tg:Ig,[p,X]),Ee=l.useMemo(()=>R?!1:Hs.getInstance().shouldAnimateMessage(r.info,x||r.info.sessionID),[r.info,x,R]),Be=l.useMemo(()=>s?Do(s.info):null,[s]),ct=l.useMemo(()=>t?Do(t.info):null,[t]),ot=l.useMemo(()=>R||!Be?!0:Be.isUser,[R,Be]),Je=l.useMemo(()=>R||!ct?!1:!ct.isUser&&ct.role==="assistant",[R,ct]),it=l.useMemo(()=>ie?"completed":h||(g?"streaming":"completed"),[ie,h,g]),dt=l.useCallback(be=>{navigator.clipboard.writeText(be),M(be),setTimeout(()=>M(null),2e3)},[]),at=i?.turnId,pt=nt(be=>{if(!at)return;const We=r.info.sessionID;if(!We)return;const Fe=be.messages.get(We);if(!Fe)return;const Ze=Fe.find($t=>$t.info?.id===at);if(!Ze)return;const ht=Ze.info.summary?.body;return typeof ht=="string"&&ht.trim().length>0?ht:void 0}),ut=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:pt,pe=l.useRef(void 0);ut&&ut.trim().length>0&&(pe.current=ut);const _=l.useRef(at);_.current!==at&&(_.current=at,pe.current=void 0);const se=pe.current,ee=l.useMemo(()=>R?qe.filter(Fe=>Fe.type==="text").map(Fe=>(Fe.text||Fe.content||"").trim()).filter(Fe=>Fe.length>0).join(`
|
|
89
|
-
`).replace(/\n\s*\n+/g,`
|
|
90
|
-
`):se&&se.trim().length>0?se:cc(qe),[se,qe,R]),me=ee.length>0,Q=l.useCallback(()=>{navigator.clipboard.writeText(ee),A(!0),setTimeout(()=>A(!1),2e3)},[ee]),oe=fe(be=>be.revertToMessage),le=l.useCallback(()=>{!B||!r.info.id||oe(B,r.info.id)},[B,r.info.id,oe]),Me=l.useCallback(be=>{D(We=>{const Fe=new Set(We);return Fe.has(be)?Fe.delete(be):Fe.add(be),Fe})},[]),$e=o??null,kt=l.useRef(!1),bt=l.useRef(!1),Dt=l.useRef(!1),Nt=l.useRef(!1),mt=l.useRef(!1);l.useEffect(()=>{bt.current=!1,Dt.current=!1,Nt.current=!1,mt.current=!1,kt.current=!1},[r.info.id]);const wt=l.useCallback(()=>{R||kt.current||(kt.current=!0,n?.("structural"))},[R,n]),je=l.useCallback(be=>{be.image&&O(be)},[]),ze=l.useCallback(be=>{O(We=>({...We,open:be}))},[]),Ge=!!Cs(r.info,"animationSettled"),Le=it==="streaming",ft=l.useMemo(()=>R?!1:Ce.some(be=>be.type==="reasoning"),[R,Ce]),Ct=Ee&&!Ge&&!Le,vt=!R&&Ee&&J.length>0&&!U;return l.useEffect(()=>{if($e?.onStreamingCandidate){if(!vt){Dt.current&&(ft&&$e?.onReasoningBlock?$e.onReasoningBlock():$e?.onReservationCancelled&&$e.onReservationCancelled(),Dt.current=!1);return}mt.current||(mt.current=!0,$e.onStreamingCandidate(),Dt.current=!0)}},[$e,vt,ft]),l.useEffect(()=>{$e?.onAnimationStart&&Ct&&(Nt.current||($e.onAnimationStart(),Nt.current=!0))},[$e,Ct]),l.useEffect(()=>{if(R)return;const be=$e?.onAnimatedHeightChange;if(!be||!(Ct||vt))return;const Fe=m.current;if(!Fe)return;if(typeof window>"u"||typeof ResizeObserver>"u"){be(Fe.getBoundingClientRect().height);return}let Ze=null;const Mt=$t=>{if(typeof window>"u"){be($t);return}Ze!==null&&window.cancelAnimationFrame(Ze),Ze=window.requestAnimationFrame(()=>{be($t)})},ht=new ResizeObserver($t=>{const zt=$t[0];zt&&Mt(zt.contentRect.height)});return ht.observe(Fe),Mt(Fe.getBoundingClientRect().height),()=>{Ze!==null&&(window.cancelAnimationFrame(Ze),Ze=null),ht.disconnect()}},[Ct,R,$e,vt]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:I("group w-full",ot?"pt-2":"pt-0",R?"pb-2":Je?"pb-0":"pb-2"),"data-message-id":r.info.id,ref:m,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:R?e.jsx(Gt,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-xl rounded-br-xs bg-primary/10 dark:bg-primary/8 px-3.5 pt-2.5 pb-1.5",children:e.jsx(el,{messageId:r.info.id,parts:Ce,isUser:R,isMessageCompleted:ie,syntaxTheme:Y,isMobile:d,hasTouchInput:u,copiedCode:T,onCopyCode:dt,expandedTools:C,onToggleTool:Me,onShowPopup:je,streamPhase:it,allowAnimation:Ct,onContentChange:n,shouldShowHeader:!1,hasTextContent:me,onCopyMessage:Q,copiedMessage:N,showReasoningTraces:S,onAuxiliaryContentComplete:wt,agentMention:q,onRevert:le,isFirstMessage:c})})})}):e.jsxs("div",{children:[ot&&e.jsx(Pg,{isUser:R,providerID:Re,agentName:Pe,modelName:ce,isDarkTheme:X}),e.jsx(el,{messageId:r.info.id,parts:Ce,isUser:R,isMessageCompleted:ie,syntaxTheme:Y,isMobile:d,hasTouchInput:u,copiedCode:T,onCopyCode:dt,expandedTools:re,onToggleTool:Me,onShowPopup:je,streamPhase:it,allowAnimation:Ct,onContentChange:n,shouldShowHeader:ot,hasTextContent:me,onCopyMessage:Q,copiedMessage:N,onAuxiliaryContentComplete:wt,showReasoningTraces:S,agentMention:q,turnGroupingContext:i})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(Ax,{popup:P,onOpenChange:ze,syntaxTheme:Y,isMobile:d})})]})},Tx=l.memo(Ex),Ix=({diff:r,syntaxTheme:s,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:od(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||t?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:I("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(ys,{style:s,language:or(t||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),Fx=({content:r,syntaxTheme:s,filePath:t})=>{const n=r.split(`
|
|
91
|
-
`),o=or(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(n.length,1),c=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${c})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ys,{style:s,language:o,PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},Px=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(Ds,{className:s}):t==="write"||t==="create"||t==="file_write"?e.jsx(Ol,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Vs,{className:s}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(Bo,{className:s}):e.jsx(ua,{className:s})},Rx=r=>{const s=r.toLowerCase();return s==="edit"||s==="multiedit"||s==="str_replace"||s==="str_replace_based_edit_tool"?"edit":s==="write"||s==="create"||s==="file_write"?"write":s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?"bash":s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?"webfetch":r},Lx=({permission:r,onResponse:s})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=fe(),{currentTheme:c}=ir(),d=l.useMemo(()=>Jc(c),[c]),u=async b=>{n(!0);try{await i(r.sessionID,r.id,b),a(!0),s?.(b)}catch{}finally{n(!1)}};if(o)return null;const p=r.type||"Unknown Tool",m=p.toLowerCase(),f=(b,v="")=>{const k=r.metadata[b];return typeof k=="string"?k:typeof k=="number"?String(k):v},h=b=>{const v=r.metadata[b];return typeof v=="number"?v:void 0},g=b=>!!r.metadata[b],x=Rx(p),y=()=>{if(m==="bash"||m==="shell"||m==="shell_command"){const k=f("command")||f("cmd")||f("script"),j=f("description"),S=f("cwd")||f("working_directory")||f("directory")||f("path"),w=h("timeout"),T=r.title===k;return e.jsxs(e.Fragment,{children:[j&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:j}),S&&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:S})]}),w&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",w,"ms"]}),k&&!T&&e.jsx("div",{children:e.jsx(ys,{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:k})})]})}if(m==="edit"||m==="multiedit"||m==="str_replace"||m==="str_replace_based_edit_tool"){const k=f("path")||f("file_path")||f("filename")||f("filePath"),j=f("changes")||f("diff"),S=g("replace_all")||g("replaceAll");return e.jsxs(e.Fragment,{children:[S&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),j&&e.jsx(Xe,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Ix,{diff:j,syntaxTheme:d,filePath:k})})]})}if(m==="write"||m==="create"||m==="file_write"){const k=f("path")||f("file_path")||f("filename")||f("filePath"),j=f("content")||f("text")||f("data");return j?e.jsx(Xe,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Fx,{content:j,syntaxTheme:d,filePath:k})}):null}if(m==="webfetch"||m==="fetch"||m==="curl"||m==="wget"){const k=f("url")||f("uri")||f("endpoint"),j=f("method")||"GET",S=r.metadata.headers&&typeof r.metadata.headers=="object"?r.metadata.headers:void 0,w=f("body")||f("data")||f("payload"),T=h("timeout"),M=f("format")||f("responseType");return e.jsxs(e.Fragment,{children:[k&&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:k})]})]}),S&&Object.keys(S).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(ys,{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(S,null,2)})})]}),w&&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(ys,{language:typeof w=="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 w=="object"?JSON.stringify(w,null,2):String(w)})})]}),(T||M)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[T&&e.jsxs("span",{children:["Timeout: ",T,"ms"]}),T&&M&&e.jsx("span",{children:" • "}),M&&e.jsxs("span",{children:["Response format: ",M]})]})]})}const b=f("command")||f("content")||f("action")||f("operation"),v=f("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(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(b)})})]}),Object.keys(r.metadata).length>0&&!b&&!v&&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(vr,{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:[Px(p),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:x})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[(()=>{let b="",v="text",k=!1;m==="bash"||m==="shell"||m==="shell_command"?(b=f("command")||f("cmd")||f("script"),v="bash",k=!0):m==="edit"||m==="multiedit"||m==="str_replace"||m==="str_replace_based_edit_tool"||m==="write"||m==="create"||m==="file_write"?(b=f("path")||f("file_path")||f("filename")||f("filePath"),k=!1):(m==="webfetch"||m==="fetch")&&(b=f("url")||f("uri")||f("endpoint"),k=!1);const j=r.title===b;return j&&b&&k?e.jsx("div",{className:"mb-3",children:e.jsx(ys,{language:v,style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:b})}):j&&b&&!k?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:b})}):r.title?e.jsx("div",{className:I("typography-ui-label text-foreground mb-3",(k||b)&&"font-mono"),children:r.title}):null})(),y()]}),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:I("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Tt,{className:"h-3 w-3"}),"Allow Once"]}),e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:I("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Mn,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:I("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(us,{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"})})]})]})})})},_x=new Set(["task"]),Ox=r=>typeof r=="string"&&_x.has(r.toLowerCase()),Bx=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},$x=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}}}},zx=r=>{const s=$x(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(x=>{if(!x)return;const y=typeof x.additions=="number"?x.additions:0,b=typeof x.deletions=="number"?x.deletions:0;(y!==0||b!==0)&&(g+=1),f+=y,h+=b}),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 x=typeof g.id=="string"&&g.id.trim().length>0?g.id:`${h}-activity-${d++}`;if(g.type==="tool"){const b=g.state?.time,v=typeof b?.end=="number"?b.end:void 0;c.push({id:x,turnId:r.turnId,messageId:h,kind:"tool",part:g,endedAt:v});return}if(g.type==="reasoning"){const y=g.text??g.content;if(typeof y!="string"||y.trim().length===0)return;const b=g.time,v=typeof b?.end=="number"?b.end:void 0;c.push({id:x,turnId:r.turnId,messageId:h,kind:"reasoning",part:g,endedAt:v});return}})});const u=new Map;c.forEach(f=>{if(f.kind==="tool"){const h=f.part.tool;if(Ox(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}},Hx=r=>{const{isWorking:s}=Kc(),t=l.useMemo(()=>Bx(r),[r]),n=l.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=l.useMemo(()=>{const x=new Map;return t.forEach(y=>{x.set(y.userMessage.info.id,y),y.assistantMessages.forEach(b=>{x.set(b.info.id,y)})}),x},[t]),a=l.useMemo(()=>{const x=new Map;return t.forEach(y=>{x.set(y.turnId,zx(y))}),x},[t]),[i,c]=l.useState(()=>new Map),d=we(x=>x.toolCallExpansion),u=d==="activity"||d==="detailed",p=l.useCallback(x=>{const y=i.get(x);return y||{isExpanded:u,previewedPartIds:new Set}},[i,u]),m=l.useCallback(x=>{c(y=>{const b=new Map(y),v=b.get(x)??{isExpanded:u,previewedPartIds:new Set};return b.set(x,{...v,isExpanded:!v.isExpanded}),b})},[u]),f=l.useCallback((x,y)=>{y.length!==0&&c(b=>{const v=new Map(b),k=v.get(x)??{isExpanded:u,previewedPartIds:new Set},j=new Set(k.previewedPartIds);return y.forEach(S=>{S&&S.trim().length>0&&j.add(S)}),v.set(x,{...k,previewedPartIds:j}),v})},[]),h=l.useCallback(x=>o.get(x),[o]),g=l.useCallback(x=>{const y=o.get(x);if(!y||!y.assistantMessages.some(O=>O.info.id===x))return;const v=a.get(y.turnId),k=v?.activityParts??[],j=!!v?.hasTools,S=!!v?.hasReasoning,w=v?.summaryBody,T=v?.diffStats,M=y.assistantMessages[0]?.info.id,N=x===M,A=y.assistantMessages[y.assistantMessages.length-1]?.info.id,C=x===A,D=p(y.turnId),P=s&&n===y.turnId;return{turnId:y.turnId,isFirstAssistantInTurn:N,isLastAssistantInTurn:C,summaryBody:w,activityParts:k,hasTools:j,hasReasoning:S,diffStats:T,activityGroupAnchorMessageId:v?.activityGroupAnchorMessageId,isWorking:P,isGroupExpanded:D.isExpanded,previewedPartIds:D.previewedPartIds,toggleGroup:()=>m(y.turnId),markPartsPreviewed:O=>f(y.turnId,O)}},[p,n,f,o,s,m,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:g}},Wx=({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(()=>{const m=new Set;return r.filter(f=>{const h=f.info?.id;if(typeof h=="string"){if(m.has(h))return!1;m.add(h)}return!qo(f.parts)})},[r]),{getContextForMessage:p}=Hx(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)=>{const h=m.info.role==="user"&&!u.slice(0,f).some(g=>g.info.role==="user");return e.jsx(Tx,{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),isFirstMessage:h},m.info.id)})}),s.length>0&&e.jsx("div",{children:s.map(m=>e.jsx(Lx,{permission:m},m.id))})]})},Ux=l.memo(Wx);function Vx(...r){return s=>{r.forEach(t=>{typeof t=="function"?t(s):t&&typeof t=="object"&&(t.current=s)})}}const cd=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 v={...i};return v["--scroll-shadow-size"]=`${t}px`,v},[t,i]),x=l.useCallback((v,k,j,S,w)=>{const T=`${S}${w.charAt(0).toUpperCase()}${w.slice(1)}Scroll`;k&&j?(v.dataset[T]="true",v.removeAttribute(`data-${S}-scroll`),v.removeAttribute(`data-${w}-scroll`)):(v.dataset[`${S}Scroll`]=String(k),v.dataset[`${w}Scroll`]=String(j),v.removeAttribute(`data-${S}-${w}-scroll`))},[]),y=l.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(k=>{v.removeAttribute(`data-${k}-scroll`)})},[]),b=l.useCallback(()=>{const v=m.current;if(!v)return;if(!n){y(v);return}const k=r==="vertical"?v.scrollTop>s:v.scrollLeft>s;let j=r==="vertical"?v.scrollTop+v.clientHeight+s<v.scrollHeight:v.scrollLeft+v.clientWidth+s<v.scrollWidth;o&&r==="vertical"&&(j=!1),x(v,k,j,r==="vertical"?"top":"left",r==="vertical"?"bottom":"right");const S=k&&j?"both":k?r==="vertical"?"top":"left":j?r==="vertical"?"bottom":"right":"none";S!==f.current&&(f.current=S,a?.(S))},[y,o,n,s,a,r,x]);return l.useEffect(()=>{const v=m.current;if(!v)return;const k=()=>b(),j=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null,S=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return b(),v.addEventListener("scroll",k,{passive:!0}),j?.observe(v),S?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",k),j?.disconnect(),S?.disconnect()}},[b]),e.jsx("div",{...u,ref:Vx(m,p),className:c,"data-orientation":r,"data-scroll-shadow":h??!0,style:g,children:d})});cd.displayName="ScrollShadow";const Gx=160,qx=({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(k=>{const j=r.current;if(!j){u();return}i.current===null&&(i.current=k);const S=Math.min(1,(k-i.current)/Gx),w=1-Math.pow(1-S,3),T=c.current,M=d.current,N=T+(M-T)*w;if(j.scrollTop=N,S<1){a.current=window.requestAnimationFrame(p);return}j.scrollTop=M,u(),n.current&&(n.current=!1,t(!1))},[u,r,t]),m=l.useCallback((k,j)=>{const S=r.current;if(!S)return;const w=Math.max(0,k),T=j?.instant??!1;if(o.current=!1,typeof window>"u"||T){u(),S.scrollTop=w;const N=w<=1;n.current!==N&&(n.current=N,t(N));return}if(u(),Math.abs(w-S.scrollTop)<=.5){S.scrollTop=w;const N=w<=1;n.current!==N&&(n.current=N,t(N));return}c.current=S.scrollTop,d.current=w,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,[]),x=l.useCallback(()=>r.current?.scrollTop??0,[r]),y=l.useCallback(()=>r.current?.scrollHeight??0,[r]),b=l.useCallback(()=>r.current?.clientHeight??0,[r]),v=l.useCallback(()=>{const k=r.current;if(!k)return;o.current&&a.current!==null&&u();const j=k.scrollTop<=1;n.current!==j&&(n.current=j,t(j))},[u,r]);return l.useEffect(()=>{const k=r.current;if(k)return k.addEventListener("wheel",h,{passive:!0}),k.addEventListener("touchstart",h,{passive:!0}),()=>{k.removeEventListener("wheel",h),k.removeEventListener("touchstart",h)}},[r,h]),l.useEffect(()=>()=>{u()},[u]),l.useMemo(()=>({handleScroll:v,scrollToPosition:m,forceManualMode:f,isAtTop:s,isManualOverrideActive:g,getScrollTop:x,getScrollHeight:y,getClientHeight:b}),[v,m,f,s,g,x,y,b])},sl=typeof window<"u"?l.useLayoutEffect:l.useEffect,rl=50,nl=40,Kx=.2,Yx=.1,Xx=150,ls=r=>{const s=r.info;return typeof s?.id=="string"?s.id:null},Jx=r=>{const s=r.info;if(s?.userMessageMarker===!0)return!0;const t=s?.clientRole,n=s?.role;return t==="user"||n==="user"},Zx=({currentSessionId:r,sessionMessages:s,updateViewportAnchor:t,isSyncing:n,isMobile:o,sessionActivityPhase:a})=>{const i=l.useRef(null),c=qx({containerRef:i}),[d,u]=l.useState(null),[p,m]=l.useState(0),[f,h]=l.useState(!1),[g,x]=l.useState(null),y=l.useRef(null),b=l.useRef(null),v=l.useRef(s.length),k=l.useRef(s.length>0?ls(s[0]):null),j=l.useRef(s.length>0?ls(s[s.length-1]):null),S=l.useRef(0),w=l.useRef(0),T=l.useRef(void 0),M=l.useRef(null),N=l.useRef(!1),A=l.useRef(!1),C=r?a?.get(r)??"idle":"idle",D=l.useCallback(de=>{const ge=Math.max(0,de);S.current!==ge&&(S.current=ge,m(ge))},[]),P=l.useCallback(()=>{const de=i.current;de&&(w.current=de.clientHeight)},[]),O=l.useCallback(()=>{if(!d)return null;const de=i.current;return de?de.querySelector(`[data-message-id="${d}"]`):null},[d]),W=l.useCallback(()=>{const de=i.current,ge=S.current;if(!de||ge<=0)return!0;const ve=de.scrollHeight-ge;return de.scrollTop+de.clientHeight<ve},[]),R=l.useCallback((de,ge)=>{const ve=de.offsetHeight,Ae=de.offsetTop;if(ve>ge*Kx){const Pe=ge*Yx;return Ae+ve-Pe}else return Ae-rl},[]),V=l.useCallback(()=>{const de=i.current;if(!de||!M.current)return;const ge=O();if(!ge)return;const ve=de.clientHeight,Ae=de.scrollHeight,Pe=R(ge,ve)+ve,Re=S.current,ce=Ae-Re;if(!N.current&&ce<Pe){const Ie=Pe-ce;Ie>Re&&D(Ie)}},[R,O,D]),ae=l.useCallback(()=>{const de=i.current;if(!de){h(!1);return}if(g){h(!1);return}if(!(de.scrollHeight>de.clientHeight)){h(!1);return}const ve=de.scrollHeight-de.scrollTop-de.clientHeight,Ae=S.current;if(Ae>0){const Te=de.scrollHeight-Ae,Pe=de.scrollTop+de.clientHeight;h(Pe<Te)}else h(ve>nl)},[g]),K=l.useCallback(de=>{const ge=i.current;if(!ge)return;const ve=ge.scrollHeight-ge.scrollTop-ge.clientHeight;if(A.current&&C==="idle"&&!n&&!de?.force&&ve>nl)return;de?.force&&(A.current=!1);const Te=ge.scrollHeight-ge.clientHeight;c.scrollToPosition(Math.max(0,Te),de)},[C,n,c]),B=l.useCallback(de=>{if(y.current===de)return;y.current=de,x(de);const ge=i.current;if(!ge){x(null);return}const ve=ge.scrollHeight,Ae=S.current,Te=ve-Ae,Pe=w.current>0?w.current:ge.clientHeight,ce=Te-rl,Ie=ce+Pe;let ie=0;Te<Ie&&(ie=Ie-Te),ie!==Ae&&D(ie),N.current=!0,window.requestAnimationFrame(()=>{c.scrollToPosition(ce,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[c,D]),L=l.useCallback(de=>{const ge=i.current;if(!ge||!r)return;de?.isTrusted&&(A.current=!0),c.handleScroll(),ae(),C==="idle"&&S.current>0&&W()&&(D(0),M.current=null,u(null));const{scrollTop:ve,scrollHeight:Ae,clientHeight:Te}=ge,Pe=(ve+Te/2)/Math.max(Ae,1),Re=Math.floor(Pe*s.length);t(r,Re)},[r,C,W,c,s.length,ae,D,t]);l.useEffect(()=>{const de=i.current;if(de)return de.addEventListener("scroll",L,{passive:!0}),()=>{de.removeEventListener("scroll",L)}},[L]),sl(()=>{if(typeof window>"u")return;P();const de=()=>{T.current!==void 0&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{P()},Xx)};return window.addEventListener("resize",de),()=>{window.removeEventListener("resize",de),T.current!==void 0&&window.clearTimeout(T.current)}},[P]),l.useEffect(()=>{r&&r!==b.current&&(b.current=r,Hs.getInstance().recordSessionStart(r),v.current=s.length,k.current=s.length>0?ls(s[0]):null,j.current=s.length>0?ls(s[s.length-1]):null,y.current=null,M.current=null,N.current=!1,u(null),S.current=0,m(0),x(null),h(!1),A.current=!1)},[r,s.length]),sl(()=>{if(n){v.current=s.length,k.current=s.length>0?ls(s[0]):null,j.current=s.length>0?ls(s[s.length-1]):null;return}if(b.current!==r)return;const de=v.current,ge=s.length;if(ge>de&&de>0){const ve=k.current,Ae=ls(s[0]),Te=ls(s[ge-1]),Pe=j.current,Re=ve!==null&&Ae!==ve,ce=Pe!==null&&Te!==Pe,Ie=Re&&!ce,ie=ce&&!Re;if(Ie){M.current=null,N.current=!1,u(null),D(0),v.current=ge,k.current=Ae,j.current=Te;return}if(ie){const qe=s.slice(de,ge).find(Jx);if(qe){const J=ls(qe);J&&(M.current=J,u(J),B(J))}else V()}}v.current=ge,k.current=s.length>0?ls(s[0]):null,j.current=s.length>0?ls(s[s.length-1]):null},[r,n,V,B,s]),l.useEffect(()=>{const de=i.current;if(!de||typeof ResizeObserver>"u")return;const ge=new ResizeObserver(()=>{V(),ae()});return ge.observe(de),()=>{ge.disconnect()}},[V,ae]),l.useEffect(()=>{if(typeof window>"u"){ae();return}const de=window.requestAnimationFrame(()=>{ae()});return()=>{window.cancelAnimationFrame(de)}},[r,s.length,ae]),l.useEffect(()=>{d&&(V(),ae())},[d,V,ae]),l.useEffect(()=>{C==="idle"&&S.current>0&&W()&&(D(0),M.current=null,N.current=!1,u(null))},[C,W,D]),l.useEffect(()=>{ae()},[p,ae]);const ne=l.useRef(new Map),Se=l.useCallback(()=>{V(),ae()},[V,ae]),Ne=l.useCallback(de=>{const ge=ne.current.get(de);if(ge)return ge;const ve={onChunk:()=>{V()},onComplete:()=>{V()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{V()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return ne.current.set(de,ve),ve},[V]);return{scrollRef:i,handleMessageContentChange:Se,getAnimationHandlers:Ne,showScrollButton:f,scrollToBottom:K,spacerHeight:p,pendingAnchorId:g,hasActiveAnchor:d!==null}},Qx=()=>{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}=fe(),h=l.useMemo(()=>r?n.get(r)??null:null,[r,n]),{isMobile:g}=Et(),x=l.useMemo(()=>r?s.get(r)||[]:[],[r,s]),y=l.useMemo(()=>r?t.get(r)||[]:[],[r,t]),{scrollRef:b,handleMessageContentChange:v,getAnimationHandlers:k,showScrollButton:j,scrollToBottom:S,spacerHeight:w,pendingAnchorId:T,hasActiveAnchor:M}=Zx({currentSessionId:r,sessionMessages:x,updateViewportAnchor:c,isSyncing:u,isMobile:g,sessionActivityPhase:f}),A=!!l.useMemo(()=>r?d.get(r)??null:null,[r,d])?.hasMoreAbove,[C,D]=l.useState(!1);l.useEffect(()=>{D(!1)},[r]);const P=l.useRef(null);l.useLayoutEffect(()=>{if(!r||r===P.current)return;P.current=r;const W=b.current;W&&(W.scrollTop=W.scrollHeight-W.clientHeight)},[r,b]);const O=l.useCallback(async()=>{if(!r||C)return;const W=b.current,R=W?.scrollHeight??null,V=W?.scrollTop??null;D(!0);try{if(await i(r,"up"),W&&R!==null&&V!==null){const ae=W.scrollHeight-R;W.scrollTop=V+ae}}finally{D(!1)}},[r,C,i,b]);return l.useEffect(()=>{if(!r||(s.has(r)?s.get(r)??[]:[]).length>0)return;(async()=>{try{await a(r)}finally{typeof window>"u"?S():window.requestAnimationFrame(()=>{S()})}})()},[r,a,s,S]),r?o&&x.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(R=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Co,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Co,{className:"h-4 w-24"}),e.jsx(Co,{className:"h-20 w-full"})]})]},R))})}),e.jsx(No,{scrollToBottom:S})]}):x.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(Ko,{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(No,{scrollToBottom:S})})]}):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(cd,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:b,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!T,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(Ux,{messages:x,permissions:y,onMessageContentChange:v,getAnimationHandlers:k,hasMoreAbove:A,isLoadingOlder:C,onLoadOlder:O,scrollToBottom:S,pendingAnchorId:T}),w>0&&M&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:w},"aria-hidden":"true"})]})}),e.jsx(ba,{containerRef:b})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[j&&x.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(De,{variant:"outline",size:"sm",onClick:()=>S({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(Cr,{className:"h-4 w-4"})})}),e.jsx(No,{scrollToBottom:S})]})]}):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(Ko,{width:140,height:140,className:"opacity-20",isAnimated:!0})})})};class ey 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(Da,{className:"w-full max-w-md",children:[e.jsx(yc,{className:"text-center",children:e.jsxs(bc,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(zu,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(wc,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data."}),this.props.sessionId&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Session: ",this.props.sessionId]}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Reset Chat"]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:"If the problem persists, try refreshing the page."})]})]})}):this.props.children}}const Zo=()=>{const r=fe(s=>s.currentSessionId);return e.jsx(ey,{sessionId:r||void 0,children:e.jsx(Qx,{})})},ol=12,ty=[{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"}],sy=({isActive:r,burstKey:s=0,className:t,durationMs:n=900,bursts:o=ty,onComplete:a})=>{const i=ue.useRef(!1);ue.useEffect(()=>{!r&&i.current&&a?.(),r&&(i.current=!0)},[r,a]);const c=ue.useMemo(()=>Array.from({length:ol},(d,u)=>{const p=Math.PI*2*u/ol;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return r?e.jsx("div",{className:I("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},ry=({durationMs:r=3400}={})=>{const[s,t]=ue.useState({isActive:!1,cycle:0}),n=ue.useRef(null),o=ue.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=ue.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=ue.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 ue.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:i,dismissFireworks:a}},dd=l.createContext(void 0),al=({children:r})=>{const{isActive:s,burstKey:t,triggerFireworks:n,dismissFireworks:o}=ry(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(dd.Provider,{value:a,children:[r,e.jsx(sy,{isActive:s,burstKey:t})]})},ny=()=>{const r=l.useContext(dd);if(!r)throw new Error("useFireworksCelebration must be used within FireworksProvider");return r},oy=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),ay=({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(""),[x,y]=l.useState(!1),b=l.useRef(null),v=l.useMemo(()=>oy(h),[h]),k=l.useMemo(()=>{const N=u.toLowerCase();return N?s.filter(A=>A.toLowerCase().includes(N)):s},[u,s]),j=l.useMemo(()=>{const N=u.toLowerCase();return N?t.filter(A=>A.toLowerCase().includes(N)):t},[u,t]),S=N=>{if(N===r){d(!1);return}o(N),d(!1),p("")},w=()=>{f(!0),setTimeout(()=>b.current?.focus(),50)},T=async()=>{if(!(!v||x)){y(!0);try{await a(v),g(""),f(!1),d(!1)}finally{y(!1)}}},M=()=>{g(""),f(!1)};return l.useEffect(()=>{c||(p(""),f(!1),g(""))},[c]),e.jsxs(Xt,{open:c,onOpenChange:d,children:[e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(Jt,{asChild:!0,children:e.jsxs(De,{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(yt,{className:"size-4 opacity-60"})]})})}),e.jsxs(et,{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(Pc,{className:"h-full min-h-0",children:[e.jsx(Rc,{placeholder:"Search branches...",value:u,onValueChange:p}),e.jsxs(Lc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(_c,{children:"No branches found."}),e.jsx(yr,{children:m?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:b,placeholder:"New branch name",value:h,onChange:N=>g(N.target.value),onKeyDown:N=>{N.key==="Enter"?(N.preventDefault(),T()):N.key==="Escape"&&(N.preventDefault(),M())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:T,disabled:!v||x,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:x?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(as,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:M,disabled:x,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(us,{className:"size-4"})})]}):e.jsxs(It,{onSelect:w,children:[e.jsx(as,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Wn,{}),e.jsxs(yr,{heading:"Local branches",children:[k.map(N=>e.jsxs(It,{onSelect:()=>S(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}`)),k.length===0&&e.jsx(It,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Wn,{}),e.jsxs(yr,{heading:"Remote branches",children:[j.map(N=>e.jsx(It,{onSelect:()=>S(N),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:N})},`remote-${N}`)),j.length===0&&e.jsx(It,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},iy=({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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsxs(De,{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(Zn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(et,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsxs(De,{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(Cr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(et,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsxs(De,{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(Yr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(et,{sideOffset:8,children:"Push changes"})]})]})},ly={branch:Yt,briefcase:aa,house:oa,graduation:na,code:ws,heart:Il,user:Xn},cy={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 ud(r){return r&&cy[r]||"var(--primary)"}const il=({icon:r,className:s,colorToken:t})=>{const n=ly[r??"branch"]??Xn;return e.jsx(n,{className:s,style:{color:ud(t)}})},dy=({activeProfile:r,identities:s,onSelect:t,isApplying:n})=>{const o=n||s.length===0;return e.jsxs(Xt,{children:[e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(Jt,{asChild:!0,children:e.jsxs(De,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:ud(r?.color)},disabled:o,children:[n?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(il,{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(yt,{className:"size-4 opacity-60"})]})})}),e.jsxs(et,{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(il,{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))})]})},uy=({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(ay,{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(Yr,{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(Cr,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:r.behind})]})]}),e.jsx(iy,{syncAction:o,onFetch:a,onPull:i,onPush:c,disabled:!r}),e.jsx("div",{className:"flex-1"}),e.jsx(dy,{activeProfile:p,identities:m,onSelect:f,isApplying:h})]}):null,my=({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(ta,{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(De,{variant:"outline",onClick:s,disabled:t,children:[t?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(Cr,{className:"size-4"}),"Pull ",r," commit",r===1?"":"s"]})]}),md={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},fy=md.M;function py(r){const s=r.index?.trim(),t=r.working_dir?.trim();return s&&s!=="?"?s.charAt(0):t?t.charAt(0):s?.charAt(0)||t?.charAt(0)||"M"}function hy(r){const s=py(r);return md[s]??fy}const gy=l.memo(function({file:s,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:c}){const d=ue.useMemo(()=>hy(s),[s]),u=d.description,p=c?.insertions??0,m=c?.deletions??0,f=ue.useCallback(x=>{x.key===" "?(x.preventDefault(),n()):x.key==="Enter"&&(x.preventDefault(),o())},[n,o]),h=ue.useCallback(x=>{x.preventDefault(),x.stopPropagation(),n()},[n]),g=ue.useCallback(x=>{x.preventDefault(),x.stopPropagation(),a()},[a]);return e.jsx("li",{children:e.jsxs("div",{className:"group flex items-center gap-2 px-3 py-1.5 hover:bg-sidebar/40 cursor-pointer",role:"button",tabIndex:0,onClick:o,onKeyDown:f,children:[e.jsx("button",{type:"button",onClick:h,"aria-pressed":t,"aria-label":`Select ${s.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t?e.jsx(la,{className:"size-4 text-primary"}):e.jsx(ca,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:d.color},title:u,"aria-label":u,children:d.code}),e.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left"},title:s.path,children:s.path}),e.jsxs("span",{className:"shrink-0 typography-micro",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",p]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",m]})]}),e.jsxs(st,{delayDuration:200,children:[e.jsx(rt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:g,disabled:i,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 ${s.path}`,children:i?e.jsx(Bt,{className:"size-3.5 animate-spin"}):e.jsx(Zn,{className:"size-3.5"})})}),e.jsx(et,{sideOffset:8,children:"Revert changes"})]})]})})}),xy=({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(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick: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(gy,{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))})})]})},fd=Hu,yy=({className:r,...s})=>e.jsx(Uu,{className:I("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}),pd=({className:r,...s})=>e.jsx(Wu,{className:I("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",r),...s}),To=38,ll=200,by=({value:r,onChange:s,placeholder:t="Commit message",disabled:n=!1})=>{const o=l.useRef(null);return l.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${To}px`;const i=Math.min(Math.max(a.scrollHeight,To),ll);a.style.height=`${i}px`},[r]),e.jsx(sr,{ref:o,value:r,onChange:a=>s(a.target.value),placeholder:t,rows:1,disabled:n,className:I("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:To,maxHeight:ll}})},wy=({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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(Cr,{className:"size-4"})})}),e.jsx(et,{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))})]})},vy=({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(fd,{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(pd,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(wy,{highlights:n,onInsert:o,onClear:a}),e.jsx(by,{value:s,onChange:t,placeholder:"Commit message",disabled:p!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{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(Vu,{className:"size-4 text-primary"})})}),e.jsx(et,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(zn,{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(ta,{className:"size-4"}),"Commit"]})}),e.jsx(zn,{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(Yr,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function jy({...r}){return e.jsx(Gu,{"data-slot":"select",...r})}function Sy({...r}){return e.jsx(Yu,{"data-slot":"select-value",...r})}function ky({className:r,size:s="default",children:t,...n}){return e.jsxs(qu,{"data-slot":"select-trigger","data-size":s,className:I("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-muted data-[state=open]:bg-muted focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 *:data-[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(Ku,{asChild:!0,children:e.jsx(yt,{className:"size-4 opacity-50"})})]})}function Ny({className:r,children:s,position:t="popper",...n}){return e.jsx(Xu,{children:e.jsxs(Ju,{"data-slot":"select-content",className:I("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:t,...n,children:[e.jsx(My,{}),e.jsx(Xe,{as:Zu,outerClassName:"max-h-[var(--radix-select-content-available-height)] w-full",className:I("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(Ay,{})]})})}function Cy({className:r,children:s,...t}){return e.jsxs(Qu,{"data-slot":"select-item",className:I("hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",r),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(em,{children:e.jsx(Tt,{className:"size-4"})})}),e.jsx(tm,{children:s})]})}function My({className:r,...s}){return e.jsx(sm,{"data-slot":"select-scroll-up-button",className:I("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(Kr,{className:"size-4"})})}function Ay({className:r,...s}){return e.jsx(rm,{"data-slot":"select-scroll-down-button",className:I("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(yt,{className:"size-4"})})}function cl(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 Dy(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 Ey=({entry:r,isExpanded:s,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:I("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:cl(r.date),children:cl(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(st,{delayDuration:500,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(r.hash)},children:e.jsx(_s,{className:"size-3"})})}),e.jsx(et,{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:I("font-semibold w-3 text-center",Dy(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))})})]}),Ty=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Iy=({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(fd,{open:u,onOpenChange:p,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(yy,{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(jy,{value:String(t),onValueChange:m=>n(Number(m)),disabled:s,children:[e.jsx(ky,{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(Sy,{placeholder:"Commits"})}),e.jsx(Ny,{children:Ty.map(m=>e.jsx(Cy,{value:String(m.value),children:m.label},m.value))})]})}),u?e.jsx(Kr,{className:"size-4 text-muted-foreground"}):e.jsx(yt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(pd,{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(Ey,{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 Rr=null;const Fy=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=fe(),{currentDirectory:n}=jt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},Py=()=>{const{git:r}=ar(),s=Fy(),{currentSessionId:t,worktreeMetadata:n}=fe(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=eo(),u=mc(s??null),p=uc(s??null),m=Sp(s??null),f=kp(s??null),h=Np(s??null),g=At(Q=>Q.isLoadingStatus),x=At(Q=>Q.isLoadingLog),{setActiveDirectory:y,fetchAll:b,fetchStatus:v,fetchBranches:k,fetchLog:j,fetchIdentity:S,setLogMaxCount:w}=At(),T=l.useMemo(()=>!Rr||Rr.directory!==s?null:Rr,[s]),[M,N]=l.useState(T?.commitMessage??""),[A,C]=l.useState(null),[D,P]=l.useState(null),[O,W]=l.useState(25),[R,V]=l.useState(!1),{triggerFireworks:ae}=ny(),[K,B]=l.useState(()=>new Set(T?.selectedPaths??[])),[L,ne]=l.useState(!1),[Se,Ne]=l.useState(new Set),[de,ge]=l.useState(!1),[ve,Ae]=l.useState([]),Te=l.useCallback(()=>{Ae([])},[]),[Pe,Re]=l.useState(new Set),[ce,Ie]=l.useState(new Map),[ie,Ce]=l.useState(new Set),qe=l.useCallback(Q=>{navigator.clipboard.writeText(Q).then(()=>{xe.success("Commit hash copied")}).catch(()=>{xe.error("Failed to copy")})},[]),J=l.useCallback(Q=>{Re(oe=>{const le=new Set(oe);return le.has(Q)?le.delete(Q):le.add(Q),le})},[]);l.useEffect(()=>{if(!s||!r)return;const Q=Array.from(Pe).filter(oe=>!ce.has(oe)&&!ie.has(oe));Q.length!==0&&(Ce(oe=>{const le=new Set(oe);return Q.forEach(Me=>le.add(Me)),le}),Q.forEach(oe=>{r.getCommitFiles(s,oe).then(le=>{Ie(Me=>new Map(Me).set(oe,le.files))}).catch(le=>{console.error("Failed to fetch commit files:",le),Ie(Me=>new Map(Me).set(oe,[]))}).finally(()=>{Ce(le=>{const Me=new Set(le);return Me.delete(oe),Me})})}))},[Pe,s,r,ce,ie]),l.useEffect(()=>()=>{if(!s){Rr=null;return}Rr={directory:s,selectedPaths:Array.from(K),commitMessage:M}},[M,s,K]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{s&&(y(s),At.getState().directories.get(s)?.status||b(s,r,{force:!0}))},[s,y,b,r]);const E=l.useCallback(async(Q=!0)=>{if(s)try{await Promise.all([v(s,r),k(s,r)])}catch(oe){if(Q){const le=oe instanceof Error?oe.message:"Failed to refresh repository state";xe.error(le)}}},[s,r,v,k]),re=l.useCallback(async()=>{s&&await j(s,r,O)},[s,r,j,O]),q=l.useCallback(async()=>{s&&await S(s,r)},[s,r,S]),F=l.useMemo(()=>{if(!p)return[];const Q=p.files??[],oe=new Map;return Q.forEach(le=>{oe.set(le.path,le)}),Array.from(oe.values()).sort((le,Me)=>le.path.localeCompare(Me.path))},[p]);l.useEffect(()=>{if(!p||F.length===0){B(new Set),ne(!1);return}B(Q=>{const oe=new Set,le=Q??new Set;return F.forEach(Me=>{le.has(Me.path)?oe.add(Me.path):L||oe.add(Me.path)}),oe})},[p,F,L]);const $=async Q=>{if(s){C(Q);try{if(Q==="fetch")await r.gitFetch(s),xe.success("Fetched latest updates");else if(Q==="pull"){const oe=await r.gitPull(s);xe.success(`Pulled ${oe.files.length} file${oe.files.length===1?"":"s"}`)}else Q==="push"&&(await r.gitPush(s),xe.success("Pushed to remote"));await E(!1),await re()}catch(oe){const le=oe instanceof Error?oe.message:`Failed to ${Q==="pull"?"pull":Q}`;xe.error(le)}finally{C(null)}}},U=async(Q={})=>{if(!s)return;if(!M.trim()){xe.error("Please enter a commit message");return}const oe=Array.from(K).sort();if(oe.length===0){xe.error("Select at least one file to commit");return}const le=Q.pushAfter?"commitAndPush":"commit";P(le);try{await r.createGitCommit(s,M.trim(),{files:oe}),xe.success("Commit created successfully"),N(""),B(new Set),ne(!1),Te(),await E(),Q.pushAfter?(await r.gitPush(s),xe.success("Pushed to remote"),ae(),await E(!1)):await E(!1),await re()}catch(Me){const $e=Me instanceof Error?Me.message:"Failed to create commit";xe.error($e)}finally{P(null)}},H=l.useCallback(async()=>{if(s){if(K.size===0){xe.error("Select at least one file to describe");return}ge(!0);try{const{message:Q}=await r.generateCommitMessage(s,Array.from(K)),oe=Q.subject?.trim()??"",le=Array.isArray(Q.highlights)?Q.highlights:[];oe&&N(oe),Ae(le),xe.success("Commit message generated")}catch(Q){const oe=Q instanceof Error?Q.message:"Failed to generate commit message";xe.error(oe)}finally{ge(!1)}}},[s,K,r]),X=async Q=>{if(!s||!p)return;const oe=p.current??null;try{await r.createBranch(s,Q,oe??"HEAD"),xe.success(`Created branch ${Q}`);let le=!1;try{await r.checkoutBranch(s,Q),await r.gitPush(s,{remote:"origin",branch:Q,options:["--set-upstream"]}),le=!0}catch(Me){const $e=Me instanceof Error?Me.message:"Unable to push new branch to origin.";xe.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",$e]})})}finally{if(oe)try{await r.checkoutBranch(s,oe)}catch(Me){console.warn("Failed to restore original branch after creation:",Me)}}await E(),await re(),le&&xe.success(`Upstream set for ${Q}`)}catch(le){const Me=le instanceof Error?le.message:"Failed to create branch";throw xe.error(Me),le}},Y=async Q=>{if(!s)return;const oe=Q.replace(/^remotes\//,"");if(p?.current!==oe)try{await r.checkoutBranch(s,oe),xe.success(`Checked out ${oe}`),await E(),await re()}catch(le){const Me=le instanceof Error?le.message:`Failed to checkout ${oe}`;xe.error(Me)}},Ee=async Q=>{if(s){V(!0);try{await r.setGitIdentity(s,Q.id),xe.success(`Applied "${Q.name}" to repository`),await q()}catch(oe){const le=oe instanceof Error?oe.message:"Failed to apply git identity";xe.error(le)}finally{V(!1)}}},Be=l.useMemo(()=>m?.all?m.all.filter(Q=>!Q.startsWith("remotes/")).sort():[],[m]),ct=l.useMemo(()=>m?.all?m.all.filter(Q=>Q.startsWith("remotes/")).map(Q=>Q.replace(/^remotes\//,"")).sort():[],[m]),ot=l.useMemo(()=>{const Q=new Map;i&&Q.set(i.id,i);for(const oe of a)Q.set(oe.id,oe);return Array.from(Q.values())},[a,i]),Je=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const Q=a.find(oe=>oe.userName===h.userName&&oe.userEmail===h.userEmail);return Q||(i&&i.userName===h.userName&&i.userEmail===h.userEmail?i:{id:"local-config",name:h.userName,userName:h.userName,userEmail:h.userEmail,sshKey:h.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[h,a,i]),it=F.length,dt=K.size,at=g||A!==null||D!==null,pt=it>0,ut=Q=>{B(oe=>{const le=new Set(oe);return le.has(Q)?le.delete(Q):le.add(Q),le}),ne(!0)},pe=()=>{const Q=new Set(F.map(oe=>oe.path));B(Q),ne(!0)},_=()=>{B(new Set),ne(!0)},se=l.useCallback(async Q=>{if(s){Ne(oe=>{const le=new Set(oe);return le.add(Q),le});try{await r.revertGitFile(s,Q),xe.success(`Reverted ${Q}`),await E(!1)}catch(oe){const le=oe instanceof Error?oe.message:"Failed to revert changes";xe.error(le)}finally{Ne(oe=>{const le=new Set(oe);return le.delete(Q),le})}}},[s,E,r]),ee=l.useCallback(()=>{if(ve.length===0)return;const Q=ve.map(oe=>oe.trim()).filter(Boolean);if(Q.length===0){Te();return}N(oe=>{const le=oe.trim(),Me=le.length>0?`
|
|
92
|
-
|
|
93
|
-
`:"";return`${le}${Me}${Q.join(`
|
|
94
|
-
`)}`.trim()})},[ve,Te]),me=l.useCallback(Q=>{W(Q),s&&(w(s,Q),j(s,r,Q))},[s,w,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(uy,{status:p,localBranches:Be,remoteBranches:ct,branchInfo:m?.branches,syncAction:A,onFetch:()=>$("fetch"),onPull:()=>$("pull"),onPush:()=>$("push"),onCheckoutBranch:Y,onCreateBranch:X,activeIdentityProfile:Je,availableIdentities:ot,onSelectIdentity:Ee,isApplyingIdentity:R,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:[pt?e.jsx(xy,{changeEntries:F,selectedPaths:K,diffStats:p?.diffStats,revertingPaths:Se,onToggleFile:ut,onSelectAll:pe,onClearSelection:_,onViewDiff:Q=>we.getState().navigateToDiff(Q),onRevertFile:se}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(my,{behind:p?.behind??0,onPull:()=>$("pull"),isPulling:A==="pull"})}),F.length>0&&e.jsx(vy,{selectedCount:dt,commitMessage:M,onCommitMessageChange:N,generatedHighlights:ve,onInsertHighlights:ee,onClearHighlights:Te,onGenerateMessage:H,isGeneratingMessage:de,onCommit:()=>U({pushAfter:!1}),onCommitAndPush:()=>U({pushAfter:!0}),commitAction:D,isBusy:at})]}),e.jsx(Iy,{log:f,isLogLoading:x,logMaxCount:O,onLogMaxCountChange:me,expandedCommitHashes:Pe,onToggleCommit:J,commitFilesMap:ce,loadingCommitHashes:ie,onCopyHash:qe})]})})]}):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."})})},Ry=256e3;function Js(r){let s=r.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const un=r=>({directory:r,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),dl=Pt((r,s)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=Js(t);return s().sessions.get(n)},setTerminalSession:(t,n)=>{const o=Js(t);r(a=>{const i=new Map(a.sessions),c=i.get(o),u=!c||c.terminalSessionId!==n.sessionId?un(o):c??un(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=Js(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??un(o);return i.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=Js(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??un(o),d=a.nextChunkId,u={id:d,data:n},p=[...c.bufferChunks,u];let m=c.bufferLength+n.length;for(;m>Ry&&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=Js(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=Js(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=Js(t);r(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{r({sessions:new Map,nextChunkId:1})}})),hd=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Ly=[{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'}],_y=[{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'}],gd=r=>Object.fromEntries(r.map(s=>[s.id,s])),ul=gd(Ly),Zs=gd(_y),Oy="ibm-plex-sans",kn="ibm-plex-mono";function By(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 ml(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 Qo=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),x=l.useRef(n),y=l.useRef([]),b=l.useRef(!1),v=l.useRef(0),k=l.useRef(null),j=l.useRef(null),[,S]=l.useReducer(C=>C+1,0);g.current=t,x.current=n;const w=l.useCallback(()=>{y.current=[],b.current=!1,v.current=0,k.current=null},[]),T=l.useCallback(()=>{const C=h.current,D=f.current,P=p.current;if(!C||!D||!P)return;const O=P.getBoundingClientRect();if(!(O.width<24||O.height<24))try{C.fit(),x.current(D.cols,D.rows)}catch{}},[]),M=l.useCallback(()=>{if(b.current)return;const C=()=>{const D=f.current;if(!D){w();return}const P=y.current.shift();if(P===void 0){b.current=!1;return}b.current=!0,D.write(P,()=>{b.current=!1,y.current.length>0&&(typeof window<"u"?window.setTimeout(C,0):C())})};C()},[w]),N=l.useCallback(C=>{C&&(y.current=[C],b.current=!1,M())},[M]),A=l.useCallback(()=>{if(j.current?.(),j.current=null,!d)return;const C=p.current;if(!C)return;const D=C.querySelector(".xterm-viewport");if(!D)return;const P=2.2,O=2.8,W=25,R=.25,V=8,ae=.05,K=.015,B={lastY:null,lastTime:null,velocity:0,rafId:null},L=()=>typeof performance<"u"?performance.now():Date.now(),ne=()=>Math.max(0,D.scrollHeight-D.clientHeight),Se=ce=>{const Ie=ne();D.scrollTop=Math.max(0,Math.min(Ie,ce))},Ne=ce=>{if(!ce)return;const Ie=D.scrollTop;return Se(Ie+ce),D.scrollTop!==Ie},de=()=>{B.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(B.rafId),B.rafId=null},ge={passive:!1,capture:!0};if(typeof window<"u"&&"PointerEvent"in window){const ce=Object.assign(B,{pointerId:null}),Ie=J=>{if(J.pointerType==="touch"){de(),ce.pointerId=J.pointerId,ce.lastY=J.clientY,ce.lastTime=L(),ce.velocity=0;try{C.setPointerCapture(J.pointerId)}catch{}}},ie=J=>{if(J.pointerType!=="touch"||ce.pointerId!==J.pointerId)return;if(ce.lastY===null){ce.lastY=J.clientY,ce.lastTime=L();return}const E=ce.lastY,re=ce.lastTime??L(),q=L();ce.lastY=J.clientY,ce.lastTime=q;const F=E-J.clientY;if(Math.abs(F)<1)return;const $=Math.max(q-re,8),U=P+Math.min(O,Math.abs(F)/W),H=F*U,X=H/$;ce.velocity=ce.velocity*(1-R)+X*R,ce.velocity>V?ce.velocity=V:ce.velocity<-V&&(ce.velocity=-V),J.cancelable&&J.preventDefault(),J.stopPropagation(),Ne(H)},Ce=J=>{if(J.pointerType!=="touch"||ce.pointerId!==J.pointerId)return;ce.pointerId=null,ce.lastY=null,ce.lastTime=null;try{C.releasePointerCapture(J.pointerId)}catch{}if(typeof window>"u")return;if(Math.abs(ce.velocity)<ae){ce.velocity=0;return}let E=L();const re=()=>{const q=L(),F=Math.max(q-E,8);E=q;const $=Ne(ce.velocity*F)??!1,U=Math.sign(ce.velocity),H=Math.max(0,Math.abs(ce.velocity)-K*F);if(ce.velocity=H*U,!$||H<=ae){de(),ce.velocity=0;return}ce.rafId=window.requestAnimationFrame(re)};ce.rafId=window.requestAnimationFrame(re)};C.addEventListener("pointerdown",Ie,ge),C.addEventListener("pointermove",ie,ge),C.addEventListener("pointerup",Ce,ge),C.addEventListener("pointercancel",Ce,ge);const qe=C.style.touchAction;C.style.touchAction="none",j.current=()=>{de(),C.removeEventListener("pointerdown",Ie,ge),C.removeEventListener("pointermove",ie,ge),C.removeEventListener("pointerup",Ce,ge),C.removeEventListener("pointercancel",Ce,ge),C.style.touchAction=qe};return}const Ae=ce=>{ce.touches.length===1&&(de(),B.lastY=ce.touches[0].clientY,B.lastTime=L(),B.velocity=0)},Te=ce=>{if(ce.touches.length!==1){B.lastY=null,B.lastTime=null,B.velocity=0,de();return}const Ie=ce.touches[0].clientY;if(B.lastY===null){B.lastY=Ie,B.lastTime=L();return}const ie=B.lastY,Ce=B.lastTime??L(),qe=L();B.lastY=Ie,B.lastTime=qe;const J=ie-Ie;if(Math.abs(J)<1)return;const E=Math.max(qe-Ce,8),re=P+Math.min(O,Math.abs(J)/W),q=J*re,F=q/E;B.velocity=B.velocity*(1-R)+F*R,B.velocity>V?B.velocity=V:B.velocity<-V&&(B.velocity=-V),ce.preventDefault(),ce.stopPropagation(),Ne(q)},Pe=()=>{if(B.lastY=null,B.lastTime=null,typeof window>"u")return;if(Math.abs(B.velocity)<ae){B.velocity=0;return}let ce=L();const Ie=()=>{const ie=L(),Ce=Math.max(ie-ce,8);ce=ie;const qe=Ne(B.velocity*Ce)??!1,J=Math.sign(B.velocity),E=Math.max(0,Math.abs(B.velocity)-K*Ce);if(B.velocity=E*J,!qe||E<=ae){de(),B.velocity=0;return}B.rafId=window.requestAnimationFrame(Ie)};B.rafId=window.requestAnimationFrame(Ie)};C.addEventListener("touchstart",Ae,ge),C.addEventListener("touchmove",Te,ge),C.addEventListener("touchend",Pe,ge),C.addEventListener("touchcancel",Pe,ge);const Re=C.style.touchAction;C.style.touchAction="none",j.current=()=>{de(),C.removeEventListener("touchstart",Ae,ge),C.removeEventListener("touchmove",Te,ge),C.removeEventListener("touchend",Pe,ge),C.removeEventListener("touchcancel",Pe,ge),C.style.touchAction=Re}},[d]);return l.useEffect(()=>{const C=new nm.Terminal(ml(a,i,o)),D=new om.FitAddon;f.current=C,h.current=D,C.loadAddon(D);const P=p.current;if(P){C.open(P);const R=P.querySelector(".xterm-viewport");R&&(R.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),m.current=R,S()),T(),C.focus()}const O=[C.onData(R=>{g.current(R)})],W=new ResizeObserver(()=>{T()});return P&&W.observe(P),()=>{j.current?.(),j.current=null,O.forEach(R=>R.dispose()),W.disconnect(),C.dispose(),f.current=null,h.current=null,w()}},[T,a,i,o,w]),l.useEffect(()=>{const C=f.current;if(!C)return;const D=ml(a,i,o);Object.assign(C.options,D),T()},[T,a,i,o]),l.useEffect(()=>{const C=f.current;C&&(C.reset(),w(),T(),C.focus())},[r,T,w]),l.useEffect(()=>(A(),()=>{j.current?.(),j.current=null}),[A,r]),l.useEffect(()=>{const C=f.current;if(!C)return;if(s.length===0){v.current!==0&&(C.reset(),w(),T());return}const D=s[0].id;if(k.current===null&&(k.current=D),(k.current!==D||v.current>s.length)&&(C.reset(),w(),k.current=D),v.current<s.length){const O=s.slice(v.current);N(O.map(W=>W.data).join("")),v.current=s.length}},[s,N,T,w]),l.useImperativeHandle(u,()=>({focus:()=>{f.current?.focus()},clear:()=>{const C=f.current;C&&(C.reset(),w(),T())},fit:()=>{T()}}),[T,w]),e.jsx("div",{ref:p,className:I("relative h-full w-full",c),children:m.current?e.jsx(ba,{containerRef:m,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null})});Qo.displayName="TerminalViewport";const fl=13,$y={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},mn={ctrl:"5",cmd:"3"},zy={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},Hy=(r,s)=>{if(s)switch(r){case"arrow-up":return`\x1B[1;${mn[s]}A`;case"arrow-down":return`\x1B[1;${mn[s]}B`;case"arrow-right":return`\x1B[1;${mn[s]}C`;case"arrow-left":return`\x1B[1;${mn[s]}D`}return $y[r]??null},Wy=()=>{const{terminal:r}=ar(),{currentTheme:s}=ir(),{monoFont:t}=hd(),{isMobile:n,hasTouchInput:o}=Et(),{currentSessionId:a,sessions:i,worktreeMetadata:c}=fe(),d=a?c.get(a)??void 0:void 0,u=l.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const $=i.find(H=>H.id===a),U=typeof $?.directory=="string"?$.directory:null;return U&&U.length>0?U:null},[a,i,d]),{currentDirectory:p,homeDirectory:m}=jt(),f=u||p||null,h=l.useMemo(()=>f?m?f===m?"~":f.startsWith(m+"/")?"~"+f.slice(m.length):f:f:"",[f,m]),g=dl(),x=g.sessions,y=g.setTerminalSession,b=g.setConnecting,v=g.appendToBuffer,k=g.clearTerminalSession,j=g.removeTerminalSession,S=g.clearBuffer,w=l.useMemo(()=>{if(f)return x.get(f)},[x,f]),T=w?.terminalSessionId??null,M=w?.bufferChunks??[],N=w?.bufferLength??0,A=w?.isConnecting??!1,C=T,[D,P]=l.useState(null),[O,W]=l.useState(!1),[R,V]=l.useState(null),[ae,K]=l.useState(!1),B=l.useRef(null),L=l.useRef(null),ne=l.useRef(C),Se=l.useRef(f),Ne=l.useRef(null),ge=we($=>$.activeMainTab)==="terminal";l.useEffect(()=>{ne.current=C},[C]),l.useEffect(()=>{Se.current=f},[f]),l.useEffect(()=>{!n&&R!==null&&V(null)},[n,R,V]),l.useEffect(()=>{!C&&R!==null&&V(null)},[C,R,V]);const ve=l.useCallback(()=>{B.current?.(),B.current=null,L.current=null},[]);l.useEffect(()=>()=>{ve(),ne.current=null},[ve]);const Ae=l.useCallback($=>{if(L.current===$)return;ve();const U=r.connect($,{onEvent:H=>{const X=Se.current;if(X)switch(H.type){case"connected":{b(X,!1),P(null),W(!1),Ne.current?.focus();break}case"reconnecting":{const Y=H.attempt??0,Ee=H.maxAttempts??3;P(`Reconnecting (${Y}/${Ee})...`),W(!1);break}case"data":{H.data&&v(X,H.data);break}case"exit":{const Y=typeof H.exitCode=="number"?H.exitCode:null,Ee=typeof H.signal=="number"?H.signal:null;v(X,`\r
|
|
95
|
-
[Process exited${Y!==null?` with code ${Y}`:""}${Ee!==null?` (signal ${Ee})`:""}]\r
|
|
96
|
-
`),k(X),b(X,!1),P("Terminal session ended"),W(!1),ve();break}}},onError:(H,X)=>{const Y=Se.current;if(!Y)return;const Ee=X?`Connection failed: ${H.message}`:H.message||"Terminal stream connection error";P(Ee),W(!!X),X&&(b(Y,!1),ve(),j(Y))}},zy);B.current=()=>{U.close(),L.current=null},L.current=$},[v,k,ve,j,b,r,P]);l.useEffect(()=>{let $=!1;if(!f){P(a?"No working directory available for terminal.":"Select a session to open the terminal."),ve();return}return(async()=>{const H=f;if(!Se.current||Se.current!==H)return;let Y=dl.getState().getTerminalSession(H)?.terminalSessionId??null;if(!Y){P(null),W(!1),b(H,!0);try{const Ee=await r.createSession({cwd:H});if($){try{await r.close(Ee.sessionId)}catch{}return}y(H,Ee),Y=Ee.sessionId}catch(Ee){$||(P(Ee instanceof Error?Ee.message:"Failed to start terminal session"),W(!0),b(H,!1));return}}!Y||$||(ne.current=Y,Ae(Y))})(),()=>{$=!0,ne.current=null,ve()}},[a,f,C,j,b,y,Ae,ve,r]);const Te=l.useCallback(async()=>{if(!f||ae)return;K(!0),P(null),W(!1),ve();const $=ne.current;try{if(r.restartSession&&$){const U=await r.restartSession($,{cwd:f});y(f,U),ne.current=U.sessionId,Ae(U.sessionId)}else{if($)try{await r.close($)}catch{}j(f)}}catch(U){P(U instanceof Error?U.message:"Failed to restart terminal"),W(!0)}finally{K(!1)}},[f,ae,ve,r,y,Ae,j]),Pe=l.useCallback(async()=>{if(f&&!ae){K(!0),P(null),W(!1),ve();try{r.forceKill&&await r.forceKill({cwd:f})}catch{}j(f),S(f),Ne.current?.clear(),await new Promise($=>setTimeout($,100));try{b(f,!0);const $=await r.createSession({cwd:f});y(f,$),ne.current=$.sessionId,Ae($.sessionId)}catch($){P($ instanceof Error?$.message:"Failed to create terminal"),W(!0),b(f,!1)}finally{K(!1)}}},[f,ae,ve,r,j,S,b,y,Ae]),Re=l.useCallback(()=>{if(!f)return;S(f),Ne.current?.clear(),Ne.current?.focus();const $=ne.current;$&&r.sendInput($,"\f").catch(U=>{P(U instanceof Error?U.message:"Failed to refresh prompt")})},[S,f,P,r]),ce=l.useCallback($=>{if(!$)return;let U=$,H=!1;if(R&&$.length>0){const Y=$[0];if(Y.length===1&&/[a-zA-Z]/.test(Y)){const Ee=Y.toUpperCase();(R==="ctrl"||R==="cmd")&&(U=String.fromCharCode(Ee.charCodeAt(0)&31),H=!0)}H||(H=!0)}const X=ne.current;X&&(r.sendInput(X,U).catch(Y=>{P(Y instanceof Error?Y.message:"Failed to send input")}),H&&(V(null),Ne.current?.focus()))},[R,V,r]),Ie=l.useCallback(($,U)=>{const H=ne.current;H&&r.resize({sessionId:H,cols:$,rows:U}).catch(()=>{})},[r]),ie=l.useCallback($=>{V(U=>U===$?null:$),Ne.current?.focus()},[V]),Ce=l.useCallback($=>{const U=Hy($,R);U&&(ce(U),V(null),Ne.current?.focus())},[R,ce,V]);l.useEffect(()=>{if(!n||!R||!C)return;const $=U=>{if(U.repeat)return;const H=U.key;if(!H||H==="Control"||H==="Meta"||H==="Alt"||H==="Shift")return;const X=H.length===1?H.toLowerCase():H,Y=U.code??"",Ee=Y.startsWith("Key")&&Y.length===4?Y.slice(3).toUpperCase():null,Be=H.length===1&&/[a-zA-Z]/.test(H)?H.toUpperCase():Ee,ct={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(X in ct){U.preventDefault(),U.stopPropagation(),Ce(ct[X]);return}if(R==="ctrl"&&Be&&Be.length===1&&Be>="A"&&Be<="Z"){const ot=String.fromCharCode(Be.charCodeAt(0)&31);U.preventDefault(),U.stopPropagation(),ce(ot),V(null),Ne.current?.focus()}};return window.addEventListener("keydown",$),()=>{window.removeEventListener("keydown",$)}},[R,Ce,ce,n,V,C]);const qe=l.useMemo(()=>{const $=Zs[kn].stack;if(typeof window>"u")return(Zs[t]??Zs[kn]).stack;const H=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return H&&H.trim().length>0?H.trim():(Zs[t]??Zs[kn]).stack??$},[t]),J=l.useMemo(()=>By(s),[s]),E=l.useMemo(()=>`${f??"no-dir"}::${C??"pending"}`,[f,C]);l.useEffect(()=>{if(!ge)return;const $=Ne.current;if(!$)return;const U=()=>{$.fit()};if(typeof window<"u"){const H=window.requestAnimationFrame(()=>{U(),$.focus()}),X=[220,400].map(Y=>window.setTimeout(U,Y));return()=>{window.cancelAnimationFrame(H),X.forEach(Y=>window.clearTimeout(Y))}}U()},[ge,E,C]);const re=D?.includes("Reconnecting"),q=D?re?e.jsx(am,{size:20,className:"text-amber-400"}):e.jsx(us,{size:20,className:"text-destructive"}):C&&!A&&!ae?e.jsx(hn,{size:20,className:"text-emerald-400"}):A||ae?e.jsx(za,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(za,{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:Te,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const F=!C||A||ae;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:[q,e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Re,disabled:!N,title:"Clear output",type:"button",children:[e.jsx(Gs,{size:16}),"Clear"]}),e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Te,disabled:ae,title:"Restart terminal session",type:"button",children:[e.jsx(Is,{size:16,className:I((A||ae)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(De,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>Ce("esc"),disabled:F,children:"Esc"}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ce("tab"),disabled:F,children:[e.jsx($a,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(De,{type:"button",size:"sm",variant:R==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ie("ctrl"),disabled:F,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:R==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ie("cmd"),disabled:F,children:[e.jsx(rr,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ce("arrow-up"),disabled:F,children:[e.jsx(Yr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ce("arrow-left"),disabled:F,children:[e.jsx($l,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ce("arrow-down"),disabled:F,children:[e.jsx(Cr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ce("arrow-right"),disabled:F,children:[e.jsx($a,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ce("enter"),disabled:F,children:[e.jsx(Bl,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:J.background},children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:ge?n?e.jsx(Qo,{ref:$=>{Ne.current=$},sessionKey:E,chunks:M,onInput:ce,onResize:Ie,theme:J,fontFamily:qe,fontSize:fl,enableTouchScroll:o},E):e.jsx(Xe,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Qo,{ref:$=>{Ne.current=$},sessionKey:E,chunks:M,onInput:ce,onResize:Ie,theme:J,fontFamily:qe,fontSize:fl,enableTouchScroll:o},E)}):null}),D&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:D}),O&&e.jsx(De,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Pe,disabled:ae,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},Uy=()=>{const{isSidebarOpen:r,activeMainTab:s,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i}=we(),{isMobile:c}=Et(),[d,u]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||u(typeof window.opencodeDesktop<"u")},[]),Qh({enabled:!0});const p=Qn(h=>h.checkForUpdates);l.useEffect(()=>{const h=setTimeout(()=>{p()},3e3);return()=>clearTimeout(h)},[p]),l.useEffect(()=>{we.getState().isMobile!==c&&t(c)},[c,t]),l.useEffect(()=>{if(typeof window>"u")return;let h;const g=()=>{h!==void 0&&window.clearTimeout(h),h=window.setTimeout(()=>{we.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",g),()=>{window.removeEventListener("resize",g),h!==void 0&&window.clearTimeout(h)}},[]),l.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const h=document.documentElement;let g=0,x=!1,y=0;const b=()=>{g=0,x=!0,h.style.setProperty("--oc-keyboard-inset","0px")},v=()=>{const S=window.visualViewport,w=S?Math.round(S.height):window.innerHeight,T=S?Math.max(0,Math.round(S.offsetTop)):0;h.style.setProperty("--oc-visual-viewport-offset-top",`${T}px`);const M=document.activeElement,N=M?.tagName,C=N==="INPUT"||N==="TEXTAREA"||N==="SELECT"||!!M?.isContentEditable,D=Math.round(h.clientHeight||window.innerHeight),P=w+T,O=Math.max(0,D-P),R=O>=(C?120:180)?O:0;if(x)R===0&&(x=!1),g=0;else if(g===0)R>0&&C&&(g=R);else{const V=w>y+6;R===0?g=0:V?b():R>g&&(g=R)}if(h.style.setProperty("--oc-keyboard-inset",`${g}px`),y=w,c&&C){const V=document.scrollingElement;V&&V.scrollTop!==0&&(V.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};v();const k=window.visualViewport;k?.addEventListener("resize",v),k?.addEventListener("scroll",v),window.addEventListener("resize",v),window.addEventListener("orientationchange",v),document.addEventListener("focusin",v,!0);const j=S=>{const w=S.target;if(!w)return;const T=w.tagName;(T==="INPUT"||T==="TEXTAREA"||T==="SELECT"||w.isContentEditable)&&b()};return document.addEventListener("focusout",j,!0),()=>{k?.removeEventListener("resize",v),k?.removeEventListener("scroll",v),window.removeEventListener("resize",v),window.removeEventListener("orientationchange",v),document.removeEventListener("focusin",v,!0),document.removeEventListener("focusout",j,!0)}},[c]);const m=l.useMemo(()=>{switch(s){case"git":return e.jsx(Py,{});case"diff":return e.jsx(nh,{});case"terminal":return e.jsx(Wy,{});default:return null}},[s]),f=s==="chat";return e.jsx(Zh,{children:e.jsxs("div",{className:I("main-content-safe-area h-[100dvh]",c?"flex flex-col":"flex",d?"bg-transparent":"bg-background"),children:[e.jsx(Bh,{}),e.jsx(Hh,{}),e.jsx(qh,{}),e.jsx(_h,{isOpen:a,onClose:()=>i(!1)}),c?e.jsxs(e.Fragment,{children:[e.jsx(vi,{}),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:I("absolute inset-0",!f&&"invisible"),children:e.jsx(cs,{children:e.jsx(Zo,{})})}),m&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(cs,{children:m})})]})}),e.jsx(Kt,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Vo,{mobileVariant:!0})})]}):e.jsxs(e.Fragment,{children:[e.jsx(uh,{isOpen:r,isMobile:c,children:e.jsx(Vo,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(vi,{}),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:I("absolute inset-0",!f&&"invisible"),children:e.jsx(cs,{children:e.jsx(Zo,{})})}),m&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(cs,{children:m})})]})})]})]}),e.jsx(ah,{})]})})},Vy=()=>{const[r,s]=l.useState("sessions"),t=fe(O=>O.currentSessionId),n=fe(O=>O.sessions),o=fe(O=>O.createSession),a=fe(O=>O.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),x=St(O=>O.isInitialized),y=St(O=>O.initializeApp),b=fe(O=>O.loadSessions),v=fe(O=>O.loadMessages),k=fe(O=>O.messages),[j,S]=l.useState(()=>x),[w,T]=l.useState(!1),M=l.useRef(!1),N=l.useRef(!1);l.useEffect(()=>{t&&s("chat")},[t]),l.useEffect(()=>{!t&&r==="chat"&&s("sessions")},[t,r]);const A=l.useCallback(()=>{s("sessions")},[]),C=l.useCallback(async()=>{(await o())?.id&&s("chat")},[o]);l.useEffect(()=>{const O=W=>{const R=W.detail,V=R?.status;(V==="connected"||V==="connecting"||V==="error"||V==="disconnected")&&(c(V),u(R?.error),V==="connected"&&m(!0))};return window.addEventListener("openchamber:connection-status",O),()=>window.removeEventListener("openchamber:connection-status",O)},[]);const D=l.useMemo(()=>j&&i==="connected"&&!w?!1:j?i==="error":i!=="connected"||w,[i,j,w]),P=p?800:250;return l.useEffect(()=>(g.current&&(window.clearTimeout(g.current),g.current=null),D?g.current=window.setTimeout(()=>h(!0),P):h(!1),()=>{g.current&&(window.clearTimeout(g.current),g.current=null)}),[P,D]),l.useEffect(()=>{(async()=>{if(!(w||j||i!=="connected")){T(!0);try{x||await y(),await b(),S(!0)}catch{}finally{T(!1)}}})()},[i,x,j,y,w,b]),l.useEffect(()=>{(async()=>{if(!j||i!=="connected"||r!=="chat")return;const W=t||n[0]?.id;if(!W)return;if(!(k.has(W)&&(k.get(W)?.length||0)>0)){t||a(W);try{await v(W)}catch{}}})()},[i,t,r,j,v,k,n,a]),l.useEffect(()=>{!j||M.current||!t&&n.length>0&&(a(n[0].id),M.current=!0)},[t,j,n,a]),l.useEffect(()=>{(async()=>{if(i!=="connected"||!j||N.current)return;const W=n.find(V=>V.id===t),R=W?.title?.toLowerCase()?.startsWith("new session");if(W&&R)a(W.id);else{const V=n.find(ae=>ae.title?.toLowerCase()?.startsWith("new session"));if(V)a(V.id);else{const ae=await o();ae?.id&&a(ae.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(Io,{title:"Sessions",onNewSession:C,onSettings:()=>s("settings")}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Vo,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>s("chat"),hideDirectoryControls:!0})})]}):r==="settings"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Io,{title:"Settings",showBack:!0,onBack:A}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(Gy,{})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Io,{title:n.find(O=>O.id===t)?.title||"Chat",showBack:!0,onBack:A,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(cs,{children:e.jsx(Zo,{})})})]}),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})]})]})},Io=({title:r,showBack:s,onBack:t,onNewSession:n,onSettings:o,showContextUsage:a})=>{const{getCurrentModel:i}=St(),c=fe(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($l,{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(as,{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(wr,{className:"h-5 w-5"})}),a&&f&&f.totalTokens>0&&e.jsx(Wo,{totalTokens:f.totalTokens,percentage:f.percentage,contextLimit:f.contextLimit,outputLimit:f.outputLimit??0,size:"compact"})]})},Gy=()=>e.jsx("div",{className:"flex flex-col h-full",children:e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(Fc,{})})}),pl=({...r})=>{const{theme:s="system"}=im();return e.jsx(lm,{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})},qy=(r=5e3)=>{const[s,t]=ue.useState(null);return ue.useEffect(()=>{if(!is())return;let n=!1,o=null;const a=async()=>{const i=await Tm();n||(t(i),o=setTimeout(a,r))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[r]),s},Ky=({onClose:r})=>{const{sessions:s,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=fe(),c=qy(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(Da,{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(cm,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),r&&e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:r,children:e.jsx(us,{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(dm,{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(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsxs(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Gs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(et,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(et,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(st,{delayDuration:1e3,children:[e.jsx(rt,{asChild:!0,children:e.jsx(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:s.map(m=>({id:m.id,title:m.title})),currentSessionId:o,cachedSessions:Array.from(t.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(et,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},Yy="openchamber-message-cursors",Nr="cursors",Xy=1,xd="openchamber.messageCursors",Ta=()=>typeof window<"u",Ia=()=>Ta()&&typeof indexedDB<"u",yd=()=>Ia()?new Promise((r,s)=>{const t=indexedDB.open(Yy,Xy);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Nr)||n.createObjectStore(Nr)},t.onerror=()=>{s(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{r(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),bd=()=>{if(!Ta())return{};try{const r=window.localStorage.getItem(xd);if(!r)return{};const s=JSON.parse(r);return s&&typeof s=="object"?s:{}}catch{return{}}},Jy=r=>{if(Ta())try{window.localStorage.setItem(xd,JSON.stringify(r))}catch{}},Zy=async(r,s,t)=>{if(!r||!s)return;if(Ia())try{const o=await yd();await new Promise((a,i)=>{const c=o.transaction(Nr,"readwrite");c.objectStore(Nr).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=bd();n[r]={messageId:s,completedAt:t},Jy(n)},Qy=async r=>{if(!r)return null;if(Ia())try{const t=await yd(),n=await new Promise((o,a)=>{const i=t.transaction(Nr,"readonly"),d=i.objectStore(Nr).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 bd()[r]??null},Ht=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},eb=50,tb=750,hl=new WeakMap,gl=r=>{if(!r||!Array.isArray(r))return 0;const s=hl.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 hl.set(r,t),t},sb=10,xl=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<sb?null:n},yl=(r,s)=>{const t=xl(r),n=xl(s);return!t||!n||t.length!==n.length?!0:t>n},ea=new Map,bl=(r,s)=>{const t=`${r}:${s}`,n=ea.get(t);if(n&&n.sessionId===r)return n.message;const i=(fe.getState().messages.get(r)||[]).find(c=>c.info.id===s)||null;return ea.set(t,{sessionId:r,message:i}),i},rb=()=>{const{addStreamingPart:r,completeStreamingMessage:s,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:p}=fe(),{checkConnection:m}=St(),f=jt(J=>J.currentDirectory),h=l.useMemo(()=>{if(!a)return;try{const E=d?.(a);if(E?.path)return E.path}catch(E){console.warn("Failed to inspect worktree metadata for session directory:",E)}const J=c.find(E=>E.id===a);if(J&&typeof J.directory=="string"&&J.directory.trim().length>0)return J.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]),x=we(J=>J.setEventStreamStatus),y=l.useRef(null),b=l.useCallback((J,E)=>{const re=E??null,q=y.current;if(!(q&&q.status===J&&q.hint===re)){if(y.current={status:J,hint:re},Ht()){const $={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[J]??"[INFO]",U=re?`${$} SSE ${J}: ${re}`:`${$} SSE ${J}`;console.info(U)}x(J,re)}},[x]),v=l.useCallback((J,E)=>{if(!J)return Promise.resolve();const re=Date.now();if(D.current)return D.current;if(re-P.current<tb)return Promise.resolve();const q=u(J).catch(F=>{console.warn(`[useEventStream] Failed to resync messages (${E}):`,F)}).finally(()=>{D.current=null,P.current=Date.now()});return D.current=q,q},[u]),k=l.useCallback(async J=>{Ht()&&console.info("[useEventStream] Bootstrapping state:",J);try{await Promise.all([p(),a?v(a,J):Promise.resolve()])}catch(E){console.warn("[useEventStream] Bootstrap failed:",J,E)}},[a,p,v]),j=l.useCallback((J,E,re)=>{Ht()&&console.debug(`[MessageTracker] ${J}: ${E}`,re)},[]),S=l.useCallback(J=>{Ht()&&console.debug(`[MessageTracker] ${J}: reported`)},[]),w=l.useRef(null),T=l.useRef(null),M=l.useRef(0);l.useRef(new Set);const N=l.useRef(new Map),A=l.useRef(null),C=l.useRef(!1),D=l.useRef(null),P=l.useRef(0),O=l.useCallback(()=>{if(typeof document>"u")return"visible";const J=document.visibilityState;return J==="hidden"&&document.hasFocus()?"visible":J},[]),W=l.useRef(O()),R=l.useRef(typeof navigator>"u"?!0:navigator.onLine),V=l.useRef(!1),ae=l.useRef(null),K=l.useRef(null),B=l.useRef(Date.now()),L=l.useRef(!1),ne=l.useCallback(J=>{const E=Date.now();E-B.current>25e3&&(k(J),B.current=E)},[k]);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(L.current=!0)},[]);const Se=l.useRef(new Map),Ne=l.useRef(new Map),de=l.useRef(a);l.useEffect(()=>{de.current=a},[a]);const ge=l.useCallback(J=>{if(!J)return;const E=Date.now(),re=N.current,q=re.get(J);q&&E-q<3e3||(re.set(J,E),setTimeout(async()=>{try{const F=await ke.getSession(J);if(F){const $={};typeof F.title=="string"&&F.title.length>0&&($.title=F.title),F.summary!==void 0&&($.summary=F.summary),Object.keys($).length>0&&i(J,$)}}catch(F){console.warn("Failed to refresh session metadata:",F)}},100))},[i]),ve=l.useCallback(()=>{A.current||(A.current=setTimeout(()=>{A.current=null;try{p()}catch(J){console.warn("Failed to refresh sessions after stream completion:",J)}},500))},[p]),Ae=l.useCallback((J,E)=>{if(Ne.current.get(J)===E)return;const q=Se.current.get(J);if(q&&(clearTimeout(q),Se.current.delete(J)),Ne.current.set(J,E),fe.setState({sessionActivityPhase:new Map(Ne.current)}),E==="cooldown"){const F=setTimeout(()=>{Se.current.delete(J),Ne.current.get(J)==="cooldown"&&(Ne.current.set(J,"idle"),fe.setState({sessionActivityPhase:new Map(Ne.current)}))},2e3);Se.current.set(J,F)}},[]),Te=l.useCallback(async()=>{try{const J=await ke.getSessionStatus();if(!J)return;Object.entries(J).forEach(([E,re])=>{if(!E||!re)return;const q=re,F=q.type==="busy"||q.type==="retry"?"busy":"idle";Ae(E,F)})}catch{}},[Ae]),Pe=l.useCallback(J=>{if(B.current=Date.now(),Ht()&&console.debug("[useEventStream] Received event:",J.type,J.properties),!J.properties)return;const E=J.properties;if(!new Set(["session.abort","session.error"]).has(J.type)){const q=(typeof E.session=="object"&&E.session!==null?E.session:null)||(typeof E.sessionInfo=="object"&&E.sessionInfo!==null?E.sessionInfo:null);if(q){const F=q,$=typeof F.id=="string"&&F.id.length>0?F.id:typeof F.sessionID=="string"&&F.sessionID.length>0?F.sessionID:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:typeof E.id=="string"&&E.id.length>0?E.id:void 0;if($){const U=typeof F.title=="string"?F.title:typeof E.title=="string"?E.title:void 0,H=typeof F.summary=="object"&&F.summary!==null?F.summary:typeof E.summary=="object"&&E.summary!==null?E.summary:void 0;if(U!==void 0||H!==void 0){const X={};U!==void 0&&(X.title=U),H!==void 0&&(X.summary=H),i($,X)}}}}switch(J.type){case"server.connected":m();break;case"global.disposed":case"server.instance.disposed":{k("server_disposed_event");break}case"openchamber:session-activity":{if(!L.current)break;const q=typeof E.sessionId=="string"?E.sessionId:null,F=typeof E.phase=="string"?E.phase:null;q&&(F==="idle"||F==="busy"||F==="cooldown")&&(Ae(q,F),ve());break}case"session.status":if(L.current)break;{const q=typeof E.sessionID=="string"?E.sessionID:null,F=typeof E.status=="object"&&E.status!==null?E.status:null,$=typeof F?.type=="string"?F.type:null;q&&$&&(Ae(q,$==="busy"||$==="retry"?"busy":"idle"),ve())}break;case"message.part.updated":{const q=typeof E.part=="object"&&E.part!==null?E.part:null;if(!q)break;const F=q,$=typeof E.info=="object"&&E.info!==null?E.info:E,U=typeof $.sessionID=="string"?$.sessionID:null,H=typeof F.sessionID=="string"&&F.sessionID.length>0?F.sessionID:typeof U=="string"&&U.length>0?U:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:null,X=typeof $.id=="string"?$.id:null,Y=typeof F.messageID=="string"&&F.messageID.length>0?F.messageID:typeof X=="string"&&X.length>0?X:typeof E.messageID=="string"&&E.messageID.length>0?E.messageID:null;if(!H||!Y){Ht()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:F.sessionID??U??E.sessionID,messageID:F.messageID??X??E.messageID});break}const Ee=H,Be=Y,ct=fe.getState().sessionMemoryState.get(Ee)?.trimmedHeadMaxId;if(ct&&!yl(Be,ct)){Ht()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:Ee,messageId:Be,trimmedHeadMaxId:ct});break}let ot="assistant";if($&&typeof $.role=="string")ot=$.role;else{const it=bl(Ee,Be);if(it){const dt=it.info.role;typeof dt=="string"&&(ot=dt)}}if(j(Be,"part_received",{role:ot}),ot==="user"&&F.synthetic===!0){j(Be,"skipped_synthetic_user_part");break}const Je={...q,type:q.type||"text"};j(Be,"addStreamingPart_called"),r(Ee,Be,Je,ot);break}case"message.updated":{const q=typeof E.info=="object"&&E.info!==null?E.info:E,F=q,$=typeof F.sessionID=="string"&&F.sessionID.length>0?F.sessionID:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:null,U=typeof F.id=="string"&&F.id.length>0?F.id:typeof E.messageID=="string"&&E.messageID.length>0?E.messageID:null;if(!$||!U){Ht()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:F.sessionID??E.sessionID,messageID:F.id??E.messageID});break}const H=$,X=U,Y=fe.getState().sessionMemoryState.get(H)?.trimmedHeadMaxId;if(Y&&!yl(X,Y)){Ht()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:H,messageId:X,trimmedHeadMaxId:Y});break}if(L.current&&Ht())try{const pe=E.parts||F.parts||[],se=(Array.isArray(pe)?pe.filter(ee=>ee?.type==="text"):[]).map(ee=>{const me=ee;return typeof me?.text=="string"?me.text:typeof me?.content=="string"?me.content:""}).join(`
|
|
97
|
-
`);console.info("[STREAM-TRACE] message.updated",{messageId:X,role:F.role,status:F.status,textLen:se.length,textPreview:se.slice(0,120),partsCount:Array.isArray(pe)?pe.length:0})}catch{}if(j(X,"message_updated",{role:F.role}),F.role==="user"){const pe=E.parts||F.parts,_=Array.isArray(pe)?pe:[],se={...q,userMessageMarker:!0,clientRole:"user"};if(t(H,X,se),_.length>0)for(let ee=0;ee<_.length;ee++){const me=_[ee];if(me.synthetic===!0)continue;const Q={...me,type:me?.type||"text",sessionID:me?.sessionID||H,messageID:me?.messageID||X};r(H,X,Q,"user")}j(X,"user_message_created_from_event",{partsCount:_.length});break}const Ee=bl(H,X),Be=gl(Ee?.parts||[]),ct=Ee?.parts?.some(pe=>pe?.type==="step-finish"&&pe.reason==="stop")??!1,ot=E.parts||F.parts,Je=Array.isArray(ot)?ot:[],it=Je.length>0,at=typeof(F.time||{})?.completed=="number";if(!it&&!at)break;if(F.role==="assistant"&&it){const pe=gl(Je),_=Be>0&&pe+eb<Be,se=Je.some(ee=>ee?.type==="step-finish"&&ee.reason==="stop");if(_&&!se){j(X,"skipped_shrinking_update",{incomingLen:pe,existingLen:Be});break}if(L.current){const ee=Be>0&&pe<Be,me=Je.some(oe=>{if(!oe||oe.type!=="text")return!1;const le=oe;return typeof le.text=="string"&&le.text.length>0});if(ee&&!(se&&me)){j(X,"desktop_shrinking_update_suppressed",{incomingLen:pe,existingLen:Be});break}}}if(t(H,X,q),it&&F.role!=="user"){const se=(fe.getState().messages.get(H)||[]).find(Q=>Q.info.id===X),ee=!se||se.parts.length===0;j(X,ee?"server_parts_injected":"server_parts_refreshed",{count:Je.length});const me=L.current&&F.role==="assistant"?Je.filter(Q=>Q?.type!=="text"):Je;for(let Q=0;Q<me.length;Q++){const oe=me[Q],le={...oe,type:oe?.type||"text",sessionID:oe?.sessionID||H,messageID:oe?.messageID||X};r(H,X,le,F.role),j(X,`server_part_${Q}`)}}const pt=q.time;if(q.role==="assistant"&&pt?.completed!==void 0&&q.role==="assistant"){const _=fe.getState().messages.get(H)||[];let se=null,ee="";for(let $e=0;$e<_.length;$e++){const kt=_[$e];kt.info.role==="assistant"&&kt.info.id>ee&&(ee=kt.info.id,se=kt.info.id)}if(X!==se)break;if(!(Je.some($e=>$e?.type==="step-finish"&&$e.reason==="stop")||ct)&&L.current){j(X,"desktop_completion_without_stop");break}const Q=pt?.completed!==void 0?pt?.completed:Date.now();if(pt?.completed||t(H,X,{...q,time:{...pt??{},completed:Q}}),j(X,"completed",{timeCompleted:Q}),S(X),Zy(H,X,Q),s(H,X),!L.current){const $e=q.sessionID,kt=typeof $e=="string"&&$e.length>0?$e:H;Ne.current.get(kt)==="busy"&&Ae(kt,"cooldown")}const oe=q.sessionID,le=typeof oe=="string"&&oe.length>0?oe:H;ge(le),q.summary&&typeof le=="string"&&n(le,null)}break}case"session.updated":{const q=typeof E.info=="object"&&E.info!==null?E.info:typeof E.sessionInfo=="object"&&E.sessionInfo!==null?E.sessionInfo:typeof E.session=="object"&&E.session!==null?E.session:E,F=typeof q.id=="string"&&q.id.length>0?q.id:typeof q.sessionID=="string"&&q.sessionID.length>0?q.sessionID:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:typeof E.id=="string"&&E.id.length>0?E.id:void 0;if(F){const $=typeof q.time=="object"&&q.time!==null?q.time:typeof E.time=="object"&&E.time!==null?E.time:null,U=$&&typeof $.compacting=="number"?$.compacting:null;n(F,U)}break}case"session.abort":{const q=typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:null,F=typeof E.messageID=="string"&&E.messageID.length>0?E.messageID:null;q&&F&&s(q,F);break}case"permission.updated":a===E.sessionID&&o(E);break;case"permission.replied":break;case"todo.updated":{const q=typeof E.sessionID=="string"?E.sessionID:null,F=Array.isArray(E.todos)?E.todos:[];q&&F.length>0&&xg(q,F);break}}},[a,r,s,t,o,m,ge,ve,n,i,j,S,Ae,k]),Re=l.useCallback(()=>{const J=O();return W.current=J,J==="visible"&&R.current},[O]),ce=l.useCallback(()=>{Ht()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:L.current,hasUnsubscribe:!!w.current,currentSessionId:de.current,effectiveDirectory:g,onlineStatus:R.current,visibilityState:W.current,lastEventTimestamp:B.current,reconnectAttempts:M.current})},[g]),Ie=l.useCallback(async()=>!0,[]),ie=l.useCallback(()=>{if(C.current){Ht()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(C.current=!0,T.current&&(clearTimeout(T.current),T.current=null),w.current){const J=w.current;w.current=null;try{J()}catch(E){console.warn("[useEventStream] Error during unsubscribe:",E)}}C.current=!1},[]),Ce=l.useCallback(async J=>{if(ce(),!Re()){V.current=!0,R.current?b("paused","Paused while hidden"):b("offline","Waiting for network");return}L.current&&(await Ie()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),J?.resetAttempts&&(M.current=0),ie(),B.current=Date.now(),b("connecting",null),Ht()&&console.info("[useEventStream] Starting event stream...");const E=q=>{console.warn("Event stream error:",q)},re=()=>{const q=V.current;if(M.current=0,V.current=!1,B.current=Date.now(),b("connected",null),m(),q)k("sse_reconnected");else{const F=de.current;F&&setTimeout(()=>{v(F,"sse_reconnected").then(()=>ge(F)).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 q=ke.subscribeToEvents(Pe,E,re,g),F=()=>{try{q()}catch($){console.warn("[useEventStream] Error during unsubscribe:",$)}};C.current?F():w.current=F}catch(q){console.error("[useEventStream] Error during subscription:",q),E(q)}},[Re,ie,b,m,v,ge,ve,s,Pe,g,Ae,Ie,ce,k]),qe=l.useCallback(J=>{if(!Re()){V.current=!0,ie(),R.current?b("paused","Paused while hidden"):b("offline","Waiting for network");return}const E=M.current+1;M.current=E;const re=J??`Retrying (${E})`;b("reconnecting",re);const q=E<=3?Math.min(1e3*Math.pow(2,E-1),8e3):Math.min(2e3*Math.pow(2,E-3),32e3),F=Math.floor(Math.random()*250),$=q+F;T.current&&clearTimeout(T.current),T.current=setTimeout(()=>{Ce({resetAttempts:!1})},$)},[Re,ie,b,Ce]);l.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=j);let J=null;L.current&&typeof window<"u"&&(J=X=>{const Y=typeof X.detail?.sessionId=="string"?X.detail.sessionId:null,Ee=typeof X.detail?.phase=="string"?X.detail.phase:null;Y&&(Ee==="idle"||Ee==="busy"||Ee==="cooldown")&&(Ae(Y,Ee),ve())},window.addEventListener("openchamber:session-activity",J));const E=()=>{ae.current&&(clearTimeout(ae.current),ae.current=null)},re=()=>{ae.current||(ae.current=setTimeout(()=>{const X=O();W.current=X,X!=="visible"?(ie(),V.current=!0,b("paused","Paused while hidden")):E()},5e3))},q=()=>{if(W.current=O(),W.current==="visible"){if(E(),ne("visibility_restore"),V.current||!w.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const X=de.current;X&&(v(X,"visibility_restore").catch(()=>{}),ge(X)),p(),Te(),b("connecting","Resuming stream"),Ce({resetAttempts:!0})}}else b("paused","Paused while hidden"),re()},F=()=>{if(W.current=O(),W.current==="visible"&&(E(),ne("window_focus"),V.current||!w.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const X=de.current;X&&(ge(X),v(X,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(Y=>console.warn("[useEventStream] Failed to refresh messages:",Y))),p(),Te(),b("connecting","Resuming stream"),Ce({resetAttempts:!0})}},$=()=>{R.current=!0,ne("network_restored"),(V.current||!w.current)&&(b("connecting","Network restored"),Ce({resetAttempts:!0}))},U=()=>{R.current=!1,V.current=!0,b("offline","Waiting for network"),ie()};typeof document<"u"&&document.addEventListener("visibilitychange",q),typeof window<"u"&&(window.addEventListener("online",$),window.addEventListener("offline",U),window.addEventListener("focus",F));const H=setTimeout(()=>{Ce({resetAttempts:!0})},100);return K.current&&clearInterval(K.current),K.current=setInterval(()=>{if(!Re())return;Date.now()-B.current>25e3&&Promise.resolve().then(async()=>{try{await ke.checkHealth()?B.current=Date.now():qe("Refreshing stalled stream")}catch(Y){console.warn("Health check after stale stream failed:",Y),qe("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(H),J&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",J),typeof document<"u"&&document.removeEventListener("visibilitychange",q),typeof window<"u"&&(window.removeEventListener("online",$),window.removeEventListener("offline",U),window.removeEventListener("focus",F)),E(),K.current&&(clearInterval(K.current),K.current=null);const X=Se.current;X.forEach(Y=>clearTimeout(Y)),X.clear(),ea.clear(),V.current=!1,W.current=O(),R.current=typeof navigator>"u"?!0:navigator.onLine,ie(),A.current&&(clearTimeout(A.current),A.current=null),b("idle",null)}},[g,j,O,ie,b,Ce,qe,u,ge,Ae,Te,Re])},nb=()=>{const{createSession:r,abortCurrentOperation:s,initializeNewOpenChamberSession:t,armAbortPrompt:n,clearAbortPrompt:o,currentSessionId:a}=fe(),{toggleCommandPalette:i,toggleHelpDialog:c,toggleSidebar:d,setSessionSwitcherOpen:u,setSessionCreateDialogOpen:p,setActiveMainTab:m,setSettingsDialogOpen:f}=we(),{agents:h}=St(),{themeMode:g,setThemeMode:x}=ir(),{working:y}=Xc(),b=l.useRef(null),v=l.useRef(null),k=l.useRef(!1),j=l.useCallback(()=>{v.current&&(clearTimeout(v.current),v.current=null),b.current=null,o()},[o]);l.useEffect(()=>{const S=w=>{if(w.ctrlKey&&w.key==="x"&&(w.preventDefault(),i()),w.ctrlKey&&w.shiftKey&&w.key.toLowerCase()==="l"){const M=ga()?.diagnostics;if(!M||(w.preventDefault(),k.current))return;k.current=!0,M.downloadLogs().then(({fileName:N,content:A})=>{const C=N||"openchamber.log",D=new Blob([A],{type:"text/plain;charset=utf-8"}),P=URL.createObjectURL(D),O=document.createElement("a");O.href=P,O.download=C,document.body.appendChild(O),O.click(),document.body.removeChild(O),URL.revokeObjectURL(P)}).finally(()=>{k.current=!1});return}if(w.ctrlKey&&w.key==="h"&&(w.preventDefault(),c()),w.ctrlKey&&!w.metaKey&&w.key.toLowerCase()==="n"){if(w.preventDefault(),w.shiftKey){p(!0);return}r().then(T=>{T&&t(T.id,h)})}if((w.metaKey||w.ctrlKey)&&w.key==="/"){w.preventDefault();const T=["light","dark","system"],N=(T.indexOf(g)+1)%T.length;x(T[N])}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="g"){w.preventDefault();const{activeMainTab:T}=we.getState();m(T==="git"?"chat":"git");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="e"){w.preventDefault();const{activeMainTab:T}=we.getState();m(T==="diff"?"chat":"diff");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="t"){w.preventDefault();const{activeMainTab:T}=we.getState();m(T==="terminal"?"chat":"terminal");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key===","){w.preventDefault();const{isSettingsDialogOpen:T}=we.getState();f(!T);return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="l"){w.preventDefault();const{isMobile:T,isSessionSwitcherOpen:M}=we.getState();T?u(!M):d();return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="i"){w.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(w.key==="Escape"){const T=a;if(!(y.canAbort&&!!T)){j();return}const N=Date.now(),A=b.current;if(A&&N<A){w.preventDefault(),j(),s();return}w.preventDefault();const C=n(3e3)??N+3e3;b.current=C,v.current&&clearTimeout(v.current);const D=Math.max(C-N,0);v.current=setTimeout(()=>{b.current&&Date.now()>=b.current&&j()},D||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[r,s,i,c,d,u,p,m,f,x,g,t,h,y,n,j,a]),l.useEffect(()=>()=>{j()},[j])},wl="openchamber:menu-action",ob=r=>{const{createSession:s,initializeNewOpenChamberSession:t}=fe(),{toggleCommandPalette:n,toggleHelpDialog:o,toggleSidebar:a,setSessionCreateDialogOpen:i,setActiveMainTab:c,setSettingsDialogOpen:d,setAboutDialogOpen:u}=we(),{agents:p}=St(),{setDirectory:m}=jt(),{setThemeMode:f}=ir(),h=l.useRef(!1),g=l.useCallback(()=>{is()&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(x=>{x.success&&x.path?m(x.path,{showOverlay:!0}):x.error&&x.error!=="Directory selection cancelled"&&xe.error("Failed to select directory",{description:x.error})}).catch(x=>{console.error("Desktop: Error selecting directory:",x),xe.error("Failed to select directory")}):Qs.requestDirectoryDialog()},[m]);l.useEffect(()=>{const x=y=>{switch(y.detail){case"about":u(!0);break;case"settings":d(!0);break;case"command-palette":n();break;case"new-session":s().then(v=>{v&&t(v.id,p)});break;case"worktree-creator":i(!0);break;case"change-workspace":g();break;case"open-git-tab":{const{activeMainTab:v}=we.getState();c(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=we.getState();c(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=we.getState();c(v==="terminal"?"chat":"terminal");break}case"theme-light":f("light");break;case"theme-dark":f("dark");break;case"theme-system":f("system");break;case"toggle-sidebar":a();break;case"toggle-memory-debug":r?.();break;case"help-dialog":o();break;case"download-logs":{const k=ga()?.diagnostics;if(!k||h.current)break;h.current=!0,k.downloadLogs().then(({fileName:j,content:S})=>{const w=j||"openchamber.log",T=new Blob([S],{type:"text/plain;charset=utf-8"}),M=URL.createObjectURL(T),N=document.createElement("a");N.href=M,N.download=w,document.body.appendChild(N),N.click(),document.body.removeChild(N),URL.revokeObjectURL(M),xe.success("Logs saved",{description:`Downloaded to ~/Downloads/${w}`})}).catch(()=>{xe.error("Failed to download logs")}).finally(()=>{h.current=!1});break}}};return window.addEventListener(wl,x),()=>window.removeEventListener(wl,x)},[s,t,n,o,a,i,c,d,u,f,p,r,g])},ab=r=>r.role==="assistant",vl=r=>{const s=r.info;if(!ab(s))return;const t=s.time?.completed;return typeof t=="number"?t:void 0},Nn=r=>{if(!r)return!1;if(r.role==="user")return!0;const s=r;return s.clientRole==="user"?!0:!!s.userMessageMarker},jl=r=>(Array.isArray(r?.parts)?r.parts:[]).map(n=>Br(n)).join(" ").replace(/\s+/g," ").trim(),ib=(r,s)=>{if(!r||!Nn(r.info))return-1;const t=jl(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(!Nn(i.info))return;const d=jl(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(!Nn(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},lb=()=>{const{currentSessionId:r,messages:s,streamingMessageIds:t}=fe(),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 ke.getSessionMessages(r),p=await Qy(r);if(!u)return;const m=d[d.length-1];if(m){const f=u.findIndex(x=>x.info.id===m.info.id),g=f===-1?ib(m,u):f;if(g!==-1)if(g<u.length-1){const x=u.slice(g+1);console.log(`[SYNC] Found ${x.length} new messages to append`);const y=[...d,...x],{syncMessages:b}=fe.getState();b(r,y)}else{const x=u[g],y=d[d.length-1],b=vl(x),v=vl(y);if(b&&!v){console.log("[SYNC] Last message completed on server");const k=[...d.slice(0,-1),x],{syncMessages:j}=fe.getState();j(r,k)}}else if(Nn(m.info)){const x=u.slice(-Ot.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:y}=fe.getState();y(r,x)}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:x}=fe.getState();x(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}=fe.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}=fe.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])},cb=()=>{l.useEffect(()=>{let r=!1;return(async()=>{try{const t=await ke.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&&fe.setState({sessionActivityPhase:n})}catch{}})(),()=>{r=!0}},[])};function db(){const{git:r}=ar(),s=jt(i=>i.currentDirectory),{setActiveDirectory:t,startPolling:n,stopPolling:o,fetchAll:a}=At();l.useEffect(()=>{if(!s||!r){o();return}return t(s),a(s,r),n(r),()=>{o()}},[s,r,t,n,o,a])}function ub({children:r}){return db(),e.jsx(e.Fragment,{children:r})}const mb=()=>{const[{isUpdating:r,message:s},t]=l.useState(()=>Km());return l.useEffect(()=>qm(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(Is,{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},fb=({open:r,onOpenChange:s})=>{const[t,n]=l.useState(null);l.useEffect(()=>{if(!r)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:c}=await br(async()=>{const{getVersion:u}=await import("./vendor-.pnpm-BcYW6LTb.js").then(p=>p.c3);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();n(d)}catch{n("1.3.0")}})():n("1.3.0")},[r]);const o=t;return e.jsx(vs,{open:r,onOpenChange:s,children:e.jsx(js,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(Ko,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),o&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",o]})]}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["A fan-made interface for"," ",e.jsx("a",{href:"https://opencode.ai/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground transition-colors",children:"OpenCode"})," ","agent"]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Fl,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Pl,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:"Made with love to comunity"})]})})})};function Sl({apis:r,children:s}){return e.jsx(va.Provider,{value:r,children:s})}const pb="curl -fsSL https://opencode.ai/install | bash",hb=3e3;function gb({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(_s,{className:"h-4 w-4"})})]})}const xb=3e4;function yb({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),xb);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 br(async()=>{const{getCurrentWindow:h}=await import("./vendor-.pnpm-BcYW6LTb.js").then(g=>g.c2);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(pb),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,hb);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(Lo,{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(gb,{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(Lo,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."})]}),n&&e.jsxs("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["Already installed? Make sure ",e.jsx("code",{className:"text-foreground/70",children:"opencode"})," is in your PATH"]}),e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["or set ",e.jsx("code",{className:"text-foreground/70",children:"OPENCODE_BINARY"})," environment variable."]})]})]})}const bb=()=>{const{isAboutDialogOpen:r,setAboutDialogOpen:s}=we();return e.jsx(fb,{open:r,onOpenChange:s})};function wb({apis:r}){const{initializeApp:s,loadProviders:t,isInitialized:n}=St(),{error:o,clearError:a,loadSessions:i}=fe(),c=jt(S=>S.currentDirectory),d=jt(S=>S.isSwitchingDirectory),[u,p]=l.useState(!1),{uiFont:m,monoFont:f}=hd(),[h,g]=l.useState(()=>r.runtime.isDesktop),[x,y]=l.useState(()=>r.runtime.isVSCode),[b,v]=l.useState(()=>r.runtime.isDesktop?Im():!0);l.useEffect(()=>{g(r.runtime.isDesktop),y(r.runtime.isVSCode)},[r.runtime.isDesktop,r.runtime.isVSCode]),l.useEffect(()=>(Za(r),()=>Za(null)),[r]),l.useEffect(()=>{if(typeof document>"u")return;const S=document.documentElement,w=ul[m]?.stack??ul[Oy].stack,T=Zs[f]?.stack??Zs[kn].stack;S.style.setProperty("--font-sans",w),S.style.setProperty("--font-heading",w),S.style.setProperty("--font-family-sans",w),S.style.setProperty("--font-mono",T),S.style.setProperty("--font-family-mono",T),S.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=w)},[m,f]),l.useEffect(()=>{if(n){const w=setTimeout(()=>{const T=document.getElementById("initial-loading");T&&(T.classList.add("fade-out"),setTimeout(()=>{T.remove()},300))},150);return()=>clearTimeout(w)}},[n]),l.useEffect(()=>{const S=setTimeout(()=>{const w=document.getElementById("initial-loading");w&&!n&&(w.classList.add("fade-out"),setTimeout(()=>{w.remove()},300))},5e3);return()=>clearTimeout(S)},[n]),l.useEffect(()=>{(async()=>{await s(),await t()})()},[s,t]),l.useEffect(()=>{if(d)return;(async()=>{ke.setDirectory(c),await i()})()},[c,d,i]),rb(),nb();const k=l.useCallback(()=>{p(S=>!S)},[]);ob(k),lb(),cb(),Ic(),l.useEffect(()=>{const S=w=>{(w.metaKey||w.ctrlKey)&&w.shiftKey&&w.key==="M"&&(w.preventDefault(),p(T=>!T))};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[]),l.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const j=l.useCallback(()=>{v(!0),window.location.reload()},[]);return h&&!b?e.jsx(cs,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(yb,{onCliAvailable:j})})}):x?e.jsx(cs,{children:e.jsx(Sl,{apis:r,children:e.jsx(al,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Vy,{}),e.jsx(pl,{})]})})})}):e.jsx(cs,{children:e.jsx(Sl,{apis:r,children:e.jsx(ub,{children:e.jsx(al,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(Uy,{}),e.jsx(pl,{}),e.jsx(mb,{}),e.jsx(bb,{}),u&&e.jsx(Ky,{onClose:()=>p(!1)})]})})})})})}const wd=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=jt.getState();r&&t.homeDirectory!==r&&t.synchronizeHomeDirectory(r),s&&t.setDirectory(s,{showOverlay:!1})},vd="/auth/session",vb=async()=>fetch(vd,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),jb=async r=>fetch(vd,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:r})}),Fa=({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})]}),Sb=({message:r="Preparing workspace…"})=>e.jsx(Fa,{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})})}),kb=({onRetry:r})=>e.jsx(Fa,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:"Unable to reach server"}),e.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:"We couldn't verify the UI session. Check that the service is running and try again."})]}),e.jsx(De,{type:"button",onClick:r,className:"w-full max-w-xs",children:"Retry"})]})}),Nb=({children:r})=>{const s=l.useMemo(()=>is(),[]),t=l.useMemo(()=>es(),[]),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(y=>y==="authenticated"?y:"pending");try{const y=await vb();if(y.ok){a("authenticated"),m("");return}if(y.status===401){a("locked");return}a("error")}catch(y){console.warn("Failed to check session status:",y),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 ec(),await tc(),await wd()))())},[n,o]);const x=async y=>{if(y.preventDefault(),!(!i||d)){u(!0),m("");try{const b=await jb(i);if(b.ok){c(""),a("authenticated");return}if(b.status===401){m("Incorrect password. Try again."),a("locked");return}m("Unexpected response from server."),a("error")}catch(b){console.warn("Failed to submit UI password:",b),m("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(Sb,{}):o==="error"?e.jsx(kb,{onRetry:()=>void g()}):o==="locked"?e.jsx(Fa,{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:x,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(um,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(Ft,{id:"openchamber-ui-password",ref:f,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:y=>{c(y.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(De,{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(mm,{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})},Fo=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 Cb{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=Fo(s.colors.surface.muted),o=Fo(s.colors.surface.subtle),a=Fo(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=es()?Em:ma;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 Pa={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"}}},Ra={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"}}},qr=[Pa,Ra];function Vn(r){return qr.find(s=>s.metadata.id===r)}const jd=Pa.metadata.id,Sd=Ra.metadata.id,Mb=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,kd=r=>r==="dark"?Ra:Pa,Ab=r=>(qr.find(t=>t.metadata.variant===r)??kd(r)).metadata.id,fn=(r,s)=>{const t=Vn(r);return t&&t.metadata.variant===s?t:qr.find(o=>o.metadata.variant===s)??kd(s)},Db=typeof window<"u"?l.useLayoutEffect:l.useEffect,Gn=(r,s)=>{if(!r)return s==="light"?jd:Sd;const t=Vn(r);return t&&t.metadata.variant===s?t.metadata.id:Ab(s)},Eb=r=>{let s=jd,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=Vn(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=Gn(a,"light"),t=Gn(i,"dark")}if(r){const o=Vn(r);o&&(o.metadata.variant==="light"?s=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:s,darkThemeId:t}};function Tb({children:r,defaultThemeId:s}){const t=ue.useMemo(()=>new Cb,[]),[n,o]=ue.useState(()=>Eb(s)),[a,i]=ue.useState(()=>Mb()),[c,d]=ue.useState(()=>typeof window>"u"||!es()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=ue.useMemo(()=>es(),[]),p=ue.useMemo(()=>u&&c?c:n.themeMode==="light"?fn(n.lightThemeId,"light"):n.themeMode==="dark"||a?fn(n.darkThemeId,"dark"):fn(n.lightThemeId,"light"),[u,n,a,c]),m=ue.useMemo(()=>u&&c?[c,...qr]:qr,[u,c]);ue.useEffect(()=>{if(!u)return;const j=T=>{d(T);const M=T.metadata.variant==="dark"?"dark":"light",N=we.getState();N.theme!==M&&N.setTheme(M)},S=T=>{const M=T.detail;M?.theme&&j(M.theme)},w=window.__OPENCHAMBER_VSCODE_THEME__;return w&&j(w),window.addEventListener("openchamber:vscode-theme",S),()=>window.removeEventListener("openchamber:vscode-theme",S)},[u]);const f=ue.useCallback(j=>{if(typeof document>"u")return;const S=j.colors.surface.background;is()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=S;let w=document.querySelector('meta[name="theme-color"]');w||(w=document.createElement("meta"),w.setAttribute("name","theme-color"),document.head.appendChild(w)),w.setAttribute("content",S);const T=j.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let M=document.querySelector(`meta[name="theme-color"][media="${T}"]`);M||(M=document.createElement("meta"),M.setAttribute("name","theme-color"),M.setAttribute("media",T),document.head.appendChild(M)),M.setAttribute("content",S)},[]),h=ue.useCallback(j=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",j)},[]);Db(()=>{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]),ue.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const j=window.matchMedia("(prefers-color-scheme: dark)"),S=w=>{i(w.matches)};return i(j.matches),j.addEventListener("change",S),()=>j.removeEventListener("change",S)},[n.themeMode]),ue.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]),ue.useEffect(()=>{As({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]),ue.useEffect(()=>{if(typeof window>"u")return;const j=S=>{const w=S.detail;w&&o(T=>{let M=T.themeMode;w.useSystemTheme===!0?M="system":w.useSystemTheme===!1&&(w.themeVariant==="dark"||w.themeVariant==="light")&&(M=w.themeVariant);let N=T.lightThemeId;typeof w.lightThemeId=="string"&&w.lightThemeId.length>0&&(N=Gn(w.lightThemeId,"light"));let A=T.darkThemeId;return typeof w.darkThemeId=="string"&&w.darkThemeId.length>0&&(A=Gn(w.darkThemeId,"dark")),M===T.themeMode&&N===T.lightThemeId&&A===T.darkThemeId?T:{themeMode:M,lightThemeId:N,darkThemeId:A}})};return window.addEventListener("openchamber:settings-synced",j),()=>window.removeEventListener("openchamber:settings-synced",j)},[]);const g=ue.useCallback(j=>{const S=m.find(w=>w.metadata.id===j);S&&o(w=>S.metadata.variant==="dark"?w.darkThemeId===S.metadata.id&&w.themeMode==="dark"?w:{...w,darkThemeId:S.metadata.id,themeMode:"dark"}:w.lightThemeId===S.metadata.id&&w.themeMode==="light"?w:{...w,lightThemeId:S.metadata.id,themeMode:"light"})},[m]),x=ue.useCallback(j=>{o(S=>S.themeMode===j?S:{...S,themeMode:j})},[]),y=ue.useCallback(j=>{if(j){o(w=>w.themeMode==="system"?w:{...w,themeMode:"system"});return}const S=p.metadata.variant==="dark"?"dark":"light";o(w=>w.themeMode===S?w:{...w,themeMode:S})},[p.metadata.variant]),b=ue.useCallback(j=>{const S=m.find(w=>w.metadata.id===j&&w.metadata.variant==="light");S&&o(w=>w.lightThemeId===S.metadata.id?w:{...w,lightThemeId:S.metadata.id})},[m]),v=ue.useCallback(j=>{const S=m.find(w=>w.metadata.id===j&&w.metadata.variant==="dark");S&&o(w=>w.darkThemeId===S.metadata.id?w:{...w,darkThemeId:S.metadata.id})},[m]),k={currentTheme:p,availableThemes:m,setTheme:g,isSystemPreference:n.themeMode==="system",setSystemPreference:y,themeMode:n.themeMode,setThemeMode:x,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:b,setDarkThemePreference:v};return e.jsx(Sa.Provider,{value:k,children:r})}const Ib=({children:r})=>{const{theme:s,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=we();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})},Fb={getLastAssistantMessage(){const r=fe.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=fe.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=fe.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=fe.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=fe.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??{},x=Array.isArray(f.parts)?f.parts:[],y=g.time??{},b=u(y.completed),v=b!==null,k=x.filter(D=>D.type==="tool"),j=x.filter(D=>D.type==="reasoning"),S=p(k.map(D=>u(D.state?.time?.end??D.state?.time?.start))),w=p(j.map(D=>u(D.time?.end??D.time?.start))),T=p([S,w].filter(D=>D!==null)),M=k.some(D=>["pending","running","started"].includes(D.state?.status)),N=j.some(D=>typeof D.time?.end!="number");k.length>0&&(d.withTools+=1),j.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const A=!!(v&&typeof S=="number"&&b<S);A&&(d.completedBeforeTool+=1);const C=!!(v&&typeof w=="number"&&b<w);return C&&(d.completedBeforeReasoning+=1),v&&M&&(d.runningToolsWhenCompleted+=1),v&&N&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:b,latestToolTimestamp:S,latestReasoningTimestamp:w,latestPartTimestamp:T,completed_missing:!v,completed_before_tool:A,completed_before_reasoning:C,running_tools_when_completed:!!(v&&M),reasoning_open_when_completed:!!(v&&N),has_tools:k.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=fe.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const n=(r.messages.get(s)||[]).filter(y=>y.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(y=>y.type==="step-finish"),i=o.parts.some(y=>y.type==="step-finish"&&y.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),x=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:",x),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=Fb,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 kl=!1;const Pb=()=>{if(kl||typeof window>"u")return;kl=!0;let r={showReasoningTraces:we.getState().showReasoningTraces,autoDeleteEnabled:we.getState().autoDeleteEnabled,autoDeleteAfterDays:we.getState().autoDeleteAfterDays},s=null,t=null;const n=()=>{const a=s;s=null,t=null,a&&Object.keys(a).length>0&&As(a)},o=a=>{s={...s??{},...a},!t&&(t=setTimeout(n,150))};we.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};i.showReasoningTraces!==r.showReasoningTraces&&(c.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==r.autoDeleteEnabled&&(c.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==r.autoDeleteAfterDays&&(c.autoDeleteAfterDays=i.autoDeleteAfterDays),r=i,Object.keys(c).length>0&&o(c)})};let Nl=!1;const Cl="openchamber-typography-base",Rb=()=>{if(typeof document>"u")return;const s=`:root {
|
|
115
|
-
${Object.entries(ma).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
116
|
-
`)}
|
|
117
|
-
}
|
|
118
|
-
`,t=document.getElementById(Cl);if(t){t.textContent=s;return}const n=document.createElement("style");n.id=Cl,n.textContent=s,document.head.appendChild(n)},Lb=()=>{Nl||typeof window>"u"||(Nl=!0,Rb())},_b=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await ec();await tc();Pb();Lb();await wd();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");fm.createRoot(Nd).render(e.jsx(ue.StrictMode,{children:e.jsx(Tb,{children:e.jsx(Ib,{children:e.jsx(Nb,{children:e.jsx(wb,{apis:_b})})})})}));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 $b=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{vs as D,Gr as S,js as a,Lp as b,I as c,Zg as d,Qg as e,Zi as f,or as g,ex as h,sx as i,$b as m,od as p,tx as r,gn as t};
|