@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
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.pnpm-CFPpXnpS.js","assets/vendor--B3aGWKBE.css","assets/ToolOutputDialog-ByonTRPM.js","assets/index-BleCEZso.js","assets/index-a7wSdHza.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as Ad,c as Dd,j as e,R as Ed,T as Td,P as Id,C as Fd,A as Pd,a as Rd,b as Ft,d as Wt,p as Ss,e as ks,f as Ld,g as l,r as Od,h as ds,I as _d,i as $d,k as Bd,l as zd,m as Hd,n as Wd,o as Ud,q as Vd,s as Dt,u as Gd,S as qd,v as Kd,w as Yd,x as ns,y as Xd,z as Al,B as Jd,D as Zd,E as Qd,F as de,G as Oa,H as Lo,J as eu,K as xt,L as sa,M as tu,U as Bt,_ as vn,Z as su,Y as ws,Q as Vs,W as Kt,O as Kr,N as nu,V as jn,X as nn,$ as Sn,a0 as Oo,a1 as Is,a2 as Dl,a3 as ru,a4 as ou,a5 as au,a6 as iu,a7 as lu,a8 as cu,a9 as du,aa as uu,ab as hr,ac as mu,ad as fu,ae as _o,af as zn,ag as he,ah as Gt,ai as na,aj as Yr,ak as El,al as pu,am as os,an as Mr,ao as Xr,ap as Os,aq as Gs,ar as Tl,as as Il,at as Hn,au as Ds,av as gs,aw as Ar,ax as Bs,ay as _a,az as ra,aA as Fl,aB as oa,aC as aa,aD as ia,aE as Jr,aF as Yn,aG as Pl,aH as Rl,aI as $a,aJ as la,aK as rn,aL as Xn,aM as hu,aN as gu,aO as Ll,aP as Ol,aQ as kn,aR as xu,aS as yu,aT as no,aU as bu,aV as ts,aW as wu,aX as ro,aY as vu,aZ as ca,a_ as da,a$ as ju,b0 as Su,b1 as ku,b2 as $o,b3 as Nu,b4 as Nn,b5 as en,b6 as Zr,b7 as Qr,b8 as ua,b9 as Cu,ba as Mu,bb as Au,bc as Du,bd as Eu,be as Tu,bf as Iu,bg as Bo,bh as gr,bi as ma,bj as Fu,bk as Pu,bl as pn,bm as Ru,bn as Lu,bo as Ou,bp as _u,bq as _l,br as $u,bs as $l,bt as Bu,bu as zu,bv as zo,bw as Hu,bx as ys,by as Bl,bz as Wu,bA as An,bB as Uu,bC as Vu,bD as Gu,bE as qu,bF as Ku,bG as Yu,bH as Xu,bI as Ju,bJ as Zu,bK as Qu,bL as em,bM as tm,bN as sm,bO as nm,bP as rm,bQ as om,bR as am,bS as im,bT as lm,bU as Ba,bV as zl,bW as cm,bX as za,bY as dm,bZ as um,b_ as mm,b$ as fm,c0 as pm,c1 as hm,c2 as gm}from"./vendor-.pnpm-CFPpXnpS.js";import{c as xm,l as ym,g as bm,r as wm,d as vm,a as jm,b as Sm,u as km,e as Nm,f as Cm,h as Mm,i as Am,j as Dm,k as Em}from"./index-BleCEZso.js";function T(...n){return Ad(Dd(n))}const Hl=(n,s)=>{const t=n??"",r=Math.max(16,s?.maxLength??45);if(t.length<=r)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,r-(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}`},Dr=n=>n?n==="/"?"/":n.replace(/\/+$/,""):"";function ss(n,s){if(!n)return"";const t=Dr(n);if(t==="/")return"/";const r=s?Dr(s):void 0;if(r&&r!=="/"){if(t===r)return"~";if(t.startsWith(`${r}/`)){const o=t.slice(r.length+1);return o?`~/${o}`:"~"}}return t}function oo(n,s){if(!n)return"/";const t=Dr(n);if(!t||t==="/")return"/";const r=s?Dr(s):void 0;return r&&r!=="/"&&t===r?"~":t.split("/").pop()||t||"/"}function Tm({delayDuration:n=0,...s}){return e.jsx(Rd,{"data-slot":"tooltip-provider",delayDuration:n,...s})}function ot({delayDuration:n=0,...s}){return e.jsx(Tm,{delayDuration:n,children:e.jsx(Ed,{"data-slot":"tooltip",...s})})}function at({...n}){return e.jsx(Td,{"data-slot":"tooltip-trigger",...n})}function st({className:n,sideOffset:s=0,children:t,...r}){return e.jsx(Id,{children:e.jsxs(Fd,{"data-slot":"tooltip-content",sideOffset:s,className:T("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",n),...r,children:[t,e.jsx(Pd,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let ao=null;const Ha=()=>{const n=new Map;return{getItem:s=>n.get(s)??null,setItem:(s,t)=>{n.set(s,t)},removeItem:s=>{n.delete(s)},clear:()=>{n.clear()},key:s=>Array.from(n.keys())[s]??null,get length(){return n.size}}},Im=()=>{if(typeof window>"u"||!window.localStorage)return Ha();const n=window.localStorage,s=Ha();let t=!0;const r=()=>{t=!1};return{getItem:u=>{if(t)try{const p=n.getItem(u);if(p!==null)return p}catch{r()}return s.getItem(u)},setItem:(u,p)=>{if(t)try{n.setItem(u,p),s.removeItem(u);return}catch{r()}s.setItem(u,p)},removeItem:u=>{if(t)try{n.removeItem(u)}catch{r()}s.removeItem(u)},clear:()=>{if(t)try{n.clear()}catch{r()}s.clear()},key:u=>{if(t)try{return n.key(u)}catch{r()}return s.key(u)},get length(){if(t)try{return n.length+s.length}catch{r()}return s.length}}},es=()=>(ao||(ao=Im()),ao),fa={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Fm={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Wa(n){return`--text-${n.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)"}}},xr={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:xr.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Es.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:xr.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Es.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:xr.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Es.tool.inline})},je=Ft()(Wt(Ss((n,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=>{n({theme:t}),s().applyTheme()},toggleSidebar:()=>{n(t=>{const r=!t.isSidebarOpen;if(r&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:r,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:r}})},setSidebarOpen:t=>{n(()=>{if(t&&typeof window<"u"){const r=Math.floor(window.innerWidth*.2);return{isSidebarOpen:t,sidebarWidth:r,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:t}})},setSidebarWidth:t=>{n({sidebarWidth:t,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:t=>{n({isSessionSwitcherOpen:t})},setActiveMainTab:t=>{n({activeMainTab:t})},setPendingDiffFile:t=>{n({pendingDiffFile:t})},navigateToDiff:t=>{n({pendingDiffFile:t,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:t}=s();return t&&n({pendingDiffFile:null}),t},setIsMobile:t=>{n({isMobile:t})},toggleCommandPalette:()=>{n(t=>({isCommandPaletteOpen:!t.isCommandPaletteOpen}))},setCommandPaletteOpen:t=>{n({isCommandPaletteOpen:t})},toggleHelpDialog:()=>{n(t=>({isHelpDialogOpen:!t.isHelpDialogOpen}))},setHelpDialogOpen:t=>{n({isHelpDialogOpen:t})},setAboutDialogOpen:t=>{n({isAboutDialogOpen:t})},setSessionCreateDialogOpen:t=>{n({isSessionCreateDialogOpen:t})},setSettingsDialogOpen:t=>{n({isSettingsDialogOpen:t})},setSidebarSection:t=>{n({sidebarSection:t})},setEventStreamStatus:(t,r)=>{n({eventStreamStatus:t,eventStreamHint:r??null})},setShowReasoningTraces:t=>{n({showReasoningTraces:t})},setAutoDeleteEnabled:t=>{n({autoDeleteEnabled:t})},setAutoDeleteAfterDays:t=>{const r=Math.max(1,Math.min(365,t));n({autoDeleteAfterDays:r})},setAutoDeleteLastRunAt:t=>{n({autoDeleteLastRunAt:t})},setToolCallExpansion:t=>{n({toolCallExpansion:t})},setFontSize:t=>{const r=Math.max(50,Math.min(200,t));n({fontSize:r}),s().applyTypography()},setPadding:t=>{const r=Math.max(50,Math.min(200,t));n({padding:r}),s().applyPadding()},applyTypography:()=>{const{fontSize:t}=s(),r=document.documentElement,o=t/100,a=Object.entries(fa);if(o===1){for(const[i]of a)r.style.removeProperty(Wa(i));return}for(const[i,c]of a){const d=parseFloat(c);Number.isFinite(d)&&r.style.setProperty(Wa(i),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=s(),r=document.documentElement,o=t/100;if(o===1){r.style.removeProperty("--padding-scale"),r.style.removeProperty("--line-height-tight"),r.style.removeProperty("--line-height-normal"),r.style.removeProperty("--line-height-relaxed"),r.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);r.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;r.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),r.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),r.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),r.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:t=>{n({diffLayoutPreference:t})},setDiffFileLayout:(t,r)=>{n(o=>({diffFileLayout:{...o.diffFileLayout,[t]:r}}))},setDiffWrapLines:t=>{n({diffWrapLines:t})},toggleFavoriteModel:(t,r)=>{n(o=>o.favoriteModels.some(i=>i.providerID===t&&i.modelID===r)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===t&&i.modelID===r))}:{favoriteModels:[{providerID:t,modelID:r},...o.favoriteModels]})},isFavoriteModel:(t,r)=>{const{favoriteModels:o}=s();return o.some(a=>a.providerID===t&&a.modelID===r)},addRecentModel:(t,r)=>{n(o=>{const a=o.recentModels.filter(i=>!(i.providerID===t&&i.modelID===r));return{recentModels:[{providerID:t,modelID:r},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||n(t=>{const r={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(r.sidebarWidth=Math.floor(window.innerWidth*.2)),r})},applyTheme:()=>{const{theme:t}=s(),r=document.documentElement;if(r.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";r.classList.add(o)}else r.classList.add(t)}}),{name:"ui-store",storage:ks(()=>es()),partialize:n=>({theme:n.theme,isSidebarOpen:n.isSidebarOpen,sidebarWidth:n.sidebarWidth,isSessionSwitcherOpen:n.isSessionSwitcherOpen,activeMainTab:n.activeMainTab,sidebarSection:n.sidebarSection,isSessionCreateDialogOpen:n.isSessionCreateDialogOpen,isSettingsDialogOpen:n.isSettingsDialogOpen,showReasoningTraces:n.showReasoningTraces,autoDeleteEnabled:n.autoDeleteEnabled,autoDeleteAfterDays:n.autoDeleteAfterDays,autoDeleteLastRunAt:n.autoDeleteLastRunAt,toolCallExpansion:n.toolCallExpansion,fontSize:n.fontSize,padding:n.padding,favoriteModels:n.favoriteModels,recentModels:n.recentModels,diffLayoutPreference:n.diffLayoutPreference,diffWrapLines:n.diffWrapLines})}),{name:"ui-store"})),as=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Qt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Wl=()=>typeof window>"u"?!1:!as()&&!Qt(),qs=()=>as()?window.opencodeDesktop??null:null,Ul=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const n=window.opencodeDesktop;return n?.getSettings&&n?.updateSettings?{getSettings:n.getSettings.bind(n),updateSettings:n.updateSettings.bind(n)}:null},Vl=async()=>{const n=qs();if(typeof window<"u"){const s=window.__OPENCHAMBER_HOME__;if(s&&s.length>0)return s}if(!n)return null;if(typeof n.homeDirectory=="string"&&n.homeDirectory.length>0)return n.homeDirectory;try{if(!n.getHomeDirectory)return null;const s=await n.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},Pm=async()=>{const n=qs();if(!n)return null;try{return await n.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},Rm=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Gl=async()=>{const n=Ul();if(!n)return null;try{return await n.getSettings()}catch(s){return console.warn("Failed to read desktop settings",s),null}},Lm=async n=>{const s=Ul();if(!s)return null;try{return await s.updateSettings(n)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},Om=async n=>{const s=qs();if(!s||!s.requestDirectoryAccess)return{success:!0,path:n};try{return await s.requestDirectoryAccess(n)}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},_m=async n=>{const s=qs();if(!s||!s.startAccessingDirectory)return{success:!0};try{return await s.startAccessingDirectory(n)}catch(t){return console.warn("Failed to start accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},$m=async n=>{const s=qs();if(!s||!s.stopAccessingDirectory)return{success:!0};try{return await s.stopAccessingDirectory(n)}catch(t){return console.warn("Failed to stop accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},Bm=async()=>{const n=qs();if(!n||!n.checkForUpdates)return null;try{return await n.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},zm=async n=>{const s=qs();if(!s||!s.downloadUpdate)return!1;try{return await s.downloadUpdate(n),!0}catch(t){return console.warn("Failed to download update",t),!1}},Hm=async()=>{const n=qs();if(!n||!n.restartToUpdate)return!1;try{return await n.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}};async function Wm(){try{const n=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)throw new Error(`Server responded with ${n.status}`);const s=await n.json();return{available:s.available??!1,version:s.version,currentVersion:s.currentVersion??"unknown",body:s.body,packageManager:s.packageManager,updateCommand:s.updateCommand}}catch(n){return console.warn("Failed to check for web updates:",n),null}}function Um(){return as()?"desktop":Wl()?"web":null}const Ua={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},eo=Ft()((n,s)=>({...Ua,checkForUpdates:async()=>{const t=Um();if(t){n({checking:!0,error:null,runtimeType:t});try{let r=null;t==="desktop"?r=await Bm():t==="web"&&(r=await Wm()),n({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now()})}catch(r){n({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:t,runtimeType:r}=s();if(!(r!=="desktop"||!t)){n({downloading:!0,error:null,progress:null});try{await zm(o=>{n({progress:o})}),n({downloading:!1,downloaded:!0})}catch(o){n({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:t,runtimeType:r}=s();if(!(r!=="desktop"||!t))try{await Hm()}catch(o){n({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{n({available:!1,downloaded:!1,info:null})},reset:()=>{n(Ua)}})),Vm="/api",Gm=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,qm=n=>{const s=typeof n=="string"&&n.trim().length>0?n.trim():"/api";if(Gm.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(r){return console.warn("Failed to normalize OpenCode base URL:",r),s}},Km=()=>{if(typeof window>"u")return null;const n=window.__OPENCHAMBER_DESKTOP_SERVER__,s=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!n||!s)return null;const t=typeof n.origin=="string"&&n.origin.length>0?n.origin:null;return t?`${t}/api`:null},Jn=n=>n.replace(/\\/g,"/"),io=()=>{if(typeof window>"u")return null;const n=window.__OPENCHAMBER_RUNTIME_APIS__;return n&&n.runtime?.isDesktop&&n.files?n.files:null};class Ym{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=Vm){const r=Km()||s;this.baseUrl=qm(r),this.client=Ld({baseUrl:this.baseUrl})}normalizeCandidatePath(s){if(typeof s!="string")return null;const t=s.trim();if(!t)return null;const r=t.replace(/\\/g,"/");return(r.length>1?r.replace(/\/+$/,""):r)||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 r=s.startsWith("/"),o=s.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${r?"/":""}${o[0]}/${o[1]}`,username:o[1]}:r?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 r=this.currentDirectory;this.currentDirectory=s;try{return await t()}finally{this.currentDirectory=r}}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[r]=Array.from(s);return this.deriveHomeDirectory(r)}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 r=await this.client.session.update({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{title:t}});if(!r.data)throw new Error("Failed to update session");return r.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(/\/$/,""),r=new URL(`${t}/session/${encodeURIComponent(s)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&r.searchParams.set("directory",this.currentDirectory);const o=await fetch(r.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(),r=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}}),r}async abortSession(s){return!!(await this.client.session.abort({path:{id:s},throwOnError:!0})).data}async revertSession(s,t,r){const o=await this.client.session.revert({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{messageID:t,partID:r}});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 r=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const o=await r.json().catch(()=>null);return!o||typeof o!="object"?{}:o}catch{return{}}}async respondToPermission(s,t,r){return(await this.client.postSessionIdPermissionsPermissionId({path:{id:s,permissionID:t},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{response:r}})).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`,r=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!r.ok){const a=await r.text();throw console.error("[OpencodeClient] Failed to update config:",r.status,a),new Error(`Failed to update config: ${r.status} ${r.statusText}`)}return await r.json()}async updateConfigPartial(s){const t=await this.getConfig(),r=s(t);return await this.updateConfig(r)}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,r,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);r&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),r());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||"/",r=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!r.ok)throw new Error(`Failed to list files: ${r.statusText}`);return await r.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 r=t.data.find(o=>o.name===s);if(r)return{name:r.name,template:r.template,description:r.description,agent:r.agent,model:r.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 r=await fetch(s);return!(!r.ok||(await r.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(s){const t=io();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 r=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s})});if(!r.ok){const a=await r.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await r.json()}async listLocalDirectory(s){const t=io();if(t)try{const r=await t.listDirectory(s||"");return!r||!Array.isArray(r.entries)?[]:r.entries.map(o=>({name:o.name,path:Jn(o.path),isDirectory:!!o.isDirectory,isFile:!o.isDirectory,isSymbolicLink:!1}))}catch(r){throw console.error("Failed to list directory contents:",r),r}try{const r=new URLSearchParams;s&&s.trim().length>0&&r.set("path",s);const o=r.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(r){throw console.error("Failed to list directory contents:",r),r}}async searchFiles(s,t){const r=io(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Jn(o):null;if(r)try{const p=await r.search({directory:o||"",query:s,maxResults:t?.limit});return Array.isArray(p)?p.map(m=>{const f=Jn(m.path),h=f.split("/").filter(Boolean).pop()||f,g=m.preview&&m.preview.length>0&&typeof m.preview[0]=="string"?Jn(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 Vl();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 r=await t.json();return r&&typeof r.home=="string"&&r.home.length>0?r.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 r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s})}),o=await r.json().catch(()=>null);if(!r.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(r){throw console.warn("Failed to update OpenCode working directory:",r),r}}}const Me=new Ym,Ho=new Set;function pa(n){return Ho.add(n),()=>{Ho.delete(n)}}function Fs(n,s){const t=Array.isArray(n)?n:[n],r=Array.from(new Set(t));if(r.length===0)return;r.includes("all")&&r.splice(0,r.length,"all");const o={scopes:r,source:s?.source,timestamp:Date.now()};for(const a of Ho)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 Er(n,s){return n.scopes.includes("all")||n.scopes.includes(s)}const ha="Updating OpenCode configuration...";let bs=0,Us=ha;const Wo=new Set;function Tr(){const n={isUpdating:bs>0,message:Us};Wo.forEach(s=>s(n))}function Ws(n){bs+=1,bs===1?(Us=n||ha,Tr()):n&&(Us=n,Tr())}function rs(){bs!==0&&(bs-=1,bs===0&&(Us=ha,Tr()))}function cs(n){Us===n&&bs>0||(Us=n,bs>0&&Tr())}function Xm(n){return Wo.add(n),n({isUpdating:bs>0,message:Us}),()=>{Wo.delete(n)}}function Jm(){return{isUpdating:bs>0,message:Us}}const yr=n=>n.builtIn||n.native===!0,ql=n=>n.hidden===!0,Kl=n=>n.filter(s=>!ql(s)),_n="useAgentsStore",Ir=n=>new Promise(s=>setTimeout(s,n)),Zm=2e4,Va=300,Ga=4,Qm=800,ef=200,tf=2e3,Dn=Ft()(Wt(Ss((n,s)=>({selectedAgentName:null,agents:[],isLoading:!1,setSelectedAgent:t=>{n({selectedAgentName:t})},loadAgents:async()=>{n({isLoading:!0});const t=s().agents;let r=null;for(let o=0;o<3;o++)try{const a=await Me.listAgents();return n({agents:a,isLoading:!1}),!0}catch(a){r=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",r),n({agents:t,isLoading:!1}),!1},createAgent:async t=>{Ws("Creating agent configuration…");let r=!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 r=!0,await gn({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadAgents();return d&&Fs("agents",{source:_n}),d}catch(o){return console.error("[AgentsStore] Failed to create agent:",o),!1}finally{r||rs()}},updateAgent:async(t,r)=>{Ws("Updating agent configuration…");let o=!1;try{console.log("[AgentsStore] Updating agent:",t),console.log("[AgentsStore] Config received:",r);const a={};r.mode!==void 0&&(a.mode=r.mode),r.description!==void 0&&(a.description=r.description),r.model!==void 0&&(a.model=r.model),r.temperature!==void 0&&(a.temperature=r.temperature),r.top_p!==void 0&&(a.top_p=r.top_p),r.prompt!==void 0&&(a.prompt=r.prompt),r.tools!==void 0&&(a.tools=r.tools),r.permission!==void 0&&(a.permission=r.permission),r.disable!==void 0&&(a.disable=r.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 gn({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadAgents();return u&&Fs("agents",{source:_n}),u}catch(a){return console.error("[AgentsStore] Failed to update agent:",a),!1}finally{o||rs()}},deleteAgent:async t=>{Ws("Deleting agent configuration…");let r=!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 r=!0,await gn({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadAgents();return c&&Fs("agents",{source:_n}),s().selectedAgentName===t&&n({selectedAgentName:null}),c}catch(o){return console.error("Failed to delete agent:",o),!1}finally{r||rs()}},getAgentByName:t=>{const{agents:r}=s();return r.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=s();return Kl(t)}}),{name:"agents-store",storage:ks(()=>es()),partialize:n=>({selectedAgentName:n.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Dn);async function sf(n){const s=typeof n=="number"&&n>0?Math.min(n,Va):0;s>0&&await Ir(s);const t=Date.now();let r=0,o=null;for(;Date.now()-t<Zm;){r+=1,cs(`Waiting for OpenCode… (attempt ${r})`);try{if(await Me.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=r<=Ga&&a<1200?Va:Math.min(Qm+Math.max(0,r-Ga)*ef,tf);await Ir(i)}throw o||new Error("OpenCode did not become ready in time")}async function gn(n={}){const{message:s,delayMs:t}=n;try{cs(s||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("agents-store"),window.localStorage.removeItem("config-store"))}catch(r){console.warn("[AgentsStore] Failed to prepare config refresh:",r)}try{await sf(t),cs("Refreshing providers and agents…");const r=St.getState(),o=Dn.getState();await Promise.all([r.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),Fs("agents",{source:_n})}catch(r){console.error("[AgentsStore] Failed to refresh configuration after OpenCode restart:",r),cs("OpenCode reload failed. Please retry refreshing configuration manually."),await Ir(1500)}finally{rs()}}async function nf(n){await gn(n)}async function rf(n){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 r=t?.error||"Failed to reload configuration";throw new Error(r)}t?.requiresReload?await gn({message:t.message,delayMs:t.reloadDelayMs}):await gn(n)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),cs("Failed to reload configuration. Please try again."),await Ir(2e3),rs(),s}}let qa=null;qa||(qa=pa(n=>{if(n.source!==_n&&Er(n,"agents")){const{loadAgents:s}=Dn.getState();s()}}));const of="https://models.dev/api.json",af="/api/openchamber/models-metadata",lf=n=>n?.toLowerCase?.()??"",cf=n=>n==="primary"||n==="all"||n===void 0||n===null,Wn=n=>typeof n=="object"&&n!==null,Fr=n=>Array.isArray(n)&&n.every(s=>typeof s=="string"),df=n=>{if(!Wn(n))return!1;const s=n;if(s.modalities){const{input:t,output:r}=s.modalities;if(t&&!Fr(t)||r&&!Fr(r))return!1}return!0},uf=n=>{if(!Wn(n))return!1;const s=n;return s.models===void 0||Wn(s.models)},Yl=(n,s)=>{const t=lf(n);return!t||!s?"":`${t}/${s}`},mf=n=>{const s=new Map;if(!Wn(n))return s;for(const[t,r]of Object.entries(n)){if(!uf(r))continue;const o=typeof r.id=="string"&&r.id.length>0?r.id:t,a=r.models;if(!(!a||!Wn(a)))for(const[i,c]of Object.entries(a)){if(!df(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:Fr(c.modalities.input)?c.modalities.input:void 0,output:Fr(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=Yl(o,d);p&&s.set(p,u)}}return s},ff=async()=>{if(typeof fetch!="function")return new Map;const n=[af,of];for(const s of n){const t=typeof AbortController<"u"?new AbortController:void 0,r=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 mf(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${s})`):console.warn(`Failed to fetch model metadata from ${s}:`,o)}finally{r&&clearTimeout(r)}}return new Map},pf=n=>new Promise(s=>setTimeout(s,n)),St=Ft()(Wt(Ss((n,s)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,loadProviders:async()=>{try{const t=ff(),r=await Me.getProviders(),o=Array.isArray(r?.providers)?r.providers:[],a=r?.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||"";n({providers:i,defaultProviders:a,currentProviderId:c,currentModelId:u});const p=await t;p.size>0&&n({modelsMetadata:p})}catch(t){console.error("Failed to load providers:",t),n({providers:[],defaultProviders:{},currentProviderId:"",currentModelId:""})}},setProvider:t=>{const{providers:r}=s(),o=r.find(a=>a.id===t);if(o){const i=o.models[0]?.id||"";n({currentProviderId:t,currentModelId:i})}},setModel:t=>{n({currentModelId:t})},saveAgentModelSelection:(t,r,o)=>{n(a=>({agentModelSelections:{...a.agentModelSelections,[t]:{providerId:r,modelId:o}}}))},getAgentModelSelection:t=>{const{agentModelSelections:r}=s();return r[t]||null},loadAgents:async()=>{const t=s().agents;let r=null;for(let o=0;o<3;o++)try{const a=await Me.listAgents(),i=Array.isArray(a)?a:[];n({agents:i});const{providers:c}=s();if(i.length===0)return n({currentAgentName:void 0}),!0;const d=i.filter(m=>cf(m.mode)),p=d.find(m=>m.name==="build")||d[0]||i[0];if(n({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)&&n({currentProviderId:p.model.providerID,currentModelId:p.model.modelID})}return!0}catch(a){r=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",r),n({agents:t}),!1},setAgent:t=>{const{agents:r,providers:o}=s();if(n({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,r))}}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=r.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)&&n({currentProviderId:i.model.providerID,currentModelId:i.model.modelID})}}},checkConnection:async()=>{let r=0,o=null;for(;r<5;)try{const a=await Me.checkHealth();return n({isConnected:a}),a}catch(a){o=a,r+=1;const i=400*r;await pf(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),n({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"),n({isConnected:!1});return}console.log("Initializing app..."),await Me.initApp(),console.log("Loading providers..."),await s().loadProviders(),console.log("Loading agents..."),await s().loadAgents(),n({isInitialized:!0,isConnected:!0}),console.log("App initialized successfully")}catch(t){console.error("Failed to initialize app:",t),n({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:t,currentProviderId:r}=s();return t.find(o=>o.id===r)},getCurrentModel:()=>{const t=s().getCurrentProvider(),{currentModelId:r}=s();if(t)return t.models.find(o=>o.id===r)},getCurrentAgent:()=>{const{agents:t,currentAgentName:r}=s();if(r)return t.find(o=>o.name===r)},getModelMetadata:(t,r)=>{const o=Yl(t,r);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=s();return Kl(t)}}),{name:"config-store",storage:ks(()=>es()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=St);let Ka=null;Ka||(Ka=pa(async n=>{const s=[];if(Er(n,"agents")){const{loadAgents:t}=St.getState();s.push(t().then(()=>{}))}if(Er(n,"providers")){const{loadProviders:t}=St.getState();s.push(t())}s.length>0&&await Promise.all(s)}));const $t={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},hf=180,Zt=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function ga(n){const s=Zt();return s?s.checkIsGitRepository(n):xm(n)}async function gf(n){const s=Zt();return s?s.getGitStatus(n):bm(n)}async function xf(n,s){const t=Zt();return t?t.deleteGitBranch(n,s):vm(n,s)}async function yf(n,s){const t=Zt();return t?t.deleteRemoteBranch(n,s):jm(n,s)}async function bf(n){const s=Zt();return s?s.listGitWorktrees(n):ym(n)}async function wf(n,s){const t=Zt();return t?t.addGitWorktree(n,s):Em(n,s)}async function Xl(n,s){const t=Zt();return t?t.removeGitWorktree(n,s):wm(n,s)}async function vf(n){const s=Zt();return s?s.ensureOpenChamberIgnored(n):Am(n)}async function jf(n,s={}){const t=Zt();return t?t.gitPush(n,s):Dm(n,s)}async function Sf(){const n=Zt();return n?n.getGitIdentities():Mm()}async function kf(n){const s=Zt();return s?s.createGitIdentity(n):Nm(n)}async function Nf(n,s){const t=Zt();return t?t.updateGitIdentity(n,s):km(n,s)}async function Cf(n){const s=Zt();return s?s.deleteGitIdentity(n):Sm(n)}async function Mf(n){const s=Zt();return s?s.getCurrentGitIdentity(n):Cm(n)}const Af=".openchamber",Ps=n=>{if(!n)return"";const s=n.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ya=(n,s)=>{const t=Ps(n),r=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${r}`:`${t}/${r}`},Jl=n=>n?n.startsWith("refs/heads/")?n.substring(11):n.startsWith("heads/")?n.substring(6):n.startsWith("refs/")?n.substring(5):n:"",Df=async n=>{try{await Me.createDirectory(n)}catch(s){if(s instanceof Error&&/exist/i.test(s.message))return;throw s}};async function Ef(n,s){const t=Ps(n),r=Ya(t,Af);return await Df(r),Ya(r,s)}async function Tf(n){const{projectDirectory:s,worktreeSlug:t,branch:r,createBranch:o}=n,a=Ps(s),i=await Ef(a,t);return await wf(a,{path:i,branch:r,createBranch:!!o}),{path:i,branch:r,label:Jl(r),projectDirectory:a,relativePath:i.startsWith(`${a}/`)?i.slice(a.length+1):i}}async function Xa(n){const{projectDirectory:s,path:t,force:r}=n,o=Ps(s);await Xl(o,{path:t,force:r})}async function If(n){const{projectDirectory:s,path:t,branch:r,force:o,deleteRemote:a,remote:i}=n,c=Ps(s),d=r.startsWith("refs/heads/")?r.substring(11):r;if(await Xl(c,{path:t,force:o}),d&&(await xf(c,{branch:d,force:!0}),a))try{await yf(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Pr(n){const s=Ps(n);return bf(s)}async function br(n){const s=Ps(n),t=await gf(s);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function Rr(n,s){const t=Ps(n),r=Ps(s.worktree);return{path:r,branch:s.branch??"",label:Jl(s.branch??""),projectDirectory:t,relativePath:r.startsWith(`${t}/`)?r.slice(t.length+1):r}}const Ja=n=>{if(!n||typeof n!="object")return null;const s={};return typeof n.showReasoningTraces=="boolean"&&(s.showReasoningTraces=n.showReasoningTraces),Object.keys(s).length>0?s:null},Ff=n=>!n||typeof n!="object"?null:{showReasoningTraces:n.showReasoningTraces},Pf=n=>{const s=je.getState();typeof n.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(n.showReasoningTraces)},Rf=async()=>{if(typeof window>"u")return null;if(as()){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 n=localStorage.getItem("appearance-preferences");if(!n)return null;try{const s=JSON.parse(n),t=Ff(s);return Ja(t)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let Zl=null;const Za=n=>{Zl=n},xa=()=>Zl,wr=n=>{typeof window>"u"||(n.themeId&&localStorage.setItem("selectedThemeId",n.themeId),n.themeVariant&&localStorage.setItem("selectedThemeVariant",n.themeVariant),n.lightThemeId&&localStorage.setItem("lightThemeId",n.lightThemeId),n.darkThemeId&&localStorage.setItem("darkThemeId",n.darkThemeId),typeof n.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(n.useSystemTheme)),n.lastDirectory&&localStorage.setItem("lastDirectory",n.lastDirectory),n.homeDirectory&&(localStorage.setItem("homeDirectory",n.homeDirectory),window.__OPENCHAMBER_HOME__=n.homeDirectory),Array.isArray(n.pinnedDirectories)&&n.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(n.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},Ql=()=>{const n=je.persist;if(n&&typeof n=="object")return n},ec=()=>xa()?.settings??null,vr=n=>{const s=je.getState();if(typeof n.showReasoningTraces=="boolean"&&n.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(n.showReasoningTraces),typeof n.autoDeleteEnabled=="boolean"&&n.autoDeleteEnabled!==s.autoDeleteEnabled&&s.setAutoDeleteEnabled(n.autoDeleteEnabled),typeof n.autoDeleteAfterDays=="number"&&Number.isFinite(n.autoDeleteAfterDays)){const t=Math.max(1,Math.min(365,n.autoDeleteAfterDays));t!==s.autoDeleteAfterDays&&s.setAutoDeleteAfterDays(t)}},Qa=n=>{if(!n||typeof n!="object")return null;const s=n,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(r=>typeof r=="string"&&r.length>0)),Array.isArray(s.securityScopedBookmarks)&&(t.securityScopedBookmarks=s.securityScopedBookmarks.filter(r=>typeof r=="string"&&r.length>0)),Array.isArray(s.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(s.pinnedDirectories.filter(r=>typeof r=="string"&&r.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},Lf=async()=>{const n=ec();if(n)try{const s=await n.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}},tc=async()=>{if(typeof window>"u")return;const n=Ql(),s=t=>{wr(t);const r=()=>vr(t);if(n?.hasHydrated?.())r();else if(r(),n?.onFinishHydration){const o=n.onFinishHydration(()=>{o?.(),r()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))};try{const t=as()?await Gl():await Lf();t&&s(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},As=async n=>{if(typeof window>"u")return;if(as()){try{const t=await Lm(n);t&&(wr(t),vr(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const s=ec();if(s)try{const t=await s.save(n);t&&(wr(t),vr(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(n)});if(!t.ok){console.warn("Failed to update shared settings via API:",t.status,t.statusText);return}const r=await t.json().catch(()=>null);r&&(wr(r),vr(r))}catch(t){console.warn("Failed to update shared settings via API:",t)}},sc=async()=>{if(typeof window>"u")return;const n=Ql();try{const s=await Rf();if(!s)return;const t=()=>Pf(s);if(n?.hasHydrated?.()){t();return}if(t(),n?.onFinishHydration){const r=n.onFinishHydration(()=>{r?.(),t()})}}catch(s){console.warn("Failed to load appearance preferences:",s)}},$n="useCommandsStore",Uo=n=>new Promise(s=>setTimeout(s,n)),Of=2e4,ei=300,ti=4,_f=800,$f=200,Bf=2e3,En=Ft()(Wt(Ss((n,s)=>({selectedCommandName:null,commands:[],isLoading:!1,setSelectedCommand:t=>{n({selectedCommandName:t})},loadCommands:async()=>{n({isLoading:!0});const t=s().commands;let r=null;for(let o=0;o<3;o++)try{const a=await Me.listCommandsWithDetails();return n({commands:a,isLoading:!1}),!0}catch(a){r=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load commands:",r),n({commands:t,isLoading:!1}),!1},createCommand:async t=>{Ws("Creating command configuration…");let r=!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 r=!0,await lo({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadCommands();return d&&Fs("commands",{source:$n}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{r||rs()}},updateCommand:async(t,r)=>{Ws("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",r);const a={};r.description!==void 0&&(a.description=r.description),r.agent!==void 0&&(a.agent=r.agent),r.model!==void 0&&(a.model=r.model),r.template!==void 0&&(a.template=r.template),r.subtask!==void 0&&(a.subtask=r.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 lo({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadCommands();return u&&Fs("commands",{source:$n}),u}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||rs()}},deleteCommand:async t=>{Ws("Deleting command configuration…");let r=!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 r=!0,await lo({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadCommands();return c&&Fs("commands",{source:$n}),s().selectedCommandName===t&&n({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{r||rs()}},getCommandByName:t=>{const{commands:r}=s();return r.find(o=>o.name===t)}}),{name:"commands-store",storage:ks(()=>es()),partialize:n=>({selectedCommandName:n.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=En);async function zf(n){const s=typeof n=="number"&&n>0?Math.min(n,ei):0;s>0&&await Uo(s);const t=Date.now();let r=0,o=null;for(;Date.now()-t<Of;){r+=1,cs(`Waiting for OpenCode… (attempt ${r})`);try{if(await Me.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=r<=ti&&a<1200?ei:Math.min(_f+Math.max(0,r-ti)*$f,Bf);await Uo(i)}throw o||new Error("OpenCode did not become ready in time")}async function lo(n={}){const{message:s,delayMs:t}=n;try{cs(s||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("commands-store"),window.localStorage.removeItem("config-store"))}catch(r){console.warn("[CommandsStore] Failed to prepare config refresh:",r)}try{await zf(t),cs("Refreshing providers and commands…");const r=St.getState(),o=En.getState();await Promise.all([r.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),Fs("commands",{source:$n})}catch(r){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",r),cs("OpenCode reload failed. Please retry refreshing configuration manually."),await Uo(1500)}finally{rs()}}let si=null;si||(si=pa(n=>{if(n.source!==$n&&Er(n,"commands")){const{loadCommands:s}=En.getState();s()}}));const Hf=3e4,Wf=40,Uf=60,Vf=(n,s,t)=>{const r=n.trim(),o=s.trim().toLowerCase();return`${r}::${o}::${t}`},ya=Ft()(Wt((n,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,r,o=Uf){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof r=="string"?r.trim():"",c=Vf(a,i,o),d=Date.now(),u=s().cache[c];if(u&&d-u.timestamp<Hf)return u.files;const p=s().inFlight[c];if(p)return p;const m=Me.searchFiles(i,{directory:a,limit:o}).then(f=>(n(h=>{const g={...h.cache,[c]:{files:f,timestamp:Date.now()}},x=h.cacheKeys.filter(y=>y!==c);for(x.push(c);x.length>Wf;){const y=x.shift();y&&delete g[y]}return{cache:g,cacheKeys:x}}),f)).finally(()=>{n(f=>{const h={...f.inFlight};return delete h[c],{inFlight:h}})});return n(f=>({inFlight:{...f.inFlight,[c]:m}})),m},invalidateDirectory(t){if(!t||t.trim().length===0){n({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;n(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 Gf={};let Ts=null;const xs=es(),ni=xs.getItem("lastDirectory"),qf=typeof ni=="string"&&ni.length>0,Zn=(n,s)=>((s?.showOverlay??!0)&&Ws("Switching project directory…"),Me.setOpenCodeWorkingDirectory(n).catch(r=>{throw console.warn("Failed to synchronize OpenCode working directory:",r),r})),Qn=(n,s,t)=>{const{showOverlay:r}=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 n}catch(i){console.error("Failed to update OpenCode working directory:",i),r&&(cs("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),rs()),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 nf({message:"Refreshing OpenCode configuration…"});try{await En.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 r&&rs()}catch(i){console.error("Failed to refresh configuration after directory change:",i),r&&(cs("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),rs())}finally{t?.(a),o()}})()},er=n=>{try{ya.getState().invalidateDirectory(n)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},Lr=()=>{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 r=xs.getItem("homeDirectory");if(r)return Ts=r,r}const n=typeof process<"u"&&Gf?.HOME;return n||process?.cwd?.()||"/"},Kf=n=>{if(typeof n!="string")return null;const s=n.trim();if(!s)return null;const t=s.replace(/\\/g,"/");if(t.length>1){const r=t.replace(/\/+$/,"");if(r&&r.length>0)return r==="/"?null:r}return t==="/"||t.length===0?null:t},Yf=n=>(Ts=n,typeof window<"u"&&xs.setItem("homeDirectory",n),As({homeDirectory:n}),n),nc=async()=>{const n=r=>{const o=Kf(r);return o?Yf(o):null};try{const r=await Me.getFilesystemHome(),o=n(r);if(o)return o}catch(r){console.warn("Failed to obtain filesystem home directory:",r)}try{const r=await Me.getSystemInfo(),o=n(r?.homeDirectory);if(o)return o}catch(r){console.warn("Failed to get home directory from system info:",r)}try{const r=await Vl(),o=n(r);if(o)return o}catch(r){console.warn("Failed to obtain desktop-integrated home directory:",r)}const s=Lr(),t=n(s);return t||s},tn=Lr();tn&&Me.setDirectory(tn);const Xf=!!(tn&&tn!=="/"),bt=Ft()(Wt((n,s)=>({currentDirectory:tn,directoryHistory:[tn],historyIndex:0,homeDirectory:tn,hasPersistedDirectory:qf,isHomeReady:Xf,isSwitchingDirectory:!1,setDirectory:(t,r)=>{console.log("[DirectoryStore] setDirectory called with path:",t);const o=r?.showOverlay??!0;Me.setDirectory(t),er();const a=Zn(t,{showOverlay:o});console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),n(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}}),Qn(a,{showOverlay:o},()=>{n(i=>i.currentDirectory!==t?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})},goBack:()=>{const t=s();if(t.historyIndex>0){const r=t.historyIndex-1,o=t.directoryHistory[r];Me.setDirectory(o),er();const a=Zn(o);xs.setItem("lastDirectory",o),As({lastDirectory:o}),n({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Qn(a,{showOverlay:!0},()=>{n(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goForward:()=>{const t=s();if(t.historyIndex<t.directoryHistory.length-1){const r=t.historyIndex+1,o=t.directoryHistory[r];Me.setDirectory(o),er();const a=Zn(o);xs.setItem("lastDirectory",o),As({lastDirectory:o}),n({currentDirectory:o,historyIndex:r,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Qn(a,{showOverlay:!0},()=>{n(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:r}=s(),o=Ts||s().homeDirectory||Lr();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=Ts||Lr();r(c)}else r(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=Ts||s().homeDirectory||await nc();s().setDirectory(t)},synchronizeHomeDirectory:t=>{const r=s(),o=t;Ts=o;const a=r.homeDirectory!==o,i=xs.getItem("lastDirectory"),c=typeof i=="string"&&i.length>0,d=!c&&(r.currentDirectory==="/"||r.currentDirectory===r.homeDirectory||!r.currentDirectory);if(!a&&!d){r.isHomeReady||n({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),n(()=>p),d&&u){Me.setDirectory(o),er(),xs.setItem("lastDirectory",o),As({lastDirectory:o});const m=Zn(o,{showOverlay:!1});Qn(m,{showOverlay:!1},()=>{n(f=>f.currentDirectory!==o?{}:f.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}As({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&nc().then(n=>{bt.getState().synchronizeHomeDirectory(n)});const rc=es(),oc="oc.sessionSelectionByDirectory",ri=".openchamber",Jf=()=>{try{const n=rc.getItem(oc);if(!n)return{};const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((t,[r,o])=>(typeof r=="string"&&typeof o=="string"&&r.length>0&&o.length>0&&(t[r]=o),t),{})}catch{return{}}};let jr=null;const ba=()=>(jr||(jr=Jf()),jr),ac=n=>{jr=n;try{rc.setItem(oc,JSON.stringify(n))}catch{}},ic=n=>{if(!n)return null;const t=ba()[n];return typeof t=="string"?t:null},Ks=(n,s)=>{if(!n)return;const t={...ba()};s?t[n]=s:delete t[n],ac(t)},Zf=(n,s)=>{if(!n)return;const t=ic(n);if(!t)return;if(!new Set(s).has(t)){const o={...ba()};delete o[n],ac(o)}},oi=async(n,s)=>{const t=n.status??await br(n.path).catch(()=>{});await If({projectDirectory:n.projectDirectory,path:n.path,branch:n.branch,force:!!t?.isDirty,deleteRemote:!!s?.deleteRemoteBranch,remote:s?.remoteName})},_t=n=>{if(typeof n!="string")return null;const s=n.trim();if(!s)return null;const t=s.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},dn=(n,s)=>{const t=n.find(r=>r.id===s);return t?_t(t.directory??null):null},Qf=async(n,s,t)=>{const r=_t(s);if(!r||n.length===0)return null;const o=n.map(u=>({id:u.id,directory:_t(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Pr(r)}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=Rr(r,u),m=_t(p.path)??p.path;m!==r&&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},Xe=Ft()(Wt(Ss((n,s)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],loadSessions:async()=>{n({isLoading:!0,error:null});try{const r=bt.getState().currentDirectory??Me.getDirectory()??null,o=Me.getApiClient(),a=async A=>{const k=await o.session.list({query:A?{directory:A}:void 0});return Array.isArray(k.data)?k.data:[]},i=_t(r),c=i?await ga(i).catch(()=>!1):!1,d=await a(i||null),u=[];let p=[];if(r&&c&&i){const A=`${i}/${ri}`;try{const k=new Set;A&&(await Me.listLocalDirectory(A)).filter(D=>D.isDirectory).forEach(D=>{const W=/^([A-Za-z]:)?\//.test(D.path)?D.path:`${A}/${D.name}`;k.add(_t(W)??W)});const M=await Pr(i);Array.isArray(M)&&(p=M.map(C=>Rr(i,C)).filter(C=>C.path.includes(`/${ri}/`)),p.forEach(C=>k.add(C.path))),k.size>0&&(await Promise.allSettled(Array.from(k).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(A=>{const k=_t(A.path);k&&m.add(k)});const f=[...d,...u].filter(A=>{const k=A.directory??i??null,M=_t(k);return M?m.has(M):!1}),h=s(),g=h.lastLoadedDirectory??null,x=r!==g;let y=[...f],b=h.currentSessionId;const v=A=>{y=[A,...y.filter(k=>k.id!==A.id)]};if(x)b=y.length>0?y[0].id:null;else if(b){if(!y.some(k=>k.id===b)){const k=h.sessions.find(M=>M.id===b);if(k)v(k);else try{const M=await Me.getSession(b);v(M)}catch{b=y.length>0?y[0].id:null}}}else b=y.length>0?y[0].id:null;const N=y.reduce((A,k)=>(A.some(M=>M.id===k.id)||A.push(k),A),[]);b&&!N.some(A=>A.id===b)&&(b=N.length>0?N[0].id:null);const w=new Set(N.map(A=>A.id));if(r){Zf(r,w);const A=ic(r);A&&w.has(A)&&(b=A)}let S=null;try{S=await Qf(N,r,h.worktreeMetadata)}catch(A){console.debug("Failed to refresh worktree metadata during session load:",A)}const j=(()=>{const A=S??h.worktreeMetadata;if(!x||!i)return A;const k=new Map;return A.forEach((M,C)=>{_t(M.projectDirectory)===i&&k.set(C,M)}),k})(),I=(()=>{if(!b)return i??null;const A=j.get(b)?.path;if(A)return _t(A)??A;const k=dn(N,b);return k||(i??null)})();try{Me.setDirectory(I??void 0)}catch(A){console.warn("Failed to sync OpenCode directory after session load:",A)}n({sessions:N,currentSessionId:b,lastLoadedDirectory:r,isLoading:!1,worktreeMetadata:j,availableWorktrees:p}),Ks(I??r,b)}catch(t){n({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,r,o)=>{n({error:null});const a=bt.getState(),i=_t(a.currentDirectory),c=_t(r??Me.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(n(g=>({sessions:[m,...g.sessions],currentSessionId:d,webUICreatedSessions:new Set([...g.webUICreatedSessions,d]),isLoading:!1})),c)try{Me.setDirectory(c)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const f=g=>{n(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=Me.getApiClient(),x=20;for(let y=0;y<x;y+=1){try{const b=await g.session.list({query:c?{directory:c}:void 0}),N=(Array.isArray(b.data)?b.data:[]).find(w=>!(p.has(w.id)||t&&w.title&&w.title!==t));if(N)return N}catch(b){console.debug("Session poll attempt failed:",b)}await new Promise(b=>setTimeout(b,2e3))}return null};try{const g=()=>Me.createSession({title:t,parentID:o??void 0});let x=null;try{x=c?await Me.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):(n(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 n(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,r)=>{n({isLoading:!0,error:null});const o=s().worktreeMetadata.get(t),a=dn(s().sessions,t),i=o?.path??a;let c=null;try{o&&r?.archiveWorktree&&(await oi(o,{deleteRemoteBranch:r?.deleteRemoteBranch,remoteName:r?.remoteName}),c=o);const d=()=>Me.deleteSession(t);if(!(i?await Me.withDirectory(i,d):await d()))return n(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;n(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=r?.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??Me.getDirectory()??null;return Ks(m,p),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return n(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,r)=>{const o=Array.from(new Set(t.filter(y=>typeof y=="string"&&y.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=r?.silent===!0;a||n({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=dn(s().sessions,y),N=b?.path??v;b&&r?.archiveWorktree&&!p.has(b.path)&&(await oi(b,{deleteRemoteBranch:r?.deleteRemoteBranch,remoteName:r?.remoteName}),d.add(y),u.push({path:b.path,projectDirectory:b.projectDirectory}),p.add(b.path));const w=()=>Me.deleteSession(y);(N?await Me.withDirectory(N,w):await w())?(i.push(y),b?.path&&!u.some(j=>j.path===b.path)&&u.push({path:b.path,projectDirectory:b.projectDirectory})):c.push(y)}catch{c.push(y)}const m=bt.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;n(y=>{const b=y.sessions.filter(S=>!f.has(S.id));y.currentSessionId&&f.has(y.currentSessionId)?g=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 N=new Set(u.map(S=>_t(S.path)).filter(S=>!!S)),w=N.size>0?y.availableWorktrees.filter(S=>!N.has(_t(S.path)??S.path)):y.availableWorktrees;return{sessions:b,currentSessionId:g,...a?{}:{isLoading:!1,error:h},worktreeMetadata:v,availableWorktrees:w}});const x=Me.getDirectory()??null;return Ks(x,g),{deletedIds:i,failedIds:c}},updateSessionTitle:async(t,r)=>{try{const o=dn(s().sessions,t),a=s().worktreeMetadata.get(t),i=()=>Me.updateSession(t,r),c=a?.path??o,d=c?await Me.withDirectory(c,i):await i();n(u=>({sessions:u.sessions.map(p=>p.id===t?d:p)}))}catch(o){n({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const r=dn(s().sessions,t),o=Me.getApiClient(),i=s().worktreeMetadata.get(t)?.path??r,c=async()=>{const u=r??Me.getDirectory();return o.session.share({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Me.withDirectory(i,c):await c();return d.data?(n(u=>({sessions:u.sessions.map(p=>p.id===t?d.data:p)})),d.data):null}catch(r){return n({error:r instanceof Error?r.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const r=dn(s().sessions,t),o=Me.getApiClient(),i=s().worktreeMetadata.get(t)?.path??r,c=async()=>{const u=r??Me.getDirectory();return o.session.unshare({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Me.withDirectory(i,c):await c();return d.data?(n(u=>({sessions:u.sessions.map(p=>p.id===t?d.data:p)})),d.data):null}catch(r){return n({error:r instanceof Error?r.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{n({currentSessionId:t,error:null});const r=Me.getDirectory()??null;Ks(r,t)},clearError:()=>{n({error:null})},getSessionsByDirectory:()=>{const{sessions:t}=s();return t},applySessionMetadata:(t,r)=>{!t||!r||n(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const i=o.sessions[a],c=r.time?{...i.time,...r.time}:i.time,d=r.summary===void 0?i.summary:r.summary||void 0,u=r.share===void 0?i.share:r.share||void 0,p={...i,...r,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:r}=s();return r.has(t)},markSessionAsOpenChamberCreated:t=>{n(r=>{const o=new Set(r.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:r}=s();r(t)},setWorktreeMetadata:(t,r)=>{t&&n(o=>{const a=new Map(o.worktreeMetadata);return r?a.set(t,r):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return s().worktreeMetadata.get(t)},setSessionDirectory:(t,r)=>{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=r??void 0;c!==(d??null)&&(n(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),r&&Ks(r,t))},updateSession:t=>{n(r=>({sessions:r.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:ks(()=>es()),partialize:n=>({currentSessionId:n.currentSessionId,sessions:n.sessions,lastLoadedDirectory:n.lastLoadedDirectory,webUICreatedSessions:Array.from(n.webUICreatedSessions),worktreeMetadata:Array.from(n.worktreeMetadata.entries()),availableWorktrees:n.availableWorktrees}),merge:(n,s)=>{if(!(u=>typeof u=="object"&&u!==null)(n))return s;const r=Array.isArray(n.sessions)?n.sessions:s.sessions,o=typeof n.currentSessionId=="string"||n.currentSessionId===null?n.currentSessionId:s.currentSessionId,a=Array.isArray(n.webUICreatedSessions)?n.webUICreatedSessions:[],i=Array.isArray(n.worktreeMetadata)?n.worktreeMetadata:[],c=Array.isArray(n.availableWorktrees)?n.availableWorktrees:s.availableWorktrees,d=typeof n.lastLoadedDirectory=="string"?n.lastLoadedDirectory:s.lastLoadedDirectory??null;return{...s,...n,sessions:r,currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:c,lastLoadedDirectory:d}}}),{name:"session-store"})),lc="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.",co=n=>typeof n=="string"&&n.trim()===lc.trim(),uo=(n,s)=>{const t=Date.now(),r=n.get(s),o=new Map(n);return o.set(s,{phase:"streaming",startedAt:r?.startedAt??t,lastUpdateAt:t}),o},Tn=(n,s)=>{const t=Array.from(s);if(!t.some(a=>n.has(a)))return n;const o=new Map(n);return t.forEach(a=>{o.delete(a)}),o},ai=new Map,cc=n=>{const s=ai.get(n);s&&(clearTimeout(s),ai.delete(n))},Ys=n=>{for(const s of n)cc(s)},Un=n=>{if(!n)return"";if(typeof n=="string")return n;if(Array.isArray(n))return n.map(s=>Un(s)).join("");if(typeof n=="object"){if(typeof n.text=="string")return n.text;if(Array.isArray(n.content))return n.content.map(s=>Un(s)).join("")}return""},Bn=n=>{if(!n)return"";const s=n;if(typeof s.text=="string")return s.text;if(Array.isArray(s.text))return s.text.map(r=>typeof r=="string"?r:Bn(r)).join("");const t=Un(s.delta);return t||(typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(r=>{if(typeof r=="string")return r;if(r&&typeof r=="object"){const o=r;return o.text||Un(o.delta)||""}return""}).join(""):"")},In=(n,s)=>{const t={...n};if(t.type=t.type||"text",t.type==="text"){const r=s&&typeof s.text=="string"?s.text:"",o=typeof t.text=="string"?t.text:"",a=Un(n.delta);o?t.text=o:a?t.text=r?`${r}${a}`:a:r?t.text=r:t.text="",delete t.delta}return t},ii=10*1024*1024,ep=n=>{const s=(n||"").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"}},tp=n=>{if(n.type&&n.type.trim().length>0)return n.type;const s=(n.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"}},sp=n=>{const s=n.replace(/\s+/g,"");if(!s)return 0;const t=s.endsWith("==")?2:s.endsWith("=")?1:0;return Math.floor(s.length*3/4)-t},np=n=>{const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let r=0;r<n.length;r+=3){const o=n[r]??0,a=n[r+1],i=n[r+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=Ft()(Wt(Ss((n,s)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:r}=s();if(r.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=tp(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"};n(g=>({attachedFiles:[...g.attachedFiles,h]}))},addServerFile:async(t,r,o)=>{const{attachedFiles:a}=s();if(a.some(b=>b.serverPath===t&&b.source==="server")){console.log(`Server file "${r}" is already attached`);return}let c=o,d,u;if(!c)try{const b=Me.getApiClient(),v=t.lastIndexOf("/"),N=v>0?t.substring(0,v):"/",w=v>0?t.substring(v+1):t,S=await b.file.read({query:{path:w,directory:N}});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: ${r}]`}const p=u||ep(r),m=p&&p.trim().length>0?p:"application/octet-stream",f=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return np(v)})(),h=d==="base64"?sp(f):new TextEncoder().encode(c||"").length;if(h>ii)throw new Error(`File "${r}" is too large. Maximum size is 10MB.`);const g=new File([],r,{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:r,size:h,source:"server",serverPath:t};n(b=>({attachedFiles:[...b.attachedFiles,y]}))},removeAttachedFile:t=>{n(r=>({attachedFiles:r.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{n({attachedFiles:[]})}}),{name:"file-store",storage:ks(()=>es()),partialize:n=>({attachedFiles:n.attachedFiles})}),{name:"file-store"}));let mo=[],fo=null;const rp=50,op=3e4,Xs=new Map,tr=new Map,un=new Map,ap=10,Or=n=>{if(typeof n!="string")return null;const s=n.trim();if(!s)return null;const t=s.indexOf("_"),r=t>=0?s.slice(t+1):s;return!r||r.length<ap?null:r},sr=(n,s)=>{const t=Or(n),r=Or(s);return!t||!r||t.length!==r.length?!0:t>r},ip=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},hn=n=>!Array.isArray(n)||n.length===0?0:n.reduce((s,t)=>{if(!t||t.type!=="text")return s;const r=t.text??t.content;return typeof r=="string"?s+r.length:s},0),_r=n=>Array.isArray(n)?n.some(s=>s?.type==="step-finish"&&s?.reason==="stop"):!1,li=n=>{if(n){if(typeof n.id=="string"&&n.id.length>0)return n.id;if(n.type){const s=n.reason,t=n.callID;return`${n.type}-${s??""}-${t??""}`}}},ci=new Set,$r=(n=[],s=[])=>{if(!s.length)return[...n];const t=[...n],r=new Set(n.map(li).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=li(o);a&&r.has(a)||(t.push(o),a&&r.add(a))}),t},lp=(n,s)=>{const t=Array.isArray(n.parts)?n.parts:[],r=Array.isArray(s.parts)?s.parts:[],o=hn(t),a=hn(r),i=_r(t),c=_r(r);let d=r;return i&&o>=a?d=$r(t,r):c&&a>=o?d=$r(r,t):o>=a&&(d=t),{...s,info:{...n.info,...s.info},parts:d}},po=n=>{const s=[],t=new Map;for(const r of n){const o=typeof r?.info?.id=="string"?r.info.id:null;if(!o){s.push(r);continue}const a=t.get(o);if(a===void 0){t.set(o,s.length),s.push(r);continue}s[a]=lp(s[a],r)}return s},cp=(n,s)=>{let t=s,r=s?Or(s):null;for(const o of n){const a=o?.info?.id,i=Or(a);!a||!i||(!r||i>r)&&(r=i,t=a)}return t},fs=(n,s,t)=>{if(n.get(s)===t)return n;const o=new Map(n);return t?o.set(s,t):o.delete(s),o},mn=(n,s,t)=>{if(n.get(s)===t)return n;const o=new Map(n);return o.set(s,t),o},nr=(n,s)=>{const t=new Map(n);let r=!1;for(const o of s)t.delete(o)&&(r=!0);return r?t:n},dp=(n,s)=>{const t=new Set,r=n.streamingMessageIds.get(s);return r&&t.add(r),n.messageStreamStates.forEach((o,a)=>{n.messageSessionIndex.get(a)===s&&t.add(a)}),t},di=(n,s,t)=>n.streamingMessageIds.get(s)===t?!0:n.messageSessionIndex.get(t)===s&&n.messageStreamStates.has(t),up=async n=>{if(n)try{const s=Xe.getState(),t=s.getWorktreeMetadata(n);if(t?.path)return t.path;const r=s.sessions.find(a=>a.id===n);return typeof r?.directory=="string"&&r.directory.length>0?r.directory:void 0}catch(s){console.warn("Failed to resolve session directory override:",s);return}},ui=n=>{if(!n)return null;try{return Xe.getState().sessions.find(r=>r.id===n)?.revert?.messageID??null}catch{return null}},mi=(n,s)=>{if(!s)return n;const t=n.findIndex(r=>r.info.id===s);return t===-1?n:n.slice(0,t)},ho=async(n,s)=>{const t=await up(n);return t?Me.withDirectory(t,s):s()},rt=Ft()(Wt(Ss((n,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,r=$t.VIEWPORT_MESSAGES)=>{const o=await ho(t,()=>Me.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?sr(m,c):!0}):i).slice(-r);n(p=>{const m=new Map(p.messages),f=p.messages.get(t)||[],h=new Map(f.filter(k=>typeof k.info?.id=="string").map(k=>[k.info.id,k])),g=u.map(k=>{const M={...k.info,clientRole:k.info?.clientRole??k.info.role,userMessageMarker:k.info.role==="user"?!0:k.info?.userMessageMarker},C=(Array.isArray(k.parts)?k.parts:[]).map(P=>{if(P?.type==="text"){const W=P.text??P.content??"";if(co(W))return{...P,synthetic:!0}}return P}),D=M?.id?h.get(M.id):void 0;if(D&&D.info.role==="assistant"){const P=Array.isArray(D.parts)?D.parts:[],W=hn(P),K=hn(C);if(_r(P)&&W>K){const Z=$r(P,C);return{...k,info:M,parts:Z}}}return{...k,info:M,parts:C}}),x=po(g),y=new Set(f.map(k=>k.info.id)),b=new Set(x.map(k=>k.info.id)),v=[];y.forEach(k=>{b.has(k)||v.push(k)}),m.set(t,x);const N=new Map(p.sessionMemoryState),w=p.sessionMemoryState.get(t);N.set(t,{viewportAnchor:x.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:w?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const S={messages:m,sessionMemoryState:N};Ys(v);const j=Tn(p.messageStreamStates,v);if(j!==p.messageStreamStates&&(S.messageStreamStates=j),v.length>0){const k=p.streamingMessageIds.get(t);k&&v.includes(k)&&(S.streamingMessageIds=fs(S.streamingMessageIds??p.streamingMessageIds,t,null))}if(v.length>0){const k=nr(S.messageSessionIndex??p.messageSessionIndex,v);k!==(S.messageSessionIndex??p.messageSessionIndex)&&(S.messageSessionIndex=k)}if(v.length>0){const k=new Map(p.pendingAssistantParts);let M=!1;v.forEach(C=>{k.delete(C)&&(M=!0)}),M&&(S.pendingAssistantParts=k)}const I=S.messageSessionIndex??p.messageSessionIndex;let A=I;return x.forEach(k=>{const M=k?.info?.id;typeof M=="string"&&M.length>0&&(A=mn(A,M,t))}),A!==I&&(S.messageSessionIndex=A),S})},sendMessage:async(t,r,o,a,i,c,d)=>{if(!i)throw new Error("No session selected");const u=i;s().sessionAbortFlags.has(u)&&n(p=>{const m=new Map(p.sessionAbortFlags);return m.delete(u),{sessionAbortFlags:m}}),await ho(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=Me.getApiClient(),y=Me.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:r,modelID:o},query:y?{directory:y}:void 0});return}if(h==="summarize"){await x.session.summarize({path:{id:u},body:{providerID:r,modelID:o},query:y?{directory:y}:void 0});return}try{const b=await Me.getCommandDetails(h);b?.template?p=b.template.replace(/\$ARGUMENTS/g,g):p=t}catch(b){console.error("Command template resolution failed:",b),p=t}}n({lastUsedProvider:{providerID:r,modelID:o}}),n(f=>{const h=f.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=un.get(u);g&&(clearTimeout(g),un.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;n(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 Me.sendMessage({id:u,providerID:r,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)}n(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.",n(g=>{const x=new Map(g.abortControllers);return x.delete(u),{abortControllers:x}});return}else f.message&&(h=f.message);throw n(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),n(f=>{const h=new Map(f.abortControllers);return h.delete(u),{abortControllers:h}}),new Error(m)}})},abortCurrentOperation:async t=>{if(!t)return;const r=s(),{abortControllers:o,messages:a}=r;o.get(t)?.abort();const c=dp(r,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),tr.delete(u))}c.size>0&&Ys(c);const d=Date.now();n(u=>{const p=Tn(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 N=(v.parts??[]).map(w=>{if(w.type==="reasoning"){const S=w,j={...S.time??{}};return typeof j.end!="number"&&(j.end=d),{...S,time:j}}if(w.type==="tool"){const S=w,j={...S.state??{}};return(j.status==="running"||j.status==="pending")&&(j.status="aborted"),{...S,state:j}}return w.type==="step-start"?{...w,type:"step-finish",aborted:!0}:w});return f=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:N}});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}:{}}}),Me.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,r,o,a,i)=>{const c=s();if(ci.has(r))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!sr(r,d)){window.__messageTracker?.(r,"ignored_trimmed_stream_part");return}const u=c.messages.get(t)||[],p=u.find(g=>g.info.id===r),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>$t.ZOMBIE_TIMEOUT){f.isZombie||n(x=>{const y=new Map(x.sessionMemoryState);return y.set(t,{...f,isZombie:!0}),{sessionMemoryState:y}}),setTimeout(()=>{s().completeStreamingMessage(t,r)},0),window.__messageTracker?.(r,"skipped_zombie_stream");return}n(g=>{const y=[...g.messages.get(t)||[]],b={},v=mn(g.messageSessionIndex,r,t);v!==g.messageSessionIndex&&(b.messageSessionIndex=v);const N=M=>{if(!((m==="assistant"||m==="user")&&g.sessionAbortFlags.has(t)))return M;const D=new Map(g.sessionAbortFlags);return D.delete(t),{...M,sessionAbortFlags:D}},w=M=>{const C=M||"",D=tr.get(r);if(C&&D===C){const K=s();if(di(K,t,r)){const O=Xs.get(r);O&&(clearTimeout(O),Xs.delete(r)),setTimeout(()=>{const Z=s();typeof Z.forceCompleteMessage=="function"&&Z.forceCompleteMessage(t,r,"timeout"),Z.completeStreamingMessage(t,r)},100)}}tr.set(r,C);const P=Xs.get(r);P&&clearTimeout(P);const W=setTimeout(()=>{const K=s();typeof K.forceCompleteMessage=="function"&&K.forceCompleteMessage(t,r,"timeout"),di(K,t,r)&&K.completeStreamingMessage(t,r),Xs.delete(r),tr.delete(r)},8e3);Xs.set(r,W)},S=t!==i,j=g.sessionMemoryState.get(t);if(S&&j?.isStreaming){y.length>=$t.BACKGROUND_STREAMING_BUFFER&&y.shift();const M=new Map(g.sessionMemoryState);M.set(t,{...j,backgroundMessageCount:(j.backgroundMessageCount||0)+1}),g.sessionMemoryState=M}if(m==="assistant"){const M=g.sessionMemoryState.get(t);if(M){const C=Date.now(),D=new Map(g.sessionMemoryState);D.set(t,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??C,lastAccessedAt:C,isZombie:!1}),g.sessionMemoryState=D}}const I=Bn(o);if(co(I)&&(o.synthetic=!0),ip()&&m==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:r,role:m,type:o?.type||"text",textLen:I.length,snapshotParts:u.length})}catch{}const A=b.streamingMessageIds??g.streamingMessageIds;if(m==="assistant"){const M=fs(A,t,r);M!==A&&(b.streamingMessageIds=M,window.__messageTracker?.(r,"streamingId_set_latest"))}const k=y.findIndex(M=>M.info.id===r);if(k!==-1&&m==="user"){const M=y[k],C=M.parts.findIndex(O=>O.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(r,"skipped_synthetic_user_part"),g;const D=In(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(r,`user_part_type:${D.type||"unknown"}`);const P={...M};C!==-1?P.parts=P.parts.map((O,Z)=>Z===C?D:O):P.parts=[...P.parts,D];const W=[...y];W[k]=P;const K=new Map(g.messages);return K.set(t,W),N({messages:K})}if(m==="assistant"&&k!==-1){const M=y[k],C=M.parts.findIndex(Z=>Z.id===o.id),D=In(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(r,`part_type:${D.type||"unknown"}`);const P={...M};C!==-1?P.parts=P.parts.map((Z,se)=>se===C?D:Z):P.parts=[...P.parts,D];const W=[...y];W[k]=P;const K=new Map(g.messages);K.set(t,W),b.messageStreamStates=uo(g.messageStreamStates,r);const O=fs(b.streamingMessageIds??g.streamingMessageIds,t,r);return O!==(b.streamingMessageIds??g.streamingMessageIds)&&(b.streamingMessageIds=O,window.__messageTracker?.(r,"streamingId_set")),D.type==="text"?w(D.text||""):w(""),N({messages:K,...b})}if(k===-1){if(m==="user"){if(o.synthetic===!0)return window.__messageTracker?.(r,"skipped_synthetic_new_user_part"),g;const V=In(o);window.__messageTracker?.(r,`new_user_part_type:${V.type||"unknown"}`);const L={info:{id:r,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,time:{created:Date.now()}},parts:[V]},R=[...y,L];R.sort((Ce,Ae)=>{const ue=Ce.info?.time?.created||0,me=Ae.info?.time?.created||0;return ue-me});const oe=new Map(g.messages);return oe.set(t,R),N({messages:oe})}if(o?.type==="text"){const V=Bn(o).trim();if(V.length>0){const L=[...y].reverse().find(R=>R.info.role==="user");if(L){const R=L.parts.map(oe=>Bn(oe)).join("").trim();if(R.length>0&&R===V)return ci.add(r),window.__messageTracker?.(r,"ignored_assistant_echo"),g}}}const M=In(o);window.__messageTracker?.(r,`part_type:${M.type||"unknown"}`),M.type==="text"?w(M.text||""):w("");const C=g.pendingAssistantParts.get(r),D=C?[...C.parts]:[],P=D.findIndex(V=>V.id===M.id);P!==-1?D[P]=M:D.push(M);const W=new Map(g.pendingAssistantParts);W.set(r,{sessionId:t,parts:D});const O={info:{id:r,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},Z=[...y,O],se=new Map(g.messages);if(se.set(t,Z),m==="assistant"){b.messageStreamStates=uo(g.messageStreamStates,r);const V=fs(b.streamingMessageIds??g.streamingMessageIds,t,r);V!==(b.streamingMessageIds??g.streamingMessageIds)&&(b.streamingMessageIds=V,window.__messageTracker?.(r,"streamingId_set"))}return N({messages:se,pendingAssistantParts:W,...b})}else{const M=y[k],C=M.parts.findIndex(O=>O.id===o.id),D=In(o,C!==-1?M.parts[C]:void 0);window.__messageTracker?.(r,`part_type:${D.type||"unknown"}`);const P={...M};C!==-1?P.parts=P.parts.map((O,Z)=>Z===C?D:O):P.parts=[...P.parts,D];const W=[...y];W[k]=P;const K=new Map(g.messages);if(K.set(t,W),P.info.role==="assistant"){b.messageStreamStates=uo(g.messageStreamStates,r);const O=fs(b.streamingMessageIds??g.streamingMessageIds,t,r);O!==(b.streamingMessageIds??g.streamingMessageIds)&&(b.streamingMessageIds=O,window.__messageTracker?.(r,"streamingId_set"))}return D.type==="text"?w(D.text||""):w(""),N({messages:K,...b})}}),o?.type==="step-finish"&&m!=="user"&&setTimeout(()=>{s().completeStreamingMessage(t,r)},0)},addStreamingPart:(t,r,o,a,i)=>{if(a!=="user"){s()._addStreamingPartImmediate(t,r,o,a,i);return}mo.push({sessionId:t,messageId:r,part:o,role:a,currentSessionId:i}),fo||(fo=setTimeout(()=>{const c=[...mo];mo=[],fo=null;const d=s();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},rp))},forceCompleteMessage:(t,r,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(u=>u.info.id===r))return c;return null};n(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],u=d.findIndex(S=>S.info.id===r);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 j=S.state;if(!j)return S;const I=j.status,A=I==="running"||I==="pending"||I==="started",k=!j.time||typeof j.time?.end!="number";if(A||k){const M={...j};return A&&(M.status="completed"),k&&(M.time={...j.time??{},end:m}),y=!0,{...S,state:M}}return S}if(S.type==="reasoning"){const j=S.time;return!j||typeof j.end!="number"?(y=!0,{...S,time:{...j??{},end:m}}):S}if(S.type==="text"){const j=S.time;return j&&typeof j.end!="number"?(y=!0,{...S,time:{...j,end:m}}):S}return S});if(!g&&!y)return i;window.__messageTracker?.(r,`force_complete:${o}`);const v={...p,info:x,parts:y?b:p.parts},N=[...d];N[u]=v;const w=new Map(i.messages);return w.set(c,N),{messages:w}})},markMessageStreamSettled:t=>{n(r=>{cc(t);const o=new Map(r.messageStreamStates);o.delete(t);let a=r.messages,i=!1;return r.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(r.messages);g.set(u,h),a=g,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),Ys([t])},updateMessageInfo:(t,r,o)=>{n(a=>{const i=a.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(i&&!sr(r,i))return window.__messageTracker?.(r,"ignored_trimmed_update"),a;const d=[...a.messages.get(t)??[]],u=d.findIndex(j=>j.info.id===r),p=a.pendingAssistantParts.get(r),m=(j=[],I=[])=>{if(!I.length)return j;const A=[...j];return I.forEach(k=>{const M=A.findIndex(C=>C.id===k.id);M===-1?A.push(k):A[M]=k}),A},f=j=>{if(!j)return j;const I=j.clientRole??j.role,A=I==="user"?!0:j.userMessageMarker;return{...j,clientRole:I,...A?{userMessageMarker:!0}:{}}};if(u===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:t,messageId:r,messageInfo:o,existingCount:d.length}),d.length>0){const W=d[0]?.info,K=typeof W?.time?.created=="number"?W.time.created:null,O=typeof W?.id=="string"?W.id:null,Z=o,se=typeof Z?.time?.created=="number"?Z.time.created:null,V=typeof Z?.id=="string"?Z.id:r;let L=!1;if(se!==null&&K!==null&&(L=se<K),!L&&V&&O&&(L=V.localeCompare(O)<0),L)return window.__messageTracker?.(r,"skipped_evicted_message_update"),a}const j=f(o);if(j&&j.role==="user"){const P=p?.parts??[],W={info:{...j,userMessageMarker:!0,clientRole:"user"},parts:P.length>0?[...P]:[]},K=new Map(a.messages),O=[...d,W];O.sort((V,L)=>{const R=V.info?.time?.created||0,oe=L.info?.time?.created||0;return R-oe}),K.set(t,O);const Z={messages:K},se=mn(Z.messageSessionIndex??a.messageSessionIndex,r,t);if(se!==(Z.messageSessionIndex??a.messageSessionIndex)&&(Z.messageSessionIndex=se),p){const V=new Map(a.pendingAssistantParts);V.delete(r),Z.pendingAssistantParts=V}return Z}if(!j||j.role!=="assistant")return a;const I=p?.parts??[],A={info:{...j,animationSettled:j?.animationSettled??!1},parts:I.length>0?[...I]:[]},k=new Map(a.messages),M=[...d,A];k.set(t,M);const C={messages:k},D=mn(C.messageSessionIndex??a.messageSessionIndex,r,t);if(D!==(C.messageSessionIndex??a.messageSessionIndex)&&(C.messageSessionIndex=D),p){const P=new Map(a.pendingAssistantParts);P.delete(r),C.pendingAssistantParts=P}return C}const h=d[u],g=h.info;if(g.userMessageMarker===!0||g.clientRole==="user"||g.role==="user"){const j={...h.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:g.providerID||void 0,modelID:g.modelID||void 0},I={...h,info:j},A=new Map(a.messages),k=[...d];return k[u]=I,A.set(t,k),{messages:A}}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},N=new Map(a.messages),w=[...d];w[u]=v,N.set(t,w);const S={messages:N};if(p){const j=new Map(a.pendingAssistantParts);j.delete(r),S.pendingAssistantParts=j}return S})},completeStreamingMessage:(t,r)=>{const o=s();window.__messageTracker?.(r,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,r,"cooldown");const a=o.streamingMessageIds.get(t)===r;a?window.__messageTracker?.(r,"streamingId_cleared"):window.__messageTracker?.(r,"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(r)){const d=new Map(o.messageStreamStates);d.delete(r),i.messageStreamStates=d}Object.keys(i).length>0&&n(i),o.pendingAssistantParts.has(r)&&n(d=>{if(!d.pendingAssistantParts.has(r))return d;const u=new Map(d.pendingAssistantParts);return u.delete(r),{pendingAssistantParts:u}}),Ys([r]);let c=!1;if(n(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=un.get(t);d&&(clearTimeout(d),un.delete(t));const u=setTimeout(()=>{n(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}}),un.delete(t)},2e3);un.set(t,u)}},syncMessages:(t,r)=>{const o=ui(t),a=mi(r,o),i=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=i?a.filter(d=>{const u=d?.info?.id;return u?sr(u,i):!0}):a;n(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 j={...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},I=(Array.isArray(S.parts)?S.parts:[]).map(M=>{if(M?.type==="text"){const C=M.text??M.content??"";if(co(C))return{...M,synthetic:!0}}return M}),A=typeof j?.id=="string"?j.id:void 0,k=A?m.get(A):void 0;if(k&&k.info.role==="assistant"){const M=Array.isArray(k.parts)?k.parts:[],C=hn(M),D=hn(I);if(_r(M)&&C>D){const W=$r(M,I);return{...S,info:j,parts:W}}}return{...S,info:j,parts:I}}),h=po(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=Tn(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=nr(b.messageSessionIndex??d.messageSessionIndex,y);S!==(b.messageSessionIndex??d.messageSessionIndex)&&(b.messageSessionIndex=S)}if(y.length>0){const S=new Map(d.pendingAssistantParts);let j=!1;y.forEach(I=>{S.delete(I)&&(j=!0)}),j&&(b.pendingAssistantParts=S)}const N=b.messageSessionIndex??d.messageSessionIndex;let w=N;return h.forEach(S=>{const j=S?.info?.id;typeof j=="string"&&j.length>0&&(w=mn(w,j,t))}),w!==N&&(b.messageSessionIndex=w),b}),setTimeout(()=>{n({isSyncing:!1})},100)},updateSessionCompaction:(t,r)=>{n(o=>{const a=new Map(o.sessionCompactionUntil);if(!r||r<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=r+op;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&n(r=>{const o=r.sessionAbortFlags.get(t);if(!o||o.acknowledged)return r;const a=new Map(r.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,r)=>{n(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:r}),{sessionMemoryState:i}})},trimToViewportWindow:(t,r=$t.VIEWPORT_MESSAGES,o)=>{const a=s(),i=a.messages.get(t);if(!i||i.length<=r)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(r/2));const p=Math.min(i.length,u+r);p===i.length&&p-u<r&&(u=Math.max(0,p-r));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);n(x=>{const y=new Map(x.messages);y.set(t,m);const b=new Map(x.sessionMemoryState),v={...c,viewportAnchor:d-u,trimmedHeadMaxId:cp(f,c.trimmedHeadMaxId)};b.set(t,v);const N={messages:y,sessionMemoryState:b};Ys(g);const w=Tn(x.messageStreamStates,g);if(w!==x.messageStreamStates&&(N.messageStreamStates=w),g.length>0){const I=x.streamingMessageIds.get(t);I&&g.includes(I)&&(N.streamingMessageIds=fs(N.streamingMessageIds??x.streamingMessageIds,t,null))}if(g.length>0){const I=nr(N.messageSessionIndex??x.messageSessionIndex,g);I!==(N.messageSessionIndex??x.messageSessionIndex)&&(N.messageSessionIndex=I)}const S=N.messageSessionIndex??x.messageSessionIndex;let j=S;return m.forEach(I=>{const A=I?.info?.id;typeof A=="string"&&A.length>0&&(j=mn(j,A,t))}),j!==S&&(N.messageSessionIndex=j),N})},evictLeastRecentlyUsed:t=>{const r=s();if(r.messages.size<=$t.MAX_SESSIONS)return;const a=[];r.messages.forEach((d,u)=>{const p=r.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];n(d=>{const p=(d.messages.get(c)||[]).map(w=>w.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((w,S)=>{w.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=Tn(d.messageStreamStates,p);b!==d.messageStreamStates&&(h.messageStreamStates=b);const v=nr(h.messageSessionIndex??d.messageSessionIndex,p);v!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=v);const N=fs(d.streamingMessageIds,c,null);if(N!==d.streamingMessageIds&&(h.streamingMessageIds=N),d.abortControllers.has(c)){const w=new Map(d.abortControllers);w.delete(c),h.abortControllers=w}return h})},loadMoreMessages:async(t,r="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 ho(t,()=>Me.getSessionMessages(t));if(r==="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($t.VIEWPORT_MESSAGES,u),m=c.slice(u-p,u);n(f=>{const h=[...m,...a],g=po(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&&n(p=>{const m=new Map(p.sessionMemoryState);return m.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:m}})}},getLastMessageModel:t=>{const{messages:r}=s(),o=r.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(()=>es()),partialize:n=>({lastUsedProvider:n.lastUsedProvider,sessionMemoryState:Array.from(n.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(n.sessionAbortFlags.entries()).map(([s,t])=>[s,{timestamp:t.timestamp,acknowledged:t.acknowledged}])}),merge:(n,s)=>{if(!n)return s;let t=s.sessionMemoryState;Array.isArray(n.sessionMemoryState)&&(t=new Map(n.sessionMemoryState.map(o=>o)));let r=s.sessionAbortFlags;return Array.isArray(n.sessionAbortFlags)&&(r=new Map(n.sessionAbortFlags)),{...s,lastUsedProvider:n.lastUsedProvider??s.lastUsedProvider,sessionMemoryState:t,sessionAbortFlags:r}}}),{name:"message-store"})),mp=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),fp=n=>n?mp.has(n.toLowerCase()):!1,pp=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},hp=n=>{if(n)try{const s=pp();if(s?.getState)return s.getState().agents?.find?.(r=>r.name===n)}catch{}},Sr=n=>{const s=hp(n);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=n=>{if(!n||typeof n!="object")return 0;const s=n.input??0,t=n.output??0,r=n.reasoning??0,o=n.cache&&typeof n.cache=="object"?n.cache.read??0:0,a=n.cache&&typeof n.cache=="object"?n.cache.write??0:0;return s+t+r+o+a},go=n=>{const s=n.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return fi(s);const t=n.parts.find(r=>typeof r.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:fi(t.tokens)},xo=(n,s,t)=>{const r=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,r),d=r>0?Math.max(r-c,1):0,u=d>0?n/d*100:0;return{percentage:Math.min(u,100),contextLimit:r,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},Fn=["ask","allow","full"],pt=Ft()(Wt(Ss((n,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,r,o)=>{n(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:r,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:r}=s();return r.get(t)||null},saveSessionAgentSelection:(t,r)=>{n(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,r),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:r}=s();return r.get(t)||null},saveAgentModelForSession:(t,r,o,a)=>{n(i=>{const c=new Map(i.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(r,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(t,r)=>{const{sessionAgentModelSelections:o}=s(),a=o.get(t);return a&&a.get(r)||null},analyzeAndSaveExternalSessionChoices:async(t,r,o)=>{const{saveAgentModelForSession:a}=s(),i=new Map,c=(m,f)=>{if("mode"in m&&m.mode&&typeof m.mode=="string"&&r.find(y=>y.name===m.mode))return m.mode;if(m.providerID&&m.modelID){const x=r.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&&r.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 N=y[b].info;if(N.providerID===m.providerID&&N.modelID===m.modelID){if(N.mode&&typeof N.mode=="string"&&r.find(j=>j.name===N.mode))return N.mode;const w=r.find(S=>S.model?.providerID===N.providerID&&S.model?.modelID===N.modelID);if(w)return w.name}}}return m.providerID&&m.modelID&&r.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&&r.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,r,o,a)=>{if(!t)return null;const i=xo(0,r,o),c=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(c===0||u===0)return null;const m=(a.get(t)||[]).filter(N=>N.info.role==="assistant");if(m.length===0)return null;const f=m[m.length-1],h=f.info.id,g=N=>{const w=()=>{n(S=>{const j=S.sessionContextUsage.get(t);if(j&&j.totalTokens===N.totalTokens&&j.percentage===N.percentage&&j.contextLimit===N.contextLimit&&(j.outputLimit??0)===(N.outputLimit??0)&&(j.normalizedOutput??0)===(N.normalizedOutput??0)&&j.thresholdLimit===N.thresholdLimit&&j.lastMessageId===N.lastMessageId)return S;const I=new Map(S.sessionContextUsage);return I.set(t,N),{sessionContextUsage:I}})};typeof queueMicrotask=="function"?queueMicrotask(w):typeof window<"u"?window.setTimeout(w,0):setTimeout(w,0)},x=s().sessionContextUsage.get(t);if(x&&x.lastMessageId===h){const N=x.normalizedOutput??x.outputLimit??0,w=x.contextLimit!==c||N!==d||x.thresholdLimit!==u;if(w&&x.totalTokens>0){const S=x.totalTokens/u*100,j={totalTokens:x.totalTokens,percentage:Math.min(S,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(j),j}if(!w&&x.totalTokens>0)return x}const y=go(f);if(y===0)return x||null;const b=xo(y,r,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,r,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=go(d);if(u===0)return;const p=xo(u,r,o);n(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,r,o,a)=>{const c=s().sessionContextUsage.get(t);(!c||c.totalTokens===0)&&s().updateSessionContextUsage(t,r,o,a)},pollForTokenUpdates:(t,r,o,a=10)=>{let i=0;const c=()=>{i++;const u=(o.get(t)||[]).find(p=>p.info.id===r);if(u&&u.info.role==="assistant"&&go(u)>0){s().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:r}=s();return r.get(t)},getSessionAgentEditMode:(t,r,o=Sr(r))=>!t||!r?o:s().sessionAgentEditModes.get(t)?.get(r)??o,setSessionAgentEditMode:(t,r,o,a=Sr(r))=>{if(!t||!r)return;const i=a??"ask";i==="deny"||o==="deny"||Fn.includes(o)&&n(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(r),u.size===0?d.delete(t):d.set(t,u)):(u.set(r,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,r,o=Sr(r))=>{if(!t||!r)return;const a=o??"ask";if(a==="deny")return;const i=s().getSessionAgentEditMode(t,r,a),c=Fn.indexOf(i),d=Fn.indexOf(a),p=((c>=0?c:d>=0?d:0)+1)%Fn.length,m=Fn[p];s().setSessionAgentEditMode(t,r,m,a)}}),{name:"context-store",storage:ks(()=>es()),partialize:n=>({sessionModelSelections:Array.from(n.sessionModelSelections.entries()),sessionAgentSelections:Array.from(n.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(n.sessionAgentModelSelections.entries()).map(([s,t])=>[s,Array.from(t.entries())]),currentAgentContext:Array.from(n.currentAgentContext.entries()),sessionContextUsage:Array.from(n.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(n.sessionAgentEditModes.entries()).map(([s,t])=>[s,Array.from(t.entries())])}),merge:(n,s)=>{const t=new Map;n?.sessionAgentModelSelections&&n.sessionAgentModelSelections.forEach(([o,a])=>{t.set(o,new Map(a))});const r=new Map;return n?.sessionAgentEditModes&&n.sessionAgentEditModes.forEach(([o,a])=>{r.set(o,new Map(a))}),{...s,...n,sessionModelSelections:new Map(n?.sessionModelSelections||[]),sessionAgentSelections:new Map(n?.sessionAgentSelections||[]),sessionAgentModelSelections:t,currentAgentContext:new Map(n?.currentAgentContext||[]),sessionContextUsage:new Map(n?.sessionContextUsage||[]),sessionAgentEditModes:r,hasHydrated:!0}}}),{name:"context-store"})),gp=n=>typeof n=="object"&&n!==null,xp=n=>{if(!Array.isArray(n))return[];const s=[];return n.forEach(t=>{if(!Array.isArray(t)||t.length!==2)return;const[r,o]=t;typeof r!="string"||!Array.isArray(o)||s.push([r,o])}),s},yp=async(n,s)=>{try{const t=Xe.getState(),r=t.getWorktreeMetadata(n);if(r?.path)return Me.withDirectory(r.path,s);const o=t.sessions.find(i=>i.id===n),a=typeof o?.directory=="string"&&o.directory.length>0?o.directory:void 0;if(a)return Me.withDirectory(a,s)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return s()},Br=Ft()(Wt(Ss((n,s)=>({permissions:new Map,addPermission:(t,r)=>{const o=t.sessionID;if(!o)return;const a=t.type?.toLowerCase?.()??null;let i=r?.currentAgentContext?.get(o);if(i||(i=r?.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=Sr(i),d=r?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&fp(a)){s().respondToPermission(o,t.id,"once").catch(()=>{});return}n(p=>{const m=p.permissions.get(o)||[],f=new Map(p.permissions);return f.set(o,[...m,t]),{permissions:f}})},respondToPermission:async(t,r,o)=>{await yp(t,()=>Me.respondToPermission(t,r,o)),o==="reject"&&await rt.getState().abortCurrentOperation(t),n(a=>{const c=(a.permissions.get(t)||[]).filter(u=>u.id!==r),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:ks(()=>es()),partialize:n=>({permissions:Array.from(n.permissions.entries())}),merge:(n,s)=>{if(!gp(n))return s;const t=xp(n.permissions);return{...s,permissions:new Map(t)}}}),{name:"permission-store"})),dc=n=>n.filter(r=>r?.type==="text").map(r=>(r.text||r.content||"").trim()).filter(r=>r.length>0).join(`
|
|
4
|
+
`).replace(/\n\s*\n+/g,`
|
|
5
|
+
`),pi=n=>{if(typeof n!="string")return null;const s=n.trim();if(!s)return null;const t=s.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},hi=(n,s,t)=>{if(!s)return null;const r=t(s)?.path;if(typeof r=="string"&&r.trim().length>0)return pi(r);const o=n.find(a=>a.id===s);return o?pi(o.directory??null):null},fe=Ft()(Wt((n,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,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},getSessionAgentEditMode:(t,r,o)=>pt.getState().getSessionAgentEditMode(t,r,o),toggleSessionAgentEditMode:(t,r,o)=>pt.getState().toggleSessionAgentEditMode(t,r,o),setSessionAgentEditMode:(t,r,o,a)=>pt.getState().setSessionAgentEditMode(t,r,o,a),loadSessions:()=>Xe.getState().loadSessions(),openNewSessionDraft:t=>{n({newSessionDraft:{open:!0,directoryOverride:t?.directoryOverride??null,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const r=St.getState(),o=r.getVisibleAgents(),a=r.currentAgentName||o.find(i=>i.name==="build")?.name||o[0]?.name;a&&r.setAgent(a)}catch{}},closeNewSessionDraft:()=>{const t=Xe.getState().currentSessionId;n({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:t})},createSession:async(t,r,o)=>{s().closeNewSessionDraft();const a=await Xe.getState().createSession(t,r,o);return a?.id&&await s().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const r=rt.getState(),{messages:o,lastUsedProvider:a}=r;let i,c;if(o.forEach((b,v)=>{const N=b.find(w=>w.info?.id===t);N&&!i&&(i=N,c=v)}),!i||i.info.role!=="assistant")return;const d=dc(i.parts);if(!d.trim())return;const u=Xe.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 Me.sendMessage({id:m.id,providerID:x,modelID:y,text:d,prefaceText:lc,agent:g??void 0})},deleteSession:(t,r)=>Xe.getState().deleteSession(t,r),deleteSessions:(t,r)=>Xe.getState().deleteSessions(t,r),updateSessionTitle:(t,r)=>Xe.getState().updateSessionTitle(t,r),shareSession:t=>Xe.getState().shareSession(t),unshareSession:t=>Xe.getState().unshareSession(t),setCurrentSession:async t=>{t&&s().closeNewSessionDraft();const r=Xe.getState().currentSessionId,o=hi(Xe.getState().sessions,t,Xe.getState().getWorktreeMetadata),a=Me.getDirectory()??bt.getState().currentDirectory??null,i=o??a;try{Me.setDirectory(i??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}if(r&&r!==t&&!s().sessionMemoryState.get(r)?.isStreaming){const d=s().messages.get(r)||[];d.length>0&&s().updateViewportAnchor(r,d.length-1),s().trimToViewportWindow(r,$t.VIEWPORT_MESSAGES)}Xe.getState().setCurrentSession(t),t&&(s().messages.get(t)||await s().loadMessages(t),s().trimToViewportWindow(t,hf)),s().evictLeastRecentlyUsed()},loadMessages:t=>rt.getState().loadMessages(t),sendMessage:async(t,r,o,a,i,c)=>{const d=s().newSessionDraft;if(d?.open){const p=await Xe.getState().createSession(d.title,d.directoryOverride??null,d.parentID??null);if(!p?.id)throw new Error("Failed to create session");const m=St.getState(),f=m.currentAgentName,h=m.currentProviderId,g=m.currentModelId;if(h&&g)try{pt.getState().saveSessionModelSelection(p.id,h,g)}catch{}if(f){try{pt.getState().saveSessionAgentSelection(p.id,f)}catch{}if(h&&g)try{pt.getState().saveAgentModelForSession(p.id,f,h,g)}catch{}}try{Xe.getState().initializeNewOpenChamberSession(p.id,m.agents)}catch{}return s().closeNewSessionDraft(),rt.getState().sendMessage(t,r,o,a,p.id,i,c)}const u=Xe.getState().currentSessionId;return rt.getState().sendMessage(t,r,o,a,u||void 0,i,c)},abortCurrentOperation:()=>{const t=Xe.getState().currentSessionId;return rt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const r=Xe.getState().currentSessionId;if(!r)return null;const o=Date.now()+t;return n({abortPromptSessionId:r,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{n({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&&rt.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,r,o,a)=>{const c=Xe.getState().currentSessionId||t;return rt.getState().addStreamingPart(t,r,o,a,c)},completeStreamingMessage:(t,r)=>rt.getState().completeStreamingMessage(t,r),markMessageStreamSettled:t=>rt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,r,o)=>rt.getState().updateMessageInfo(t,r,o),updateSessionCompaction:(t,r)=>rt.getState().updateSessionCompaction(t,r??null),addPermission:t=>{const r={currentAgentContext:pt.getState().currentAgentContext,sessionAgentSelections:pt.getState().sessionAgentSelections,getSessionAgentEditMode:pt.getState().getSessionAgentEditMode};return Br.getState().addPermission(t,r)},respondToPermission:(t,r,o)=>Br.getState().respondToPermission(t,r,o),clearError:()=>Xe.getState().clearError(),getSessionsByDirectory:t=>Xe.getState().getSessionsByDirectory(t),getLastMessageModel:t=>rt.getState().getLastMessageModel(t),getCurrentAgent:t=>pt.getState().getCurrentAgent(t),syncMessages:(t,r)=>rt.getState().syncMessages(t,r),applySessionMetadata:(t,r)=>Xe.getState().applySessionMetadata(t,r),addAttachedFile:t=>zs.getState().addAttachedFile(t),addServerFile:(t,r,o)=>zs.getState().addServerFile(t,r,o),removeAttachedFile:t=>zs.getState().removeAttachedFile(t),clearAttachedFiles:()=>zs.getState().clearAttachedFiles(),updateViewportAnchor:(t,r)=>rt.getState().updateViewportAnchor(t,r),trimToViewportWindow:(t,r)=>{const o=Xe.getState().currentSessionId;return rt.getState().trimToViewportWindow(t,r,o||void 0)},evictLeastRecentlyUsed:()=>{const t=Xe.getState().currentSessionId;return rt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,r)=>rt.getState().loadMoreMessages(t,r),saveSessionModelSelection:(t,r,o)=>pt.getState().saveSessionModelSelection(t,r,o),getSessionModelSelection:t=>pt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,r)=>pt.getState().saveSessionAgentSelection(t,r),getSessionAgentSelection:t=>pt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,r,o,a)=>pt.getState().saveAgentModelForSession(t,r,o,a),getAgentModelForSession:(t,r)=>pt.getState().getAgentModelForSession(t,r),analyzeAndSaveExternalSessionChoices:(t,r)=>{const o=rt.getState().messages;return pt.getState().analyzeAndSaveExternalSessionChoices(t,r,o)},isOpenChamberCreatedSession:t=>Xe.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>Xe.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,r)=>Xe.getState().initializeNewOpenChamberSession(t,r),setWorktreeMetadata:(t,r)=>Xe.getState().setWorktreeMetadata(t,r),setSessionDirectory:(t,r)=>Xe.getState().setSessionDirectory(t,r),getWorktreeMetadata:t=>Xe.getState().getWorktreeMetadata(t),getContextUsage:(t,r)=>{if(s().newSessionDraft?.open)return null;const o=Xe.getState().currentSessionId;if(!o)return null;const a=rt.getState().messages;return pt.getState().getContextUsage(o,t,r,a)},updateSessionContextUsage:(t,r,o)=>{const a=rt.getState().messages;return pt.getState().updateSessionContextUsage(t,r,o,a)},initializeSessionContextUsage:(t,r,o)=>{const a=rt.getState().messages;return pt.getState().initializeSessionContextUsage(t,r,o,a)},debugSessionMessages:async t=>{const r=rt.getState().messages.get(t)||[],o=Xe.getState().sessions.find(a=>a.id===t);console.log(`Debug session ${t}:`,{session:o,messageCount:r.length,messages:r.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(t,r,o)=>{const a=rt.getState().messages;return pt.getState().pollForTokenUpdates(t,r,a,o)},updateSession:t=>Xe.getState().updateSession(t),revertToMessage:async(t,r)=>{const a=(rt.getState().messages.get(t)||[]).find(p=>p.info.id===r);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 Me.revertSession(t,r);Xe.getState().updateSession(c);const d=rt.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);rt.getState().syncMessages(t,m)}}i&&n({pendingInputText:i})},setPendingInputText:t=>{n({pendingInputText:t})},consumePendingInputText:()=>{const t=s().pendingInputText;return t!==null&&n({pendingInputText:null}),t}}),{name:"composed-session-store"}));Xe.subscribe((n,s)=>{if(n.sessions===s.sessions&&n.currentSessionId===s.currentSessionId&&n.lastLoadedDirectory===s.lastLoadedDirectory&&n.isLoading===s.isLoading&&n.error===s.error&&n.webUICreatedSessions===s.webUICreatedSessions&&n.worktreeMetadata===s.worktreeMetadata&&n.availableWorktrees===s.availableWorktrees)return;const t=fe.getState().newSessionDraft?.open;fe.setState({sessions:n.sessions,currentSessionId:t?null:n.currentSessionId,lastLoadedDirectory:n.lastLoadedDirectory,isLoading:n.isLoading,error:n.error,webUICreatedSessions:n.webUICreatedSessions,worktreeMetadata:n.worktreeMetadata,availableWorktrees:n.availableWorktrees})});rt.subscribe((n,s)=>{if(n.messages===s.messages&&n.sessionMemoryState===s.sessionMemoryState&&n.messageStreamStates===s.messageStreamStates&&n.sessionCompactionUntil===s.sessionCompactionUntil&&n.sessionAbortFlags===s.sessionAbortFlags&&n.streamingMessageIds===s.streamingMessageIds&&n.abortControllers===s.abortControllers&&n.lastUsedProvider===s.lastUsedProvider&&n.isSyncing===s.isSyncing)return;const t=new Map;n.messages.forEach((r,o)=>{if(!(!Array.isArray(r)||r.length===0))for(let a=r.length-1;a>=0;a-=1){const i=r[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:n.messages,sessionMemoryState:n.sessionMemoryState,messageStreamStates:n.messageStreamStates,sessionCompactionUntil:n.sessionCompactionUntil,sessionAbortFlags:n.sessionAbortFlags,streamingMessageIds:n.streamingMessageIds,abortControllers:n.abortControllers,lastUsedProvider:n.lastUsedProvider,isSyncing:n.isSyncing,userSummaryTitles:t})});zs.subscribe((n,s)=>{n.attachedFiles!==s.attachedFiles&&fe.setState({attachedFiles:n.attachedFiles})});pt.subscribe((n,s)=>{n.sessionModelSelections===s.sessionModelSelections&&n.sessionAgentSelections===s.sessionAgentSelections&&n.sessionAgentModelSelections===s.sessionAgentModelSelections&&n.currentAgentContext===s.currentAgentContext&&n.sessionContextUsage===s.sessionContextUsage&&n.sessionAgentEditModes===s.sessionAgentEditModes||fe.setState({sessionModelSelections:n.sessionModelSelections,sessionAgentSelections:n.sessionAgentSelections,sessionAgentModelSelections:n.sessionAgentModelSelections,currentAgentContext:n.currentAgentContext,sessionContextUsage:n.sessionContextUsage,sessionAgentEditModes:n.sessionAgentEditModes})});Br.subscribe((n,s)=>{n.permissions!==s.permissions&&fe.setState({permissions:n.permissions})});const bp=fe.getState().newSessionDraft?.open;fe.setState({sessions:Xe.getState().sessions,currentSessionId:bp?null:Xe.getState().currentSessionId,lastLoadedDirectory:Xe.getState().lastLoadedDirectory,isLoading:Xe.getState().isLoading,error:Xe.getState().error,webUICreatedSessions:Xe.getState().webUICreatedSessions,worktreeMetadata:Xe.getState().worktreeMetadata,availableWorktrees:Xe.getState().availableWorktrees,messages:rt.getState().messages,sessionMemoryState:rt.getState().sessionMemoryState,messageStreamStates:rt.getState().messageStreamStates,sessionCompactionUntil:rt.getState().sessionCompactionUntil,sessionAbortFlags:rt.getState().sessionAbortFlags,streamingMessageIds:rt.getState().streamingMessageIds,abortControllers:rt.getState().abortControllers,lastUsedProvider:rt.getState().lastUsedProvider,isSyncing:rt.getState().isSyncing,permissions:Br.getState().permissions,attachedFiles:zs.getState().attachedFiles,sessionModelSelections:pt.getState().sessionModelSelections,sessionAgentSelections:pt.getState().sessionAgentSelections,sessionAgentModelSelections:pt.getState().sessionAgentModelSelections,currentAgentContext:pt.getState().currentAgentContext,sessionContextUsage:pt.getState().sessionContextUsage,sessionAgentEditModes:pt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=fe);const wa=({containerRef:n,minThumbSize:s=32,hideDelayMs:t=1e3,className:r,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 k=n.current;if(!k)return;const{scrollHeight:M,clientHeight:C,scrollTop:D,scrollWidth:P,clientWidth:W,scrollLeft:K}=k,O=8;if(M>C){const Z=Math.max(C-O*2,0),se=C/M*Z,V=Math.max(s,Math.min(Z,se)),L=Math.max(Z-V,0),R=Math.max(M-C,1),oe=D/R*L;d({length:V,offset:oe})}else d({length:0,offset:0});if(!o&&P>W){const Z=Math.max(W-O*2,0),se=W/P*Z,V=Math.max(s,Math.min(Z,se)),L=Math.max(Z-V,0),R=Math.max(P-W,1),oe=K/R*L;p({length:V,offset:oe})}else p({length:0,offset:0})},[n,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 k=n.current;if(!k)return;y(),i(!0),b(),k.addEventListener("scroll",v,{passive:!0});const M=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null;M?.observe(k);const C=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return C?.observe(k,{childList:!0,subtree:!0,characterData:!0}),()=>{k.removeEventListener("scroll",v),M?.disconnect(),C?.disconnect(),m.current&&clearTimeout(m.current),f.current&&cancelAnimationFrame(f.current)}},[n,v,b,y]);const N=(k,M)=>{const C=n.current;C&&(h.current=!0,g.current={pointerX:k.clientX,pointerY:k.clientY,scrollTop:C.scrollTop,scrollLeft:C.scrollLeft},x.current=M,i(!0),m.current&&clearTimeout(m.current),k.currentTarget.setPointerCapture(k.pointerId))},w=k=>{if(!h.current)return;const M=n.current;if(!M)return;const C=x.current;if(C==="vertical"){const{pointerY:D,scrollTop:P}=g.current,W=k.clientY-D,K=M.clientHeight,O=Math.max(K-c.length,1),Z=Math.max(M.scrollHeight-M.clientHeight,1),se=W/O*Z;M.scrollTop=P+se}else if(C==="horizontal"){const{pointerX:D,scrollLeft:P}=g.current,W=k.clientX-D,K=M.clientWidth,O=Math.max(K-u.length,1),Z=Math.max(M.scrollWidth-M.clientWidth,1),se=W/O*Z;M.scrollLeft=P+se}},S=k=>{h.current&&(h.current=!1,k.currentTarget.releasePointerCapture(k.pointerId),b())},j=c.length>0,I=u.length>0;if(!j&&!I)return null;const A=8;return e.jsxs("div",{className:T("overlay-scrollbar",r),"aria-hidden":"true",style:{opacity:a?1:0},children:[j&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${A+c.offset}px`,right:`${A/2}px`},onPointerDown:k=>N(k,"vertical"),onPointerMove:w,onPointerUp:S,onPointerCancel:S}),I&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${A+u.offset}px`,bottom:`${A/2}px`},onPointerDown:k=>N(k,"horizontal"),onPointerMove:w,onPointerUp:S,onPointerCancel:S})]})},tt=l.forwardRef(({className:n,outerClassName:s,children:t,style:r,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,...p},m)=>{const f=l.useRef(null);return l.useImperativeHandle(m,()=>f.current,[]),e.jsxs("div",{className:T("relative flex flex-col min-h-0 w-full overflow-hidden",s),children:[e.jsx(i,{ref:f,className:T("overlay-scrollbar-target overlay-scrollbar-container",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",n),style:r,...p,children:t}),e.jsx(wa,{containerRef:f,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});tt.displayName="ScrollableOverlay";const gi="mobile-overlay-root",wp=()=>{if(typeof document>"u")return null;let n=document.getElementById(gi);return n||(n=document.createElement("div"),n.id=gi,document.body.appendChild(n)),n},qt=({open:n,title:s,onClose:t,children:r,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:c})=>{const d=l.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=wp()),l.useEffect(()=>{if(!n)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)}},[n,t]),!n||!d.current)return null;const u=i??"max-h-[min(70vh,520px)]",p=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:T("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),onClick:m=>m.stopPropagation(),children:[(()=>{const m=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(ds,{className:"h-4 w-4"})});return c?c(m):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:s}),m]})})(),e.jsx(tt,{outerClassName:u,className:"px-2 py-2 pwa-overlay-scroll",children:r}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return Od.createPortal(p,d.current)},Vo=({totalTokens:n,percentage:s,contextLimit:t,outputLimit:r,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 r=="number"?Math.max(r,0):0,f=[`Used tokens: ${u(n)}`,`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:T("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",onTouchStart:a?h:void 0,onTouchEnd:a?g:void 0,children:[e.jsx(_d,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:T(p(s),"font-medium"),children:[Math.min(s,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[x,e.jsx(qt,{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(n)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(m)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:T("typography-meta font-semibold",p(s)),children:[Math.min(s,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:x}),e.jsx(st,{children:e.jsx("div",{className:"space-y-0.5",children:f.map(y=>e.jsx("p",{className:"typography-micro leading-tight",children:y},y))})})]})},Pn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},uc=(n,s,t)=>{if(typeof window>"u")return;const r=document.documentElement,o=s==="mobile",a=s==="tablet";r.classList.remove("device-mobile","device-tablet","device-desktop"),r.classList.add(s==="mobile"?"device-mobile":s==="tablet"?"device-tablet":"device-desktop"),n?(r.classList.add("desktop-runtime"),r.style.setProperty("--is-mobile","0"),r.style.setProperty("--device-type","desktop"),r.style.setProperty("--font-scale","1"),r.style.setProperty("--has-coarse-pointer","0"),r.style.setProperty("--has-touch-input","0"),r.classList.remove("mobile-pointer")):(r.classList.remove("desktop-runtime"),r.style.setProperty("--is-mobile",o?"1":"0"),r.style.setProperty("--device-type",s),r.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),r.style.setProperty("--has-coarse-pointer",t?"1":"0"),r.style.setProperty("--has-touch-input",t?"1":"0"),t?r.classList.add("mobile-pointer"):r.classList.remove("mobile-pointer"))};function yo(){const n=window.innerWidth,s=typeof window.matchMedia=="function",t=s?window.matchMedia("(pointer: coarse)"):null,r=s?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=r?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=n>Pn.md&&n<=Pn.lg,p=n<=Pn.md;let m=d&&p,f=d&&!m&&u,h=!d||n>Pn.lg,g="desktop";c?(m=!1,f=!1,h=!0,g="desktop"):m?g="mobile":f?g="tablet":(h=!0,g="desktop"),uc(c,g,d);let x="xs";for(const[y,b]of Object.entries(Pn))n>=b&&(x=y);return{isMobile:m,isTablet:f,isDesktop:h,deviceType:g,screenWidth:n,breakpoint:x,hasTouchInput:d}}function Nt(){const[n,s]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:yo());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{s(yo())};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)"),r=window.matchMedia("(hover: none)"),o=()=>{s(yo())},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(r),()=>{a.forEach(c=>c())}},[]),l.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",r=typeof window.matchMedia=="function",o=r?window.matchMedia("(pointer: coarse)"):null,a=r?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;uc(t,n.deviceType,u)},[n.deviceType,n.hasTouchInput]),n}const rr=5e3,vp=1e4,jp=5e3,Sp=1e4,ps=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),kp=(n,s)=>{if(!n&&!s)return!1;if(!n||!s)return!0;const t=new Set([...Object.keys(n),...Object.keys(s)]);for(const r of t){const o=n[r],a=s[r];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},Np=(n,s)=>{if(!n&&!s)return!1;if(!n||!s)return!0;const t=n.files??[],r=s.files??[];if(t.length!==r.length||n.ahead!==s.ahead||n.behind!==s.behind||n.current!==s.current||n.tracking!==s.tracking||n.isClean!==s.isClean)return!0;const o=new Set(t.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of r)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!kp(n.diffStats,s.diffStats)},Cp=(n,s)=>{const t=new Set;if(!s)return t;const r=n?.files??[],o=s.files??[],a=new Map(r.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=n?.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},jt=Ft()(Wt((n,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:rr,setActiveDirectory:t=>{const{activeDirectory:r,directories:o}=s();if(r!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,ps()),n({activeDirectory:t,directories:a})}else n({activeDirectory:t})},getDirectoryState:t=>s().directories.get(t)??null,fetchStatus:async(t,r,o={})=>{const{silent:a=!1}=o,{directories:i}=s();let c=i.get(t);c||(c=ps()),a||n({isLoadingStatus:!0});let d=!1;try{if(!await r.checkIsGitRepository(t)){const m=new Map(i);return m.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),n({directories:m,isLoadingStatus:!1}),!1}const p=await r.getGitStatus(t);if(Np(c.status,p)){d=!0;const m=new Map(s().directories),f=m.get(t)??ps(),h=Cp(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}),n({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}),n({directories:m})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||n({isLoadingStatus:!1})}return d},fetchBranches:async(t,r)=>{n({isLoadingBranches:!0});try{const o=await r.getGitBranches(t),a=new Map(s().directories),i=a.get(t)??ps();a.set(t,{...i,branches:o}),n({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{n({isLoadingBranches:!1})}},fetchLog:async(t,r,o)=>{const{directories:a}=s(),i=a.get(t),c=o??i?.logMaxCount??25;n({isLoadingLog:!0});try{const d=await r.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}),n({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{n({isLoadingLog:!1})}},fetchIdentity:async(t,r)=>{n({isLoadingIdentity:!0});try{const o=await r.getCurrentGitIdentity(t),a=new Map(s().directories),i=a.get(t)??ps();a.set(t,{...i,identity:o}),n({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{n({isLoadingIdentity:!1})}},fetchAll:async(t,r,o={})=>{const{directories:a}=s();let i=a.get(t);if(!i){i=ps();const m=new Map(a);m.set(t,i),n({directories:m})}const{force:c=!1}=o,d=Date.now();await s().fetchStatus(t,r);const u=s().directories.get(t);if(!u?.isGitRepo)return;await s().fetchBranches(t,r);const p=d-(u.lastLogFetch||0);(c||p>Sp||!u.log)&&await s().fetchLog(t,r),await s().fetchIdentity(t,r),await s().fetchAllDiffs(t,r)},getDiff:(t,r)=>s().directories.get(t)?.diffCache.get(r)??null,setDiff:(t,r,o)=>{const a=new Map(s().directories),i=a.get(t)??ps(),c=new Map(i.diffCache);c.set(r,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:c}),n({directories:a})},clearDiffCache:t=>{const r=new Map(s().directories),o=r.get(t);o&&(r.set(t,{...o,diffCache:new Map}),n({directories:r}))},fetchAllDiffs:async(t,r)=>{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 r.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}),n({directories:d})},setLogMaxCount:(t,r)=>{const o=new Map(s().directories),a=o.get(t)??ps();o.set(t,{...a,logMaxCount:r}),n({directories:o})},startPolling:t=>{const{pollIntervalId:r}=s();if(r)return;const o=()=>{const{currentPollInterval:a}=s();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){n({pollIntervalId:o()});return}const{activeDirectory:c}=s();if(!c){n({pollIntervalId:o()});return}if(await s().fetchStatus(c,t,{silent:!0}))await s().fetchLog(c,t),await s().fetchAllDiffs(c,t),n({currentPollInterval:rr});else{const p=Math.min(a+jp,vp);n({currentPollInterval:p})}const{pollIntervalId:u}=s();u!==null&&n({pollIntervalId:o()})},a)};n({pollIntervalId:o(),currentPollInterval:rr})},stopPolling:()=>{const{pollIntervalId:t}=s();t&&(clearTimeout(t),n({pollIntervalId:null,currentPollInterval:rr}))},refresh:async(t,r={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,t,r)}}),{name:"git-store"})),mc=n=>jt(s=>n?s.directories.get(n)?.status??null:null),Mp=n=>jt(s=>n?s.directories.get(n)?.branches??null:null),Ap=n=>jt(s=>n?s.directories.get(n)?.log??null:null),Dp=n=>jt(s=>n?s.directories.get(n)?.identity??null:null),fc=n=>jt(s=>n?s.directories.get(n)?.isGitRepo??null:null),Ep=n=>jt(s=>n?s.directories.get(n)?.status?.files?.length??0:0);function Yt({...n}){return e.jsx($d,{"data-slot":"dropdown-menu",...n})}function Xt({...n}){return e.jsx(Bd,{"data-slot":"dropdown-menu-trigger",...n})}function Jt({className:n,sideOffset:s=4,...t}){return e.jsx(zd,{children:e.jsx(Hd,{"data-slot":"dropdown-menu-content",sideOffset:s,className:T("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",n),...t})})}function ht({className:n,inset:s,variant:t="default",...r}){return e.jsx(Gd,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":t,className:T("hover:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",n),...r})}function Tp({...n}){return e.jsx(Wd,{"data-slot":"dropdown-menu-radio-group",...n})}function Ip({className:n,children:s,...t}){return e.jsxs(Ud,{"data-slot":"dropdown-menu-radio-item",className:T("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",n),...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(Vd,{children:e.jsx(Dt,{className:"size-3"})})}),s]})}function Vn({className:n,...s}){return e.jsx(qd,{"data-slot":"dropdown-menu-separator",className:T("bg-border -mx-1 my-0.5 h-px",n),...s})}function xn({...n}){return e.jsx(Kd,{"data-slot":"dropdown-menu-sub",...n})}function yn({className:n,inset:s,children:t,...r}){return e.jsxs(Yd,{"data-slot":"dropdown-menu-sub-trigger","data-inset":s,className:T("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",n),...r,children:[t,e.jsx(ns,{className:"ml-auto size-3.5"})]})}function bn({className:n,...s}){return e.jsx(Xd,{"data-slot":"dropdown-menu-sub-content",className:T("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",n),...s})}const Fp={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 va(n){return Fp[n]||{displayName:n.charAt(0).toUpperCase()+n.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Pp(n,s,t){const r=va(n);if(r.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=on(o);if(a)return a}if(n==="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 r.outputLanguage||"text"}function on(n){const s=n.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 Rp=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function pc(n){const s=n.split(".").pop()?.toLowerCase();return Rp.includes(s||"")}function Lp(n){const s=n.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 Op(n,s){if(!n)return"";const t=r=>{const o=n[r];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(s==="bash"){const r=t("command");if(r)return r}if(s==="task"){const r=t("prompt");if(r)return r;const o=t("description");if(o)return o}if((s==="edit"||s==="multiedit")&&typeof n=="object"){const r=t("filePath")||t("file_path")||t("path");if(r)return`File path: ${r}`}if(s==="write"&&typeof n=="object"){const r=t("content");if(r)return r}return typeof n=="object"?Object.entries(n).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(n)}const ja=l.createContext(null),an=()=>{const n=l.useContext(ja);if(!n)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return n},hc=n=>{const s=an();return n(s)},_p=()=>hc(n=>n.runtime.isDesktop),Sa=()=>hc(n=>n.runtime.isVSCode),$p=Jd("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 Ee({className:n,variant:s,size:t,asChild:r=!1,...o}){const a=r?Al:"button";return e.jsx(a,{"data-slot":"button",className:T($p({variant:s,size:t,className:n})),...o})}const Bp=({mode:n,onModeChange:s,className:t})=>{const r=l.useCallback(o=>{o.stopPropagation(),s(n==="side-by-side"?"unified":"side-by-side")},[n,s]);return e.jsx(Ee,{size:"sm",variant:"ghost",className:T("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:r,title:n==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:n==="side-by-side"?e.jsx(Zd,{className:"h-3 w-3"}):e.jsx(Qd,{className:"h-3 w-3"})})},ka=de.createContext(void 0);function ln(){const n=de.useContext(ka);if(!n)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return n}function to(){return de.useContext(ka)}const zp="Flexoki",Hp="dark",Wp={"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"},Up=[{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"}}],Vp={name:zp,type:Hp,colors:Wp,tokenColors:Up},Gp="Flexoki",qp="light",Kp={"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"},Yp=[{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"}}],Xp={name:Gp,type:qp,colors:Kp,tokenColors:Yp},Na="flexoki-dark",Ca="flexoki-light",Jp=Vp,Zp=Xp;function gc(n,s){return Object.defineProperty(n,"toString",{value:()=>s,enumerable:!1,configurable:!0}),Object.defineProperty(n,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0}),n}function xc(n,s,t){const r=n.colors?.["editor.background"],o=n.colors?.["editor.foreground"];if(!r||!o)throw new Error(`Flexoki Shiki theme "${s}" is missing editor.background/editor.foreground`);const a=n.tokenColors??[];return{...n,name:s,type:t,fg:o,bg:r,settings:a}}const Ma=xc(Jp,Na,"dark"),Aa=xc(Zp,Ca,"light");gc(Ma,Na);gc(Aa,Ca);const Cn={dark:Na,light:Ca},xi=[Aa,Ma];let yi=!1;function yc(){yi||(Oa(Cn.dark,async()=>Ma),Oa(Cn.light,async()=>Aa),yi=!0)}const Qp=`
|
|
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 eh(n,s,t){const r=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${n}:${s.length}:${t.length}:${r.length}:${o.length}`}const bi=({original:n,modified:s,language:t,fileName:r="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=to()?.currentTheme?.metadata?.variant==="dark";yc();const d=de.useRef(null),u=de.useMemo(()=>{const m=eh(r,n,s);if(d.current?.key===m)return d.current.fileDiff;const f={name:r,contents:n,cacheKey:`old-${m}`},h={name:r,contents:s,cacheKey:`new-${m}`},g=Lo(f,h);return d.current={key:m,fileDiff:g},g},[r,n,s,t]),p=de.useMemo(()=>({theme:{dark:Cn.dark,light:Cn.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:Qp}),[c,o,a]);return typeof window>"u"?null:e.jsx(tt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(eu,{fileDiff:u,options:p})})},th=1100,sh=n=>{const{index:s,working_dir:t}=n;return s==="A"||t==="A"||s==="?"||t==="?"},wi=(n,s)=>{const t=n??0,r=s??0;return!t&&!r?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,r?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",r]}):null]})},nh=l.memo(({changedFiles:n,selectedFile:s,selectedFileEntry:t,onSelectFile:r,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 n.length===0?null:e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[t?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(t.path)}),wi(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(xt,{className:"size-4 opacity-50"})]})}),e.jsx(Jt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Tp,{value:s??"",onValueChange:r,children:n.map(i=>e.jsx(Ip,{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))})})]})}),rh=l.memo(({filePath:n,diff:s,isVisible:t,renderSideBySide:r})=>{const o=s.original.length>0,a=s.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=r?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=r?"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: ${n}`,className:r?"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: ${n}`,className:r?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),oh=l.memo(({filePath:n,diff:s,isVisible:t,renderSideBySide:r,wrapLines:o})=>{const a=l.useMemo(()=>on(n)||"text",[n]);return pc(n)?e.jsx(rh,{filePath:n,diff:s,isVisible:t,renderSideBySide:r}):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:n,renderSideBySide:r,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(bi,{original:s.original,modified:s.modified,language:a,fileName:n,renderSideBySide:r,wrapLines:o})})}),ah=l.memo(({directory:n,filePath:s,isVisible:t,renderSideBySide:r,wrapLines:o})=>{const a=jt(l.useCallback(c=>c.directories.get(n)?.diffCache.get(s)??null,[n,s])),i=l.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a?.original,a?.modified]);return i?e.jsx(oh,{filePath:s,diff:i,isVisible:t,renderSideBySide:r,wrapLines:o}):null}),ih=()=>{const{currentSessionId:n,sessions:s,worktreeMetadata:t}=fe(),{currentDirectory:r}=bt(),o=n?t.get(n)??void 0:void 0,i=s.find(c=>c.id===n)?.directory;return o?.path??i??r??void 0},lh=()=>{const{git:n}=an(),s=ih(),{screenWidth:t,isMobile:r}=Nt(),o=fc(s??null),a=mc(s??null),i=jt(D=>D.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d}=jt(),[u,p]=l.useState(null),m=je(D=>D.pendingDiffFile),f=je(D=>D.setPendingDiffFile),h=je(D=>D.diffLayoutPreference),g=je(D=>D.diffFileLayout),x=je(D=>D.setDiffFileLayout),y=je(D=>D.diffWrapLines),b=je(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:sh(P)})).sort((P,W)=>P.path.localeCompare(W.path))},[a]),N=l.useMemo(()=>u?v.find(D=>D.path===u)??null:null,[v,u]),w=l.useMemo(()=>{if(!N)return null;const D=g[N.path];if(D)return D;if(h==="inline")return"inline";if(h==="side-by-side")return"side-by-side";const P=t<th;return N.isNew||P?"inline":"side-by-side"},[N,g,h,t]);l.useEffect(()=>{s&&(c(s),jt.getState().directories.get(s)?.status||d(s,n))},[s,c,d,n]),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)},[]),j=(w??"side-by-side")==="side-by-side",A=!!jt(l.useCallback(D=>!s||!u?null:D.directories.get(s)?.diffCache.get(u)??null,[s,u])),k=!!u&&!A,M=()=>!s||v.length===0?null:v.map(D=>e.jsx(ah,{directory:s,filePath:D.path,isVisible:D.path===u,renderSideBySide:j,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:[M(),k&&!A&&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:[!r&&e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(sa,{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(nh,{changedFiles:v,selectedFile:u,selectedFileEntry:N,onSelectFile:S,isMobile:r||t<=768}),e.jsx("div",{className:"flex-1"}),N&&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(tu,{className:"size-4"})}),N&&w&&e.jsx(Bp,{mode:w==="side-by-side"?"side-by-side":"unified",onModeChange:D=>{if(!N)return;const P=D==="side-by-side"?"side-by-side":"inline";x(N.path,P)}})]}),C()]})},ch=()=>{const{git:n}=an(),{currentSessionId:s,sessions:t,worktreeMetadata:r}=fe(),{currentDirectory:o}=bt(),a=s?r.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}=jt(),m=Ep(d??null);return l.useEffect(()=>{d&&(u(d),jt.getState().directories.get(d)?.status||p(d,n))},[d,u,p,n]),m},dh=()=>{const n=je(d=>d.setSessionSwitcherOpen),s=je(d=>d.toggleSidebar),{isMobile:t}=Nt(),[r,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?n(!0):s()},[t,n,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||!r||!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(Kr,{className:"h-5 w-5"})})})},vi=()=>{const n=je(R=>R.setSessionSwitcherOpen),s=je(R=>R.toggleSidebar),t=je(R=>R.setSettingsDialogOpen),r=je(R=>R.toggleCommandPalette),o=je(R=>R.toggleHelpDialog),a=je(R=>R.isSidebarOpen),i=je(R=>R.sidebarWidth),c=je(R=>R.activeMainTab),d=je(R=>R.setActiveMainTab),{getCurrentModel:u}=St(),p=fe(R=>R.getContextUsage),{isMobile:m}=Nt(),f=ch(),h=eo(R=>R.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||""),[]);de.useEffect(()=>{if(typeof window>"u")return;const R=typeof window.opencodeDesktop<"u";y(R)},[]);const v=u(),N=v&&typeof v.limit=="object"&&v.limit!==null?v.limit:null,w=N&&typeof N.context=="number"?N.context:0,S=N&&typeof N.output=="number"?N.output:0,j=p(w,S),I=je(R=>R.isSessionSwitcherOpen),A=l.useCallback(()=>{if(typeof document>"u")return;const R=document.activeElement;if(!R)return;const oe=R.tagName;(oe==="INPUT"||oe==="TEXTAREA"||oe==="SELECT"||R.isContentEditable)&&R.blur()},[]),k=l.useCallback(()=>{if(m){A(),n(!I);return}s()},[A,m,I,n,s]),M=l.useCallback(()=>{m&&A(),n(!1),t(!0)},[A,m,n,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 R=g.current?.getBoundingClientRect().height;R&&document.documentElement.style.setProperty("--oc-header-height",`${R}px`)},[]);de.useEffect(()=>{if(typeof window>"u")return;P();const R=g.current;if(!R||typeof ResizeObserver>"u")return()=>{};const oe=new ResizeObserver(()=>{P()});return oe.observe(R),window.addEventListener("resize",P),window.addEventListener("orientationchange",P),()=>{oe.disconnect(),window.removeEventListener("resize",P),window.removeEventListener("orientationchange",P)}},[P]),de.useEffect(()=>{P()},[P,m]);const W=l.useCallback(async R=>{if(!R.target.closest("button, a, input, select, textarea")&&R.button===0&&x)try{const{getCurrentWindow:oe}=await vn(async()=>{const{getCurrentWindow:Ae}=await import("./vendor-.pnpm-CFPpXnpS.js").then(ue=>ue.c3);return{getCurrentWindow:Ae}},__vite__mapDeps([0,1]));await oe().startDragging()}catch(oe){console.error("Failed to start window dragging:",oe)}},[x]),K=l.useCallback(async R=>{if(R.button===0&&x)try{const{getCurrentWindow:oe}=await vn(async()=>{const{getCurrentWindow:Ae}=await import("./vendor-.pnpm-CFPpXnpS.js").then(ue=>ue.c3);return{getCurrentWindow:Ae}},__vite__mapDeps([0,1]));await oe().startDragging()}catch(oe){console.error("Failed to start window dragging:",oe)}},[x]),O=l.useMemo(()=>[{id:"chat",label:"Chat",icon:su},{id:"diff",label:"Diff",icon:ws,badge:!m&&f>0?f:void 0},{id:"terminal",label:"Terminal",icon:Vs},{id:"git",label:"Git",icon:Kt}],[f,m]);de.useEffect(()=>{const R=oe=>{if((oe.metaKey||oe.ctrlKey)&&!oe.shiftKey&&!oe.altKey){const Ce=parseInt(oe.key,10);Ce>=1&&Ce<=O.length&&(oe.preventDefault(),d(O[Ce-1].id))}};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[O,d]);const Z=(R,oe)=>{const Ce=c===R.id,Ae=R.icon,ue=R.id==="chat",me=R.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(R.id),onMouseDown:Ce?K:void 0,className:T("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",Ce?"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",Ce?"text-foreground":"text-muted-foreground",Ce&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",Ce&&ue&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",ue&&!(x&&b&&a)&&"border-l",me&&"border-r",ue&&!m&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...Ce&&ue&&a?{"--sidebar-w":x&&b?`${i}px`:"64px"}:{},...ue&&!(x&&b&&a)||me?{borderColor:"var(--interactive-border)"}:{}},"aria-label":R.label,"aria-selected":Ce,role:"tab",children:[m?e.jsx(Ae,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(Ae,{size:16}),e.jsx("span",{className:"header-tab-label",children:R.label})]}),ue&&!m&&j&&j.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Vo,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit??0,size:"compact"})}),R.badge!==void 0&&R.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:R.badge})]}),!oe&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},R.id)},se=()=>e.jsxs("div",{onMouseDown:W,className:T("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:k,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(Kr,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:O.map((R,oe)=>Z(R,oe===O.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(ot,{delayDuration:500,children:[e.jsx(at,{asChild:!0,children:e.jsx("button",{type:"button",onClick:r,"aria-label":"Open command palette",className:C,children:e.jsx(nn,{className:"h-5 w-5"})})}),e.jsx(st,{children:e.jsx("p",{children:"Command Palette (Ctrl+X)"})})]}),e.jsxs(ot,{delayDuration:500,children:[e.jsx(at,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:C,children:e.jsx(Sn,{className:"h-5 w-5"})})}),e.jsx(st,{children:e.jsx("p",{children:"Keyboard Shortcuts (Ctrl+H)"})})]})]})]}),V=()=>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:k,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(nu,{className:"h-5 w-5"})}),j&&j.totalTokens>0&&c==="chat"&&e.jsx(Vo,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit??0,size:"compact",isMobile:!0})]}),e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center",role:"tablist","aria-label":"Main navigation",children:O.map(R=>{const oe=c===R.id,Ce=R.icon;return e.jsxs(ot,{delayDuration:500,children:[e.jsx(at,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{m&&A(),d(R.id)},"aria-label":R.label,"aria-selected":oe,role:"tab",className:T(C,oe&&"text-foreground"),children:[e.jsx(Ce,{className:"h-5 w-5"}),R.badge!==void 0&&R.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:R.badge})]})}),e.jsx(st,{children:e.jsx("p",{children:R.label})})]},R.id)})}),e.jsxs(ot,{delayDuration:500,children:[e.jsx(at,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:M,"aria-label":"Open settings",className:T(C,"relative"),children:[e.jsx(jn,{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(st,{children:e.jsx("p",{children:h?"Settings (Update available)":"Settings"})})]})]})]}),L=T("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:L,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:m?V():se()})};function Da({className:n,...s}){return e.jsx("div",{"data-slot":"card",className:T("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",n),...s})}function bc({className:n,...s}){return e.jsx("div",{"data-slot":"card-header",className:T("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",n),...s})}function wc({className:n,...s}){return e.jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",n),...s})}function vc({className:n,...s}){return e.jsx("div",{"data-slot":"card-content",className:T("px-6",n),...s})}class ls extends l.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,t){this.setState({error:s,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(Da,{className:"w-full max-w-md",children:[e.jsx(bc,{className:"text-center",children:e.jsxs(wc,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Oo,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(vc,{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(Ee,{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 or=0;function vs({...n}){return e.jsx(ru,{"data-slot":"dialog",...n})}function jc({...n}){return e.jsx(du,{"data-slot":"dialog-trigger",...n})}function uh({...n}){return e.jsx(iu,{"data-slot":"dialog-portal",...n})}const Sc=de.forwardRef(({className:n,...s},t)=>(de.useEffect(()=>(or+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{or=Math.max(0,or-1),or===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Dl,{ref:t,"data-slot":"dialog-overlay",className:T("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",n),...s})));Sc.displayName=Dl.displayName;function js({className:n,children:s,showCloseButton:t=!0,...r}){return e.jsxs(uh,{"data-slot":"dialog-portal",children:[e.jsx(Sc,{className:"rounded-none"}),e.jsxs(ou,{"data-slot":"dialog-content",className:T("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",n),...r,children:[s,t&&e.jsxs(au,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(ds,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Rs({className:n,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:T("flex flex-col gap-2 text-center sm:text-left",n),...s})}function Gn({className:n,...s}){return e.jsx("div",{"data-slot":"dialog-footer",className:T("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",n),...s})}function Ls({className:n,...s}){return e.jsx(lu,{"data-slot":"dialog-title",className:T("typography-markdown leading-none font-semibold text-foreground",n),...s})}function cn({className:n,...s}){return e.jsx(cu,{"data-slot":"dialog-description",className:T("text-muted-foreground typography-ui-label",n),...s})}const ji="https://github.com/btriapitsyn/openchamber/releases";async function mh(){try{const n=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return n.ok?{success:!0}:{success:!1,error:(await n.json().catch(()=>({}))).error||`Server error: ${n.status}`}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to install update"}}}async function fh(n=30,s=2e3){for(let t=0;t<n;t++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(r=>setTimeout(r,s))}return!1}const kc=({open:n,onOpenChange:s,info:t,downloading:r,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[p,m]=de.useState(!1),[f,h]=de.useState("idle"),[g,x]=de.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",N=t?.updateCommand||"openchamber update";de.useEffect(()=>{n||(h("idle"),x(null))},[n]);const w=async()=>{try{await navigator.clipboard.writeText(N),m(!0),setTimeout(()=>m(!1),2e3)}catch{}},S=de.useCallback(async()=>{h("updating"),x(null);const I=await mh();if(!I.success){h("error"),x(I.error||"Update failed");return}h("restarting"),await new Promise(k=>setTimeout(k,2e3)),h("reconnecting"),await fh()?window.location.reload():(h("error"),x("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),j=f!=="idle"&&f!=="error";return e.jsx(vs,{open:n,onOpenChange:j?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(uu,{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&&j&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(hr,{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&&!j&&e.jsx(tt,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((I,A)=>/^\d+\.\d+\.\d+$/.test(I.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",I.trim(),`
|
|
58
|
+
`]},A):I.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(mu,{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:N}),e.jsx("button",{onClick:w,className:T("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(Dt,{className:"h-4 w-4"}):e.jsx(fu,{className:"h-4 w-4"})})]})]}),!v&&r&&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:T("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(_o,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!r&&e.jsxs("button",{onClick:c,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(zn,{className:"h-4 w-4"}),"Download Update"]}),!v&&r&&e.jsxs("button",{disabled:!0,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(hr,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Is,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!j&&e.jsxs("button",{onClick:S,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(zn,{className:"h-4 w-4"}),"Update Now"]}),v&&j&&e.jsxs("button",{disabled:!0,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(hr,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},zr=264,Si=200,ki=500,ph=40,Ni="openchamber:check-for-updates",hh=({isOpen:n,isMobile:s,children:t})=>{const{sidebarWidth:r,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=je(),[c,d]=l.useState(!1),u=l.useRef(0),p=l.useRef(r||zr),[m,f]=l.useState(!1),h=eo(),g=l.useRef(!1),x=h.checkForUpdates,{available:y,downloaded:b,checking:v}=h,[N,w]=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 M=typeof window.opencodeDesktop<"u";w(M)},[]),l.useEffect(()=>{if(typeof window>"u")return;const M=()=>{typeof window.opencodeDesktop<"u"&&(g.current=!0,x())};return window.addEventListener(Ni,M),()=>{window.removeEventListener(Ni,M)}},[x]),l.useEffect(()=>{g.current&&(v||(y||b?f(!0):he.success("No updates available",{description:"You are running the latest version."}),g.current=!1))},[y,b,v]),l.useEffect(()=>{if(s||!c)return;const M=D=>{const P=D.clientX-u.current,W=Math.min(ki,Math.max(Si,p.current+P));o(W)},C=()=>{d(!1)};return window.addEventListener("pointermove",M),window.addEventListener("pointerup",C,{once:!0}),()=>{window.removeEventListener("pointermove",M),window.removeEventListener("pointerup",C)}},[s,c,o]),l.useEffect(()=>{s&&c&&d(!1)},[s,c]);const j=l.useCallback(async M=>{if(M.button===0&&N)try{const{getCurrentWindow:C}=await vn(async()=>{const{getCurrentWindow:P}=await import("./vendor-.pnpm-CFPpXnpS.js").then(W=>W.c3);return{getCurrentWindow:P}},__vite__mapDeps([0,1]));await C().startDragging()}catch(C){console.error("Failed to start window dragging from sidebar:",C)}},[N]);if(s)return null;const I=n?Math.min(ki,Math.max(Si,r||zr)):0,A=N&&S,k=M=>{n&&(d(!0),u.current=M.clientX,p.current=I,M.preventDefault())};return e.jsxs("aside",{className:T("relative flex h-full overflow-hidden border-r",N?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",c?"transition-none":"",!n&&"border-r-0"),style:{width:`${I}px`,minWidth:`${I}px`,maxWidth:`${I}px`,pointerEvents:n?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!n||I===0,children:[n&&e.jsx("div",{className:T("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:k,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:T("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!n&&"pointer-events-none select-none opacity-0"),style:{width:`${I}px`,overflowX:"hidden"},"aria-hidden":!n,children:[A&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${ph}px`},onMouseDown:j,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:t})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:T("flex items-center gap-2 rounded-md px-3 py-2","text-sm font-semibold text-muted-foreground","hover:text-foreground","transition-colors"),children:[e.jsx(jn,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),y||b?e.jsxs("button",{onClick:()=>f(!0),className:T("flex items-center gap-1.5 rounded-md px-2.5 py-1.5","text-xs font-medium","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(zn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!N&&e.jsxs(ot,{children:[e.jsx(at,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:T("flex items-center justify-center rounded-md p-1.5","text-muted-foreground","hover:text-foreground hover:bg-muted/50","transition-colors"),children:e.jsx(Gt,{className:"h-4 w-4"})})}),e.jsx(st,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(kc,{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})]})]})},Nc=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:na},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Yr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:nn},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:El},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Kt},{id:"settings",label:"Appearance",description:"Fine-tune themes, fonts, and typography across the interface.",icon:pu}],gh={},Cc={},Mc={};Nc.forEach(n=>{gh[n.id]=n.label,Cc[n.id]=n.description,Mc[n.id]=n});const Ci=Cc,xh=Mc;function Hr({className:n,variant:s,...t}){return e.jsx(Ee,{variant:s,size:"sm",className:T("h-7 px-2 py-0",n),...t})}function It({className:n,type:s,...t}){return e.jsx("input",{type:s,"data-slot":"input",className:T("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",n),...t})}const yh=()=>{const[n,s]=l.useState(""),[t,r]=l.useState(!1),{selectedAgentName:o,agents:a,setSelectedAgent:i,deleteAgent:c,loadAgents:d}=Dn(),{setSidebarOpen:u}=je(),{isMobile:p}=Nt();l.useEffect(()=>{d()},[d]);const m=()=>{if(!n.trim()){he.error("Agent name is required");return}if(a.some(v=>v.name===n)){he.error("An agent with this name already exists");return}i(n),s(""),r(!1),p&&u(!1)},f=async v=>{if(yr(v)){he.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${v.name}"?`)&&(await c(v.name)?he.success(`Agent "${v.name}" deleted successfully`):he.error("Failed to delete agent"))},h=v=>{const N=v.name;let w=1,S=`${N} Copy`;for(;a.some(j=>j.name===S);)w++,S=`${N} Copy ${w}`;i(S),r(!1),p&&u(!1)},g=v=>{switch(v){case"primary":return e.jsx(Hn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Il,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(Tl,{className:"h-3 w-3 text-primary"});default:return null}},x=a.filter(v=>!ql(v)),y=x.filter(yr),b=x.filter(v=>!yr(v));return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(vs,{open:t,onOpenChange:r,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",p?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Agents"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:x.length}),e.jsx(jc,{asChild:!0,children:e.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(os,{className:"size-4"})})})]})]})}),e.jsx(tt,{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(Mr,{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(cn,{children:"Enter a unique name for your new agent"})]}),e.jsx(It,{value:n,onChange:v=>s(v.target.value),placeholder:"Agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:v=>{v.key==="Enter"&&m()}}),e.jsxs(Gn,{children:[e.jsx(Ee,{variant:"ghost",onClick:()=>r(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Hr,{onClick:m,children:"Create"})]})]})]})})},Mi=({agent:n,isSelected:s,onSelect:t,onDelete:r,onDuplicate:o,getAgentModeIcon:a})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",s?"text-primary":"text-foreground hover:text-primary/80"),children:n.name}),a(n.mode)]}),n.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:n.description})]}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(Ee,{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(Xr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(ht,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(Os,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),!yr(n)&&r&&e.jsxs(ht,{onClick:i=>{i.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})});function hs({className:n,variant:s,...t}){return e.jsx(Ee,{variant:s,size:"sm",className:T("h-6 px-2 text-xs",n),...t})}const sn=de.forwardRef(({className:n,...s},t)=>e.jsx(tt,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:T("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",n),...s}));sn.displayName="Textarea";const bh="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",wh="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",vh=Object.assign({"../assets/provider-logos/gocode.svg":bh,"../assets/provider-logos/kimi-for-coding.svg":wh}),Go=new Map;for(const[n,s]of Object.entries(vh)){const t=n.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&s&&Go.set(t[1].toLowerCase(),s)}function Ac(n){const s=n?.toLowerCase()??null,t=s?Go.has(s):!1,r=s?Go.get(s)??null:null,[o,a]=de.useState(t?"local":"remote");de.useEffect(()=>{a(t?"local":"remote")},[t,s]);const i=de.useCallback(()=>{a(c=>c==="local"&&t?"remote":"none")},[t]);return s?o==="local"&&r?{src:r,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 Ut=({providerId:n,alt:s,className:t,onError:r})=>{const{src:o,onError:a,hasLogo:i}=Ac(n),c=l.useCallback(()=>{a(),r?.()},[a,r]);return!i||!o?null:e.jsx("img",{src:o,alt:s||`${n} logo`,className:T("dark:invert",t),onError:c})},Dc=()=>{const{providers:n}=St(),{favoriteModels:s,recentModels:t}=je(),r=l.useMemo(()=>s.map(({providerID:a,modelID:i})=>{const c=n.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,n]),o=l.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const c=n.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,n,s]);return{favoriteModelsList:r,recentModelsList:o}},Ec=({providerId:n,modelId:s,onChange:t,className:r})=>{const{providers:o,modelsMetadata:a}=St(),i=je(A=>A.isMobile),{toggleFavoriteModel:c,isFavoriteModel:d,addRecentModel:u}=je(),{favoriteModelsList:p,recentModelsList:m}=Dc(),{isMobile:f}=Nt(),h=i||f,[g,x]=l.useState(!1),[y,b]=l.useState(new Set),v=()=>x(!1),N=A=>{b(k=>{const M=new Set(k);return M.has(A)?M.delete(A):M.add(A),M})},w=A=>{const k=A?.name||A?.id||"",M=String(k);return M.length>40?M.substring(0,37)+"...":M},S=(A,k)=>{const M=`${A}/${k}`;return a.get(M)},j=(A,k)=>{t(A,k),u(A,k)},I=()=>h?e.jsx(qt,{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:A,providerID:k,modelID:M})=>{const C=k===n&&M===s,D=S(k,M);return e.jsxs("div",{className:T("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:()=>{j(k,M),v()},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{providerId:k,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:w(A)})]}),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(k,M)},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-${k}-${M}`)})})]}),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:A,providerID:k,modelID:M})=>{const C=k===n&&M===s,D=S(k,M);return e.jsxs("div",{className:T("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:()=>{j(k,M),v()},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{providerId:k,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:w(A)})]}),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(k,M)},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(Bs,{className:"h-4 w-4"})})]},`recent-mobile-${k}-${M}`)})})]}),o.map(A=>{const k=Array.isArray(A.models)?A.models:[];if(k.length===0)return null;const M=A.id===n,C=y.has(A.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:()=>N(A.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{providerId:A.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:A.name}),M&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),C?e.jsx(xt,{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:k.map(D=>{const P=A.id===n&&D.id===s,W=S(A.id,D.id);return e.jsxs("div",{className:T("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:()=>{j(A.id,D.id),v()},children:[e.jsx("span",{className:"font-medium truncate",children:w(D)}),typeof W?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:W.description})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:K=>{K.preventDefault(),K.stopPropagation(),c(A.id,D.id)},className:T("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(A.id,D.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(A.id,D.id)?"Unfavorite":"Favorite",children:d(A.id,D.id)?e.jsx(gs,{className:"h-4 w-4"}):e.jsx(Bs,{className:"h-4 w-4"})}),P&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},D.id)})})]},A.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:()=>{j("",""),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:T("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",r),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[n?e.jsx(Ut,{providerId:n,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:n&&s?`${n}/${s}`:"Select model..."})]}),e.jsx(xt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",r),children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Ut,{providerId:n,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:n&&s?`${n}/${s}`:"Not selected"}),e.jsx(xt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Jt,{className:"max-w-[300px]",children:[p.length>0&&e.jsxs(xn,{children:[e.jsxs(yn,{className:"typography-meta",children:[e.jsx(gs,{className:"h-3 w-3 flex-shrink-0 mr-2 text-yellow-500"}),"Favorites"]}),e.jsx(bn,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(tt,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:p.map(({model:A,providerID:k,modelID:M})=>{const C=S(k,M);return e.jsx(ht,{className:"typography-meta",onSelect:D=>{D.preventDefault(),j(k,M)},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:w(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(k,M)},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-${k}-${M}`)})})})]}),m.length>0&&e.jsxs(xn,{children:[e.jsxs(yn,{className:"typography-meta",children:[e.jsx(Ar,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(bn,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(tt,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:m.map(({model:A,providerID:k,modelID:M})=>{const C=S(k,M);return e.jsx(ht,{className:"typography-meta",onSelect:D=>{D.preventDefault(),j(k,M)},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:w(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(k,M)},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(Bs,{className:"h-3.5 w-3.5"})})]})},`recent-${k}-${M}`)})})})]}),(p.length>0||m.length>0)&&e.jsx(Vn,{}),o.map(A=>{const k=Array.isArray(A.models)?A.models:[];return k.length===0?e.jsxs(ht,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Ut,{providerId:A.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),A.name," (No models)"]},A.id):e.jsxs(xn,{children:[e.jsxs(yn,{className:"typography-meta",children:[e.jsx(Ut,{providerId:A.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),A.name]}),e.jsx(bn,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(tt,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:k.map(M=>{const C=S(A.id,M.id);return e.jsx(ht,{className:"typography-meta",onSelect:D=>{D.preventDefault(),j(A.id,M.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:w(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(A.id,M.id)},className:T("flex h-4 w-4 items-center justify-center hover:text-yellow-600",d(A.id,M.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":d(A.id,M.id)?"Unfavorite":"Favorite",children:d(A.id,M.id)?e.jsx(gs,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})]})},M.id)})})})]},A.id)}),e.jsx(ht,{className:"typography-meta",onSelect:()=>j("",""),children:e.jsx("span",{className:"text-muted-foreground",children:"No model (optional)"})})]})]}),I()]})},jh=()=>{const{tools:n}=an(),[s,t]=l.useState([]),[r,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 n.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}},[n]),{tools:s,isLoading:r,error:a}},Sh=()=>{const{selectedAgentName:n,getAgentByName:s,createAgent:t,updateAgent:r,agents:o}=Dn();St();const{tools:a}=jh(),i=n?s(n):null,c=n&&!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,N]=l.useState(void 0),[w,S]=l.useState(""),[j,I]=l.useState({}),[A,k]=l.useState("allow"),[M,C]=l.useState("allow"),[D,P]=l.useState("ask"),[W,K]=l.useState(!1);l.useEffect(()=>{if(c)u(n||""),m(""),h("subagent"),x(""),b(void 0),N(void 0),S(""),I({}),k("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),N(i.topP),S(i.prompt||""),I(i.tools||{}),i.permission)){const V=i.permission.edit;(V==="allow"||V==="ask"||V==="deny"||V==="full")&&k(V),i.permission.webfetch&&C(i.permission.webfetch),typeof i.permission.bash=="string"&&P(i.permission.bash)}},[i,c,n,o]);const O=async()=>{if(!d.trim()){he.error("Agent name is required");return}K(!0);try{const V=g.trim(),L={name:d.trim(),description:p.trim()||void 0,mode:f,model:V===""?null:V,temperature:y,top_p:v,prompt:w.trim()||void 0,tools:Object.keys(j).length>0?j:void 0,permission:{edit:A,webfetch:M,bash:D}};let R;c?R=await t(L):R=await r(d,L),R?he.success(c?"Agent created successfully":"Agent updated successfully"):he.error(c?"Failed to create agent":"Failed to update agent")}catch(V){console.error("Error saving agent:",V),he.error("An error occurred while saving")}finally{K(!1)}},Z=V=>{I(L=>({...L,[V]:!L[V]}))},se=V=>{const L={};a.forEach(R=>{L[R]=V}),I(L)};return n?e.jsxs(tt,{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(It,{value:d,onChange:V=>u(V.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(sn,{value:p,onChange:V=>m(V.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:T("gap-2",f==="primary"?void 0:"text-foreground"),children:[e.jsx(Hn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(hs,{variant:f==="subagent"?"default":"outline",onClick:()=>h("subagent"),className:T("gap-2",f==="subagent"?void 0:"text-foreground"),children:[e.jsx(Tl,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(hs,{variant:f==="all"?"default":"outline",onClick:()=>h("all"),className:T("gap-2",f==="all"?void 0:"text-foreground"),children:[e.jsx(Il,{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(Ec,{providerId:g?g.split("/")[0]:"",modelId:g?g.split("/")[1]:"",onChange:(V,L)=>{x(V&&L?`${V}/${L}`:"")}})]}),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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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 L=Math.max(0,(y!==void 0?y:.7)-.1);b(parseFloat(L.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(_a,{className:"h-3.5 w-3.5"})}),e.jsx(It,{type:"text",inputMode:"decimal",value:y!==void 0?y:"",onChange:V=>{const L=V.target.value;if(L===""){b(void 0);return}const R=parseFloat(L);!isNaN(R)&&R>=0&&R<=2&&b(R)},onBlur:V=>{const L=V.target.value;if(L!==""){const R=parseFloat(L);if(!isNaN(R)){const oe=Math.max(0,Math.min(2,R));b(parseFloat(oe.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 L=Math.min(2,(y!==void 0?y:.7)+.1);b(parseFloat(L.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(os,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Top P",e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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 L=Math.max(0,(v!==void 0?v:.9)-.1);N(parseFloat(L.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(_a,{className:"h-3.5 w-3.5"})}),e.jsx(It,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:V=>{const L=V.target.value;if(L===""){N(void 0);return}const R=parseFloat(L);!isNaN(R)&&R>=0&&R<=1&&N(R)},onBlur:V=>{const L=V.target.value;if(L!==""){const R=parseFloat(L);if(!isNaN(R)){const oe=Math.max(0,Math.min(1,R));N(parseFloat(oe.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 L=Math.min(1,(v!==void 0?v:.9)+.1);N(parseFloat(L.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(os,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"System Prompt"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Override the default system prompt for this agent"})]}),e.jsx(sn,{value:w,onChange:V=>S(V.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(Ee,{variant:"outline",size:"sm",onClick:()=>se(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>se(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(V=>e.jsx("button",{type:"button",onClick:()=>Z(V),className:T("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",j[V]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:V},V))})]}),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(Ee,{size:"sm",variant:A==="full"?"default":"outline",onClick:()=>k("full"),className:"h-6 px-2 text-xs",children:"Full"}),e.jsx(Ee,{size:"sm",variant:A==="allow"?"default":"outline",onClick:()=>k("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ee,{size:"sm",variant:A==="ask"?"default":"outline",onClick:()=>k("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ee,{size:"sm",variant:A==="deny"?"default":"outline",onClick:()=>k("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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(st,{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(Ee,{size:"sm",variant:D==="allow"?"default":"outline",onClick:()=>P("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ee,{size:"sm",variant:D==="ask"?"default":"outline",onClick:()=>P("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ee,{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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(st,{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(Ee,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>C("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ee,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>C("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ee,{size:"sm",variant:M==="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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(st,{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(Ee,{size:"sm",variant:"default",onClick:O,disabled:W,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ra,{className:"h-3 w-3"}),W?"Saving...":"Save Changes"]})})]})]}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Mr,{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"})]})})},kh=()=>{const[n,s]=l.useState(""),[t,r]=l.useState(!1),{selectedCommandName:o,commands:a,setSelectedCommand:i,deleteCommand:c,loadCommands:d}=En(),{setSidebarOpen:u}=je(),{isMobile:p}=Nt();l.useEffect(()=>{d()},[d]);const m=()=>{if(!n.trim()){he.error("Command name is required");return}const g=n.trim().replace(/\s+/g,"-");if(a.some(x=>x.name===g)){he.error("A command with this name already exists");return}i(g),s(""),r(!1),p&&u(!1)},f=async g=>{window.confirm(`Are you sure you want to delete command "${g.name}"?`)&&(await c(g.name)?he.success(`Command "${g.name}" deleted successfully`):he.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),r(!1),p&&u(!1)};return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(vs,{open:t,onOpenChange:r,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",p?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Commands"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.length}),e.jsx(jc,{asChild:!0,children:e.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(os,{className:"size-4"})})})]})]})}),e.jsx(tt,{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(Nh,{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(cn,{children:"Enter a unique name for your new slash command"})]}),e.jsx(It,{value:n,onChange:g=>s(g.target.value),placeholder:"Command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:g=>{g.key==="Enter"&&m()}}),e.jsxs(Gn,{children:[e.jsx(Ee,{variant:"ghost",onClick:()=>r(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Hr,{onClick:m,children:"Create"})]})]})]})})},Nh=({command:n,isSelected:s,onSelect:t,onDelete:r,onDuplicate:o})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:T("typography-ui-label font-medium truncate flex-1",s?"text-primary":"text-foreground hover:text-primary/80"),children:["/",n.name]})}),n.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:n.description})]}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(Ee,{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(Xr,{className:"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(ht,{onClick:a=>{a.stopPropagation(),o()},children:[e.jsx(Os,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(ht,{onClick:a=>{a.stopPropagation(),r()},className:"text-destructive focus:text-destructive",children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})}),Ch=({agentName:n,onChange:s,className:t})=>{const{loadAgents:r,getVisibleAgents:o}=Dn(),a=o(),i=je(g=>g.isMobile),{isMobile:c}=Nt(),d=i||c,[u,p]=l.useState(!1);l.useEffect(()=>{r()},[r]);const m=()=>p(!1),f=g=>{s(g)},h=()=>d?e.jsx(qt,{open:u,onClose:m,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(g=>{const x=g.name===n;return e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",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:T("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:n||"Select agent..."})]}),e.jsx(xt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",t),children:[e.jsx(Mr,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:n||"Not selected"}),e.jsx(xt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Jt,{className:"max-w-[300px]",children:[a.map(g=>e.jsx(ht,{className:"typography-meta",onSelect:()=>f(g.name),children:e.jsx("span",{className:"font-medium",children:g.name})},g.name)),e.jsx(ht,{className:"typography-meta",onSelect:()=>f(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),h()]})},Mh=()=>{const{selectedCommandName:n,getCommandByName:s,createCommand:t,updateCommand:r,commands:o}=En(),a=n?s(n):null,i=n&&!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),[N,w]=l.useState(!1);l.useEffect(()=>{i?(d(n||""),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,n,o]);const S=async()=>{if(!c.trim()){he.error("Command name is required");return}if(!x.trim()){he.error("Command template is required");return}w(!0);try{const j=m.trim(),I=h.trim(),A=x.trim(),k={name:c.trim(),description:u.trim()||void 0,agent:j===""?null:j,model:I===""?null:I,template:A,subtask:b};let M;i?M=await t(k):M=await r(c,k),M?he.success(i?"Command created successfully":"Command updated successfully"):he.error(i?"Failed to create command":"Failed to update command")}catch(j){console.error("Error saving command:",j),he.error("An error occurred while saving")}finally{w(!1)}};return n?e.jsxs(tt,{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(It,{value:c,onChange:j=>d(j.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(sn,{value:u,onChange:j=>p(j.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(Ch,{agentName:m,onChange:j=>f(j)}),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(Ec,{providerId:h?h.split("/")[0]:"",modelId:h?h.split("/")[1]:"",onChange:(j,I)=>{g(j&&I?`${j}/${I}`:"")}}),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:j=>v(j.target.checked),className:"sr-only"}),e.jsx("div",{className:T("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(Dt,{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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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(sn,{value:x,onChange:j=>y(j.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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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(Ee,{size:"sm",variant:"default",onClick:S,disabled:N,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ra,{className:"h-3 w-3"}),N?"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"})]})})},Tc=({sectionId:n,variant:s})=>{const t=xh[n],r=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(r,{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[n]})]}):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(r,{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[n]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60",children:"Coming soon..."})]})},Ah=()=>e.jsx(tt,{outerClassName:"h-full",className:"px-3 py-2",children:e.jsx(Tc,{sectionId:"providers",variant:"sidebar"})}),Dh=()=>e.jsx(tt,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:e.jsx(Tc,{sectionId:"providers",variant:"page"})}),so=Ft()(Wt(Ss((n,s)=>({selectedProfileId:null,profiles:[],globalIdentity:null,isLoading:!1,setSelectedProfile:t=>{n({selectedProfileId:t})},loadProfiles:async()=>{n({isLoading:!0});const t=s().profiles;try{const r=await Sf();return n({profiles:r,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),n({profiles:t,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const t=await Mf("");if(t&&t.userName&&t.userEmail){const r={id:"global",name:"Global Identity",userName:t.userName,userEmail:t.userEmail,sshKey:t.sshCommand?t.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};n({globalIdentity:r})}else n({globalIdentity:null});return!0}catch(t){return console.error("Failed to load global git identity:",t),n({globalIdentity:null}),!1}},createProfile:async t=>{try{const r={...t,id:t.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:t.color||"keyword",icon:t.icon||"branch"};return await kf(r),await s().loadProfiles(),!0}catch(r){return console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(t,r)=>{try{const o=s().profiles.find(i=>i.id===t);if(!o)throw new Error("Profile not found");const a={...o,...r};return await Nf(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 Cf(t),s().selectedProfileId===t&&n({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return console.error("Failed to delete git identity profile:",r),!1}},getProfileById:t=>{const{profiles:r,globalIdentity:o}=s();return t==="global"?o||void 0:r.find(a=>a.id===t)}}),{name:"git-identities-store",storage:ks(()=>es()),partialize:n=>({selectedProfileId:n.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=so);const Eh={branch:Kt,briefcase:ia,house:aa,graduation:oa,code:ws,heart:Fl},Th={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Ih=()=>{const{selectedProfileId:n,profiles:s,globalIdentity:t,setSelectedProfile:r,deleteProfile:o,loadProfiles:a,loadGlobalIdentity:i}=so(),{setSidebarOpen:c}=je(),{isMobile:d}=Nt();l.useEffect(()=>{a(),i()},[a,i]);const u=()=>{r("new"),d&&c(!1)},p=async m=>{window.confirm(`Are you sure you want to delete profile "${m.name}"?`)&&(await o(m.id)?he.success(`Profile "${m.name}" deleted successfully`):he.error("Failed to delete profile"))};return e.jsxs("div",{className:"flex h-full flex-col bg-sidebar",children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",d?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Git Profiles"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:s.length}),e.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",onClick:u,children:e.jsx(os,{className:"size-4"})})]})]})}),e.jsxs(tt,{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:n==="global",onSelect:()=>{r("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(Kt,{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:n===m.id,onSelect:()=>{r(m.id),d&&c(!1)},onDelete:()=>p(m)},m.id))})]})]})},Ai=({profile:n,isSelected:s,onSelect:t,onDelete:r,isReadOnly:o=!1})=>{const a=Eh[n.icon||"branch"]||Kt,i=Th[n.color||""];return e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a,{className:"w-4 h-4 flex-shrink-0",style:{color:i}}),e.jsx("div",{className:T("typography-ui-label font-medium truncate flex-1",s?"text-primary":"text-foreground hover:text-primary/80"),children:n.name})]}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:n.userEmail})]}),!o&&r&&e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx(Ee,{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(Xr,{className:"h-3.5 w-3.5"})})}),e.jsx(Jt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(ht,{onClick:c=>{c.stopPropagation(),r()},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)"}],Fh=[{key:"branch",Icon:Kt,label:"Branch"},{key:"briefcase",Icon:ia,label:"Work"},{key:"house",Icon:aa,label:"Personal"},{key:"graduation",Icon:oa,label:"School"},{key:"code",Icon:ws,label:"Code"}],Ph=()=>{const{selectedProfileId:n,getProfileById:s,createProfile:t,updateProfile:r,deleteProfile:o}=so(),a=l.useMemo(()=>n&&n!=="new"?s(n):null,[n,s]),i=n==="new",c=n==="global",[d,u]=l.useState(""),[p,m]=l.useState(""),[f,h]=l.useState(""),[g,x]=l.useState(""),[y,b]=l.useState("keyword"),[v,N]=l.useState("branch"),[w,S]=l.useState(!1);l.useEffect(()=>{i?(u(""),m(""),h(""),x(""),b("keyword"),N("branch")):a&&(u(a.name),m(a.userName),h(a.userEmail),x(a.sshKey||""),b(a.color||"keyword"),N(a.icon||"branch"))},[a,i,n]);const j=async()=>{if(!p.trim()||!f.trim()){he.error("User name and email are required");return}S(!0);try{const k={name:d.trim()||p.trim(),userName:p.trim(),userEmail:f.trim(),sshKey:g.trim()||null,color:y,icon:v};let M;if(i)M=await t(k);else if(n)M=await r(n,k);else return;M?he.success(i?"Profile created successfully":"Profile updated successfully"):he.error(i?"Failed to create profile":"Failed to update profile")}catch(k){console.error("Error saving profile:",k),he.error("An error occurred while saving")}finally{S(!1)}},I=async()=>{if(!(!n||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(n)?he.success("Profile deleted successfully"):he.error("Failed to delete profile")}catch(k){console.error("Error deleting profile:",k),he.error("An error occurred while deleting")}},A=l.useMemo(()=>Di.find(M=>M.key===y)?.cssVar||"var(--syntax-keyword)",[y]);return n?e.jsxs(tt,{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(It,{value:d,onChange:k=>u(k.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(k=>e.jsx("button",{onClick:()=>b(k.key),className:T("w-8 h-8 rounded-lg border-2 transition-all",y===k.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:k.cssVar},title:k.label},k.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:Fh.map(k=>{const M=k.Icon;return e.jsx("button",{onClick:()=>N(k.key),className:T("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",v===k.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:k.label,children:e.jsx(M,{className:"w-4 h-4",style:{color:A}})},k.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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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(It,{value:p,onChange:k=>m(k.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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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(It,{type:"email",value:f,onChange:k=>h(k.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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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(It,{value:g,onChange:k=>x(k.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(Ee,{size:"sm",variant:"destructive",onClick:I,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Gs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:T("flex gap-2",i&&"ml-auto"),children:e.jsxs(Ee,{size:"sm",variant:"default",onClick:j,disabled:w,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(ra,{className:"h-3 w-3"}),w?"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(Jr,{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 bo(n,s,t){return Math.min(t,Math.max(s,n))}const Wr=de.forwardRef(({value:n,onValueChange:s,min:t=-1/0,max:r=1/0,step:o=1,className:a,containerClassName:i,onBlur:c,onKeyDown:d,disabled:u,...p},m)=>{const f=de.useRef(null);de.useImperativeHandle(m,()=>f.current);const[h,g]=de.useState(()=>String(n));de.useEffect(()=>{document.activeElement!==f.current&&g(String(n))},[n]);const x=de.useCallback(()=>{f.current?.focus()},[]),y=de.useCallback(M=>{const C=bo(M,t,r);s(C),g(String(C))},[r,t,s]),b=de.useCallback(()=>{const M=Number(h);return Number.isFinite(M)?M:n},[h,n]),v=de.useCallback(()=>{y(b()+o),x()},[y,b,x,o]),N=de.useCallback(()=>{y(b()-o),x()},[y,b,x,o]),w=M=>{const C=M.target.value;g(C);const D=Number(C);Number.isFinite(D)&&s(bo(D,t,r))},S=M=>{const C=Number(h);if(!Number.isFinite(C))g(String(n));else{const D=bo(C,t,r);D!==C&&s(D),g(String(D))}c?.(M)},j=M=>{if(M.key==="ArrowUp"){M.preventDefault(),v();return}if(M.key==="ArrowDown"){M.preventDefault(),N();return}d?.(M)},I=b(),A=u||I<=t,k=u||I>=r;return e.jsxs("div",{className:T("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",i),children:[e.jsx("input",{...p,ref:f,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(r)?r:void 0,step:o,value:h,onChange:w,onBlur:S,onKeyDown:j,disabled:u,className:T("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:k,onClick:v,className:T("flex flex-1 items-center justify-center","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(Yn,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:A,onClick:N,className:T("flex flex-1 items-center justify-center border-t border-border","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(xt,{className:"h-3.5 w-3.5"})})]})]})});Wr.displayName="NumberInput";const Rh=[{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."}],Lh=()=>{const{isMobile:n}=Nt(),s=je(h=>h.showReasoningTraces),t=je(h=>h.setShowReasoningTraces),r=je(h=>h.toolCallExpansion),o=je(h=>h.setToolCallExpansion),a=je(h=>h.fontSize),i=je(h=>h.setFontSize),c=je(h=>h.padding),d=je(h=>h.setPadding),u=je(h=>h.diffLayoutPreference),p=je(h=>h.setDiffLayoutPreference),{themeMode:m,setThemeMode:f}=ln();return e.jsxs("div",{className:"w-full space-y-8",children:[!Qt()&&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:Rh.map(h=>e.jsx(hs,{variant:m===h.value?"default":"outline",className:T(m===h.value?void 0:"text-foreground"),onClick:()=>f(h.value),children:h.label},h.value))})]}),!n&&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(Wr,{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"})}),n?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(Wr,{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===r)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Ei.map(h=>e.jsx(hs,{variant:r===h.value?"default":"outline",className:T(r===h.value?void 0:"text-foreground"),onClick:()=>o(h.value),children:h.label},h.value))})]}),!n&&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:T(u===h.id?void 0:"text-foreground"),onClick:()=>p(h.id),children:h.label},h.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children: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"})]})]})},Oh="https://github.com/btriapitsyn/openchamber",_h=()=>{const[n,s]=l.useState(!1),t=eo(),r=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:r})]}),t.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(hr,{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:T("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(zn,{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:T("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:"Check for updates"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("a",{href:Oh,target:"_blank",rel:"noopener noreferrer",className:T("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Pl,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:T("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Rl,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(kc,{open:n,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})]})},$h=1440*60*1e3,Ic=5,Ii=1440*60*1e3,wo=n=>n.time?.updated??n.time?.created??0,Fi=({sessions:n,currentSessionId:s,cutoffDays:t,keepRecent:r=Ic,now:o=Date.now()})=>{if(!Array.isArray(n)||t<=0)return[];const a=o-t*$h,i=[...n].sort((d,u)=>wo(u)-wo(d)),c=new Set(i.slice(0,r).map(d=>d.id));return i.filter(d=>{if(!d?.id||c.has(d.id)||d.id===s||d.share)return!1;const u=wo(d);return u?u<a:!1}).map(d=>d.id)},Fc=n=>{const s=n?.autoRun!==!1,t=fe(x=>x.sessions),r=fe(x=>x.currentSessionId),o=fe(x=>x.isLoading),a=fe(x=>x.deleteSessions),i=je(x=>x.autoDeleteEnabled),c=je(x=>x.autoDeleteAfterDays),d=je(x=>x.autoDeleteLastRunAt),u=je(x=>x.setAutoDeleteLastRunAt),[p,m]=l.useState(!1),f=l.useRef(!1),h=l.useMemo(()=>c<=0?[]:Fi({sessions:t,currentSessionId:r,cutoffDays:c}),[c,r,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:r,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,r,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:Ic}},vo=1,jo=365,Bh=()=>{const{isMobile:n}=Nt(),s=je(f=>f.autoDeleteEnabled),t=je(f=>f.autoDeleteAfterDays),r=je(f=>f.setAutoDeleteEnabled),o=je(f=>f.setAutoDeleteAfterDays),[a,i]=l.useState(String(t));l.useEffect(()=>{i(String(t))},[t]);const{candidates:c,isRunning:d,runCleanup:u}=Fc({autoRun:!1}),p=c.length,m=l.useCallback(async()=>{const f=await u({force:!0});if(f.deletedIds.length===0&&f.failedIds.length===0){he.message("No sessions eligible for deletion");return}f.deletedIds.length>0&&he.success(`Deleted ${f.deletedIds.length} session${f.deletedIds.length===1?"":"s"}`),f.failedIds.length>0&&he.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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(st,{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=>r(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:[n?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(jo,Math.max(vo,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(jo,Math.max(vo,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(Wr,{value:t,onValueChange:o,min:vo,max:jo,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]})]})},Pc=()=>{const{isMobile:n}=Nt(),s=n&&Wl();return e.jsxs(tt,{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(Lh,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Bh,{})}),s&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(_h,{})})]})},Pi=(()=>{const n=Nc.filter(r=>r.id!=="sessions"),s=n.find(r=>r.id==="settings"),t=n.filter(r=>r.id!=="settings");return s?[s,...t]:n})(),zh=({isOpen:n,onClose:s})=>{const[t,r]=l.useState("settings"),[o,a]=l.useState(!1),{isMobile:i}=Nt();l.useEffect(()=>{n&&(r("settings"),a(!1))},[n]);const c=l.useCallback(y=>{r(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(yh,{});case"commands":return e.jsx(kh,{});case"providers":return e.jsx(Ah,{});case"git-identities":return e.jsx(Ih,{});default:return null}})();return i?e.jsx("div",{onClick:d,children:y}):y},p=()=>{switch(t){case"agents":return e.jsx(Sh,{});case"commands":return e.jsx(Mh,{});case"providers":return e.jsx(Dh,{});case"git-identities":return e.jsx(Ph,{});case"settings":return e.jsx(Pc,{});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(Ee,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx($a,{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(cn,{className:"typography-meta text-muted-foreground hidden sm:block",children:m.description})]}),g=e.jsxs("div",{className:T("flex flex-col min-h-0",i?"h-full overflow-hidden":"flex-1 overflow-hidden"),children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1 border-b border-border/40 bg-background/95 px-3 py-1.5",children:Pi.map(({id:y,label:b,icon:v})=>{const N=t===y,w=v;return e.jsxs("button",{onClick:()=>c(y),className:T("flex items-center gap-1 rounded-md px-2.5 py-1.5 text-xs font-medium whitespace-nowrap","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",N?"text-primary":"text-muted-foreground hover:text-foreground"),"aria-pressed":N,"aria-label":b,children:[e.jsx(w,{className:T("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:T("overflow-hidden border-r bg-sidebar",i&&"w-full border-r-0"),style:i?void 0:{width:`${zr}px`,minWidth:`${zr}px`},children:e.jsx(ls,{children:u()})}),(t==="settings"||!i||o)&&e.jsx("div",{className:T("flex-1 overflow-hidden bg-background",i&&"w-full"),children:e.jsx(ls,{children:p()})})]})]}),x=e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[!f&&h,g]});return f?e.jsx(qt,{open:n,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(Ee,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx($a,{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:n,onOpenChange:y=>!y&&s(),children:e.jsx(js,{className:T("flex flex-col gap-0 p-0","h-[88vh] w-[65vw] max-w-[900px]"),children:x})})};function Rc({className:n,...s}){return e.jsx(rn,{"data-slot":"command",className:T("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",n),...s})}function Hh({title:n="Command Palette",description:s="Search for a command to run...",children:t,className:r,showCloseButton:o=!0,...a}){return e.jsxs(vs,{...a,children:[e.jsxs(Rs,{className:"sr-only",children:[e.jsx(Ls,{children:n}),e.jsx(cn,{children:s})]}),e.jsx(js,{className:T("overflow-hidden p-0 transform-gpu will-change-transform",r),showCloseButton:o,children:e.jsx(Rc,{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 Lc({className:n,...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(la,{className:"size-4 shrink-0 opacity-50"}),e.jsx(rn.Input,{"data-slot":"command-input",className:T("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",n),...s})]})}function Oc({className:n,children:s,scrollbarClassName:t,disableHorizontal:r,...o}){return e.jsx(tt,{as:rn.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:T("scroll-py-1 overflow-x-hidden h-full min-h-0",n),scrollbarClassName:t??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:r??!0,...o,children:s})}function _c({...n}){return e.jsx(rn.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...n})}function wn({className:n,...s}){return e.jsx(rn.Group,{"data-slot":"command-group",className:T("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",n),...s})}function Ur({className:n,...s}){return e.jsx(rn.Separator,{"data-slot":"command-separator",className:T("bg-border -mx-1 h-px",n),...s})}function Tt({className:n,...s}){return e.jsx(rn.Item,{"data-slot":"command-item",className:T("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",n),...s})}function _s({className:n,...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(nn,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(Xn,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},r=typeof s.children=="string"?s.children:"",o=r?r.split("+").map(a=>a.trim()).filter(Boolean):[];return e.jsx("span",{"data-slot":"command-shortcut",className:T("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",n),...s,children:o.length>0?o.map((a,i)=>e.jsxs(de.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):s.children})}const Wh=()=>{const{isCommandPaletteOpen:n,setCommandPaletteOpen:s,setHelpDialogOpen:t,setSessionCreateDialogOpen:r,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,toggleSidebar:c}=je(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:p}=fe(),{currentDirectory:m}=bt(),{themeMode:f,setThemeMode:h}=ln(),g=()=>{s(!1)},x=async()=>{o("chat"),i(!1),d(),g()},y=P=>{u(P),g()},b=P=>{h(P),g()},v=()=>{t(!0),g()},N=()=>{r(!0),g()},{isMobile:w}=Nt(),S=()=>{if(w){const{isSessionSwitcherOpen:P}=je.getState();i(!P)}else c();g()},j=()=>{o("diff"),g()},I=()=>{o("git"),g()},A=()=>{o("terminal"),g()},k=()=>{a(!0),g()},M=()=>{rf(),g()},C=p(m??""),D=l.useMemo(()=>C.slice(0,5),[C]);return e.jsxs(Hh,{open:n,onOpenChange:s,children:[e.jsx(Lc,{placeholder:"Type a command or search..."}),e.jsxs(Oc,{children:[e.jsx(_c,{children:"No results found."}),e.jsxs(wn,{heading:"Actions",children:[e.jsxs(Tt,{onSelect:S,children:[e.jsx(Kr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsx(_s,{children:"Ctrl + L"})]}),e.jsxs(Tt,{onSelect:x,children:[e.jsx(os,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(_s,{children:"Ctrl + N"})]}),e.jsxs(Tt,{onSelect:N,children:[e.jsx(Kt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(_s,{children:"Shift + Ctrl + N"})]}),e.jsxs(Tt,{onSelect:v,children:[e.jsx(Sn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsx(_s,{children:"Ctrl + H"})]}),e.jsxs(Tt,{onSelect:j,children:[e.jsx(ws,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsx(_s,{children:"Ctrl + E"})]}),e.jsxs(Tt,{onSelect:I,children:[e.jsx(Kt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsx(_s,{children:"Ctrl + G"})]}),e.jsxs(Tt,{onSelect:A,children:[e.jsx(Vs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsx(_s,{children:"Ctrl + T"})]}),e.jsxs(Tt,{onSelect:k,children:[e.jsx(jn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsx(_s,{children:"Ctrl + ,"})]}),e.jsxs(Tt,{onSelect:M,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Ur,{}),e.jsxs(wn,{heading:"Theme",children:[e.jsxs(Tt,{onSelect:()=>b("light"),children:[e.jsx(hu,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),f==="light"&&e.jsx(Dt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(Tt,{onSelect:()=>b("dark"),children:[e.jsx(gu,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),f==="dark"&&e.jsx(Dt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(Tt,{onSelect:()=>b("system"),children:[e.jsx(Ll,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),f==="system"&&e.jsx(Dt,{className:"ml-auto h-4 w-4"})]})]}),D.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ur,{}),e.jsx(wn,{heading:"Recent Sessions",children:D.map(P=>e.jsxs(Tt,{onSelect:()=>y(P.id),children:[e.jsx(na,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})]},P.id))})]})]})]})},Uh=(n,s)=>{const t=n.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Yn,{className:"h-3.5 w-3.5"},`ctrl-${s}`):t==="shift"||t==="⇧"?e.jsx(yu,{className:"h-3.5 w-3.5"},`shift-${s}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(nn,{className:"h-3.5 w-3.5"},`cmd-${s}`):e.jsx("span",{className:"text-xs font-medium",children:n.trim()},`key-${s}`)},Vh=n=>{const s=n.split("+").map(t=>t.trim()).filter(Boolean);return s.length===0?n.trim():s.map((t,r)=>e.jsxs(l.Fragment,{children:[r>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),Uh(t,r)]},`${t}-${r}`))},Gh=()=>{const{isHelpDialogOpen:n,setHelpDialogOpen:s}=je(),t=[{category:"Navigation & Commands",items:[{keys:["Ctrl + X"],description:"Open Command Palette",icon:nn},{keys:["Ctrl + H"],description:"Show Keyboard Shortcuts (this dialog)",icon:Sn},{keys:["Ctrl + L"],description:"Toggle Session Sidebar",icon:Kr}]},{category:"Session Management",items:[{keys:["Ctrl + N"],description:"Create New Session",icon:os},{keys:["Shift + Ctrl + N"],description:"Open Worktree Creator",icon:Kt},{keys:["Ctrl + I"],description:"Focus Chat Input",icon:Ol},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:kn}]},{category:"Interface",items:[{keys:["⌘ + /","Ctrl + /"],description:"Cycle Theme (Light → Dark → System)",icon:xu},{keys:["Ctrl + E"],description:"Open Diff Panel",icon:ws},{keys:["Ctrl + G"],description:"Open Git Panel",icon:Kt},{keys:["Ctrl + T"],description:"Open Terminal",icon:Vs},{keys:["Ctrl + ,"],description:"Open Settings",icon:jn}]}];return e.jsx(vs,{open:n,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(jn,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(cn,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsx("div",{className:"space-y-4 mt-3",children:t.map(r=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:r.category}),e.jsx("div",{className:"space-y-1",children:r.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:Vh(i)})]},`${i}-${c}`))})]},a))})]},r.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(Sn,{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"})]})]})]})})]})})},So=new Set,ko=new Set,No=new Set,Qs={onDeleteRequest(n){return So.add(n),()=>{So.delete(n)}},requestDelete(n){n.sessions.length&&So.forEach(s=>s(n))},onCreateRequest(n){return ko.add(n),()=>{ko.delete(n)}},requestCreate(n){const s=n??{};ko.forEach(t=>t(s))},onDirectoryRequest(n){return No.add(n),()=>{No.delete(n)}},requestDirectoryDialog(){No.forEach(n=>n())}},qh=".openchamber",Ri="oc.sessions.groupCollapse",Li="oc.sessions.expandedParents",Oi=n=>{const s=new Date(n),t=new Date,r=(i,c)=>i.getFullYear()===c.getFullYear()&&i.getMonth()===c.getMonth()&&i.getDate()===c.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),r(s,t)?"Today":r(s,o)?"Yesterday":s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},Ms=n=>{if(!n)return null;const s=n.replace(/\\/g,"/").replace(/\/+$/,"");return s.length===0?"/":s},Kh=(n,s)=>{const t=Ms(n),r=Array.from(s.values())[0];if(r?.projectDirectory)return Ms(r.projectDirectory);if(!t)return null;const o=`/${qh}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},qo=({mobileVariant:n=!1,onSessionSelected:s,allowReselect:t=!1,hideDirectoryControls:r=!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(()=>es(),[]),[b,v]=l.useState(new Set),[N,w]=l.useState(null),[S,j]=l.useState(new Set),[I,A]=l.useState(null),k=bt(z=>z.currentDirectory),M=bt(z=>z.homeDirectory),C=bt(z=>z.setDirectory),D=je(z=>z.setActiveMainTab),P=je(z=>z.setSessionSwitcherOpen),W=fe(z=>z.getSessionsByDirectory),K=fe(z=>z.currentSessionId),O=fe(z=>z.setCurrentSession),Z=fe(z=>z.updateSessionTitle),se=fe(z=>z.shareSession),V=fe(z=>z.unshareSession),L=fe(z=>z.sessionMemoryState),R=fe(z=>z.sessionActivityPhase),oe=fe(z=>z.worktreeMetadata),Ce=fe(z=>z.availableWorktrees),Ae=fe(z=>z.openNewSessionDraft),[ue,me]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const z=y.getItem(Ri);if(z){const U=JSON.parse(z);Array.isArray(U)&&v(new Set(U.filter(ie=>typeof ie=="string")))}const ge=y.getItem(Li);if(ge){const U=JSON.parse(ge);Array.isArray(U)&&f(new Set(U.filter(ie=>typeof ie=="string")))}}catch{}},[y]),l.useEffect(()=>{typeof window>"u"||me(typeof window.opencodeDesktop<"u")},[]);const ke=W(k),De=l.useMemo(()=>[...ke].sort((z,ge)=>(ge.time?.created||0)-(z.time?.created||0)),[ke]);l.useEffect(()=>{if(!k){w(null);return}let z=!1;return ga(k).then(ge=>{z||w(ge)}).catch(()=>{z||w(null)}),()=>{z=!0}},[k]);const _e=l.useMemo(()=>new Map(De.map(z=>[z.id,z])),[De]),Ne=l.useMemo(()=>{const z=new Map;return De.forEach(ge=>{const U=ge.parentID;U&&z.set(ge.id,U)}),z},[De]),Pe=l.useMemo(()=>{const z=new Map;return De.forEach(ge=>{const U=ge.parentID;if(!U)return;const ie=z.get(U)??[];ie.push(ge),z.set(U,ie)}),z.forEach(ge=>ge.sort((U,ie)=>(ie.time?.created||0)-(U.time?.created||0))),z},[De]);l.useEffect(()=>{K&&f(z=>{const ge=new Set(z);let U=Ne.get(K)||null,ie=!1;for(;U;)ge.has(U)||(ge.add(U),ie=!0),U=Ne.get(U)||null;return ie?ge:z})},[K,Ne]);const le=l.useMemo(()=>Kh(k,oe),[k,oe]);l.useEffect(()=>{const z=new Set;De.forEach(ge=>{const U=Ms(ge.directory??null);U&&z.add(U)}),le&&z.add(le),z.forEach(ge=>{const U=h.get(ge);U&&U!=="unknown"||x.current.has(ge)||(x.current.add(ge),Me.listLocalDirectory(ge).then(()=>{g(ie=>{const Se=new Map(ie);return Se.get(ge)==="exists"?ie:(Se.set(ge,"exists"),Se)})}).catch(()=>{g(ie=>{const Se=new Map(ie);return Se.get(ge)==="missing"?ie:(Se.set(ge,"missing"),Se)})}).finally(()=>{x.current.delete(ge)}))})},[De,le,h]),l.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const Le=l.useMemo(()=>oo(k,M),[k,M]),ae=l.useMemo(()=>ss(k,M),[k,M]),Ie=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."})]}),Ge=l.useCallback((z,ge)=>{if(!ge){if(n&&(D("chat"),P(!1)),!t&&z===K){s?.(z);return}O(z),s?.(z)}},[t,K,n,s,D,O,P]),te=l.useCallback(async()=>{o&&i.trim()&&(await Z(o,i.trim()),a(null),c(""))},[o,i,Z]),E=l.useCallback(()=>{a(null),c("")},[]),ne=l.useCallback(async z=>{const ge=await se(z.id);ge&&ge.share?.url?he.success("Session shared",{description:"You can copy the link from the menu."}):he.error("Unable to share session")},[se]),G=l.useCallback((z,ge)=>{navigator.clipboard.writeText(z).then(()=>{u(ge),p.current&&clearTimeout(p.current),p.current=window.setTimeout(()=>{u(null),p.current=null},2e3)}).catch(()=>{he.error("Failed to copy URL")})},[]),F=l.useCallback(async z=>{await V(z)?he.success("Session unshared"):he.error("Unable to unshare session")},[V]),_=l.useCallback(z=>{const ge=[],U=ie=>{(Pe.get(ie)??[]).forEach(we=>{ge.push(we),U(we.id)})};return U(z),ge},[Pe]),B=fe(z=>z.deleteSession),$=fe(z=>z.deleteSessions),Q=l.useCallback(async z=>{const ge=_(z.id);if(ge.length===0)await B(z.id)?he.success("Session deleted"):he.error("Failed to delete session");else{const U=[z.id,...ge.map(we=>we.id)],{deletedIds:ie,failedIds:Se}=await $(U);ie.length>0&&he.success(`Deleted ${ie.length} session${ie.length===1?"":"s"}`),Se.length>0&&he.error(`Failed to delete ${Se.length} session${Se.length===1?"":"s"}`)}},[_,B,$]),X=l.useCallback(z=>{D("chat"),n&&P(!1),Ae({directoryOverride:z??null})},[Ae,D,P,n]),Te=l.useCallback(()=>{Qs.requestCreate({worktreeMode:"create"})},[]),We=l.useCallback(()=>{ue&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(z=>{z.success&&z.path?C(z.path,{showOverlay:!0}):z.error&&z.error!=="Directory selection cancelled"&&he.error("Failed to select directory",{description:z.error})}).catch(z=>{console.error("Desktop: Error selecting directory:",z),he.error("Failed to select directory")}):Qs.requestDirectoryDialog()},[ue,C]),it=l.useCallback(z=>{f(ge=>{const U=new Set(ge);U.has(z)?U.delete(z):U.add(z);try{y.setItem(Li,JSON.stringify(Array.from(U)))}catch{}return U})},[y]),nt=l.useCallback(z=>{const ge=Pe.get(z.id)??[];return{session:z,children:ge.map(U=>nt(U))}},[Pe]),Ze=l.useMemo(()=>{const z=new Map,ge=Ms(le??null),U=new Map,ie=new Set;Ce.forEach(ve=>{if(ve.path){const ee=Ms(ve.path)??ve.path;ie.add(ee),U.set(ee,ve)}});const Se=ve=>{const ee=Ms(ve.directory??null),re=oe.get(ve.id),Oe=((re?.path?ie.has(Ms(re.path)??re.path):!1)?re:null)??(ee?U.get(ee)??null:null),qe=!Oe&&(ee&&ge?ee===ge:!ee&&!!ge),ft=qe?"main":Oe?.path??ee??ve.id,Ct=Oe?.path??ee??ge??null;if(!z.has(ft)){const Et=qe?"Main workspace":Oe?.label||Oe?.branch||oo(Ct||"",M)||"Worktree",Pt=Oe?.relativePath?ss(Oe.relativePath,M):Ct?ss(Ct,M):null;z.set(ft,{id:ft,label:Et,description:Pt,isMain:qe,worktree:Oe,directory:Ct,sessions:[]})}return z.get(ft)};return De.filter(ve=>{const ee=ve.parentID;return ee?!_e.has(ee):!0}).forEach(ve=>{const ee=Se(ve),re=nt(ve);ee.sessions.push(re)}),z.has("main")||z.set("main",{id:"main",label:"Main workspace",description:ge?ss(ge,M):null,isMain:!0,worktree:null,directory:ge,sessions:[]}),U.forEach((ve,ee)=>{const re=ve.path;z.has(re)||z.set(re,{id:re,label:ve.label||ve.branch||oo(ee,M)||"Worktree",description:ve.relativePath?ss(ve.relativePath,M):ss(ee,M),isMain:!1,worktree:ve,directory:ee,sessions:[]})}),z.forEach(ve=>{ve.sessions.sort((ee,re)=>(re.session.time?.created||0)-(ee.session.time?.created||0))}),Array.from(z.values()).sort((ve,ee)=>ve.isMain!==ee.isMain?ve.isMain?-1:1:(ve.label||"").localeCompare(ee.label||""))},[De,oe,Ce,le,M,nt,_e]),lt=l.useCallback(z=>{v(ge=>{const U=new Set(ge);U.has(z)?U.delete(z):U.add(z);try{y.setItem(Ri,JSON.stringify(Array.from(U)))}catch{}return U})},[y]),mt=l.useCallback(z=>{j(ge=>{const U=new Set(ge);return U.has(z)?U.delete(z):U.add(z),U})},[]),dt=l.useCallback((z,ge=0,U)=>{const ie=z.session,Se=Ms(ie.directory??null)??Ms(U??null),ve=(Se?h.get(Se):null)==="missing",ee=L.get(ie.id),re=K===ie.id,ye=ie.title||"Untitled Session",Oe=z.children.length>0,qe=m.has(ie.id),ft=ie.summary?.additions,Ct=ie.summary?.deletions,Et=typeof ft=="number"||typeof Ct=="number";if(o===ie.id)return e.jsx("div",{className:T("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",ge>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:be=>{be.preventDefault(),te()},children:[e.jsx("input",{value:i,onChange:be=>c(be.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:be=>{be.key==="Escape"&&E()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Dt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:E,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(ds,{className:"size-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Oe?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:qe?e.jsx(xt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Oi(ie.time?.created||Date.now())}),ie.share?e.jsx(no,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Et&&((ft??0)!==0||(Ct??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,ft??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ct??0)]})]}):null,Oe?e.jsxs("span",{className:"truncate",children:[z.children.length," ",z.children.length===1?"task":"tasks"]}):null]})]})},ie.id);const Pt=R?.get(ie.id)??"idle",Mt=Pt==="busy"||Pt==="cooldown",yt=ee&&ee.isZombie?e.jsx(Oo,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(l.Fragment,{children:[e.jsx("div",{className:T("group relative flex items-center rounded-md px-1.5 py-1",re?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",ve?"opacity-75":"",ge>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:ve,onClick:()=>Ge(ie.id,ve),className:T("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground"),children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:e.jsx("span",{className:T("truncate typography-ui-label font-normal text-foreground",Mt&&"animate-pulse [animation-duration:1.8s]"),children:ye})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Oe?e.jsx("span",{role:"button",tabIndex:0,onClick:be=>{be.stopPropagation(),it(ie.id)},onKeyDown:be=>{(be.key==="Enter"||be.key===" ")&&(be.preventDefault(),be.stopPropagation(),it(ie.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":qe?"Collapse subsessions":"Expand subsessions",children:qe?e.jsx(xt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Oi(ie.time?.created||Date.now())}),ie.share?e.jsx(no,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Et&&((ft??0)!==0||(Ct??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,ft??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Ct??0)]})]}):null,Oe?e.jsxs("span",{className:"truncate",children:[z.children.length," ",z.children.length===1?"task":"tasks"]}):null,ve?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Oo,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[yt,e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx("button",{type:"button",className:T("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",n?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:be=>be.stopPropagation(),onKeyDown:be=>be.stopPropagation(),children:e.jsx(Xr,{className:n?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Jt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(ht,{onClick:()=>{a(ie.id),c(ye)},className:"[&>svg]:mr-1",children:[e.jsx(Ds,{className:"mr-1 h-4 w-4"}),"Rename"]}),ie.share?e.jsxs(e.Fragment,{children:[e.jsx(ht,{onClick:()=>{ie.share?.url&&G(ie.share.url,ie.id)},className:"[&>svg]:mr-1",children:d===ie.id?e.jsxs(e.Fragment,{children:[e.jsx(Dt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Os,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(ht,{onClick:()=>F(ie.id),className:"[&>svg]:mr-1",children:[e.jsx(bu,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(ht,{onClick:()=>ne(ie),className:"[&>svg]:mr-1",children:[e.jsx(no,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(ht,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Q(ie),children:[e.jsx(Gs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Oe&&qe?z.children.map(be=>dt(be,ge+1,Se??U)):null]},ie.id)},[h,L,R,K,m,o,i,te,E,it,Ge,ne,G,F,Q,d,n]);return e.jsxs("div",{className:T("flex h-full flex-col text-foreground overflow-x-hidden",n?"":ue?"bg-transparent":"bg-sidebar"),children:[!r&&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:We,className:T("group flex min-w-0 flex-1 items-center gap-2 rounded-md px-0 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!ue&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:ae||"/",children:[e.jsx("span",{className:T("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!ue&&"bg-sidebar/60"),children:e.jsx(ts,{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:Le||"/"})})]}),N?e.jsx("button",{type:"button",onClick:Te,className:T("inline-flex h-10 w-7 flex-shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!ue&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",children:e.jsx(wu,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}):null]})}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:T("space-y-1 pb-1 pl-2.5 pr-1",""),children:Ze.length===0?Ie:r&&Ze.length===1&&Ze[0].isMain?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const z=Ze[0],ge=r?10:7,U=z.sessions.length,ie=S.has(z.id),Se=ie?z.sessions:z.sessions.slice(0,ge),we=U-Se.length;return U===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."}):e.jsxs(e.Fragment,{children:[Se.map(ve=>dt(ve,0,z.directory)),we>0&&!ie?e.jsxs("button",{type:"button",onClick:()=>mt(z.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 ",we," more ",we===1?"session":"sessions"]}):null,ie&&U>ge?e.jsx("button",{type:"button",onClick:()=>mt(z.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]})})()}):Ze.map(z=>e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>lt(z.id),className:T("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b",!ue&&"bg-sidebar"),style:{borderColor:I===z.id?"var(--color-border)":b.has(z.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>A(z.id),onMouseLeave:()=>A(null),"aria-label":b.has(z.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:z.label}),!r&&e.jsx("span",{role:"button",tabIndex:0,className:T("inline-flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground"),"aria-label":"Create session in this group",onClick:ge=>{ge.stopPropagation(),X(z.directory)},onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&(ge.stopPropagation(),X(z.directory))},children:e.jsx(os,{className:"h-4.5 w-4.5"})})]})}),b.has(z.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const ge=S.has(z.id),U=r?10:7,ie=z.sessions.length,Se=ge?z.sessions:z.sessions.slice(0,U),we=ie-Se.length;return e.jsxs(e.Fragment,{children:[Se.map(ve=>dt(ve,0,z.directory)),ie===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,we>0&&!ge?e.jsxs("button",{type:"button",onClick:()=>mt(z.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 ",we," more ",we===1?"session":"sessions"]}):null,ge&&ie>U?e.jsx("button",{type:"button",onClick:()=>mt(z.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]})})()})]},z.id))})]})},$c=()=>{const[n,s]=de.useState(!1);de.useEffect(()=>{s(as())},[]);const t=de.useCallback(async a=>n?await Om(a):{success:!0,path:a},[n]),r=de.useCallback(async a=>n?await _m(a):{success:!0},[n]),o=de.useCallback(async a=>n?await $m(a):{success:!0},[n]);return{isDesktop:n,requestAccess:t,startAccessing:r,stopAccessing:o}},_i=({currentPath:n,onSelectPath:s,triggerClassName:t,variant:r="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:p=!1})=>{const m=l.useMemo(()=>as(),[]),[f,h]=l.useState([]),[g,x]=l.useState(new Set),[y,b]=l.useState(!0),[v,N]=l.useState(!1),[w,S]=l.useState(""),[j,I]=l.useState(new Set),[A,k]=l.useState(null),[M,C]=l.useState(""),[D,P]=l.useState(!0),W=l.useRef(null),{requestAccess:K,startAccessing:O,isDesktop:Z}=$c(),se=l.useRef(c),V=l.useCallback(E=>{if(!E)return E;if(E==="/"||E.length===0)return"/";let ne=E;for(;ne.length>1&&ne.endsWith("/");)ne=ne.slice(0,-1);return ne.length===0?"/":ne},[]),L=l.useMemo(()=>{if(!w)return null;const E=w.replace(/\\/g,"/");return V(E)},[w,V]),R=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const E=d.replace(/\\/g,"/"),ne=V(E);if(ne&&ne!=="/")return ne}return L&&L!=="/"?L:null},[d,L,V]),oe=l.useMemo(()=>typeof u=="boolean"?!!(u&&R):!!R,[u,R]);l.useEffect(()=>{oe||(b(!0),h([]))},[oe]);const Ce=l.useCallback(E=>{if(!E||!oe||!R)return!1;const ne=E.replace(/\\/g,"/"),G=V(ne)??ne;if(G===R)return!0;const F=`${R}/`;return G.startsWith(F)},[oe,R,V]),Ae=async E=>{if(oe){if(a==="deferred"){s(E);return}if(Z){const ne=await K(E);ne.success&&ne.path?(await O(ne.path),s(ne.path)):(console.error("Failed to get directory access:",ne.error),s(E))}else s(E)}};l.useEffect(()=>{let E=!1;const ne=_=>{if(!_)return!1;const B=V(_.replace(/\\/g,"/"));return!B||B==="/"?!1:(S(typeof B=="string"?B:_.replace(/\\/g,"/")),!0)};return(d?ne(d):!1)||(async()=>{try{const _=await Me.getFilesystemHome();if(!E&&ne(_))return}catch(_){console.warn("Failed to resolve filesystem home directory:",_)}try{const _=await Me.getSystemInfo();if(!E&&ne(_?.homeDirectory))return}catch(_){console.warn("Failed to resolve home directory from system info:",_)}})(),()=>{E=!0}},[d,V]),l.useEffect(()=>{let E=!1;const ne=B=>{if(E)return;const $=B.filter(Q=>typeof Q=="string"&&Q.length>0).map(Q=>{const X=Q.replace(/\\/g,"/");return V(X)??X});I(new Set($))},G=()=>{try{const B=localStorage.getItem("pinnedDirectories");if(!B)return;const $=JSON.parse(B);Array.isArray($)&&ne($)}catch(B){console.warn("Failed to load pinned directories from local storage:",B)}},F=async()=>{try{let B=[];if(m){const $=await Gl();B=Array.isArray($?.pinnedDirectories)?$.pinnedDirectories:[]}else{const $=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if($.ok){const Q=await $.json();B=Array.isArray(Q?.pinnedDirectories)?Q.pinnedDirectories:[]}}if(E)return;ne(B)}catch(B){console.warn("Failed to load pinned directories:",B)}};G();const _=B=>{const $=B.detail;$&&Array.isArray($.pinnedDirectories)&&ne($.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",_),F(),()=>{E=!0,window.removeEventListener("openchamber:settings-synced",_)}},[m,V]);const ue=l.useRef(!0);l.useEffect(()=>{if(ue.current){ue.current=!1;return}const E={pinnedDirectories:Array.from(j)};As(E)},[j]),l.useEffect(()=>{R&&I(E=>{const ne=Array.from(E).map(G=>V(G.replace(/\\/g,"/"))??G).filter(G=>Ce(G));return new Set(ne)})},[R,Ce,V]),l.useEffect(()=>{se.current!==c&&(se.current=c,x(new Set))},[c]);const me=E=>{I(ne=>{if(!Ce(E))return ne;const G=V(E.replace(/\\/g,"/"))??E.replace(/\\/g,"/"),F=new Set(ne);return F.has(G)?F.delete(G):F.add(G),F})},ke=l.useMemo(()=>Array.from(j).map(E=>V(E.replace(/\\/g,"/"))??E).filter(E=>Ce(E)).map(E=>({path:E,name:E.split("/").pop()||E})).sort((E,ne)=>E.name.localeCompare(ne.name)),[j,Ce,V]),De=l.useCallback(async E=>{const ne=$=>c||!$.startsWith("."),G=R;if(!oe||!G)return[];const F=E&&E.length>0?E:G,_=F?F.replace(/\\/g,"/"):null,B=_?V(_)??_:null;if(B){const $=`${G}/`;if(!(B===G||B.startsWith($)))return[]}try{return(await Me.listLocalDirectory(E)).filter(Q=>{if(!Q.isDirectory||!ne(Q.name))return!1;const X=Q.path.replace(/\\/g,"/"),Te=V(X)??X,We=Te===G?G:`${G}/`;return Te===G||Te.startsWith(We)}).map(Q=>({name:Q.name,path:Q.path.replace(/\\/g,"/"),isDirectory:!0})).sort((Q,X)=>Q.name.localeCompare(X.name))}catch{try{const Q=await Me.getApiClient().file.list({query:{path:".",directory:E}});return Q.data?Q.data.filter(X=>{if(X.type!=="directory"||!X.name||!ne(X.name))return!1;const Te=String(X.absolute||X.path||X.name).replace(/\\/g,"/"),We=V(Te)??Te,it=We===G?G:`${G}/`;return We===G||We.startsWith(it)}).map(X=>({name:X.name||"",path:String(X.absolute||X.path||X.name).replace(/\\/g,"/"),isDirectory:!0})).filter(X=>X.name!=="").sort((X,Te)=>X.name.localeCompare(Te.name)):[]}catch{return[]}}},[c,R,V,oe]),_e=l.useCallback(async()=>{if(!oe||!R){b(!0),h([]);return}b(!0);try{const E=await De(R);h(E)}catch{}finally{b(!1)}},[oe,R,De]);l.useEffect(()=>{oe&&(r==="inline"||v)&&_e()},[r,v,oe,_e]);const Ne=async E=>{if(!oe)return;const ne=g.has(E.path),G=new Set(g);if(ne){G.delete(E.path),x(G);return}G.add(E.path),x(G);const F=await De(E.path),_=B=>B.map($=>$.path===E.path?{...$,children:F}:$.children?{...$,children:_($.children)}:$);h(B=>_(B))};l.useEffect(()=>{A&&W.current&&(W.current.focus(),W.current.select())},[A]);const Pe=(E,ne=[])=>{const G="new_directory",F=ne.map(Q=>Q.name);if(!F.includes(G))return G;let _=1;const B=new RegExp(`^${G}(\\d+)$`);for(const Q of F){const X=Q.match(B);if(X){const Te=parseInt(X[1],10);Te>_&&(_=Te)}}let $=2;for(;F.includes(`${G}${$}`);)$++;return`${G}${Math.max($,_+1)}`},le=async E=>{if(oe){if(g.has(E.path)){const ne=Pe(E.path,E.children);C(ne)}else{const ne=new Set(g);if(ne.add(E.path),x(ne),E.children){const G=Pe(E.path,E.children);C(G)}else{const G=await De(E.path),F=B=>B.map($=>$.path===E.path?{...$,children:G}:$.children?{...$,children:F($.children)}:$);h(B=>F(B));const _=Pe(E.path,G);C(_)}}k(E.path)}},Le=async()=>{if(!A||!oe)return;const E=M.trim()||"new_directory",ne=`${A}/${E}`;try{await Me.createDirectory(ne);const G=await De(A),F=_=>_.map(B=>B.path===A?{...B,children:G}:B.children?{...B,children:F(B.children)}:B);h(_=>F(_)),k(null),C("")}catch(G){console.error("Failed to create directory:",G)}},ae=()=>{k(null),C("")},Ie=(E,ne=0)=>{const G=g.has(E.path),F=E.isDirectory,_=j.has(E.path),B=n===E.path,$=r==="inline",Q=e.jsxs(e.Fragment,{children:[F&&e.jsx("button",{onClick:X=>{X.stopPropagation(),Ne(E)},className:"p-0.5 hover:bg-accent rounded",children:G?e.jsx(xt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}),!F&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:X=>{X.stopPropagation(),Ae(E.path),r==="dropdown"&&a==="immediate"&&N(!1)},onDoubleClick:X=>{X.stopPropagation(),i&&i(E.path)},className:T("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",$&&B?"text-primary":"text-foreground"),children:[G?e.jsx(ts,{className:T("h-3.5 w-3.5 text-muted-foreground",$&&B&&"text-primary")}):e.jsx(ts,{className:T("h-3.5 w-3.5 text-muted-foreground",$&&B&&"text-primary")}),e.jsx("span",{className:T("typography-ui-label font-medium truncate",$&&B?"text-primary":"text-foreground"),children:E.name})]}),e.jsx("button",{onClick:X=>{X.stopPropagation(),le(E)},className:T("p-1 hover:bg-accent rounded transition-opacity",p?"opacity-70":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(os,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:X=>{X.stopPropagation(),me(E.path)},className:T("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(ro,{className:"h-3 w-3 text-primary"}):e.jsx(vu,{className:"h-3 w-3 text-muted-foreground"})})]});return r==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:T("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",B?"text-primary":"text-foreground"),style:{paddingLeft:`${ne*12+8}px`},children:Q}),G&&e.jsxs(e.Fragment,{children:[A===E.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(ne+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(It,{ref:W,value:M,onChange:X=>C(X.target.value),onKeyDown:X=>{X.key==="Enter"?(X.preventDefault(),X.stopPropagation(),Le()):X.key==="Escape"&&(X.preventDefault(),X.stopPropagation(),ae())},onBlur:Le,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:X=>{X.preventDefault(),X.stopPropagation(),Le()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Dt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:X=>{X.preventDefault(),X.stopPropagation(),ae()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"})})]}),E.children&&E.children.map(X=>Ie(X,ne+1))]})]},E.path):e.jsxs("div",{children:[e.jsxs(ht,{className:T("flex items-center gap-1 cursor-pointer group",n===E.path&&"bg-accent"),style:{paddingLeft:`${ne*12+8}px`},onSelect:X=>{X.preventDefault()},children:[F&&e.jsx("button",{onClick:X=>{X.stopPropagation(),Ne(E)},className:"p-0.5 hover:bg-accent rounded",children:G?e.jsx(xt,{className:"h-3 w-3"}):e.jsx(ns,{className:"h-3 w-3"})}),!F&&e.jsx("div",{className:"w-4"}),Q]}),G&&e.jsxs("div",{children:[A===E.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(ne+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(It,{ref:W,value:M,onChange:X=>C(X.target.value),onKeyDown:X=>{X.key==="Enter"?(X.preventDefault(),X.stopPropagation(),Le()):X.key==="Escape"&&(X.preventDefault(),X.stopPropagation(),ae())},onBlur:Le,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:X=>{X.preventDefault(),X.stopPropagation(),Le()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Dt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:X=>{X.preventDefault(),X.stopPropagation(),ae()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"})})]}),E.children&&E.children.map(X=>Ie(X,ne+1))]})]},E.path)},Ge=(E,ne)=>{if(r==="inline"){const G=n===ne;return e.jsxs("div",{className:T("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>Ae(ne),onDoubleClick:F=>{F.stopPropagation(),i&&i(ne)},className:T("flex flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",G?"text-primary":"text-foreground"),children:[e.jsx(ts,{className:T("h-3.5 w-3.5 text-muted-foreground",G&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",G?"text-primary":"text-foreground"),children:E}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:ss(ne,w)})]})]}),e.jsx("button",{onClick:()=>me(ne),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(ro,{className:"h-3 w-3 text-primary"})})]},ne)}return e.jsxs(ht,{onSelect:G=>{G.preventDefault(),Ae(ne),a==="immediate"&&N(!1)},className:T("flex items-start gap-2 cursor-pointer group py-2",n===ne&&"bg-accent"),children:[e.jsx(ts,{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:ss(ne,w)})]}),e.jsx("button",{onClick:G=>{G.stopPropagation(),G.preventDefault(),me(ne)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(ro,{className:"h-3 w-3 text-primary"})})]},ne)},te=e.jsx(e.Fragment,{children:oe?e.jsxs(e.Fragment,{children:[ke.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(xt,{className:"h-3.5 w-3.5"}):e.jsx(ns,{className:"h-3.5 w-3.5"}),e.jsx(Bs,{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:ke.length})]}),D&&ke.map(({name:E,path:ne})=>Ge(E,ne)),r==="dropdown"&&e.jsx(Vn,{}),r==="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(ts,{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=>Ie(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 r==="inline"?e.jsx("div",{className:T("overflow-hidden rounded-xl border border-border/40 bg-sidebar/70",o),children:e.jsx(tt,{outerClassName:"max-h-full",className:"w-full",children:te})}):e.jsxs(Yt,{open:v,onOpenChange:N,children:[e.jsx(Xt,{asChild:!0,children:e.jsxs(Ee,{variant:"ghost",className:T("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",t),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(ts,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:n,children:ss(n,w)})]}),e.jsx(xt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Jt,{align:"start",className:"w-[350px]",children:e.jsx(tt,{outerClassName:"h-full",className:"w-full",children:te})})]})},$i="directoryTreeShowHidden",Yh=({open:n,onOpenChange:s})=>{const{currentDirectory:t,homeDirectory:r,setDirectory:o,isHomeReady:a}=bt(),[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 L=window.localStorage.getItem($i);if(L==="true")return!0;if(L==="false")return!1}catch{}return!1}),{isDesktop:y,requestAccess:b,startAccessing:v}=$c(),{isMobile:N}=Nt(),w=l.useCallback(L=>L?ss(L,r):"",[r]);l.useEffect(()=>{if(n){m(!1),h(!1);const L=t||r||"";c(L),u(w(L))}},[n,t,r,w]),l.useEffect(()=>{!n||p||i||r&&a&&(c(r),m(!0),u("~"))},[n,p,i,r,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem($i,g?"true":"false")}catch{}},[g]);const S=l.useCallback(()=>{s(!1)},[s]),j=l.useCallback(async L=>{if(!(!L||f)){if(L===t){S();return}h(!0);try{let R=L;if(y){const oe=await b(L);if(!oe.success){he.error("Unable to access directory",{description:oe.error||"Desktop denied directory access."});return}R=oe.path??L;const Ce=await v(R);if(!Ce.success){he.error("Failed to open directory",{description:Ce.error||"Desktop could not grant file access."});return}}o(R),S()}catch(R){he.error("Failed to select directory",{description:R instanceof Error?R.message:"Unknown error occurred."})}finally{h(!1)}}},[t,S,y,b,o,v,f]),I=l.useCallback(async()=>{const L=d.trim()||i;L&&await j(L)},[j,d,i]),A=l.useCallback(L=>{c(L),m(!0),u(w(L))},[w]),k=l.useCallback(async L=>{c(L),m(!0),u(w(L)),await j(L)},[j,w]),M=l.useCallback(L=>{const R=L.target.value;if(u(R),m(!0),R.startsWith("/")||R.startsWith("~")){const oe=R.startsWith("~")&&r?R.replace(/^~/,r):R;c(oe)}},[r]),C=l.useCallback(L=>{L.key==="Enter"&&(L.preventDefault(),I())},[I]),D=l.useCallback(()=>{x(L=>!L)},[]),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(cn,{className:"hidden sm:block",children:"Choose the working directory for sessions and OpenCode operations."})]}),W=e.jsx(It,{value:d,onChange:M,onKeyDown:C,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),K=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(_i,{variant:"inline",currentPath:i??t,onSelectPath:A,onDoubleClickPath:k,className:"h-full sm:min-h-[280px] sm:h-[380px]",selectionBehavior:"deferred",showHidden:g,rootDirectory:a?r:null,isRootReady:a})}),O=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(ca,{className:"h-4 w-4 text-primary"}):e.jsx(da,{className:"h-4 w-4"}),"Show hidden"]}),Z=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:W}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:O}),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(_i,{variant:"inline",currentPath:i??t,onSelectPath:A,onDoubleClickPath:k,className:"h-full",selectionBehavior:"deferred",showHidden:g,rootDirectory:a?r:null,isRootReady:a,alwaysShowActions:!0})})]}),se=e.jsxs(tt,{outerClassName:"flex-1 min-h-0 overflow-hidden",className:"directory-dialog-body sm:px-0 sm:pb-0 flex flex-col gap-3",children:[W,e.jsx("div",{className:"flex items-center justify-end",children:O}),K]}),V=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ee,{variant:"ghost",onClick:S,disabled:f,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Ee,{onClick:I,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 N?e.jsx(qt,{open:n,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:V()}),children:Z}):e.jsx(vs,{open:n,onOpenChange:s,children:e.jsxs(js,{className:T("flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6"),onOpenAutoFocus:L=>{L.preventDefault()},children:[P,se,e.jsx(Gn,{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:V()})]})})},Vr=".openchamber",ar=n=>n?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:n}):void 0,Xh=n=>n.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Bc=n=>n.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),zc=n=>{if(!n)return"";const s=n.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},ir=(n,s)=>{const t=zc(n),r=Bc(s),o=!t||t==="/"?`/${Vr}`:`${t}/${Vr}`;return r?`${o}/${r}`:o},Jh=()=>{const[n,s]=l.useState(!1),[t,r]=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),[N,w]=l.useState(null),[S,j]=l.useState([]),[I,A]=l.useState(!1),[k,M]=l.useState(!1),{sessions:C,createSession:D,deleteSession:P,deleteSessions:W,loadSessions:K,initializeNewOpenChamberSession:O,setWorktreeMetadata:Z,setSessionDirectory:se,getWorktreeMetadata:V,isLoading:L}=fe(),{currentDirectory:R,homeDirectory:oe,hasPersistedDirectory:Ce,isHomeReady:Ae}=bt(),{agents:ue}=St(),{isSessionCreateDialogOpen:me,setSessionCreateDialogOpen:ke}=je(),{isMobile:De,isTablet:_e,hasTouchInput:Ne}=Nt(),Pe=De||_e||Ne,le=l.useMemo(()=>zc(R),[R]),Le=l.useMemo(()=>Xh(o),[o]),ae=l.useMemo(()=>Bc(Le),[Le]),Ie=l.useMemo(()=>!le||!ae?"":ir(le,ae),[le,ae]),Ge=g===!0,te=l.useMemo(()=>(N?.worktree?.status?.isDirty??!1)||S.some(U=>U.metadata.status?.isDirty),[N?.worktree?.status?.isDirty,S]),E=l.useMemo(()=>{const U=N?.worktree;return U&&typeof U.branch=="string"&&U.branch.trim().length>0?!0:S.length>0&&S.every(({metadata:ie})=>typeof ie.branch=="string"&&ie.branch.trim().length>0)},[N?.worktree,S]),ne=N?.mode==="worktree",G=ne,F=k||!ne||!E;l.useEffect(()=>{le&&(v.current.has(le)||vf(le).then(()=>v.current.add(le)).catch(U=>{console.warn("Failed to ensure .openchamber directory is ignored:",U),v.current.delete(le)}))},[le]),l.useEffect(()=>{K()},[K,R]),l.useEffect(()=>{!t&&Ae&&!Ce&&(s(!0),r(!0))},[Ce,t,Ae]),l.useEffect(()=>{if(!me){a(""),c([]),m(null),u(!1),h(!1),x(null),b(!1);return}if(!le){c([]),x(null),h(!1);return}let U=!1;return u(!0),h(!0),m(null),(async()=>{try{const ie=await ga(le);if(U)return;if(x(ie),!ie)c([]),m(null);else{const Se=await Pr(le);if(U)return;const we=Se.map(ye=>Rr(le,ye)),ee=`${ir(le,"")}/`,re=we.filter(ye=>ye.path.startsWith(ee));c(re)}}catch(ie){if(U)return;const Se=ie instanceof Error?ie.message:"Failed to load worktrees";m(Se)}finally{U||(u(!1),h(!1))}})(),()=>{U=!0}},[me,le]);const _=l.useCallback(U=>{w({sessions:U.sessions,dateLabel:U.dateLabel,mode:U.mode??"session",worktree:U.worktree??null})},[]),B=l.useCallback(()=>{w(null),j([]),A(!1),M(!1)},[]);l.useEffect(()=>Qs.onDeleteRequest(U=>{_(U)}),[_]),l.useEffect(()=>Qs.onDirectoryRequest(()=>{s(!0)}),[]),l.useEffect(()=>Qs.onCreateRequest(()=>{a(""),ke(!0)}),[ke]),l.useEffect(()=>{if(!N){j([]),A(!1);return}const U=N.sessions.map(Se=>{const we=V(Se.id);return we?{session:Se,metadata:we}:null}).filter(Se=>!!Se);if(j(U),A(!1),U.length===0)return;let ie=!1;return(async()=>{const Se=await Promise.all(U.map(async({metadata:we})=>{if(we.status&&typeof we.status.isDirty=="boolean")return we.status;try{return await br(we.path)}catch{return we.status}})).catch(we=>(console.warn("Failed to inspect worktree status before deletion:",we),U.map(({metadata:ve})=>ve.status)));ie||!Array.isArray(Se)||j(we=>we.map((ve,ee)=>({session:ve.session,metadata:{...ve.metadata,status:Se[ee]??ve.metadata.status}})))})(),()=>{ie=!0}},[N,V]),l.useEffect(()=>{E||A(!1)},[E]);const $=l.useCallback(U=>{a(U),m(null)},[]),Q=l.useCallback(async()=>{if(!(!le||!g))try{const ie=(await Pr(le)).map(ee=>Rr(le,ee)),we=`${ir(le,"")}/`,ve=ie.filter(ee=>ee.path.startsWith(we));c(ve)}catch{}},[le,g]),X=l.useRef(null);l.useEffect(()=>{X.current?.mode==="worktree"&&!N&&Q(),X.current=N},[N,Q]);const Te=l.useCallback(()=>{if(!le){const we="Select a project directory first.";return m(we),he.error(we),!1}const U=Le,ie=ae;if(!U){const we="Provide a branch name for the new worktree.";return m(we),he.error(we),!1}if(!ie){const we="Provide a branch name that can be used as a folder.";return m(we),he.error(we),!1}const Se=ir(le,ie);if(i.some(we=>we.path===Se)){const we="A worktree with this folder already exists.";return m(we),he.error(we),!1}return m(null),!0},[le,Le,ae,i]),We=async()=>{if(y||L||!Te())return;b(!0),m(null);let U=null;try{const ie=Le,we=await Tf({projectDirectory:le,worktreeSlug:ae,branch:ie,createBranch:!0});U=we;let ve=await br(we.path).catch(()=>{});try{await jf(we.path,{remote:"origin",branch:ie,options:["--set-upstream"]}),ve=await br(we.path).catch(()=>ve),he.success(`Configured upstream for ${ie}`)}catch(ye){const Oe=ye instanceof Error?ye.message:"Unable to push new worktree branch.";he.warning("Worktree created locally",{description:ar(`Upstream setup failed: ${Oe}`)})}const ee=ve?{...we,status:ve}:we,re=await D(void 0,we.path);if(!re){await Xa({projectDirectory:le,path:we.path,force:!0}).catch(()=>{});const ye="Failed to create session for worktree";m(ye),he.error(ye);return}O(re.id,ue),se(re.id,we.path),Z(re.id,ee),await Q(),a(""),he.success("Worktree created")}catch(ie){U&&await Xa({projectDirectory:le,path:U.path,force:!0}).catch(()=>{});const Se=ie instanceof Error?ie.message:"Failed to create worktree";m(Se),he.error(Se)}finally{b(!1)}},it=l.useCallback(U=>{const ie=C.filter(Se=>V(Se.id)?.path===U.path);Qs.requestDelete({sessions:ie,mode:"worktree",worktree:U})},[C,V]),nt=l.useCallback(async()=>{if(N){M(!0);try{const U=G,ie=U&&I;if(N.sessions.length===1){const Se=N.sessions[0];if(!await P(Se.id,{archiveWorktree:U,deleteRemoteBranch:ie})){he.error("Failed to delete session"),M(!1);return}const ve=U?ie?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;he.success("Session deleted",{description:ar(ve)})}else{const Se=N.sessions.map(ee=>ee.id),{deletedIds:we,failedIds:ve}=await W(Se,{archiveWorktree:U,deleteRemoteBranch:ie});if(we.length>0){const ee=U?ie?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,ye=[ve.length>0?`${ve.length} session${ve.length===1?"":"s"} could not be deleted.`:N.dateLabel?`Removed all sessions from ${N.dateLabel}.`:void 0,ee].filter(Boolean).join(" ");he.success(`Deleted ${we.length} session${we.length===1?"":"s"}`,{description:ar(ye||void 0)})}if(ve.length>0&&(he.error(`Failed to delete ${ve.length} session${ve.length===1?"":"s"}`,{description:ar("Please try again in a moment.")}),we.length===0)){M(!1);return}}B()}finally{M(!1)}}},[N,I,P,W,B,G]),Ze=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:Vr}),"."]})]}),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(It,{id:"worktree-branch-input",value:o,onChange:U=>$(U.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!Ge||f,onKeyDown:U=>{U.key==="Enter"&&!y&&We()}}),e.jsx(Ee,{onClick:We,disabled:y||L||!Ge||!Le,className:"h-8",children:y?"Creating…":"Create"})]}),Le&&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:Le})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:ss(Ie,oe)})]})]}),p&&e.jsx("p",{className:"typography-meta text-destructive",children:p}),!Ge&&!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:Vr}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:i.map(U=>{const ie=U.relativePath||(U.path.startsWith(le+"/")?U.path.slice(le.length+1):U.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:U.label||U.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:ie})]}),e.jsx("button",{type:"button",onClick:()=>it(U),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 ${U.branch||U.label}`,children:e.jsx(Gs,{className:"h-4 w-4"})})]},U.path)})})]})]}),lt=e.jsx(Ee,{variant:"ghost",onClick:()=>ke(!1),disabled:y,children:"Close"}),mt=N?.worktree??S[0]?.metadata??null,dt=N?N.mode==="worktree"?`This removes the selected worktree and ${N.sessions.length===1?"1 linked session":`${N.sessions.length} linked sessions`}.`:`This action permanently removes ${N.sessions.length===1?"1 session":`${N.sessions.length} sessions`}${N.dateLabel?` from ${N.dateLabel}`:""}.`:"",z=N?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:[N.sessions.slice(0,3).map(U=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:U.title||"Untitled Session"},U.id)),N.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",N.sessions.length-3," more"]})]})}),ne?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"}),mt?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:mt.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:mt?ss(mt.path,oe):"Worktree path unavailable."}),te&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),E?e.jsxs("button",{type:"button",onClick:()=>{F||A(U=>!U)},disabled:F,className:T("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:I?e.jsx(ca,{className:"size-4 text-primary"}):e.jsx(da,{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:I?"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,ge=e.jsxs(e.Fragment,{children:[e.jsx(Ee,{variant:"ghost",onClick:B,disabled:k,children:"Cancel"}),e.jsx(Ee,{variant:"destructive",onClick:nt,disabled:k,children:k?"Deleting…":ne?"Delete worktree":N?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[Pe?e.jsx(qt,{open:me,onClose:()=>ke(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:lt}),children:e.jsx("div",{className:"space-y-2 pb-2",children:Ze})}):e.jsx(vs,{open:me,onOpenChange:ke,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"})}),Ze,e.jsx(Gn,{className:"mt-2 gap-2 pt-1 pb-1",children:lt})]})}),Pe?e.jsx(qt,{open:!!N,onClose:()=>{k||B()},title:N?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:ge}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[dt&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:dt}),z]})}):e.jsx(vs,{open:!!N,onOpenChange:U=>{if(!U){if(k)return;B()}},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:N?.sessions.length===1?"Delete session":"Delete sessions"}),dt&&e.jsx(cn,{children:dt})]}),z,e.jsx(Gn,{className:"mt-2 gap-2 pt-1 pb-1",children:ge})]})}),e.jsx(Yh,{open:n,onOpenChange:s})]})};function Zh(){return new Worker(ju,{type:"module"})}const Qh=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function eg(n,s,t){const r=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${n}:${s.length}:${t.length}:${r.length}:${o.length}`}function Bi(n){if(typeof window>"u")return()=>{};const s=window.setTimeout(()=>n(void 0),0);return()=>window.clearTimeout(s)}const tg=({children:n})=>{const s=ku(),t=jt(c=>c.activeDirectory),r=jt(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=jt(c=>t?c.directories.get(t)?.diffCache.size??0:0),a=de.useRef(!1),i=de.useRef(new Map);return de.useEffect(()=>{if(!s||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Lo(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(u,d)},[s]),de.useEffect(()=>{if(!s||!t||!r||o===0)return;const c=jt.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,on(y);const v=eg(y,b.original,b.modified),N={name:y,contents:b.original,cacheKey:`old-${v}`},w={name:y,contents:b.modified,cacheKey:`new-${v}`},S=Lo(N,w),j={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(j,S)}f<m.length&&(p=Bi(h))};return h(void 0),f<m.length&&(p=Bi(h)),()=>{u=!0,p?.()}},[s,t,r,o]),e.jsx(e.Fragment,{children:n})},sg=({children:n})=>{const t=to()?.currentTheme?.metadata?.variant==="dark";yc();const r=de.useMemo(()=>({theme:{dark:Cn.dark,light:Cn.light},themeType:t?"dark":"light",langs:Qh}),[t]);return e.jsx(Su,{poolOptions:{workerFactory:Zh,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:r,children:e.jsx(tg,{children:n})})},ng=(n={})=>{const{edgeThreshold:s=30,minSwipeDistance:t=50,maxSwipeTime:r=300,enabled:o=!0}=n,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=je(),d=de.useRef(null),u=de.useRef(null);return de.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:N,y:w,time:S}=u.current,j=N-y,I=w-b,A=S-v,k=Math.abs(I)<Math.abs(j),M=A<=r,C=Math.abs(I)<t;j>=t&&k&&M&&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,r,i,c]),null},On=n=>n==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:n==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;de.memo(()=>{const n=de.useRef(null),{addAttachedFile:s}=fe(),{isMobile:t}=je(),r=Sa(),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),he.error(g instanceof Error?g.message:"Failed to attach file")}}p>0&&he.success(`Attached ${p} file${p>1?"s":""}`)},c=async u=>{const p=u.target.files;p&&(await i(p),n.current&&(n.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
|
+
`);he.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),N=new Uint8Array(v.length);for(let S=0;S<v.length;S++)N[S]=v.charCodeAt(S);const w=new Blob([N],{type:b});return new File([w],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),he.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:n,type:"file",multiple:!0,className:"hidden",onChange:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{r?d():n.current?.click()},className:T(o,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),title:"Attach files",children:e.jsx($o,{className:T(a,"text-current")})})]})});const rg=de.memo(({file:n,onRemove:s})=>{const t=()=>n.mimeType.startsWith("image/")?e.jsx(Nn,{className:"h-3.5 w-3.5"}):n.mimeType.includes("text")||n.mimeType.includes("code")?e.jsx(en,{className:"h-3.5 w-3.5"}):n.mimeType.includes("json")||n.mimeType.includes("xml")?e.jsx(Zr,{className:"h-3.5 w-3.5"}):e.jsx(en,{className:"h-3.5 w-3.5"}),r=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})(n.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:n.source==="server"?"Server file":"Local file",children:n.source==="server"?e.jsx(Nu,{className:"h-3 w-3 text-primary"}):e.jsx(Ll,{className:"h-3 w-3 text-muted-foreground"})}),t(),e.jsx("span",{title:n.serverPath||a,children:a}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",r(n.size),")"]}),e.jsx("button",{onClick:s,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(ds,{className:"h-3 w-3"})})]})}),og=de.memo(()=>{const{attachedFiles:n,removeAttachedFile:s}=fe();return n.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:"}),n.map(t=>e.jsx(rg,{file:t,onRemove:()=>s(t.id)},t.id))]})})}),Hc=de.memo(({files:n,onShowPopup:s})=>{const t=n.filter(d=>d.type==="file"&&(d.mime||d.url)),r=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(Nn,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(en,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Zr,{className:"h-3.5 w-3.5"}):e.jsx(en,{className:"h-3.5 w-3.5"}):e.jsx(en,{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=r(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:r(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=r(d.filename)||"Image";return e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{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(Nn,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:p})]})}),e.jsx(st,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:p})]},`img-${u}`)})})})]})}),Wc=(n,s=200)=>{const[t,r]=de.useState(n);return de.useEffect(()=>{const o=window.setTimeout(()=>{r(n)},s);return()=>{window.clearTimeout(o)}},[n,s]),t},ag=l.forwardRef(({searchQuery:n,onFileSelect:s,onClose:t},r)=>{const{currentDirectory:o}=bt(),{addServerFile:a}=fe(),i=ya(C=>C.searchFiles),c=Wc(n,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,N]=l.useState({}),w=l.useRef([]),S=l.useRef([]),j=l.useRef([]),I=l.useRef(null),A=l.useCallback((C,D)=>{const P=C.trim().toLowerCase();if(!P)return 0;const W=D.toLowerCase();let K=0,O=-1,Z=0;for(let se=0;se<P.length;se+=1){const V=P[se];if(!V||V===" ")continue;const L=W.indexOf(V,O+1);if(L===-1)return null;const R=L-O-1;if(R===0?Z+=1:Z=0,K+=10,K+=Math.max(0,18-L),K-=Math.max(0,R),L===0)K+=12;else{const oe=W[L-1];(oe==="/"||oe==="_"||oe==="-"||oe==="."||oe===" ")&&(K+=10)}K+=Z>0?12:0,O=L}return K+=Math.max(0,24-Math.round(W.length/3)),K},[]);l.useEffect(()=>{const C=D=>{const P=D.target;!P||!I.current||I.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(W=>{if(P)return;const K=D?W.map(O=>{const Z=O.relativePath||O.name||O.path,se=A(D,Z);return se===null?null:{file:O,score:se,labelLength:Z.length}}).filter(Boolean):W.map(O=>({file:O,score:0,labelLength:(O.relativePath||O.name||O.path).length}));K.sort((O,Z)=>Z.score-O.score||O.labelLength-Z.labelLength||O.file.path.localeCompare(Z.file.path)),u(K.slice(0,15).map(O=>O.file))}).catch(()=>{P||u([])}).finally(()=>{P||m(!1)}),()=>{P=!0}},[o,c,A,i]),l.useEffect(()=>{h(0),b({}),N({})},[d]),l.useEffect(()=>{w.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),l.useEffect(()=>{let C=null;const D=()=>{C!==null&&cancelAnimationFrame(C),C=requestAnimationFrame(()=>{const P={},W={};S.current.forEach((K,O)=>{if(!K)return;const se=j.current[O]?.offsetWidth??K.scrollWidth,V=Math.max(0,se-K.clientWidth),L=V>8;if(P[O]=L,L){const R=Math.max(.6,V/110);W[O]=R}}),b(P),N(W)})};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 W=C.clientWidth;W>0&&x(W)};if(D(),typeof ResizeObserver>"u")return;const P=new ResizeObserver(D);return P.observe(C),()=>{P.disconnect()}},[f]);const k=l.useCallback(async C=>{await a(C.path,C.name),s(C)},[a,s]);l.useImperativeHandle(r,()=>({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,W=d[P];W&&k(W)}}}}),[d,f,t,k]);const M=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(en,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Nn,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Zr,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:I,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:p?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Qr,{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,W=Hl(P,{maxLength:45}),K=f===D,O=y[D]??!1,Z=v[D]??2.6,se=e.jsxs("div",{ref:V=>{w.current[D]=V},className:T("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",K&&"bg-muted"),onClick:()=>k(C),onMouseEnter:()=>h(D),children:[M(C),e.jsxs("span",{ref:V=>{S.current[D]=V},className:"relative flex-1 overflow-hidden max-w-[360px] file-mention-marquee-container",style:K?{"--file-mention-marquee-width":`${g}px`,"--file-mention-marquee-duration":`${Z}s`}:void 0,"aria-label":P,children:[e.jsx("span",{ref:V=>{j.current[D]=V},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:P}),O&&K?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:P}):e.jsx("span",{className:"block truncate",children:W})]})]});return e.jsx(l.Fragment,{children:se},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"})]})}),Uc=l.forwardRef(({searchQuery:n,onCommandSelect:s,onClose:t},r)=>{const{hasMessagesInCurrentSession:o}=fe(ua(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 Me.listCommands()).map(j=>({name:j.name,description:j.description,agent:j.agent,model:j.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(j=>v.set(j.name,j)),y.forEach(j=>v.set(j.name,j));const N=Array.from(v.values()),w=!o,S=(n?N.filter(j=>j.name.toLowerCase().includes(n.toLowerCase())||j.description&&j.description.toLowerCase().includes(n.toLowerCase())):N).filter(j=>w||j.name!=="init");S.sort((j,I)=>{const A=j.name.toLowerCase().startsWith(n.toLowerCase()),k=I.name.toLowerCase().startsWith(n.toLowerCase());return A&&!k?-1:!A&&k?1:j.name.localeCompare(I.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=(n?y.filter(v=>v.name.toLowerCase().includes(n.toLowerCase())||v.description&&v.description.toLowerCase().includes(n.toLowerCase())):y).filter(v=>x||v.name!=="init");i(b)}finally{d(!1)}})()},[n,o]),l.useEffect(()=>{p(0)},[a]),l.useEffect(()=>{m.current[u]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[u]),l.useImperativeHandle(r,()=>({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(en,{className:"h-3.5 w-3.5 text-green-500"});case"summarize":return e.jsx(Mu,{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(Cu,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(nn,{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(tt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Qr,{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:T("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"})]})});Uc.displayName="CommandAutocomplete";const ig=n=>n?n!=="primary":!1,Vc=l.forwardRef(({searchQuery:n,onAgentSelect:s,onClose:t},r)=>{const o=l.useRef(null),[a,i]=l.useState(0),[c,d]=l.useState([]),{getVisibleAgents:u}=St();l.useEffect(()=>{const f=u().filter(x=>ig(x.mode)).map(x=>({name:x.name,description:x.description,mode:x.mode??void 0})),h=n.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,n]),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(r,()=>({handleKeyDown:m=>{if(m==="Escape"){t();return}if(c.length){if(m==="ArrowDown"){i(f=>(f+1)%c.length);return}if(m==="ArrowUp"){i(f=>(f-1+c.length)%c.length);return}if(m==="Enter"||m==="Tab"){const f=c[(a+c.length)%c.length];f&&s(f.name)}}}}),[c,s,t,a]);const p=(m,f)=>e.jsx("div",{className:T("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",f===a&&"bg-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(tt,{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"})]})});Vc.displayName="AgentMentionAutocomplete";function lg({className:n,children:s,...t}){return e.jsxs(Au,{"data-slot":"scroll-area",className:T("relative",n),...t,children:[e.jsx(Du,{"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(cg,{}),e.jsx(Eu,{})]})}function cg({className:n,orientation:s="vertical",...t}){return e.jsx(Tu,{"data-slot":"scroll-area-scrollbar",orientation:s,className:T("flex touch-none p-px select-none",s==="vertical"&&"h-full w-2.5 border-l border-l-transparent",s==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",n),...t,children:e.jsx(Iu,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const dg=({onFilesSelected:n,multiSelect:s=!1,children:t,open:r,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Nt(),c=Sa(),d=i||c,{currentDirectory:u}=bt(),p=ya(F=>F.searchFiles),[m,f]=l.useState(!1),[h,g]=l.useState(!1),[x,y]=l.useState(""),b=Wc(x,200),[v,N]=l.useState(new Set),[w,S]=l.useState(new Set),[j,I]=l.useState({}),A=l.useRef(new Set),k=l.useRef(new Set),[M,C]=l.useState([]),[D,P]=l.useState(!1),[W,K]=l.useState(!1),[O,Z]=l.useState(!1),[se,V]=l.useState(null),L=r??m,R=o??f,oe=l.useCallback(F=>F.slice().sort((_,B)=>_.type!==B.type?_.type==="directory"?-1:1:_.name.localeCompare(B.name)),[]),Ce=l.useCallback((F,_)=>oe(_.filter(B=>!B.name.startsWith(".")).map(B=>{const $=B.name,Q=!B.isDirectory&&$.includes(".")?$.split(".").pop()?.toLowerCase():void 0;return{name:$,path:B.path||`${F}/${$}`,type:B.isDirectory?"directory":"file",size:0,extension:Q}})),[oe]),Ae=l.useCallback(async F=>{K(!0),V(null);try{const _=await Me.listLocalDirectory(F),B=Ce(F,_.map($=>({name:$.name,path:$.path,isDirectory:$.isDirectory})));A.current=new Set([F]),k.current=new Set,I({[F]:B}),S(new Set)}catch{V("Failed to load directory contents"),A.current=new Set([F]),k.current=new Set,I({[F]:[]}),S(new Set)}finally{K(!1)}},[Ce]),ue=l.useCallback(async F=>{const _=F.trim();if(_&&!A.current.has(_)&&!k.current.has(_)){k.current=new Set(k.current),k.current.add(_);try{const B=await Me.listLocalDirectory(_),$=Ce(_,B.map(Q=>({name:Q.name,path:Q.path,isDirectory:Q.isDirectory})));A.current=new Set(A.current),A.current.add(_),I(Q=>({...Q,[_]:$}))}catch{I(B=>B[_]?B:{...B,[_]:[]})}finally{k.current=new Set(k.current),k.current.delete(_)}}},[Ce]);l.useEffect(()=>{(L||h)&&u&&Ae(u)},[L,h,u,Ae]),l.useEffect(()=>{if(!(L||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(B=>{if(_)return;const $=B.map(Q=>({name:Q.name,path:Q.path,type:"file",extension:Q.extension,relativePath:Q.relativePath,size:0}));C($)}).catch(()=>{_||C([])}).finally(()=>{_||P(!1)}),()=>{_=!0}},[L,h,u,b,p]),l.useEffect(()=>{!L&&!h&&(N(new Set),y(""),C([]),P(!1))},[L,h]);const me=F=>{if(F.type==="directory")return w.has(F.path)?e.jsx(ts,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(ts,{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(Bo,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Nn,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Bo,{className:"h-3.5 w-3.5 text-muted-foreground"})}},ke=async F=>{w.has(F)?S(B=>{const $=new Set(B);return $.delete(F),$}):(S(B=>{const $=new Set(B);return $.add(F),$}),await ue(F))},De=F=>{N(s?_=>{const B=new Set(_);return B.has(F)?B.delete(F):B.add(F),B}:new Set([F]))},_e=async()=>{const F=new Map;Object.values(j).forEach($=>{$.forEach(Q=>{Q.type==="file"&&F.set(Q.path,Q)})});const _=new Map(M.map($=>[$.path,$])),B=Array.from(v).map($=>F.get($)??_.get($)).filter($=>!!$);Z(!0);try{await n(B),N(new Set),R(!1),g(!1)}finally{Z(!1)}},Ne=l.useMemo(()=>u?j[u]??[]:[],[j,u]),Pe=x.trim().length>0,le=F=>j[F]??[],Le=F=>{if(u&&F.startsWith(u)){const _=F.substring(u.length);return _.startsWith("/")?_.substring(1):_}return F.split("/").pop()||F},ae=(F,_)=>{const B=Pe?F.relativePath||Le(F.path):F.name,$=Pe&&B.includes("/")&&B.length>45,Q=$?Hl(B,{maxLength:d?42:48}):B,X=e.jsxs("div",{className:T("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-muted cursor-pointer typography-ui-label text-foreground text-left",F.type==="file"&&v.has(F.path)&&"bg-primary/10"),style:{paddingLeft:`${_*12}px`},onClick:Te=>{Te.preventDefault(),Te.stopPropagation(),F.type==="file"&&De(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:me(F)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":B,children:Q})]}),F.type==="file"&&v.has(F.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return $?e.jsxs(ot,{delayDuration:120,children:[e.jsx(at,{asChild:!0,children:X}),e.jsx(st,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:B})})]},F.path):l.cloneElement(X,{key:F.path})},Ie=(F,_)=>{const B=F.type==="directory",$=B?le(F.path):[],Q=w.has(F.path),X=B&&Q&&k.current.has(F.path)&&$.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!B&&v.has(F.path)&&"bg-primary/10"),style:{paddingLeft:`${_*12}px`},onClick:Te=>{Te.preventDefault(),Te.stopPropagation(),B?ke(F.path):De(F.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:me(F)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:F.name}),!B&&v.has(F.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),B&&Q&&$.length>0&&e.jsx("div",{children:$.map(Te=>Ie(Te,_+1))}),B&&Q&&X&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(_+1)*12}px`},children:"Loading…"})]},F.path)},Ge=v.size>0?`${v.size} file${v.size!==1?"s":""} selected`:"No files selected",te=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:Ge}),e.jsx(Ee,{size:"sm",onClick:_e,disabled:v.size===0||O,className:"h-6 typography-meta",children:O?"Attaching...":"Attach Files"})]}),E=d?"flex-1 min-h-[240px]":"h-[300px]",ne=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(la,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(It,{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(ds,{className:"h-3 w-3"})})]})}),e.jsxs(lg,{className:E,children:[W&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Loading files..."})}),se&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:se})}),!W&&!se&&e.jsxs("div",{className:"py-1 px-2",children:[Pe?D?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):M.map(F=>ae(F,0)):Ne.map(F=>Ie(F,0)),!Pe&&Ne.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),Pe&&!D&&M.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),G=e.jsx("span",{className:"inline-flex cursor-pointer",onClick: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(),R(!0)},children:t}):null,e.jsx(qt,{open:L,onClose:()=>R(!1),title:"Select Project Files",footer:te,children:e.jsx("div",{className:"flex flex-col gap-0",children:ne})})]}):d?e.jsxs(e.Fragment,{children:[G,e.jsx(qt,{open:h,onClose:()=>g(!1),title:"Select Project Files",footer:te,children:e.jsx("div",{className:"flex flex-col gap-0",children:ne})})]}):e.jsxs(Yt,{open:L,onOpenChange:R,children:[e.jsx(Xt,{asChild:!0,children:t}),e.jsxs(Jt,{className:T("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[ne,e.jsx(Vn,{}),te]})]})},lr=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function $s(n){if(!n||n==="build")return lr[0];let s=0;for(let r=0;r<n.length;r++){const o=n.charCodeAt(r);s=(s<<5)-s+o,s=s&s}const t=1+Math.abs(s)%(lr.length-1);return lr[t]}const ug=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Gc=n=>ug(n),mg=n=>n?typeof n=="string"?n==="ask":Gc(n)?Object.values(n).some(s=>s==="ask"):!1:!1,fg=n=>n?typeof n=="string"?n==="deny":Gc(n)?Object.values(n).some(s=>s==="deny"):!1:!1,qc=({agentDefaultEditMode:n,webfetchPermission:s,bashPermission:t})=>{const r=mg(t),o=fg(t),a=!r&&!o,i=s==="allow",c=s!=="deny",d=n==="allow"||n==="full",u=n==="ask";let p=n;d&&i&&a?p="full":d&&r?p="allow":u&&(p="ask");const m={ask:u,allow:u||d&&r,full:n!=="deny"&&c&&r,deny:!1},f=m.allow||m.full;return{cascadeDefaultMode:p,modeAvailability:m,autoApproveAvailable:f,bashHasAsk:r,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:c}},cr=n=>n==="primary"||n==="all"||n===void 0||n===null,pg=[{key:"tool_call",icon:ma,label:"Tool calling",isActive:n=>n?.tool_call===!0},{key:"reasoning",icon:Yr,label:"Reasoning",isActive:n=>n?.reasoning===!0}],hg={text:{icon:Ol,label:"Text"},image:{icon:Nn,label:"Image"},video:{icon:Pu,label:"Video"},audio:{icon:Fu,label:"Audio"},pdf:{icon:Zr,label:"PDF"}},gg=n=>n.trim().toLowerCase(),Ns=(n,s)=>{const t=s==="input"?n?.modalities?.input:n?.modalities?.output;return!Array.isArray(t)||t.length===0?[]:Array.from(new Set(t.map(o=>gg(o)))).map(o=>{const a=hg[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},xg=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),yg=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Ot=n=>{if(typeof n!="number"||Number.isNaN(n))return"—";if(n===0)return"0";const s=xg.format(n);return s.endsWith(".0")?s.slice(0,-2):s},dr=n=>typeof n!="number"||!Number.isFinite(n)?"—":yg.format(n),Rn=n=>pg.filter(s=>s.isActive(n)).map(s=>({key:s.key,icon:s.icon,label:s.label})),zi=n=>{if(!n)return"—";const s=n.match(/^(\d{4})-(\d{2})$/);if(s){const t=Number.parseInt(s[1],10),r=Number.parseInt(s[2],10)-1,o=new Date(Date.UTC(t,r,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return n},Hi=n=>{if(!n)return"—";const s=new Date(n);return Number.isNaN(s.getTime())?n:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(s)},Wi=({className:n})=>{const{providers:s,currentProviderId:t,currentModelId:r,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:N,getSessionAgentEditMode:w,setSessionAgentEditMode:S}=fe(),j=pt(H=>H.hasHydrated),{toggleFavoriteModel:I,isFavoriteModel:A,addRecentModel:k}=je(),{favoriteModelsList:M,recentModelsList:C}=Dc(),{isMobile:D}=Nt(),P=_p(),W=Sa(),K=D||W,[O,Z]=l.useState(null),[se,V]=l.useState(null),[L,R]=l.useState(""),oe=l.useCallback(()=>Z(null),[]),Ce=l.useCallback(()=>V(null),[]),Ae=l.useRef(void 0),[ue,me]=l.useState(()=>{const H=new Set;return t&&H.add(t),H}),[ke,De]=l.useState(!1),[_e,Ne]=l.useState(!1),[Pe,le]=l.useState(!1),Le=l.useId();l.useEffect(()=>{O==="model"&&me(()=>{const H=new Set;return t&&H.add(t),H})},[O,t]),l.useEffect(()=>{O!=="agent"&&De(!1),O!=="model"&&R("")},[O]),l.useEffect(()=>{_e||le(!1)},[_e]);const ae=p?.(),Ie=ae?.permission?.edit;let Ge="ask";(Ie==="allow"||Ie==="ask"||Ie==="deny"||Ie==="full")&&(Ge=Ie);const te=ae?ae.tools?.edit!==!1:!1;(!ae||!te)&&(Ge="deny");const E=ae?.permission?.webfetch,ne=ae?.permission?.bash,G=l.useMemo(()=>qc({agentDefaultEditMode:Ge,webfetchPermission:E,bashPermission:ne}),[Ge,E,ne]),{cascadeDefaultMode:F,modeAvailability:_,autoApproveAvailable:B}=G,$=!!(h&&o),Q=$&&h&&o?w(h,o,F):F,X={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Te=l.useCallback(H=>!_[H],[_]),We=l.useMemo(()=>!$||Te(Q)&&Q!==F?F:Q,[F,Te,$,Q]),it=[{mode:"ask",label:X.ask,disabled:Te("ask")},{mode:"allow",label:X.allow,disabled:Te("allow")},{mode:"full",label:X.full,disabled:Te("full")}],nt=l.useMemo(()=>On(We),[We]),Ze=!$||!B;l.useEffect(()=>{Ze&&(De(!1),le(!1))},[Ze]);const lt=D?"mobile":W?"vscode":"default",mt=lt==="mobile"?"h-9":lt==="vscode"?"h-6":"h-8",dt=lt==="mobile"?"h-5 w-5":"h-4 w-4",z=lt==="mobile"?"h-5 w-5":"h-4 w-4",ge=K?"typography-micro":"typography-meta",U=lt==="mobile"?"gap-x-2":lt==="vscode"?"gap-x-1":"gap-x-3",ie=X[We],Se=l.useCallback((H,J=dt)=>{const Y=T(J,"flex-shrink-0"),ce=On(H),Ke={color:ce?ce.text:"var(--foreground)"};return H==="full"?e.jsx(Ds,{className:Y,style:Ke}):H==="allow"?e.jsx(gr,{className:Y,style:Ke}):H==="deny"?e.jsx(kn,{className:Y,style:Ke}):e.jsx(Sn,{className:Y,style:Ke})},[dt]),we=l.useCallback(H=>{Ze||!h||!o||Te(H)||(S(h,o,H,F),Ne(!1),De(!1),le(!1))},[F,Ze,h,o,S,Ne,le,Te]),ve=d(),ee=Array.isArray(ve?.models)?ve.models:[],re=t&&r?u(t,r):void 0,ye=Rn(re),Oe=Ns(re,"input"),qe=Ns(re,"output"),ft=[{label:"Input",value:dr(re?.cost?.input)},{label:"Output",value:dr(re?.cost?.output)},{label:"Cache read",value:dr(re?.cost?.cache_read)},{label:"Cache write",value:dr(re?.cost?.cache_write)}],Ct=[{label:"Context",value:Ot(re?.limit?.context)},{label:"Output",value:Ot(re?.limit?.output)}],Et=l.useRef(void 0),Pt=h?g.get(h)?.length??-1:-1,Mt=l.useRef(null),yt=l.useCallback((H,J,Y)=>{if(!H||!J)return"model-missing";const ce=s.find(pe=>pe.id===H);return ce?(Array.isArray(ce.models)?ce.models:[]).find(pe=>pe.id===J)?(a(H),i(J),h&&Y&&b(h,Y,H,J),"applied"):"model-missing":"provider-missing"},[s,a,i,h,b]);l.useEffect(()=>{if(!h){Mt.current=null;return}if(!j||s.length===0||f.length===0)return;(!Mt.current||Mt.current.sessionId!==h)&&(Mt.current={sessionId:h,resolved:!1,inFlight:!1});const H=Mt.current;if(!H||H.resolved||H.inFlight)return;let J=!1;const Y=()=>{if(J)return;const pe=Mt.current;pe&&pe.sessionId===h&&(pe.resolved=!0,pe.inFlight=!1)},ce=()=>{const pe=y(h);if(pe){o!==pe&&c(pe);const ze=v(h,pe);if(ze){const Ye=yt(ze.providerId,ze.modelId,pe);if(Ye==="applied")return"resolved";if(Ye==="provider-missing")return"waiting"}else return"resolved"}for(const ze of f){const Ye=v(h,ze.name);if(!Ye)continue;o!==ze.name&&c(ze.name),x(h,ze.name);const At=yt(Ye.providerId,Ye.modelId,ze.name);if(At==="applied")return"resolved";if(At==="provider-missing")return"waiting"}return"continue"},Ve=()=>{if(f.length===0)return;const pe=f.filter(Ye=>cr(Ye.mode)),ze=f.find(Ye=>Ye.name==="build")||pe[0]||f[0];ze&&(x(h,ze.name),o!==ze.name&&c(ze.name),ze.model?.providerID&&ze.model?.modelID&&yt(ze.model.providerID,ze.model.modelID,ze.name))};return(async()=>{try{const pe=ce();if(pe==="resolved"){Y();return}if(pe==="waiting"||Pt===-1)return;if(Pt>0){H.inFlight=!0;try{const ze=await N(h,f);if(J)return;if(ze.size>0){let Ye=null,At=-1/0;for(const[He,Lt]of ze)Lt.timestamp>At&&(At=Lt.timestamp,Ye=He);if(Ye){x(h,Ye),o!==Ye&&c(Ye);const He=ze.get(Ye);if(He){const Lt=yt(He.providerId,He.modelId,Ye);if(Lt==="applied"){Y();return}if(Lt==="provider-missing")return}else{Y();return}}}}catch(ze){J||console.error("[ModelControls] Error resolving session from messages:",ze)}finally{const ze=Mt.current;!J&&ze&&ze.sessionId===h&&(ze.inFlight=!1)}}Ve(),Y()}catch(pe){J||console.error("[ModelControls] Error in session switch:",pe)}})(),()=>{J=!0}},[h,Pt,f,o,y,v,c,yt,N,x,j,s]),l.useEffect(()=>{if(!j||!h||s.length===0||f.length===0)return;const J=y(h)||o;if(!J)return;const Y=v(h,J);if(!Y)return;const ce=s.find(ze=>ze.id===Y.providerId);if(!ce||!(Array.isArray(ce.models)?ce.models.some(ze=>ze.id===Y.modelId):!1))return;const Ke=t===Y.providerId,pe=r===Y.modelId;Ke&&pe||(J!==o&&c(J),yt(Y.providerId,Y.modelId,J))},[j,h,o,t,r,s,f,y,v,yt,c]),l.useEffect(()=>{if(!j)return;(async()=>{try{if(o!==Et.current&&(Et.current=o,o&&h)){await new Promise(ce=>setTimeout(ce,50));const J=v(h,o);if(J){const ce=yt(J.providerId,J.modelId,o);if(ce==="applied"||ce==="provider-missing")return}const Y=f.find(ce=>ce.name===o);if(Y?.model?.providerID&&Y?.model?.modelID&&yt(Y.model.providerID,Y.model.modelID,o)==="provider-missing")return}}catch(J){console.error("[ModelControls] Agent change error:",J)}})()},[o,h,v,yt,f,j]);const be=H=>{try{c(H),Ne(!1),h&&x(h,H),K&&oe()}catch(J){console.error("[ModelControls] Handle agent change error:",J)}},Be=(H,J)=>{try{const Y=yt(H,J,o||void 0);if(Y!=="applied"){Y==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",H):Y==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:H,modelId:J});return}k(H,J),Ne(!1),K&&oe()}catch(Y){console.error("[ModelControls] Handle model change error:",Y)}},Qe=H=>{const J=typeof H?.name=="string"?H.name:typeof H?.id=="string"?H.id:"";return J.length>40?J.substring(0,37)+"...":J},Je=()=>s.find(J=>J.id===t)?.name||t,ut=()=>{if(!t||!r||ee.length===0)return"Not selected";const H=ee.find(J=>J.id===r);return Qe(H)},wt=()=>{if(!o){const J=f.filter(Ve=>cr(Ve.mode)),ce=J.find(Ve=>Ve.name==="build")||J[0];return ce?kt(ce.name):"Select Agent"}const H=f.find(J=>J.name===o);return kt(H?H.name:o)},kt=H=>H.charAt(0).toUpperCase()+H.slice(1),xe=(H,J,Y)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:J,"aria-label":J,role:"img",children:e.jsx(H,{className:"h-3.5 w-3.5"})},Y),$e=l.useCallback(H=>{me(J=>{const Y=new Set(J);return Y.has(H)?Y.delete(H):Y.add(H),Y})},[]),Fe=l.useCallback(H=>{Ae.current&&clearTimeout(Ae.current),Ae.current=setTimeout(()=>{V(H)},500)},[]),et=l.useCallback(()=>{Ae.current&&clearTimeout(Ae.current)},[]);l.useEffect(()=>()=>{Ae.current&&clearTimeout(Ae.current)},[]);const vt=()=>!K||se!=="model"?null:e.jsx(qt,{open:!0,onClose:Ce,title:re?.name||ut(),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:Je()})]}),ye.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:ye.map(({key:H,icon:J,label:Y})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[xe(J,Y,`cap-${H}`),e.jsx("span",{className:"typography-meta text-foreground",children:Y})]},H))})]}),(Oe.length>0||qe.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[Oe.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:Oe.map(({key:H,icon:J,label:Y})=>xe(J,`${Y} input`,`input-${H}`))})]}),qe.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Output"}),e.jsx("div",{className:"flex gap-1",children:qe.map(({key:H,icon:J,label:Y})=>xe(J,`${Y} output`,`output-${H}`))})]})]})]}),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:Ot(re?.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:Ot(re?.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(re?.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(re?.release_date)})]})]})]})]})}),gt=()=>{if(!K||se!=="agent"||!ae)return null;const H=Object.entries(ae.tools||{}).filter(([,pe])=>pe).map(([pe])=>pe).sort(),J=!!(ae.prompt&&ae.prompt.trim().length>0),Y=ae.model?.providerID&&ae.model?.modelID,ce=ae.temperature!==void 0||ae.topP!==void 0,Ve=pe=>Se(pe==="full"||pe==="allow"||pe==="deny"?pe:"ask","h-3.5 w-3.5"),Ke=pe=>pe==="full"?"Full":pe==="allow"?"Allow":pe==="deny"?"Deny":"Ask";return e.jsx(qt,{open:!0,onClose:Ce,title:kt(ae.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ae.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:ae.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:ae.mode==="primary"?"Primary":ae.mode==="subagent"?"Subagent":ae.mode==="all"?"All":"—"})]}),(Y||ce)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),Y&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ae.model.providerID," / ",ae.model.modelID]}),ce&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[ae.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:ae.temperature})]}),ae.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:ae.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"}),H.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:H.map(pe=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:pe},pe))}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ve(ae.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ke(ae.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:[Ve(typeof ae.permission?.bash=="string"?ae.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ke(typeof ae.permission?.bash=="string"?ae.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:[Ve(ae.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ke(ae.permission?.webfetch)})]})]})]})]}),J&&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(gr,{className:"h-4 w-4 text-foreground"})]})})]})})},Rt=()=>{if(!K)return null;const H=L.trim().toLowerCase(),J=s.map(Y=>{const ce=Array.isArray(Y.models)?Y.models:[],Ve=H.length===0?!0:Y.name.toLowerCase().includes(H)||Y.id.toLowerCase().includes(H),Ke=H.length===0?ce:ce.filter(pe=>{const ze=Qe(pe).toLowerCase(),Ye=typeof pe.id=="string"?pe.id.toLowerCase():"";return ze.includes(H)||Ye.includes(H)});return{provider:Y,providerModels:Ke,matchesProvider:Ve}}).filter(({matchesProvider:Y,providerModels:ce})=>Y||ce.length>0);return e.jsx(qt,{open:O==="model",onClose:oe,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(la,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(It,{value:L,onChange:Y=>R(Y.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),L&&e.jsx("button",{type:"button",onClick:()=>R(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(kn,{className:"h-4 w-4"})})]})}),J.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."}),!L&&M.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:M.map(({model:Y,providerID:ce,modelID:Ve})=>{const Ke=ce===t&&Ve===r,pe=u(ce,Ve);return e.jsxs("button",{type:"button",onClick:()=>Be(ce,Ve),className:T("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",Ke?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ut,{providerId:ce,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Qe(Y)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(pe?.limit?.context||pe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[pe?.limit?.context?`${Ot(pe?.limit?.context)} ctx`:"",pe?.limit?.context&&pe?.limit?.output?" • ":"",pe?.limit?.output?`${Ot(pe?.limit?.output)} out`:""]})})]},`fav-mobile-${ce}-${Ve}`)})})]}),!L&&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(Ar,{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:Y,providerID:ce,modelID:Ve})=>{const Ke=ce===t&&Ve===r,pe=u(ce,Ve);return e.jsxs("button",{type:"button",onClick:()=>Be(ce,Ve),className:T("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",Ke?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ut,{providerId:ce,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Qe(Y)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(pe?.limit?.context||pe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[pe?.limit?.context?`${Ot(pe?.limit?.context)} ctx`:"",pe?.limit?.context&&pe?.limit?.output?" • ":"",pe?.limit?.output?`${Ot(pe?.limit?.output)} out`:""]})})]},`recent-mobile-${ce}-${Ve}`)})})]}),J.map(({provider:Y,providerModels:ce})=>{if(ce.length===0&&!H.length)return null;const Ve=Y.id===t,Ke=ue.has(Y.id)||H.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:()=>$e(Y.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Ke,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{providerId:Y.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Y.name}),Ve&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Ke?e.jsx(xt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ns,{className:"h-3 w-3 text-muted-foreground"})]}),Ke&&ce.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:ce.map(pe=>{const ze=Ve&&pe.id===r,Ye=u(Y.id,pe.id),At=Rn(Ye).slice(0,3),He=Ns(Ye,"input");return e.jsxs("div",{className:T("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 last:border-b-0","rounded-lg transition-colors",!ze&&"hover:bg-muted",ze?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Be(Y.id,pe.id),className:T("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Qe(pe)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Ye?.limit?.context||Ye?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Ye?.limit?.context?e.jsxs("span",{children:[Ot(Ye?.limit?.context)," ctx"]}):null,Ye?.limit?.context&&Ye?.limit?.output?e.jsx("span",{children:"•"}):null,Ye?.limit?.output?e.jsxs("span",{children:[Ot(Ye?.limit?.output)," out"]}):null]}),(At.length>0||He.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...At,...He].map(({key:Lt,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-${Y.id}-${pe.id}-${Lt}`))})]})]}),e.jsx("button",{type:"button",onClick:Lt=>{Lt.preventDefault(),Lt.stopPropagation(),I(Y.id,pe.id)},className:T("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",A(Y.id,pe.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":A(Y.id,pe.id)?"Unfavorite":"Favorite",title:A(Y.id,pe.id)?"Remove from favorites":"Add to favorites",children:A(Y.id,pe.id)?e.jsx(gs,{className:"h-4 w-4"}):e.jsx(Bs,{className:"h-4 w-4"})})]},pe.id)})})]},Y.id)})]})})},zt=()=>{if(!K)return null;const H=f.filter(J=>cr(J.mode));return e.jsx(qt,{open:O==="agent",onClose:oe,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[H.map(J=>{const Y=J.name===o,ce=$s(J.name);return e.jsxs("button",{type:"button",className:T("flex w-full flex-col gap-1 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary agent-list-item",ce.class,Y?"active":"border-border/40"),onClick:()=>be(J.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("h-2 w-2 rounded-full",ce.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:Y?{color:`var(${ce.var})`}:void 0,children:kt(J.name)})]}),J.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:J.description})]},J.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:Ze,onClick:()=>{Ze||De(J=>!J)},className:T("flex w-full items-center justify-between gap-2 px-2 py-1.5 text-left bg-transparent","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-t-xl",Ze?"cursor-not-allowed opacity-60":void 0),children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:nt?nt.text:"var(--foreground)",mixBlendMode:"normal"},children:ie})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!nt&&"text-muted-foreground"),style:nt?{color:nt.text}:void 0,children:Se(We,dt)}),e.jsx(xt,{className:T("h-4 w-4 text-muted-foreground transition-transform",ke?"rotate-180":"")})]})]}),ke&&!Ze&&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:it.map(J=>{const Y=J.mode===We,ce=On(J.mode);return e.jsxs("button",{type:"button",disabled:J.disabled,onClick:()=>we(J.mode),className:T("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",J.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",Y?"bg-primary/10":void 0),style:Y&&ce?{backgroundColor:ce.background??void 0}:void 0,children:[Se(J.mode,dt),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:ce?ce.text:"var(--foreground)"},children:J.label})})]},J.mode)})})})]})]})})},us=()=>e.jsx(st,{align:"start",sideOffset:8,className:"max-w-[320px]",children:re?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:re.name||ut()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Je()})]}),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:ye.length>0?ye.map(({key:H,icon:J,label:Y})=>xe(J,Y,`cap-${H}`)):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:Oe.length>0?Oe.map(({key:H,icon:J,label:Y})=>xe(J,`${Y} input`,`input-${H}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:qe.length>0?qe.map(({key:H,icon:J,label:Y})=>xe(J,`${Y} output`,`output-${H}`)):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)"}),ft.map(H=>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:H.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:H.value})]},H.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"}),Ct.map(H=>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:H.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:H.value})]},H.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(re.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(re.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),q=()=>e.jsxs(ot,{delayDuration:1e3,children:[K?e.jsxs("button",{type:"button",onClick:()=>Z("model"),onTouchStart:()=>Fe("model"),onTouchEnd:et,onTouchCancel:et,className:T("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",D&&"flex-1","cursor-pointer hover:opacity-70",mt),children:[t?e.jsx(Ut,{providerId:t,className:T(z,"flex-shrink-0")}):e.jsx(Ds,{className:T(z,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label typography-micro font-medium truncate min-w-0",D?"flex-1":"max-w-[220px]"),children:ut()})]}):e.jsxs(Yt,{open:_e,onOpenChange:Ne,children:[e.jsx(at,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:T("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",mt),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(Ut,{providerId:t,className:T(z,"flex-shrink-0")}),e.jsx(Ds,{className:T(z,"text-primary/60 hidden")})]}):e.jsx(Ds,{className:T(z,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label",ge,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:ut()},`${t}-${r}`)]})})}),e.jsxs(Jt,{className:"max-w-[300px]",children:[M.length>0&&e.jsxs(xn,{children:[e.jsxs(yn,{className:"typography-meta",children:[e.jsx(gs,{className:"h-3 w-3 flex-shrink-0 mr-2 text-primary"}),"Favorites"]}),e.jsx(bn,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(tt,{outerClassName:"max-h-[320px] min-w-[200px]",children:M.map(({model:H,providerID:J,modelID:Y})=>{const ce=u(J,Y),Ve=Rn(ce).map(He=>({...He,id:`cap-${He.key}`})),Ke=[...Ns(ce,"input"),...Ns(ce,"output")],pe=Array.from(new Map(Ke.map(He=>[He.key,He])).values()).map(He=>({...He,id:`mod-${He.key}`})),ze=[...Ve,...pe],Ye=Ot(ce?.limit?.context),At=Ot(ce?.limit?.output);return e.jsx(ht,{className:"typography-meta",onSelect:()=>{Be(J,Y)},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:Qe(H)}),ce?.limit?.context||ce?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ce?.limit?.context?`${Ye} ctx`:"",ce?.limit?.context&&ce?.limit?.output?" • ":"",ce?.limit?.output?`${At} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[ze.map(({id:He,icon:Lt,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(Lt,{className:"h-3 w-3"})},He)),e.jsx("button",{onClick:He=>{He.preventDefault(),He.stopPropagation(),I(J,Y)},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-${J}-${Y}`)})})})]}),C.length>0&&e.jsxs(xn,{children:[e.jsxs(yn,{className:"typography-meta",children:[e.jsx(Ar,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(bn,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(tt,{outerClassName:"max-h-[320px] min-w-[200px]",children:C.map(({model:H,providerID:J,modelID:Y})=>{const ce=u(J,Y),Ve=Rn(ce).map(He=>({...He,id:`cap-${He.key}`})),Ke=[...Ns(ce,"input"),...Ns(ce,"output")],pe=Array.from(new Map(Ke.map(He=>[He.key,He])).values()).map(He=>({...He,id:`mod-${He.key}`})),ze=[...Ve,...pe],Ye=Ot(ce?.limit?.context),At=Ot(ce?.limit?.output);return e.jsx(ht,{className:"typography-meta",onSelect:()=>{Be(J,Y)},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:Qe(H)}),ce?.limit?.context||ce?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ce?.limit?.context?`${Ye} ctx`:"",ce?.limit?.context&&ce?.limit?.output?" • ":"",ce?.limit?.output?`${At} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[ze.map(({id:He,icon:Lt,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(Lt,{className:"h-3 w-3"})},He)),e.jsx("button",{onClick:He=>{He.preventDefault(),He.stopPropagation(),I(J,Y)},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(Bs,{className:"h-3.5 w-3.5"})})]})]})},`recent-${J}-${Y}`)})})})]}),(M.length>0||C.length>0)&&e.jsx(Vn,{}),s.map(H=>{const J=Array.isArray(H.models)?H.models:[];return J.length===0?e.jsxs(ht,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Ut,{providerId:H.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),H.name," (No models)"]},H.id):e.jsxs(xn,{children:[e.jsxs(yn,{className:"typography-meta",children:[e.jsx(Ut,{providerId:H.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),H.name]}),e.jsx(bn,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(tt,{outerClassName:"max-h-[320px] min-w-[200px]",children:J.map(Y=>{const ce=u(H.id,Y.id),Ve=Rn(ce).map(He=>({...He,id:`cap-${He.key}`})),Ke=[...Ns(ce,"input"),...Ns(ce,"output")],pe=Array.from(new Map(Ke.map(He=>[He.key,He])).values()).map(He=>({...He,id:`mod-${He.key}`})),ze=[...Ve,...pe],Ye=Ot(ce?.limit?.context),At=Ot(ce?.limit?.output);return e.jsx(ht,{className:"typography-meta",onSelect:()=>{Be(H.id,Y.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:Qe(Y)}),ce?.limit?.context||ce?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ce?.limit?.context?`${Ye} ctx`:"",ce?.limit?.context&&ce?.limit?.output?" • ":"",ce?.limit?.output?`${At} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[ze.map(({id:He,icon:Lt,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(Lt,{className:"h-3 w-3"})},He)),e.jsx("button",{onClick:He=>{He.preventDefault(),He.stopPropagation(),I(H.id,Y.id)},className:T("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",A(H.id,Y.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":A(H.id,Y.id)?"Unfavorite":"Favorite",title:A(H.id,Y.id)?"Remove from favorites":"Add to favorites",children:A(H.id,Y.id)?e.jsx(gs,{className:"h-3.5 w-3.5"}):e.jsx(Bs,{className:"h-3.5 w-3.5"})})]})]})},Y.id)})})})]},H.id)})]})]}),us()]}),Re=()=>{if(!ae)return e.jsx(st,{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 H=Object.entries(ae.tools||{}).filter(([,pe])=>pe).map(([pe])=>pe).sort(),J=!!(ae.prompt&&ae.prompt.trim().length>0),Y=ae.model?.providerID&&ae.model?.modelID,ce=ae.temperature!==void 0||ae.topP!==void 0,Ve=pe=>Se(pe==="full"||pe==="allow"||pe==="deny"?pe:"ask","h-3.5 w-3.5"),Ke=pe=>pe==="full"?"Full":pe==="allow"?"Allow":pe==="deny"?"Deny":"Ask";return e.jsx(st,{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:kt(ae.name)}),ae.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:ae.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:ae.mode==="primary"?"Primary":ae.mode==="subagent"?"Subagent":ae.mode==="all"?"All":"—"})]}),(Y||ce)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),Y?e.jsxs("span",{className:"typography-meta text-foreground",children:[ae.model.providerID," / ",ae.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),ce&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[ae.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:ae.temperature})]}),ae.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:ae.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"}),H.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:H.map(pe=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:pe},pe))}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ve(ae.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ke(ae.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:[Ve(typeof ae.permission?.bash=="string"?ae.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ke(typeof ae.permission?.bash=="string"?ae.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:[Ve(ae.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ke(ae.permission?.webfetch)})]})]})]}),J&&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(gr,{className:"h-4 w-4 text-foreground"})]})]})})},Ue=()=>K?e.jsxs("button",{type:"button",onClick:()=>Z("agent"),onTouchStart:()=>Fe("agent"),onTouchEnd:et,onTouchCancel:et,className:T("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",mt,"cursor-pointer hover:opacity-70",K&&"ml-1"),children:[e.jsx(Hn,{className:T(z,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${$s(o).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",ge,"font-medium truncate min-w-0"),style:o?{color:`var(${$s(o).var})`}:void 0,children:wt()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(ot,{delayDuration:1e3,children:[e.jsxs(Yt,{children:[e.jsx(at,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",mt),children:[e.jsx(Hn,{className:T(z,"flex-shrink-0",o?"":"text-muted-foreground"),style:o?{color:`var(${$s(o).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",ge,"font-medium min-w-0 truncate",P?"max-w-[220px]":void 0),style:o?{color:`var(${$s(o).var})`}:void 0,children:wt()})]})})}),e.jsxs(Jt,{align:"end",children:[f.filter(H=>cr(H.mode)).map(H=>e.jsx(ht,{className:"typography-meta",onSelect:()=>be(H.name),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("h-1 w-1 rounded-full agent-dot",$s(H.name).class)}),e.jsx("span",{className:"font-medium",children:kt(H.name)})]}),H.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:H.description})]})},H.name)),e.jsx(Vn,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:Ze,onClick:()=>{Ze||le(H=>!H)},className:T("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",Ze?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Pe,"aria-controls":Le,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:nt?nt.text:"var(--foreground)"},children:ie})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!nt&&"text-muted-foreground"),style:nt?{color:nt.text}:void 0,children:Se(We)}),e.jsx(xt,{className:T("h-3.5 w-3.5 transition-transform text-muted-foreground",Pe?"rotate-180":"")})]})]}),Pe&&!Ze&&e.jsx("div",{id:Le,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:it.map(H=>{const J=H.mode===We,Y=On(H.mode);return e.jsxs("button",{type:"button",disabled:H.disabled,onClick:()=>we(H.mode),className:T("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",H.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",J?"bg-primary/10":void 0),style:J&&Y?{backgroundColor:Y.background??void 0}:void 0,children:[Se(H.mode,dt),e.jsx("span",{className:"typography-meta font-medium",style:{color:Y?Y.text:"var(--foreground)"},children:H.label})]},H.mode)})})]})]})]}),Re()]})}),ct=T("@container/model-controls flex items-center min-w-0",U,D&&"w-full",n);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:ct,children:[e.jsx("div",{className:T("flex items-center min-w-0",D?"flex-1 min-w-0 overflow-hidden":"flex-1 min-w-0 justify-end"),children:q()}),e.jsx("div",{className:T("flex items-center min-w-0",U,D&&"flex-shrink-0"),children:Ue()})]}),Rt(),zt(),vt(),gt()]})},bg=n=>n?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(n):!0,wg=(n,s)=>{if(typeof n!="string"||n.length===0)return{sanitizedText:n,mention:null};const t=s.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!n.includes("#"))return{sanitizedText:n,mention:null};let r=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(n))!==null;){const c=i.index,d=c+i[0].length,u=c>0?n[c-1]:null;if(!bg(u))continue;const p={name:o.name,source:{value:i[0],start:c,end:d}};r||(r=p)}}return r?{sanitizedText:n,mention:r}:{sanitizedText:n,mention:null}},Kc=n=>({id:n.id,content:n.content,status:n.status||"pending",priority:n.priority||"medium"}),Ko=Ft()(Wt((n,s)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){n({isLoading:!0});try{const o=(await Me.getSessionTodos(t)).map(Kc);n(a=>{const i=new Map(a.sessionTodos);return i.set(t,o),{sessionTodos:i,isLoading:!1}})}catch(r){console.warn("[TodoStore] Failed to load todos:",r),n({isLoading:!1})}}},updateTodos:(t,r)=>{n(o=>{const a=new Map(o.sessionTodos);return a.set(t,r),{sessionTodos:a}})},getTodosForSession:t=>s().sessionTodos.get(t)||[],clearTodos:t=>{n(r=>{const o=new Map(r.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),vg=(n,s)=>{const t=s.map(Kc);Ko.getState().updateTodos(n,t)},Ui=[{variant:"shine",component:({children:n,className:s,...t})=>e.jsx(pn.span,{...t,className:T("bg-[linear-gradient(110deg,#bfbfbf,35%,#000,50%,#bfbfbf,75%,#bfbfbf)] dark:bg-[linear-gradient(110deg,#404040,35%,#fff,50%,#404040,75%,#404040)]","bg-[length:200%_100%] bg-clip-text text-transparent",s),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:n})},{variant:"generate-effect",component:({children:n,className:s,...t})=>typeof n!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:n.split("").map((r,o)=>de.createElement(pn.span,{...t,key:r+String(o),className:T("inline-block whitespace-pre text-primary-foreground",s),initial:{opacity:0,filter:"blur(4px)",rotateX:90,y:5},whileInView:{opacity:1,filter:"blur(0px)",rotateX:0,y:0},transition:{ease:"easeOut",duration:.3,delay:o*.015},viewport:{once:!0}},r))})},{variant:"glitch",component:({children:n,className:s,...t})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...t,className:T("invisible",s),children:n}),e.jsx("span",{...t,className:T("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",s),children:n}),e.jsx("span",{...t,className:T("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",s),children:n})]})},{variant:"hover-enter",component:({children:n,className:s,...t})=>{if(typeof n!="string")return null;const r=.25,o=.025,a=n.split("").map(i=>i===" "?" ":i);return e.jsxs(pn.span,{...t,className:T("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",s),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((i,c)=>e.jsx(pn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:r,ease:"easeInOut",delay:o*c},children:i},String(c)))}),e.jsx("div",{className:T("absolute inset-0"),children:a.map((i,c)=>e.jsx(pn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:r,ease:"easeInOut",delay:o*c},children:i},String(c)))})]})}},{variant:"shake",component:({children:n,className:s,...t})=>e.jsx("span",{...t,className:T("text-primary-muted hover:animate-text-shake",s),children:n})},{variant:"hover-decoration",component:({children:n,className:s,...t})=>e.jsx("div",{className:T("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:e.jsx("span",{...t,className:T("text-primary-muted",s),children:n})})}];function Co({variant:n="shine",className:s,...t}){const a=Ui.find(i=>i.variant===n)?.component||Ui[0].component;return e.jsx(Al,{children:e.jsx(a,{...t,className:s})})}const jg=2e3,Sg=1500;function kg({statusText:n,isWaitingForPermission:s,wasAborted:t,completionId:r,isComplete:o}){const[a,i]=de.useState(null),[c,d]=de.useState(!1),[u,p]=de.useState(!1),[m,f]=de.useState(!1),[h,g]=de.useState(null),x=de.useRef(0),y=de.useRef([]),b=de.useRef(!1),v=de.useRef(null),N=de.useRef(null),w=de.useRef(null),S=de.useRef(0),j=de.useRef(null),I=de.useRef(!1),A=de.useRef(!1),k=de.useRef(!1),M=de.useRef(!0),C=de.useRef(null),D=de.useRef(null),P=(Z,se)=>{if(v.current&&(clearTimeout(v.current),v.current=null),N.current&&(clearTimeout(N.current),N.current=null),Z==="aborted"){i(null),d(!1),f(!1),g("aborted"),j.current="aborted",I.current=!0,A.current=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p(!0)):p(!0);return}g(null),f(!1),j.current=Z,I.current=!0,i(Z),d(se),u||(typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{p(!0)}):p(!0))};if(de.useEffect(()=>{const Z=Date.now();n?(b.current=!1,a?(n!==a||!!s!==c)&&y.current.push({status:n,permission:!!s}):(P(n,!!s),x.current=Z,y.current=[])):b.current=!0},[n,s,a,c,t]),de.useEffect(()=>{t&&(A.current=!0)},[t]),de.useEffect(()=>{k.current=!!o},[o]),de.useEffect(()=>{o&&(b.current=!0)},[o]),de.useEffect(()=>{const Z=R=>{if(m)return;const oe=j.current!==null||I.current;R&&oe?(f(!1),p(!0),i(null),d(!1),g(R),j.current=null,R==="success"&&r&&(C.current=r),D.current=Date.now(),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{p(!1),g(null),I.current=!1,N.current=null},Sg)):(f(!0),p(!1),g(null),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{i(null),d(!1),f(!1),I.current=!1,j.current=null,v.current=null},180)),A.current=!1};if(!!!(n||a||h!==null||b.current||y.current.length>0||A.current||k.current)){w.current!==null&&(cancelAnimationFrame(w.current),w.current=null);return}const L=R=>{if(R-S.current<150){w.current=requestAnimationFrame(L);return}S.current=R;const oe=Date.now(),Ce=oe-x.current,Ae=b.current&&k.current;if(!Ae&&y.current.length>0&&Ce<jg){w.current=requestAnimationFrame(L);return}if(b.current&&A.current)b.current=!1,y.current=[],Z("aborted");else if(!Ae&&y.current.length>0){const ke=y.current[y.current.length-1];P(ke.status,ke.permission),x.current=oe,y.current=[]}else if(b.current){b.current=!1,y.current.length>0&&(I.current=!0),y.current=[];let ke=null;if(A.current?ke="aborted":k.current&&(ke="success",I.current=!0),ke==="success"&&r&&C.current===r){i(null),d(!1),f(!1),p(!1),g(null),y.current=[],I.current=!1,j.current=null,b.current=!1,A.current=!1,w.current=null;return}Z(ke)}!!(a||h!==null||y.current.length>0||b.current||A.current||k.current)?w.current=requestAnimationFrame(L):w.current=null};return w.current=requestAnimationFrame(L),()=>{w.current!==null&&(cancelAnimationFrame(w.current),w.current=null)}},[n,a,h,o,t,m]),de.useEffect(()=>()=>{v.current&&clearTimeout(v.current),N.current&&clearTimeout(N.current)},[]),de.useEffect(()=>{if(typeof window>"u")return;M.current=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0;const Z=()=>{M.current=!0},se=()=>{M.current=!1};return window.addEventListener("focus",Z),window.addEventListener("blur",se),()=>{window.removeEventListener("focus",Z),window.removeEventListener("blur",se)}},[]),de.useEffect(()=>{const Z=()=>{if(typeof document>"u"||typeof Date>"u"||document.visibilityState!=="visible")return;const se=D.current;(h!==null||a!==null)&&se&&Date.now()-se>500&&(i(null),d(!1),f(!1),p(!1),g(null),y.current=[],I.current=!1,j.current=null,b.current=!1,A.current=!1)};return document.addEventListener("visibilitychange",Z),window.addEventListener("focus",Z),()=>{document.removeEventListener("visibilitychange",Z),window.removeEventListener("focus",Z)}},[a,h]),!a&&h===null)return null;let W;h==="success"?W="Done":h==="aborted"?W="Aborted":a?W=a.charAt(0).toUpperCase()+a.slice(1):W="Working";const K=c?"assertive":"polite",O=h===null?`${W}...`:W;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":K,"aria-label":W,"data-waiting":c?"true":void 0,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[h===null&&e.jsx(Co,{variant:"shine",className:"typography-ui-header",children:O}),h==="success"&&e.jsx(Co,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}),h==="aborted"&&e.jsx(Co,{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"}},Ng=({todo:n})=>{const s=Vi[n.status]||Vi.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:T("flex-1 typography-ui-label",s.textClassName),children:n.content})})},Gi=[],Cg=({isWorking:n,statusText:s,isWaitingForPermission:t,wasAborted:r,abortActive:o,completionId:a,isComplete:i,showAbort:c,onAbort:d,showAbortStatus:u})=>{const[p,m]=l.useState(!1),f=fe(C=>C.currentSessionId),h=Ko(C=>f?C.sessionTodos.get(f)??Gi:Gi),g=Ko(C=>C.loadTodos),{isMobile:x}=je(),y=x||Qt();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]),N=l.useMemo(()=>{const C=h.filter(P=>P.status!=="cancelled").length;return{completed:h.filter(P=>P.status==="completed").length,total:C}},[h]),w=b.length>0,S=!u&&(r||!o),j=n||w||u,I=l.useRef(null);if(l.useEffect(()=>{if(!p)return;const C=D=>{I.current&&!I.current.contains(D.target)&&m(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[p]),!j)return null;const A=()=>m(C=>!C),k=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(kn,{size:18,"aria-hidden":"true"})}):null,M=w?e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!y&&v?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:v.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[N.completed,"/",N.total]}),p?e.jsx(Yn,{className:"h-3.5 w-3.5"}):e.jsx(xt,{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(kn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):S?e.jsx(kg,{statusText:s,isWaitingForPermission:t,wasAborted:r,completionId:a??null,isComplete:i},f??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:I,children:[k,M,p&&w&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:T("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:b.map(C=>e.jsx(Ng,{todo:C},C.id))})]})]})]})})},Mg=n=>!n||typeof n!="object"?!1:!!n.synthetic,Yo=n=>!Array.isArray(n)||n.length===0?!1:n.every(s=>Mg(s)),Ag={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Dg(n){const s=fe(t=>!n||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(n)??"idle");return l.useMemo(()=>{if(s==="idle")return Ag;const t=s==="busy",r=s==="cooldown";return{phase:s,isWorking:t||r,isBusy:t,isCooldown:r}},[s])}function Yc(){const n=fe(s=>s.currentSessionId);return Dg(n)}const Eg={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=n=>n.role==="assistant",Tg=n=>n.type==="reasoning",Xc=n=>n.type==="text",Ki=n=>{if(Xc(n))return n.text;const s=n;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=n=>(Xc(n)||Tg(n),n.time),Ig=n=>{if(n.tool)return n.tool;const s=n;return typeof s.name=="string"?s.name:"tool"};function Jc(){const{currentSessionId:n,messages:s,permissions:t,sessionAbortFlags:r}=fe(ua(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=Yc(),c=l.useMemo(()=>n?s.get(n)??[]:[],[n,s]),d=l.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const h=c.filter(A=>qi(A.info)&&!Yo(A.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const g=[...h].sort((A,k)=>{const M=typeof A.info.time?.created=="number"?A.info.time.created:null,C=typeof k.info.time?.created=="number"?k.info.time.created:null;return M!==null&&C!==null&&M!==C?M-C:A.info.id.localeCompare(k.info.id)}),x=g[g.length-1];let y,b;const v=new Set(["edit","write"]);for(let A=(x.parts??[]).length-1;A>=0;A-=1){const k=x.parts?.[A];if(k)switch(k.type){case"reasoning":{const M=k.time??Yi(k);(!M||typeof M.end>"u")&&!y&&(y="reasoning");break}case"tool":{const M=k.state?.status;if((M==="running"||M==="pending")&&!y){const C=Ig(k);v.has(C)?y="editing":(y="tool",b=C)}break}case"text":{const M=Ki(k)??"";if(typeof M=="string"&&M.trim().length>0){const C=Yi(k);(!C||typeof C.end>"u")&&!y&&(y="text")}break}}}const N={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"},w=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],S=A=>N[A]??`using ${A}`,j=()=>w[Math.floor(Math.random()*w.length)],I=y==="editing"?"editing file":y==="tool"&&b?S(b):y==="reasoning"?"thinking":y==="text"?"composing":j();return{activePartType:y,activeToolName:b,statusText:I}},[c]),u=l.useMemo(()=>{const h=n,g=h?r?.get(h)??null:null,x=!!(g&&!g.acknowledged);return{wasAborted:x,abortActive:x}},[n,r]),p=l.useMemo(()=>{if(u.wasAborted)return{...Eg,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)&&!Yo(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=n;return(h?t?.get(h)??[]:[]).length>0?{...p,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:p},[n,t,p]);return{forming:m,working:f}}const Fg=8,Pg=n=>n==="primary"||n==="all"||n===void 0||n===null,ur=({onOpenSettings:n,scrollToBottom:s})=>{const[t,r]=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,N]=l.useState(null),w=l.useRef(null),S=l.useRef(null),j=l.useRef(null),I=l.useRef(null),A=l.useRef(null),k=fe(q=>q.sendMessage),M=fe(q=>q.currentSessionId),C=fe(q=>q.newSessionDraft?.open),D=fe(q=>q.abortCurrentOperation),P=fe(q=>q.acknowledgeSessionAbort),W=fe(q=>q.abortPromptSessionId),K=fe(q=>q.abortPromptExpiresAt),O=fe(q=>q.clearAbortPrompt),Z=fe(q=>q.attachedFiles),se=fe(q=>q.addAttachedFile),V=fe(q=>q.addServerFile),L=fe(q=>q.clearAttachedFiles),R=fe(q=>q.saveSessionAgentSelection),oe=fe(q=>q.consumePendingInputText),Ce=fe(q=>q.pendingInputText),{currentProviderId:Ae,currentModelId:ue,currentAgentName:me,setAgent:ke,getVisibleAgents:De}=St(),_e=De(),{isMobile:Ne}=je(),{working:Pe}=Jc(),[le,Le]=l.useState(!1),ae=l.useRef(null),Ie=l.useRef(!1),Ge=l.useRef(!1),te=l.useCallback(q=>{if(!Ne||q.pointerType!=="touch")return;const Re=w.current;if(!Re||document.activeElement===Re)return;q.preventDefault(),q.stopPropagation();const Ue=document.scrollingElement;Ue&&Ue.scrollTop!==0&&(Ue.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Re.focus({preventScroll:!0})}catch{Re.focus()}const ct=Re.value.length;try{Re.setSelectionRange(ct,ct)}catch{}},[Ne]);l.useEffect(()=>{if(Ce!==null){const q=oe();q&&(r(q),setTimeout(()=>{w.current?.focus()},0))}},[Ce,oe]);const E=l.useMemo(()=>{if(me)return _e.find(q=>q.name===me)},[_e,me]),ne=l.useMemo(()=>{const q=E?.permission?.edit;let Re="ask";(q==="allow"||q==="ask"||q==="deny"||q==="full")&&(Re=q);const Ue=E?E.tools?.edit!==!1:!1;return(!E||!Ue)&&(Re="deny"),Re},[E]),G=fe(l.useCallback(q=>!M||!me?void 0:q.sessionAgentEditModes.get(M)?.get(me),[M,me])),F=E?.permission?.webfetch,_=E?.permission?.bash,B=l.useMemo(()=>qc({agentDefaultEditMode:ne,webfetchPermission:F,bashPermission:_}),[ne,F,_]),$=!!(M&&me),Q=l.useMemo(()=>$&&G&&B.modeAvailability[G]?G:B.cascadeDefaultMode,[B,$,G]),X=l.useMemo(()=>On(Q),[Q]),Te=l.useCallback(q=>Qt()?`color-mix(in srgb, ${q} 55%, transparent)`:q,[]),We=l.useMemo(()=>{const q=Qt()?1:2;if(!X)return{borderWidth:q};const Re=X.border??X.text;return{borderColor:Te(Re),borderWidth:q}},[X,Te]),it=t.trim()||Z.length>0,nt=Pe.isWorking,Ze=l.useMemo(()=>M?W===M&&!!K:!1,[W,K,M]),lt=async q=>{if(q?.preventDefault(),!it||!M&&!C)return;const Re=t.replace(/^\n+|\n+$/g,"");s?.({instant:!0,force:!0});const Ue=Re.trimStart();if(Ue.startsWith("/")&&Ue.slice(1).trim().split(/\s+/)[0]?.toLowerCase()==="summarize"&&s?.({instant:!0,force:!0}),!Ae||!ue){console.warn("Cannot send message: provider or model not selected");return}const{sanitizedText:ct,mention:H}=wg(Re,_e),J=H?.name,Y=Z.map(ce=>({...ce}));Y.length>0&&L(),r(""),Ne&&w.current?.blur(),await k(ct,Ae,ue,me,Y,J).catch(ce=>{const Ve=ce instanceof Error?ce.message:typeof ce=="string"?ce:String(ce??""),Ke=Ve.toLowerCase();console.error("Message send failed:",Ve||ce),!(Ke.includes("timeout")||Ke.includes("timed out")||Ke.includes("may still be processing")||Ke.includes("being processed")||Ke.includes("failed to fetch")||Ke.includes("networkerror")||Ke.includes("network error")||Ke.includes("gateway timeout")||Ke==="failed to send message")&&(Y.length>0&&zs.setState({attachedFiles:Y}),he.error(Ve||"Message failed to send. Attachments restored."))}),Ne||w.current?.focus()},mt=q=>{if(p&&I.current&&(q.key==="Enter"||q.key==="ArrowUp"||q.key==="ArrowDown"||q.key==="Escape"||q.key==="Tab")){q.preventDefault(),I.current.handleKeyDown(q.key);return}if(g&&A.current&&(q.key==="Enter"||q.key==="ArrowUp"||q.key==="ArrowDown"||q.key==="Escape"||q.key==="Tab")){q.preventDefault(),A.current.handleKeyDown(q.key);return}if(i&&j.current&&(q.key==="Enter"||q.key==="ArrowUp"||q.key==="ArrowDown"||q.key==="Escape"||q.key==="Tab")){q.preventDefault(),j.current.handleKeyDown(q.key);return}if(q.key==="Tab"&&!p&&!i){q.preventDefault(),ge();return}q.key==="Enter"&&!q.shiftKey&&!Ne&&(q.preventDefault(),lt())},dt=l.useCallback(()=>{ae.current&&(clearTimeout(ae.current),ae.current=null),Le(!0),ae.current=setTimeout(()=>{Le(!1),ae.current=null},1800)},[]),z=l.useCallback(()=>{O(),dt(),D()},[D,O,dt]),ge=()=>{const q=_e.filter(H=>Pg(H.mode));if(q.length<=1)return;const Ue=(q.findIndex(H=>H.name===me)+1)%q.length,ct=q[Ue];ke(ct.name),M&&R(M,ct.name)},U=l.useCallback(()=>{const q=w.current;if(!q)return;q.style.height="auto";const Re=q.ownerDocument?.defaultView,Ue=Re?Re.getComputedStyle(q):null,ct=Ue?parseFloat(Ue.lineHeight):NaN,H=Ue?parseFloat(Ue.paddingTop):NaN,J=Ue?parseFloat(Ue.paddingBottom):NaN,Y=22,Ve=Number.isNaN(H)||Number.isNaN(J)?16:H+J,pe=(Number.isNaN(ct)?Y:ct)*Fg+Ve,ze=q.scrollHeight||q.offsetHeight,Ye=Math.min(ze,pe);q.style.height=`${Ye}px`,q.style.maxHeight=`${pe}px`,N(At=>At&&At.height===Ye&&At.maxHeight===pe?At:{height:Ye,maxHeight:pe})},[]);l.useLayoutEffect(()=>{U()},[U,t,Ne]);const ie=l.useCallback((q,Re)=>{if(q.startsWith("/")){const J=q.indexOf(" "),Y=q.indexOf(`
|
|
67
|
+
`),ce=Math.min(J===-1?q.length:J,Y===-1?q.length:Y);if(Re<=ce&&J===-1){const Ve=q.substring(1,ce);h(Ve),m(!0),c(!1),x(!1)}else m(!1);return}m(!1);const Ue=q.substring(0,Re),ct=Ue.lastIndexOf("#");if(ct!==-1){const J=ct>0?Ue[ct-1]:null,Y=Ue.substring(ct+1),ce=Y.includes(" ")||Y.includes(`
|
|
68
|
+
`);if((!J||/\s/.test(J))&&!ce){b(Y),x(!0),c(!1);return}}x(!1),b("");const H=Ue.lastIndexOf("@");if(H!==-1){const J=Ue.substring(H+1);!J.includes(" ")&&!J.includes(`
|
|
69
|
+
`)?(u(J),c(!0)):c(!1)}else c(!1)},[b,h,u,x,m,c]),Se=l.useCallback(q=>{if(!q)return;const Re=w.current;if(!Re){const Y=t+q;r(Y),ie(Y,Y.length),requestAnimationFrame(()=>U());return}const Ue=Re.selectionStart??t.length,ct=Re.selectionEnd??t.length,H=`${t.substring(0,Ue)}${q}${t.substring(ct)}`;r(H);const J=Ue+q.length;requestAnimationFrame(()=>{const Y=w.current;Y&&(Y.selectionStart=J,Y.selectionEnd=J),U()}),ie(H,J)},[U,t,ie]),we=q=>{const Re=q.target.value,Ue=q.target.selectionStart??Re.length;r(Re),U(),ie(Re,Ue)},ve=l.useCallback(async q=>{const Re=new Map;Array.from(q.clipboardData.files||[]).forEach(J=>{J.type.startsWith("image/")&&Re.set(`${J.name}-${J.size}`,J)}),Array.from(q.clipboardData.items||[]).forEach(J=>{if(J.kind==="file"&&J.type.startsWith("image/")){const Y=J.getAsFile();Y&&Re.set(`${Y.name}-${Y.size}`,Y)}});const Ue=Array.from(Re.values());if(Ue.length===0||!M&&!C)return;q.preventDefault();const ct=q.clipboardData.getData("text");ct&&Se(ct);let H=0;for(const J of Ue){const Y=fe.getState().attachedFiles.length;try{await se(J),fe.getState().attachedFiles.length>Y&&(H+=1)}catch(ce){console.error("Clipboard image attach failed",ce),he.error(ce instanceof Error?ce.message:"Failed to attach image from clipboard")}}H>0&&he.success(`Attached ${H} image${H>1?"s":""} from clipboard`)},[se,M,C,Se]),ee=q=>{const Re=w.current?.selectionStart||0,ct=t.substring(0,Re).lastIndexOf("@");if(ct!==-1){const H=t.substring(0,ct)+q.name+t.substring(Re);r(H)}c(!1),u(""),w.current?.focus()},re=q=>{const Ue=w.current?.selectionStart??t.length,H=t.substring(0,Ue).lastIndexOf("#");if(H!==-1){const J=t.substring(0,H)+`#${q} `+t.substring(Ue);r(J);const Y=H+q.length+2;requestAnimationFrame(()=>{w.current&&(w.current.selectionStart=Y,w.current.selectionEnd=Y),U(),ie(J,Y)})}x(!1),b(""),w.current?.focus()},ye=q=>{r(`/${q.name} `);const Re=w.current;Re&&(Re._commandMetadata=q),m(!1),h(""),setTimeout(()=>{w.current&&(w.current.focus(),w.current.setSelectionRange(w.current.value.length,w.current.value.length))},0)};l.useEffect(()=>{M&&w.current&&!Ne&&w.current.focus()},[M,Ne]),l.useEffect(()=>{W&&W!==M&&O()},[W,M,O]);const Oe=q=>{q.preventDefault(),q.stopPropagation(),(M||C)&&!o&&a(!0)},qe=q=>{q.preventDefault(),q.stopPropagation(),q.currentTarget===q.target&&a(!1)},ft=async q=>{if(q.preventDefault(),q.stopPropagation(),a(!1),!M&&!C)return;const Re=Array.from(q.dataTransfer.files);let Ue=0;for(const ct of Re){const H=fe.getState().attachedFiles.length;try{await se(ct),fe.getState().attachedFiles.length>H&&(Ue+=1)}catch(J){console.error("File attach failed",J),he.error(J instanceof Error?J.message:"Failed to attach file")}}Ue>0&&he.success(`Attached ${Ue} file${Ue>1?"s":""}`)},Ct=l.useCallback(async q=>{let Re=0;for(const Ue of q){const ct=fe.getState().attachedFiles.length;try{await V(Ue.path,Ue.name),fe.getState().attachedFiles.length>ct&&(Re+=1)}catch(H){console.error("Server file attach failed",H),he.error(H instanceof Error?H.message:"Failed to attach file")}}Re>0&&he.success(`Attached ${Re} file${Re>1?"s":""}`)},[V]),Et=l.useRef(null),[Pt,Mt]=l.useState(!1),yt=l.useCallback(async q=>{let Re=0;const Ue=Array.isArray(q)?q:Array.from(q);for(const ct of Ue){const H=fe.getState().attachedFiles.length;try{await se(ct),fe.getState().attachedFiles.length>H&&(Re+=1)}catch(J){console.error("File attach failed",J),he.error(J instanceof Error?J.message:"Failed to attach file")}}Re>0&&he.success(`Attached ${Re} file${Re>1?"s":""}`)},[se]),be=l.useCallback(async()=>{try{const Re=await(await fetch("/api/vscode/pick-files")).json(),Ue=Array.isArray(Re?.files)?Re.files:[],ct=Array.isArray(Re?.skipped)?Re.skipped:[];if(ct.length>0){const J=ct.map(Y=>`${Y?.name||"file"}: ${Y?.reason||"skipped"}`).join(`
|
|
70
|
+
`);he.error(`Some files were skipped:
|
|
71
|
+
${J}`)}const H=Ue.map(J=>{if(!J?.dataUrl)return null;try{const[Y,ce]=J.dataUrl.split(","),Ve=J.mimeType||Y?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!ce)return null;const Ke=atob(ce),pe=new Uint8Array(Ke.length);for(let Ye=0;Ye<Ke.length;Ye++)pe[Ye]=Ke.charCodeAt(Ye);const ze=new Blob([pe],{type:Ve});return new File([ze],J.name||"file",{type:Ve})}catch(Y){return console.error("Failed to decode VS Code picked file",Y),null}}).filter(Boolean);H.length>0&&await yt(H)}catch(q){console.error("VS Code file pick failed",q),he.error(q instanceof Error?q.message:"Failed to pick files in VS Code")}},[yt]),Be=l.useCallback(()=>{if(Qt()){be();return}Et.current?.click()},[be]),Qe=l.useCallback(async q=>{const Re=q.target.files;Re&&(await yt(Re),q.target.value="")},[yt]),Je="gap-x-1.5 gap-y-0",ut=Qt(),wt=Ne?"px-1.5 py-1.5":ut?"px-1.5 py-1":"px-2.5 py-1.5",kt=Ne?"h-9 w-9":ut?"h-[22px] w-[22px]":"h-7 w-7",xe=Ne?"h-5 w-5":ut?"h-4 w-4":"h-[18px] w-[18px]",$e=T(kt,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),et=!Ne&&Ze&&nt?e.jsx("button",{type:"button",onClick:z,className:T($e,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(kn,{className:T(xe)})}):e.jsx("button",{type:Ne?"button":"submit",disabled:!it||!M&&!C,onPointerDownCapture:q=>{!Ne||q.pointerType!=="touch"||!it||!M&&!C||(Ge.current=!0,q.preventDefault(),q.stopPropagation(),lt())},onClick:q=>{if(Ne){if(Ge.current){Ge.current=!1;return}q.preventDefault(),lt()}},className:T($e,it&&(M||C)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Ru,{className:T(xe)})}),vt=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Et,type:"file",multiple:!0,className:"hidden",onChange:Qe,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(dg,{onFilesSelected:Ct,multiSelect:!0,presentation:Ne||ut?"modal":"dropdown",open:Pt,onOpenChange:Mt,children:Ne||ut?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Yt,{children:[e.jsx(Xt,{asChild:!0,children:e.jsx("button",{type:"button",className:$e,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(Lu,{className:T(xe,"text-current")})})}),e.jsxs(Jt,{align:"start",children:[e.jsxs(ht,{onSelect:()=>{requestAnimationFrame(()=>Be())},children:[e.jsx($o,{}),"Attach files"]}),e.jsxs(ht,{onSelect:()=>{requestAnimationFrame(()=>{Mt(!0)})},children:[e.jsx(Ou,{}),"Attach from project"]})]})]})]})]}),gt=n?e.jsx("button",{type:"button",onClick:n,className:$e,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(Hn,{className:T(xe,"text-current")})}):null,Rt=e.jsxs(e.Fragment,{children:[vt,gt]}),zt=Pe.statusText;l.useEffect(()=>{const q=!!Pe.wasAborted;!Ie.current&&q&&!le&&(dt(),M&&P(M)),Ie.current=q},[P,M,le,dt,Pe.wasAborted]),l.useEffect(()=>()=>{ae.current&&(clearTimeout(ae.current),ae.current=null)},[]);const us=Ne&&nt;return e.jsxs("form",{onSubmit:lt,className:"pt-0 pb-4 bottom-safe-area",children:[e.jsx(Cg,{isWorking:Pe.isWorking,statusText:zt,isWaitingForPermission:Pe.isWaitingForPermission,wasAborted:Pe.wasAborted,abortActive:Pe.abortActive,completionId:Pe.lastCompletionId,isComplete:Pe.isComplete,showAbort:us,onAbort:z,showAbortStatus:le}),e.jsxs("div",{ref:S,className:T("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Oe,onDragLeave:qe,onDrop:ft,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:$e,onClick:()=>Be(),title:"Attach files","aria-label":"Attach files",children:e.jsx($o,{className:T(xe,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(og,{}),e.jsxs("div",{className:T("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:We,children:[p&&e.jsx(Uc,{ref:I,searchQuery:f,onCommandSelect:ye,onClose:()=>m(!1)}),g&&e.jsx(Vc,{ref:A,searchQuery:y,onAgentSelect:re,onClose:()=>x(!1)}),i&&e.jsx(ag,{ref:j,searchQuery:d,onFileSelect:ee,onClose:()=>c(!1)}),e.jsx(sn,{ref:w,"data-chat-input":"true",value:t,onChange:we,onKeyDown:mt,onPaste:ve,onPointerDownCapture:te,placeholder:M||C?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!M&&!C,className:T("min-h-[52px] resize-none border-0 px-3 shadow-none rounded-t-xl rounded-b-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent",Ne?"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:T("rounded-b-xl bg-transparent",wt,Ne?"flex items-center gap-x-1.5":T("flex items-center justify-between",Je)),"data-chat-input-footer":"true",children:Ne?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:Rt}),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:T("w-full flex items-center justify-end min-w-0")})}),et]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("flex items-center flex-shrink-0",Je),children:Rt}),e.jsxs("div",{className:T("flex items-center flex-1 justify-end",Je,"md:gap-x-3"),children:[e.jsx(Wi,{className:T("flex-1 min-w-0 justify-end")}),et]})]})})]})]})]})};function Mo({className:n,...s}){return e.jsx("div",{"data-slot":"skeleton",className:T("bg-accent animate-pulse rounded-xl",n),...s})}const Xi=(n,s,t,r,o=4)=>{const a=[];for(let i=0;i<o;i++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,p=i/o,m=(i+1)/o,f=(v,N,w)=>v+(N-v)*w,h=(v,N,w,S,j,I)=>{const A=f(v,N,j),k=f(S,w,j);return f(A,k,I)},g={x:h(n.x,s.x,t.x,r.x,d,p),y:h(n.y,s.y,t.y,r.y,d,p)},x={x:h(n.x,s.x,t.x,r.x,u,p),y:h(n.y,s.y,t.y,r.y,u,p)},y={x:h(n.x,s.x,t.x,r.x,u,m),y:h(n.y,s.y,t.y,r.y,u,m)},b={x:h(n.x,s.x,t.x,r.x,d,m),y:h(n.y,s.y,t.y,r.y,d,m)};a.push({path:`M${g.x} ${g.y} L${x.x} ${x.y} L${y.x} ${y.y} L${b.x} ${b.y} Z`,row:i,col:c})}return a},Zc=({className:n="",width:s=70,height:t=70,isAnimated:r=!1})=>{const o=to();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const i=a?"white":"black",c=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",p=48,m=.866,f=.5,h=50,g={x:50,y:h-p},x={x:50-p*m,y:h-p*f},y={x:50+p*m,y:h-p*f},b={x:50,y:h},v={x:50-p*m,y:h+p*f},N={x:50+p*m,y:h+p*f},w={x:50,y:h+p},j=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(g.y+x.y+b.y+y.y)/4})`,I=Xi(x,b,w,v),A=Xi(b,y,N,w),k=de.useMemo(()=>{const M=[];for(let C=0;C<32;C++)M.push(.1+Math.random()*.5);return M},[]);return e.jsxs("svg",{width:s,height:t,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:n,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${b.x} ${b.y} L${x.x} ${x.y} L${v.x} ${v.y} L${w.x} ${w.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),I.map((M,C)=>e.jsx("path",{d:M.path,fill:u,opacity:k[C]},`left-${C}`)),e.jsx("path",{d:`M${b.x} ${b.y} L${y.x} ${y.y} L${N.x} ${N.y} L${w.x} ${w.y} Z`,fill:c,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),A.map((M,C)=>e.jsx("path",{d:M.path,fill:u,opacity:k[C+16]},`right-${C}`)),e.jsx("path",{d:`M${g.x} ${g.y} L${x.x} ${x.y} L${b.x} ${b.y} L${y.x} ${y.y} Z`,fill:"none",stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:r?void 0:1,children:[r&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${j} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function Rg({children:n,className:s,interval:t=2,transition:r={duration:.3},variants:o,onIndexChange:a,trigger:i=!0,mode:c="popLayout"}){const[d,u]=de.useState(0),p=de.Children.toArray(n);de.useEffect(()=>{if(!i)return;const f=t*1e3,h=setInterval(()=>{u(g=>{const x=(g+1)%p.length;return a?.(x),x})},f);return()=>clearInterval(h)},[p.length,t,a,i]);const m={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:T("relative",s),children:[e.jsx("div",{className:"invisible whitespace-nowrap",children:p.map((f,h)=>e.jsx("div",{className:h===0?"":"absolute",children:f},h))}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(_u,{mode:c,initial:!1,children:e.jsx(pn.div,{initial:"initial",animate:"animate",exit:"exit",transition:r,variants:o||m,className:"absolute whitespace-nowrap",children:p[d]},d)})})]})}const Lg=["Fix the failing tests","Refactor this to be more readable","Add form validation","Optimize this function","Write tests for this","Explain how this works","Add a new feature","Help me debug this","Review my code","Simplify this logic","Add error handling","Create a new component","Update the documentation","Find the bug here","Improve performance","Add type definitions"],Og=()=>{const n=to();let s=!0;n?s=n.currentTheme.metadata.variant!=="light":typeof window<"u"&&(s=window.matchMedia("(prefers-color-scheme: dark)").matches);const t=s?"rgba(255,255,255,0.4)":"rgba(0,0,0,0.4)";return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[e.jsx(Zc,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Rg,{className:"text-body-md",interval:4,transition:{duration:.5},children:Lg.map(r=>e.jsxs("span",{style:{color:t},children:['"',r,'…"']},r))})]})},Ao=l.memo(Og),_g={'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"}},$g={'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 r=this.sessionStartTimes.get(t);if(!r)return this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created),!1;const o=s.time.created>r-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 Qc(n){const s=n.colors.syntax,t=n.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:n.colors.status.error,backgroundColor:n.colors.status.errorBackground},inserted:{color:n.colors.status.success,backgroundColor:n.colors.status.successBackground},title:{color:n.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 Vt=({children:n,className:s})=>{const[t,r]=l.useState(!1);return l.useEffect(()=>{let o=null;const a=()=>r(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:T("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",s),children:n})},Bg=({isUser:n,providerID:s,agentName:t,modelName:r,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=Ac(s);return e.jsx(Vt,{children:e.jsx("div",{className:T("pl-3","mb-2"),children:e.jsx("div",{className:T("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:n?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Jr,{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(Yr,{className:"h-4 w-4",style:{color:`var(${$s(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:T("font-bold typography-ui-header tracking-tight leading-none",n?"text-primary":"text-foreground"),children:n?"You":r||"Assistant"}),!n&&t&&e.jsx("div",{className:T("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",$s(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},zg=l.memo(Bg),Ji=(n,s)=>{const t=n[Symbol.toPrimitive];if(typeof t=="function")try{if(t()===s)return n}catch{}try{Object.defineProperty(n,"toString",{value:()=>s,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(n,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0})}catch{}return n},Zi=()=>{if(!Qt()||typeof window>"u")return xi;const n=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(n?.light&&n?.dark){const s=Ji({...n.light},`vscode-shiki-light:${String(n.light?.name??"theme")}`),t=Ji({...n.dark},`vscode-shiki-dark:${String(n.dark?.name??"theme")}`);return[s,t]}return xi},ed=()=>{const[n,s]=l.useState(Zi);return l.useEffect(()=>{if(!Qt()||typeof window>"u")return;const t=r=>{s(Zi())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),n},td=n=>{const s=[],t=[],r=n.querySelector("thead");r&&r.querySelectorAll("th").forEach(i=>s.push(i.innerText.trim()));const o=n.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}},sd=({headers:n,rows:s})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
72
|
+
`)?`"${o.replace(/"/g,'""')}"`:o,r=[];return n.length>0&&r.push(n.map(t).join(",")),s.forEach(o=>r.push(o.map(t).join(","))),r.join(`
|
|
73
|
+
`)},Hg=({headers:n,rows:s})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),r=[];return n.length>0&&r.push(n.map(t).join(" ")),s.forEach(o=>r.push(o.map(t).join(" "))),r.join(`
|
|
74
|
+
`)},Wg=({headers:n,rows:s})=>{if(n.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),r=[];return r.push(`| ${n.map(t).join(" | ")} |`),r.push(`| ${n.map(()=>"---").join(" | ")} |`),s.forEach(o=>{const a=n.map((i,c)=>t(o[c]||""));r.push(`| ${a.join(" | ")} |`)}),r.join(`
|
|
75
|
+
`)},Ug=(n,s,t)=>{const r=new Blob([s],{type:t}),o=URL.createObjectURL(r),a=document.createElement("a");a.href=o,a.download=n,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},Vg=({tableRef:n})=>{const[s,t]=l.useState(!1),[r,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=n.current?.querySelector("table");if(d)try{const u=td(d),p=c==="csv"?sd(u):Hg(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(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:s?e.jsx(Dt,{className:"size-3.5"}):e.jsx(Os,{className:"size-3.5"})}),r&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>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"})]})]})},Gg=({tableRef:n})=>{const[s,t]=l.useState(!1),r=l.useRef(null);l.useEffect(()=>{const a=i=>{r.current&&!r.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=n.current?.querySelector("table");if(i)try{const c=td(i),d=a==="csv"?sd(c):Wg(c);Ug(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:r,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(zn,{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"})]})]})},qg=({children:n,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(Vg,{tableRef:t}),e.jsx(Gg,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:T("w-full border-collapse border border-border",s),"data-streamdown":"table",children:n})})]})},Kg=({children:n,className:s,style:t,...r})=>{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 N=v.indexOf(":");if(N===-1)continue;const w=v.slice(0,N).trim(),S=v.slice(N+1).trim();!w.startsWith("--")||S.length===0||(b[w]=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",{...r,className:T(s),style:c,children:n}),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(Dt,{className:"size-3.5"}):e.jsx(Os,{className:"size-3.5"})})})]})},nd={pre:Kg,table:qg},Yg=({content:n,part:s,messageId:t,isAnimated:r=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const c=ed(),d=l.useMemo(()=>`markdown-${s?.id?`part-${s.id}`:`message-${t}`}`,[t,s?.id]),u=i==="tool"?"streamdown-content streamdown-tool":"streamdown-content",p=e.jsx("div",{className:T("break-words",o),children:e.jsx(_l,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:nd,children:n})});return r?e.jsx(Vt,{children:p},d):p},qn=({content:n,className:s,variant:t="assistant"})=>{const r=ed(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:T("break-words",s),children:e.jsx(_l,{mode:"static",shikiTheme:r,className:o,controls:{code:!1,table:!1},components:nd,children:n})})},Xg={thinking:{label:"Thinking",Icon:Yr},justification:{label:"Justification",Icon:na}},rd=n=>typeof n!="string"||n.trim().length===0?"":n.split(`
|
|
76
|
+
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
77
|
+
`).trim(),Jg=n=>{if(!n)return"";const s=n.trim(),t=s.indexOf(`
|
|
78
|
+
`),r=s.indexOf("."),o=[t>=0?t:1/0,r>=0?r:1/0],a=Math.min(...o);return Number.isFinite(a)?s.substring(0,a).trim():s},Ea=({text:n,variant:s,onContentChange:t,blockId:r})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>Jg(n),[n]),{label:c,Icon:d}=Xg[s];return l.useEffect(()=>{n.trim().length!==0&&t?.("structural")},[t,o,n]),!n||n.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":r,children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(u=>!u),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(xt,{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:T("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(tt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:n})})]})},od=({part:n,onContentChange:s,messageId:t})=>{const r=n,o=r.text||r.content||"",a=l.useMemo(()=>rd(o),[o]);return("time"in n?n.time:null)?.end?e.jsx(Ea,{text:a,variant:"thinking",onContentChange:s,blockId:n.id||`${t}-reasoning`}):null},Zg=n=>rd(n),Qg=({part:n,messageId:s,streamPhase:t,allowAnimation:r,onContentChange:o,renderAsReasoning:a=!1})=>{const i=n,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",u=l.useMemo(()=>a?Zg(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:n.id||`${s}-reasoning-text`},n.id||`${s}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Yg,{content:u,part:n,messageId:s,isAnimated:r,isStreaming:!1})},n.id||`${s}-text`)},ex=n=>`https://opencode.ai/docs/agents/#${encodeURIComponent(n)}`,tx=({part:n,messageId:s,agentMention:t})=>{const r=n,o=r.text,a=typeof o=="string"?o:r.content||r.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:ex(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:T("break-words whitespace-pre-wrap font-sans typography-markdown",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:p,onClick:m,children:f()},n.id||`${s}-user-text`)},sx=l.memo(tx),nx=n=>{let s=n.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},ad=n=>n?n.includes("<file_diagnostics>")||n.includes("This file has errors")||n.includes("please fix"):!1,rx=n=>n?n.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Qi=(n,s)=>!n||typeof n!="object"?String(n):Op(n,s||""),Do=(n,s,t)=>{let r=nx(n);if((s==="edit"||s==="multiedit")&&ad(r)&&(r=rx(r)),(s==="edit"||s==="multiedit")&&r.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return r},ox=(n,s)=>{try{const t=n.trim().split(`
|
|
79
|
+
`).filter(Boolean);if(t.length===0)return null;const r=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,c]=a,d=Math.floor(i.length/2),u=!c.endsWith("/");r.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:T("w-full min-w-0 font-mono space-y-0.5",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Es.tool.popup,children:r.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}},ax=(n,s,t)=>{try{const r=n.trim().split(`
|
|
80
|
+
`).filter(Boolean);if(r.length===0)return null;const o={};return r.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,c,d,u]=i,p=u!==void 0?d:"",m=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:p,content:m})}}),e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Es.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," match",r.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:T("font-medium text-muted-foreground",s?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:T("flex items-start gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},ix=(n,s,t)=>{try{const r=n.trim().split(`
|
|
81
|
+
`).filter(Boolean);if(r.length===0)return null;const o={};r.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",u=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Es.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",r.length," file",r.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:T("font-medium text-muted-foreground",s?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:T("pl-4 grid gap-1",s?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:T("flex items-center gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},i))]})}catch{return null}},lx=(n,s)=>{try{const t=JSON.parse(n);if(!Array.isArray(t))return null;const r={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const i="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:i,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:i,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:T("space-y-3 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style: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]}),r.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",r.in_progress.length]}),r.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",r.pending.length]}),r.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",r.completed.length]}),r.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",r.cancelled.length]})]}),r.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:r.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))})]}),r.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:r.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))})]}),r.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{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:r.completed.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Dt,{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))})]}),r.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:r.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}},cx=(n,s,t)=>{try{return e.jsx("div",{className:T("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Es.tool.popup,children:e.jsx(qn,{content:n,variant:"tool"})})}catch{return null}},id=n=>{const s=n.split(`
|
|
82
|
+
`);let t="";const r=[];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++}r.push({file:t,oldStart:c,newStart:d,lines:u}),o=m;continue}o++}return r},Xo=(n,s,t)=>Pp(s,n,t),ld=n=>{const s="h-3.5 w-3.5 flex-shrink-0",t=n.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx($u,{className:s}):t==="write"||t==="create"||t==="file_write"?e.jsx($l,{className:s}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(Bo,{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(ts,{className:s}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(Bu,{className:s}):t==="glob"?e.jsx(zu,{className:s}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(zo,{className:s}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(zo,{className:s}):t==="todowrite"||t==="todoread"?e.jsx(Hu,{className:s}):t.startsWith("git")?e.jsx(Kt,{className:s}):e.jsx(ma,{className:s})},dx=(n,s,t=Date.now())=>{const o=(s?s-n:t-n)/1e3;return`${(o<.05&&s!==void 0?.1:o).toFixed(1)}s`},ux=({start:n,end:s,active:t})=>{const[r,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:dx(n,s,r)})},mx=n=>{if(!n?.diff||typeof n.diff!="string")return null;const s=n.diff.split(`
|
|
83
|
+
`);let t=0,r=0;for(const o of s)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&r++;return t===0&&r===0?null:{added:t,removed:r}},Jo=(n,s,t)=>{if(t)return n.split("/").pop()||n;if(n.startsWith(s)){const r=n.substring(s.length);return r.startsWith("/")?r.substring(1):r}return n},fx=(n,s,t,r)=>{const o=s,a=o.metadata,i=o.input;if((n.tool==="edit"||n.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return Jo(d,r,t)}if((n.tool==="read"||n.tool==="write")&&i){const d=i?.filePath||i?.file_path||i?.path;if(typeof d=="string")return Jo(d,r,t)}if(n.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(n.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);const c=i?.description||a?.description||"title"in s&&s.title||"";return typeof c=="string"?c:""},Zo=({children:n,maxHeightClass:s="max-h-[60vh]",className:t,outerClassName:r,disableHorizontal:o=!1})=>e.jsx(tt,{outerClassName:T("w-full min-w-0 flex-none overflow-hidden",s,r),className:T("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",t),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:n})}),px=n=>{const s=n.state?.title;return typeof s=="string"&&s.trim().length>0?s:typeof n.tool=="string"&&n.tool.trim().length>0?n.tool:"tool"},hx=n=>n.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),gx=({entries:n,isExpanded:s,hasPrevTool:t,hasNextTool:r,output:o})=>{const a=l.useMemo(()=>n.filter(f=>f.state?.status==="completed"),[n]),i=typeof o=="string"?hx(o):"",c=i.length>0,[d,u]=l.useState(!1);if(a.length===0&&!c)return null;const p=s?a:a.slice(-6),m=Math.max(0,a.length-p.length);return e.jsxs("div",{className:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',t?"before:top-[-0.45rem]":"before:top-[-0.25rem]",r?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[a.length>0?e.jsx(Zo,{maxHeightClass:s?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[m>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",m," more…"]}):null,p.map((f,h)=>{const g=typeof f.tool=="string"&&f.tool.trim().length>0?f.tool:"tool",x=px(f),y=va(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:ld(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:T("space-y-1",a.length>0&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:f=>f.stopPropagation(),onClick:f=>{f.stopPropagation(),u(h=>!h)},children:[d?e.jsx(xt,{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(Zo,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(qn,{content:i,variant:"tool"})})}):null]}):null]})},xx=({diff:n,syntaxTheme:s,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:id(n).map((r,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:`${r.file} (line ${r.oldStart})`}),e.jsx("div",{children:r.lines.map((a,i)=>e.jsxs("div",{className:T("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ys,{style:s,language:on(typeof t?.file_path=="string"?t.file_path:typeof t?.filePath=="string"?t.filePath:r.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))}),yx=({content:n,syntaxTheme:s,filePath:t,displayPath:r})=>{const o=n.split(`
|
|
85
|
+
`),a=on(t??"")||Xo(n,"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:`${r} (${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))})]})},bx=({content:n,filePath:s,displayPath:t})=>{const r=Lp(s),o=s.toLowerCase().endsWith(".svg"),a=l.useMemo(()=>o&&!n.startsWith("data:")?`data:image/svg+xml;base64,${btoa(n)}`:n.startsWith("data:")?n:`data:${r};base64,${n}`,[n,r,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"}})})]})},wx=({part:n,state:s,syntaxTheme:t,isMobile:r,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=n.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=n.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,y=n.tool==="write"&&!!x,b=g?pc(g):!1,v=y?g?Jo(g,o,r):"New file":null,N=l.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&n.tool==="bash"?Qi(u,n.tool):typeof u.content=="string"?u.content??"":Qi(u,n.tool),[u,n.tool]),w=N.trim().length>0,S=(I,A)=>e.jsx(Zo,{maxHeightClass:A?.maxHeightClass,className:A?.className,disableHorizontal:A?.disableHorizontal,outerClassName:A?.outerClassName,children:I}),j=()=>{if(n.tool==="todowrite"||n.tool==="todoread"){if(s.status==="completed"&&m){const I=lx(f,{unstyled:!0});return S(I??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(n.tool==="list"&&m){const I=ox(f,{unstyled:!0});return S(I??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(n.tool==="grep"&&m){const I=ax(f,r,{unstyled:!0});return S(I??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(n.tool==="glob"&&m){const I=ix(f,r,{unstyled:!0});return S(I??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(n.tool==="task"&&m)return S(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(qn,{content:f,variant:"tool"})}));if((n.tool==="web-search"||n.tool==="websearch"||n.tool==="search_web")&&m){const I=cx(f,t,{unstyled:!0});return S(I??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:f}))}if(n.tool==="codesearch"&&m)return S(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(qn,{content:f,variant:"tool"})}));if((n.tool==="edit"||n.tool==="multiedit")&&(!m&&h||f.trim().length===0||ad(f))&&h)return S(e.jsx(xx,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(m&&f.trim()){if(n.tool==="read"){const I=Do(f,n.tool,d),A=I.split(`
|
|
86
|
+
`),k=typeof u?.offset=="number"?u.offset:0,M=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:A.map((D,P)=>{const W=C(D),K=k+P+1,O=!W&&(M===void 0||P<M);return e.jsxs("div",{className:T("typography-code font-mono flex w-full min-w-0",W&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:O?K:""}),e.jsx("div",{className:"flex-1 min-w-0",children:W?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:D}):e.jsx(ys,{style:t,language:Xo(I,n.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:Xo(Do(f,n.tool,d),n.tool,u),PreTag:"div",customStyle:{...xr.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Do(f,n.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:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:n.tool==="todowrite"||n.tool==="todoread"?j():e.jsxs(e.Fragment,{children:[y&&b?e.jsx("div",{className:"my-1",children:S(e.jsx(bx,{content:x,filePath:g,displayPath:v??"New file"}))}):y?e.jsx("div",{className:"my-1",children:S(e.jsx(yx,{content:x,syntaxTheme:t,filePath:g,displayPath:v??"New file"}))}):w?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:N}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,n.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:"}),j()]}),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})]})]})})},kr=({part:n,isExpanded:s,onToggle:t,syntaxTheme:r,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=n.state,u=bt(W=>W.currentDirectory),p=n.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,N=l.useRef({}),w=l.useRef(n.id);if(w.current!==n.id&&(w.current=n.id,N.current={}),p){if(typeof v?.start=="number"){const W=N.current.start;(typeof W!="number"||v.start<W)&&(N.current.start=v.start)}typeof v?.end=="number"&&(N.current.end=v.end)}const S=p?N.current.start??v?.start:v?.start,j=p?N.current.end??v?.end:v?.end,I=l.useMemo(()=>{if(!p)return[];const W=y?.summary;return Array.isArray(W)?W.filter(K=>typeof K=="object"&&K!==null):[]},[p,y]),A=l.useRef(I.length);l.useEffect(()=>{p&&A.current!==I.length&&(A.current=I.length,a?.("structural"))},[p,a,I.length]);const k=n.tool==="edit"||n.tool==="multiedit"?mx(y):null,M=fx(n,d,o,u),C=va(n.tool).displayName,D=l.useContext(ja),P=W=>{if(p||!D?.editor){t(n.id);return}let K;if((n.tool==="edit"||n.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(n.tool))&&(K=b?.filePath||b?.file_path||b?.path||y?.filePath||y?.file_path||y?.path),typeof K=="string"){W.stopPropagation();let O=K;K.startsWith("/")||(O=u.endsWith("/")?u+K:u+"/"+K),D.editor.openFile(O)}else t(n.id)};return!m&&!p?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick: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:W=>{W.stopPropagation(),t(n.id)},children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:!p&&h?{color:"var(--status-error)"}:{},children:ld(n.tool)}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(xt,{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:[M&&e.jsx("span",{className:T("truncate",o&&"max-w-[120px]"),children:M}),k&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",k.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",k.removed]})]}),typeof S=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(ux,{start:S,end:typeof j=="number"?j:void 0,active:!!(p&&f&&typeof j!="number")})})]})]}),p&&(I.length>0||f||m)?e.jsx(gx,{entries:I,isExpanded:s,hasPrevTool:i,hasNextTool:c,output:typeof x.output=="string"?x.output:void 0}):null,!p&&s?e.jsx(wx,{part:n,state:d,syntaxTheme:r,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c}):null]})},vx=n=>typeof n!="string"||n.trim().length===0?"":n.split(`
|
|
87
|
+
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
88
|
+
`).trim(),jx=({part:n,messageId:s,onContentChange:t})=>{const r=n,o=r.text||r.content||"",a=l.useMemo(()=>vx(o),[o]);return("time"in n?n.time:null)?.end?e.jsx(Ea,{text:a,variant:"justification",onContentChange:t,blockId:n.id||`${s}-justification`}):null},Sx=l.memo(jx),kx=n=>{const s={tools:n.filter(r=>r.kind==="tool").length,reasoning:n.filter(r=>r.kind==="reasoning").length,justifications:n.filter(r=>r.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(", ")},el=n=>[...n].sort((s,t)=>{const r=typeof s.endedAt=="number"?s.endedAt:void 0,o=typeof t.endedAt=="number"?t.endedAt:void 0;return r===void 0&&o===void 0?0:r===void 0?1:o===void 0?-1:r-o}),Nx=n=>{const s={},t=n.filter(r=>r.kind==="tool");return t.forEach((r,o)=>{const a=r.part.id;a&&(s[a]={hasPrev:o>0,hasNext:o<t.length-1})}),s},Cx=({parts:n,isExpanded:s,onToggle:t,syntaxTheme:r,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(()=>el(d?n.filter(b=>b.part.id&&u.has(b.id)):n),[n,d,u]),x=kx(g),y=Nx(g);return g.length===0?null:e.jsx(Vt,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl cursor-pointer"),onClick:t,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(El,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(xt,{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:T("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:g.map((b,v)=>{const N=b.part.id||`group-part-${v}`,w=y[N],S=`${N}-exp${f}`;switch(b.kind){case"tool":return e.jsx(Vt,{children:e.jsx(kr,{part:b.part,isExpanded:a.has(N),onToggle:i,syntaxTheme:r,isMobile:o,onContentChange:c,hasPrevTool:w?.hasPrev??!1,hasNextTool:w?.hasNext??!1})},S);case"reasoning":return e.jsx(Vt,{children:e.jsx(od,{part:b.part,messageId:b.messageId,onContentChange:c})},S);case"justification":return e.jsx(Vt,{children:e.jsx(Sx,{part:b.part,messageId:b.messageId,onContentChange:c})},S);default:return null}})})]})})},Mx=l.memo(Cx),Ax=({isMigrating:n,children:s,className:t})=>e.jsx("div",{className:T("w-full overflow-hidden",n&&"pointer-events-none",t),style:n?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:s}),Eo=l.memo(Ax),cd=n=>{const s=n,t=s.text;return typeof t=="string"?t:s.content||s.value||""},dd=n=>{if(n.type!=="text")return!1;const s=cd(n);return!s||s.trim().length===0},Dx=(n,s={})=>{const{includeReasoning:t=!0}=s;return n.filter(r=>!!r.synthetic||!t&&r.type==="reasoning"?!1:!(r.type==="patch"))},Ex=(n,s)=>{const t=l.useRef(null),r=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(n);i.current=n;const c=l.useRef(s);c.current=s;const d=l.useRef(!1),u=s.size>0;return l.useEffect(()=>{n&&n.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),r.current=window.setTimeout(()=>{r.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,n]),l.useEffect(()=>{n&&(!n.isWorking||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),r.current&&(window.clearTimeout(r.current),r.current=null),a(!1),d.current=!1)},[u,n]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),r.current&&window.clearTimeout(r.current)},[]),{isAnimating:o}},Tx=new Set(["task"]),fn=n=>typeof n=="string"&&Tx.has(n.toLowerCase()),Ix=({messageId:n,parts:s,isMobile:t,hasTouchInput:r,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(A=>A.type!=="text"?!1:!dd(A)),[s]),x=d?.token;let y=!1;const b=!!a,v=!!i,N=!!(r??t),w=!!o,S=l.useCallback(()=>{h.current!==null&&typeof window<"u"&&(window.clearTimeout(h.current),h.current=null)},[]),j=l.useCallback(()=>{!N||!b||!w||typeof window>"u"||(S(),f(!0),h.current=window.setTimeout(()=>{f(!1),h.current=null},1800))},[b,S,w,N]);l.useEffect(()=>{w||(f(!1),S())},[S,w]);const I=l.useCallback(A=>{!a||!w||(A.stopPropagation(),A.preventDefault(),a(),N&&j())},[w,N,a,j]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:N&&b&&w?j:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:g.map((A,k)=>{let M;return d&&x&&!y&&cd(A).includes(x)&&(M=d,y=!0),e.jsx(Vt,{children:e.jsx(sx,{part:A,messageId:n,isMobile:t,agentMention:M})},`user-text-${k}`)})}),e.jsx(Hc,{files:s,onShowPopup:c}),b&&w||u&&!p?e.jsxs("div",{className:T("mt-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",m&&"opacity-100 pointer-events-auto"),children:[u&&!p&&e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{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:A=>A.stopPropagation(),onClick:A=>{A.stopPropagation(),u()},children:e.jsx(Bl,{className:"h-3.5 w-3.5"})})}),e.jsx(st,{sideOffset:6,children:"Revert from here"})]}),b&&w&&e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{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:A=>A.stopPropagation(),onClick:I,onFocus:()=>f(!0),onBlur:()=>{v||f(!1)},children:v?e.jsx(Dt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Os,{className:"h-3.5 w-3.5"})})}),e.jsx(st,{sideOffset:6,children:"Copy message"})]})]}):null]})},Fx=({messageId:n,parts:s,isMessageCompleted:t,syntaxTheme:r,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:N=!1,turnGroupingContext:w})=>{const[S,j]=l.useState(!1),I=l.useRef(null),A=!!y,k=!!b,M=!!(a??o),C=!t,D=l.useMemo(()=>s.filter(be=>!dd(be)).filter(be=>be.type!=="compaction"),[s]),P=l.useMemo(()=>D.filter(be=>be.type==="tool"),[D]),W=l.useMemo(()=>D.filter(be=>be.type==="text"),[D]),K=fe(be=>be.createSessionFromAssistantMessage),O=w?.isLastAssistantInTurn??!1,Z=l.useMemo(()=>s.some(be=>be.type==="step-finish"&&be.reason==="stop"),[s]),se=P.length>0,V=l.useMemo(()=>P.some(be=>{const Qe=(be.state??{})?.status;return Qe==="pending"||Qe==="running"||Qe==="started"}),[P]),L=l.useCallback(be=>{const Be=be.state??{},Qe=Be?.status;if(Qe==="pending"||Qe==="running"||Qe==="started")return!1;const Je=Be?.time??{},ut=typeof Je?.end=="number"?Je.end:void 0,wt=typeof Je?.start=="number"?Je.start:void 0;return!(typeof ut!="number"||typeof wt=="number"&&ut<wt)},[]),R=l.useMemo(()=>P.length===0?!0:V?!1:P.every(be=>L(be)),[P,V,L]),oe=l.useMemo(()=>W.length===0?!0:W.every(be=>typeof be.time?.end=="number"),[W]),Ce=l.useMemo(()=>D.filter(be=>be.type==="reasoning"),[D]),Ae=l.useMemo(()=>Ce.length===0?!0:Ce.every(be=>typeof be.time?.end=="number"),[Ce]),me=l.useMemo(()=>{let be=0,Be=0;return D.forEach(Qe=>{Qe.type==="step-start"?be+=1:Qe.type==="step-finish"&&(Be+=1)}),{stepStarts:be,stepFinishes:Be,hasOpenStep:be>Be}},[D]).hasOpenStep,ke=Ce.length>0&&se&&(V||me||!R),De=l.useMemo(()=>se?W.length===0?me||V||!R:!0:W.length>0?ke:!1,[W.length,me,V,se,ke,R]),_e=C||De&&(!oe||!R||V||me)||ke,Ne=C||se&&(V||me||!R),Pe=C||ke,le=se||Ce.length>0,Le=W.length===0,ae=le&&Le&&!Ne&&!Pe&&R&&Ae,Ie=l.useRef(!1),Ge=l.useRef(!1);l.useEffect(()=>{Ge.current=!1},[n]),l.useEffect(()=>{if(!ae){Ie.current=!1;return}Ie.current||(Ie.current=!0,v?.())},[ae,v]),l.useEffect(()=>{if(C){Ge.current=!1;return}if(se){Ge.current=!1;return}Ce.length!==0&&(Pe||!Ae||Ge.current||(Ge.current=!0,h?.("structural")))},[C,se,h,Ae,Ce.length,Pe]);const te=!!x&&!C,E=l.useCallback(()=>{I.current!==null&&typeof window<"u"&&(window.clearTimeout(I.current),I.current=null)},[]),ne=l.useCallback(()=>{!M||!A||!te||typeof window>"u"||(E(),j(!0),I.current=window.setTimeout(()=>{j(!1),I.current=null},1800))},[A,E,te,M]);l.useEffect(()=>{te||(j(!1),E())},[E,te]);const G=l.useCallback(be=>{!y||!te||(be.stopPropagation(),be.preventDefault(),y(),M&&ne())},[te,M,y,ne]),F=l.useCallback(be=>{be.stopPropagation(),be.preventDefault(),K&&K(n)},[K,n]);l.useEffect(()=>()=>{E()},[E]);const _=l.useMemo(()=>{const be={},Be=P.filter(Qe=>fn(Qe.tool)||Ne?!1:L(Qe));return Be.forEach((Qe,Je)=>{be[Qe.id]={hasPrev:Je>0,hasNext:Je<Be.length-1}}),be},[P,Ne,L]),B=l.useMemo(()=>w?.activityParts??[],[w]),$=l.useMemo(()=>w?B.filter(be=>be.messageId===n):[],[B,n,w]),Q=l.useMemo(()=>{const be=new Map;return $.forEach(Be=>{be.set(Be.part,Be)}),be},[$]),X=l.useMemo(()=>w?(N?B:B.filter(Be=>Be.kind==="tool")).filter(Be=>{if(Be.kind!=="tool")return!0;const Qe=Be.part.tool;return!fn(Qe)}):[],[B,N,w]),[Te,We]=l.useState(!1);l.useEffect(()=>{w&&X.length>1&&We(!0)},[w,X.length]);const it=!!(w&&Te),nt=l.useMemo(()=>{if(!w)return[];if(!it)return[];if(!w.isWorking)return[];const be=[];return $.forEach(Be=>{if(w.previewedPartIds.has(Be.id)||!N&&Be.kind!=="tool")return;const Qe=Be.part;if(Be.kind==="tool"){const Je=Qe;if(fn(Je.tool)||Ne||!L(Je))return}else if(Be.kind==="reasoning"){if(!N||Pe||typeof Qe.time?.end!="number")return}else if(Be.kind==="justification"&&(!N||_e||typeof Qe.time?.end!="number"))return;be.push(Be)}),be},[$,L,_e,Pe,Ne,N,it,w]),Ze=l.useMemo(()=>{const be=new Set;return nt.forEach(Be=>{be.add(Be.id)}),be},[nt]),{isAnimating:lt}=Ex(w,Ze),mt=!!(w&&w.activityGroupAnchorMessageId===n&&it&&X.length>0),dt=l.useMemo(()=>P.filter(be=>fn(be.tool)),[P]),z=l.useMemo(()=>{if(!w||!mt)return!1;if(!w.isWorking)return!0;const be=w.previewedPartIds;return X.some(Be=>be.has(Be.id))},[mt,w,X]),ge=l.useRef(null),U=l.useRef(null);l.useEffect(()=>{ge.current=null,U.current=null},[n]);const ie=Date.now();dt.length>0&&ge.current===null&&(ge.current=ie),z&&U.current===null&&(U.current=ie);const Se=!!(dt.length>0&&z&&typeof ge.current=="number"&&typeof U.current=="number"&&U.current>ge.current),we=l.useMemo(()=>{const be=[],Be=()=>{!w||!mt||be.push(e.jsx(Mx,{parts:X,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:r,isMobile:o,expandedTools:d,onToggleTool:u,onShowPopup:p,onContentChange:h,isWorking:w.isWorking,previewedPartIds:w.previewedPartIds,diffStats:w.diffStats},"progressive-group"))};Se||Be(),dt.forEach(Je=>{be.push(e.jsx(Vt,{children:e.jsx(kr,{part:Je,isExpanded:d.has(Je.id),onToggle:u,syntaxTheme:r,isMobile:o,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Je.id}`))}),Se&&Be();const Qe=[];return D.forEach((Je,ut)=>{const wt=Q.get(Je);if(!wt||!w)return;let kt=null,xe=null;if(!it){if(wt.kind==="tool"){const Fe=Je;if(fn(Fe.tool))return;const vt=Fe.state?.time,gt=L(Fe);if(!(!Ne&>))return;const zt=_[Fe.id];xe=e.jsx(Vt,{children:e.jsx(kr,{part:Fe,isExpanded:d.has(Fe.id),onToggle:u,syntaxTheme:r,isMobile:o,onContentChange:h,hasPrevTool:zt?.hasPrev??!1,hasNextTool:zt?.hasNext??!1})},`tool-${Fe.id}`),kt=gt&&typeof vt?.end=="number"?vt.end:null}xe&&Qe.push({part:Je,index:ut,endTime:kt,element:xe});return}if(!w.isWorking||w.isGroupExpanded||w.previewedPartIds.has(wt.id)||!N&&wt.kind!=="tool")return;const $e=Ze.has(wt.id);switch(wt.kind){case"tool":{const Fe=Je;if(fn(Fe.tool))break;const vt=Fe.state?.time,gt=L(Fe);if(!(!Ne&>))break;const zt=_[Fe.id],us=e.jsx(Vt,{children:e.jsx(kr,{part:Fe,isExpanded:d.has(Fe.id),onToggle:u,syntaxTheme:r,isMobile:o,onContentChange:h,hasPrevTool:zt?.hasPrev??!1,hasNextTool:zt?.hasNext??!1})},`tool-${Fe.id}`);xe=$e?e.jsx(Eo,{isMigrating:lt,children:us},`migrating-tool-${Fe.id}`):us,kt=gt&&typeof vt?.end=="number"?vt.end:null;break}case"reasoning":{if(!N)break;const Fe=Je.time,et=typeof Fe?.end=="number";if(!(et&&!Pe))break;const gt=e.jsx(Vt,{children:e.jsx(od,{part:Je,messageId:n,onContentChange:h})},`reasoning-${ut}`);xe=$e?e.jsx(Eo,{isMigrating:lt,children:gt},`migrating-reasoning-${ut}`):gt,kt=et?Fe?.end??null:null;break}case"justification":{if(!N)break;const Fe=Je.time,et=typeof Fe?.end=="number";if(!(et&&!_e))break;const gt=e.jsx(Vt,{children:e.jsx(Qg,{part:Je,messageId:n,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${ut}`);xe=$e?e.jsx(Eo,{isMigrating:lt,children:gt},`migrating-text-${ut}`):gt,kt=et?Fe?.end??null:null;break}}xe&&Qe.push({part:Je,index:ut,endTime:kt,element:xe})}),Qe.sort((Je,ut)=>Je.endTime===null&&ut.endTime===null?Je.index-ut.index:Je.endTime===null?1:ut.endTime===null?-1:Je.endTime-ut.endTime),Qe.forEach(({element:Je})=>{be.push(Je)}),be},[Q,i,b,d,x,lt,o,L,n,h,c,y,p,u,Ze,_e,Pe,Ne,it,g,N,r,_,w,X,D,P,dt,mt,Se]),ve=w?.turnId,ee=fe(be=>be.currentSessionId),re=rt(be=>{if(!ve||!ee)return;const Be=be.messages.get(ee);if(!Be)return;const Qe=Be.find(wt=>wt.info?.id===ve);if(!Qe)return;const ut=Qe.info.summary?.body;return typeof ut=="string"&&ut.trim().length>0?ut:void 0}),ye=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:re,Oe=l.useRef(void 0);ye&&ye.trim().length>0&&(Oe.current=ye);const qe=l.useRef(ve);qe.current!==ve&&(qe.current=ve,Oe.current=void 0);const ft=Oe.current,Ct=w?.isLastAssistantInTurn&&ft&&ft.trim().length>0,Et=x&&W.length>0&&Z&&O,[Pt,Mt]=l.useState(!1),yt=e.jsxs(e.Fragment,{children:[e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{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:be=>be.stopPropagation(),onClick:F,children:e.jsx(Wu,{className:"h-4 w-4"})})}),e.jsx(st,{sideOffset:6,children:"Start new session from this answer"})]}),y&&e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{type:"button",variant:"ghost",size:"icon","data-visible":S||k?"true":void 0,className:T("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!te&&"opacity-50"),disabled:!te,"aria-label":"Copy message text","aria-hidden":!te,onPointerDown:be=>be.stopPropagation(),onClick:G,onFocus:()=>{te&&j(!0)},onBlur:()=>{k||j(!1)},children:k?e.jsx(Dt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Os,{className:"h-3.5 w-3.5"})})}),e.jsx(st,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:T("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:M&&A&&te?ne: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:[we,Ct&&e.jsx(Vt,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Mt(!0),onMouseLeave:()=>Mt(!1),children:[e.jsx(qn,{content:ft}),Et&&e.jsx("div",{className:T("mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",Pt&&"opacity-100 pointer-events-auto"),children:yt})]})},"summary-body")]}),e.jsx(Hc,{files:s,onShowPopup:p}),!Ct&&Et&&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:yt})]})})},Px=({isUser:n,...s})=>n?e.jsx(Ix,{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(Fx,{...s}),tl=l.memo(Px),To=n=>{const s=n,t=s?.clientRole,r=s?.role;return s?.userMessageMarker===!0||t==="user"||r==="user"||s?.origin==="user"||s?.source==="user"?{role:"user",isUser:!0}:{role:t||r||"assistant",isUser:!1}},Rx=l.lazy(()=>vn(()=>import("./ToolOutputDialog-ByonTRPM.js"),__vite__mapDeps([2,0,1,3,4]))),Lx=new Set(["task","edit","multiedit","write","bash"]),sl=n=>typeof n=="string"&&Lx.has(n.toLowerCase());function Io(n){const s=l.useRef({hasValue:!1,value:void 0});return!s.current.hasValue&&n!==void 0&&n!==null&&(s.current={hasValue:!0,value:n}),s.current.hasValue?s.current.value:n}const Cs=(n,s)=>{if(typeof n=="object"&&n!==null)return n[s]},Ox=({message:n,previousMessage:s,nextMessage:t,onContentChange:r,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i,isFirstMessage:c=!1})=>{const{isMobile:d,hasTouchInput:u}=Nt(),{currentTheme:p}=ln(),m=l.useRef(null),f=fe(ua(xe=>({lifecyclePhase:xe.messageStreamStates.get(n.info.id)?.phase??null,isStreamingMessage:(()=>{const $e=n.info.sessionID??xe.currentSessionId??null;return $e?(xe.streamingMessageIds.get($e)??null)===n.info.id:!1})(),currentSessionId:xe.currentSessionId,getCurrentAgent:xe.getCurrentAgent,getSessionAgentSelection:xe.getSessionAgentSelection,getAgentModelForSession:xe.getAgentModelForSession,getSessionModelSelection:xe.getSessionModelSelection}))),{lifecyclePhase:h,isStreamingMessage:g,currentSessionId:x,getCurrentAgent:y,getSessionAgentSelection:b,getAgentModelForSession:v,getSessionModelSelection:N}=f,w=St(xe=>xe.providers),S=je(xe=>xe.showReasoningTraces),j=je(xe=>xe.toolCallExpansion);l.useEffect(()=>{x&&Hs.getInstance().recordSessionStart(x)},[x]);const[I,A]=l.useState(null),[k,M]=l.useState(!1),[C,D]=l.useState(new Set),[P,W]=l.useState({open:!1,title:"",content:""});l.useEffect(()=>{D(new Set)},[n.info.id,j]);const O=l.useMemo(()=>To(n.info),[n.info]).isUser,Z=l.useMemo(()=>O?n.parts.map(xe=>xe.type==="compaction"?{type:"text",text:"/summarize"}:xe):n.parts,[O,n.parts]),se=l.useMemo(()=>{if(O||!s)return null;const xe=Cs(s.info,"clientRole"),$e=Cs(s.info,"role");if((typeof xe=="string"?xe:typeof $e=="string"?$e:void 0)!=="user")return null;const et=Cs(s.info,"mode"),vt=Cs(s.info,"providerID"),gt=Cs(s.info,"modelID"),Rt=typeof et=="string"&&et.trim().length>0?et:void 0,zt=typeof vt=="string"&&vt.trim().length>0?vt:void 0,us=typeof gt=="string"&>.trim().length>0?gt:void 0;return!Rt&&!zt&&!us?null:{agentName:Rt,providerId:zt,modelId:us}},[O,s]),V=l.useMemo(()=>{if(O)return;const xe=Cs(n.info,"mode");if(typeof xe=="string"&&xe.trim().length>0)return xe;if(se?.agentName)return se.agentName;const $e=n.info.sessionID;if(!$e)return;const Fe=y($e);return Fe||(b($e)??void 0)},[O,n.info,se,y,b]),L=n.info.sessionID,R=O?null:Cs(n.info,"providerID"),oe=O?null:Cs(n.info,"modelID"),Ce=l.useMemo(()=>{if(O||!L)return null;if(se?.providerId&&se?.modelId)return{providerId:se.providerId,modelId:se.modelId};if(V){const $e=v(L,V);if($e?.providerId&&$e?.modelId)return $e}const xe=N(L);return xe?.providerId&&xe?.modelId?xe:null},[O,L,V,se,v,N]),Ae=l.useMemo(()=>O?null:typeof R=="string"&&R.trim().length>0?R:Ce?.providerId??null,[O,R,Ce]),ue=l.useMemo(()=>O?null:typeof oe=="string"&&oe.trim().length>0?oe:Ce?.modelId??null,[O,oe,Ce]),me=l.useMemo(()=>{if(!O&&Ae&&ue&&w.length>0){const xe=w.find($e=>$e.id===Ae);if(xe?.models&&Array.isArray(xe.models)){const et=xe.models.find(vt=>vt.id===ue)?.name;return typeof et=="string"?et:void 0}}},[O,Ae,ue,w]),ke=Io(V),De=Io(Ae??void 0),_e=Io(me),Ne=ke??void 0,Pe=De??null,le=_e??void 0,Le=l.useMemo(()=>{const xe=n.info.time;return typeof xe?.completed=="number"?xe.completed:null},[n.info.time]),ae=l.useMemo(()=>O?!0:!!(Le&&Le>0),[O,Le]),Ie=l.useMemo(()=>Dx(Z,{includeReasoning:S}),[Z,S]),Ge=l.useMemo(()=>O||ae?Ie:[],[O,ae,Ie]),te=l.useMemo(()=>O?[]:Ie.filter(xe=>xe.type==="text"),[O,Ie]),E=l.useMemo(()=>O?[]:Ie.filter($e=>$e.type==="tool"),[O,Ie]),ne=l.useMemo(()=>{if(j==="collapsed"||j==="activity")return C;const xe=new Set;for(const Fe of E){const et=Fe.tool;Fe.id&&sl(et)&&xe.add(Fe.id)}if(i?.isFirstAssistantInTurn)for(const Fe of i.activityParts){if(Fe.kind!=="tool")continue;const et=Fe.part;et.id&&sl(et.tool)&&xe.add(et.id)}const $e=new Set(xe);for(const Fe of C)$e.has(Fe)?$e.delete(Fe):$e.add(Fe);return $e},[C,j,E,i]),G=l.useMemo(()=>{if(!O)return;const xe=n.parts.find(vt=>vt.type==="agent");if(!xe)return;const $e=xe,Fe=typeof $e.name=="string"?$e.name:void 0;if(!Fe)return;const et=$e.source&&typeof $e.source.value=="string"&&$e.source.value.trim().length>0?$e.source.value:`#${Fe}`;return{name:Fe,token:et}},[O,n.parts]),_=l.useMemo(()=>{let xe=0,$e=0;return Ie.forEach(Fe=>{Fe.type==="step-start"?xe+=1:Fe.type==="step-finish"&&($e+=1)}),{hasOpenStep:xe>$e}},[Ie]).hasOpenStep,B=l.useMemo(()=>O?!1:te.length===0||E.length===0?_:!0,[te.length,E.length,_,O]),$=p?.metadata.variant,Q=l.useMemo(()=>$?$==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[$]),X=l.useMemo(()=>p?Qc(p):Q?_g:$g,[p,Q]),Te=l.useMemo(()=>O?!1:Hs.getInstance().shouldAnimateMessage(n.info,x||n.info.sessionID),[n.info,x,O]),We=l.useMemo(()=>s?To(s.info):null,[s]),it=l.useMemo(()=>t?To(t.info):null,[t]),nt=l.useMemo(()=>O||!We?!0:We.isUser,[O,We]),Ze=l.useMemo(()=>O||!it?!1:!it.isUser&&it.role==="assistant",[O,it]),lt=l.useMemo(()=>ae?"completed":h||(g?"streaming":"completed"),[ae,h,g]),mt=l.useCallback(xe=>{navigator.clipboard.writeText(xe),A(xe),setTimeout(()=>A(null),2e3)},[]),dt=i?.turnId,z=rt(xe=>{if(!dt)return;const $e=n.info.sessionID;if(!$e)return;const Fe=xe.messages.get($e);if(!Fe)return;const et=Fe.find(Rt=>Rt.info?.id===dt);if(!et)return;const gt=et.info.summary?.body;return typeof gt=="string"&>.trim().length>0?gt:void 0}),ge=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:z,U=l.useRef(void 0);ge&&ge.trim().length>0&&(U.current=ge);const ie=l.useRef(dt);ie.current!==dt&&(ie.current=dt,U.current=void 0);const Se=U.current,we=l.useMemo(()=>O?Ge.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:dc(Ge),[Se,Ge,O]),ve=we.length>0,ee=l.useCallback(()=>{navigator.clipboard.writeText(we),M(!0),setTimeout(()=>M(!1),2e3)},[we]),re=fe(xe=>xe.revertToMessage),ye=l.useCallback(()=>{!L||!n.info.id||re(L,n.info.id)},[L,n.info.id,re]),Oe=l.useCallback(xe=>{D($e=>{const Fe=new Set($e);return Fe.has(xe)?Fe.delete(xe):Fe.add(xe),Fe})},[]),qe=o??null,ft=l.useRef(!1),Ct=l.useRef(!1),Et=l.useRef(!1),Pt=l.useRef(!1),Mt=l.useRef(!1);l.useEffect(()=>{Ct.current=!1,Et.current=!1,Pt.current=!1,Mt.current=!1,ft.current=!1},[n.info.id]);const yt=l.useCallback(()=>{O||ft.current||(ft.current=!0,r?.("structural"))},[O,r]),be=l.useCallback(xe=>{xe.image&&W(xe)},[]),Be=l.useCallback(xe=>{W($e=>({...$e,open:xe}))},[]),Qe=!!Cs(n.info,"animationSettled"),Je=lt==="streaming",ut=l.useMemo(()=>O?!1:Ie.some(xe=>xe.type==="reasoning"),[O,Ie]),wt=Te&&!Qe&&!Je,kt=!O&&Te&&te.length>0&&!B;return l.useEffect(()=>{if(qe?.onStreamingCandidate){if(!kt){Et.current&&(ut&&qe?.onReasoningBlock?qe.onReasoningBlock():qe?.onReservationCancelled&&qe.onReservationCancelled(),Et.current=!1);return}Mt.current||(Mt.current=!0,qe.onStreamingCandidate(),Et.current=!0)}},[qe,kt,ut]),l.useEffect(()=>{qe?.onAnimationStart&&wt&&(Pt.current||(qe.onAnimationStart(),Pt.current=!0))},[qe,wt]),l.useEffect(()=>{if(O)return;const xe=qe?.onAnimatedHeightChange;if(!xe||!(wt||kt))return;const Fe=m.current;if(!Fe)return;if(typeof window>"u"||typeof ResizeObserver>"u"){xe(Fe.getBoundingClientRect().height);return}let et=null;const vt=Rt=>{if(typeof window>"u"){xe(Rt);return}et!==null&&window.cancelAnimationFrame(et),et=window.requestAnimationFrame(()=>{xe(Rt)})},gt=new ResizeObserver(Rt=>{const zt=Rt[0];zt&&vt(zt.contentRect.height)});return gt.observe(Fe),vt(Fe.getBoundingClientRect().height),()=>{et!==null&&(window.cancelAnimationFrame(et),et=null),gt.disconnect()}},[wt,O,qe,kt]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("group w-full",nt?"pt-2":"pt-0",O?"pb-2":Ze?"pb-0":"pb-2"),"data-message-id":n.info.id,ref:m,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:O?e.jsx(Vt,{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(tl,{messageId:n.info.id,parts:Ie,isUser:O,isMessageCompleted:ae,syntaxTheme:X,isMobile:d,hasTouchInput:u,copiedCode:I,onCopyCode:mt,expandedTools:C,onToggleTool:Oe,onShowPopup:be,streamPhase:lt,allowAnimation:wt,onContentChange:r,shouldShowHeader:!1,hasTextContent:ve,onCopyMessage:ee,copiedMessage:k,showReasoningTraces:S,onAuxiliaryContentComplete:yt,agentMention:G,onRevert:ye,isFirstMessage:c})})})}):e.jsxs("div",{children:[nt&&e.jsx(zg,{isUser:O,providerID:Pe,agentName:Ne,modelName:le,isDarkTheme:Q}),e.jsx(tl,{messageId:n.info.id,parts:Ie,isUser:O,isMessageCompleted:ae,syntaxTheme:X,isMobile:d,hasTouchInput:u,copiedCode:I,onCopyCode:mt,expandedTools:ne,onToggleTool:Oe,onShowPopup:be,streamPhase:lt,allowAnimation:wt,onContentChange:r,shouldShowHeader:nt,hasTextContent:ve,onCopyMessage:ee,copiedMessage:k,onAuxiliaryContentComplete:yt,showReasoningTraces:S,agentMention:G,turnGroupingContext:i})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(Rx,{popup:P,onOpenChange:Be,syntaxTheme:X,isMobile:d})})]})},_x=l.memo(Ox),$x=({diff:n,syntaxTheme:s,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:id(n).map((r,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:`${r.file||t?.split("/").pop()||"file"} (line ${r.oldStart})`}),e.jsx("div",{children:r.lines.map((a,i)=>e.jsxs("div",{className:T("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ys,{style:s,language:on(t||r.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))}),Bx=({content:n,syntaxTheme:s,filePath:t})=>{const r=n.split(`
|
|
91
|
+
`),o=on(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(r.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:r.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))})]})},zx=n=>{const s="h-3 w-3",t=n.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($l,{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(zo,{className:s}):e.jsx(ma,{className:s})},Hx=n=>{const s=n.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":n},Wx=({permission:n,onResponse:s})=>{const[t,r]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=fe(),{currentTheme:c}=ln(),d=l.useMemo(()=>Qc(c),[c]),u=async b=>{r(!0);try{await i(n.sessionID,n.id,b),a(!0),s?.(b)}catch{}finally{r(!1)}};if(o)return null;const p=n.type||"Unknown Tool",m=p.toLowerCase(),f=(b,v="")=>{const N=n.metadata[b];return typeof N=="string"?N:typeof N=="number"?String(N):v},h=b=>{const v=n.metadata[b];return typeof v=="number"?v:void 0},g=b=>!!n.metadata[b],x=Hx(p),y=()=>{if(m==="bash"||m==="shell"||m==="shell_command"){const N=f("command")||f("cmd")||f("script"),w=f("description"),S=f("cwd")||f("working_directory")||f("directory")||f("path"),j=h("timeout"),I=n.title===N;return e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:w}),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})]}),j&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",j,"ms"]}),N&&!I&&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:N})})]})}if(m==="edit"||m==="multiedit"||m==="str_replace"||m==="str_replace_based_edit_tool"){const N=f("path")||f("file_path")||f("filename")||f("filePath"),w=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"})}),w&&e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx($x,{diff:w,syntaxTheme:d,filePath:N})})]})}if(m==="write"||m==="create"||m==="file_write"){const N=f("path")||f("file_path")||f("filename")||f("filePath"),w=f("content")||f("text")||f("data");return w?e.jsx(tt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Bx,{content:w,syntaxTheme:d,filePath:N})}):null}if(m==="webfetch"||m==="fetch"||m==="curl"||m==="wget"){const N=f("url")||f("uri")||f("endpoint"),w=f("method")||"GET",S=n.metadata.headers&&typeof n.metadata.headers=="object"?n.metadata.headers:void 0,j=f("body")||f("data")||f("payload"),I=h("timeout"),A=f("format")||f("responseType");return e.jsxs(e.Fragment,{children:[N&&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:w}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:N})]})]}),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(tt,{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)})})]}),j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(tt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(ys,{language:typeof j=="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 j=="object"?JSON.stringify(j,null,2):String(j)})})]}),(I||A)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[I&&e.jsxs("span",{children:["Timeout: ",I,"ms"]}),I&&A&&e.jsx("span",{children:" • "}),A&&e.jsxs("span",{children:["Response format: ",A]})]})]})}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(tt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(b)})})]}),Object.keys(n.metadata).length>0&&!b&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(tt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(n.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(Sn,{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:[zx(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",N=!1;m==="bash"||m==="shell"||m==="shell_command"?(b=f("command")||f("cmd")||f("script"),v="bash",N=!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"),N=!1):(m==="webfetch"||m==="fetch")&&(b=f("url")||f("uri")||f("endpoint"),N=!1);const w=n.title===b;return w&&b&&N?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})}):w&&b&&!N?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})}):n.title?e.jsx("div",{className:T("typography-ui-label text-foreground mb-3",(N||b)&&"font-mono"),children:n.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:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter: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(Dt,{className:"h-3 w-3"}),"Allow Once"]}),e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Ar,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter: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(ds,{className:"h-3 w-3"}),"Deny"]}),t&&e.jsx("div",{className:"ml-auto typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},Ux=new Set(["task"]),Vx=n=>typeof n=="string"&&Ux.has(n.toLowerCase()),Gx=n=>{const s=[];let t=null;return n.forEach(r=>{const o=r.info.clientRole??r.info.role;o==="user"?(t={turnId:r.info.id,userMessage:r,assistantMessages:[]},s.push(t)):o==="assistant"&&t&&t.assistantMessages.push(r)}),s},qx=n=>{for(const s of n.assistantMessages)for(const t of s.parts)if(t.type==="step-finish"){const r=t.reason,o=s.info.finish;if(r==="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}}}},Kx=n=>{const s=qx(n);let t;const o=n.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;n.assistantMessages.forEach(f=>{f.parts.forEach(h=>{h.type==="tool"?a=!0:h.type==="reasoning"&&(i=!0)})});const c=[];let d=0;n.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:n.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:n.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(Vx(h))return}u.set(f.messageId,(u.get(f.messageId)??0)+1)});let p,m=0;for(const f of n.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}},Yx=n=>{const{isWorking:s}=Yc(),t=l.useMemo(()=>Gx(n),[n]),r=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,Kx(y))}),x},[t]),[i,c]=l.useState(()=>new Map),d=je(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),N=v.get(x)??{isExpanded:u,previewedPartIds:new Set},w=new Set(N.previewedPartIds);return y.forEach(S=>{S&&S.trim().length>0&&w.add(S)}),v.set(x,{...N,previewedPartIds:w}),v})},[]),h=l.useCallback(x=>o.get(x),[o]),g=l.useCallback(x=>{const y=o.get(x);if(!y||!y.assistantMessages.some(W=>W.info.id===x))return;const v=a.get(y.turnId),N=v?.activityParts??[],w=!!v?.hasTools,S=!!v?.hasReasoning,j=v?.summaryBody,I=v?.diffStats,A=y.assistantMessages[0]?.info.id,k=x===A,M=y.assistantMessages[y.assistantMessages.length-1]?.info.id,C=x===M,D=p(y.turnId),P=s&&r===y.turnId;return{turnId:y.turnId,isFirstAssistantInTurn:k,isLastAssistantInTurn:C,summaryBody:j,activityParts:N,hasTools:w,hasReasoning:S,diffStats:I,activityGroupAnchorMessageId:v?.activityGroupAnchorMessageId,isWorking:P,isGroupExpanded:D.isExpanded,previewedPartIds:D.previewedPartIds,toggleGroup:()=>m(y.turnId),markPartsPreviewed:W=>f(y.turnId,W)}},[p,r,f,o,s,m,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:g}},Xx=({messages:n,permissions:s,onMessageContentChange:t,getAnimationHandlers:r,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 n.filter(f=>{const h=f.info?.id;if(typeof h=="string"){if(m.has(h))return!1;m.add(h)}return!Yo(f.parts)})},[n]),{getContextForMessage:p}=Yx(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(_x,{message:m,previousMessage:f>0?u[f-1]:void 0,nextMessage:f<u.length-1?u[f+1]:void 0,onContentChange:t,animationHandlers:r(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(Wx,{permission:m},m.id))})]})},Jx=l.memo(Xx);function Zx(...n){return s=>{n.forEach(t=>{typeof t=="function"?t(s):t&&typeof t=="object"&&(t.current=s)})}}const ud=l.forwardRef(({orientation:n="vertical",offset:s=72,size:t=48,isEnabled:r=!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,N,w,S,j)=>{const I=`${S}${j.charAt(0).toUpperCase()}${j.slice(1)}Scroll`;N&&w?(v.dataset[I]="true",v.removeAttribute(`data-${S}-scroll`),v.removeAttribute(`data-${j}-scroll`)):(v.dataset[`${S}Scroll`]=String(N),v.dataset[`${j}Scroll`]=String(w),v.removeAttribute(`data-${S}-${j}-scroll`))},[]),y=l.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(N=>{v.removeAttribute(`data-${N}-scroll`)})},[]),b=l.useCallback(()=>{const v=m.current;if(!v)return;if(!r){y(v);return}const N=n==="vertical"?v.scrollTop>s:v.scrollLeft>s;let w=n==="vertical"?v.scrollTop+v.clientHeight+s<v.scrollHeight:v.scrollLeft+v.clientWidth+s<v.scrollWidth;o&&n==="vertical"&&(w=!1),x(v,N,w,n==="vertical"?"top":"left",n==="vertical"?"bottom":"right");const S=N&&w?"both":N?n==="vertical"?"top":"left":w?n==="vertical"?"bottom":"right":"none";S!==f.current&&(f.current=S,a?.(S))},[y,o,r,s,a,n,x]);return l.useEffect(()=>{const v=m.current;if(!v)return;const N=()=>b(),w=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null,S=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return b(),v.addEventListener("scroll",N,{passive:!0}),w?.observe(v),S?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",N),w?.disconnect(),S?.disconnect()}},[b]),e.jsx("div",{...u,ref:Zx(m,p),className:c,"data-orientation":n,"data-scroll-shadow":h??!0,style:g,children:d})});ud.displayName="ScrollShadow";const Qx=160,ey=({containerRef:n})=>{const[s,t]=l.useState(!0),r=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(N=>{const w=n.current;if(!w){u();return}i.current===null&&(i.current=N);const S=Math.min(1,(N-i.current)/Qx),j=1-Math.pow(1-S,3),I=c.current,A=d.current,k=I+(A-I)*j;if(w.scrollTop=k,S<1){a.current=window.requestAnimationFrame(p);return}w.scrollTop=A,u(),r.current&&(r.current=!1,t(!1))},[u,n,t]),m=l.useCallback((N,w)=>{const S=n.current;if(!S)return;const j=Math.max(0,N),I=w?.instant??!1;if(o.current=!1,typeof window>"u"||I){u(),S.scrollTop=j;const k=j<=1;r.current!==k&&(r.current=k,t(k));return}if(u(),Math.abs(j-S.scrollTop)<=.5){S.scrollTop=j;const k=j<=1;r.current!==k&&(r.current=k,t(k));return}c.current=S.scrollTop,d.current=j,i.current=null,a.current=window.requestAnimationFrame(p)},[u,n,p,t]),f=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),g=l.useCallback(()=>o.current,[]),x=l.useCallback(()=>n.current?.scrollTop??0,[n]),y=l.useCallback(()=>n.current?.scrollHeight??0,[n]),b=l.useCallback(()=>n.current?.clientHeight??0,[n]),v=l.useCallback(()=>{const N=n.current;if(!N)return;o.current&&a.current!==null&&u();const w=N.scrollTop<=1;r.current!==w&&(r.current=w,t(w))},[u,n]);return l.useEffect(()=>{const N=n.current;if(N)return N.addEventListener("wheel",h,{passive:!0}),N.addEventListener("touchstart",h,{passive:!0}),()=>{N.removeEventListener("wheel",h),N.removeEventListener("touchstart",h)}},[n,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])},nl=typeof window<"u"?l.useLayoutEffect:l.useEffect,rl=50,ol=40,ty=.2,sy=.1,ny=150,is=n=>{const s=n.info;return typeof s?.id=="string"?s.id:null},ry=n=>{const s=n.info;if(s?.userMessageMarker===!0)return!0;const t=s?.clientRole,r=s?.role;return t==="user"||r==="user"},oy=({currentSessionId:n,sessionMessages:s,updateViewportAnchor:t,isSyncing:r,isMobile:o,sessionActivityPhase:a})=>{const i=l.useRef(null),c=ey({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),N=l.useRef(s.length>0?is(s[0]):null),w=l.useRef(s.length>0?is(s[s.length-1]):null),S=l.useRef(0),j=l.useRef(0),I=l.useRef(void 0),A=l.useRef(null),k=l.useRef(!1),M=l.useRef(!1),C=n?a?.get(n)??"idle":"idle",D=l.useCallback(ue=>{const me=Math.max(0,ue);S.current!==me&&(S.current=me,m(me))},[]),P=l.useCallback(()=>{const ue=i.current;ue&&(j.current=ue.clientHeight)},[]),W=l.useCallback(()=>{if(!d)return null;const ue=i.current;return ue?ue.querySelector(`[data-message-id="${d}"]`):null},[d]),K=l.useCallback(()=>{const ue=i.current,me=S.current;if(!ue||me<=0)return!0;const ke=ue.scrollHeight-me;return ue.scrollTop+ue.clientHeight<ke},[]),O=l.useCallback((ue,me)=>{const ke=ue.offsetHeight,De=ue.offsetTop;if(ke>me*ty){const Ne=me*sy;return De+ke-Ne}else return De-rl},[]),Z=l.useCallback(()=>{const ue=i.current;if(!ue||!A.current)return;const me=W();if(!me)return;const ke=ue.clientHeight,De=ue.scrollHeight,Ne=O(me,ke)+ke,Pe=S.current,le=De-Pe;if(!k.current&&le<Ne){const Le=Ne-le;Le>Pe&&D(Le)}},[O,W,D]),se=l.useCallback(()=>{const ue=i.current;if(!ue){h(!1);return}if(g){h(!1);return}if(!(ue.scrollHeight>ue.clientHeight)){h(!1);return}const ke=ue.scrollHeight-ue.scrollTop-ue.clientHeight,De=S.current;if(De>0){const _e=ue.scrollHeight-De,Ne=ue.scrollTop+ue.clientHeight;h(Ne<_e)}else h(ke>ol)},[g]),V=l.useCallback(ue=>{const me=i.current;if(!me)return;const ke=me.scrollHeight-me.scrollTop-me.clientHeight;if(M.current&&C==="idle"&&!r&&!ue?.force&&ke>ol)return;ue?.force&&(M.current=!1);const _e=me.scrollHeight-me.clientHeight;c.scrollToPosition(Math.max(0,_e),ue)},[C,r,c]),L=l.useCallback(ue=>{if(y.current===ue)return;y.current=ue,x(ue);const me=i.current;if(!me){x(null);return}const ke=me.scrollHeight,De=S.current,_e=ke-De,Ne=j.current>0?j.current:me.clientHeight,le=_e-rl,Le=le+Ne;let ae=0;_e<Le&&(ae=Le-_e),ae!==De&&D(ae),k.current=!0,window.requestAnimationFrame(()=>{c.scrollToPosition(le,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[c,D]),R=l.useCallback(ue=>{const me=i.current;if(!me||!n)return;ue?.isTrusted&&(M.current=!0),c.handleScroll(),se(),C==="idle"&&S.current>0&&K()&&(D(0),A.current=null,u(null));const{scrollTop:ke,scrollHeight:De,clientHeight:_e}=me,Ne=(ke+_e/2)/Math.max(De,1),Pe=Math.floor(Ne*s.length);t(n,Pe)},[n,C,K,c,s.length,se,D,t]);l.useEffect(()=>{const ue=i.current;if(ue)return ue.addEventListener("scroll",R,{passive:!0}),()=>{ue.removeEventListener("scroll",R)}},[R]),nl(()=>{if(typeof window>"u")return;P();const ue=()=>{I.current!==void 0&&window.clearTimeout(I.current),I.current=window.setTimeout(()=>{P()},ny)};return window.addEventListener("resize",ue),()=>{window.removeEventListener("resize",ue),I.current!==void 0&&window.clearTimeout(I.current)}},[P]),l.useEffect(()=>{n&&n!==b.current&&(b.current=n,Hs.getInstance().recordSessionStart(n),v.current=s.length,N.current=s.length>0?is(s[0]):null,w.current=s.length>0?is(s[s.length-1]):null,y.current=null,A.current=null,k.current=!1,u(null),S.current=0,m(0),x(null),h(!1),M.current=!1)},[n,s.length]),nl(()=>{if(r){v.current=s.length,N.current=s.length>0?is(s[0]):null,w.current=s.length>0?is(s[s.length-1]):null;return}if(b.current!==n)return;const ue=v.current,me=s.length;if(me>ue&&ue>0){const ke=N.current,De=is(s[0]),_e=is(s[me-1]),Ne=w.current,Pe=ke!==null&&De!==ke,le=Ne!==null&&_e!==Ne,Le=Pe&&!le,ae=le&&!Pe;if(Le){A.current=null,k.current=!1,u(null),D(0),v.current=me,N.current=De,w.current=_e;return}if(ae){const Ge=s.slice(ue,me).find(ry);if(Ge){const te=is(Ge);te&&(A.current=te,u(te),L(te))}else Z()}}v.current=me,N.current=s.length>0?is(s[0]):null,w.current=s.length>0?is(s[s.length-1]):null},[n,r,Z,L,s]),l.useEffect(()=>{const ue=i.current;if(!ue||typeof ResizeObserver>"u")return;const me=new ResizeObserver(()=>{Z(),se()});return me.observe(ue),()=>{me.disconnect()}},[Z,se]),l.useEffect(()=>{if(typeof window>"u"){se();return}const ue=window.requestAnimationFrame(()=>{se()});return()=>{window.cancelAnimationFrame(ue)}},[n,s.length,se]),l.useEffect(()=>{d&&(Z(),se())},[d,Z,se]),l.useEffect(()=>{C==="idle"&&S.current>0&&K()&&(D(0),A.current=null,k.current=!1,u(null))},[C,K,D]),l.useEffect(()=>{se()},[p,se]);const oe=l.useRef(new Map),Ce=l.useCallback(()=>{Z(),se()},[Z,se]),Ae=l.useCallback(ue=>{const me=oe.current.get(ue);if(me)return me;const ke={onChunk:()=>{Z()},onComplete:()=>{Z()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{Z()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return oe.current.set(ue,ke),ke},[Z]);return{scrollRef:i,handleMessageContentChange:Ce,getAnimationHandlers:Ae,showScrollButton:f,scrollToBottom:V,spacerHeight:p,pendingAnchorId:g,hasActiveAnchor:d!==null}},ay=()=>{const{currentSessionId:n,messages:s,permissions:t,streamingMessageIds:r,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,sessionMemoryState:d,openNewSessionDraft:u,isSyncing:p,messageStreamStates:m,trimToViewportWindow:f,sessionActivityPhase:h,newSessionDraft:g}=fe(),x=l.useMemo(()=>n?r.get(n)??null:null,[n,r]),{isMobile:y}=Nt(),b=!!g?.open;l.useEffect(()=>{!n&&!b&&u()},[n,b,u]);const v=l.useMemo(()=>n?s.get(n)||[]:[],[n,s]),N=l.useMemo(()=>n?t.get(n)||[]:[],[n,t]),{scrollRef:w,handleMessageContentChange:S,getAnimationHandlers:j,showScrollButton:I,scrollToBottom:A,spacerHeight:k,pendingAnchorId:M,hasActiveAnchor:C}=oy({currentSessionId:n,sessionMessages:v,updateViewportAnchor:c,isSyncing:p,isMobile:y,sessionActivityPhase:h}),P=!!l.useMemo(()=>n?d.get(n)??null:null,[n,d])?.hasMoreAbove,[W,K]=l.useState(!1);l.useEffect(()=>{K(!1)},[n]);const O=l.useRef(null);l.useLayoutEffect(()=>{if(!n||n===O.current)return;O.current=n;const se=w.current;se&&(se.scrollTop=se.scrollHeight-se.clientHeight)},[n,w]);const Z=l.useCallback(async()=>{if(!n||W)return;const se=w.current,V=se?.scrollHeight??null,L=se?.scrollTop??null;K(!0);try{if(await i(n,"up"),se&&V!==null&&L!==null){const R=se.scrollHeight-V;se.scrollTop=L+R}}finally{K(!1)}},[n,W,i,w]);return l.useEffect(()=>{if(!n||(s.has(n)?s.get(n)??[]:[]).length>0)return;(async()=>{try{await a(n)}finally{typeof window>"u"?A():window.requestAnimationFrame(()=>{A()})}})()},[n,a,s,A]),!n&&!b?e.jsx("div",{className:"flex flex-col h-full bg-background",style:y?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(Ao,{})}):!n&&b?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:y?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Ao,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(ur,{scrollToBottom:A})})]}):n?o&&v.length===0&&!x&&!s.has(n)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:y?{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(V=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Mo,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Mo,{className:"h-4 w-24"}),e.jsx(Mo,{className:"h-20 w-full"})]})]},V))})}),e.jsx(ur,{scrollToBottom:A})]}):v.length===0&&!x?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:y?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Ao,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(ur,{scrollToBottom:A})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:y?{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(ud,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:w,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!M,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(Jx,{messages:v,permissions:N,onMessageContentChange:S,getAnimationHandlers:j,hasMoreAbove:P,isLoadingOlder:W,onLoadOlder:Z,scrollToBottom:A,pendingAnchorId:M}),k>0&&C&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:k},"aria-hidden":"true"})]})}),e.jsx(wa,{containerRef:w})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[I&&v.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>A({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(An,{className:"h-4 w-4"})})}),e.jsx(ur,{scrollToBottom:A})]})]}):null};class iy 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(bc,{className:"text-center",children:e.jsxs(wc,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Uu,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(vc,{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(Ee,{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 Qo=()=>{const n=fe(s=>s.currentSessionId);return e.jsx(iy,{sessionId:n||void 0,children:e.jsx(ay,{})})},al=12,ly=[{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"}],cy=({isActive:n,burstKey:s=0,className:t,durationMs:r=900,bursts:o=ly,onComplete:a})=>{const i=de.useRef(!1);de.useEffect(()=>{!n&&i.current&&a?.(),n&&(i.current=!0)},[n,a]);const c=de.useMemo(()=>Array.from({length:al},(d,u)=>{const p=Math.PI*2*u/al;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return n?e.jsx("div",{className:T("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}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},dy=({durationMs:n=3400}={})=>{const[s,t]=de.useState({isActive:!1,cycle:0}),r=de.useRef(null),o=de.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=de.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=de.useCallback(()=>{o(),t(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{t(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},n)},[o,n]);return de.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:i,dismissFireworks:a}},md=l.createContext(void 0),il=({children:n})=>{const{isActive:s,burstKey:t,triggerFireworks:r,dismissFireworks:o}=dy(),a=l.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return e.jsxs(md.Provider,{value:a,children:[n,e.jsx(cy,{isActive:s,burstKey:t})]})},uy=()=>{const n=l.useContext(md);if(!n)throw new Error("useFireworksCelebration must be used within FireworksProvider");return n},my=n=>n.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),fy=({currentBranch:n,localBranches:s,remoteBranches:t,branchInfo:r,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(()=>my(h),[h]),N=l.useMemo(()=>{const k=u.toLowerCase();return k?s.filter(M=>M.toLowerCase().includes(k)):s},[u,s]),w=l.useMemo(()=>{const k=u.toLowerCase();return k?t.filter(M=>M.toLowerCase().includes(k)):t},[u,t]),S=k=>{if(k===n){d(!1);return}o(k),d(!1),p("")},j=()=>{f(!0),setTimeout(()=>b.current?.focus(),50)},I=async()=>{if(!(!v||x)){y(!0);try{await a(v),g(""),f(!1),d(!1)}finally{y(!1)}}},A=()=>{g(""),f(!1)};return l.useEffect(()=>{c||(p(""),f(!1),g(""))},[c]),e.jsxs(Yt,{open:c,onOpenChange:d,children:[e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs(Ee,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx(Kt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:n||"Detached HEAD"}),e.jsx(xt,{className:"size-4 opacity-60"})]})})}),e.jsxs(st,{sideOffset:8,children:["Switch branch (",s.length," local · ",t.length," remote)"]})]}),e.jsx(Jt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Rc,{className:"h-full min-h-0",children:[e.jsx(Lc,{placeholder:"Search branches...",value:u,onValueChange:p}),e.jsxs(Oc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(_c,{children:"No branches found."}),e.jsx(wn,{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:k=>g(k.target.value),onKeyDown:k=>{k.key==="Enter"?(k.preventDefault(),I()):k.key==="Escape"&&(k.preventDefault(),A())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:I,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(os,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:A,disabled:x,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(ds,{className:"size-4"})})]}):e.jsxs(Tt,{onSelect:j,children:[e.jsx(os,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Ur,{}),e.jsxs(wn,{heading:"Local branches",children:[N.map(k=>e.jsxs(Tt,{onSelect:()=>S(k),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:k}),(r?.[k]?.ahead||r?.[k]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[k].ahead||0," ahead ·"," ",r[k].behind||0," behind"]})]}),n===k&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${k}`)),N.length===0&&e.jsx(Tt,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Ur,{}),e.jsxs(wn,{heading:"Remote branches",children:[w.map(k=>e.jsx(Tt,{onSelect:()=>S(k),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:k})},`remote-${k}`)),w.length===0&&e.jsx(Tt,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},py=({syncAction:n,onFetch:s,onPull:t,onPush:r,disabled:o})=>{const a=o||n!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:s,disabled:a,children:[n==="fetch"?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(Qr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(st,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[n==="pull"?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(An,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(st,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[n==="push"?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(Xn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(st,{sideOffset:8,children:"Push changes"})]})]})},hy={branch:Kt,briefcase:ia,house:aa,graduation:oa,code:ws,heart:Fl,user:Jr},gy={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 fd(n){return n&&gy[n]||"var(--primary)"}const ll=({icon:n,className:s,colorToken:t})=>{const r=hy[n??"branch"]??Jr;return e.jsx(r,{className:s,style:{color:fd(t)}})},xy=({activeProfile:n,identities:s,onSelect:t,isApplying:r})=>{const o=r||s.length===0;return e.jsxs(Yt,{children:[e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Xt,{asChild:!0,children:e.jsxs(Ee,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:fd(n?.color)},disabled:o,children:[r?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(ll,{icon:n?.icon,colorToken:n?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:n?.name||"No identity"}),e.jsx(xt,{className:"size-4 opacity-60"})]})})}),e.jsxs(st,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:n?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:n?.userEmail||"No email configured"})]})]}),e.jsx(Jt,{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(ht,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ll,{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))})]})},yy=({status:n,localBranches:s,remoteBranches:t,branchInfo:r,syncAction:o,onFetch:a,onPull:i,onPush:c,onCheckoutBranch:d,onCreateBranch:u,activeIdentityProfile:p,availableIdentities:m,onSelectIdentity:f,isApplyingIdentity:h,isWorktreeMode:g})=>n?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(fy,{currentBranch:n.current,localBranches:s,remoteBranches:t,branchInfo:r,onCheckout:d,onCreate:u}),n.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(Xn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:n.ahead})]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(An,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:n.behind})]})]}),e.jsx(py,{syncAction:o,onFetch:a,onPull:i,onPush:c,disabled:!n}),e.jsx("div",{className:"flex-1"}),e.jsx(xy,{activeProfile:p,identities:m,onSelect:f,isApplying:h})]}):null,by=({behind:n,onPull:s,isPulling:t})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(sa,{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"}),n>0&&e.jsxs(Ee,{variant:"outline",onClick:s,disabled:t,children:[t?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(An,{className:"size-4"}),"Pull ",n," commit",n===1?"":"s"]})]}),pd={"?":{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"}},wy=pd.M;function vy(n){const s=n.index?.trim(),t=n.working_dir?.trim();return s&&s!=="?"?s.charAt(0):t?t.charAt(0):s?.charAt(0)||t?.charAt(0)||"M"}function jy(n){const s=vy(n);return pd[s]??wy}const Sy=l.memo(function({file:s,checked:t,onToggle:r,onViewDiff:o,onRevert:a,isReverting:i,stats:c}){const d=de.useMemo(()=>jy(s),[s]),u=d.description,p=c?.insertions??0,m=c?.deletions??0,f=de.useCallback(x=>{x.key===" "?(x.preventDefault(),r()):x.key==="Enter"&&(x.preventDefault(),o())},[r,o]),h=de.useCallback(x=>{x.preventDefault(),x.stopPropagation(),r()},[r]),g=de.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(ca,{className:"size-4 text-primary"}):e.jsx(da,{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(ot,{delayDuration:200,children:[e.jsx(at,{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(Qr,{className:"size-3.5"})})}),e.jsx(st,{sideOffset:8,children:"Revert changes"})]})]})})}),ky=({changeEntries:n,selectedPaths:s,diffStats:t,revertingPaths:r,onToggleFile:o,onSelectAll:a,onClearSelection:i,onViewDiff:c,onRevertFile:d})=>{const u=s.size,p=n.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(Ee,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Ee,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(tt,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:n.map(m=>e.jsx(Sy,{file:m,checked:s.has(m.path),stats:t?.[m.path],onToggle:()=>o(m.path),onViewDiff:()=>c(m.path),onRevert:()=>d(m.path),isReverting:r.has(m.path)},m.path))})})]})},hd=Vu,Ny=({className:n,...s})=>e.jsx(qu,{className:T("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",n),...s}),gd=({className:n,...s})=>e.jsx(Gu,{className:T("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",n),...s}),Fo=38,cl=200,Cy=({value:n,onChange:s,placeholder:t="Commit message",disabled:r=!1})=>{const o=l.useRef(null);return l.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${Fo}px`;const i=Math.min(Math.max(a.scrollHeight,Fo),cl);a.style.height=`${i}px`},[n]),e.jsx(sn,{ref:o,value:n,onChange:a=>s(a.target.value),placeholder:t,rows:1,disabled:r,className:T("rounded-lg bg-background/80 resize-none overflow-y-auto",r&&"opacity-50"),style:{minHeight:Fo,maxHeight:cl}})},My=({highlights:n,onInsert:s,onClear:t})=>{if(n.length===0)return null;const r=()=>{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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{variant:"ghost",size:"icon",className:"size-6",onClick:r,"aria-label":"Insert highlights into commit message",children:e.jsx(An,{className:"size-4"})})}),e.jsx(st,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:n.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},Ay=({selectedCount:n,commitMessage:s,onCommitMessageChange:t,generatedHighlights:r,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:p,isBusy:m})=>{const f=n>0,h=s.trim()&&f&&p===null;return e.jsxs(hd,{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?`${n} file${n===1?"":"s"} selected`:"No files selected"})]}),e.jsx(gd,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(My,{highlights:r,onInsert:o,onClear:a}),e.jsx(Cy,{value:s,onChange:t,placeholder:"Commit message",disabled:p!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:c||p!==null||n===0||m,"aria-label":"Generate commit message",children:c?e.jsx(Bt,{className:"size-4 animate-spin"}):e.jsx(Ku,{className:"size-4 text-primary"})})}),e.jsx(st,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Hr,{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(sa,{className:"size-4"}),"Commit"]})}),e.jsx(Hr,{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(Xn,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function Dy({...n}){return e.jsx(Yu,{"data-slot":"select",...n})}function Ey({...n}){return e.jsx(Zu,{"data-slot":"select-value",...n})}function Ty({className:n,size:s="default",children:t,...r}){return e.jsxs(Xu,{"data-slot":"select-trigger","data-size":s,className:T("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-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",n),...r,children:[t,e.jsx(Ju,{asChild:!0,children:e.jsx(xt,{className:"size-4 opacity-50"})})]})}function Iy({className:n,children:s,position:t="popper",...r}){return e.jsx(Qu,{children:e.jsxs(em,{"data-slot":"select-content",className:T("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n),position:t,...r,children:[e.jsx(Py,{}),e.jsx(tt,{as:tm,outerClassName:"max-h-[var(--radix-select-content-available-height)] w-full",className:T("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:s}),e.jsx(Ry,{})]})})}function Fy({className:n,children:s,...t}){return e.jsxs(sm,{"data-slot":"select-item",className:T("hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",n),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(nm,{children:e.jsx(Dt,{className:"size-4"})})}),e.jsx(rm,{children:s})]})}function Py({className:n,...s}){return e.jsx(om,{"data-slot":"select-scroll-up-button",className:T("flex cursor-default items-center justify-center py-1",n),...s,children:e.jsx(Yn,{className:"size-4"})})}function Ry({className:n,...s}){return e.jsx(am,{"data-slot":"select-scroll-down-button",className:T("flex cursor-default items-center justify-center py-1",n),...s,children:e.jsx(xt,{className:"size-4"})})}function dl(n){const s=new Date(n);return Number.isNaN(s.getTime())?n:s.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function Ly(n){switch(n){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 Oy=({entry:n,isExpanded:s,onToggle:t,files:r,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:T("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",s?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:n.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:n.author_name,children:n.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:dl(n.date),children:dl(n.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:n.hash.slice(0,8)}),e.jsxs(ot,{delayDuration:500,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(n.hash)},children:e.jsx(Os,{className:"size-3"})})}),e.jsx(st,{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..."})]}):r.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:r.map(i=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:T("font-semibold w-3 text-center",Ly(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))})})]}),_y=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],$y=({log:n,isLogLoading:s,logMaxCount:t,onLogMaxCountChange:r,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:c,onCopyHash:d})=>{const[u,p]=l.useState(!0);return n?e.jsxs(hd,{open:u,onOpenChange:p,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Ny,{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(Dy,{value:String(t),onValueChange:m=>r(Number(m)),disabled:s,children:[e.jsx(Ty,{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(Ey,{placeholder:"Commits"})}),e.jsx(Iy,{children:_y.map(m=>e.jsx(Fy,{value:String(m.value),children:m.label},m.value))})]})}),u?e.jsx(Yn,{className:"size-4 text-muted-foreground"}):e.jsx(xt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(gd,{children:e.jsx(tt,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:n.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:n.all.map(m=>e.jsx(Oy,{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 Ln=null;const By=()=>{const{currentSessionId:n,sessions:s,worktreeMetadata:t}=fe(),{currentDirectory:r}=bt(),o=n?t.get(n)??void 0:void 0,i=s.find(c=>c.id===n)?.directory;return o?.path??i??r??void 0},zy=()=>{const{git:n}=an(),s=By(),{currentSessionId:t,worktreeMetadata:r}=fe(),o=t?r.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=so(),u=fc(s??null),p=mc(s??null),m=Mp(s??null),f=Ap(s??null),h=Dp(s??null),g=jt(ee=>ee.isLoadingStatus),x=jt(ee=>ee.isLoadingLog),{setActiveDirectory:y,fetchAll:b,fetchStatus:v,fetchBranches:N,fetchLog:w,fetchIdentity:S,setLogMaxCount:j}=jt(),I=l.useMemo(()=>!Ln||Ln.directory!==s?null:Ln,[s]),[A,k]=l.useState(I?.commitMessage??""),[M,C]=l.useState(null),[D,P]=l.useState(null),[W,K]=l.useState(25),[O,Z]=l.useState(!1),{triggerFireworks:se}=uy(),[V,L]=l.useState(()=>new Set(I?.selectedPaths??[])),[R,oe]=l.useState(!1),[Ce,Ae]=l.useState(new Set),[ue,me]=l.useState(!1),[ke,De]=l.useState([]),_e=l.useCallback(()=>{De([])},[]),[Ne,Pe]=l.useState(new Set),[le,Le]=l.useState(new Map),[ae,Ie]=l.useState(new Set),Ge=l.useCallback(ee=>{navigator.clipboard.writeText(ee).then(()=>{he.success("Commit hash copied")}).catch(()=>{he.error("Failed to copy")})},[]),te=l.useCallback(ee=>{Pe(re=>{const ye=new Set(re);return ye.has(ee)?ye.delete(ee):ye.add(ee),ye})},[]);l.useEffect(()=>{if(!s||!n)return;const ee=Array.from(Ne).filter(re=>!le.has(re)&&!ae.has(re));ee.length!==0&&(Ie(re=>{const ye=new Set(re);return ee.forEach(Oe=>ye.add(Oe)),ye}),ee.forEach(re=>{n.getCommitFiles(s,re).then(ye=>{Le(Oe=>new Map(Oe).set(re,ye.files))}).catch(ye=>{console.error("Failed to fetch commit files:",ye),Le(Oe=>new Map(Oe).set(re,[]))}).finally(()=>{Ie(ye=>{const Oe=new Set(ye);return Oe.delete(re),Oe})})}))},[Ne,s,n,le,ae]),l.useEffect(()=>()=>{if(!s){Ln=null;return}Ln={directory:s,selectedPaths:Array.from(V),commitMessage:A}},[A,s,V]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{s&&(y(s),jt.getState().directories.get(s)?.status||b(s,n,{force:!0}))},[s,y,b,n]);const E=l.useCallback(async(ee=!0)=>{if(s)try{await Promise.all([v(s,n),N(s,n)])}catch(re){if(ee){const ye=re instanceof Error?re.message:"Failed to refresh repository state";he.error(ye)}}},[s,n,v,N]),ne=l.useCallback(async()=>{s&&await w(s,n,W)},[s,n,w,W]),G=l.useCallback(async()=>{s&&await S(s,n)},[s,n,S]),F=l.useMemo(()=>{if(!p)return[];const ee=p.files??[],re=new Map;return ee.forEach(ye=>{re.set(ye.path,ye)}),Array.from(re.values()).sort((ye,Oe)=>ye.path.localeCompare(Oe.path))},[p]);l.useEffect(()=>{if(!p||F.length===0){L(new Set),oe(!1);return}L(ee=>{const re=new Set,ye=ee??new Set;return F.forEach(Oe=>{ye.has(Oe.path)?re.add(Oe.path):R||re.add(Oe.path)}),re})},[p,F,R]);const _=async ee=>{if(s){C(ee);try{if(ee==="fetch")await n.gitFetch(s),he.success("Fetched latest updates");else if(ee==="pull"){const re=await n.gitPull(s);he.success(`Pulled ${re.files.length} file${re.files.length===1?"":"s"}`)}else ee==="push"&&(await n.gitPush(s),he.success("Pushed to remote"));await E(!1),await ne()}catch(re){const ye=re instanceof Error?re.message:`Failed to ${ee==="pull"?"pull":ee}`;he.error(ye)}finally{C(null)}}},B=async(ee={})=>{if(!s)return;if(!A.trim()){he.error("Please enter a commit message");return}const re=Array.from(V).sort();if(re.length===0){he.error("Select at least one file to commit");return}const ye=ee.pushAfter?"commitAndPush":"commit";P(ye);try{await n.createGitCommit(s,A.trim(),{files:re}),he.success("Commit created successfully"),k(""),L(new Set),oe(!1),_e(),await E(),ee.pushAfter?(await n.gitPush(s),he.success("Pushed to remote"),se(),await E(!1)):await E(!1),await ne()}catch(Oe){const qe=Oe instanceof Error?Oe.message:"Failed to create commit";he.error(qe)}finally{P(null)}},$=l.useCallback(async()=>{if(s){if(V.size===0){he.error("Select at least one file to describe");return}me(!0);try{const{message:ee}=await n.generateCommitMessage(s,Array.from(V)),re=ee.subject?.trim()??"",ye=Array.isArray(ee.highlights)?ee.highlights:[];re&&k(re),De(ye),he.success("Commit message generated")}catch(ee){const re=ee instanceof Error?ee.message:"Failed to generate commit message";he.error(re)}finally{me(!1)}}},[s,V,n]),Q=async ee=>{if(!s||!p)return;const re=p.current??null;try{await n.createBranch(s,ee,re??"HEAD"),he.success(`Created branch ${ee}`);let ye=!1;try{await n.checkoutBranch(s,ee),await n.gitPush(s,{remote:"origin",branch:ee,options:["--set-upstream"]}),ye=!0}catch(Oe){const qe=Oe instanceof Error?Oe.message:"Unable to push new branch to origin.";he.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",qe]})})}finally{if(re)try{await n.checkoutBranch(s,re)}catch(Oe){console.warn("Failed to restore original branch after creation:",Oe)}}await E(),await ne(),ye&&he.success(`Upstream set for ${ee}`)}catch(ye){const Oe=ye instanceof Error?ye.message:"Failed to create branch";throw he.error(Oe),ye}},X=async ee=>{if(!s)return;const re=ee.replace(/^remotes\//,"");if(p?.current!==re)try{await n.checkoutBranch(s,re),he.success(`Checked out ${re}`),await E(),await ne()}catch(ye){const Oe=ye instanceof Error?ye.message:`Failed to checkout ${re}`;he.error(Oe)}},Te=async ee=>{if(s){Z(!0);try{await n.setGitIdentity(s,ee.id),he.success(`Applied "${ee.name}" to repository`),await G()}catch(re){const ye=re instanceof Error?re.message:"Failed to apply git identity";he.error(ye)}finally{Z(!1)}}},We=l.useMemo(()=>m?.all?m.all.filter(ee=>!ee.startsWith("remotes/")).sort():[],[m]),it=l.useMemo(()=>m?.all?m.all.filter(ee=>ee.startsWith("remotes/")).map(ee=>ee.replace(/^remotes\//,"")).sort():[],[m]),nt=l.useMemo(()=>{const ee=new Map;i&&ee.set(i.id,i);for(const re of a)ee.set(re.id,re);return Array.from(ee.values())},[a,i]),Ze=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const ee=a.find(re=>re.userName===h.userName&&re.userEmail===h.userEmail);return ee||(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]),lt=F.length,mt=V.size,dt=g||M!==null||D!==null,z=lt>0,ge=ee=>{L(re=>{const ye=new Set(re);return ye.has(ee)?ye.delete(ee):ye.add(ee),ye}),oe(!0)},U=()=>{const ee=new Set(F.map(re=>re.path));L(ee),oe(!0)},ie=()=>{L(new Set),oe(!0)},Se=l.useCallback(async ee=>{if(s){Ae(re=>{const ye=new Set(re);return ye.add(ee),ye});try{await n.revertGitFile(s,ee),he.success(`Reverted ${ee}`),await E(!1)}catch(re){const ye=re instanceof Error?re.message:"Failed to revert changes";he.error(ye)}finally{Ae(re=>{const ye=new Set(re);return ye.delete(ee),ye})}}},[s,E,n]),we=l.useCallback(()=>{if(ke.length===0)return;const ee=ke.map(re=>re.trim()).filter(Boolean);if(ee.length===0){_e();return}k(re=>{const ye=re.trim(),Oe=ye.length>0?`
|
|
92
|
+
|
|
93
|
+
`:"";return`${ye}${Oe}${ee.join(`
|
|
94
|
+
`)}`.trim()})},[ke,_e]),ve=l.useCallback(ee=>{K(ee),s&&(j(s,ee),w(s,n,ee))},[s,j,w,n]);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(Kt,{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(yy,{status:p,localBranches:We,remoteBranches:it,branchInfo:m?.branches,syncAction:M,onFetch:()=>_("fetch"),onPull:()=>_("pull"),onPush:()=>_("push"),onCheckoutBranch:X,onCreateBranch:Q,activeIdentityProfile:Ze,availableIdentities:nt,onSelectIdentity:Te,isApplyingIdentity:O,isWorktreeMode:!!o}),e.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[z?e.jsx(ky,{changeEntries:F,selectedPaths:V,diffStats:p?.diffStats,revertingPaths:Ce,onToggleFile:ge,onSelectAll:U,onClearSelection:ie,onViewDiff:ee=>je.getState().navigateToDiff(ee),onRevertFile:Se}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(by,{behind:p?.behind??0,onPull:()=>_("pull"),isPulling:M==="pull"})}),F.length>0&&e.jsx(Ay,{selectedCount:mt,commitMessage:A,onCommitMessageChange:k,generatedHighlights:ke,onInsertHighlights:we,onClearHighlights:_e,onGenerateMessage:$,isGeneratingMessage:ue,onCommit:()=>B({pushAfter:!1}),onCommitAndPush:()=>B({pushAfter:!0}),commitAction:D,isBusy:dt})]}),e.jsx($y,{log:f,isLogLoading:x,logMaxCount:W,onLogMaxCountChange:ve,expandedCommitHashes:Ne,onToggleCommit:te,commitFilesMap:le,loadingCommitHashes:ae,onCopyHash:Ge})]})})]}):e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view repository details."})})},Hy=256e3;function Js(n){let s=n.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const mr=n=>({directory:n,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),ul=Ft((n,s)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const r=Js(t);return s().sessions.get(r)},setTerminalSession:(t,r)=>{const o=Js(t);n(a=>{const i=new Map(a.sessions),c=i.get(o),u=!c||c.terminalSessionId!==r.sessionId?mr(o):c??mr(o);return i.set(o,{...u,terminalSessionId:r.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,r)=>{const o=Js(t);n(a=>{const i=new Map(a.sessions),c=i.get(o)??mr(o);return i.set(o,{...c,isConnecting:r,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,r)=>{if(!r)return;const o=Js(t);n(a=>{const i=new Map(a.sessions),c=i.get(o)??mr(o),d=a.nextChunkId,u={id:d,data:r},p=[...c.bufferChunks,u];let m=c.bufferLength+r.length;for(;m>Hy&&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 r=Js(t);n(o=>{const a=new Map(o.sessions),i=a.get(r);return i&&a.set(r,{...i,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const r=Js(t);n(o=>{const a=new Map(o.sessions),i=a.get(r);return i?(a.set(r,{...i,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const r=Js(t);n(o=>{const a=new Map(o.sessions);return a.delete(r),{sessions:a}})},clearAllTerminalSessions:()=>{n({sessions:new Map,nextChunkId:1})}})),xd=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Wy=[{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'}],Uy=[{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'}],yd=n=>Object.fromEntries(n.map(s=>[s.id,s])),ml=yd(Wy),Zs=yd(Uy),Vy="ibm-plex-sans",Nr="ibm-plex-mono";function Gy(n){const{colors:s}=n,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 fl(n,s,t){return{fontFamily:`${n}, "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 ea=l.forwardRef(({sessionKey:n,chunks:s,onInput:t,onResize:r,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(r),y=l.useRef([]),b=l.useRef(!1),v=l.useRef(0),N=l.useRef(null),w=l.useRef(null),[,S]=l.useReducer(C=>C+1,0);g.current=t,x.current=r;const j=l.useCallback(()=>{y.current=[],b.current=!1,v.current=0,N.current=null},[]),I=l.useCallback(()=>{const C=h.current,D=f.current,P=p.current;if(!C||!D||!P)return;const W=P.getBoundingClientRect();if(!(W.width<24||W.height<24))try{C.fit(),x.current(D.cols,D.rows)}catch{}},[]),A=l.useCallback(()=>{if(b.current)return;const C=()=>{const D=f.current;if(!D){j();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()},[j]),k=l.useCallback(C=>{C&&(y.current=[C],b.current=!1,A())},[A]),M=l.useCallback(()=>{if(w.current?.(),w.current=null,!d)return;const C=p.current;if(!C)return;const D=C.querySelector(".xterm-viewport");if(!D)return;const P=2.2,W=2.8,K=25,O=.25,Z=8,se=.05,V=.015,L={lastY:null,lastTime:null,velocity:0,rafId:null},R=()=>typeof performance<"u"?performance.now():Date.now(),oe=()=>Math.max(0,D.scrollHeight-D.clientHeight),Ce=le=>{const Le=oe();D.scrollTop=Math.max(0,Math.min(Le,le))},Ae=le=>{if(!le)return;const Le=D.scrollTop;return Ce(Le+le),D.scrollTop!==Le},ue=()=>{L.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(L.rafId),L.rafId=null},me={passive:!1,capture:!0};if(typeof window<"u"&&"PointerEvent"in window){const le=Object.assign(L,{pointerId:null}),Le=te=>{if(te.pointerType==="touch"){ue(),le.pointerId=te.pointerId,le.lastY=te.clientY,le.lastTime=R(),le.velocity=0;try{C.setPointerCapture(te.pointerId)}catch{}}},ae=te=>{if(te.pointerType!=="touch"||le.pointerId!==te.pointerId)return;if(le.lastY===null){le.lastY=te.clientY,le.lastTime=R();return}const E=le.lastY,ne=le.lastTime??R(),G=R();le.lastY=te.clientY,le.lastTime=G;const F=E-te.clientY;if(Math.abs(F)<1)return;const _=Math.max(G-ne,8),B=P+Math.min(W,Math.abs(F)/K),$=F*B,Q=$/_;le.velocity=le.velocity*(1-O)+Q*O,le.velocity>Z?le.velocity=Z:le.velocity<-Z&&(le.velocity=-Z),te.cancelable&&te.preventDefault(),te.stopPropagation(),Ae($)},Ie=te=>{if(te.pointerType!=="touch"||le.pointerId!==te.pointerId)return;le.pointerId=null,le.lastY=null,le.lastTime=null;try{C.releasePointerCapture(te.pointerId)}catch{}if(typeof window>"u")return;if(Math.abs(le.velocity)<se){le.velocity=0;return}let E=R();const ne=()=>{const G=R(),F=Math.max(G-E,8);E=G;const _=Ae(le.velocity*F)??!1,B=Math.sign(le.velocity),$=Math.max(0,Math.abs(le.velocity)-V*F);if(le.velocity=$*B,!_||$<=se){ue(),le.velocity=0;return}le.rafId=window.requestAnimationFrame(ne)};le.rafId=window.requestAnimationFrame(ne)};C.addEventListener("pointerdown",Le,me),C.addEventListener("pointermove",ae,me),C.addEventListener("pointerup",Ie,me),C.addEventListener("pointercancel",Ie,me);const Ge=C.style.touchAction;C.style.touchAction="none",w.current=()=>{ue(),C.removeEventListener("pointerdown",Le,me),C.removeEventListener("pointermove",ae,me),C.removeEventListener("pointerup",Ie,me),C.removeEventListener("pointercancel",Ie,me),C.style.touchAction=Ge};return}const De=le=>{le.touches.length===1&&(ue(),L.lastY=le.touches[0].clientY,L.lastTime=R(),L.velocity=0)},_e=le=>{if(le.touches.length!==1){L.lastY=null,L.lastTime=null,L.velocity=0,ue();return}const Le=le.touches[0].clientY;if(L.lastY===null){L.lastY=Le,L.lastTime=R();return}const ae=L.lastY,Ie=L.lastTime??R(),Ge=R();L.lastY=Le,L.lastTime=Ge;const te=ae-Le;if(Math.abs(te)<1)return;const E=Math.max(Ge-Ie,8),ne=P+Math.min(W,Math.abs(te)/K),G=te*ne,F=G/E;L.velocity=L.velocity*(1-O)+F*O,L.velocity>Z?L.velocity=Z:L.velocity<-Z&&(L.velocity=-Z),le.preventDefault(),le.stopPropagation(),Ae(G)},Ne=()=>{if(L.lastY=null,L.lastTime=null,typeof window>"u")return;if(Math.abs(L.velocity)<se){L.velocity=0;return}let le=R();const Le=()=>{const ae=R(),Ie=Math.max(ae-le,8);le=ae;const Ge=Ae(L.velocity*Ie)??!1,te=Math.sign(L.velocity),E=Math.max(0,Math.abs(L.velocity)-V*Ie);if(L.velocity=E*te,!Ge||E<=se){ue(),L.velocity=0;return}L.rafId=window.requestAnimationFrame(Le)};L.rafId=window.requestAnimationFrame(Le)};C.addEventListener("touchstart",De,me),C.addEventListener("touchmove",_e,me),C.addEventListener("touchend",Ne,me),C.addEventListener("touchcancel",Ne,me);const Pe=C.style.touchAction;C.style.touchAction="none",w.current=()=>{ue(),C.removeEventListener("touchstart",De,me),C.removeEventListener("touchmove",_e,me),C.removeEventListener("touchend",Ne,me),C.removeEventListener("touchcancel",Ne,me),C.style.touchAction=Pe}},[d]);return l.useEffect(()=>{const C=new im.Terminal(fl(a,i,o)),D=new lm.FitAddon;f.current=C,h.current=D,C.loadAddon(D);const P=p.current;if(P){C.open(P);const O=P.querySelector(".xterm-viewport");O&&(O.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),m.current=O,S()),I(),C.focus()}const W=[C.onData(O=>{g.current(O)})],K=new ResizeObserver(()=>{I()});return P&&K.observe(P),()=>{w.current?.(),w.current=null,W.forEach(O=>O.dispose()),K.disconnect(),C.dispose(),f.current=null,h.current=null,j()}},[I,a,i,o,j]),l.useEffect(()=>{const C=f.current;if(!C)return;const D=fl(a,i,o);Object.assign(C.options,D),I()},[I,a,i,o]),l.useEffect(()=>{const C=f.current;C&&(C.reset(),j(),I(),C.focus())},[n,I,j]),l.useEffect(()=>(M(),()=>{w.current?.(),w.current=null}),[M,n]),l.useEffect(()=>{const C=f.current;if(!C)return;if(s.length===0){v.current!==0&&(C.reset(),j(),I());return}const D=s[0].id;if(N.current===null&&(N.current=D),(N.current!==D||v.current>s.length)&&(C.reset(),j(),N.current=D),v.current<s.length){const W=s.slice(v.current);k(W.map(K=>K.data).join("")),v.current=s.length}},[s,k,I,j]),l.useImperativeHandle(u,()=>({focus:()=>{f.current?.focus()},clear:()=>{const C=f.current;C&&(C.reset(),j(),I())},fit:()=>{I()}}),[I,j]),e.jsx("div",{ref:p,className:T("relative h-full w-full",c),children:m.current?e.jsx(wa,{containerRef:m,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null})});ea.displayName="TerminalViewport";const pl=13,qy={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},fr={ctrl:"5",cmd:"3"},Ky={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},Yy=(n,s)=>{if(s)switch(n){case"arrow-up":return`\x1B[1;${fr[s]}A`;case"arrow-down":return`\x1B[1;${fr[s]}B`;case"arrow-right":return`\x1B[1;${fr[s]}C`;case"arrow-left":return`\x1B[1;${fr[s]}D`}return qy[n]??null},Xy=()=>{const{terminal:n}=an(),{currentTheme:s}=ln(),{monoFont:t}=xd(),{isMobile:r,hasTouchInput:o}=Nt(),{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($=>$.id===a),B=typeof _?.directory=="string"?_.directory:null;return B&&B.length>0?B:null},[a,i,d]),{currentDirectory:p,homeDirectory:m}=bt(),f=u||p||null,h=l.useMemo(()=>f?m?f===m?"~":f.startsWith(m+"/")?"~"+f.slice(m.length):f:f:"",[f,m]),g=ul(),x=g.sessions,y=g.setTerminalSession,b=g.setConnecting,v=g.appendToBuffer,N=g.clearTerminalSession,w=g.removeTerminalSession,S=g.clearBuffer,j=l.useMemo(()=>{if(f)return x.get(f)},[x,f]),I=j?.terminalSessionId??null,A=j?.bufferChunks??[],k=j?.bufferLength??0,M=j?.isConnecting??!1,C=I,[D,P]=l.useState(null),[W,K]=l.useState(!1),[O,Z]=l.useState(null),[se,V]=l.useState(!1),L=l.useRef(null),R=l.useRef(null),oe=l.useRef(C),Ce=l.useRef(f),Ae=l.useRef(null),me=je(_=>_.activeMainTab)==="terminal";l.useEffect(()=>{oe.current=C},[C]),l.useEffect(()=>{Ce.current=f},[f]),l.useEffect(()=>{!r&&O!==null&&Z(null)},[r,O,Z]),l.useEffect(()=>{!C&&O!==null&&Z(null)},[C,O,Z]);const ke=l.useCallback(()=>{L.current?.(),L.current=null,R.current=null},[]);l.useEffect(()=>()=>{ke(),oe.current=null},[ke]);const De=l.useCallback(_=>{if(R.current===_)return;ke();const B=n.connect(_,{onEvent:$=>{const Q=Ce.current;if(Q)switch($.type){case"connected":{b(Q,!1),P(null),K(!1),Ae.current?.focus();break}case"reconnecting":{const X=$.attempt??0,Te=$.maxAttempts??3;P(`Reconnecting (${X}/${Te})...`),K(!1);break}case"data":{$.data&&v(Q,$.data);break}case"exit":{const X=typeof $.exitCode=="number"?$.exitCode:null,Te=typeof $.signal=="number"?$.signal:null;v(Q,`\r
|
|
95
|
+
[Process exited${X!==null?` with code ${X}`:""}${Te!==null?` (signal ${Te})`:""}]\r
|
|
96
|
+
`),N(Q),b(Q,!1),P("Terminal session ended"),K(!1),ke();break}}},onError:($,Q)=>{const X=Ce.current;if(!X)return;const Te=Q?`Connection failed: ${$.message}`:$.message||"Terminal stream connection error";P(Te),K(!!Q),Q&&(b(X,!1),ke(),w(X))}},Ky);L.current=()=>{B.close(),R.current=null},R.current=_},[v,N,ke,w,b,n,P]);l.useEffect(()=>{let _=!1;if(!f){P(a?"No working directory available for terminal.":"Select a session to open the terminal."),ke();return}return(async()=>{const $=f;if(!Ce.current||Ce.current!==$)return;let X=ul.getState().getTerminalSession($)?.terminalSessionId??null;if(!X){P(null),K(!1),b($,!0);try{const Te=await n.createSession({cwd:$});if(_){try{await n.close(Te.sessionId)}catch{}return}y($,Te),X=Te.sessionId}catch(Te){_||(P(Te instanceof Error?Te.message:"Failed to start terminal session"),K(!0),b($,!1));return}}!X||_||(oe.current=X,De(X))})(),()=>{_=!0,oe.current=null,ke()}},[a,f,C,w,b,y,De,ke,n]);const _e=l.useCallback(async()=>{if(!f||se)return;V(!0),P(null),K(!1),ke();const _=oe.current;try{if(n.restartSession&&_){const B=await n.restartSession(_,{cwd:f});y(f,B),oe.current=B.sessionId,De(B.sessionId)}else{if(_)try{await n.close(_)}catch{}w(f)}}catch(B){P(B instanceof Error?B.message:"Failed to restart terminal"),K(!0)}finally{V(!1)}},[f,se,ke,n,y,De,w]),Ne=l.useCallback(async()=>{if(f&&!se){V(!0),P(null),K(!1),ke();try{n.forceKill&&await n.forceKill({cwd:f})}catch{}w(f),S(f),Ae.current?.clear(),await new Promise(_=>setTimeout(_,100));try{b(f,!0);const _=await n.createSession({cwd:f});y(f,_),oe.current=_.sessionId,De(_.sessionId)}catch(_){P(_ instanceof Error?_.message:"Failed to create terminal"),K(!0),b(f,!1)}finally{V(!1)}}},[f,se,ke,n,w,S,b,y,De]),Pe=l.useCallback(()=>{if(!f)return;S(f),Ae.current?.clear(),Ae.current?.focus();const _=oe.current;_&&n.sendInput(_,"\f").catch(B=>{P(B instanceof Error?B.message:"Failed to refresh prompt")})},[S,f,P,n]),le=l.useCallback(_=>{if(!_)return;let B=_,$=!1;if(O&&_.length>0){const X=_[0];if(X.length===1&&/[a-zA-Z]/.test(X)){const Te=X.toUpperCase();(O==="ctrl"||O==="cmd")&&(B=String.fromCharCode(Te.charCodeAt(0)&31),$=!0)}$||($=!0)}const Q=oe.current;Q&&(n.sendInput(Q,B).catch(X=>{P(X instanceof Error?X.message:"Failed to send input")}),$&&(Z(null),Ae.current?.focus()))},[O,Z,n]),Le=l.useCallback((_,B)=>{const $=oe.current;$&&n.resize({sessionId:$,cols:_,rows:B}).catch(()=>{})},[n]),ae=l.useCallback(_=>{Z(B=>B===_?null:_),Ae.current?.focus()},[Z]),Ie=l.useCallback(_=>{const B=Yy(_,O);B&&(le(B),Z(null),Ae.current?.focus())},[O,le,Z]);l.useEffect(()=>{if(!r||!O||!C)return;const _=B=>{if(B.repeat)return;const $=B.key;if(!$||$==="Control"||$==="Meta"||$==="Alt"||$==="Shift")return;const Q=$.length===1?$.toLowerCase():$,X=B.code??"",Te=X.startsWith("Key")&&X.length===4?X.slice(3).toUpperCase():null,We=$.length===1&&/[a-zA-Z]/.test($)?$.toUpperCase():Te,it={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(Q in it){B.preventDefault(),B.stopPropagation(),Ie(it[Q]);return}if(O==="ctrl"&&We&&We.length===1&&We>="A"&&We<="Z"){const nt=String.fromCharCode(We.charCodeAt(0)&31);B.preventDefault(),B.stopPropagation(),le(nt),Z(null),Ae.current?.focus()}};return window.addEventListener("keydown",_),()=>{window.removeEventListener("keydown",_)}},[O,Ie,le,r,Z,C]);const Ge=l.useMemo(()=>{const _=Zs[Nr].stack;if(typeof window>"u")return(Zs[t]??Zs[Nr]).stack;const $=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return $&&$.trim().length>0?$.trim():(Zs[t]??Zs[Nr]).stack??_},[t]),te=l.useMemo(()=>Gy(s),[s]),E=l.useMemo(()=>`${f??"no-dir"}::${C??"pending"}`,[f,C]);l.useEffect(()=>{if(!me)return;const _=Ae.current;if(!_)return;const B=()=>{_.fit()};if(typeof window<"u"){const $=window.requestAnimationFrame(()=>{B(),_.focus()}),Q=[220,400].map(X=>window.setTimeout(B,X));return()=>{window.cancelAnimationFrame($),Q.forEach(X=>window.clearTimeout(X))}}B()},[me,E,C]);const ne=D?.includes("Reconnecting"),G=D?ne?e.jsx(cm,{size:20,className:"text-amber-400"}):e.jsx(ds,{size:20,className:"text-destructive"}):C&&!M&&!se?e.jsx(gr,{size:20,className:"text-emerald-400"}):M||se?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:_e,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const F=!C||M||se;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[G,e.jsxs(Ee,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Pe,disabled:!k,title:"Clear output",type:"button",children:[e.jsx(Gs,{size:16}),"Clear"]}),e.jsxs(Ee,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:_e,disabled:se,title:"Restart terminal session",type:"button",children:[e.jsx(Is,{size:16,className:T((M||se)&&"animate-spin")}),"Restart"]})]})]}),r?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>Ie("esc"),disabled:F,children:"Esc"}),e.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ie("tab"),disabled:F,children:[e.jsx(Ba,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ee,{type:"button",size:"sm",variant:O==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ae("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(Ee,{type:"button",size:"sm",variant:O==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ae("cmd"),disabled:F,children:[e.jsx(nn,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ie("arrow-up"),disabled:F,children:[e.jsx(Xn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ie("arrow-left"),disabled:F,children:[e.jsx(zl,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ie("arrow-down"),disabled:F,children:[e.jsx(An,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ie("arrow-right"),disabled:F,children:[e.jsx(Ba,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Ie("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:te.background},children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:me?r?e.jsx(ea,{ref:_=>{Ae.current=_},sessionKey:E,chunks:A,onInput:le,onResize:Le,theme:te,fontFamily:Ge,fontSize:pl,enableTouchScroll:o},E):e.jsx(tt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(ea,{ref:_=>{Ae.current=_},sessionKey:E,chunks:A,onInput:le,onResize:Le,theme:te,fontFamily:Ge,fontSize:pl,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}),W&&e.jsx(Ee,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Ne,disabled:se,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},Jy=()=>{const{isSidebarOpen:n,activeMainTab:s,setIsMobile:t,isSessionSwitcherOpen:r,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i}=je(),{isMobile:c}=Nt(),[d,u]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||u(typeof window.opencodeDesktop<"u")},[]),ng({enabled:!0});const p=eo(h=>h.checkForUpdates);l.useEffect(()=>{const h=setTimeout(()=>{p()},3e3);return()=>clearTimeout(h)},[p]),l.useEffect(()=>{je.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(()=>{je.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,j=S?Math.round(S.height):window.innerHeight,I=S?Math.max(0,Math.round(S.offsetTop)):0;h.style.setProperty("--oc-visual-viewport-offset-top",`${I}px`);const A=document.activeElement,k=A?.tagName,C=k==="INPUT"||k==="TEXTAREA"||k==="SELECT"||!!A?.isContentEditable,D=Math.round(h.clientHeight||window.innerHeight),P=j+I,W=Math.max(0,D-P),O=W>=(C?120:180)?W:0;if(x)O===0&&(x=!1),g=0;else if(g===0)O>0&&C&&(g=O);else{const Z=j>y+6;O===0?g=0:Z?b():O>g&&(g=O)}if(h.style.setProperty("--oc-keyboard-inset",`${g}px`),y=j,c&&C){const Z=document.scrollingElement;Z&&Z.scrollTop!==0&&(Z.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};v();const N=window.visualViewport;N?.addEventListener("resize",v),N?.addEventListener("scroll",v),window.addEventListener("resize",v),window.addEventListener("orientationchange",v),document.addEventListener("focusin",v,!0);const w=S=>{const j=S.target;if(!j)return;const I=j.tagName;(I==="INPUT"||I==="TEXTAREA"||I==="SELECT"||j.isContentEditable)&&b()};return document.addEventListener("focusout",w,!0),()=>{N?.removeEventListener("resize",v),N?.removeEventListener("scroll",v),window.removeEventListener("resize",v),window.removeEventListener("orientationchange",v),document.removeEventListener("focusin",v,!0),document.removeEventListener("focusout",w,!0)}},[c]);const m=l.useMemo(()=>{switch(s){case"git":return e.jsx(zy,{});case"diff":return e.jsx(lh,{});case"terminal":return e.jsx(Xy,{});default:return null}},[s]),f=s==="chat";return e.jsx(sg,{children:e.jsxs("div",{className:T("main-content-safe-area h-[100dvh]",c?"flex flex-col":"flex",d?"bg-transparent":"bg-background"),children:[e.jsx(Wh,{}),e.jsx(Gh,{}),e.jsx(Jh,{}),e.jsx(zh,{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:T("absolute inset-0",!f&&"invisible"),children:e.jsx(ls,{children:e.jsx(Qo,{})})}),m&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:m})})]})}),e.jsx(qt,{open:r,onClose:()=>o(!1),title:"Sessions",children:e.jsx(qo,{mobileVariant:!0})})]}):e.jsxs(e.Fragment,{children:[e.jsx(hh,{isOpen:n,isMobile:c,children:e.jsx(qo,{})}),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:T("absolute inset-0",!f&&"invisible"),children:e.jsx(ls,{children:e.jsx(Qo,{})})}),m&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:m})})]})})]})]}),e.jsx(dh,{})]})})},Zy=()=>{const[n,s]=l.useState("chat"),t=fe(D=>D.currentSessionId),r=fe(D=>D.sessions),o=fe(D=>!!D.newSessionDraft?.open),a=fe(D=>D.openNewSessionDraft),[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(D=>D.isInitialized),y=St(D=>D.initializeApp),b=fe(D=>D.loadSessions),v=fe(D=>D.loadMessages),N=fe(D=>D.messages),[w,S]=l.useState(()=>x),[j,I]=l.useState(!1);l.useEffect(()=>{t&&s("chat")},[t]),l.useEffect(()=>{!t&&!o&&a()},[t,o,a]);const A=l.useCallback(()=>{s("sessions")},[]),k=l.useCallback(()=>{a(),s("chat")},[a]);l.useEffect(()=>{const D=P=>{const W=P.detail,K=W?.status;(K==="connected"||K==="connecting"||K==="error"||K==="disconnected")&&(c(K),u(W?.error),K==="connected"&&m(!0))};return window.addEventListener("openchamber:connection-status",D),()=>window.removeEventListener("openchamber:connection-status",D)},[]);const M=l.useMemo(()=>w&&i==="connected"&&!j?!1:w?i==="error":i!=="connected"||j,[i,w,j]),C=p?800:250;return l.useEffect(()=>(g.current&&(window.clearTimeout(g.current),g.current=null),M?g.current=window.setTimeout(()=>h(!0),C):h(!1),()=>{g.current&&(window.clearTimeout(g.current),g.current=null)}),[C,M]),l.useEffect(()=>{(async()=>{if(!(j||w||i!=="connected")){I(!0);try{x||await y(),await b(),S(!0)}catch{}finally{I(!1)}}})()},[i,x,w,y,j,b]),l.useEffect(()=>{(async()=>{if(!w||i!=="connected"||n!=="chat"||o||!t)return;if(!(N.has(t)&&(N.get(t)?.length||0)>0))try{await v(t)}catch{}})()},[i,t,n,w,v,N,o]),e.jsxs("div",{className:"h-full w-full bg-background text-foreground flex flex-col",children:[n==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Po,{title:"Sessions",onNewSession:k,onSettings:()=>s("settings")}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(qo,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>s("chat"),hideDirectoryControls:!0})})]}):n==="settings"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Po,{title:"Settings",showBack:!0,onBack:A}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(Qy,{})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(Po,{title:o&&!t?"New session":r.find(D=>D.id===t)?.title||"Chat",showBack:!0,onBack:A,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:e.jsx(Qo,{})})})]}),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})]})]})},Po=({title:n,showBack:s,onBack:t,onNewSession:r,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(zl,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:n,children:n}),r&&e.jsx("button",{onClick:r,className:"p-1 rounded hover:bg-muted transition-colors","aria-label":"New session",children:e.jsx(os,{className:"h-5 w-5"})}),o&&e.jsx("button",{onClick:o,className:"p-1 rounded hover:bg-muted transition-colors","aria-label":"Settings",children:e.jsx(jn,{className:"h-5 w-5"})}),a&&f&&f.totalTokens>0&&e.jsx(Vo,{totalTokens:f.totalTokens,percentage:f.percentage,contextLimit:f.contextLimit,outputLimit:f.outputLimit??0,size:"compact"})]})},Qy=()=>e.jsx("div",{className:"flex flex-col h-full",children:e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(Pc,{})})}),hl=({...n})=>{const{theme:s="system"}=dm();return e.jsx(um,{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)"},...n})},eb=(n=5e3)=>{const[s,t]=de.useState(null);return de.useEffect(()=>{if(!as())return;let r=!1,o=null;const a=async()=>{const i=await Pm();r||(t(i),o=setTimeout(a,n))};return a(),()=>{r=!0,o&&clearTimeout(o)}},[n]),s},tb=({onClose:n})=>{const{sessions:s,messages:t,sessionMemoryState:r,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=fe(),c=eb(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=r.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,r,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(mm,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),n&&e.jsx(Ee,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:n,children:e.jsx(ds,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Messages"}),e.jsx("div",{className:"typography-markdown font-semibold",children:d})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Cached Sessions"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[p," / ",$t.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:[$t.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:[$t.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:[$t.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]})]}),e.jsxs("div",{className:"border-t pt-2",children:[e.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e.jsx(tt,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(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(fm,{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>$t.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(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsxs(Ee,{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(st,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(st,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(ot,{delayDuration:1e3,children:[e.jsx(at,{asChild:!0,children:e.jsx(Ee,{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(r)})},children:"Log State"})}),e.jsx(st,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},sb="openchamber-message-cursors",Mn="cursors",nb=1,bd="openchamber.messageCursors",Ta=()=>typeof window<"u",Ia=()=>Ta()&&typeof indexedDB<"u",wd=()=>Ia()?new Promise((n,s)=>{const t=indexedDB.open(sb,nb);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(Mn)||r.createObjectStore(Mn)},t.onerror=()=>{s(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{n(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),vd=()=>{if(!Ta())return{};try{const n=window.localStorage.getItem(bd);if(!n)return{};const s=JSON.parse(n);return s&&typeof s=="object"?s:{}}catch{return{}}},rb=n=>{if(Ta())try{window.localStorage.setItem(bd,JSON.stringify(n))}catch{}},ob=async(n,s,t)=>{if(!n||!s)return;if(Ia())try{const o=await wd();await new Promise((a,i)=>{const c=o.transaction(Mn,"readwrite");c.objectStore(Mn).put({messageId:s,completedAt:t},n),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 r=vd();r[n]={messageId:s,completedAt:t},rb(r)},ab=async n=>{if(!n)return null;if(Ia())try{const t=await wd(),r=await new Promise((o,a)=>{const i=t.transaction(Mn,"readonly"),d=i.objectStore(Mn).get(n);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(),r}catch{}return vd()[n]??null},Ht=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},ib=50,lb=750,gl=new WeakMap,xl=n=>{if(!n||!Array.isArray(n))return 0;const s=gl.get(n);if(s!==void 0)return s;let t=0;for(let r=0;r<n.length;r++){const o=n[r];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(t+=a.length)}}return gl.set(n,t),t},cb=10,yl=n=>{if(typeof n!="string")return null;const s=n.trim();if(!s)return null;const t=s.indexOf("_"),r=t>=0?s.slice(t+1):s;return!r||r.length<cb?null:r},bl=(n,s)=>{const t=yl(n),r=yl(s);return!t||!r||t.length!==r.length?!0:t>r},ta=new Map,wl=(n,s)=>{const t=`${n}:${s}`,r=ta.get(t);if(r&&r.sessionId===n)return r.message;const i=(fe.getState().messages.get(n)||[]).find(c=>c.info.id===s)||null;return ta.set(t,{sessionId:n,message:i}),i},db=()=>{const{addStreamingPart:n,completeStreamingMessage:s,updateMessageInfo:t,updateSessionCompaction:r,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:p}=fe(),{checkConnection:m}=St(),f=bt(te=>te.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 te=c.find(E=>E.id===a);if(te&&typeof te.directory=="string"&&te.directory.trim().length>0)return te.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=je(te=>te.setEventStreamStatus),y=l.useRef(null),b=l.useCallback((te,E)=>{const ne=E??null,G=y.current;if(!(G&&G.status===te&&G.hint===ne)){if(y.current={status:te,hint:ne},Ht()){const _={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[te]??"[INFO]",B=ne?`${_} SSE ${te}: ${ne}`:`${_} SSE ${te}`;console.info(B)}x(te,ne)}},[x]),v=l.useCallback((te,E)=>{if(!te)return Promise.resolve();const ne=Date.now();if(D.current)return D.current;if(ne-P.current<lb)return Promise.resolve();const G=u(te).catch(F=>{console.warn(`[useEventStream] Failed to resync messages (${E}):`,F)}).finally(()=>{D.current=null,P.current=Date.now()});return D.current=G,G},[u]),N=l.useCallback(async te=>{Ht()&&console.info("[useEventStream] Bootstrapping state:",te);try{await Promise.all([p(),a?v(a,te):Promise.resolve()])}catch(E){console.warn("[useEventStream] Bootstrap failed:",te,E)}},[a,p,v]),w=l.useCallback((te,E,ne)=>{Ht()&&console.debug(`[MessageTracker] ${te}: ${E}`,ne)},[]),S=l.useCallback(te=>{Ht()&&console.debug(`[MessageTracker] ${te}: reported`)},[]),j=l.useRef(null),I=l.useRef(null),A=l.useRef(0);l.useRef(new Set);const k=l.useRef(new Map),M=l.useRef(null),C=l.useRef(!1),D=l.useRef(null),P=l.useRef(0),W=l.useCallback(()=>{if(typeof document>"u")return"visible";const te=document.visibilityState;return te==="hidden"&&document.hasFocus()?"visible":te},[]),K=l.useRef(W()),O=l.useRef(typeof navigator>"u"?!0:navigator.onLine),Z=l.useRef(!1),se=l.useRef(null),V=l.useRef(null),L=l.useRef(Date.now()),R=l.useRef(!1),oe=l.useCallback(te=>{const E=Date.now();E-L.current>25e3&&(N(te),L.current=E)},[N]);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(R.current=!0)},[]);const Ce=l.useRef(new Map),Ae=l.useRef(new Map),ue=l.useRef(a);l.useEffect(()=>{ue.current=a},[a]);const me=l.useCallback(te=>{if(!te)return;const E=Date.now(),ne=k.current,G=ne.get(te);G&&E-G<3e3||(ne.set(te,E),setTimeout(async()=>{try{const F=await Me.getSession(te);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(te,_)}}catch(F){console.warn("Failed to refresh session metadata:",F)}},100))},[i]),ke=l.useCallback(()=>{M.current||(M.current=setTimeout(()=>{M.current=null;try{p()}catch(te){console.warn("Failed to refresh sessions after stream completion:",te)}},500))},[p]),De=l.useCallback((te,E)=>{if(Ae.current.get(te)===E)return;const G=Ce.current.get(te);if(G&&(clearTimeout(G),Ce.current.delete(te)),Ae.current.set(te,E),fe.setState({sessionActivityPhase:new Map(Ae.current)}),E==="cooldown"){const F=setTimeout(()=>{Ce.current.delete(te),Ae.current.get(te)==="cooldown"&&(Ae.current.set(te,"idle"),fe.setState({sessionActivityPhase:new Map(Ae.current)}))},2e3);Ce.current.set(te,F)}},[]),_e=l.useCallback(async()=>{try{const te=await Me.getSessionStatus();if(!te)return;Object.entries(te).forEach(([E,ne])=>{if(!E||!ne)return;const G=ne,F=G.type==="busy"||G.type==="retry"?"busy":"idle";De(E,F)})}catch{}},[De]),Ne=l.useCallback(te=>{if(L.current=Date.now(),Ht()&&console.debug("[useEventStream] Received event:",te.type,te.properties),!te.properties)return;const E=te.properties;if(!new Set(["session.abort","session.error"]).has(te.type)){const G=(typeof E.session=="object"&&E.session!==null?E.session:null)||(typeof E.sessionInfo=="object"&&E.sessionInfo!==null?E.sessionInfo:null);if(G){const F=G,_=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 B=typeof F.title=="string"?F.title:typeof E.title=="string"?E.title:void 0,$=typeof F.summary=="object"&&F.summary!==null?F.summary:typeof E.summary=="object"&&E.summary!==null?E.summary:void 0;if(B!==void 0||$!==void 0){const Q={};B!==void 0&&(Q.title=B),$!==void 0&&(Q.summary=$),i(_,Q)}}}}switch(te.type){case"server.connected":m();break;case"global.disposed":case"server.instance.disposed":{N("server_disposed_event");break}case"openchamber:session-activity":{if(!R.current)break;const G=typeof E.sessionId=="string"?E.sessionId:null,F=typeof E.phase=="string"?E.phase:null;G&&(F==="idle"||F==="busy"||F==="cooldown")&&(De(G,F),ke());break}case"session.status":if(R.current)break;{const G=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;G&&_&&(De(G,_==="busy"||_==="retry"?"busy":"idle"),ke())}break;case"message.part.updated":{const G=typeof E.part=="object"&&E.part!==null?E.part:null;if(!G)break;const F=G,_=typeof E.info=="object"&&E.info!==null?E.info:E,B=typeof _.sessionID=="string"?_.sessionID:null,$=typeof F.sessionID=="string"&&F.sessionID.length>0?F.sessionID:typeof B=="string"&&B.length>0?B:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:null,Q=typeof _.id=="string"?_.id:null,X=typeof F.messageID=="string"&&F.messageID.length>0?F.messageID:typeof Q=="string"&&Q.length>0?Q:typeof E.messageID=="string"&&E.messageID.length>0?E.messageID:null;if(!$||!X){Ht()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:F.sessionID??B??E.sessionID,messageID:F.messageID??Q??E.messageID});break}const Te=$,We=X,it=fe.getState().sessionMemoryState.get(Te)?.trimmedHeadMaxId;if(it&&!bl(We,it)){Ht()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:Te,messageId:We,trimmedHeadMaxId:it});break}let nt="assistant";if(_&&typeof _.role=="string")nt=_.role;else{const lt=wl(Te,We);if(lt){const mt=lt.info.role;typeof mt=="string"&&(nt=mt)}}if(w(We,"part_received",{role:nt}),nt==="user"&&F.synthetic===!0){w(We,"skipped_synthetic_user_part");break}const Ze={...G,type:G.type||"text"};w(We,"addStreamingPart_called"),n(Te,We,Ze,nt);break}case"message.updated":{const G=typeof E.info=="object"&&E.info!==null?E.info:E,F=G,_=typeof F.sessionID=="string"&&F.sessionID.length>0?F.sessionID:typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:null,B=typeof F.id=="string"&&F.id.length>0?F.id:typeof E.messageID=="string"&&E.messageID.length>0?E.messageID:null;if(!_||!B){Ht()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:F.sessionID??E.sessionID,messageID:F.id??E.messageID});break}const $=_,Q=B,X=fe.getState().sessionMemoryState.get($)?.trimmedHeadMaxId;if(X&&!bl(Q,X)){Ht()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:$,messageId:Q,trimmedHeadMaxId:X});break}if(R.current&&Ht())try{const U=E.parts||F.parts||[],Se=(Array.isArray(U)?U.filter(we=>we?.type==="text"):[]).map(we=>{const ve=we;return typeof ve?.text=="string"?ve.text:typeof ve?.content=="string"?ve.content:""}).join(`
|
|
97
|
+
`);console.info("[STREAM-TRACE] message.updated",{messageId:Q,role:F.role,status:F.status,textLen:Se.length,textPreview:Se.slice(0,120),partsCount:Array.isArray(U)?U.length:0})}catch{}if(w(Q,"message_updated",{role:F.role}),F.role==="user"){const U=E.parts||F.parts,ie=Array.isArray(U)?U:[],Se={...G,userMessageMarker:!0,clientRole:"user"};if(t($,Q,Se),ie.length>0)for(let we=0;we<ie.length;we++){const ve=ie[we];if(ve.synthetic===!0)continue;const ee={...ve,type:ve?.type||"text",sessionID:ve?.sessionID||$,messageID:ve?.messageID||Q};n($,Q,ee,"user")}w(Q,"user_message_created_from_event",{partsCount:ie.length});break}const Te=wl($,Q),We=xl(Te?.parts||[]),it=Te?.parts?.some(U=>U?.type==="step-finish"&&U.reason==="stop")??!1,nt=E.parts||F.parts,Ze=Array.isArray(nt)?nt:[],lt=Ze.length>0,dt=typeof(F.time||{})?.completed=="number";if(!lt&&!dt)break;if(F.role==="assistant"&<){const U=xl(Ze),ie=We>0&&U+ib<We,Se=Ze.some(we=>we?.type==="step-finish"&&we.reason==="stop");if(ie&&!Se){w(Q,"skipped_shrinking_update",{incomingLen:U,existingLen:We});break}if(R.current){const we=We>0&&U<We,ve=Ze.some(re=>{if(!re||re.type!=="text")return!1;const ye=re;return typeof ye.text=="string"&&ye.text.length>0});if(we&&!(Se&&ve)){w(Q,"desktop_shrinking_update_suppressed",{incomingLen:U,existingLen:We});break}}}if(t($,Q,G),lt&&F.role!=="user"){const Se=(fe.getState().messages.get($)||[]).find(ee=>ee.info.id===Q),we=!Se||Se.parts.length===0;w(Q,we?"server_parts_injected":"server_parts_refreshed",{count:Ze.length});const ve=R.current&&F.role==="assistant"?Ze.filter(ee=>ee?.type!=="text"):Ze;for(let ee=0;ee<ve.length;ee++){const re=ve[ee],ye={...re,type:re?.type||"text",sessionID:re?.sessionID||$,messageID:re?.messageID||Q};n($,Q,ye,F.role),w(Q,`server_part_${ee}`)}}const z=G.time;if(G.role==="assistant"&&z?.completed!==void 0&&G.role==="assistant"){const ie=fe.getState().messages.get($)||[];let Se=null,we="";for(let qe=0;qe<ie.length;qe++){const ft=ie[qe];ft.info.role==="assistant"&&ft.info.id>we&&(we=ft.info.id,Se=ft.info.id)}if(Q!==Se)break;if(!(Ze.some(qe=>qe?.type==="step-finish"&&qe.reason==="stop")||it)&&R.current){w(Q,"desktop_completion_without_stop");break}const ee=z?.completed!==void 0?z?.completed:Date.now();if(z?.completed||t($,Q,{...G,time:{...z??{},completed:ee}}),w(Q,"completed",{timeCompleted:ee}),S(Q),ob($,Q,ee),s($,Q),!R.current){const qe=G.sessionID,ft=typeof qe=="string"&&qe.length>0?qe:$;Ae.current.get(ft)==="busy"&&De(ft,"cooldown")}const re=G.sessionID,ye=typeof re=="string"&&re.length>0?re:$;me(ye),G.summary&&typeof ye=="string"&&r(ye,null)}break}case"session.updated":{const G=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 G.id=="string"&&G.id.length>0?G.id:typeof G.sessionID=="string"&&G.sessionID.length>0?G.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 G.time=="object"&&G.time!==null?G.time:typeof E.time=="object"&&E.time!==null?E.time:null,B=_&&typeof _.compacting=="number"?_.compacting:null;r(F,B)}break}case"session.abort":{const G=typeof E.sessionID=="string"&&E.sessionID.length>0?E.sessionID:null,F=typeof E.messageID=="string"&&E.messageID.length>0?E.messageID:null;G&&F&&s(G,F);break}case"permission.updated":a===E.sessionID&&o(E);break;case"permission.replied":break;case"todo.updated":{const G=typeof E.sessionID=="string"?E.sessionID:null,F=Array.isArray(E.todos)?E.todos:[];G&&F.length>0&&vg(G,F);break}}},[a,n,s,t,o,m,me,ke,r,i,w,S,De,N]),Pe=l.useCallback(()=>{const te=W();return K.current=te,te==="visible"&&O.current},[W]),le=l.useCallback(()=>{Ht()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:R.current,hasUnsubscribe:!!j.current,currentSessionId:ue.current,effectiveDirectory:g,onlineStatus:O.current,visibilityState:K.current,lastEventTimestamp:L.current,reconnectAttempts:A.current})},[g]),Le=l.useCallback(async()=>!0,[]),ae=l.useCallback(()=>{if(C.current){Ht()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(C.current=!0,I.current&&(clearTimeout(I.current),I.current=null),j.current){const te=j.current;j.current=null;try{te()}catch(E){console.warn("[useEventStream] Error during unsubscribe:",E)}}C.current=!1},[]),Ie=l.useCallback(async te=>{if(le(),!Pe()){Z.current=!0,O.current?b("paused","Paused while hidden"):b("offline","Waiting for network");return}R.current&&(await Le()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),te?.resetAttempts&&(A.current=0),ae(),L.current=Date.now(),b("connecting",null),Ht()&&console.info("[useEventStream] Starting event stream...");const E=G=>{console.warn("Event stream error:",G)},ne=()=>{const G=Z.current;if(A.current=0,Z.current=!1,L.current=Date.now(),b("connected",null),m(),G)N("sse_reconnected");else{const F=ue.current;F&&setTimeout(()=>{v(F,"sse_reconnected").then(()=>me(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 G=Me.subscribeToEvents(Ne,E,ne,g),F=()=>{try{G()}catch(_){console.warn("[useEventStream] Error during unsubscribe:",_)}};C.current?F():j.current=F}catch(G){console.error("[useEventStream] Error during subscription:",G),E(G)}},[Pe,ae,b,m,v,me,ke,s,Ne,g,De,Le,le,N]),Ge=l.useCallback(te=>{if(!Pe()){Z.current=!0,ae(),O.current?b("paused","Paused while hidden"):b("offline","Waiting for network");return}const E=A.current+1;A.current=E;const ne=te??`Retrying (${E})`;b("reconnecting",ne);const G=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),_=G+F;I.current&&clearTimeout(I.current),I.current=setTimeout(()=>{Ie({resetAttempts:!1})},_)},[Pe,ae,b,Ie]);l.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=w);let te=null;R.current&&typeof window<"u"&&(te=Q=>{const X=typeof Q.detail?.sessionId=="string"?Q.detail.sessionId:null,Te=typeof Q.detail?.phase=="string"?Q.detail.phase:null;X&&(Te==="idle"||Te==="busy"||Te==="cooldown")&&(De(X,Te),ke())},window.addEventListener("openchamber:session-activity",te));const E=()=>{se.current&&(clearTimeout(se.current),se.current=null)},ne=()=>{se.current||(se.current=setTimeout(()=>{const Q=W();K.current=Q,Q!=="visible"?(ae(),Z.current=!0,b("paused","Paused while hidden")):E()},5e3))},G=()=>{if(K.current=W(),K.current==="visible"){if(E(),oe("visibility_restore"),Z.current||!j.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Q=ue.current;Q&&(v(Q,"visibility_restore").catch(()=>{}),me(Q)),p(),_e(),b("connecting","Resuming stream"),Ie({resetAttempts:!0})}}else b("paused","Paused while hidden"),ne()},F=()=>{if(K.current=W(),K.current==="visible"&&(E(),oe("window_focus"),Z.current||!j.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Q=ue.current;Q&&(me(Q),v(Q,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(X=>console.warn("[useEventStream] Failed to refresh messages:",X))),p(),_e(),b("connecting","Resuming stream"),Ie({resetAttempts:!0})}},_=()=>{O.current=!0,oe("network_restored"),(Z.current||!j.current)&&(b("connecting","Network restored"),Ie({resetAttempts:!0}))},B=()=>{O.current=!1,Z.current=!0,b("offline","Waiting for network"),ae()};typeof document<"u"&&document.addEventListener("visibilitychange",G),typeof window<"u"&&(window.addEventListener("online",_),window.addEventListener("offline",B),window.addEventListener("focus",F));const $=setTimeout(()=>{Ie({resetAttempts:!0})},100);return V.current&&clearInterval(V.current),V.current=setInterval(()=>{if(!Pe())return;Date.now()-L.current>25e3&&Promise.resolve().then(async()=>{try{await Me.checkHealth()?L.current=Date.now():Ge("Refreshing stalled stream")}catch(X){console.warn("Health check after stale stream failed:",X),Ge("Refreshing stalled stream")}})},1e4),()=>{clearTimeout($),te&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",te),typeof document<"u"&&document.removeEventListener("visibilitychange",G),typeof window<"u"&&(window.removeEventListener("online",_),window.removeEventListener("offline",B),window.removeEventListener("focus",F)),E(),V.current&&(clearInterval(V.current),V.current=null);const Q=Ce.current;Q.forEach(X=>clearTimeout(X)),Q.clear(),ta.clear(),Z.current=!1,K.current=W(),O.current=typeof navigator>"u"?!0:navigator.onLine,ae(),M.current&&(clearTimeout(M.current),M.current=null),b("idle",null)}},[g,w,W,ae,b,Ie,Ge,u,me,De,_e,Pe])},ub=()=>{const{openNewSessionDraft:n,abortCurrentOperation:s,armAbortPrompt:t,clearAbortPrompt:r,currentSessionId:o}=fe(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:c,setSessionSwitcherOpen:d,setSessionCreateDialogOpen:u,setActiveMainTab:p,setSettingsDialogOpen:m}=je(),{themeMode:f,setThemeMode:h}=ln(),{working:g}=Jc(),x=l.useRef(null),y=l.useRef(null),b=l.useRef(!1),v=l.useCallback(()=>{y.current&&(clearTimeout(y.current),y.current=null),x.current=null,r()},[r]);l.useEffect(()=>{const N=w=>{if(w.ctrlKey&&w.key==="x"&&(w.preventDefault(),a()),w.ctrlKey&&w.shiftKey&&w.key.toLowerCase()==="l"){const j=xa()?.diagnostics;if(!j||(w.preventDefault(),b.current))return;b.current=!0,j.downloadLogs().then(({fileName:I,content:A})=>{const k=I||"openchamber.log",M=new Blob([A],{type:"text/plain;charset=utf-8"}),C=URL.createObjectURL(M),D=document.createElement("a");D.href=C,D.download=k,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(C)}).finally(()=>{b.current=!1});return}if(w.ctrlKey&&w.key==="h"&&(w.preventDefault(),i()),w.ctrlKey&&!w.metaKey&&w.key.toLowerCase()==="n"){if(w.preventDefault(),w.shiftKey){u(!0);return}p("chat"),d(!1),n()}if((w.metaKey||w.ctrlKey)&&w.key==="/"){w.preventDefault();const S=["light","dark","system"],I=(S.indexOf(f)+1)%S.length;h(S[I])}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="g"){w.preventDefault();const{activeMainTab:S}=je.getState();p(S==="git"?"chat":"git");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="e"){w.preventDefault();const{activeMainTab:S}=je.getState();p(S==="diff"?"chat":"diff");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="t"){w.preventDefault();const{activeMainTab:S}=je.getState();p(S==="terminal"?"chat":"terminal");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key===","){w.preventDefault();const{isSettingsDialogOpen:S}=je.getState();m(!S);return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="l"){w.preventDefault();const{isMobile:S,isSessionSwitcherOpen:j}=je.getState();S?d(!j):c();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 S=o;if(!(g.canAbort&&!!S)){v();return}const I=Date.now(),A=x.current;if(A&&I<A){w.preventDefault(),v(),s();return}w.preventDefault();const k=t(3e3)??I+3e3;x.current=k,y.current&&clearTimeout(y.current);const M=Math.max(k-I,0);y.current=setTimeout(()=>{x.current&&Date.now()>=x.current&&v()},M||0);return}};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[n,s,a,i,c,d,u,p,m,h,f,g,t,v,o]),l.useEffect(()=>()=>{v()},[v])},vl="openchamber:menu-action",mb=n=>{const{openNewSessionDraft:s}=fe(),{toggleCommandPalette:t,toggleHelpDialog:r,toggleSidebar:o,setSessionSwitcherOpen:a,setSessionCreateDialogOpen:i,setActiveMainTab:c,setSettingsDialogOpen:d,setAboutDialogOpen:u}=je(),{setDirectory:p}=bt(),{setThemeMode:m}=ln(),f=l.useRef(!1),h=l.useCallback(()=>{as()&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(g=>{g.success&&g.path?p(g.path,{showOverlay:!0}):g.error&&g.error!=="Directory selection cancelled"&&he.error("Failed to select directory",{description:g.error})}).catch(g=>{console.error("Desktop: Error selecting directory:",g),he.error("Failed to select directory")}):Qs.requestDirectoryDialog()},[p]);l.useEffect(()=>{const g=x=>{switch(x.detail){case"about":u(!0);break;case"settings":d(!0);break;case"command-palette":t();break;case"new-session":c("chat"),a(!1),s();break;case"worktree-creator":i(!0);break;case"change-workspace":h();break;case"open-git-tab":{const{activeMainTab:b}=je.getState();c(b==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:b}=je.getState();c(b==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:b}=je.getState();c(b==="terminal"?"chat":"terminal");break}case"theme-light":m("light");break;case"theme-dark":m("dark");break;case"theme-system":m("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":n?.();break;case"help-dialog":r();break;case"download-logs":{const v=xa()?.diagnostics;if(!v||f.current)break;f.current=!0,v.downloadLogs().then(({fileName:N,content:w})=>{const S=N||"openchamber.log",j=new Blob([w],{type:"text/plain;charset=utf-8"}),I=URL.createObjectURL(j),A=document.createElement("a");A.href=I,A.download=S,document.body.appendChild(A),A.click(),document.body.removeChild(A),URL.revokeObjectURL(I),he.success("Logs saved",{description:`Downloaded to ~/Downloads/${S}`})}).catch(()=>{he.error("Failed to download logs")}).finally(()=>{f.current=!1});break}}};return window.addEventListener(vl,g),()=>window.removeEventListener(vl,g)},[s,t,r,o,a,i,c,d,u,m,n,h])},fb=n=>n.role==="assistant",jl=n=>{const s=n.info;if(!fb(s))return;const t=s.time?.completed;return typeof t=="number"?t:void 0},Cr=n=>{if(!n)return!1;if(n.role==="user")return!0;const s=n;return s.clientRole==="user"?!0:!!s.userMessageMarker},Sl=n=>(Array.isArray(n?.parts)?n.parts:[]).map(r=>Bn(r)).join(" ").replace(/\s+/g," ").trim(),pb=(n,s)=>{if(!n||!Cr(n.info))return-1;const t=Sl(n),r=typeof n.info?.time?.created=="number"?n.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return s.forEach((i,c)=>{if(!Cr(i.info))return;const d=Sl(i),u=!!(t&&d&&d===t),p=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,m=typeof r=="number"&&typeof p=="number"?Math.abs(p-r):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 r=="number"?s.findIndex(i=>{if(!Cr(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-r)<1e3}):-1},hb=()=>{const{currentSessionId:n,messages:s,streamingMessageIds:t}=fe(),r=l.useMemo(()=>n?t.get(n)??null:null,[n,t]),o=l.useRef(void 0),a=l.useRef(0),i=l.useCallback(async()=>{if(!n||r)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=s.get(n)||[],u=await Me.getSessionMessages(n),p=await ab(n);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?pb(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(n,y)}else{const x=u[g],y=d[d.length-1],b=jl(x),v=jl(y);if(b&&!v){console.log("[SYNC] Last message completed on server");const N=[...d.slice(0,-1),x],{syncMessages:w}=fe.getState();w(n,N)}}else if(Cr(m.info)){const x=u.slice(-$t.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:y}=fe.getState();y(n,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(-$t.VIEWPORT_MESSAGES);if(g.length>0){console.log(`[SYNC] Restoring ${g.length} messages after cursor`);const{syncMessages:x}=fe.getState();x(n,g)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-$t.VIEWPORT_MESSAGES),{syncMessages:g}=fe.getState();g(n,h)}}else if(u.length>0){const f=u.slice(-$t.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${f.length} messages`);const{syncMessages:h}=fe.getState();h(n,f)}}catch(d){console.debug("Background sync failed:",d)}}},[n,s,r]);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(!n||r)return;const c=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[n,r,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])},gb=()=>{l.useEffect(()=>{let n=!1;return(async()=>{try{const t=await Me.getSessionStatus();if(n||!t)return;const r=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,c=i.type==="busy"||i.type==="retry"?"busy":"idle";r.set(o,c)}),r.size>0&&fe.setState({sessionActivityPhase:r})}catch{}})(),()=>{n=!0}},[])};function xb(){const{git:n}=an(),s=bt(i=>i.currentDirectory),{setActiveDirectory:t,startPolling:r,stopPolling:o,fetchAll:a}=jt();l.useEffect(()=>{if(!s||!n){o();return}return t(s),a(s,n),r(n),()=>{o()}},[s,n,t,r,o,a])}function yb({children:n}){return xb(),e.jsx(e.Fragment,{children:n})}const bb=()=>{const[{isUpdating:n,message:s},t]=l.useState(()=>Jm());return l.useEffect(()=>Xm(t),[]),n?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},wb=({open:n,onOpenChange:s})=>{const[t,r]=l.useState(null);l.useEffect(()=>{if(!n)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:c}=await vn(async()=>{const{getVersion:u}=await import("./vendor-.pnpm-CFPpXnpS.js").then(p=>p.c4);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();r(d)}catch{r("1.3.1")}})():r("1.3.1")},[n]);const o=t;return e.jsx(vs,{open:n,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(Zc,{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(Pl,{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(Rl,{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 kl({apis:n,children:s}){return e.jsx(ja.Provider,{value:n,children:s})}const vb="curl -fsSL https://opencode.ai/install | bash",jb=3e3;function Sb({onCopy:n}){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:n,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Os,{className:"h-4 w-4"})})]})}const kb=3e4;function Nb({onCliAvailable:n}){const[s,t]=l.useState(!1),[r,o]=l.useState(!1),[a,i]=l.useState(!1);l.useEffect(()=>{const p=setTimeout(()=>o(!0),kb);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 vn(async()=>{const{getCurrentWindow:h}=await import("./vendor-.pnpm-CFPpXnpS.js").then(g=>g.c3);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(vb),t(!0),setTimeout(()=>t(!1),2e3)}catch(p){console.error("Failed to copy:",p)}},[]);return l.useEffect(()=>{const p=async()=>{await d()&&n?.()},m=setInterval(p,jb);return p(),()=>clearInterval(m)},[d,n]),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(_o,{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(Dt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(Sb,{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(_o,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."})]}),r&&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 Cb=()=>{const{isAboutDialogOpen:n,setAboutDialogOpen:s}=je();return e.jsx(wb,{open:n,onOpenChange:s})};function Mb({apis:n}){const{initializeApp:s,isInitialized:t}=St(),{error:r,clearError:o,loadSessions:a}=fe(),i=bt(w=>w.currentDirectory),c=bt(w=>w.isSwitchingDirectory),[d,u]=l.useState(!1),{uiFont:p,monoFont:m}=xd(),[f,h]=l.useState(()=>n.runtime.isDesktop),[g,x]=l.useState(()=>n.runtime.isVSCode),[y,b]=l.useState(()=>n.runtime.isDesktop?Rm():!0);l.useEffect(()=>{h(n.runtime.isDesktop),x(n.runtime.isVSCode)},[n.runtime.isDesktop,n.runtime.isVSCode]),l.useEffect(()=>(Za(n),()=>Za(null)),[n]),l.useEffect(()=>{if(typeof document>"u")return;const w=document.documentElement,S=ml[p]?.stack??ml[Vy].stack,j=Zs[m]?.stack??Zs[Nr].stack;w.style.setProperty("--font-sans",S),w.style.setProperty("--font-heading",S),w.style.setProperty("--font-family-sans",S),w.style.setProperty("--font-mono",j),w.style.setProperty("--font-family-mono",j),w.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=S)},[p,m]),l.useEffect(()=>{if(t){const S=setTimeout(()=>{const j=document.getElementById("initial-loading");j&&(j.classList.add("fade-out"),setTimeout(()=>{j.remove()},300))},150);return()=>clearTimeout(S)}},[t]),l.useEffect(()=>{const w=setTimeout(()=>{const S=document.getElementById("initial-loading");S&&!t&&(S.classList.add("fade-out"),setTimeout(()=>{S.remove()},300))},5e3);return()=>clearTimeout(w)},[t]),l.useEffect(()=>{(async()=>{await s()})()},[s]),l.useEffect(()=>{if(c)return;(async()=>{Me.setDirectory(i),await a()})()},[i,c,a]),db(),ub();const v=l.useCallback(()=>{u(w=>!w)},[]);mb(v),hb(),gb(),Fc(),l.useEffect(()=>{const w=S=>{(S.metaKey||S.ctrlKey)&&S.shiftKey&&S.key==="M"&&(S.preventDefault(),u(j=>!j))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),l.useEffect(()=>{r&&setTimeout(()=>o(),5e3)},[r,o]);const N=l.useCallback(()=>{b(!0),window.location.reload()},[]);return f&&!y?e.jsx(ls,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(Nb,{onCliAvailable:N})})}):g?e.jsx(ls,{children:e.jsx(kl,{apis:n,children:e.jsx(il,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Zy,{}),e.jsx(hl,{})]})})})}):e.jsx(ls,{children:e.jsx(kl,{apis:n,children:e.jsx(yb,{children:e.jsx(il,{children:e.jsxs("div",{className:`h-full text-foreground ${f?"bg-transparent":"bg-background"}`,children:[e.jsx(Jy,{}),e.jsx(hl,{}),e.jsx(bb,{}),e.jsx(Cb,{}),d&&e.jsx(tb,{onClose:()=>u(!1)})]})})})})})}const jd=async()=>{if(typeof window>"u")return;let n=null,s=null;try{n=window.localStorage.getItem("homeDirectory"),s=window.localStorage.getItem("lastDirectory")}catch(r){console.warn("Failed to read saved directory preferences:",r)}const t=bt.getState();n&&t.homeDirectory!==n&&t.synchronizeHomeDirectory(n),s&&t.setDirectory(s,{showOverlay:!1})},Sd="/auth/session",Ab=async()=>fetch(Sd,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Db=async n=>fetch(Sd,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:n})}),Fa=({children:n})=>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:n})]}),Eb=({message:n="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:n})})}),Tb=({onRetry:n})=>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(Ee,{type:"button",onClick:n,className:"w-full max-w-xs",children:"Retry"})]})}),Ib=({children:n})=>{const s=l.useMemo(()=>as(),[]),t=l.useMemo(()=>Qt(),[]),r=s||t,[o,a]=l.useState(()=>r?"authenticated":"pending"),[i,c]=l.useState(""),[d,u]=l.useState(!1),[p,m]=l.useState(""),f=l.useRef(null),h=l.useRef(r),g=l.useCallback(async()=>{if(r){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await Ab();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")}},[r]);l.useEffect(()=>{r||g()},[g,r]),l.useEffect(()=>{!r&&o==="locked"&&(h.current=!1)},[r,o]),l.useEffect(()=>{o==="locked"&&f.current&&(f.current.focus(),f.current.select())},[o]),l.useEffect(()=>{r||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await tc(),await sc(),await jd()))())},[r,o]);const x=async y=>{if(y.preventDefault(),!(!i||d)){u(!0),m("");try{const b=await Db(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(Eb,{}):o==="error"?e.jsx(Tb,{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(pm,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(It,{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(Ee,{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(hm,{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:n})},Ro=n=>{if(!n||typeof n!="string")return null;const s=n.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 r=Number.parseInt(t,16);if(Number.isNaN(r))return null;const o=r>>16&255,a=r>>8&255,i=r&255;return`${o} ${a} ${i}`};class Fb{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 r=Ro(s.colors.surface.muted),o=Ro(s.colors.surface.subtle),a=Ro(s.colors.interactive.border);t.push(` --sidebar-base: ${s.colors.surface.muted} !important;`),r&&t.push(` --sidebar-base-rgb: ${r} !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(r)t.push(` --sidebar-overlay-strong: rgb(${r} / ${c}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${r} / ${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),r=document.createElement("style");r.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")),r.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(r),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 r=this.generateSyntaxTokens(s);for(const[o,a]of Object.entries(r))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(s){const t=s.base,r=s.tokens||{};return{commentDoc:r.commentDoc||this.lighten(t.comment,10),stringEscape:r.stringEscape||this.darken(t.string,20),stringInterpolation:r.stringInterpolation||t.variable,stringRegex:r.stringRegex||this.adjustHue(t.string,15),keywordControl:r.keywordControl||t.keyword,keywordOperator:r.keywordOperator||t.operator,keywordImport:r.keywordImport||this.lighten(t.keyword,10),keywordReturn:r.keywordReturn||this.emphasize(t.keyword),functionCall:r.functionCall||this.lighten(t.function,5),functionBuiltin:r.functionBuiltin||this.darken(t.function,10),method:r.method||t.function,methodCall:r.methodCall||this.lighten(t.function,5),variableBuiltin:r.variableBuiltin||this.emphasize(t.variable),variableProperty:r.variableProperty||this.lighten(t.variable,10),variableReadonly:r.variableReadonly||t.number,parameter:r.parameter||t.variable,typePrimitive:r.typePrimitive||this.darken(t.type,10),typeInterface:r.typeInterface||t.type,className:r.className||this.emphasize(t.type),enum:r.enum||t.type,boolean:r.boolean||t.number,null:r.null||this.opacity(t.number,.7),constant:r.constant||t.number,punctuation:r.punctuation||this.opacity(t.foreground,.7),delimiter:r.delimiter||this.opacity(t.foreground,.8),bracket:r.bracket||t.foreground,tag:r.tag||t.keyword,tagAttribute:r.tagAttribute||t.variable,tagAttributeValue:r.tagAttributeValue||t.string,tagBracket:r.tagBracket||this.opacity(t.foreground,.8),decorator:r.decorator||t.function,annotation:r.annotation||t.function,namespace:r.namespace||this.opacity(t.type,.8),module:r.module||this.opacity(t.type,.8),...r}}generateComponentColors(s,t){const r=[];return s.markdown?r.push(...this.generateMarkdownColors(s.markdown,t)):r.push(...this.generateDefaultMarkdownColors(t)),s.chat?r.push(...this.generateChatColors(s.chat,t)):r.push(...this.generateDefaultChatColors(t)),s.tools?r.push(...this.generateToolColors(s.tools,t)):r.push(...this.generateDefaultToolColors(t)),r}generateMarkdownColors(s,t){const r=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return r.push(` --markdown-heading1: ${s.heading1||o};`),r.push(` --markdown-heading2: ${s.heading2||this.opacity(o,.9)};`),r.push(` --markdown-heading3: ${s.heading3||this.opacity(o,.8)};`),r.push(` --markdown-heading4: ${s.heading4||t.colors.surface.foreground};`),r.push(` --markdown-link: ${s.link||o};`),r.push(` --markdown-link-hover: ${s.linkHover||t.colors.primary.hover||this.darken(o,10)};`),r.push(` --markdown-inline-code: ${s.inlineCode||t.colors.syntax.base.string};`),r.push(` --markdown-inline-code-bg: ${s.inlineCodeBackground||a};`),r.push(` --markdown-blockquote: ${s.blockquote||t.colors.surface.mutedForeground};`),r.push(` --markdown-blockquote-border: ${s.blockquoteBorder||t.colors.interactive.border};`),r.push(` --markdown-list-marker: ${s.listMarker||this.opacity(o,.6)};`),r.push(` --markdown-bold: ${s.bold||t.colors.surface.foreground};`),r.push(` --markdown-italic: ${s.italic||this.opacity(t.colors.surface.foreground,.9)};`),r.push(` --markdown-strikethrough: ${s.strikethrough||t.colors.surface.mutedForeground};`),r.push(` --markdown-hr: ${s.hr||t.colors.interactive.border};`),r}generateDefaultMarkdownColors(s){const t=[],r=s.colors.primary.base,o=s.colors.chat?.background||s.colors.surface.background;return t.push(` --markdown-heading1: ${r};`),t.push(` --markdown-heading2: ${this.opacity(r,.9)};`),t.push(` --markdown-heading3: ${this.opacity(r,.8)};`),t.push(` --markdown-heading4: ${s.colors.surface.foreground};`),t.push(` --markdown-link: ${r};`),t.push(` --markdown-link-hover: ${s.colors.primary.hover||this.darken(r,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(r,.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 r=[],o=s.background||t.colors.surface.background;return r.push(` --chat-background: ${o};`),r.push(` --chat-user-message: ${s.userMessage||t.colors.surface.foreground};`),r.push(` --chat-user-message-bg: ${s.userMessageBackground||t.colors.surface.elevated};`),r.push(` --chat-assistant-message: ${s.assistantMessage||t.colors.surface.foreground};`),r.push(` --chat-assistant-message-bg: ${s.assistantMessageBackground||t.colors.surface.muted};`),r.push(` --chat-timestamp: ${s.timestamp||t.colors.surface.mutedForeground};`),r.push(` --chat-divider: ${s.divider||t.colors.interactive.border};`),r.push(` --chat-typing: ${s.typing||t.colors.surface.mutedForeground};`),r}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 r=[];return r.push(` --tools-background: ${s?.background||this.opacity(t.colors.surface.muted,.2)};`),r.push(` --tools-border: ${s?.border||this.opacity(t.colors.interactive.border,.3)};`),r.push(` --tools-header-hover: ${s?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),r.push(` --tools-icon: ${s?.icon||t.colors.surface.mutedForeground};`),r.push(` --tools-title: ${s?.title||t.colors.surface.foreground};`),r.push(` --tools-description: ${s?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),s?.edit?(r.push(` --tools-edit-added: ${s.edit.added||t.colors.status.success};`),r.push(` --tools-edit-added-bg: ${s.edit.addedBackground||t.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${s.edit.removed||t.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${s.edit.removedBackground||t.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${s.edit.modified||t.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${s.edit.modifiedBackground||t.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${s.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(r.push(` --tools-edit-added: ${t.colors.status.success};`),r.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),r.push(` --tools-edit-removed: ${t.colors.status.error};`),r.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),r.push(` --tools-edit-modified: ${t.colors.status.info};`),r.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),r.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),r}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=Qt()?Fm:fa;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 r=s.slice(1);if(r.length===3){const o=parseInt(r[0]+r[0],16),a=parseInt(r[1]+r[1],16),i=parseInt(r[2]+r[2],16);return`rgba(${o}, ${a}, ${i}, ${t})`}else if(r.length===6){const o=parseInt(r.slice(0,2),16),a=parseInt(r.slice(2,4),16),i=parseInt(r.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 r=parseInt(s.slice(1),16),o=Math.round(2.55*t),a=(r>>16)-o,i=(r>>8&255)-o,c=(r&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 r=parseInt(s.slice(1),16),o=Math.round(2.55*t),a=(r>>16)+o,i=(r>>8&255)+o,c=(r&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"}}},Kn=[Pa,Ra];function Gr(n){return Kn.find(s=>s.metadata.id===n)}const kd=Pa.metadata.id,Nd=Ra.metadata.id,Pb=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Cd=n=>n==="dark"?Ra:Pa,Rb=n=>(Kn.find(t=>t.metadata.variant===n)??Cd(n)).metadata.id,pr=(n,s)=>{const t=Gr(n);return t&&t.metadata.variant===s?t:Kn.find(o=>o.metadata.variant===s)??Cd(s)},Lb=typeof window<"u"?l.useLayoutEffect:l.useEffect,qr=(n,s)=>{if(!n)return s==="light"?kd:Nd;const t=Gr(n);return t&&t.metadata.variant===s?t.metadata.id:Rb(s)},Ob=n=>{let s=kd,t=Nd,r="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")r=o;else if(c!==null){if(c==="true")r="system";else if(d){const m=Gr(d);m&&(r=m.metadata.variant==="dark"?"dark":"light",m.metadata.variant==="dark"?t=m.metadata.id:s=m.metadata.id)}}else(u==="light"||u==="dark")&&(r=u);s=qr(a,"light"),t=qr(i,"dark")}if(n){const o=Gr(n);o&&(o.metadata.variant==="light"?s=o.metadata.id:t=o.metadata.id)}return{themeMode:r,lightThemeId:s,darkThemeId:t}};function _b({children:n,defaultThemeId:s}){const t=de.useMemo(()=>new Fb,[]),[r,o]=de.useState(()=>Ob(s)),[a,i]=de.useState(()=>Pb()),[c,d]=de.useState(()=>typeof window>"u"||!Qt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=de.useMemo(()=>Qt(),[]),p=de.useMemo(()=>u&&c?c:r.themeMode==="light"?pr(r.lightThemeId,"light"):r.themeMode==="dark"||a?pr(r.darkThemeId,"dark"):pr(r.lightThemeId,"light"),[u,r,a,c]),m=de.useMemo(()=>u&&c?[c,...Kn]:Kn,[u,c]);de.useEffect(()=>{if(!u)return;const w=I=>{d(I);const A=I.metadata.variant==="dark"?"dark":"light",k=je.getState();k.theme!==A&&k.setTheme(A)},S=I=>{const A=I.detail;A?.theme&&w(A.theme)},j=window.__OPENCHAMBER_VSCODE_THEME__;return j&&w(j),window.addEventListener("openchamber:vscode-theme",S),()=>window.removeEventListener("openchamber:vscode-theme",S)},[u]);const f=de.useCallback(w=>{if(typeof document>"u")return;const S=w.colors.surface.background;as()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=S;let j=document.querySelector('meta[name="theme-color"]');j||(j=document.createElement("meta"),j.setAttribute("name","theme-color"),document.head.appendChild(j)),j.setAttribute("content",S);const I=w.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let A=document.querySelector(`meta[name="theme-color"][media="${I}"]`);A||(A=document.createElement("meta"),A.setAttribute("name","theme-color"),A.setAttribute("media",I),document.head.appendChild(A)),A.setAttribute("content",S)},[]),h=de.useCallback(w=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",w)},[]);Lb(()=>{if(typeof window>"u")return;t.apply(p),h(u),f(p);const w=document.documentElement;w.classList.remove("light","dark"),w.classList.add(p.metadata.variant)},[h,t,p,u,f]),de.useEffect(()=>{if(r.themeMode!=="system"||typeof window>"u")return;const w=window.matchMedia("(prefers-color-scheme: dark)"),S=j=>{i(j.matches)};return i(w.matches),w.addEventListener("change",S),()=>w.removeEventListener("change",S)},[r.themeMode]),de.useEffect(()=>{typeof window>"u"||(localStorage.setItem("themeMode",r.themeMode),localStorage.setItem("lightThemeId",r.lightThemeId),localStorage.setItem("darkThemeId",r.darkThemeId),localStorage.setItem("useSystemTheme",String(r.themeMode==="system")),localStorage.setItem("selectedThemeId",p.metadata.id),localStorage.setItem("selectedThemeVariant",p.metadata.variant==="light"?"light":"dark"))},[r,p]),de.useEffect(()=>{As({themeId:p.metadata.id,themeVariant:p.metadata.variant==="light"?"light":"dark",useSystemTheme:r.themeMode==="system",lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId})},[p.metadata.id,p.metadata.variant,r.themeMode,r.lightThemeId,r.darkThemeId]),de.useEffect(()=>{if(typeof window>"u")return;const w=S=>{const j=S.detail;j&&o(I=>{let A=I.themeMode;j.useSystemTheme===!0?A="system":j.useSystemTheme===!1&&(j.themeVariant==="dark"||j.themeVariant==="light")&&(A=j.themeVariant);let k=I.lightThemeId;typeof j.lightThemeId=="string"&&j.lightThemeId.length>0&&(k=qr(j.lightThemeId,"light"));let M=I.darkThemeId;return typeof j.darkThemeId=="string"&&j.darkThemeId.length>0&&(M=qr(j.darkThemeId,"dark")),A===I.themeMode&&k===I.lightThemeId&&M===I.darkThemeId?I:{themeMode:A,lightThemeId:k,darkThemeId:M}})};return window.addEventListener("openchamber:settings-synced",w),()=>window.removeEventListener("openchamber:settings-synced",w)},[]);const g=de.useCallback(w=>{const S=m.find(j=>j.metadata.id===w);S&&o(j=>S.metadata.variant==="dark"?j.darkThemeId===S.metadata.id&&j.themeMode==="dark"?j:{...j,darkThemeId:S.metadata.id,themeMode:"dark"}:j.lightThemeId===S.metadata.id&&j.themeMode==="light"?j:{...j,lightThemeId:S.metadata.id,themeMode:"light"})},[m]),x=de.useCallback(w=>{o(S=>S.themeMode===w?S:{...S,themeMode:w})},[]),y=de.useCallback(w=>{if(w){o(j=>j.themeMode==="system"?j:{...j,themeMode:"system"});return}const S=p.metadata.variant==="dark"?"dark":"light";o(j=>j.themeMode===S?j:{...j,themeMode:S})},[p.metadata.variant]),b=de.useCallback(w=>{const S=m.find(j=>j.metadata.id===w&&j.metadata.variant==="light");S&&o(j=>j.lightThemeId===S.metadata.id?j:{...j,lightThemeId:S.metadata.id})},[m]),v=de.useCallback(w=>{const S=m.find(j=>j.metadata.id===w&&j.metadata.variant==="dark");S&&o(j=>j.darkThemeId===S.metadata.id?j:{...j,darkThemeId:S.metadata.id})},[m]),N={currentTheme:p,availableThemes:m,setTheme:g,isSystemPreference:r.themeMode==="system",setSystemPreference:y,themeMode:r.themeMode,setThemeMode:x,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:b,setDarkThemePreference:v};return e.jsx(ka.Provider,{value:N,children:n})}const $b=({children:n})=>{const{theme:s,applyTheme:t,fontSize:r,applyTypography:o,padding:a,applyPadding:i}=je();return l.useLayoutEffect(()=>{t(),o(),i()},[s,t,r,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:n})},Bb={getLastAssistantMessage(){const n=fe.getState(),s=n.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const t=n.messages.get(s);if(!t||t.length===0)return console.log("[ERROR] No messages in current session"),null;for(let r=t.length-1;r>=0;r--){const o=t[r];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(n,s=80){return!n||typeof n!="string"||n.length<=s?n:n.substring(0,s)+"…"},truncateMessages(n){return n.map(s=>({...s,parts:(s.parts||[]).map(t=>{const r={...t};return"text"in t&&(r.text=this.truncateString(t.text)),"textPreview"in t&&(r.textPreview=this.truncateString(t.textPreview)),t.state&&(r.state={...t.state},"output"in t.state&&(r.state.output=this.truncateString(t.state.output)),"error"in t.state&&(r.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(r.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),r})}))},getAllMessages(n=!1){const s=fe.getState(),t=s.currentSessionId;if(!t)return console.log("[ERROR] No active session"),[];const r=s.messages.get(t)||[];return console.log(`[MESSAGES] Total messages in session: ${r.length}`),r.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),n?this.truncateMessages(r):r},checkLastMessage(){const n=this.getLastAssistantMessage();if(!n)return!1;const s=n.isEmpty||n.isEmptyResponse;return s?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:n.messageId,isEmpty:n.isEmpty,isEmptyResponse:n.isEmptyResponse,partsCount:n.partsCount}),n.parts.length>0&&console.log("Parts:",n.parts)):console.log("[OK] Last message looks good!"),s},getStreamingState(){const n=fe.getState(),s=n.currentSessionId?n.streamingMessageIds.get(n.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:s,streamingMessageIds:Array.from(n.streamingMessageIds.entries()),messageStreamStates:Array.from(n.messageStreamStates.entries())}),{streamingMessageId:s,streamingMessageIds:n.streamingMessageIds,streamStates:n.messageStreamStates}},findEmptyMessages(){const n=fe.getState(),s=n.currentSessionId;if(!s)return console.log("[ERROR] No active session"),[];const r=(n.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 ${r.length} empty assistant messages`),r.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})}),r},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(n={}){const{includeNonAssistant:s=!1,verbose:t=!0,maxTableRows:r=25}=n,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,N=x.filter(D=>D.type==="tool"),w=x.filter(D=>D.type==="reasoning"),S=p(N.map(D=>u(D.state?.time?.end??D.state?.time?.start))),j=p(w.map(D=>u(D.time?.end??D.time?.start))),I=p([S,j].filter(D=>D!==null)),A=N.some(D=>["pending","running","started"].includes(D.state?.status)),k=w.some(D=>typeof D.time?.end!="number");N.length>0&&(d.withTools+=1),w.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const M=!!(v&&typeof S=="number"&&b<S);M&&(d.completedBeforeTool+=1);const C=!!(v&&typeof j=="number"&&b<j);return C&&(d.completedBeforeReasoning+=1),v&&A&&(d.runningToolsWhenCompleted+=1),v&&k&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:b,latestToolTimestamp:S,latestReasoningTimestamp:j,latestPartTimestamp:I,completed_missing:!v,completed_before_tool:M,completed_before_reasoning:C,running_tools_when_completed:!!(v&&A),reasoning_open_when_completed:!!(v&&k),has_tools:N.length>0,has_reasoning:w.length>0}});return t&&(console.table(m.slice(0,r)),m.length>r&&console.log(`Displayed first ${r} rows out of ${m.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:m}},checkCompletionStatus(){const n=fe.getState(),s=n.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const r=(n.messages.get(s)||[]).filter(y=>y.info.role==="assistant");if(r.length===0)return console.log("[ERROR] No assistant messages"),null;const o=r[r.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=n.messageStreamStates,h=o.info.sessionID?n.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=Bb,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",n=>{try{const s=n.message||"",t=n.filename||"";typeof s=="string"&&s.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&n.preventDefault()}catch{}}));let Nl=!1;const zb=()=>{if(Nl||typeof window>"u")return;Nl=!0;let n={showReasoningTraces:je.getState().showReasoningTraces,autoDeleteEnabled:je.getState().autoDeleteEnabled,autoDeleteAfterDays:je.getState().autoDeleteAfterDays},s=null,t=null;const r=()=>{const a=s;s=null,t=null,a&&Object.keys(a).length>0&&As(a)},o=a=>{s={...s??{},...a},!t&&(t=setTimeout(r,150))};je.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};i.showReasoningTraces!==n.showReasoningTraces&&(c.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==n.autoDeleteEnabled&&(c.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==n.autoDeleteAfterDays&&(c.autoDeleteAfterDays=i.autoDeleteAfterDays),n=i,Object.keys(c).length>0&&o(c)})};let Cl=!1;const Ml="openchamber-typography-base",Hb=()=>{if(typeof document>"u")return;const s=`:root {
|
|
115
|
+
${Object.entries(fa).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
116
|
+
`)}
|
|
117
|
+
}
|
|
118
|
+
`,t=document.getElementById(Ml);if(t){t.textContent=s;return}const r=document.createElement("style");r.id=Ml,r.textContent=s,document.head.appendChild(r)},Wb=()=>{Cl||typeof window>"u"||(Cl=!0,Hb())},Ub=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await tc();await sc();zb();Wb();await jd();typeof window<"u"&&(window.debugContextTokens=()=>{const n=window.__zustand_session_store__;if(!n)return;const s=n.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 Md=document.getElementById("root");if(!Md)throw new Error("Root element not found");gm.createRoot(Md).render(e.jsx(de.StrictMode,{children:e.jsx(_b,{children:e.jsx($b,{children:e.jsx(Ib,{children:e.jsx(Mb,{apis:Ub})})})})}));if(typeof window<"u"){const n=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(s){console.warn("Failed to notify desktop runtime that renderer is ready:",s)}};n(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&n()})}const qb=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{vs as D,qn as S,js as a,Bp as b,T as c,ox as d,ax as e,Qi as f,on as g,ix as h,cx as i,qb as m,id as p,lx as r,xr as t};
|