@openchamber/web 1.2.4 → 1.2.5
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/dist/assets/{ToolOutputDialog-DUsgiKZ7.js → ToolOutputDialog-BK6SvVkC.js} +2 -2
- package/dist/assets/index-BgMc3ajO.css +1 -0
- package/dist/assets/{index-CQ_4iGIA.js → index-DcXQiyJT.js} +2 -2
- package/dist/assets/main-5ipM17PM.js +118 -0
- package/dist/assets/{vendor-.pnpm-COYWCHRJ.js → vendor-.pnpm-B7ko08Tb.js} +318 -318
- package/dist/index.html +3 -3
- package/package.json +1 -1
- package/server/lib/git-service.js +2 -1
- package/dist/assets/index-DjY07vF-.css +0 -1
- package/dist/assets/main-Bt_SaCEa.js +0 -117
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.pnpm-COYWCHRJ.js","assets/vendor--B3aGWKBE.css","assets/ToolOutputDialog-DUsgiKZ7.js","assets/index-CQ_4iGIA.js","assets/index-DjY07vF-.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{t as Jc,c as Zc,j as e,R as Qc,T as ed,P as td,C as sd,A as rd,a as nd,b as Ot,d as Ht,p as xs,e as ys,f as od,g as l,r as ad,h as hs,I as id,i as ld,k as cd,l as dd,m as ud,n as md,o as fd,q as pd,s as It,u as hd,S as gd,v as xd,w as yd,x as gs,y as bd,z as cl,B as dl,D as wd,E as vd,F as de,G as ka,H as bo,J as jd,K as vt,L as wo,M as Sd,U as $t,_ as _r,Z as kd,Y as zs,Q as Ws,W as zt,O as _n,N as Nd,V as pr,X as vo,$ as As,a0 as ul,a1 as Cd,a2 as Md,a3 as Ad,a4 as Dd,a5 as Ed,a6 as Td,a7 as Id,a8 as Fd,a9 as jo,aa as Wo,ab as Pd,ac as Uo,ad as Bn,ae as br,af as ml,ag as Rd,ah as ls,ai as vn,aj as On,ak as Rs,al as Us,am as fl,an as pl,ao as Br,ap as xe,aq as Ns,ar as ms,as as jn,at as Zs,au as ts,av as Na,aw as Vo,ax as hl,ay as Go,az as qo,aA as Ko,aB as $n,aC as zn,aD as Ca,aE as sr,aF as Yo,aG as Tr,aH as Or,aI as Ld,aJ as _d,aK as gl,aL as xl,aM as hr,aN as Bd,aO as Od,aP as Vn,aQ as $d,aR as os,aS as zd,aT as Hd,aU as Gn,aV as Wd,aW as Xo,aX as Jo,aY as Ud,aZ as Vd,a_ as Gd,a$ as So,b0 as qd,b1 as gr,b2 as Qs,b3 as Hn,b4 as Wn,b5 as Zo,b6 as Kd,b7 as Yd,b8 as Xd,b9 as Jd,ba as Zd,bb as Qd,bc as eu,bd as ko,be as un,bf as Qo,bg as tu,bh as su,bi as Sr,bj as ru,bk as nu,bl as ou,bm as yl,bn as au,bo as iu,bp as lu,bq as cu,br as No,bs as du,bt as Ss,bu as uu,bv as Ir,bw as mu,bx as fu,by as pu,bz as hu,bA as gu,bB as xu,bC as yu,bD as bu,bE as wu,bF as vu,bG as ju,bH as Su,bI as ku,bJ as Nu,bK as Cu,bL as Mu,bM as Ma,bN as bl,bO as Au,bP as Du,bQ as Aa,bR as Eu,bS as Tu,bT as Iu,bU as Fu,bV as Pu,bW as Ru,bX as Lu}from"./vendor-.pnpm-COYWCHRJ.js";import{c as _u,l as Bu,g as Ou,r as $u,d as zu,a as Hu,b as Wu,u as Uu,e as Vu,f as Gu,h as qu,i as Ku,j as Yu,k as Xu}from"./index-CQ_4iGIA.js";function T(...r){return Jc(Zc(r))}const wl=(r,s)=>{const t=r??"",n=Math.max(16,s?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>i)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},Sn=r=>r?r==="/"?"/":r.replace(/\/+$/,""):"";function Vt(r,s){if(!r)return"";const t=Sn(r);if(t==="/")return"/";const n=s?Sn(s):void 0;if(n&&n!=="/"){if(t===n)return"~";if(t.startsWith(`${n}/`)){const o=t.slice(n.length+1);return o?`~/${o}`:"~"}}return t}function qn(r,s){if(!r)return"/";const t=Sn(r);if(!t||t==="/")return"/";const n=s?Sn(s):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Ju({delayDuration:r=0,...s}){return e.jsx(nd,{"data-slot":"tooltip-provider",delayDuration:r,...s})}function gt({delayDuration:r=0,...s}){return e.jsx(Ju,{delayDuration:r,children:e.jsx(Qc,{"data-slot":"tooltip",...s})})}function xt({...r}){return e.jsx(ed,{"data-slot":"tooltip-trigger",...r})}function ft({className:r,sideOffset:s=0,children:t,...n}){return e.jsx(td,{children:e.jsxs(sd,{"data-slot":"tooltip-content",sideOffset:s,className:T("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",r),...n,children:[t,e.jsx(rd,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Kn=null;const Da=()=>{const r=new Map;return{getItem:s=>r.get(s)??null,setItem:(s,t)=>{r.set(s,t)},removeItem:s=>{r.delete(s)},clear:()=>{r.clear()},key:s=>Array.from(r.keys())[s]??null,get length(){return r.size}}},Zu=()=>{if(typeof window>"u"||!window.localStorage)return Da();const r=window.localStorage,s=Da();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const p=r.getItem(u);if(p!==null)return p}catch{n()}return s.getItem(u)},setItem:(u,p)=>{if(t)try{r.setItem(u,p),s.removeItem(u);return}catch{n()}s.setItem(u,p)},removeItem:u=>{if(t)try{r.removeItem(u)}catch{n()}s.removeItem(u)},clear:()=>{if(t)try{r.clear()}catch{n()}s.clear()},key:u=>{if(t)try{return r.key(u)}catch{n()}return s.key(u)},get length(){if(t)try{return r.length+s.length}catch{n()}return s.length}}},Qt=()=>(Kn||(Kn=Zu()),Kn),ea={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Qu={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Ea(r){return`--text-${r.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const Cs={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)"}}},mn={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...Cs.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:mn.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...Cs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:mn.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...Cs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:mn.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...Cs.tool.inline})},Fe=Ot()(Ht(xs((r,s)=>({theme:"system",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",pendingDiffFile:null,isMobile:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!1,toolCallExpansion:"collapsed",fontSize:100,padding:100,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,setTheme:t=>{r({theme:t}),s().applyTheme()},toggleSidebar:()=>{r(t=>{const n=!t.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:t=>{r(()=>{if(t&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:t,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:t}})},setSidebarWidth:t=>{r({sidebarWidth:t,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:t=>{r({isSessionSwitcherOpen:t})},setActiveMainTab:t=>{r({activeMainTab:t})},setPendingDiffFile:t=>{r({pendingDiffFile:t})},navigateToDiff:t=>{r({pendingDiffFile:t,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:t}=s();return t&&r({pendingDiffFile:null}),t},setIsMobile:t=>{r({isMobile:t})},toggleCommandPalette:()=>{r(t=>({isCommandPaletteOpen:!t.isCommandPaletteOpen}))},setCommandPaletteOpen:t=>{r({isCommandPaletteOpen:t})},toggleHelpDialog:()=>{r(t=>({isHelpDialogOpen:!t.isHelpDialogOpen}))},setHelpDialogOpen:t=>{r({isHelpDialogOpen:t})},setSessionCreateDialogOpen:t=>{r({isSessionCreateDialogOpen:t})},setSettingsDialogOpen:t=>{r({isSettingsDialogOpen:t})},setSidebarSection:t=>{r({sidebarSection:t})},setEventStreamStatus:(t,n)=>{r({eventStreamStatus:t,eventStreamHint:n??null})},setShowReasoningTraces:t=>{r({showReasoningTraces:t})},setToolCallExpansion:t=>{r({toolCallExpansion:t})},setFontSize:t=>{const n=Math.max(50,Math.min(200,t));r({fontSize:n}),s().applyTypography()},setPadding:t=>{const n=Math.max(50,Math.min(200,t));r({padding:n}),s().applyPadding()},applyTypography:()=>{const{fontSize:t}=s(),n=document.documentElement,o=t/100,a=Object.entries(ea);if(o===1){for(const[i]of a)n.style.removeProperty(Ea(i));return}for(const[i,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(Ea(i),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=s(),n=document.documentElement,o=t/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:t=>{r({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{r(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{r({diffWrapLines:t})},toggleFavoriteModel:(t,n)=>{r(o=>o.favoriteModels.some(i=>i.providerID===t&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===t&&i.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=s();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{r(o=>{const a=o.recentModels.filter(i=>!(i.providerID===t&&i.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||r(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=s(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)}}),{name:"ui-store",storage:ys(()=>Qt()),partialize:r=>({theme:r.theme,isSidebarOpen:r.isSidebarOpen,sidebarWidth:r.sidebarWidth,isSessionSwitcherOpen:r.isSessionSwitcherOpen,activeMainTab:r.activeMainTab,sidebarSection:r.sidebarSection,isSessionCreateDialogOpen:r.isSessionCreateDialogOpen,isSettingsDialogOpen:r.isSettingsDialogOpen,showReasoningTraces:r.showReasoningTraces,toolCallExpansion:r.toolCallExpansion,fontSize:r.fontSize,padding:r.padding,favoriteModels:r.favoriteModels,recentModels:r.recentModels,diffLayoutPreference:r.diffLayoutPreference,diffWrapLines:r.diffWrapLines})}),{name:"ui-store"})),Zt=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",ss=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Vs=()=>Zt()?window.opencodeDesktop??null:null,vl=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const r=window.opencodeDesktop;return r?.getSettings&&r?.updateSettings?{getSettings:r.getSettings.bind(r),updateSettings:r.updateSettings.bind(r)}:null},jl=async()=>{const r=Vs();if(typeof window<"u"){const s=window.__OPENCHAMBER_HOME__;if(s&&s.length>0)return s}if(!r)return null;if(typeof r.homeDirectory=="string"&&r.homeDirectory.length>0)return r.homeDirectory;try{if(!r.getHomeDirectory)return null;const s=await r.getHomeDirectory();if(s?.success&&typeof s.path=="string"&&s.path.length>0)return s.path}catch(s){console.warn("Failed to obtain desktop home directory:",s)}return null},em=async()=>{const r=Vs();if(!r)return null;try{return await r.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},tm=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Sl=async()=>{const r=vl();if(!r)return null;try{return await r.getSettings()}catch(s){return console.warn("Failed to read desktop settings",s),null}},sm=async r=>{const s=vl();if(!s)return null;try{return await s.updateSettings(r)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},rm=async r=>{const s=Vs();if(!s||!s.requestDirectoryAccess)return{success:!0,path:r};try{return await s.requestDirectoryAccess(r)}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},nm=async r=>{const s=Vs();if(!s||!s.startAccessingDirectory)return{success:!0};try{return await s.startAccessingDirectory(r)}catch(t){return console.warn("Failed to start accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},om=async r=>{const s=Vs();if(!s||!s.stopAccessingDirectory)return{success:!0};try{return await s.stopAccessingDirectory(r)}catch(t){return console.warn("Failed to stop accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},am=async()=>{const r=Vs();if(!r||!r.checkForUpdates)return null;try{return await r.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},im=async r=>{const s=Vs();if(!s||!s.downloadUpdate)return!1;try{return await s.downloadUpdate(r),!0}catch(t){return console.warn("Failed to download update",t),!1}},lm=async()=>{const r=Vs();if(!r||!r.restartToUpdate)return!1;try{return await r.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}},cm="/api",dm=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,um=r=>{const s=typeof r=="string"&&r.trim().length>0?r.trim():"/api";if(dm.test(s)||typeof window>"u")return s;const t=window.location?.href||window.location?.origin;if(!t)return s;try{return new URL(s,t).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),s}},mm=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_DESKTOP_SERVER__,s=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!r||!s)return null;const t=typeof r.origin=="string"&&r.origin.length>0?r.origin:null;return t?`${t}/api`:null},qr=r=>r.replace(/\\/g,"/"),Yn=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_RUNTIME_APIS__;return r&&r.runtime?.isDesktop&&r.files?r.files:null};class fm{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=cm){const n=mm()||s;this.baseUrl=um(n),this.client=od({baseUrl:this.baseUrl})}normalizeCandidatePath(s){if(typeof s!="string")return null;const t=s.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(s){const t=s.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],c=s.slice(a.length+(s.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=s.startsWith("/"),o=s.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(s){this.currentDirectory=s}getDirectory(){return this.currentDirectory}async withDirectory(s,t){if(s==null)return t();const n=this.currentDirectory;this.currentDirectory=s;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const s=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&s.add(a)};try{const a=(await this.client.path.get({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!s.size)try{const o=await this.client.project.current({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!s.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!s.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!s.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(s);return this.deriveHomeDirectory(n)}async listSessions(){const s=await this.client.session.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});return Array.isArray(s.data)?s.data:[]}async createSession(s){const t=await this.client.session.create({query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{parentID:s?.parentID,title:s?.title}});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(s){const t=await this.client.session.get({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(s){return(await this.client.session.delete({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||!1}async updateSession(s,t){const n=await this.client.session.update({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{title:t}});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(s){return(await this.client.session.messages({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}async getSessionTodos(s){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(s)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}async sendMessage(s){const t=Date.now(),n=s.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(s.prefaceText&&s.prefaceText.trim()&&o.push({type:"text",text:s.prefaceText}),s.text&&s.text.trim()){const a={type:"text",text:s.text};o.push(a)}if(s.files&&s.files.length>0&&s.files.forEach(a=>{const i={type:"file",mime:a.mime,filename:a.filename,url:a.url};o.push(i)}),s.agentMentions&&s.agentMentions.length>0){const[a]=s.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({path:{id:s.id},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{model:{providerID:s.providerID,modelID:s.modelID},agent:s.agent,parts:o}}),n}async abortSession(s){return!!(await this.client.session.abort({path:{id:s},throwOnError:!0})).data}async getSessionStatus(){try{const s=this.baseUrl.replace(/\/$/,""),t=new URL(`${s}/session/status`);this.currentDirectory&&this.currentDirectory.length>0&&t.searchParams.set("directory",this.currentDirectory);const n=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return{};const o=await n.json().catch(()=>null);return!o||typeof o!="object"?{}:o}catch{return{}}}async respondToPermission(s,t,n){return(await this.client.postSessionIdPermissionsPermissionId({path:{id:s,permissionID:t},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{response:n}})).data||!1}async getConfig(){const s=await this.client.config.get();if(!s.data)throw new Error("Failed to get config");return s.data}async updateConfig(s){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(s){const t=await this.getConfig(),n=s(t);return await this.updateConfig(n)}async getProviders(){const s=await this.client.config.providers({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!s.data)throw new Error("Failed to get providers");return s.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}catch{return[]}}subscribeToEvents(s,t,n,o){this.sseAbortController&&this.sseAbortController.abort();const a=new AbortController;return this.sseAbortController=a,console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const i=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",i);const c=async d=>{try{const u=await this.client.event.subscribe({query:i?{directory:i}:void 0,signal:a.signal,sseMaxRetryAttempts:2,sseDefaultRetryDelay:500,sseMaxRetryDelay:8e3,onSseError:p=>{p instanceof Error&&p.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",p),t&&!a.signal.aborted&&t(p))},onSseEvent:p=>{if(!a.signal.aborted){const f=p.data;f&&typeof f=="object"&&s(f)}}});n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const p of u.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(u){if(u?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",u),t&&t(u);const p=Math.min(500*Math.pow(2,d),8e3);await new Promise(f=>setTimeout(f,p)),a.signal.aborted||await c(d+1)}};try{await c(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortController===a&&(this.sseAbortController=null)}})(),()=>{this.sseAbortController===a&&(this.sseAbortController=null),a.abort()}}async readFile(s){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${s}
|
|
3
|
-
// This would be loaded from the server`}}async listFiles(s){try{const t=s||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model,template:t.template,subtask:t.subtask}))}catch{return[]}}async getCommandDetails(s){try{const t=await this.client.command.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(t.data){const n=t.data.find(o=>o.name===s);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let s;const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;t==="/api"?s="/health":t.endsWith("/api")?s=`${t.slice(0,-4)}/health`:s=`${t}/health`;const n=await fetch(s);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(s){const t=Yn();if(t?.createDirectory)try{return await t.createDirectory(s)}catch(a){const i=a instanceof Error?a.message:String(a);throw new Error(i||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(s){const t=Yn();if(t)try{const n=await t.listDirectory(s||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:qr(o.path),isDirectory:!!o.isDirectory,isFile:!o.isDirectory,isSymbolicLink:!1}))}catch(n){throw console.error("Failed to list directory contents:",n),n}try{const n=new URLSearchParams;s&&s.trim().length>0&&n.set("path",s);const o=n.toString(),a=await fetch(`${this.baseUrl}/fs/list${o?`?${o}`:""}`);if(!a.ok){const c=await a.json().catch(()=>({})),d=typeof c.error=="string"?c.error:"Failed to list directory";throw new Error(d)}const i=await a.json();return!i||!Array.isArray(i.entries)?[]:i.entries}catch(n){throw console.error("Failed to list directory contents:",n),n}}async searchFiles(s,t){const n=Yn(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?qr(o):null;if(n)try{const p=await n.search({directory:o||"",query:s,maxResults:t?.limit});return Array.isArray(p)?p.map(f=>{const m=qr(f.path),h=m.split("/").filter(Boolean).pop()||m,g=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?qr(f.preview[0]):a&&m.startsWith(a)&&m.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:m,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(()=>({})),f=typeof p.error=="string"?p.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const s=await jl();if(s)return s;try{const t=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok){const o=await t.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await t.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(t){return console.warn("Failed to resolve filesystem home directory:",t),null}}async setOpenCodeWorkingDirectory(s){if(!s||typeof s!="string"||!s.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",s),null;const t=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",t,"with path:",s);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},i=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:s}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const Ae=new fm,Co=new Set;function ta(r){return Co.add(r),()=>{Co.delete(r)}}function Ds(r,s){const t=Array.isArray(r)?r:[r],n=Array.from(new Set(t));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:s?.source,timestamp:Date.now()};for(const a of Co)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 kn(r,s){return r.scopes.includes("all")||r.scopes.includes(s)}const pm="https://models.dev/api.json",hm="/api/openchamber/models-metadata",gm=r=>r?.toLowerCase?.()??"",xm=r=>r==="primary"||r==="all"||r===void 0||r===null,$r=r=>typeof r=="object"&&r!==null,Nn=r=>Array.isArray(r)&&r.every(s=>typeof s=="string"),ym=r=>{if(!$r(r))return!1;const s=r;if(s.modalities){const{input:t,output:n}=s.modalities;if(t&&!Nn(t)||n&&!Nn(n))return!1}return!0},bm=r=>{if(!$r(r))return!1;const s=r;return s.models===void 0||$r(s.models)},kl=(r,s)=>{const t=gm(r);return!t||!s?"":`${t}/${s}`},wm=r=>{const s=new Map;if(!$r(r))return s;for(const[t,n]of Object.entries(r)){if(!bm(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!$r(a)))for(const[i,c]of Object.entries(a)){if(!ym(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:Nn(c.modalities.input)?c.modalities.input:void 0,output:Nn(c.modalities.output)?c.modalities.output:void 0}:void 0,cost:c.cost,limit:c.limit,knowledge:typeof c.knowledge=="string"?c.knowledge:void 0,release_date:typeof c.release_date=="string"?c.release_date:void 0,last_updated:typeof c.last_updated=="string"?c.last_updated:void 0},p=kl(o,d);p&&s.set(p,u)}}return s},vm=async()=>{if(typeof fetch!="function")return new Map;const r=[hm,pm];for(const s of r){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(s),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(s,a);if(!i.ok)throw new Error(`Metadata request to ${s} returned status ${i.status}`);const c=await i.json();return wm(c)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${s})`):console.warn(`Failed to fetch model metadata from ${s}:`,o)}finally{n&&clearTimeout(n)}}return new Map},jm=r=>new Promise(s=>setTimeout(s,r)),St=Ot()(Ht(xs((r,s)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,loadProviders:async()=>{try{const t=vm(),n=await Ae.getProviders(),o=Array.isArray(n?.providers)?n.providers:[],a=n?.default||{},i=o.map(f=>{const m=f.models??{},h=Object.keys(m).map(g=>m[g]);return{...f,models:h}}),c=a.provider||i[0]?.id||"",d=i.find(f=>f.id===c),u=a.model||d?.models?.[0]?.id||"";r({providers:i,defaultProviders:a,currentProviderId:c,currentModelId:u});const p=await t;p.size>0&&r({modelsMetadata:p})}catch(t){console.error("Failed to load providers:",t),r({providers:[],defaultProviders:{},currentProviderId:"",currentModelId:""})}},setProvider:t=>{const{providers:n}=s(),o=n.find(a=>a.id===t);if(o){const i=o.models[0]?.id||"";r({currentProviderId:t,currentModelId:i})}},setModel:t=>{r({currentModelId:t})},saveAgentModelSelection:(t,n,o)=>{r(a=>({agentModelSelections:{...a.agentModelSelections,[t]:{providerId:n,modelId:o}}}))},getAgentModelSelection:t=>{const{agentModelSelections:n}=s();return n[t]||null},loadAgents:async()=>{const t=s().agents;let n=null;for(let o=0;o<3;o++)try{const a=await Ae.listAgents(),i=Array.isArray(a)?a:[];r({agents:i});const{providers:c}=s();if(i.length===0)return r({currentAgentName:void 0}),!0;const d=i.filter(f=>xm(f.mode)),p=d.find(f=>f.name==="build")||d[0]||i[0];if(r({currentAgentName:p.name}),p?.model?.providerID&&p?.model?.modelID){const f=c.find(m=>m.id===p.model.providerID);f&&f.models.find(h=>h.id===p.model.modelID)&&r({currentProviderId:p.model.providerID,currentModelId:p.model.modelID})}return!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),r({agents:t}),!1},setAgent:t=>{const{agents:n,providers:o}=s();if(r({currentAgentName:t}),t&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const i=a.getState(),{currentSessionId:c,isOpenChamberCreatedSession:d,initializeNewOpenChamberSession:u,getAgentModelForSession:p}=i;c&&a.setState(f=>{const m=new Map(f.currentAgentContext);return m.set(c,t),{currentAgentContext:m}}),c&&d(c)&&(p(c,t)||u(c,n))}}if(t&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const{currentSessionId:c,getAgentModelForSession:d}=a.getState();if(c&&d(c,t))return}const i=n.find(c=>c.name===t);if(i?.model?.providerID&&i?.model?.modelID){const c=o.find(d=>d.id===i.model.providerID);c&&c.models.find(u=>u.id===i.model.modelID)&&r({currentProviderId:i.model.providerID,currentModelId:i.model.modelID})}}},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Ae.checkHealth();return r({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await jm(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),r({isConnected:!1}),!1},initializeApp:async()=>{try{console.log("Starting app initialization...");const t=await s().checkConnection();if(console.log("Connection check result:",t),!t){console.log("Server not connected"),r({isConnected:!1});return}console.log("Initializing app..."),await Ae.initApp(),console.log("Loading providers..."),await s().loadProviders(),console.log("Loading agents..."),await s().loadAgents(),r({isInitialized:!0,isConnected:!0}),console.log("App initialized successfully")}catch(t){console.error("Failed to initialize app:",t),r({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:t,currentProviderId:n}=s();return t.find(o=>o.id===n)},getCurrentModel:()=>{const t=s().getCurrentProvider(),{currentModelId:n}=s();if(t)return t.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:t,currentAgentName:n}=s();if(n)return t.find(o=>o.name===n)},getModelMetadata:(t,n)=>{const o=kl(t,n);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)}}),{name:"config-store",storage:ys(()=>Qt()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=St);let Ta=null;Ta||(Ta=ta(async r=>{const s=[];if(kn(r,"agents")){const{loadAgents:t}=St.getState();s.push(t().then(()=>{}))}if(kn(r,"providers")){const{loadProviders:t}=St.getState();s.push(t())}s.length>0&&await Promise.all(s)}));const Bt={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Sm=180,Jt=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function sa(r){const s=Jt();return s?s.checkIsGitRepository(r):_u(r)}async function km(r){const s=Jt();return s?s.getGitStatus(r):Ou(r)}async function Nm(r,s){const t=Jt();return t?t.deleteGitBranch(r,s):zu(r,s)}async function Cm(r,s){const t=Jt();return t?t.deleteRemoteBranch(r,s):Hu(r,s)}async function Mm(r){const s=Jt();return s?s.listGitWorktrees(r):Bu(r)}async function Am(r,s){const t=Jt();return t?t.addGitWorktree(r,s):Xu(r,s)}async function Nl(r,s){const t=Jt();return t?t.removeGitWorktree(r,s):$u(r,s)}async function Dm(r){const s=Jt();return s?s.ensureOpenChamberIgnored(r):Ku(r)}async function Em(r,s={}){const t=Jt();return t?t.gitPush(r,s):Yu(r,s)}async function Tm(){const r=Jt();return r?r.getGitIdentities():qu()}async function Im(r){const s=Jt();return s?s.createGitIdentity(r):Vu(r)}async function Fm(r,s){const t=Jt();return t?t.updateGitIdentity(r,s):Uu(r,s)}async function Pm(r){const s=Jt();return s?s.deleteGitIdentity(r):Wu(r)}async function Rm(r){const s=Jt();return s?s.getCurrentGitIdentity(r):Gu(r)}const Lm=".openchamber",Es=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ia=(r,s)=>{const t=Es(r),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Cl=r=>r?r.startsWith("refs/heads/")?r.substring(11):r.startsWith("heads/")?r.substring(6):r.startsWith("refs/")?r.substring(5):r:"",_m=async r=>{try{await Ae.createDirectory(r)}catch(s){if(s instanceof Error&&/exist/i.test(s.message))return;throw s}};async function Bm(r,s){const t=Es(r),n=Ia(t,Lm);return await _m(n),Ia(n,s)}async function Om(r){const{projectDirectory:s,worktreeSlug:t,branch:n,createBranch:o}=r,a=Es(s),i=await Bm(a,t);return await Am(a,{path:i,branch:n,createBranch:!!o}),{path:i,branch:n,label:Cl(n),projectDirectory:a,relativePath:i.startsWith(`${a}/`)?i.slice(a.length+1):i}}async function Fa(r){const{projectDirectory:s,path:t,force:n}=r,o=Es(s);await Nl(o,{path:t,force:n})}async function $m(r){const{projectDirectory:s,path:t,branch:n,force:o,deleteRemote:a,remote:i}=r,c=Es(s),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Nl(c,{path:t,force:o}),d&&(await Nm(c,{branch:d,force:!0}),a))try{await Cm(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Cn(r){const s=Es(r);return Mm(s)}async function fn(r){const s=Es(r),t=await km(s);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function Mn(r,s){const t=Es(r),n=Es(s.worktree);return{path:n,branch:s.branch??"",label:Cl(s.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const Pa=r=>{if(!r||typeof r!="object")return null;const s={};return typeof r.showReasoningTraces=="boolean"&&(s.showReasoningTraces=r.showReasoningTraces),Object.keys(s).length>0?s:null},zm=r=>!r||typeof r!="object"?null:{showReasoningTraces:r.showReasoningTraces},Hm=r=>{const s=Fe.getState();typeof r.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(r.showReasoningTraces)},Wm=async()=>{if(typeof window>"u")return null;if(Zt()){const s=window.opencodeAppearance;if(!s||typeof s.load!="function")return null;try{const t=await s.load();return Pa(typeof t=="object"&&t!==null?t:null)}catch(t){return console.warn("Failed to load appearance preferences from desktop storage:",t),null}}const r=localStorage.getItem("appearance-preferences");if(!r)return null;try{const s=JSON.parse(r),t=zm(s);return Pa(t)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let Ml=null;const Ra=r=>{Ml=r},Al=()=>Ml,pn=r=>{typeof window>"u"||(r.themeId&&localStorage.setItem("selectedThemeId",r.themeId),r.themeVariant&&localStorage.setItem("selectedThemeVariant",r.themeVariant),r.lightThemeId&&localStorage.setItem("lightThemeId",r.lightThemeId),r.darkThemeId&&localStorage.setItem("darkThemeId",r.darkThemeId),typeof r.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(r.useSystemTheme)),r.lastDirectory&&localStorage.setItem("lastDirectory",r.lastDirectory),r.homeDirectory&&(localStorage.setItem("homeDirectory",r.homeDirectory),window.__OPENCHAMBER_HOME__=r.homeDirectory),Array.isArray(r.pinnedDirectories)&&r.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(r.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},Dl=()=>{const r=Fe.persist;if(r&&typeof r=="object")return r},El=()=>Al()?.settings??null,hn=r=>{const s=Fe.getState();typeof r.showReasoningTraces=="boolean"&&r.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(r.showReasoningTraces)},La=r=>{if(!r||typeof r!="object")return null;const s=r,t={};return typeof s.themeId=="string"&&s.themeId.length>0&&(t.themeId=s.themeId),(s.useSystemTheme===!0||s.useSystemTheme===!1)&&(t.useSystemTheme=s.useSystemTheme),typeof s.themeVariant=="string"&&(s.themeVariant==="light"||s.themeVariant==="dark")&&(t.themeVariant=s.themeVariant),typeof s.lightThemeId=="string"&&s.lightThemeId.length>0&&(t.lightThemeId=s.lightThemeId),typeof s.darkThemeId=="string"&&s.darkThemeId.length>0&&(t.darkThemeId=s.darkThemeId),typeof s.lastDirectory=="string"&&s.lastDirectory.length>0&&(t.lastDirectory=s.lastDirectory),typeof s.homeDirectory=="string"&&s.homeDirectory.length>0&&(t.homeDirectory=s.homeDirectory),Array.isArray(s.approvedDirectories)&&(t.approvedDirectories=s.approvedDirectories.filter(n=>typeof n=="string"&&n.length>0)),Array.isArray(s.securityScopedBookmarks)&&(t.securityScopedBookmarks=s.securityScopedBookmarks.filter(n=>typeof n=="string"&&n.length>0)),Array.isArray(s.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(s.pinnedDirectories.filter(n=>typeof n=="string"&&n.length>0)))),typeof s.showReasoningTraces=="boolean"&&(t.showReasoningTraces=s.showReasoningTraces),t},Um=async()=>{const r=El();if(r)try{const s=await r.load();return La(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 La(t)}catch(s){return console.warn("Failed to load shared settings from server:",s),null}},Tl=async()=>{if(typeof window>"u")return;const r=Dl(),s=t=>{pn(t);const n=()=>hn(t);if(r?.hasHydrated?.())n();else if(n(),r?.onFinishHydration){const o=r.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))};try{const t=Zt()?await Sl():await Um();t&&s(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},ks=async r=>{if(typeof window>"u")return;if(Zt()){try{const t=await sm(r);t&&(pn(t),hn(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const s=El();if(s)try{const t=await s.save(r);t&&(pn(t),hn(t));return}catch(t){console.warn("Failed to update settings via runtime settings API:",t)}try{const t=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(r)});if(!t.ok){console.warn("Failed to update shared settings via API:",t.status,t.statusText);return}const n=await t.json().catch(()=>null);n&&(pn(n),hn(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Il=async()=>{if(typeof window>"u")return;const r=Dl();try{const s=await Wm();if(!s)return;const t=()=>Hm(s);if(r?.hasHydrated?.()){t();return}if(t(),r?.onFinishHydration){const n=r.onFinishHydration(()=>{n?.(),t()})}}catch(s){console.warn("Failed to load appearance preferences:",s)}},ra="Updating OpenCode configuration...";let ps=0,Hs=ra;const Mo=new Set;function An(){const r={isUpdating:ps>0,message:Hs};Mo.forEach(s=>s(r))}function $s(r){ps+=1,ps===1?(Hs=r||ra,An()):r&&(Hs=r,An())}function rs(){ps!==0&&(ps-=1,ps===0&&(Hs=ra,An()))}function is(r){Hs===r&&ps>0||(Hs=r,ps>0&&An())}function Vm(r){return Mo.add(r),r({isUpdating:ps>0,message:Hs}),()=>{Mo.delete(r)}}function Gm(){return{isUpdating:ps>0,message:Hs}}const Fr="useAgentsStore",Dn=r=>new Promise(s=>setTimeout(s,r)),qm=2e4,_a=300,Ba=4,Km=800,Ym=200,Xm=2e3,wr=Ot()(Ht(xs((r,s)=>({selectedAgentName:null,agents:[],isLoading:!1,setSelectedAgent:t=>{r({selectedAgentName:t})},loadAgents:async()=>{r({isLoading:!0});const t=s().agents;let n=null;for(let o=0;o<3;o++)try{const a=await Ae.listAgents();return r({agents:a,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),r({agents:t,isLoading:!1}),!1},createAgent:async t=>{$s("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.tools&&Object.keys(t.tools).length>0&&(o.tools=t.tools),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),console.log("[AgentsStore] Agent config to save:",o);const a=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const u=i?.error||"Failed to create agent";throw new Error(u)}if(console.log("[AgentsStore] Agent created successfully"),i?.requiresReload??!0)return n=!0,await dr({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadAgents();return d&&Ds("agents",{source:Fr}),d}catch(o){return console.error("[AgentsStore] Failed to create agent:",o),!1}finally{n||rs()}},updateAgent:async(t,n)=>{$s("Updating agent configuration…");let o=!1;try{console.log("[AgentsStore] Updating agent:",t),console.log("[AgentsStore] Config received:",n);const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.tools!==void 0&&(a.tools=n.tools),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable),console.log("[AgentsStore] Agent config to update:",a);const i=await fetch(`/api/config/agents/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),c=await i.json().catch(()=>null);if(!i.ok){const p=c?.error||"Failed to update agent";throw new Error(p)}if(console.log("[AgentsStore] Agent updated successfully"),c?.requiresReload??!0)return o=!0,await dr({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadAgents();return u&&Ds("agents",{source:Fr}),u}catch(a){return console.error("[AgentsStore] Failed to update agent:",a),!1}finally{o||rs()}},deleteAgent:async t=>{$s("Deleting agent configuration…");let n=!1;try{const o=await fetch(`/api/config/agents/${encodeURIComponent(t)}`,{method:"DELETE"}),a=await o.json().catch(()=>null);if(!o.ok){const d=a?.error||"Failed to delete agent";throw new Error(d)}if(console.log("[AgentsStore] Agent deleted successfully"),a?.requiresReload??!0)return n=!0,await dr({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadAgents();return c&&Ds("agents",{source:Fr}),s().selectedAgentName===t&&r({selectedAgentName:null}),c}catch(o){return console.error("Failed to delete agent:",o),!1}finally{n||rs()}},getAgentByName:t=>{const{agents:n}=s();return n.find(o=>o.name===t)}}),{name:"agents-store",storage:ys(()=>Qt()),partialize:r=>({selectedAgentName:r.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=wr);async function Jm(r){const s=typeof r=="number"&&r>0?Math.min(r,_a):0;s>0&&await Dn(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<qm;){n+=1,is(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ae.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=Ba&&a<1200?_a:Math.min(Km+Math.max(0,n-Ba)*Ym,Xm);await Dn(i)}throw o||new Error("OpenCode did not become ready in time")}async function dr(r={}){const{message:s,delayMs:t}=r;try{is(s||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("agents-store"),window.localStorage.removeItem("config-store"))}catch(n){console.warn("[AgentsStore] Failed to prepare config refresh:",n)}try{await Jm(t),is("Refreshing providers and agents…");const n=St.getState(),o=wr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),Ds("agents",{source:Fr})}catch(n){console.error("[AgentsStore] Failed to refresh configuration after OpenCode restart:",n),is("OpenCode reload failed. Please retry refreshing configuration manually."),await Dn(1500)}finally{rs()}}async function Zm(r){await dr(r)}async function Qm(r){$s("Reloading OpenCode configuration…");try{const s=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await s.json().catch(()=>null);if(!s.ok){const n=t?.error||"Failed to reload configuration";throw new Error(n)}t?.requiresReload?await dr({message:t.message,delayMs:t.reloadDelayMs}):await dr(r)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),is("Failed to reload configuration. Please try again."),await Dn(2e3),rs(),s}}let Oa=null;Oa||(Oa=ta(r=>{if(r.source!==Fr&&kn(r,"agents")){const{loadAgents:s}=wr.getState();s()}}));const Pr="useCommandsStore",Ao=r=>new Promise(s=>setTimeout(s,r)),ef=2e4,$a=300,za=4,tf=800,sf=200,rf=2e3,vr=Ot()(Ht(xs((r,s)=>({selectedCommandName:null,commands:[],isLoading:!1,setSelectedCommand:t=>{r({selectedCommandName:t})},loadCommands:async()=>{r({isLoading:!0});const t=s().commands;let n=null;for(let o=0;o<3;o++)try{const a=await Ae.listCommandsWithDetails();return r({commands:a,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load commands:",n),r({commands:t,isLoading:!1}),!1},createCommand:async t=>{$s("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),console.log("[CommandsStore] Command config to save:",o);const a=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const u=i?.error||"Failed to create command";throw new Error(u)}if(console.log("[CommandsStore] Command created successfully"),i?.requiresReload??!0)return n=!0,await Xn({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadCommands();return d&&Ds("commands",{source:Pr}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||rs()}},updateCommand:async(t,n)=>{$s("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=await fetch(`/api/config/commands/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),c=await i.json().catch(()=>null);if(!i.ok){const p=c?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),c?.requiresReload??!0)return o=!0,await Xn({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadCommands();return u&&Ds("commands",{source:Pr}),u}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||rs()}},deleteCommand:async t=>{$s("Deleting command configuration…");let n=!1;try{const o=await fetch(`/api/config/commands/${encodeURIComponent(t)}`,{method:"DELETE"}),a=await o.json().catch(()=>null);if(!o.ok){const d=a?.error||"Failed to delete command";throw new Error(d)}if(console.log("[CommandsStore] Command deleted successfully"),a?.requiresReload??!0)return n=!0,await Xn({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadCommands();return c&&Ds("commands",{source:Pr}),s().selectedCommandName===t&&r({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||rs()}},getCommandByName:t=>{const{commands:n}=s();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:ys(()=>Qt()),partialize:r=>({selectedCommandName:r.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=vr);async function nf(r){const s=typeof r=="number"&&r>0?Math.min(r,$a):0;s>0&&await Ao(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<ef;){n+=1,is(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ae.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=za&&a<1200?$a:Math.min(tf+Math.max(0,n-za)*sf,rf);await Ao(i)}throw o||new Error("OpenCode did not become ready in time")}async function Xn(r={}){const{message:s,delayMs:t}=r;try{is(s||"Reloading OpenCode configuration…"),typeof window<"u"&&window.localStorage&&(window.localStorage.removeItem("commands-store"),window.localStorage.removeItem("config-store"))}catch(n){console.warn("[CommandsStore] Failed to prepare config refresh:",n)}try{await nf(t),is("Refreshing providers and commands…");const n=St.getState(),o=vr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),Ds("commands",{source:Pr})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),is("OpenCode reload failed. Please retry refreshing configuration manually."),await Ao(1500)}finally{rs()}}let Ha=null;Ha||(Ha=ta(r=>{if(r.source!==Pr&&kn(r,"commands")){const{loadCommands:s}=vr.getState();s()}}));const of=3e4,af=40,lf=60,cf=(r,s,t)=>{const n=r.trim(),o=s.trim().toLowerCase();return`${n}::${o}::${t}`},na=Ot()(Ht((r,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=lf){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=cf(a,i,o),d=Date.now(),u=s().cache[c];if(u&&d-u.timestamp<of)return u.files;const p=s().inFlight[c];if(p)return p;const f=Ae.searchFiles(i,{directory:a,limit:o}).then(m=>(r(h=>{const g={...h.cache,[c]:{files:m,timestamp:Date.now()}},x=h.cacheKeys.filter(y=>y!==c);for(x.push(c);x.length>af;){const y=x.shift();y&&delete g[y]}return{cache:g,cacheKeys:x}}),m)).finally(()=>{r(m=>{const h={...m.inFlight};return delete h[c],{inFlight:h}})});return r(m=>({inFlight:{...m.inFlight,[c]:f}})),f},invalidateDirectory(t){if(!t||t.trim().length===0){r({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;r(a=>{const i={...a.cache},c=a.cacheKeys.filter(p=>p.startsWith(o)?(delete i[p],!1):!0),d=Object.entries(a.inFlight).filter(([p])=>!p.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"}));var df={};let Ms=null;const fs=Qt(),Wa=fs.getItem("lastDirectory"),uf=typeof Wa=="string"&&Wa.length>0,Kr=(r,s)=>((s?.showOverlay??!0)&&$s("Switching project directory…"),Ae.setOpenCodeWorkingDirectory(r).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),Yr=(r,s,t)=>{const{showOverlay:n}=s,o=()=>{try{ge.getState().loadSessions()}catch(a){console.error("Failed to reload sessions after directory change:",a)}};(async()=>{let a=null;try{a=await r}catch(i){console.error("Failed to update OpenCode working directory:",i),n&&(is("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 Zm({message:"Refreshing OpenCode configuration…"});try{await vr.getState().loadCommands();try{Ds("commands",{source:"useCommandsStore"})}catch(i){console.warn("Failed to emit command configuration change:",i)}}catch(i){console.warn("Failed to reload commands after directory change:",i)}}else n&&rs()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(is("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),rs())}finally{t?.(a),o()}})()},Xr=r=>{try{na.getState().invalidateDirectory(r)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},En=()=>{if(typeof window<"u"){const s=fs.getItem("lastDirectory");if(s)return s;if(Ms)return Ms;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 Ms=t,fs.setItem("homeDirectory",t),t;const n=fs.getItem("homeDirectory");if(n)return Ms=n,n}const r=typeof process<"u"&&df?.HOME;return r||process?.cwd?.()||"/"},mf=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.replace(/\\/g,"/");if(t.length>1){const n=t.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return t==="/"||t.length===0?null:t},ff=r=>(Ms=r,typeof window<"u"&&fs.setItem("homeDirectory",r),ks({homeDirectory:r}),r),Fl=async()=>{const r=n=>{const o=mf(n);return o?ff(o):null};try{const n=await Ae.getFilesystemHome(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Ae.getSystemInfo(),o=r(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await jl(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const s=En(),t=r(s);return t||s},er=En();er&&Ae.setDirectory(er);const pf=!!(er&&er!=="/"),jt=Ot()(Ht((r,s)=>({currentDirectory:er,directoryHistory:[er],historyIndex:0,homeDirectory:er,hasPersistedDirectory:uf,isHomeReady:pf,isSwitchingDirectory:!1,setDirectory:(t,n)=>{console.log("[DirectoryStore] setDirectory called with path:",t);const o=n?.showOverlay??!0;Ae.setDirectory(t),Xr();const a=Kr(t,{showOverlay:o});console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),r(i=>{const c=[...i.directoryHistory.slice(0,i.historyIndex+1),t];return fs.setItem("lastDirectory",t),ks({lastDirectory:t}),{currentDirectory:t,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),Yr(a,{showOverlay:o},()=>{r(i=>i.currentDirectory!==t?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})},goBack:()=>{const t=s();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];Ae.setDirectory(o),Xr();const a=Kr(o);fs.setItem("lastDirectory",o),ks({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Yr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goForward:()=>{const t=s();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];Ae.setDirectory(o),Xr();const a=Kr(o);fs.setItem("lastDirectory",o),ks({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Yr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=s(),o=Ms||s().homeDirectory||En();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=Ms||En();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=Ms||s().homeDirectory||await Fl();s().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=s(),o=t;Ms=o;const a=n.homeDirectory!==o,i=fs.getItem("lastDirectory"),c=typeof i=="string"&&i.length>0,d=!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||r({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",p={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d&&(p.currentDirectory=o,p.directoryHistory=[o],p.historyIndex=0,p.isSwitchingDirectory=!0),r(()=>p),d&&u){Ae.setDirectory(o),Xr(),fs.setItem("lastDirectory",o),ks({lastDirectory:o});const f=Kr(o,{showOverlay:!1});Yr(f,{showOverlay:!1},()=>{r(m=>m.currentDirectory!==o?{}:m.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}ks({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Fl().then(r=>{jt.getState().synchronizeHomeDirectory(r)});const Pl=Qt(),Rl="oc.sessionSelectionByDirectory",Ua=".openchamber",hf=()=>{try{const r=Pl.getItem(Rl);if(!r)return{};const s=JSON.parse(r);return!s||typeof s!="object"?{}:Object.entries(s).reduce((t,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(t[n]=o),t),{})}catch{return{}}};let gn=null;const oa=()=>(gn||(gn=hf()),gn),Ll=r=>{gn=r;try{Pl.setItem(Rl,JSON.stringify(r))}catch{}},_l=r=>{if(!r)return null;const t=oa()[r];return typeof t=="string"?t:null},Gs=(r,s)=>{if(!r)return;const t={...oa()};s?t[r]=s:delete t[r],Ll(t)},gf=(r,s)=>{if(!r)return;const t=_l(r);if(!t)return;if(!new Set(s).has(t)){const o={...oa()};delete o[r],Ll(o)}},Va=async(r,s)=>{const t=r.status??await fn(r.path).catch(()=>{});await $m({projectDirectory:r.projectDirectory,path:r.path,branch:r.branch,force:!!t?.isDirty,deleteRemote:!!s?.deleteRemoteBranch,remote:s?.remoteName})},Lt=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},or=(r,s)=>{const t=r.find(n=>n.id===s);return t?Lt(t.directory??null):null},xf=async(r,s,t)=>{const n=Lt(s);if(!n||r.length===0)return null;const o=r.map(u=>({id:u.id,directory:Lt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Cn(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const p=new Map(t);return o.forEach(({id:f})=>{p.delete(f)&&(u=!0)}),u?p:null}const i=new Map;a.forEach(u=>{const p=Mn(n,u),f=Lt(p.path)??p.path;f!==n&&i.set(f,p)});let c=!1;const d=new Map(t);return o.forEach(({id:u,directory:p})=>{const f=i.get(p);if(!f){d.delete(u)&&(c=!0);return}const m=d.get(u);(!m||m.path!==f.path||m.branch!==f.branch||m.label!==f.label)&&(d.set(u,f),c=!0)}),c?d:null},rt=Ot()(Ht(xs((r,s)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],loadSessions:async()=>{r({isLoading:!0,error:null});try{const n=jt.getState().currentDirectory??Ae.getDirectory()??null,o=Ae.getApiClient(),a=async A=>{const N=await o.session.list({query:A?{directory:A}:void 0});return Array.isArray(N.data)?N.data:[]},i=Lt(n),c=i?await sa(i).catch(()=>!1):!1,d=await a(i||null),u=[];let p=[];if(n&&c&&i){const A=`${i}/${Ua}`;try{const N=new Set;A&&(await Ae.listLocalDirectory(A)).filter(E=>E.isDirectory).forEach(E=>{const $=/^([A-Za-z]:)?\//.test(E.path)?E.path:`${A}/${E.name}`;N.add(Lt($)??$)});const M=await Cn(i);Array.isArray(M)&&(p=M.map(C=>Mn(i,C)).filter(C=>C.path.includes(`/${Ua}/`)),p.forEach(C=>N.add(C.path))),N.size>0&&(await Promise.allSettled(Array.from(N).map(E=>a(E)))).forEach(E=>{E.status==="fulfilled"&&Array.isArray(E.value)&&u.push(...E.value)})}catch{p=[]}}const f=new Set;i&&f.add(i),p.forEach(A=>{const N=Lt(A.path);N&&f.add(N)});const m=[...d,...u].filter(A=>{const N=A.directory??i??null,M=Lt(N);return M?f.has(M):!1}),h=s(),g=h.lastLoadedDirectory??null,x=n!==g;let y=[...m],b=h.currentSessionId;const k=A=>{y=[A,...y.filter(N=>N.id!==A.id)]};if(x)b=y.length>0?y[0].id:null;else if(b){if(!y.some(N=>N.id===b)){const N=h.sessions.find(M=>M.id===b);if(N)k(N);else try{const M=await Ae.getSession(b);k(M)}catch{b=y.length>0?y[0].id:null}}}else b=y.length>0?y[0].id:null;const j=y.reduce((A,N)=>(A.some(M=>M.id===N.id)||A.push(N),A),[]);b&&!j.some(A=>A.id===b)&&(b=j.length>0?j[0].id:null);const v=new Set(j.map(A=>A.id));if(n){gf(n,v);const A=_l(n);A&&v.has(A)&&(b=A)}let S=null;try{S=await xf(j,n,h.worktreeMetadata)}catch(A){console.debug("Failed to refresh worktree metadata during session load:",A)}const w=(()=>{const A=S??h.worktreeMetadata;if(!x||!i)return A;const N=new Map;return A.forEach((M,C)=>{Lt(M.projectDirectory)===i&&N.set(C,M)}),N})(),D=(()=>{if(!b)return i??null;const A=w.get(b)?.path;if(A)return Lt(A)??A;const N=or(j,b);return N||(i??null)})();try{Ae.setDirectory(D??void 0)}catch(A){console.warn("Failed to sync OpenCode directory after session load:",A)}r({sessions:j,currentSessionId:b,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:w,availableWorktrees:p}),Gs(D??n,b)}catch(t){r({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,n,o)=>{r({error:null});const a=jt.getState(),i=Lt(a.currentDirectory),c=Lt(n??Ae.getDirectory()??i),d=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=s(),p=new Set(u.sessions.map(g=>g.id)),f={id:d,title:t||"New session",parentID:o??void 0,directory:c??null,projectID:u.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(r(g=>({sessions:[f,...g.sessions],currentSessionId:d,webUICreatedSessions:new Set([...g.webUICreatedSessions,d]),isLoading:!1})),c)try{Ae.setDirectory(c)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const m=g=>{r(x=>({sessions:x.sessions.map(b=>b.id===d?g:b),currentSessionId:g.id,webUICreatedSessions:new Set([...Array.from(x.webUICreatedSessions).filter(b=>b!==d),g.id])})),Gs(c??null,g.id)},h=async()=>{const g=Ae.getApiClient(),x=20;for(let y=0;y<x;y+=1){try{const b=await g.session.list({query:c?{directory:c}:void 0}),j=(Array.isArray(b.data)?b.data:[]).find(v=>!(p.has(v.id)||t&&v.title&&v.title!==t));if(j)return j}catch(b){console.debug("Session poll attempt failed:",b)}await new Promise(b=>setTimeout(b,2e3))}return null};try{const g=()=>Ae.createSession({title:t,parentID:o??void 0});let x=null;try{x=c?await Ae.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?(m(x),x):(r(y=>({sessions:y.sessions.filter(b=>b.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(b=>b!==d)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return r(x=>({sessions:x.sessions.filter(y=>y.id!==d),currentSessionId:u.currentSessionId,webUICreatedSessions:new Set(Array.from(x.webUICreatedSessions).filter(y=>y!==d)),isLoading:!1,error:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{r({isLoading:!0,error:null});const o=s().worktreeMetadata.get(t),a=or(s().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await Va(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Ae.deleteSession(t);if(!(i?await Ae.withDirectory(i,d):await d()))return r(m=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const g=new Map(m.worktreeMetadata);g.delete(t),h.worktreeMetadata=g}return h}),!1;let p=null;r(m=>{const h=m.sessions.filter(y=>y.id!==t);p=m.currentSessionId===t?null:m.currentSessionId;const g=new Map(m.worktreeMetadata);g.delete(t);const x=n?.archiveWorktree&&o?m.availableWorktrees.filter(y=>Lt(y.path)!==Lt(o.path)):m.availableWorktrees;return{sessions:h,currentSessionId:p,isLoading:!1,worktreeMetadata:g,availableWorktrees:x}});const f=i??Ae.getDirectory()??null;return Gs(f,p),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return r(c?p=>{const f=new Map(p.worktreeMetadata);return f.delete(t),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(x=>typeof x=="string"&&x.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};r({isLoading:!0,error:null});const a=[],i=[],c=new Set,d=[],u=new Set;for(const x of o)try{const y=s().worktreeMetadata.get(x),b=or(s().sessions,x),k=y?.path??b;y&&n?.archiveWorktree&&!u.has(y.path)&&(await Va(y,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c.add(x),d.push({path:y.path,projectDirectory:y.projectDirectory}),u.add(y.path));const j=()=>Ae.deleteSession(x);(k?await Ae.withDirectory(k,j):await j())?(a.push(x),y?.path&&!d.some(S=>S.path===y.path)&&d.push({path:y.path,projectDirectory:y.projectDirectory})):i.push(x)}catch{i.push(x)}const p=jt.getState();d.forEach(({path:x,projectDirectory:y})=>{p.currentDirectory===x&&p.setDirectory(y,{showOverlay:!1})});const f=new Set(a),m=i.length>0?i.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let h=null;r(x=>{const y=x.sessions.filter(v=>!f.has(v.id));x.currentSessionId&&f.has(x.currentSessionId)?h=y.length>0?y[0].id:null:h=x.currentSessionId;const b=new Map(x.worktreeMetadata);for(const v of f)b.delete(v);for(const v of c)b.delete(v);const k=new Set(d.map(v=>Lt(v.path)).filter(v=>!!v)),j=k.size>0?x.availableWorktrees.filter(v=>!k.has(Lt(v.path)??v.path)):x.availableWorktrees;return{sessions:y,currentSessionId:h,isLoading:!1,worktreeMetadata:b,availableWorktrees:j,error:m}});const g=Ae.getDirectory()??null;return Gs(g,h),{deletedIds:a,failedIds:i}},updateSessionTitle:async(t,n)=>{try{const o=or(s().sessions,t),a=s().worktreeMetadata.get(t),i=()=>Ae.updateSession(t,n),c=a?.path??o,d=c?await Ae.withDirectory(c,i):await i();r(u=>({sessions:u.sessions.map(p=>p.id===t?d:p)}))}catch(o){r({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=or(s().sessions,t),o=Ae.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ae.getDirectory();return o.session.share({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Ae.withDirectory(i,c):await c();return d.data?(r(u=>({sessions:u.sessions.map(p=>p.id===t?d.data:p)})),d.data):null}catch(n){return r({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=or(s().sessions,t),o=Ae.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ae.getDirectory();return o.session.unshare({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Ae.withDirectory(i,c):await c();return d.data?(r(u=>({sessions:u.sessions.map(p=>p.id===t?d.data:p)})),d.data):null}catch(n){return r({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{r({currentSessionId:t,error:null});const n=Ae.getDirectory()??null;Gs(n,t)},clearError:()=>{r({error:null})},getSessionsByDirectory:()=>{const{sessions:t}=s();return t},applySessionMetadata:(t,n)=>{!t||!n||r(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const i=o.sessions[a],c=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,p={...i,...n,time:c,summary:d,share:u},f=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),m=[...o.sessions];return m[a]=f?p:i,f?{sessions:m}:o})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=s();return n.has(t)},markSessionAsOpenChamberCreated:t=>{r(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=s();n(t)},setWorktreeMetadata:(t,n)=>{t&&r(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return s().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=s().sessions,a=o.findIndex(u=>u.id===t);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(r(u=>{const p=[...u.sessions],f={...p[a]};return d!==void 0?f.directory=d:delete f.directory,p[a]=f,{sessions:p}}),c&&Gs(c,null),n&&Gs(n,t))},updateSession:t=>{r(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:ys(()=>Qt()),partialize:r=>({currentSessionId:r.currentSessionId,sessions:r.sessions,lastLoadedDirectory:r.lastLoadedDirectory,webUICreatedSessions:Array.from(r.webUICreatedSessions),worktreeMetadata:Array.from(r.worktreeMetadata.entries()),availableWorktrees:r.availableWorktrees}),merge:(r,s)=>{if(!(u=>typeof u=="object"&&u!==null)(r))return s;const n=Array.isArray(r.sessions)?r.sessions:s.sessions,o=typeof r.currentSessionId=="string"||r.currentSessionId===null?r.currentSessionId:s.currentSessionId,a=Array.isArray(r.webUICreatedSessions)?r.webUICreatedSessions:[],i=Array.isArray(r.worktreeMetadata)?r.worktreeMetadata:[],c=Array.isArray(r.availableWorktrees)?r.availableWorktrees:s.availableWorktrees,d=typeof r.lastLoadedDirectory=="string"?r.lastLoadedDirectory:s.lastLoadedDirectory??null;return{...s,...r,sessions:n,currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:c,lastLoadedDirectory:d}}}),{name:"session-store"})),Bl="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.",Jn=r=>typeof r=="string"&&r.trim()===Bl.trim(),Zn=(r,s)=>{const t=Date.now(),n=r.get(s),o=new Map(r);return o.set(s,{phase:"streaming",startedAt:n?.startedAt??t,lastUpdateAt:t}),o},kr=(r,s)=>{const t=Array.from(s);if(!t.some(a=>r.has(a)))return r;const o=new Map(r);return t.forEach(a=>{o.delete(a)}),o},Ga=new Map,Ol=r=>{const s=Ga.get(r);s&&(clearTimeout(s),Ga.delete(r))},qs=r=>{for(const s of r)Ol(s)},zr=r=>{if(!r)return"";if(typeof r=="string")return r;if(Array.isArray(r))return r.map(s=>zr(s)).join("");if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(Array.isArray(r.content))return r.content.map(s=>zr(s)).join("")}return""},Rr=r=>{if(!r)return"";const s=r;if(typeof s.text=="string")return s.text;if(Array.isArray(s.text))return s.text.map(n=>typeof n=="string"?n:Rr(n)).join("");const t=zr(s.delta);return t||(typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||zr(o.delta)||""}return""}).join(""):"")},Nr=(r,s)=>{const t={...r};if(t.type=t.type||"text",t.type==="text"){const n=s&&typeof s.text=="string"?s.text:"",o=typeof t.text=="string"?t.text:"",a=zr(r.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},qa=10*1024*1024,yf=r=>{const s=(r||"").toLowerCase();switch(s.includes(".")&&s.split(".").pop()||""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"bmp":return"image/bmp";case"ico":return"image/x-icon";case"pdf":return"application/pdf";default:return"text/plain"}},bf=r=>{if(r.type&&r.type.trim().length>0)return r.type;const s=(r.name||"").toLowerCase(),t=s.includes(".")&&s.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(s))return"text/plain";switch(t){case"md":case"markdown":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"sh":case"bash":case"zsh":return"text/plain";default:return"application/octet-stream"}},wf=r=>{const s=r.replace(/\s+/g,"");if(!s)return 0;const t=s.endsWith("==")?2:s.endsWith("=")?1:0;return Math.floor(s.length*3/4)-t},vf=r=>{const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<r.length;n+=3){const o=r[n]??0,a=r[n+1],i=r[n+2],c=o<<16|(a??0)<<8|(i??0);t+=s[c>>18&63],t+=s[c>>12&63],t+=typeof a=="number"?s[c>>6&63]:"=",t+=typeof i=="number"?s[c&63]:"="}return t},Bs=Ot()(Ht(xs((r,s)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=s();if(n.some(g=>g.filename===t.name&&g.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=qa;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=bf(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)}),f=p.startsWith("data:")?p.replace(/^data:[^;]*/,`data:${c}`):p,m=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:f,mimeType:c,filename:m(t.name),size:t.size,source:"local"};r(g=>({attachedFiles:[...g.attachedFiles,h]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=s();if(a.some(b=>b.serverPath===t&&b.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,u;if(!c)try{const b=Ae.getApiClient(),k=t.lastIndexOf("/"),j=k>0?t.substring(0,k):"/",v=k>0?t.substring(k+1):t,S=await b.file.read({query:{path:v,directory:j}});S.data&&"content"in S.data?(c=S.data.content,d=S.data.encoding??void 0,u=S.data.mimeType??void 0):c=""}catch(b){console.error("Failed to read server file:",b),c=`[File: ${n}]`}const p=u||yf(n),f=p&&p.trim().length>0?p:"application/octet-stream",m=(()=>{if(d==="base64")return c||"";const k=new TextEncoder().encode(c||"");return vf(k)})(),h=d==="base64"?wf(m):new TextEncoder().encode(c||"").length;if(h>qa)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const g=new File([],n,{type:f}),x=`data:${f};base64,${m}`,y={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:g,dataUrl:x,mimeType:f,filename:n,size:h,source:"server",serverPath:t};r(b=>({attachedFiles:[...b.attachedFiles,y]}))},removeAttachedFile:t=>{r(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{r({attachedFiles:[]})}}),{name:"file-store",storage:ys(()=>Qt()),partialize:r=>({attachedFiles:r.attachedFiles})}),{name:"file-store"}));let Qn=[],eo=null;const jf=50,Sf=3e4,Ks=new Map,Jr=new Map,ar=new Map,kf=10,Tn=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.indexOf("_"),n=t>=0?s.slice(t+1):s;return!n||n.length<kf?null:n},Ka=(r,s)=>{const t=Tn(r),n=Tn(s);return!t||!n||t.length!==n.length?!0:t>n},Nf=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Zr=r=>!Array.isArray(r)||r.length===0?0:r.reduce((s,t)=>{if(!t||t.type!=="text")return s;const n=t.text??t.content;return typeof n=="string"?s+n.length:s},0),Ya=r=>Array.isArray(r)?r.some(s=>s?.type==="step-finish"&&s?.reason==="stop"):!1,Xa=r=>{if(r){if(typeof r.id=="string"&&r.id.length>0)return r.id;if(r.type){const s=r.reason,t=r.callID;return`${r.type}-${s??""}-${t??""}`}}},Ja=new Set,Za=(r=[],s=[])=>{if(!s.length)return[...r];const t=[...r],n=new Set(r.map(Xa).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=Xa(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},Cf=(r,s)=>{let t=s,n=s?Tn(s):null;for(const o of r){const a=o?.info?.id,i=Tn(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},ds=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return t?o.set(s,t):o.delete(s),o},ir=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return o.set(s,t),o},Qr=(r,s)=>{const t=new Map(r);let n=!1;for(const o of s)t.delete(o)&&(n=!0);return n?t:r},Mf=(r,s)=>{const t=new Set,n=r.streamingMessageIds.get(s);return n&&t.add(n),r.messageStreamStates.forEach((o,a)=>{r.messageSessionIndex.get(a)===s&&t.add(a)}),t},Qa=(r,s,t)=>r.streamingMessageIds.get(s)===t?!0:r.messageSessionIndex.get(t)===s&&r.messageStreamStates.has(t),Af=async r=>{if(r)try{const s=rt.getState(),t=s.getWorktreeMetadata(r);if(t?.path)return t.path;const n=s.sessions.find(a=>a.id===r);return typeof n?.directory=="string"&&n.directory.length>0?n.directory:void 0}catch(s){console.warn("Failed to resolve session directory override:",s);return}},to=async(r,s)=>{const t=await Af(r);return t?Ae.withDirectory(t,s):s()},lt=Ot()(Ht(xs((r,s)=>({messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,loadMessages:async(t,n=Bt.VIEWPORT_MESSAGES)=>{const o=await to(t,()=>Ae.getSessionMessages(t)),a=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=(a?o.filter(d=>{const u=d?.info?.id;return u?Ka(u,a):!0}):o).slice(-n);r(d=>{const u=new Map(d.messages),p=d.messages.get(t)||[],f=new Map(p.filter(D=>typeof D.info?.id=="string").map(D=>[D.info.id,D])),h=c.map(D=>{const A={...D.info,clientRole:D.info?.clientRole??D.info.role,userMessageMarker:D.info.role==="user"?!0:D.info?.userMessageMarker},N=(Array.isArray(D.parts)?D.parts:[]).map(C=>{if(C?.type==="text"){const E=C.text??C.content??"";if(Jn(E))return{...C,synthetic:!0}}return C}),M=A?.id?f.get(A.id):void 0;if(M&&M.info.role==="assistant"){const C=Array.isArray(M.parts)?M.parts:[],E=Zr(C),F=Zr(N);if(Ya(C)&&E>F){const R=Za(C,N);return{...D,info:A,parts:R}}}return{...D,info:A,parts:N}}),g=new Set(p.map(D=>D.info.id)),x=new Set(h.map(D=>D.info.id)),y=[];g.forEach(D=>{x.has(D)||y.push(D)}),u.set(t,h);const b=new Map(d.sessionMemoryState),k=d.sessionMemoryState.get(t);b.set(t,{viewportAnchor:h.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>c.length,trimmedHeadMaxId:k?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const j={messages:u,sessionMemoryState:b};qs(y);const v=kr(d.messageStreamStates,y);if(v!==d.messageStreamStates&&(j.messageStreamStates=v),y.length>0){const D=d.streamingMessageIds.get(t);D&&y.includes(D)&&(j.streamingMessageIds=ds(j.streamingMessageIds??d.streamingMessageIds,t,null))}if(y.length>0){const D=Qr(j.messageSessionIndex??d.messageSessionIndex,y);D!==(j.messageSessionIndex??d.messageSessionIndex)&&(j.messageSessionIndex=D)}if(y.length>0){const D=new Map(d.pendingAssistantParts);let A=!1;y.forEach(N=>{D.delete(N)&&(A=!0)}),A&&(j.pendingAssistantParts=D)}const S=j.messageSessionIndex??d.messageSessionIndex;let w=S;return h.forEach(D=>{const A=D?.info?.id;typeof A=="string"&&A.length>0&&(w=ir(w,A,t))}),w!==S&&(j.messageSessionIndex=w),j})},sendMessage:async(t,n,o,a,i,c,d)=>{if(!i)throw new Error("No session selected");const u=i;s().sessionAbortFlags.has(u)&&r(p=>{const f=new Map(p.sessionAbortFlags);return f.delete(u),{sessionAbortFlags:f}}),await to(u,async()=>{try{let p=t;if(t.startsWith("/")){const m=t.indexOf(" "),h=m===-1?t.substring(1):t.substring(1,m),g=m===-1?"":t.substring(m+1).trim(),x=Ae.getApiClient(),y=Ae.getDirectory();if(h==="init"){const b=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await x.session.init({path:{id:u},body:{messageID:b,providerID:n,modelID:o},query:y?{directory:y}:void 0});return}if(h==="summarize"){await x.session.summarize({path:{id:u},body:{providerID:n,modelID:o},query:y?{directory:y}:void 0});return}try{const b=await Ae.getCommandDetails(h);b?.template?p=b.template.replace(/\$ARGUMENTS/g,g):p=t}catch(b){console.error("Command template resolution failed:",b),p=t}}r({lastUsedProvider:{providerID:n,modelID:o}}),r(m=>{const h=m.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=ar.get(u);g&&(clearTimeout(g),ar.delete(u));const x=new Map(m.sessionMemoryState);return x.set(u,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:x}});try{const m=new AbortController;r(g=>{const x=new Map(g.abortControllers);return x.set(u,m),{abortControllers:x}});const h=(c??[]).map(g=>({type:"file",mime:g.mimeType,filename:g.filename,url:g.dataUrl}));if(await Ae.sendMessage({id:u,providerID:n,modelID:o,text:p,agent:a,files:h.length>0?h:void 0,agentMentions:d?[{name:d}]:void 0}),h.length>0)try{Bs.getState().clearAttachedFiles()}catch(g){console.error("Failed to clear attached files after send",g)}r(g=>{const x=new Map(g.abortControllers);return x.delete(u),{abortControllers:x}})}catch(m){let h="Network error while sending message. The message may still be processing.";if(m.name==="AbortError")h="Request timed out. The message may still be processing.";else if(m.message?.includes("504")||m.message?.includes("Gateway")){h="Gateway timeout - your message is being processed. Please wait for response.",r(g=>{const x=new Map(g.abortControllers);return x.delete(u),{abortControllers:x}});return}else m.message&&(h=m.message);throw r(g=>{const x=new Map(g.abortControllers);return x.delete(u),{abortControllers:x}}),new Error(h)}}catch(p){let f="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?f="Request timed out. The message may still be processing.":p.response?.status===401?f="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?f="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?f="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(f=p.message),r(m=>{const h=new Map(m.abortControllers);return h.delete(u),{abortControllers:h}}),new Error(f)}})},abortCurrentOperation:async t=>{if(!t)return;const n=s(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=Mf(n,t);if(c.size===0){const u=t?a.get(t)??[]:[];let p=null;for(let f=u.length-1;f>=0;f-=1){const m=u[f];if(!m||m.info.role!=="assistant")continue;if(p||(p=m.info.id),(m.parts??[]).some(g=>g.type==="reasoning"||g.type==="tool"||g.type==="step-start")){c.add(m.info.id);break}}c.size===0&&p&&c.add(p)}for(const u of c){const p=Ks.get(u);p&&(clearTimeout(p),Ks.delete(u),Jr.delete(u))}c.size>0&&qs(c);const d=Date.now();r(u=>{const p=kr(u.messageStreamStates,c),f=u.messages.get(t)??[];let m=!1,h=u.messages;if(f.length>0&&c.size>0){const b=f.map(k=>{if(!c.has(k.info.id)&&c.size>0)return k;const j=(k.parts??[]).map(v=>{if(v.type==="reasoning"){const S=v,w={...S.time??{}};return typeof w.end!="number"&&(w.end=d),{...S,time:w}}if(v.type==="tool"){const S=v,w={...S.state??{}};return(w.status==="running"||w.status==="pending")&&(w.status="aborted"),{...S,state:w}}return v.type==="step-start"?{...v,type:"step-finish",aborted:!0}:v});return m=!0,{...k,info:{...k.info,abortedAt:d,streaming:!1,status:"aborted"},parts:j}});m&&(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:ds(u.streamingMessageIds,t,null),...m?{messages:h}:{}}}),Ae.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=s();if(Ja.has(n))return;const d=c.messages.get(t)||[],u=d.find(h=>h.info.id===n),p=a==="user"||u?.info.role==="user"?"user":a||u?.info.role||"assistant",f=s().sessionMemoryState.get(t);if(f?.streamStartTime&&Date.now()-f.streamStartTime>Bt.ZOMBIE_TIMEOUT){f.isZombie||r(g=>{const x=new Map(g.sessionMemoryState);return x.set(t,{...f,isZombie:!0}),{sessionMemoryState:x}}),setTimeout(()=>{s().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}r(h=>{const x=[...h.messages.get(t)||[]],y={},b=ir(h.messageSessionIndex,n,t);b!==h.messageSessionIndex&&(y.messageSessionIndex=b);const k=N=>{if(!((p==="assistant"||p==="user")&&h.sessionAbortFlags.has(t)))return N;const C=new Map(h.sessionAbortFlags);return C.delete(t),{...N,sessionAbortFlags:C}},j=N=>{const M=N||"",C=Jr.get(n);if(M&&C===M){const $=s();if(Qa($,t,n)){const R=Ks.get(n);R&&(clearTimeout(R),Ks.delete(n)),setTimeout(()=>{const Y=s();typeof Y.forceCompleteMessage=="function"&&Y.forceCompleteMessage(t,n,"timeout"),Y.completeStreamingMessage(t,n)},100)}}Jr.set(n,M);const E=Ks.get(n);E&&clearTimeout(E);const F=setTimeout(()=>{const $=s();typeof $.forceCompleteMessage=="function"&&$.forceCompleteMessage(t,n,"timeout"),Qa($,t,n)&&$.completeStreamingMessage(t,n),Ks.delete(n),Jr.delete(n)},8e3);Ks.set(n,F)},v=t!==i,S=h.sessionMemoryState.get(t);if(v&&S?.isStreaming){x.length>=Bt.BACKGROUND_STREAMING_BUFFER&&x.shift();const N=new Map(h.sessionMemoryState);N.set(t,{...S,backgroundMessageCount:(S.backgroundMessageCount||0)+1}),h.sessionMemoryState=N}if(p==="assistant"){const N=h.sessionMemoryState.get(t);if(N){const M=Date.now(),C=new Map(h.sessionMemoryState);C.set(t,{...N,isStreaming:!0,streamStartTime:N.streamStartTime??M,lastAccessedAt:M,isZombie:!1}),h.sessionMemoryState=C}}const w=Rr(o);if(Jn(w)&&(o.synthetic=!0),Nf()&&p==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:p,type:o?.type||"text",textLen:w.length,snapshotParts:d.length})}catch{}const D=y.streamingMessageIds??h.streamingMessageIds;if(p==="assistant"){const N=ds(D,t,n);N!==D&&(y.streamingMessageIds=N,window.__messageTracker?.(n,"streamingId_set_latest"))}const A=x.findIndex(N=>N.info.id===n);if(A!==-1&&p==="user"){const N=x[A],M=N.parts.findIndex(R=>R.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const C=Nr(o,M!==-1?N.parts[M]:void 0);window.__messageTracker?.(n,`user_part_type:${C.type||"unknown"}`);const E={...N};M!==-1?E.parts=E.parts.map((R,Y)=>Y===M?C:R):E.parts=[...E.parts,C];const F=[...x];F[A]=E;const $=new Map(h.messages);return $.set(t,F),k({messages:$})}if(p==="assistant"&&A!==-1){const N=x[A],M=N.parts.findIndex(Y=>Y.id===o.id),C=Nr(o,M!==-1?N.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const E={...N};M!==-1?E.parts=E.parts.map((Y,Z)=>Z===M?C:Y):E.parts=[...E.parts,C];const F=[...x];F[A]=E;const $=new Map(h.messages);$.set(t,F),y.messageStreamStates=Zn(h.messageStreamStates,n);const R=ds(y.streamingMessageIds??h.streamingMessageIds,t,n);return R!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=R,window.__messageTracker?.(n,"streamingId_set")),C.type==="text"?j(C.text||""):j(""),k({messages:$,...y})}if(A===-1){if(p==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const z=Nr(o);window.__messageTracker?.(n,`new_user_part_type:${z.type||"unknown"}`);const G={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,time:{created:Date.now()}},parts:[z]},W=[...x,G];W.sort((Ne,Me)=>{const Le=Ne.info?.time?.created||0,ye=Me.info?.time?.created||0;return Le-ye});const ce=new Map(h.messages);return ce.set(t,W),k({messages:ce})}if(o?.type==="text"){const z=Rr(o).trim();if(z.length>0){const G=[...x].reverse().find(W=>W.info.role==="user");if(G){const W=G.parts.map(ce=>Rr(ce)).join("").trim();if(W.length>0&&W===z)return Ja.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const N=Nr(o);window.__messageTracker?.(n,`part_type:${N.type||"unknown"}`),N.type==="text"?j(N.text||""):j("");const M=h.pendingAssistantParts.get(n),C=M?[...M.parts]:[],E=C.findIndex(z=>z.id===N.id);E!==-1?C[E]=N:C.push(N);const F=new Map(h.pendingAssistantParts);F.set(n,{sessionId:t,parts:C});const R={info:{id:n,sessionID:t,role:p,clientRole:p,providerID:h.lastUsedProvider?.providerID||"",modelID:h.lastUsedProvider?.modelID||"",time:{created:Date.now()},animationSettled:p==="assistant"?!1:void 0,streaming:p==="assistant"?!0:void 0},parts:C},Y=[...x,R],Z=new Map(h.messages);if(Z.set(t,Y),p==="assistant"){y.messageStreamStates=Zn(h.messageStreamStates,n);const z=ds(y.streamingMessageIds??h.streamingMessageIds,t,n);z!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=z,window.__messageTracker?.(n,"streamingId_set"))}return k({messages:Z,pendingAssistantParts:F,...y})}else{const N=x[A],M=N.parts.findIndex(R=>R.id===o.id),C=Nr(o,M!==-1?N.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`);const E={...N};M!==-1?E.parts=E.parts.map((R,Y)=>Y===M?C:R):E.parts=[...E.parts,C];const F=[...x];F[A]=E;const $=new Map(h.messages);if($.set(t,F),E.info.role==="assistant"){y.messageStreamStates=Zn(h.messageStreamStates,n);const R=ds(y.streamingMessageIds??h.streamingMessageIds,t,n);R!==(y.streamingMessageIds??h.streamingMessageIds)&&(y.streamingMessageIds=R,window.__messageTracker?.(n,"streamingId_set"))}return C.type==="text"?j(C.text||""):j(""),k({messages:$,...y})}}),o?.type==="step-finish"&&p!=="user"&&setTimeout(()=>{s().completeStreamingMessage(t,n)},0)},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){s()._addStreamingPartImmediate(t,n,o,a,i);return}Qn.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),eo||(eo=setTimeout(()=>{const c=[...Qn];Qn=[],eo=null;const d=s();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},jf))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};r(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],u=d.findIndex(S=>S.info.id===n);if(u===-1)return i;const p=d[u];if(!p)return i;const f=Date.now(),m=p.info,h=typeof m?.time?.completed=="number"&&m.time.completed>0;let g=!1;const x={...m};h||(x.time={...m.time??{},completed:f},g=!0),x.status!=="completed"&&(x.status="completed",g=!0),x.streaming&&(x.streaming=!1,g=!0);let y=!1;const b=p.parts.map(S=>{if(!S)return S;if(S.type==="tool"){const w=S.state;if(!w)return S;const D=w.status,A=D==="running"||D==="pending"||D==="started",N=!w.time||typeof w.time?.end!="number";if(A||N){const M={...w};return A&&(M.status="completed"),N&&(M.time={...w.time??{},end:f}),y=!0,{...S,state:M}}return S}if(S.type==="reasoning"){const w=S.time;return!w||typeof w.end!="number"?(y=!0,{...S,time:{...w??{},end:f}}):S}if(S.type==="text"){const w=S.time;return w&&typeof w.end!="number"?(y=!0,{...S,time:{...w,end:f}}):S}return S});if(!g&&!y)return i;window.__messageTracker?.(n,`force_complete:${o}`);const k={...p,info:x,parts:y?b:p.parts},j=[...d];j[u]=k;const v=new Map(i.messages);return v.set(c,j),{messages:v}})},markMessageStreamSettled:t=>{r(n=>{Ol(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,u)=>{if(i)return;const p=d.findIndex(x=>x.info.id===t);if(p===-1)return;const f=d[p];if(f.info?.animationSettled)return;const m={...f,info:{...f.info,animationSettled:!0}},h=[...d];h[p]=m;const g=new Map(n.messages);g.set(u,h),a=g,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),qs([t])},updateMessageInfo:(t,n,o)=>{r(a=>{const c=[...a.messages.get(t)??[]],d=c.findIndex(S=>S.info.id===n),u=a.pendingAssistantParts.get(n),p=(S=[],w=[])=>{if(!w.length)return S;const D=[...S];return w.forEach(A=>{const N=D.findIndex(M=>M.id===A.id);N===-1?D.push(A):D[N]=A}),D},f=S=>{if(!S)return S;const w=S.clientRole??S.role,D=w==="user"?!0:S.userMessageMarker;return{...S,clientRole:w,...D?{userMessageMarker:!0}:{}}};if(d===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:t,messageId:n,messageInfo:o,existingCount:c.length}),c.length>0){const F=c[0]?.info,$=typeof F?.time?.created=="number"?F.time.created:null,R=typeof F?.id=="string"?F.id:null,Y=o,Z=typeof Y?.time?.created=="number"?Y.time.created:null,z=typeof Y?.id=="string"?Y.id:n;let G=!1;if(Z!==null&&$!==null&&(G=Z<$),!G&&z&&R&&(G=z.localeCompare(R)<0),G)return window.__messageTracker?.(n,"skipped_evicted_message_update"),a}const S=f(o);if(S&&S.role==="user"){const E=u?.parts??[],F={info:{...S,userMessageMarker:!0,clientRole:"user"},parts:E.length>0?[...E]:[]},$=new Map(a.messages),R=[...c,F];R.sort((z,G)=>{const W=z.info?.time?.created||0,ce=G.info?.time?.created||0;return W-ce}),$.set(t,R);const Y={messages:$},Z=ir(Y.messageSessionIndex??a.messageSessionIndex,n,t);if(Z!==(Y.messageSessionIndex??a.messageSessionIndex)&&(Y.messageSessionIndex=Z),u){const z=new Map(a.pendingAssistantParts);z.delete(n),Y.pendingAssistantParts=z}return Y}if(!S||S.role!=="assistant")return a;const w=u?.parts??[],D={info:{...S,animationSettled:S?.animationSettled??!1},parts:w.length>0?[...w]:[]},A=new Map(a.messages),N=[...c,D];A.set(t,N);const M={messages:A},C=ir(M.messageSessionIndex??a.messageSessionIndex,n,t);if(C!==(M.messageSessionIndex??a.messageSessionIndex)&&(M.messageSessionIndex=C),u){const E=new Map(a.pendingAssistantParts);E.delete(n),M.pendingAssistantParts=E}return M}const m=c[d],h=m.info;if(h.userMessageMarker===!0||h.clientRole==="user"||h.role==="user"){const S={...m.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:h.providerID||void 0,modelID:h.modelID||void 0},w={...m,info:S},D=new Map(a.messages),A=[...c];return A[d]=w,D.set(t,A),{messages:D}}const x={...m.info,...o};o.role&&o.role!==m.info.role&&(x.role=m.info.role),x.clientRole=x.clientRole??m.info.clientRole??m.info.role,x.clientRole==="user"&&(x.userMessageMarker=!0);const y=u?.parts?p(m.parts,u.parts):m.parts,b={...m,info:x,parts:y},k=new Map(a.messages),j=[...c];j[d]=b,k.set(t,j);const v={messages:k};if(u){const S=new Map(a.pendingAssistantParts);S.delete(n),v.pendingAssistantParts=S}return v})},completeStreamingMessage:(t,n)=>{const o=s();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(a&&(i.streamingMessageIds=ds(o.streamingMessageIds,t,null),i.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),i.messageStreamStates=d}Object.keys(i).length>0&&r(i),o.pendingAssistantParts.has(n)&&r(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),qs([n]);let c=!1;if(r(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const p=new Map(d.sessionMemoryState),f=Date.now(),m={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return p.set(t,m),c=!0,{sessionMemoryState:p}}),c){const d=ar.get(t);d&&(clearTimeout(d),ar.delete(t));const u=setTimeout(()=>{r(p=>{const f=p.sessionMemoryState.get(t);if(!f||f.isStreaming)return p;const m=new Map(p.sessionMemoryState),{streamingCooldownUntil:h,...g}=f;return m.set(t,g),{sessionMemoryState:m}}),ar.delete(t)},2e3);ar.set(t,u)}},syncMessages:(t,n)=>{const o=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,a=o?n.filter(i=>{const c=i?.info?.id;return c?Ka(c,o):!0}):n;r(i=>{const c=new Map(i.messages),d=i.messages.get(t)||[],u=new Map(d.filter(j=>typeof j.info?.id=="string").map(j=>[j.info.id,j])),f=a.map(j=>{const v={...j.info,clientRole:j.info?.clientRole??j.info.role,userMessageMarker:j.info.role==="user"?!0:j.info?.userMessageMarker,animationSettled:j.info.role==="assistant"?j.info?.animationSettled??!0:j.info?.animationSettled},S=(Array.isArray(j.parts)?j.parts:[]).map(A=>{if(A?.type==="text"){const N=A.text??A.content??"";if(Jn(N))return{...A,synthetic:!0}}return A}),w=typeof v?.id=="string"?v.id:void 0,D=w?u.get(w):void 0;if(D&&D.info.role==="assistant"){const A=Array.isArray(D.parts)?D.parts:[],N=Zr(A),M=Zr(S);if(Ya(A)&&N>M){const E=Za(A,S);return{...j,info:v,parts:E}}}return{...j,info:v,parts:S}}),m=new Set(d.map(j=>j.info.id)),h=new Set(f.map(j=>j.info.id)),g=[];m.forEach(j=>{h.has(j)||g.push(j)}),c.set(t,f);const x={messages:c,isSyncing:!0};qs(g);const y=kr(i.messageStreamStates,g);if(y!==i.messageStreamStates&&(x.messageStreamStates=y),g.length>0){const j=i.streamingMessageIds.get(t);j&&g.includes(j)&&(x.streamingMessageIds=ds(x.streamingMessageIds??i.streamingMessageIds,t,null))}if(g.length>0){const j=Qr(x.messageSessionIndex??i.messageSessionIndex,g);j!==(x.messageSessionIndex??i.messageSessionIndex)&&(x.messageSessionIndex=j)}if(g.length>0){const j=new Map(i.pendingAssistantParts);let v=!1;g.forEach(S=>{j.delete(S)&&(v=!0)}),v&&(x.pendingAssistantParts=j)}const b=x.messageSessionIndex??i.messageSessionIndex;let k=b;return f.forEach(j=>{const v=j?.info?.id;typeof v=="string"&&v.length>0&&(k=ir(k,v,t))}),k!==b&&(x.messageSessionIndex=k),x}),setTimeout(()=>{r({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{r(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=n+Sf;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&r(n=>{const o=n.sessionAbortFlags.get(t);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,n)=>{r(o=>{const a=o.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},i=new Map(o.sessionMemoryState);return i.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:i}})},trimToViewportWindow:(t,n=Bt.VIEWPORT_MESSAGES,o)=>{const a=s(),i=a.messages.get(t);if(!i||i.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const p=Math.min(i.length,u+n);p===i.length&&p-u<n&&(u=Math.max(0,p-n));const f=i.slice(u,p),m=i.slice(0,u),h=new Set(f.map(x=>x.info.id)),g=i.filter(x=>!h.has(x.info.id)).map(x=>x.info.id);r(x=>{const y=new Map(x.messages);y.set(t,f);const b=new Map(x.sessionMemoryState),k={...c,viewportAnchor:d-u,trimmedHeadMaxId:Cf(m,c.trimmedHeadMaxId)};b.set(t,k);const j={messages:y,sessionMemoryState:b};qs(g);const v=kr(x.messageStreamStates,g);if(v!==x.messageStreamStates&&(j.messageStreamStates=v),g.length>0){const D=x.streamingMessageIds.get(t);D&&g.includes(D)&&(j.streamingMessageIds=ds(j.streamingMessageIds??x.streamingMessageIds,t,null))}if(g.length>0){const D=Qr(j.messageSessionIndex??x.messageSessionIndex,g);D!==(j.messageSessionIndex??x.messageSessionIndex)&&(j.messageSessionIndex=D)}const S=j.messageSessionIndex??x.messageSessionIndex;let w=S;return f.forEach(D=>{const A=D?.info?.id;typeof A=="string"&&A.length>0&&(w=ir(w,A,t))}),w!==S&&(j.messageSessionIndex=w),j})},evictLeastRecentlyUsed:t=>{const n=s();if(n.messages.size<=Bt.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const p=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,p])});const i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=i[0][0];r(d=>{const p=(d.messages.get(c)||[]).map(v=>v.info.id),f=new Map(d.messages),m=new Map(d.sessionMemoryState);f.delete(c),m.delete(c);const h={messages:f,sessionMemoryState:m},g=new Map(d.pendingAssistantParts);let x=!1;g.forEach((v,S)=>{v.sessionId===c&&(g.delete(S),x=!0)}),x&&(h.pendingAssistantParts=g);const y=new Map(d.sessionCompactionUntil);y.delete(c)&&(h.sessionCompactionUntil=y),qs(p);const b=kr(d.messageStreamStates,p);b!==d.messageStreamStates&&(h.messageStreamStates=b);const k=Qr(h.messageSessionIndex??d.messageSessionIndex,p);k!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=k);const j=ds(d.streamingMessageIds,c,null);if(j!==d.streamingMessageIds&&(h.streamingMessageIds=j),d.abortControllers.has(c)){const v=new Map(d.abortControllers);v.delete(c),h.abortControllers=v}return h})},loadMoreMessages:async(t,n="up")=>{const o=s(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const c=await to(t,()=>Ae.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=c.findIndex(p=>p.info.id===d.info.id);if(u>0){const p=Math.min(Bt.VIEWPORT_MESSAGES,u),f=c.slice(u-p,u);r(m=>{const h=[...f,...a],g=new Map(m.messages);g.set(t,h);const x=new Map(m.sessionMemoryState);return x.set(t,{...i,viewportAnchor:i.viewportAnchor+f.length,hasMoreAbove:u-p>0,totalAvailableMessages:c.length}),{messages:g,sessionMemoryState:x}})}else u===0&&r(p=>{const f=new Map(p.sessionMemoryState);return f.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:f}})}},getLastMessageModel:t=>{const{messages:n}=s(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:ys(()=>Qt()),partialize:r=>({lastUsedProvider:r.lastUsedProvider,sessionMemoryState:Array.from(r.sessionMemoryState.entries()).map(([s,t])=>[s,{viewportAnchor:t.viewportAnchor,isStreaming:t.isStreaming,lastAccessedAt:t.lastAccessedAt,backgroundMessageCount:t.backgroundMessageCount,totalAvailableMessages:t.totalAvailableMessages,hasMoreAbove:t.hasMoreAbove,trimmedHeadMaxId:t.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(r.sessionAbortFlags.entries()).map(([s,t])=>[s,{timestamp:t.timestamp,acknowledged:t.acknowledged}])}),merge:(r,s)=>{if(!r)return s;let t=s.sessionMemoryState;Array.isArray(r.sessionMemoryState)&&(t=new Map(r.sessionMemoryState.map(o=>o)));let n=s.sessionAbortFlags;return Array.isArray(r.sessionAbortFlags)&&(n=new Map(r.sessionAbortFlags)),{...s,lastUsedProvider:r.lastUsedProvider??s.lastUsedProvider,sessionMemoryState:t,sessionAbortFlags:n}}}),{name:"message-store"})),Df=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Ef=r=>r?Df.has(r.toLowerCase()):!1,Tf=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},If=r=>{if(r)try{const s=Tf();if(s?.getState)return s.getState().agents?.find?.(n=>n.name===r)}catch{}},xn=r=>{const s=If(r);if(!s)return"ask";const t=s.permission?.edit;return t==="allow"||t==="ask"||t==="deny"||t==="full"?t:(s.tools?s.tools.edit!==!1:!0)?"ask":"deny"},ei=r=>{if(!r||typeof r!="object")return 0;const s=r.input??0,t=r.output??0,n=r.reasoning??0,o=r.cache&&typeof r.cache=="object"?r.cache.read??0:0,a=r.cache&&typeof r.cache=="object"?r.cache.write??0:0;return s+t+n+o+a},so=r=>{const s=r.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return ei(s);const t=r.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:ei(t.tokens)},ro=(r,s,t)=>{const n=Number.isFinite(s)?Math.max(s,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),c=Math.min(i,n),d=n>0?Math.max(n-c,1):0,u=d>0?r/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},Cr=["ask","allow","full"],wt=Ot()(Ht(xs((r,s)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{r(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=s();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{r(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=s();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{r(i=>{const c=new Map(i.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=s(),a=o.get(t);return a&&a.get(n)||null},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a}=s(),i=new Map,c=(f,m)=>{if("mode"in f&&f.mode&&typeof f.mode=="string"&&n.find(y=>y.name===f.mode))return f.mode;if(f.providerID&&f.modelID){const x=n.find(y=>y.model?.providerID===f.providerID&&y.model?.modelID===f.modelID);if(x)return x.name}const{currentAgentContext:h}=s(),g=h.get(t);if(g&&n.find(x=>x.name===g))return g;if(m>0&&f.providerID&&f.modelID){const y=(o.get(t)||[]).filter(b=>b.info.role==="assistant").sort((b,k)=>b.info.time.created-k.info.time.created);for(let b=m-1;b>=0;b--){const j=y[b].info;if(j.providerID===f.providerID&&j.modelID===f.modelID){if(j.mode&&typeof j.mode=="string"&&n.find(w=>w.name===j.mode))return j.mode;const v=n.find(S=>S.model?.providerID===j.providerID&&S.model?.modelID===j.modelID);if(v)return v.name}}}return f.providerID&&f.modelID&&n.find(y=>y.name==="build")?"build":null},d=o.get(t)||[],u=d.filter(f=>f.info.role==="assistant"||f.info.role==="user").sort((f,m)=>f.info.time.created-m.info.time.created),p=d.filter(f=>f.info.role==="assistant").sort((f,m)=>f.info.time.created-m.info.time.created);for(let f=0;f<u.length;f++){const m=u[f],{info:h}=m,g=h;if(g.providerID&&g.modelID){const x=c(g,p.indexOf(m));if(x&&n.find(y=>y.name===x)){const y={providerId:g.providerID,modelId:g.modelID,timestamp:h.time.created},b=i.get(x);(!b||y.timestamp>b.timestamp)&&i.set(x,y)}}}for(const[f,m]of i)a(t,f,m.providerId,m.modelId);return i},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=ro(0,n,o),c=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(t)||[]).filter(j=>j.info.role==="assistant");if(f.length===0)return null;const m=f[f.length-1],h=m.info.id,g=j=>{const v=()=>{r(S=>{const w=S.sessionContextUsage.get(t);if(w&&w.totalTokens===j.totalTokens&&w.percentage===j.percentage&&w.contextLimit===j.contextLimit&&(w.outputLimit??0)===(j.outputLimit??0)&&(w.normalizedOutput??0)===(j.normalizedOutput??0)&&w.thresholdLimit===j.thresholdLimit&&w.lastMessageId===j.lastMessageId)return S;const D=new Map(S.sessionContextUsage);return D.set(t,j),{sessionContextUsage:D}})};typeof queueMicrotask=="function"?queueMicrotask(v):typeof window<"u"?window.setTimeout(v,0):setTimeout(v,0)},x=s().sessionContextUsage.get(t);if(x&&x.lastMessageId===h){const j=x.normalizedOutput??x.outputLimit??0,v=x.contextLimit!==c||j!==d||x.thresholdLimit!==u;if(v&&x.totalTokens>0){const S=x.totalTokens/u*100,w={totalTokens:x.totalTokens,percentage:Math.min(S,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(w),w}if(!v&&x.totalTokens>0)return x}const y=so(m);if(y===0)return x||null;const b=ro(y,n,o),k={totalTokens:y,percentage:b.percentage,contextLimit:b.contextLimit,outputLimit:b.outputLimit,normalizedOutput:b.normalizedOutput,thresholdLimit:b.thresholdLimit,lastMessageId:h};return g(k),k},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=so(d);if(u===0)return;const p=ro(u,n,o);r(f=>{const m=new Map(f.sessionContextUsage);return m.set(t,{totalTokens:u,percentage:p.percentage,contextLimit:p.contextLimit,outputLimit:p.outputLimit,normalizedOutput:p.normalizedOutput,thresholdLimit:p.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:m}})},initializeSessionContextUsage:(t,n,o,a)=>{const c=s().sessionContextUsage.get(t);(!c||c.totalTokens===0)&&s().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const c=()=>{i++;const u=(o.get(t)||[]).find(p=>p.info.id===n);if(u&&u.info.role==="assistant"&&so(u)>0){s().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=s();return n.get(t)},getSessionAgentEditMode:(t,n,o=xn(n))=>!t||!n?o:s().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=xn(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||Cr.includes(o)&&r(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=xn(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=s().getSessionAgentEditMode(t,n,a),c=Cr.indexOf(i),d=Cr.indexOf(a),p=((c>=0?c:d>=0?d:0)+1)%Cr.length,f=Cr[p];s().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:ys(()=>Qt()),partialize:r=>({sessionModelSelections:Array.from(r.sessionModelSelections.entries()),sessionAgentSelections:Array.from(r.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(r.sessionAgentModelSelections.entries()).map(([s,t])=>[s,Array.from(t.entries())]),currentAgentContext:Array.from(r.currentAgentContext.entries()),sessionContextUsage:Array.from(r.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(r.sessionAgentEditModes.entries()).map(([s,t])=>[s,Array.from(t.entries())])}),merge:(r,s)=>{const t=new Map;r?.sessionAgentModelSelections&&r.sessionAgentModelSelections.forEach(([o,a])=>{t.set(o,new Map(a))});const n=new Map;return r?.sessionAgentEditModes&&r.sessionAgentEditModes.forEach(([o,a])=>{n.set(o,new Map(a))}),{...s,...r,sessionModelSelections:new Map(r?.sessionModelSelections||[]),sessionAgentSelections:new Map(r?.sessionAgentSelections||[]),sessionAgentModelSelections:t,currentAgentContext:new Map(r?.currentAgentContext||[]),sessionContextUsage:new Map(r?.sessionContextUsage||[]),sessionAgentEditModes:n,hasHydrated:!0}}}),{name:"context-store"})),Ff=r=>typeof r=="object"&&r!==null,Pf=r=>{if(!Array.isArray(r))return[];const s=[];return r.forEach(t=>{if(!Array.isArray(t)||t.length!==2)return;const[n,o]=t;typeof n!="string"||!Array.isArray(o)||s.push([n,o])}),s},Rf=async(r,s)=>{try{const t=rt.getState(),n=t.getWorktreeMetadata(r);if(n?.path)return Ae.withDirectory(n.path,s);const o=t.sessions.find(i=>i.id===r),a=typeof o?.directory=="string"&&o.directory.length>0?o.directory:void 0;if(a)return Ae.withDirectory(a,s)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return s()},In=Ot()(Ht(xs((r,s)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o)return;const a=t.type?.toLowerCase?.()??null;let i=n?.currentAgentContext?.get(o);if(i||(i=n?.sessionAgentSelections?.get(o)??void 0),!i&&typeof window<"u"){const p=window.__zustand_config_store__;p?.getState&&(i=p.getState().currentAgentName??void 0)}const c=xn(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&Ef(a)){s().respondToPermission(o,t.id,"once").catch(()=>{});return}r(p=>{const f=p.permissions.get(o)||[],m=new Map(p.permissions);return m.set(o,[...f,t]),{permissions:m}})},respondToPermission:async(t,n,o)=>{await Rf(t,()=>Ae.respondToPermission(t,n,o)),o==="reject"&&await lt.getState().abortCurrentOperation(t),r(a=>{const c=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:ys(()=>Qt()),partialize:r=>({permissions:Array.from(r.permissions.entries())}),merge:(r,s)=>{if(!Ff(r))return s;const t=Pf(r.permissions);return{...s,permissions:new Map(t)}}}),{name:"permission-store"})),$l=r=>r.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
|
|
4
|
-
`).replace(/\n\s*\n+/g,`
|
|
5
|
-
`),ti=r=>{if(typeof r!="string")return null;const s=r.trim();if(!s)return null;const t=s.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},si=(r,s,t)=>{if(!s)return null;const n=t(s)?.path;if(typeof n=="string"&&n.trim().length>0)return ti(n);const o=r.find(a=>a.id===s);return o?ti(o.directory??null):null},ge=Ot()(Ht((r,s)=>({sessions:[],currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,getSessionAgentEditMode:(t,n,o)=>wt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>wt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>wt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>rt.getState().loadSessions(),createSession:async(t,n,o)=>{const a=await rt.getState().createSession(t,n,o);return a?.id&&await s().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=lt.getState(),{messages:o,lastUsedProvider:a}=n;let i,c;if(o.forEach((b,k)=>{const j=b.find(v=>v.info?.id===t);j&&!i&&(i=j,c=k)}),!i||i.info.role!=="assistant")return;const d=$l(i.parts);if(!d.trim())return;const u=rt.getState(),p=si(u.sessions,c??null,u.getWorktreeMetadata),f=await s().createSession(void 0,p??null,null);if(!f)return;const{currentProviderId:m,currentModelId:h,currentAgentName:g}=St.getState(),x=m||a?.providerID,y=h||a?.modelID;!x||!y||await Ae.sendMessage({id:f.id,providerID:x,modelID:y,text:d,prefaceText:Bl,agent:g??void 0})},deleteSession:(t,n)=>rt.getState().deleteSession(t,n),deleteSessions:(t,n)=>rt.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>rt.getState().updateSessionTitle(t,n),shareSession:t=>rt.getState().shareSession(t),unshareSession:t=>rt.getState().unshareSession(t),setCurrentSession:async t=>{const n=s().currentSessionId,o=si(rt.getState().sessions,t,rt.getState().getWorktreeMetadata),a=Ae.getDirectory()??jt.getState().currentDirectory??null,i=o??a;try{Ae.setDirectory(i??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}if(n&&n!==t&&!s().sessionMemoryState.get(n)?.isStreaming){const d=s().messages.get(n)||[];d.length>0&&s().updateViewportAnchor(n,d.length-1),s().trimToViewportWindow(n,Bt.VIEWPORT_MESSAGES)}rt.getState().setCurrentSession(t),t&&(s().messages.get(t)||await s().loadMessages(t),s().trimToViewportWindow(t,Sm)),s().evictLeastRecentlyUsed()},loadMessages:t=>lt.getState().loadMessages(t),sendMessage:(t,n,o,a,i,c)=>{const d=rt.getState().currentSessionId;return lt.getState().sendMessage(t,n,o,a,d||void 0,i,c)},abortCurrentOperation:()=>{const t=rt.getState().currentSessionId;return lt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=rt.getState().currentSessionId;if(!n)return null;const o=Date.now()+t;return r({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{r({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&<.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=rt.getState().currentSessionId||t;return lt.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>lt.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>lt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>lt.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>lt.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:wt.getState().currentAgentContext,sessionAgentSelections:wt.getState().sessionAgentSelections,getSessionAgentEditMode:wt.getState().getSessionAgentEditMode};return In.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>In.getState().respondToPermission(t,n,o),clearError:()=>rt.getState().clearError(),getSessionsByDirectory:t=>rt.getState().getSessionsByDirectory(t),getLastMessageModel:t=>lt.getState().getLastMessageModel(t),getCurrentAgent:t=>wt.getState().getCurrentAgent(t),syncMessages:(t,n)=>lt.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>rt.getState().applySessionMetadata(t,n),addAttachedFile:t=>Bs.getState().addAttachedFile(t),addServerFile:(t,n,o)=>Bs.getState().addServerFile(t,n,o),removeAttachedFile:t=>Bs.getState().removeAttachedFile(t),clearAttachedFiles:()=>Bs.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>lt.getState().updateViewportAnchor(t,n),trimToViewportWindow:(t,n)=>{const o=rt.getState().currentSessionId;return lt.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=rt.getState().currentSessionId;return lt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>lt.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>wt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>wt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>wt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>wt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>wt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>wt.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=lt.getState().messages;return wt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>rt.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>rt.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>rt.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>rt.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>rt.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>rt.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{const o=rt.getState().currentSessionId;if(!o)return null;const a=lt.getState().messages;return wt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=lt.getState().messages;return wt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=lt.getState().messages;return wt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=lt.getState().messages.get(t)||[],o=rt.getState().sessions.find(a=>a.id===t);console.log(`Debug session ${t}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(t,n,o)=>{const a=lt.getState().messages;return wt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>rt.getState().updateSession(t)}),{name:"composed-session-store"}));rt.subscribe((r,s)=>{r.sessions===s.sessions&&r.currentSessionId===s.currentSessionId&&r.lastLoadedDirectory===s.lastLoadedDirectory&&r.isLoading===s.isLoading&&r.error===s.error&&r.webUICreatedSessions===s.webUICreatedSessions&&r.worktreeMetadata===s.worktreeMetadata&&r.availableWorktrees===s.availableWorktrees||ge.setState({sessions:r.sessions,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,isLoading:r.isLoading,error:r.error,webUICreatedSessions:r.webUICreatedSessions,worktreeMetadata:r.worktreeMetadata,availableWorktrees:r.availableWorktrees})});lt.subscribe((r,s)=>{if(r.messages===s.messages&&r.sessionMemoryState===s.sessionMemoryState&&r.messageStreamStates===s.messageStreamStates&&r.sessionCompactionUntil===s.sessionCompactionUntil&&r.sessionAbortFlags===s.sessionAbortFlags&&r.streamingMessageIds===s.streamingMessageIds&&r.abortControllers===s.abortControllers&&r.lastUsedProvider===s.lastUsedProvider&&r.isSyncing===s.isSyncing)return;const t=new Map;r.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const c=i.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const p=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:u,createdAt:p});break}}}}}),ge.setState({messages:r.messages,sessionMemoryState:r.sessionMemoryState,messageStreamStates:r.messageStreamStates,sessionCompactionUntil:r.sessionCompactionUntil,sessionAbortFlags:r.sessionAbortFlags,streamingMessageIds:r.streamingMessageIds,abortControllers:r.abortControllers,lastUsedProvider:r.lastUsedProvider,isSyncing:r.isSyncing,userSummaryTitles:t})});Bs.subscribe((r,s)=>{r.attachedFiles!==s.attachedFiles&&ge.setState({attachedFiles:r.attachedFiles})});wt.subscribe((r,s)=>{r.sessionModelSelections===s.sessionModelSelections&&r.sessionAgentSelections===s.sessionAgentSelections&&r.sessionAgentModelSelections===s.sessionAgentModelSelections&&r.currentAgentContext===s.currentAgentContext&&r.sessionContextUsage===s.sessionContextUsage&&r.sessionAgentEditModes===s.sessionAgentEditModes||ge.setState({sessionModelSelections:r.sessionModelSelections,sessionAgentSelections:r.sessionAgentSelections,sessionAgentModelSelections:r.sessionAgentModelSelections,currentAgentContext:r.currentAgentContext,sessionContextUsage:r.sessionContextUsage,sessionAgentEditModes:r.sessionAgentEditModes})});In.subscribe((r,s)=>{r.permissions!==s.permissions&&ge.setState({permissions:r.permissions})});ge.setState({sessions:rt.getState().sessions,currentSessionId:rt.getState().currentSessionId,lastLoadedDirectory:rt.getState().lastLoadedDirectory,isLoading:rt.getState().isLoading,error:rt.getState().error,webUICreatedSessions:rt.getState().webUICreatedSessions,worktreeMetadata:rt.getState().worktreeMetadata,availableWorktrees:rt.getState().availableWorktrees,messages:lt.getState().messages,sessionMemoryState:lt.getState().sessionMemoryState,messageStreamStates:lt.getState().messageStreamStates,sessionCompactionUntil:lt.getState().sessionCompactionUntil,sessionAbortFlags:lt.getState().sessionAbortFlags,streamingMessageIds:lt.getState().streamingMessageIds,abortControllers:lt.getState().abortControllers,lastUsedProvider:lt.getState().lastUsedProvider,isSyncing:lt.getState().isSyncing,permissions:In.getState().permissions,attachedFiles:Bs.getState().attachedFiles,sessionModelSelections:wt.getState().sessionModelSelections,sessionAgentSelections:wt.getState().sessionAgentSelections,sessionAgentModelSelections:wt.getState().sessionAgentModelSelections,currentAgentContext:wt.getState().currentAgentContext,sessionContextUsage:wt.getState().sessionContextUsage,sessionAgentEditModes:wt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=ge);const aa=({containerRef:r,minThumbSize:s=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=l.useState(!1),[c,d]=l.useState({length:0,offset:0}),[u,p]=l.useState({length:0,offset:0}),f=l.useRef(null),m=l.useRef(null),h=l.useRef(!1),g=l.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),x=l.useRef(null),y=l.useCallback(()=>{const N=r.current;if(!N)return;const{scrollHeight:M,clientHeight:C,scrollTop:E,scrollWidth:F,clientWidth:$,scrollLeft:R}=N,Y=8;if(M>C){const Z=Math.max(C-Y*2,0),z=C/M*Z,G=Math.max(s,Math.min(Z,z)),W=Math.max(Z-G,0),ce=Math.max(M-C,1),Ne=E/ce*W;d({length:G,offset:Ne})}else d({length:0,offset:0});if(!o&&F>$){const Z=Math.max($-Y*2,0),z=$/F*Z,G=Math.max(s,Math.min(Z,z)),W=Math.max(Z-G,0),ce=Math.max(F-$,1),Ne=R/ce*W;p({length:G,offset:Ne})}else p({length:0,offset:0})},[r,s,o]),b=l.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),k=l.useCallback(()=>{m.current&&cancelAnimationFrame(m.current),m.current=requestAnimationFrame(()=>{y(),i(!0),b()})},[b,y]);l.useEffect(()=>{const N=r.current;if(!N)return;y(),i(!0),b(),N.addEventListener("scroll",k,{passive:!0});const M=typeof ResizeObserver<"u"?new ResizeObserver(()=>y()):null;M?.observe(N);const C=typeof MutationObserver<"u"?new MutationObserver(()=>y()):null;return C?.observe(N,{childList:!0,subtree:!0,characterData:!0}),()=>{N.removeEventListener("scroll",k),M?.disconnect(),C?.disconnect(),f.current&&clearTimeout(f.current),m.current&&cancelAnimationFrame(m.current)}},[r,k,b,y]);const j=(N,M)=>{const C=r.current;C&&(h.current=!0,g.current={pointerX:N.clientX,pointerY:N.clientY,scrollTop:C.scrollTop,scrollLeft:C.scrollLeft},x.current=M,i(!0),f.current&&clearTimeout(f.current),N.currentTarget.setPointerCapture(N.pointerId))},v=N=>{if(!h.current)return;const M=r.current;if(!M)return;const C=x.current;if(C==="vertical"){const{pointerY:E,scrollTop:F}=g.current,$=N.clientY-E,R=M.clientHeight,Y=Math.max(R-c.length,1),Z=Math.max(M.scrollHeight-M.clientHeight,1),z=$/Y*Z;M.scrollTop=F+z}else if(C==="horizontal"){const{pointerX:E,scrollLeft:F}=g.current,$=N.clientX-E,R=M.clientWidth,Y=Math.max(R-u.length,1),Z=Math.max(M.scrollWidth-M.clientWidth,1),z=$/Y*Z;M.scrollLeft=F+z}},S=N=>{h.current&&(h.current=!1,N.currentTarget.releasePointerCapture(N.pointerId),b())},w=c.length>0,D=u.length>0;if(!w&&!D)return null;const A=8;return e.jsxs("div",{className:T("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[w&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${A+c.offset}px`,right:`${A/2}px`},onPointerDown:N=>j(N,"vertical"),onPointerMove:v,onPointerUp:S,onPointerCancel:S}),D&&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:N=>j(N,"horizontal"),onPointerMove:v,onPointerUp:S,onPointerCancel:S})]})},Ye=l.forwardRef(({className:r,outerClassName:s,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,...p},f)=>{const m=l.useRef(null);return l.useImperativeHandle(f,()=>m.current,[]),e.jsxs("div",{className:T("relative flex flex-col min-h-0 w-full overflow-hidden",s),children:[e.jsx(i,{ref:m,className:T("overlay-scrollbar-target overlay-scrollbar-container",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",r),style:n,...p,children:t}),e.jsx(aa,{containerRef:m,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});Ye.displayName="ScrollableOverlay";const ri="mobile-overlay-root",Lf=()=>{if(typeof document>"u")return null;let r=document.getElementById(ri);return r||(r=document.createElement("div"),r.id=ri,document.body.appendChild(r)),r},qt=({open:r,title:s,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:c})=>{const d=l.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Lf()),l.useEffect(()=>{if(!r)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const m=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",m),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",m)}},[r,t]),!r||!d.current)return null;const u=i??"max-h-[min(70vh,520px)]",p=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:T("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),onClick:f=>f.stopPropagation(),children:[(()=>{const f=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(hs,{className:"h-4 w-4"})});return c?c(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:s}),f]})})(),e.jsx(Ye,{outerClassName:u,className:"px-2 py-2 pwa-overlay-scroll",children:n}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return ad.createPortal(p,d.current)},Do=({totalTokens:r,percentage:s,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,c]=l.useState(!1),d=l.useRef(void 0),u=y=>y>=1e6?`${(y/1e6).toFixed(1)}M`:y>=1e3?`${(y/1e3).toFixed(1)}K`:y.toFixed(1).replace(/\.0$/,""),p=y=>y>=90?"text-status-error":y>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,m=[`Used tokens: ${u(r)}`,`Context limit: ${u(t)}`,`Output limit: ${u(f)}`],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(id,{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(r)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:T("typography-meta font-semibold",p(s)),children:[Math.min(s,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:x}),e.jsx(ft,{children:e.jsx("div",{className:"space-y-0.5",children:m.map(y=>e.jsx("p",{className:"typography-micro leading-tight",children:y},y))})})]})},Mr={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},zl=(r,s,t)=>{if(typeof window>"u")return;const n=document.documentElement,o=s==="mobile",a=s==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(s==="mobile"?"device-mobile":s==="tablet"?"device-tablet":"device-desktop"),r?(n.classList.add("desktop-runtime"),n.style.setProperty("--is-mobile","0"),n.style.setProperty("--device-type","desktop"),n.style.setProperty("--font-scale","1"),n.style.setProperty("--has-coarse-pointer","0"),n.style.setProperty("--has-touch-input","0"),n.classList.remove("mobile-pointer")):(n.classList.remove("desktop-runtime"),n.style.setProperty("--is-mobile",o?"1":"0"),n.style.setProperty("--device-type",s),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",t?"1":"0"),n.style.setProperty("--has-touch-input",t?"1":"0"),t?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function no(){const r=window.innerWidth,s=typeof window.matchMedia=="function",t=s?window.matchMedia("(pointer: coarse)"):null,n=s?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=r>Mr.md&&r<=Mr.lg,p=r<=Mr.md;let f=d&&p,m=d&&!f&&u,h=!d||r>Mr.lg,g="desktop";c?(f=!1,m=!1,h=!0,g="desktop"):f?g="mobile":m?g="tablet":(h=!0,g="desktop"),zl(c,g,d);let x="xs";for(const[y,b]of Object.entries(Mr))r>=b&&(x=y);return{isMobile:f,isTablet:m,isDesktop:h,deviceType:g,screenWidth:r,breakpoint:x,hasTouchInput:d}}function At(){const[r,s]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:no());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{s(no())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),l.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{s(no())},a=[],i=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return i(t),i(n),()=>{a.forEach(c=>c())}},[]),l.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||c||d>0;zl(t,r.deviceType,u)},[r.deviceType,r.hasTouchInput]),r}const en=5e3,_f=1e4,Bf=5e3,Of=1e4,us=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),$f=(r,s)=>{if(!r&&!s)return!1;if(!r||!s)return!0;const t=new Set([...Object.keys(r),...Object.keys(s)]);for(const n of t){const o=r[n],a=s[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},zf=(r,s)=>{if(!r&&!s)return!1;if(!r||!s)return!0;const t=r.files??[],n=s.files??[];if(t.length!==n.length||r.ahead!==s.ahead||r.behind!==s.behind||r.current!==s.current||r.tracking!==s.tracking||r.isClean!==s.isClean)return!0;const o=new Set(t.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of n)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!$f(r.diffStats,s.diffStats)},Hf=(r,s)=>{const t=new Set;if(!s)return t;const n=r?.files??[],o=s.files??[],a=new Map(n.map(f=>[f.path,f])),i=new Map(o.map(f=>[f.path,f])),c=new Set([...a.keys(),...i.keys()]);for(const f of c){const m=a.get(f),h=i.get(f);if(!m||!h){t.add(f);continue}if(m.index!==h.index||m.working_dir!==h.working_dir){t.add(f);continue}}const d=r?.diffStats??{},u=s.diffStats??{},p=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of p){const m=d[f],h=u[f];if(!m||!h){t.add(f);continue}(m.insertions!==h.insertions||m.deletions!==h.deletions)&&t.add(f)}return t},Nt=Ot()(Ht((r,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:en,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=s();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,us()),r({activeDirectory:t,directories:a})}else r({activeDirectory:t})},getDirectoryState:t=>s().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:i}=s();let c=i.get(t);c||(c=us()),a||r({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(i);return f.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),r({directories:f,isLoadingStatus:!1}),!1}const p=await n.getGitStatus(t);if(zf(c.status,p)){d=!0;const f=new Map(s().directories),m=f.get(t)??us(),h=Hf(m.status,p),g=new Set((m.status?.files??[]).map(k=>k.path)),x=new Set((p.files??[]).map(k=>k.path)),y=new Map(m.diffCache);for(const k of g)x.has(k)||y.delete(k);for(const k of h)y.delete(k);const b=h.size>0;f.set(t,{...m,isGitRepo:!0,status:p,diffCache:y,lastStatusFetch:Date.now(),lastStatusChange:b?Date.now():m.lastStatusChange}),r({directories:f})}else{const f=new Map(s().directories),m=f.get(t)??us();f.set(t,{...m,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:m.lastStatusChange}),r({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||r({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{r({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(s().directories),i=a.get(t)??us();a.set(t,{...i,branches:o}),r({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{r({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=s(),i=a.get(t),c=o??i?.logMaxCount??25;r({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),u=new Map(s().directories),p=u.get(t)??us();u.set(t,{...p,log:d,lastLogFetch:Date.now(),logMaxCount:c}),r({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{r({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{r({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(s().directories),i=a.get(t)??us();a.set(t,{...i,identity:o}),r({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{r({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=s();let i=a.get(t);if(!i){i=us();const f=new Map(a);f.set(t,i),r({directories:f})}const{force:c=!1}=o,d=Date.now();await s().fetchStatus(t,n);const u=s().directories.get(t);if(!u?.isGitRepo)return;await s().fetchBranches(t,n);const p=d-(u.lastLogFetch||0);(c||p>Of||!u.log)&&await s().fetchLog(t,n),await s().fetchIdentity(t,n),await s().fetchAllDiffs(t,n)},getDiff:(t,n)=>s().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(s().directories),i=a.get(t)??us(),c=new Map(i.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:c}),r({directories:a})},clearDiffCache:t=>{const n=new Map(s().directories),o=n.get(t);o&&(n.set(t,{...o,diffCache:new Map}),r({directories:n}))},fetchAllDiffs:async(t,n)=>{const o=s().directories.get(t);if(!o?.status?.files||o.status.files.length===0)return;const i=o.status.files.filter(m=>!o.diffCache.has(m.path));if(i.length===0)return;const c=await Promise.allSettled(i.map(async m=>{const h=await n.getGitFileDiff(t,{path:m.path});return{path:m.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),f=Date.now();c.forEach(m=>{m.status==="fulfilled"&&p.set(m.value.path,{...m.value.diff,fetchedAt:f})}),d.set(t,{...u,diffCache:p}),r({directories:d})},setLogMaxCount:(t,n)=>{const o=new Map(s().directories),a=o.get(t)??us();o.set(t,{...a,logMaxCount:n}),r({directories:o})},startPolling:t=>{const{pollIntervalId:n}=s();if(n)return;const o=()=>{const{currentPollInterval:a}=s();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){r({pollIntervalId:o()});return}const{activeDirectory:c}=s();if(!c){r({pollIntervalId:o()});return}if(await s().fetchStatus(c,t,{silent:!0}))await s().fetchLog(c,t),await s().fetchAllDiffs(c,t),r({currentPollInterval:en});else{const p=Math.min(a+Bf,_f);r({currentPollInterval:p})}const{pollIntervalId:u}=s();u!==null&&r({pollIntervalId:o()})},a)};r({pollIntervalId:o(),currentPollInterval:en})},stopPolling:()=>{const{pollIntervalId:t}=s();t&&(clearTimeout(t),r({pollIntervalId:null,currentPollInterval:en}))},refresh:async(t,n={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,t,n)}}),{name:"git-store"})),Hl=r=>Nt(s=>r?s.directories.get(r)?.status??null:null),Wf=r=>Nt(s=>r?s.directories.get(r)?.branches??null:null),Uf=r=>Nt(s=>r?s.directories.get(r)?.log??null:null),Vf=r=>Nt(s=>r?s.directories.get(r)?.identity??null:null),Wl=r=>Nt(s=>r?s.directories.get(r)?.isGitRepo??null:null),Gf=r=>Nt(s=>r?s.directories.get(r)?.status?.files?.length??0:0);function Kt({...r}){return e.jsx(ld,{"data-slot":"dropdown-menu",...r})}function Yt({...r}){return e.jsx(cd,{"data-slot":"dropdown-menu-trigger",...r})}function Xt({className:r,sideOffset:s=4,...t}){return e.jsx(dd,{children:e.jsx(ud,{"data-slot":"dropdown-menu-content",sideOffset:s,className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...t})})}function yt({className:r,inset:s,variant:t="default",...n}){return e.jsx(hd,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":t,className:T("hover:bg-accent hover:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),...n})}function qf({...r}){return e.jsx(md,{"data-slot":"dropdown-menu-radio-group",...r})}function Kf({className:r,children:s,...t}){return e.jsxs(fd,{"data-slot":"dropdown-menu-radio-item",className:T("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-accent hover:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),...t,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(pd,{children:e.jsx(It,{className:"size-3"})})}),s]})}function Hr({className:r,...s}){return e.jsx(gd,{"data-slot":"dropdown-menu-separator",className:T("bg-border -mx-1 my-0.5 h-px",r),...s})}function ur({...r}){return e.jsx(xd,{"data-slot":"dropdown-menu-sub",...r})}function mr({className:r,inset:s,children:t,...n}){return e.jsxs(yd,{"data-slot":"dropdown-menu-sub-trigger","data-inset":s,className:T("hover:bg-accent hover:text-accent-foreground flex cursor-default items-center rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8",r),...n,children:[t,e.jsx(gs,{className:"ml-auto size-3.5"})]})}function fr({className:r,...s}){return e.jsx(bd,{"data-slot":"dropdown-menu-sub-content",className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...s})}const Yf={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 ia(r){return Yf[r]||{displayName:r.charAt(0).toUpperCase()+r.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Xf(r,s,t){const n=ia(r);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=Gr(o);if(a)return a}if(r==="webfetch"){if(s.trim().startsWith("{")||s.trim().startsWith("["))try{return JSON.parse(s),"json"}catch{}if(s.trim().startsWith("<"))return"html";if(s.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function Gr(r){const s=r.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"javascript",ts:"typescript",tsx:"typescript",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",jsonc:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",cc:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",dart:"dart",r:"r",lua:"lua",vim:"vim",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",md:"markdown",mdx:"markdown",rst:"text",txt:"text",dockerfile:"dockerfile",makefile:"makefile",gitignore:"text",env:"text",conf:"text",cfg:"text",ini:"ini",sql:"sql",diff:"diff",patch:"diff"}[s||""]||null}const Jf=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function Ul(r){const s=r.split(".").pop()?.toLowerCase();return Jf.includes(s||"")}function Zf(r){const s=r.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[s||""]||"image/png"}function Qf(r,s){if(!r)return"";const t=n=>{const o=r[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(s==="bash"){const n=t("command");if(n)return n}if(s==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((s==="edit"||s==="multiedit")&&typeof r=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(s==="write"&&typeof r=="object"){const n=t("content");if(n)return n}return typeof r=="object"?Object.entries(r).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${i}: ${c}`}).join(`
|
|
6
|
-
`):String(r)}const la=l.createContext(null),rr=()=>{const r=l.useContext(la);if(!r)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return r},Vl=r=>{const s=rr();return r(s)},ep=()=>Vl(r=>r.runtime.isDesktop),ca=()=>Vl(r=>r.runtime.isVSCode),tp=dl("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:r,variant:s,size:t,asChild:n=!1,...o}){const a=n?cl:"button";return e.jsx(a,{"data-slot":"button",className:T(tp({variant:s,size:t,className:r})),...o})}const sp=({mode:r,onModeChange:s,className:t})=>{const n=l.useCallback(o=>{o.stopPropagation(),s(r==="side-by-side"?"unified":"side-by-side")},[r,s]);return e.jsx(Ee,{size:"sm",variant:"ghost",className:T("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:n,title:r==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:r==="side-by-side"?e.jsx(wd,{className:"h-3 w-3"}):e.jsx(vd,{className:"h-3 w-3"})})},da=de.createContext(void 0);function jr(){const r=de.useContext(da);if(!r)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return r}function ua(){return de.useContext(da)}const rp="Flexoki",np="dark",op={"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"},ap=[{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"}}],ip={name:rp,type:np,colors:op,tokenColors:ap},lp="Flexoki",cp="light",dp={"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"},up=[{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"}}],mp={name:lp,type:cp,colors:dp,tokenColors:up},ma="flexoki-dark",fa="flexoki-light",fp=ip,pp=mp;function Gl(r,s){return Object.defineProperty(r,"toString",{value:()=>s,enumerable:!1,configurable:!0}),Object.defineProperty(r,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0}),r}function ql(r,s,t){const n=r.colors?.["editor.background"],o=r.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${s}" is missing editor.background/editor.foreground`);const a=r.tokenColors??[];return{...r,name:s,type:t,fg:o,bg:n,settings:a}}const pa=ql(fp,ma,"dark"),ha=ql(pp,fa,"light");Gl(pa,ma);Gl(ha,fa);const xr={dark:ma,light:fa},ni=[ha,pa];let oi=!1;function Kl(){oi||(ka(xr.dark,async()=>pa),ka(xr.light,async()=>ha),oi=!0)}const hp=`
|
|
7
|
-
:host {
|
|
8
|
-
font-family: var(--font-mono);
|
|
9
|
-
font-size: var(--text-code);
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
:host, pre, [data-diffs], [data-code] {
|
|
13
|
-
transform: translateZ(0);
|
|
14
|
-
-webkit-transform: translateZ(0);
|
|
15
|
-
-webkit-backface-visibility: hidden;
|
|
16
|
-
backface-visibility: hidden;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
pre, [data-code] {
|
|
20
|
-
font-family: var(--font-mono);
|
|
21
|
-
font-size: var(--text-code);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
[data-code] {
|
|
25
|
-
-webkit-overflow-scrolling: touch;
|
|
26
|
-
}
|
|
27
|
-
/* Reduce hunk separator height */
|
|
28
|
-
[data-separator-content] {
|
|
29
|
-
height: 24px !important;
|
|
30
|
-
}
|
|
31
|
-
[data-expand-button] {
|
|
32
|
-
height: 24px !important;
|
|
33
|
-
width: 24px !important;
|
|
34
|
-
}
|
|
35
|
-
[data-separator-multi-button] {
|
|
36
|
-
row-gap: 0 !important;
|
|
37
|
-
}
|
|
38
|
-
[data-expand-up] {
|
|
39
|
-
height: 12px !important;
|
|
40
|
-
min-height: 12px !important;
|
|
41
|
-
max-height: 12px !important;
|
|
42
|
-
margin: 0 !important;
|
|
43
|
-
margin-top: 3px !important;
|
|
44
|
-
padding: 0 !important;
|
|
45
|
-
border-radius: 4px 4px 0 0 !important;
|
|
46
|
-
}
|
|
47
|
-
[data-expand-down] {
|
|
48
|
-
height: 12px !important;
|
|
49
|
-
min-height: 12px !important;
|
|
50
|
-
max-height: 12px !important;
|
|
51
|
-
margin: 0 !important;
|
|
52
|
-
margin-top: -3px !important;
|
|
53
|
-
padding: 0 !important;
|
|
54
|
-
border-radius: 0 0 4px 4px !important;
|
|
55
|
-
}
|
|
56
|
-
`;function gp(r,s,t){const n=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${r}:${s.length}:${t.length}:${n.length}:${o.length}`}const ai=({original:r,modified:s,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=ua()?.currentTheme?.metadata?.variant==="dark";Kl();const d=de.useRef(null),u=de.useMemo(()=>{const f=gp(n,r,s);if(d.current?.key===f)return d.current.fileDiff;const m={name:n,contents:r,cacheKey:`old-${f}`},h={name:n,contents:s,cacheKey:`new-${f}`},g=bo(m,h);return d.current={key:f,fileDiff:g},g},[n,r,s,t]),p=de.useMemo(()=>({theme:{dark:xr.dark,light:xr.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:hp}),[c,o,a]);return typeof window>"u"?null:e.jsx(Ye,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(jd,{fileDiff:u,options:p})})},xp=1100,yp=r=>{const{index:s,working_dir:t}=r;return s==="A"||t==="A"||s==="?"||t==="?"},ii=(r,s)=>{const t=r??0,n=s??0;return!t&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[t?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",t]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},bp=l.memo(({changedFiles:r,selectedFile:s,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=l.useCallback(i=>{if(!o)return i;const c=i.lastIndexOf("/");return c>=0?i.slice(c+1):i},[o]);return r.length===0?null:e.jsxs(Kt,{children:[e.jsx(Yt,{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)}),ii(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(vt,{className:"size-4 opacity-50"})]})}),e.jsx(Xt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(qf,{value:s??"",onValueChange:n,children:r.map(i=>e.jsx(Kf,{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:ii(i.insertions,i.deletions)})]})},i.path))})})]})}),wp=l.memo(({filePath:r,diff:s,isVisible:t,renderSideBySide:n})=>{const o=s.original.length>0,a=s.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:i,children:[o&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:s.original,alt:`Original: ${r}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:c,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:s.modified,alt:`Modified: ${r}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),vp=l.memo(({filePath:r,diff:s,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=l.useMemo(()=>Gr(r)||"text",[r]);return Ul(r)?e.jsx(wp,{filePath:r,diff:s,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(ai,{original:s.original,modified:s.modified,language:a,fileName:r,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(ai,{original:s.original,modified:s.modified,language:a,fileName:r,renderSideBySide:n,wrapLines:o})})}),jp=l.memo(({directory:r,filePath:s,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Nt(l.useCallback(c=>c.directories.get(r)?.diffCache.get(s)??null,[r,s])),i=l.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a?.original,a?.modified]);return i?e.jsx(vp,{filePath:s,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),Sp=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=ge(),{currentDirectory:n}=jt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},kp=()=>{const{git:r}=rr(),s=Sp(),{screenWidth:t,isMobile:n}=At(),o=Wl(s??null),a=Hl(s??null),i=Nt(E=>E.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d}=Nt(),[u,p]=l.useState(null),f=Fe(E=>E.pendingDiffFile),m=Fe(E=>E.setPendingDiffFile),h=Fe(E=>E.diffLayoutPreference),g=Fe(E=>E.diffFileLayout),x=Fe(E=>E.setDiffFileLayout),y=Fe(E=>E.diffWrapLines),b=Fe(E=>E.setDiffWrapLines),k=l.useMemo(()=>{if(!a?.files)return[];const E=a.diffStats??{};return a.files.map(F=>({...F,insertions:E[F.path]?.insertions??0,deletions:E[F.path]?.deletions??0,isNew:yp(F)})).sort((F,$)=>F.path.localeCompare($.path))},[a]),j=l.useMemo(()=>u?k.find(E=>E.path===u)??null:null,[k,u]),v=l.useMemo(()=>{if(!j)return null;const E=g[j.path];if(E)return E;if(h==="inline")return"inline";if(h==="side-by-side")return"side-by-side";const F=t<xp;return j.isNew||F?"inline":"side-by-side"},[j,g,h,t]);l.useEffect(()=>{s&&(c(s),Nt.getState().directories.get(s)?.status||d(s,r))},[s,c,d,r]),l.useEffect(()=>{f&&(p(f),m(null))},[f,m]),l.useEffect(()=>{!u&&k.length>0&&p(k[0].path)},[k,u]),l.useEffect(()=>{u&&k.length>0&&(k.some(F=>F.path===u)||p(k[0]?.path??null))},[k,u]);const S=l.useCallback(E=>{p(E)},[]),w=(v??"side-by-side")==="side-by-side",A=!!Nt(l.useCallback(E=>!s||!u?null:E.directories.get(s)?.diffCache.get(u)??null,[s,u])),N=!!u&&!A,M=()=>!s||k.length===0?null:k.map(E=>e.jsx(jp,{directory:s,filePath:E.path,isVisible:E.path===u,renderSideBySide:w,wrapLines:y},E.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($t,{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."}):k.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(),N&&!A&&e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx($t,{size:16,className:"animate-spin"}),"Loading diff…"]})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 bg-background",children:[!n&&e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(wo,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${k.length} ${k.length===1?"file":"files"} changed`})]}),e.jsx(bp,{changedFiles:k,selectedFile:u,selectedFileEntry:j,onSelectFile:S,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),j&&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(Sd,{className:"size-4"})}),j&&v&&e.jsx(sp,{mode:v==="side-by-side"?"side-by-side":"unified",onModeChange:E=>{if(!j)return;const F=E==="side-by-side"?"side-by-side":"inline";x(j.path,F)}})]}),C()]})},Np=()=>{const{git:r}=rr(),{currentSessionId:s,sessions:t,worktreeMetadata:n}=ge(),{currentDirectory:o}=jt(),a=s?n.get(s)??void 0:void 0,c=t.find(m=>m.id===s)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:u,fetchStatus:p}=Nt(),f=Gf(d??null);return l.useEffect(()=>{d&&(u(d),Nt.getState().directories.get(d)?.status||p(d,r))},[d,u,p,r]),f},Cp=()=>{const r=Fe(d=>d.setSessionSwitcherOpen),s=Fe(d=>d.toggleSidebar),{isMobile:t}=At(),[n,o]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=l.useCallback(()=>{t?r(!0):s()},[t,r,s]),c="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground";return t||!n||!a?null:e.jsx("div",{className:"fixed top-[0.375rem] left-[5.25rem] z-[9999]",style:{pointerEvents:"auto","--padding-scale":"1"},children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Open sessions",className:c,children:e.jsx(_n,{className:"h-5 w-5"})})})},li=()=>{const r=Fe(z=>z.setSessionSwitcherOpen),s=Fe(z=>z.toggleSidebar),t=Fe(z=>z.setSettingsDialogOpen),n=Fe(z=>z.isSidebarOpen),o=Fe(z=>z.sidebarWidth),a=Fe(z=>z.activeMainTab),i=Fe(z=>z.setActiveMainTab),{getCurrentModel:c}=St(),d=ge(z=>z.getContextUsage),{isMobile:u}=At(),p=Np(),f=l.useRef(null),[m,h]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),g=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);de.useEffect(()=>{if(typeof window>"u")return;const z=typeof window.opencodeDesktop<"u";h(z)},[]);const x=c(),y=x&&typeof x.limit=="object"&&x.limit!==null?x.limit:null,b=y&&typeof y.context=="number"?y.context:0,k=y&&typeof y.output=="number"?y.output:0,j=d(b,k),v=Fe(z=>z.isSessionSwitcherOpen),S=l.useCallback(()=>{if(typeof document>"u")return;const z=document.activeElement;if(!z)return;const G=z.tagName;(G==="INPUT"||G==="TEXTAREA"||G==="SELECT"||z.isContentEditable)&&z.blur()},[]),w=l.useCallback(()=>{if(u){S(),r(!v);return}s()},[S,u,v,r,s]),D=l.useCallback(()=>{u&&S(),r(!1),t(!0)},[S,u,r,t]),A="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground",N=l.useMemo(()=>m&&g?n?"pl-0":"pl-[8.0rem]":"pl-3",[m,g,n]),M=l.useCallback(()=>{if(typeof document>"u")return;const z=f.current?.getBoundingClientRect().height;z&&document.documentElement.style.setProperty("--oc-header-height",`${z}px`)},[]);de.useEffect(()=>{if(typeof window>"u")return;M();const z=f.current;if(!z||typeof ResizeObserver>"u")return()=>{};const G=new ResizeObserver(()=>{M()});return G.observe(z),window.addEventListener("resize",M),window.addEventListener("orientationchange",M),()=>{G.disconnect(),window.removeEventListener("resize",M),window.removeEventListener("orientationchange",M)}},[M]),de.useEffect(()=>{M()},[M,u]);const C=l.useCallback(async z=>{if(!z.target.closest("button, a, input, select, textarea")&&z.button===0&&m)try{const{getCurrentWindow:G}=await _r(async()=>{const{getCurrentWindow:ce}=await import("./vendor-.pnpm-COYWCHRJ.js").then(Ne=>Ne.bY);return{getCurrentWindow:ce}},__vite__mapDeps([0,1]));await G().startDragging()}catch(G){console.error("Failed to start window dragging:",G)}},[m]),E=l.useCallback(async z=>{if(z.button===0&&m)try{const{getCurrentWindow:G}=await _r(async()=>{const{getCurrentWindow:ce}=await import("./vendor-.pnpm-COYWCHRJ.js").then(Ne=>Ne.bY);return{getCurrentWindow:ce}},__vite__mapDeps([0,1]));await G().startDragging()}catch(G){console.error("Failed to start window dragging:",G)}},[m]),F=l.useMemo(()=>[{id:"chat",label:"Chat",icon:kd},{id:"diff",label:"Diff",icon:zs,badge:!u&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:Ws},{id:"git",label:"Git",icon:zt}],[p,u]);de.useEffect(()=>{const z=G=>{if((G.metaKey||G.ctrlKey)&&!G.shiftKey&&!G.altKey){const W=parseInt(G.key,10);W>=1&&W<=F.length&&(G.preventDefault(),i(F[W-1].id))}};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[F,i]);const $=(z,G)=>{const W=a===z.id,ce=z.icon,Ne=z.id==="chat",Me=z.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>i(z.id),onMouseDown:W?E:void 0,className:T("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",W?"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",W?"text-foreground":"text-muted-foreground",W&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",W&&Ne&&n&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",Ne&&!(m&&g&&n)&&"border-l",Me&&"border-r",Ne&&!u&&"min-w-[165px]"),style:{...W&&Ne&&n?{"--sidebar-w":m&&g?`${o}px`:"64px"}:{},...Ne&&!(m&&g&&n)||Me?{borderColor:"var(--interactive-border)"}:{}},"aria-selected":W,role:"tab",children:[u?e.jsx(ce,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{size:16}),e.jsx("span",{children:z.label})]}),Ne&&!u&&j&&j.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Do,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit??0,size:"compact"})}),z.badge!==void 0&&z.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:z.badge})]}),!G&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},z.id)},R=()=>e.jsxs("div",{onMouseDown:C,className:T("app-region-drag relative flex h-12 select-none items-center",N),role:"tablist","aria-label":"Main navigation",children:[!(m&&g)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:w,"aria-label":"Open sessions",className:`${A} mr-2.5`,children:e.jsx(_n,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:F.map((z,G)=>$(z,G===F.length-1))}),e.jsx("div",{className:"flex-1"})]}),Y=()=>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:w,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(Nd,{className:"h-5 w-5"})}),j&&j.totalTokens>0&&a==="chat"&&e.jsx(Do,{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:F.map(z=>{const G=a===z.id,W=z.icon;return e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{u&&S(),i(z.id)},"aria-label":z.label,"aria-selected":G,role:"tab",className:T(A,G&&"text-foreground"),children:[e.jsx(W,{className:"h-5 w-5"}),z.badge!==void 0&&z.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:z.badge})]})}),e.jsx(ft,{children:e.jsx("p",{children:z.label})})]},z.id)})}),e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:D,"aria-label":"Open settings",className:A,children:e.jsx(pr,{className:"h-5 w-5"})})}),e.jsx(ft,{children:e.jsx("p",{children:"Settings"})})]})]})]}),Z=T("header-safe-area border-b relative z-10",m?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:f,className:Z,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:u?Y():R()})};function ga({className:r,...s}){return e.jsx("div",{"data-slot":"card",className:T("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",r),...s})}function Yl({className:r,...s}){return e.jsx("div",{"data-slot":"card-header",className:T("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",r),...s})}function Xl({className:r,...s}){return e.jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",r),...s})}function Jl({className:r,...s}){return e.jsx("div",{"data-slot":"card-content",className:T("px-6",r),...s})}class as 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(ga,{className:"w-full max-w-md",children:[e.jsx(Yl,{className:"text-center",children:e.jsxs(Xl,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(vo,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Jl,{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(As,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}const Eo=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_MOCK_UPDATE__;return r?r===!0?{currentVersion:"1.0.3",newVersion:"1.0.8"}:r:null},ci=r=>({checking:!1,available:!0,downloading:!1,downloaded:!1,info:{available:!0,version:r.newVersion??"99.0.0-test",currentVersion:r.currentVersion??"0.0.0",body:void 0},progress:null,error:null}),di=()=>Eo()!==null,Mp=(r=!0)=>{const[s,t]=de.useState({checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null}),[n]=de.useState(di),[o,a]=de.useState(()=>{if(di()){const f=Eo();return f?ci(f):null}return null}),i=de.useCallback(async()=>{if(n){const f=Eo();if(f){const m=ci(f);m.info={...m.info,body:`## [${f.newVersion}] - 2025-01-01
|
|
57
|
-
- Mock update for UI testing`},a(m)}return}if(Zt()){t(f=>({...f,checking:!0,error:null}));try{const f=await am();t(m=>({...m,checking:!1,available:f?.available??!1,info:f}))}catch(f){t(m=>({...m,checking:!1,error:f instanceof Error?f.message:"Failed to check for updates"}))}}},[n]),c=de.useCallback(async()=>{if(n){a(h=>h&&{...h,downloading:!0});let f=0;const m=setInterval(()=>{f+=20,a(h=>h&&{...h,progress:{downloaded:f*1e3,total:1e5}}),f>=100&&(clearInterval(m),a(h=>h&&{...h,downloading:!1,downloaded:!0,progress:null}))},500);return}if(!(!Zt()||!s.available)){t(f=>({...f,downloading:!0,error:null,progress:null}));try{await im(f=>{t(m=>({...m,progress:f}))}),t(f=>({...f,downloading:!1,downloaded:!0}))}catch(f){t(m=>({...m,downloading:!1,error:f instanceof Error?f.message:"Failed to download update"}))}}},[n,s.available]),d=de.useCallback(async()=>{if(!n&&!(!Zt()||!s.downloaded))try{await lm()}catch(f){t(m=>({...m,error:f instanceof Error?f.message:"Failed to restart"}))}},[n,s.downloaded]),u=de.useCallback(()=>{if(n){a(null);return}t(f=>({...f,available:!1,downloaded:!1,info:null}))},[n]);return de.useEffect(()=>{if(r&&(Zt()||n)){const f=setTimeout(()=>{i()},3e3);return()=>clearTimeout(f)}},[r,i,n]),{...n&&o?o:s,checkForUpdates:i,downloadUpdate:c,restartToUpdate:d,dismiss:u}};let tn=0;function Ts({...r}){return e.jsx(Cd,{"data-slot":"dialog",...r})}function Zl({...r}){return e.jsx(Id,{"data-slot":"dialog-trigger",...r})}function Ap({...r}){return e.jsx(Dd,{"data-slot":"dialog-portal",...r})}const Ql=de.forwardRef(({className:r,...s},t)=>(de.useEffect(()=>(tn+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{tn=Math.max(0,tn-1),tn===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(ul,{ref:t,"data-slot":"dialog-overlay",className:T("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",r),...s})));Ql.displayName=ul.displayName;function Is({className:r,children:s,showCloseButton:t=!0,...n}){return e.jsxs(Ap,{"data-slot":"dialog-portal",children:[e.jsx(Ql,{className:"rounded-none"}),e.jsxs(Md,{"data-slot":"dialog-content",className:T("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",r),...n,children:[s,t&&e.jsxs(Ad,{"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(hs,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Fs({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:T("flex flex-col gap-2 text-center sm:text-left",r),...s})}function Wr({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-footer",className:T("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",r),...s})}function Ps({className:r,...s}){return e.jsx(Ed,{"data-slot":"dialog-title",className:T("typography-markdown leading-none font-semibold text-foreground",r),...s})}function nr({className:r,...s}){return e.jsx(Td,{"data-slot":"dialog-description",className:T("text-muted-foreground typography-ui-label",r),...s})}const ui="https://github.com/btriapitsyn/openchamber/releases",Dp=({open:r,onOpenChange:s,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d})=>{const u=t?.version?`${ui}/tag/v${t.version}`:ui,p=a?.total?Math.round(a.downloaded/a.total*100):0;return e.jsx(Ts,{open:r,onOpenChange:s,children:e.jsxs(Is,{className:"max-w-md",children:[e.jsx(Fs,{children:e.jsxs(Ps,{className:"flex items-center gap-2",children:[e.jsx(Fd,{className:"h-5 w-5 text-primary"}),"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(t?.currentVersion||t?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t?.currentVersion&&e.jsx("span",{className:"font-mono",children:t.currentVersion}),t?.currentVersion&&t?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),t?.version&&e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),t?.body&&e.jsx(Ye,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((f,m)=>/^\d+\.\d+\.\d+$/.test(f.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",f.trim(),`
|
|
58
|
-
`]},m):f.replace(/^- /gm,"• ").trim()+`
|
|
59
|
-
|
|
60
|
-
`)})}),n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[p,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${p}%`}})})]}),i&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:i})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:T("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(jo,{className:"h-4 w-4"}),"GitHub"]}),!o&&!n&&e.jsxs("button",{onClick:c,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Wo,{className:"h-4 w-4"}),"Download Update"]}),n&&e.jsxs("button",{disabled:!0,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(Pd,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),o&&e.jsxs("button",{onClick:d,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(As,{className:"h-4 w-4"}),"Restart to Update"]})]})]})]})})},Fn=264,mi=200,fi=500,Ep=40,pi="openchamber:check-for-updates",Tp=({isOpen:r,isMobile:s,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a}=Fe(),[i,c]=l.useState(!1),d=l.useRef(0),u=l.useRef(n||Fn),[p,f]=l.useState(!1),m=Mp(),h=l.useRef(!1),g=m.checkForUpdates,{available:x,downloaded:y,checking:b}=m,[k,j]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),v=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const N=typeof window.opencodeDesktop<"u";j(N)},[]),l.useEffect(()=>{if(typeof window>"u")return;const N=()=>{typeof window.opencodeDesktop<"u"&&(h.current=!0,g())};return window.addEventListener(pi,N),()=>{window.removeEventListener(pi,N)}},[g]),l.useEffect(()=>{h.current&&(b||((x||y)&&f(!0),h.current=!1))},[x,y,b]),l.useEffect(()=>{if(s||!i)return;const N=C=>{const E=C.clientX-d.current,F=Math.min(fi,Math.max(mi,u.current+E));o(F)},M=()=>{c(!1)};return window.addEventListener("pointermove",N),window.addEventListener("pointerup",M,{once:!0}),()=>{window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",M)}},[s,i,o]),l.useEffect(()=>{s&&i&&c(!1)},[s,i]);const S=l.useCallback(async N=>{if(N.button===0&&k)try{const{getCurrentWindow:M}=await _r(async()=>{const{getCurrentWindow:E}=await import("./vendor-.pnpm-COYWCHRJ.js").then(F=>F.bY);return{getCurrentWindow:E}},__vite__mapDeps([0,1]));await M().startDragging()}catch(M){console.error("Failed to start window dragging from sidebar:",M)}},[k]);if(s)return null;const w=r?Math.min(fi,Math.max(mi,n||Fn)):0,D=k&&v,A=N=>{r&&(c(!0),d.current=N.clientX,u.current=w,N.preventDefault())};return e.jsxs("aside",{className:T("relative flex h-full overflow-hidden border-r",k?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",i?"transition-none":"",!r&&"border-r-0"),style:{width:`${w}px`,minWidth:`${w}px`,maxWidth:`${w}px`,pointerEvents:r?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!r||w===0,children:[r&&e.jsx("div",{className:T("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",i?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:A,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:T("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!r&&"pointer-events-none select-none opacity-0"),style:{width:`${w}px`,overflowX:"hidden"},"aria-hidden":!r,children:[D&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Ep}px`},onMouseDown:S,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(as,{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(pr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),(x||y)&&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(Wo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]})]})}),e.jsx(Dp,{open:p,onOpenChange:f,info:m.info,downloading:m.downloading,downloaded:m.downloaded,progress:m.progress,error:m.error,onDownload:m.downloadUpdate,onRestart:m.restartToUpdate})]})]})},ec=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Uo},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Bn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:br},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:ml},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:zt},{id:"settings",label:"Appearance",description:"Fine-tune themes, fonts, and typography across the interface.",icon:Rd}],Ip={},tc={},sc={};ec.forEach(r=>{Ip[r.id]=r.label,tc[r.id]=r.description,sc[r.id]=r});const hi=tc,Fp=sc;function Ls({className:r,variant:s,...t}){return e.jsx(Ee,{variant:s,size:"sm",className:T("h-7 px-2 py-0",r),...t})}function Tt({className:r,type:s,...t}){return e.jsx("input",{type:s,"data-slot":"input",className:T("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",r),...t})}const Pp=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedAgentName:o,agents:a,setSelectedAgent:i,deleteAgent:c,loadAgents:d}=wr(),{setSidebarOpen:u}=Fe(),{isMobile:p}=At();l.useEffect(()=>{d()},[d]);const f=()=>{if(!r.trim()){xe.error("Agent name is required");return}if(a.some(b=>b.name===r)){xe.error("An agent with this name already exists");return}i(r),s(""),n(!1),p&&u(!1)},m=async b=>{if(b.builtIn){xe.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${b.name}"?`)&&(await c(b.name)?xe.success(`Agent "${b.name}" deleted successfully`):xe.error("Failed to delete agent"))},h=b=>{const k=b.name;let j=1,v=`${k} Copy`;for(;a.some(S=>S.name===v);)j++,v=`${k} Copy ${j}`;i(v),n(!1),p&&u(!1)},g=b=>{switch(b){case"primary":return e.jsx(Br,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(pl,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(fl,{className:"h-3 w-3 text-primary"});default:return null}},x=a.filter(b=>b.builtIn),y=a.filter(b=>!b.builtIn);return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(Ts,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",p?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Agents"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.length}),e.jsx(Zl,{asChild:!0,children:e.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(ls,{className:"size-4"})})})]})]})}),e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:a.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(vn,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[x.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),x.map(b=>e.jsx(gi,{agent:b,isSelected:o===b.name,onSelect:()=>{i(b.name),p&&u(!1)},onDuplicate:()=>h(b),getAgentModeIcon:g},b.name))]}),y.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"}),y.map(b=>e.jsx(gi,{agent:b,isSelected:o===b.name,onSelect:()=>{i(b.name),p&&u(!1)},onDelete:()=>m(b),onDuplicate:()=>h(b),getAgentModeIcon:g},b.name))]})]})}),e.jsxs(Is,{children:[e.jsxs(Fs,{children:[e.jsx(Ps,{children:"Create New Agent"}),e.jsx(nr,{children:"Enter a unique name for your new agent"})]}),e.jsx(Tt,{value:r,onChange:b=>s(b.target.value),placeholder:"Agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:b=>{b.key==="Enter"&&f()}}),e.jsxs(Wr,{children:[e.jsx(Ee,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Ls,{onClick:f,children:"Create"})]})]})]})})},gi=({agent:r,isSelected:s,onSelect:t,onDelete:n,onDuplicate:o,getAgentModeIcon:a})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",s?"text-primary":"text-foreground hover:text-primary/80"),children:r.name}),a(r.mode)]}),r.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.description})]}),e.jsxs(Kt,{children:[e.jsx(Yt,{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(On,{className:"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(yt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(Rs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),!r.builtIn&&n&&e.jsxs(yt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})});function js({className:r,variant:s,...t}){return e.jsx(Ee,{variant:s,size:"sm",className:T("h-6 px-2 text-xs",r),...t})}const tr=de.forwardRef(({className:r,...s},t)=>e.jsx(Ye,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:T("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",r),...s}));tr.displayName="Textarea";const Rp="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",Lp="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",_p=Object.assign({"../assets/provider-logos/gocode.svg":Rp,"../assets/provider-logos/kimi-for-coding.svg":Lp}),To=new Map;for(const[r,s]of Object.entries(_p)){const t=r.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&s&&To.set(t[1].toLowerCase(),s)}function rc(r){const s=r?.toLowerCase()??null,t=s?To.has(s):!1,n=s?To.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"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${s}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const Ut=({providerId:r,alt:s,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=rc(r),c=l.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:s||`${r} logo`,className:T("dark:invert",t),onError:c})},nc=()=>{const{providers:r}=St(),{favoriteModels:s,recentModels:t}=Fe(),n=l.useMemo(()=>s.map(({providerID:a,modelID:i})=>{const c=r.find(p=>p.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(p=>p.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[s,r]),o=l.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const c=r.find(p=>p.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(p=>p.id===i);return u?{provider:c,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!s.some(c=>c.providerID===a&&c.modelID===i)),[t,r,s]);return{favoriteModelsList:n,recentModelsList:o}},oc=({providerId:r,modelId:s,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=St(),i=Fe(A=>A.isMobile),{toggleFavoriteModel:c,isFavoriteModel:d,addRecentModel:u}=Fe(),{favoriteModelsList:p,recentModelsList:f}=nc(),{isMobile:m}=At(),h=i||m,[g,x]=l.useState(!1),[y,b]=l.useState(new Set),k=()=>x(!1),j=A=>{b(N=>{const M=new Set(N);return M.has(A)?M.delete(A):M.add(A),M})},v=A=>{const N=A?.name||A?.id||"",M=String(N);return M.length>40?M.substring(0,37)+"...":M},S=(A,N)=>{const M=`${A}/${N}`;return a.get(M)},w=(A,N)=>{t(A,N),u(A,N)},D=()=>h?e.jsx(qt,{open:g,onClose:k,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:N,modelID:M})=>{const C=N===r&&M===s,E=S(N,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:()=>{w(N,M),k()},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{providerId:N,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:v(A)})]}),typeof E?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:E.description})]}),e.jsx("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),c(N,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(ms,{className:"h-4 w-4"})})]},`fav-mobile-${N}-${M}`)})})]}),f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:A,providerID:N,modelID:M})=>{const C=N===r&&M===s,E=S(N,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:()=>{w(N,M),k()},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{providerId:N,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:v(A)})]}),typeof E?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:E.description})]}),e.jsx("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),c(N,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(Zs,{className:"h-4 w-4"})})]},`recent-mobile-${N}-${M}`)})})]}),o.map(A=>{const N=Array.isArray(A.models)?A.models:[];if(N.length===0)return null;const M=A.id===r,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:()=>j(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(vt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(gs,{className:"h-3 w-3 text-muted-foreground"})]}),C&&e.jsx("div",{className:"border-t border-border/20",children:N.map(E=>{const F=A.id===r&&E.id===s,$=S(A.id,E.id);return e.jsxs("div",{className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",F?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsxs("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{w(A.id,E.id),k()},children:[e.jsx("span",{className:"font-medium truncate",children:v(E)}),typeof $?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:$.description})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:R=>{R.preventDefault(),R.stopPropagation(),c(A.id,E.id)},className:T("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(A.id,E.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(A.id,E.id)?"Unfavorite":"Favorite",children:d(A.id,E.id)?e.jsx(ms,{className:"h-4 w-4"}):e.jsx(Zs,{className:"h-4 w-4"})}),F&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},E.id)})})]},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:()=>{w("",""),k()},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",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(Ut,{providerId:r,className:"h-3.5 w-3.5"}):e.jsx(Ns,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:r&&s?`${r}/${s}`:"Select model..."})]}),e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",n),children:[r?e.jsxs(e.Fragment,{children:[e.jsx(Ut,{providerId:r,className:"h-3 w-3 flex-shrink-0"}),e.jsx(Ns,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(Ns,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:r&&s?`${r}/${s}`:"Not selected"}),e.jsx(vt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Xt,{className:"max-w-[300px]",children:[p.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(ms,{className:"h-3 w-3 flex-shrink-0 mr-2 text-yellow-500"}),"Favorites"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ye,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:p.map(({model:A,providerID:N,modelID:M})=>{const C=S(N,M);return e.jsx(yt,{className:"typography-meta",onSelect:E=>{E.preventDefault(),w(N,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:v(A)}),typeof C?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:C.description})]}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),c(N,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(ms,{className:"h-3.5 w-3.5"})})]})},`fav-${N}-${M}`)})})})]}),f.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(jn,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ye,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:f.map(({model:A,providerID:N,modelID:M})=>{const C=S(N,M);return e.jsx(yt,{className:"typography-meta",onSelect:E=>{E.preventDefault(),w(N,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:v(A)}),typeof C?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:C.description})]}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),c(N,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(Zs,{className:"h-3.5 w-3.5"})})]})},`recent-${N}-${M}`)})})})]}),(p.length>0||f.length>0)&&e.jsx(Hr,{}),o.map(A=>{const N=Array.isArray(A.models)?A.models:[];return N.length===0?e.jsxs(yt,{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(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(Ut,{providerId:A.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),A.name]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ye,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:N.map(M=>{const C=S(A.id,M.id);return e.jsx(yt,{className:"typography-meta",onSelect:E=>{E.preventDefault(),w(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:v(M)}),typeof C?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground truncate",children:C.description})]}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.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(ms,{className:"h-3.5 w-3.5"}):e.jsx(Zs,{className:"h-3.5 w-3.5"})})]})},M.id)})})})]},A.id)}),e.jsx(yt,{className:"typography-meta",onSelect:()=>w("",""),children:e.jsx("span",{className:"text-muted-foreground",children:"No model (optional)"})})]})]}),D()]})},Bp=()=>{const{tools:r}=rr(),[s,t]=l.useState([]),[n,o]=l.useState(!0),[a,i]=l.useState(null);return l.useEffect(()=>{let c=!1;return(async()=>{o(!0),i(null);try{const u=await r.getAvailableTools();if(c)return;t(u)}catch(u){if(c)return;const p=u instanceof Error?u.message:"Failed to fetch tools";console.error("Failed to fetch available tools:",p),i(p),t([])}finally{c||o(!1)}})(),()=>{c=!0}},[r]),{tools:s,isLoading:n,error:a}},Op=()=>{const{selectedAgentName:r,getAgentByName:s,createAgent:t,updateAgent:n,agents:o}=wr();St();const{tools:a}=Bp(),i=r?s(r):null,c=r&&!i,[d,u]=l.useState(""),[p,f]=l.useState(""),[m,h]=l.useState("subagent"),[g,x]=l.useState(""),[y,b]=l.useState(void 0),[k,j]=l.useState(void 0),[v,S]=l.useState(""),[w,D]=l.useState({}),[A,N]=l.useState("allow"),[M,C]=l.useState("allow"),[E,F]=l.useState("ask"),[$,R]=l.useState(!1);l.useEffect(()=>{if(c)u(r||""),f(""),h("subagent"),x(""),b(void 0),j(void 0),S(""),D({}),N("allow"),C("allow"),F("ask");else if(i&&(u(i.name),f(i.description||""),h(i.mode||"subagent"),i.model?.providerID&&i.model?.modelID?x(`${i.model.providerID}/${i.model.modelID}`):x(""),b(i.temperature),j(i.topP),S(i.prompt||""),D(i.tools||{}),i.permission)){const G=i.permission.edit;(G==="allow"||G==="ask"||G==="deny"||G==="full")&&N(G),i.permission.webfetch&&C(i.permission.webfetch),typeof i.permission.bash=="string"&&F(i.permission.bash)}},[i,c,r,o]);const Y=async()=>{if(!d.trim()){xe.error("Agent name is required");return}R(!0);try{const G=g.trim(),W={name:d.trim(),description:p.trim()||void 0,mode:m,model:G===""?null:G,temperature:y,top_p:k,prompt:v.trim()||void 0,tools:Object.keys(w).length>0?w:void 0,permission:{edit:A,webfetch:M,bash:E}};let ce;c?ce=await t(W):ce=await n(d,W),ce?xe.success(c?"Agent created successfully":"Agent updated successfully"):xe.error(c?"Failed to create agent":"Failed to update agent")}catch(G){console.error("Error saving agent:",G),xe.error("An error occurred while saving")}finally{R(!1)}},Z=G=>{D(W=>({...W,[G]:!W[G]}))},z=G=>{const W={};a.forEach(ce=>{W[ce]=G}),D(W)};return r?e.jsxs(Ye,{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(Tt,{value:d,onChange:G=>u(G.target.value),placeholder:"my-agent",disabled:!c})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(tr,{value:p,onChange:G=>f(G.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(js,{variant:m==="primary"?"default":"outline",onClick:()=>h("primary"),className:T("gap-2",m==="primary"?void 0:"text-foreground"),children:[e.jsx(Br,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(js,{variant:m==="subagent"?"default":"outline",onClick:()=>h("subagent"),className:T("gap-2",m==="subagent"?void 0:"text-foreground"),children:[e.jsx(fl,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(js,{variant:m==="all"?"default":"outline",onClick:()=>h("all"),className:T("gap-2",m==="all"?void 0:"text-foreground"),children:[e.jsx(pl,{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(oc,{providerId:g?g.split("/")[0]:"",modelId:g?g.split("/")[1]:"",onChange:(G,W)=>{x(G&&W?`${G}/${W}`:"")}})]}),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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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 W=Math.max(0,(y!==void 0?y:.7)-.1);b(parseFloat(W.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(Na,{className:"h-3.5 w-3.5"})}),e.jsx(Tt,{type:"text",inputMode:"decimal",value:y!==void 0?y:"",onChange:G=>{const W=G.target.value;if(W===""){b(void 0);return}const ce=parseFloat(W);!isNaN(ce)&&ce>=0&&ce<=2&&b(ce)},onBlur:G=>{const W=G.target.value;if(W!==""){const ce=parseFloat(W);if(!isNaN(ce)){const Ne=Math.max(0,Math.min(2,ce));b(parseFloat(Ne.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const W=Math.min(2,(y!==void 0?y:.7)+.1);b(parseFloat(W.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(ls,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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 W=Math.max(0,(k!==void 0?k:.9)-.1);j(parseFloat(W.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(Na,{className:"h-3.5 w-3.5"})}),e.jsx(Tt,{type:"text",inputMode:"decimal",value:k!==void 0?k:"",onChange:G=>{const W=G.target.value;if(W===""){j(void 0);return}const ce=parseFloat(W);!isNaN(ce)&&ce>=0&&ce<=1&&j(ce)},onBlur:G=>{const W=G.target.value;if(W!==""){const ce=parseFloat(W);if(!isNaN(ce)){const Ne=Math.max(0,Math.min(1,ce));j(parseFloat(Ne.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const W=Math.min(1,(k!==void 0?k:.9)+.1);j(parseFloat(W.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(ls,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"System Prompt"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Override the default system prompt for this agent"})]}),e.jsx(tr,{value:v,onChange:G=>S(G.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Available Tools"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select tools this agent can access"})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>z(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>z(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(G=>e.jsx("button",{type:"button",onClick:()=>Z(G),className:T("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",w[G]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:G},G))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure permission levels for different operations"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Edit Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ee,{size:"sm",variant:A==="full"?"default":"outline",onClick:()=>N("full"),className:"h-6 px-2 text-xs",children:"Full"}),e.jsx(Ee,{size:"sm",variant:A==="allow"?"default":"outline",onClick:()=>N("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ee,{size:"sm",variant:A==="ask"?"default":"outline",onClick:()=>N("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ee,{size:"sm",variant:A==="deny"?"default":"outline",onClick:()=>N("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Controls file editing permissions."}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ft,{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:E==="allow"?"default":"outline",onClick:()=>F("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ee,{size:"sm",variant:E==="ask"?"default":"outline",onClick:()=>F("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ee,{size:"sm",variant:E==="deny"?"default":"outline",onClick:()=>F("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Permission for running bash commands"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ft,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(ft,{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:Y,disabled:$,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Vo,{className:"h-3 w-3"}),$?"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(vn,{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"})]})})},$p=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedCommandName:o,commands:a,setSelectedCommand:i,deleteCommand:c,loadCommands:d}=vr(),{setSidebarOpen:u}=Fe(),{isMobile:p}=At();l.useEffect(()=>{d()},[d]);const f=()=>{if(!r.trim()){xe.error("Command name is required");return}const g=r.trim().replace(/\s+/g,"-");if(a.some(x=>x.name===g)){xe.error("A command with this name already exists");return}i(g),s(""),n(!1),p&&u(!1)},m=async g=>{window.confirm(`Are you sure you want to delete command "${g.name}"?`)&&(await c(g.name)?xe.success(`Command "${g.name}" deleted successfully`):xe.error("Failed to delete command"))},h=g=>{const x=g.name;let y=1,b=`${x}-copy`;for(;a.some(k=>k.name===b);)y++,b=`${x}-copy-${y}`;i(b),n(!1),p&&u(!1)};return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(Ts,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",p?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Commands"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.length}),e.jsx(Zl,{asChild:!0,children:e.jsx(Ee,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(ls,{className:"size-4"})})})]})]})}),e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:a.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ws,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No commands configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:[...a].sort((g,x)=>g.name.localeCompare(x.name)).map(g=>e.jsx(zp,{command:g,isSelected:o===g.name,onSelect:()=>{i(g.name),p&&u(!1)},onDelete:()=>m(g),onDuplicate:()=>h(g)},g.name))})}),e.jsxs(Is,{children:[e.jsxs(Fs,{children:[e.jsx(Ps,{children:"Create New Command"}),e.jsx(nr,{children:"Enter a unique name for your new slash command"})]}),e.jsx(Tt,{value:r,onChange:g=>s(g.target.value),placeholder:"Command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:g=>{g.key==="Enter"&&f()}}),e.jsxs(Wr,{children:[e.jsx(Ee,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Ls,{onClick:f,children:"Create"})]})]})]})})},zp=({command:r,isSelected:s,onSelect:t,onDelete:n,onDuplicate:o})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:T("typography-ui-label font-medium truncate flex-1",s?"text-primary":"text-foreground hover:text-primary/80"),children:["/",r.name]})}),r.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.description})]}),e.jsxs(Kt,{children:[e.jsx(Yt,{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(On,{className:"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(yt,{onClick:a=>{a.stopPropagation(),o()},children:[e.jsx(Rs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(yt,{onClick:a=>{a.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})}),Hp=({agentName:r,onChange:s,className:t})=>{const{agents:n,loadAgents:o}=wr(),a=Fe(h=>h.isMobile),{isMobile:i}=At(),c=a||i,[d,u]=l.useState(!1);l.useEffect(()=>{o()},[o]);const p=()=>u(!1),f=h=>{s(h)},m=()=>c?e.jsx(qt,{open:d,onClose:p,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[n.map(h=>{const g=h.name===r;return e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",g?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{f(h.name),p()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:h.name}),h.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:h.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},h.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(""),p()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No agent (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[c?e.jsxs("button",{type:"button",onClick:()=>u(!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(vn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:r||"Select agent..."})]}),e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Kt,{children:[e.jsx(Yt,{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(vn,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:r||"Not selected"}),e.jsx(vt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Xt,{className:"max-w-[300px]",children:[n.map(h=>e.jsx(yt,{className:"typography-meta",onSelect:()=>f(h.name),children:e.jsx("span",{className:"font-medium",children:h.name})},h.name)),e.jsx(yt,{className:"typography-meta",onSelect:()=>f(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),m()]})},Wp=()=>{const{selectedCommandName:r,getCommandByName:s,createCommand:t,updateCommand:n,commands:o}=vr(),a=r?s(r):null,i=r&&!a,[c,d]=l.useState(""),[u,p]=l.useState(""),[f,m]=l.useState(""),[h,g]=l.useState(""),[x,y]=l.useState(""),[b,k]=l.useState(!1),[j,v]=l.useState(!1);l.useEffect(()=>{i?(d(r||""),p(""),m(""),g(""),y(""),k(!1)):a&&(d(a.name),p(a.description||""),m(a.agent||""),g(a.model||""),y(a.template||""),k(a.subtask||!1))},[a,i,r,o]);const S=async()=>{if(!c.trim()){xe.error("Command name is required");return}if(!x.trim()){xe.error("Command template is required");return}v(!0);try{const w=f.trim(),D=h.trim(),A=x.trim(),N={name:c.trim(),description:u.trim()||void 0,agent:w===""?null:w,model:D===""?null:D,template:A,subtask:b};let M;i?M=await t(N):M=await n(c,N),M?xe.success(i?"Command created successfully":"Command updated successfully"):xe.error(i?"Failed to create command":"Failed to update command")}catch(w){console.error("Error saving command:",w),xe.error("An error occurred while saving")}finally{v(!1)}};return r?e.jsxs(Ye,{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(Tt,{value:c,onChange:w=>d(w.target.value),placeholder:"my-command",disabled:!i}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Used with slash (/) prefix in chat"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(tr,{value:u,onChange:w=>p(w.target.value),placeholder:"What does this command do?",rows:3})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model & Agent Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and agent for command execution"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(Hp,{agentName:f,onChange:w=>m(w)}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Agent to execute this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(oc,{providerId:h?h.split("/")[0]:"",modelId:h?h.split("/")[1]:"",onChange:(w,D)=>{g(w&&D?`${w}/${D}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:b,onChange:w=>k(w.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(It,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{sideOffset:8,className:"max-w-xs",children:["When enabled, this command will always execute in a subagent context,",e.jsx("br",{}),"even if triggered from main agent.",e.jsx("br",{}),"Useful for isolating command logic and maintaining clean separation of concerns."]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Command Template"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Define the prompt template for this command. Use $ARGUMENTS for user input."})]}),e.jsx(tr,{value:x,onChange:w=>y(w.target.value),placeholder:`Your command template here...
|
|
61
|
-
|
|
62
|
-
Use $ARGUMENTS to reference user input.
|
|
63
|
-
Use !\`shell command\` to inject shell output.
|
|
64
|
-
Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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:j,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Vo,{className:"h-3 w-3"}),j?"Saving...":"Save Changes"]})})]})]}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ws,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a command from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})},ac=({sectionId:r,variant:s})=>{const t=Fp[r],n=t.icon;return s==="sidebar"?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center",children:[e.jsx("div",{className:"rounded-full bg-accent/40 p-3 text-muted-foreground",children:e.jsx(n,{className:"h-5 w-5"})}),e.jsx("h3",{className:"typography-ui-label font-semibold text-foreground",children:t.label}),e.jsx("p",{className:"typography-meta max-w-xs text-muted-foreground",children:hi[r]})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-4 px-6 text-center",children:[e.jsx("div",{className:"rounded-full bg-accent/40 p-4 text-muted-foreground",children:e.jsx(n,{className:"h-8 w-8"})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:t.label}),e.jsx("p",{className:"typography-body max-w-md text-muted-foreground",children:hi[r]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60",children:"Coming soon..."})]})},Up=()=>e.jsx(Ye,{outerClassName:"h-full",className:"px-3 py-2",children:e.jsx(ac,{sectionId:"providers",variant:"sidebar"})}),Vp=()=>e.jsx(Ye,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:e.jsx(ac,{sectionId:"providers",variant:"page"})}),Un=Ot()(Ht(xs((r,s)=>({selectedProfileId:null,profiles:[],globalIdentity:null,isLoading:!1,setSelectedProfile:t=>{r({selectedProfileId:t})},loadProfiles:async()=>{r({isLoading:!0});const t=s().profiles;try{const n=await Tm();return r({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),r({profiles:t,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const t=await Rm("");if(t&&t.userName&&t.userEmail){const n={id:"global",name:"Global Identity",userName:t.userName,userEmail:t.userEmail,sshKey:t.sshCommand?t.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};r({globalIdentity:n})}else r({globalIdentity:null});return!0}catch(t){return console.error("Failed to load global git identity:",t),r({globalIdentity:null}),!1}},createProfile:async t=>{try{const n={...t,id:t.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:t.color||"keyword",icon:t.icon||"branch"};return await Im(n),await s().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(t,n)=>{try{const o=s().profiles.find(i=>i.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Fm(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 Pm(t),s().selectedProfileId===t&&r({selectedProfileId:null}),await s().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:t=>{const{profiles:n,globalIdentity:o}=s();return t==="global"?o||void 0:n.find(a=>a.id===t)}}),{name:"git-identities-store",storage:ys(()=>Qt()),partialize:r=>({selectedProfileId:r.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Un);const Gp={branch:zt,briefcase:Ko,house:qo,graduation:Go,code:zs,heart:hl},qp={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Kp=()=>{const{selectedProfileId:r,profiles:s,globalIdentity:t,setSelectedProfile:n,deleteProfile:o,loadProfiles:a,loadGlobalIdentity:i}=Un(),{setSidebarOpen:c}=Fe(),{isMobile:d}=At();l.useEffect(()=>{a(),i()},[a,i]);const u=()=>{n("new"),d&&c(!1)},p=async f=>{window.confirm(`Are you sure you want to delete profile "${f.name}"?`)&&(await o(f.id)?xe.success(`Profile "${f.name}" deleted successfully`):xe.error("Failed to delete profile"))};return e.jsxs("div",{className:"flex h-full flex-col bg-sidebar",children:[e.jsx("div",{className: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(ls,{className:"size-4"})})]})]})}),e.jsxs(Ye,{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(xi,{profile:t,isSelected:r==="global",onSelect:()=>{n("global"),d&&c(!1)},onDelete:void 0,isReadOnly:!0})]}),s.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),s.length===0&&!t?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(zt,{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(f=>e.jsx(xi,{profile:f,isSelected:r===f.id,onSelect:()=>{n(f.id),d&&c(!1)},onDelete:()=>p(f)},f.id))})]})]})},xi=({profile:r,isSelected:s,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=Gp[r.icon||"branch"]||zt,i=qp[r.color||""];return e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a,{className:"w-4 h-4 flex-shrink-0",style:{color:i}}),e.jsx("div",{className:T("typography-ui-label font-medium truncate flex-1",s?"text-primary":"text-foreground hover:text-primary/80"),children:r.name})]}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.userEmail})]}),!o&&n&&e.jsxs(Kt,{children:[e.jsx(Yt,{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(On,{className:"h-3.5 w-3.5"})})}),e.jsx(Xt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(yt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Us,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})})},yi=[{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)"}],Yp=[{key:"branch",Icon:zt,label:"Branch"},{key:"briefcase",Icon:Ko,label:"Work"},{key:"house",Icon:qo,label:"Personal"},{key:"graduation",Icon:Go,label:"School"},{key:"code",Icon:zs,label:"Code"}],Xp=()=>{const{selectedProfileId:r,getProfileById:s,createProfile:t,updateProfile:n,deleteProfile:o}=Un(),a=l.useMemo(()=>r&&r!=="new"?s(r):null,[r,s]),i=r==="new",c=r==="global",[d,u]=l.useState(""),[p,f]=l.useState(""),[m,h]=l.useState(""),[g,x]=l.useState(""),[y,b]=l.useState("keyword"),[k,j]=l.useState("branch"),[v,S]=l.useState(!1);l.useEffect(()=>{i?(u(""),f(""),h(""),x(""),b("keyword"),j("branch")):a&&(u(a.name),f(a.userName),h(a.userEmail),x(a.sshKey||""),b(a.color||"keyword"),j(a.icon||"branch"))},[a,i,r]);const w=async()=>{if(!p.trim()||!m.trim()){xe.error("User name and email are required");return}S(!0);try{const N={name:d.trim()||p.trim(),userName:p.trim(),userEmail:m.trim(),sshKey:g.trim()||null,color:y,icon:k};let M;if(i)M=await t(N);else if(r)M=await n(r,N);else return;M?xe.success(i?"Profile created successfully":"Profile updated successfully"):xe.error(i?"Failed to create profile":"Failed to update profile")}catch(N){console.error("Error saving profile:",N),xe.error("An error occurred while saving")}finally{S(!1)}},D=async()=>{if(!(!r||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(r)?xe.success("Profile deleted successfully"):xe.error("Failed to delete profile")}catch(N){console.error("Error deleting profile:",N),xe.error("An error occurred while deleting")}},A=l.useMemo(()=>yi.find(M=>M.key===y)?.cssVar||"var(--syntax-keyword)",[y]);return r?e.jsxs(Ye,{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(Tt,{value:d,onChange:N=>u(N.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:yi.map(N=>e.jsx("button",{onClick:()=>b(N.key),className:T("w-8 h-8 rounded-lg border-2 transition-all",y===N.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:N.cssVar},title:N.label},N.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Yp.map(N=>{const M=N.Icon;return e.jsx("button",{onClick:()=>j(N.key),className:T("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",k===N.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:N.label,children:e.jsx(M,{className:"w-4 h-4",style:{color:A}})},N.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(Tt,{value:p,onChange:N=>f(N.target.value),placeholder:"John Doe",required:!c,readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(Tt,{type:"email",value:m,onChange:N=>h(N.target.value),placeholder:"john@example.com",required:!c,readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["SSH Key Path",e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(ts,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(ft,{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(Tt,{value:g,onChange:N=>x(N.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!c&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(Ee,{size:"sm",variant:"destructive",onClick:D,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Us,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:T("flex gap-2",i&&"ml-auto"),children:e.jsxs(Ee,{size:"sm",variant:"default",onClick:w,disabled:v,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Vo,{className:"h-3 w-3"}),v?"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($n,{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 oo(r,s,t){return Math.min(t,Math.max(s,r))}const Io=de.forwardRef(({value:r,onValueChange:s,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:c,onKeyDown:d,disabled:u,...p},f)=>{const m=de.useRef(null);de.useImperativeHandle(f,()=>m.current);const[h,g]=de.useState(()=>String(r));de.useEffect(()=>{document.activeElement!==m.current&&g(String(r))},[r]);const x=de.useCallback(()=>{m.current?.focus()},[]),y=de.useCallback(M=>{const C=oo(M,t,n);s(C),g(String(C))},[n,t,s]),b=de.useCallback(()=>{const M=Number(h);return Number.isFinite(M)?M:r},[h,r]),k=de.useCallback(()=>{y(b()+o),x()},[y,b,x,o]),j=de.useCallback(()=>{y(b()-o),x()},[y,b,x,o]),v=M=>{const C=M.target.value;g(C);const E=Number(C);Number.isFinite(E)&&s(oo(E,t,n))},S=M=>{const C=Number(h);if(!Number.isFinite(C))g(String(r));else{const E=oo(C,t,n);E!==C&&s(E),g(String(E))}c?.(M)},w=M=>{if(M.key==="ArrowUp"){M.preventDefault(),k();return}if(M.key==="ArrowDown"){M.preventDefault(),j();return}d?.(M)},D=b(),A=u||D<=t,N=u||D>=n;return e.jsxs("div",{className:T("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",i),children:[e.jsx("input",{...p,ref:m,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:h,onChange:v,onBlur:S,onKeyDown:w,disabled:u,className:T("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:N,onClick:k,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(zn,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:A,onClick:j,className:T("flex flex-1 items-center justify-center border-t border-border","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(vt,{className:"h-3.5 w-3.5"})})]})]})});Io.displayName="NumberInput";const Jp=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],bi=[{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"}],wi=[{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."}],Zp=()=>{const{isMobile:r}=At(),s=Fe(h=>h.showReasoningTraces),t=Fe(h=>h.setShowReasoningTraces),n=Fe(h=>h.toolCallExpansion),o=Fe(h=>h.setToolCallExpansion),a=Fe(h=>h.fontSize),i=Fe(h=>h.setFontSize),c=Fe(h=>h.padding),d=Fe(h=>h.setPadding),u=Fe(h=>h.diffLayoutPreference),p=Fe(h=>h.setDiffLayoutPreference),{themeMode:f,setThemeMode:m}=jr();return e.jsxs("div",{className:"w-full space-y-8",children:[!ss()&&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:Jp.map(h=>e.jsx(js,{variant:f===h.value?"default":"outline",className:T(f===h.value?void 0:"text-foreground"),onClick:()=>m(h.value),children:h.label},h.value))})]}),!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Font Size"})}),e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:a,onChange:h=>i(Number(h.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(Io,{value:a,onValueChange:i,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(js,{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(As,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Spacing"})}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:c,onChange:h=>d(Number(h.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Spacing percentage"}),e.jsx("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:c}),e.jsx(js,{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(As,{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(Io,{value:c,onValueChange:d,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(js,{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(As,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Tool Output"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:bi.find(h=>h.value===n)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:bi.map(h=>e.jsx(js,{variant:n===h.value?"default":"outline",className:T(n===h.value?void 0:"text-foreground"),onClick:()=>o(h.value),children:h.label},h.value))})]}),!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:wi.map(h=>e.jsx(js,{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:wi.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"})]})]})},ic=()=>e.jsx(Ye,{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(Zp,{})}),vi=(()=>{const r=ec.filter(n=>n.id!=="sessions"),s=r.find(n=>n.id==="settings"),t=r.filter(n=>n.id!=="settings");return s?[s,...t]:r})(),Qp=({isOpen:r,onClose:s})=>{const[t,n]=l.useState("settings"),[o,a]=l.useState(!1),{isMobile:i}=At();l.useEffect(()=>{r&&(n("settings"),a(!1))},[r]);const c=l.useCallback(y=>{n(y),i&&a(!1)},[i]),d=l.useCallback(()=>{i&&a(!0)},[i]),u=()=>{if(t==="settings")return null;const y=(()=>{switch(t){case"agents":return e.jsx(Pp,{});case"commands":return e.jsx($p,{});case"providers":return e.jsx(Up,{});case"git-identities":return e.jsx(Kp,{});default:return null}})();return i?e.jsx("div",{onClick:d,children:y}):y},p=()=>{switch(t){case"agents":return e.jsx(Op,{});case"commands":return e.jsx(Wp,{});case"providers":return e.jsx(Vp,{});case"git-identities":return e.jsx(Xp,{});case"settings":return e.jsx(ic,{});default:return null}},f=vi.find(y=>y.id===t),m=i,h=e.jsxs(Fs,{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(Ca,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx(Ps,{className:"typography-ui-header",children:"Settings"})]}),f&&e.jsx(nr,{className:"typography-meta text-muted-foreground hidden sm:block",children:f.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:vi.map(({id:y,label:b,icon:k})=>{const j=t===y,v=k;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",j?"text-primary":"text-muted-foreground hover:text-foreground"),"aria-pressed":j,"aria-label":b,children:[e.jsx(v,{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:`${Fn}px`,minWidth:`${Fn}px`},children:e.jsx(as,{children:u()})}),(t==="settings"||!i||o)&&e.jsx("div",{className:T("flex-1 overflow-hidden bg-background",i&&"w-full"),children:e.jsx(as,{children:p()})})]})]}),x=e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[!m&&h,g]});return m?e.jsx(qt,{open:r,onClose:s,title:"Settings",className:"max-w-full",contentMaxHeightClassName:"h-[min(80dvh,720px)]",renderHeader:y=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsxs("div",{className:"relative flex flex-1 items-center justify-center",children:[o&&e.jsxs(Ee,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(Ca,{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(Ts,{open:r,onOpenChange:y=>!y&&s(),children:e.jsx(Is,{className:T("flex flex-col gap-0 p-0","h-[88vh] w-[65vw] max-w-[900px]"),children:x})})};function lc({className:r,...s}){return e.jsx(sr,{"data-slot":"command",className:T("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",r),...s})}function eh({title:r="Command Palette",description:s="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(Ts,{...a,children:[e.jsxs(Fs,{className:"sr-only",children:[e.jsx(Ps,{children:r}),e.jsx(nr,{children:s})]}),e.jsx(Is,{className:T("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(lc,{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 cc({className:r,...s}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(Yo,{className:"size-4 shrink-0 opacity-50"}),e.jsx(sr.Input,{"data-slot":"command-input",className:T("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r),...s})]})}function dc({className:r,children:s,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(Ye,{as:sr.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:T("scroll-py-1 overflow-x-hidden h-full min-h-0",r),scrollbarClassName:t??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:s})}function uc({...r}){return e.jsx(sr.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...r})}function Lr({className:r,...s}){return e.jsx(sr.Group,{"data-slot":"command-group",className:T("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",r),...s})}function Fo({className:r,...s}){return e.jsx(sr.Separator,{"data-slot":"command-separator",className:T("bg-border -mx-1 h-px",r),...s})}function _t({className:r,...s}){return e.jsx(sr.Item,{"data-slot":"command-item",className:T("hover:bg-accent hover:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",r),...s})}function Ys({className:r,...s}){const t=a=>{const i=a.trim().toLowerCase();return i==="ctrl"||i==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?e.jsx(br,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(Tr,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof s.children=="string"?s.children:"",o=n?n.split("+").map(a=>a.trim()).filter(Boolean):[];return e.jsx("span",{"data-slot":"command-shortcut",className:T("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",r),...s,children:o.length>0?o.map((a,i)=>e.jsxs(de.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):s.children})}const th=()=>{const{isCommandPaletteOpen:r,setCommandPaletteOpen:s,setHelpDialogOpen:t,setSessionCreateDialogOpen:n,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,toggleSidebar:c}=Fe(),{createSession:d,setCurrentSession:u,getSessionsByDirectory:p,initializeNewOpenChamberSession:f}=ge(),{currentDirectory:m}=jt(),{agents:h}=St(),{themeMode:g,setThemeMode:x}=jr(),y=()=>{s(!1)},b=async()=>{const $=await d();$&&f($.id,h),y()},k=$=>{u($),y()},j=$=>{x($),y()},v=()=>{t(!0),y()},S=()=>{n(!0),y()},{isMobile:w}=At(),D=()=>{if(w){const{isSessionSwitcherOpen:$}=Fe.getState();i(!$)}else c();y()},A=()=>{o("git"),y()},N=()=>{o("terminal"),y()},M=()=>{a(!0),y()},C=()=>{Qm(),y()},E=p(m??""),F=l.useMemo(()=>E.slice(0,5),[E]);return e.jsxs(eh,{open:r,onOpenChange:s,children:[e.jsx(cc,{placeholder:"Type a command or search..."}),e.jsxs(dc,{children:[e.jsx(uc,{children:"No results found."}),e.jsxs(Lr,{heading:"Actions",children:[e.jsxs(_t,{onSelect:D,children:[e.jsx(_n,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsx(Ys,{children:"Ctrl + L"})]}),e.jsxs(_t,{onSelect:b,children:[e.jsx(ls,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Ys,{children:"Ctrl + N"})]}),e.jsxs(_t,{onSelect:S,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Ys,{children:"Shift + Ctrl + N"})]}),e.jsxs(_t,{onSelect:v,children:[e.jsx(Or,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsx(Ys,{children:"Ctrl + H"})]}),e.jsxs(_t,{onSelect:A,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsx(Ys,{children:"Ctrl + G"})]}),e.jsxs(_t,{onSelect:N,children:[e.jsx(Ws,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsx(Ys,{children:"Ctrl + T"})]}),e.jsxs(_t,{onSelect:M,children:[e.jsx(pr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsx(Ys,{children:"Ctrl + ,"})]}),e.jsxs(_t,{onSelect:C,children:[e.jsx(As,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Fo,{}),e.jsxs(Lr,{heading:"Theme",children:[e.jsxs(_t,{onSelect:()=>j("light"),children:[e.jsx(Ld,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),g==="light"&&e.jsx(It,{className:"ml-auto h-4 w-4"})]}),e.jsxs(_t,{onSelect:()=>j("dark"),children:[e.jsx(_d,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),g==="dark"&&e.jsx(It,{className:"ml-auto h-4 w-4"})]}),e.jsxs(_t,{onSelect:()=>j("system"),children:[e.jsx(gl,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),g==="system"&&e.jsx(It,{className:"ml-auto h-4 w-4"})]})]}),F.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Fo,{}),e.jsx(Lr,{heading:"Recent Sessions",children:F.map($=>e.jsxs(_t,{onSelect:()=>k($.id),children:[e.jsx(Uo,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:$.title||"Untitled Session"})]},$.id))})]})]})]})},sh=(r,s)=>{const t=r.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(zn,{className:"h-3.5 w-3.5"},`ctrl-${s}`):t==="shift"||t==="⇧"?e.jsx(Od,{className:"h-3.5 w-3.5"},`shift-${s}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(br,{className:"h-3.5 w-3.5"},`cmd-${s}`):e.jsx("span",{className:"text-xs font-medium",children:r.trim()},`key-${s}`)},rh=r=>{const s=r.split("+").map(t=>t.trim()).filter(Boolean);return s.length===0?r.trim():s.map((t,n)=>e.jsxs(l.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),sh(t,n)]},`${t}-${n}`))},nh=()=>{const{isHelpDialogOpen:r,setHelpDialogOpen:s}=Fe(),t=[{category:"Navigation & Commands",items:[{keys:["Ctrl + X"],description:"Open Command Palette",icon:br},{keys:["Ctrl + H"],description:"Show Keyboard Shortcuts (this dialog)",icon:Or},{keys:["Ctrl + L"],description:"Toggle Session Sidebar",icon:_n}]},{category:"Session Management",items:[{keys:["Ctrl + N"],description:"Create New Session",icon:ls},{keys:["Shift + Ctrl + N"],description:"Open Session Creator (worktree support)",icon:zt},{keys:["Ctrl + I"],description:"Focus Chat Input",icon:xl},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:hr}]},{category:"Interface",items:[{keys:["⌘ + /","Ctrl + /"],description:"Cycle Theme (Light → Dark → System)",icon:Bd},{keys:["Ctrl + G"],description:"Open Git Panel",icon:zt},{keys:["Ctrl + T"],description:"Open Terminal",icon:Ws},{keys:["Ctrl + ,"],description:"Open Settings",icon:pr}]}];return e.jsx(Ts,{open:r,onOpenChange:s,children:e.jsxs(Is,{className:"max-w-2xl",children:[e.jsxs(Fs,{children:[e.jsxs(Ps,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(nr,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsx("div",{className:"space-y-4 mt-3",children:t.map(n=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:n.category}),e.jsx("div",{className:"space-y-1",children:n.items.map((o,a)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[o.icon&&e.jsx(o.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:o.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(o.keys)?o.keys:o.keys.split(" / ")).map((i,c)=>e.jsxs(l.Fragment,{children:[c>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:rh(i)})]},`${i}-${c}`))})]},a))})]},n.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Or,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsx("li",{children:"• Use Command Palette (Ctrl + X) to quickly access all actions"}),e.jsx("li",{children:"• The 5 most recent sessions appear in the Command Palette"}),e.jsx("li",{children:"• Theme cycling remembers your preference across sessions"})]})]})]})})]})})},ao=new Set,io=new Set,lo=new Set,cr={onDeleteRequest(r){return ao.add(r),()=>{ao.delete(r)}},requestDelete(r){r.sessions.length&&ao.forEach(s=>s(r))},onCreateRequest(r){return io.add(r),()=>{io.delete(r)}},requestCreate(r){const s=r??{};io.forEach(t=>t(s))},onDirectoryRequest(r){return lo.add(r),()=>{lo.delete(r)}},requestDirectoryDialog(){lo.forEach(r=>r())}},oh=".openchamber",ji="oc.sessions.groupCollapse",Si="oc.sessions.expandedParents",ki=r=>{const s=new Date(r),t=new Date,n=(i,c)=>i.getFullYear()===c.getFullYear()&&i.getMonth()===c.getMonth()&&i.getDate()===c.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),n(s,t)?"Today":n(s,o)?"Yesterday":s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},vs=r=>{if(!r)return null;const s=r.replace(/\\/g,"/").replace(/\/+$/,"");return s.length===0?"/":s},ah=(r,s)=>{const t=vs(r),n=Array.from(s.values())[0];if(n?.projectDirectory)return vs(n.projectDirectory);if(!t)return null;const o=`/${oh}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},Po=({mobileVariant:r=!1,onSessionSelected:s,allowReselect:t=!1,hideDirectoryControls:n=!1})=>{const[o,a]=l.useState(null),[i,c]=l.useState(""),[d,u]=l.useState(null),p=l.useRef(null),[f,m]=l.useState(new Set),[h,g]=l.useState(()=>new Map),x=l.useRef(new Set),y=l.useMemo(()=>Qt(),[]),[b,k]=l.useState(!1),[j,v]=l.useState(new Set),[S,w]=l.useState(null),[D,A]=l.useState(new Set),[N,M]=l.useState(null),C=jt(P=>P.currentDirectory),E=jt(P=>P.homeDirectory),F=jt(P=>P.setDirectory),$=St(P=>P.agents),R=ge(P=>P.getSessionsByDirectory),Y=ge(P=>P.currentSessionId),Z=ge(P=>P.setCurrentSession),z=ge(P=>P.updateSessionTitle),G=ge(P=>P.shareSession),W=ge(P=>P.unshareSession),ce=ge(P=>P.sessionMemoryState),Ne=ge(P=>P.sessionActivityPhase),Me=ge(P=>P.worktreeMetadata),Le=ge(P=>P.availableWorktrees),ye=ge(P=>P.createSession),ie=ge(P=>P.initializeNewOpenChamberSession),je=ge(P=>P.setSessionDirectory),[Ce,We]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const P=y.getItem(ji);if(P){const re=JSON.parse(P);Array.isArray(re)&&v(new Set(re.filter(pe=>typeof pe=="string")))}const se=y.getItem(Si);if(se){const re=JSON.parse(se);Array.isArray(re)&&m(new Set(re.filter(pe=>typeof pe=="string")))}}catch{}},[y]),l.useEffect(()=>{typeof window>"u"||We(typeof window.opencodeDesktop<"u")},[]);const oe=R(C),B=l.useMemo(()=>[...oe].sort((P,se)=>(se.time?.created||0)-(P.time?.created||0)),[oe]);l.useEffect(()=>{if(!C){w(null);return}let P=!1;return sa(C).then(se=>{P||w(se)}).catch(()=>{P||w(null)}),()=>{P=!0}},[C]);const J=l.useMemo(()=>new Map(B.map(P=>[P.id,P])),[B]),O=l.useMemo(()=>{const P=new Map;return B.forEach(se=>{const re=se.parentID;re&&P.set(se.id,re)}),P},[B]),X=l.useMemo(()=>{const P=new Map;return B.forEach(se=>{const re=se.parentID;if(!re)return;const pe=P.get(re)??[];pe.push(se),P.set(re,pe)}),P.forEach(se=>se.sort((re,pe)=>(pe.time?.created||0)-(re.time?.created||0))),P},[B]);l.useEffect(()=>{Y&&m(P=>{const se=new Set(P);let re=O.get(Y)||null,pe=!1;for(;re;)se.has(re)||(se.add(re),pe=!0),re=O.get(re)||null;return pe?se:P})},[Y,O]);const _=l.useMemo(()=>ah(C,Me),[C,Me]);l.useEffect(()=>{const P=new Set;B.forEach(se=>{const re=vs(se.directory??null);re&&P.add(re)}),_&&P.add(_),P.forEach(se=>{const re=h.get(se);re&&re!=="unknown"||x.current.has(se)||(x.current.add(se),Ae.listLocalDirectory(se).then(()=>{g(pe=>{const Te=new Map(pe);return Te.get(se)==="exists"?pe:(Te.set(se,"exists"),Te)})}).catch(()=>{g(pe=>{const Te=new Map(pe);return Te.get(se)==="missing"?pe:(Te.set(se,"missing"),Te)})}).finally(()=>{x.current.delete(se)}))})},[B,_,h]),l.useEffect(()=>()=>{p.current&&clearTimeout(p.current)},[]);const te=l.useMemo(()=>qn(C,E),[C,E]),K=l.useMemo(()=>Vt(C,E),[C,E]),ae=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."})]}),be=l.useCallback((P,se)=>{if(!se){if(!t&&P===Y){s?.(P);return}Z(P),s?.(P)}},[t,Y,s,Z]),fe=l.useCallback(async()=>{o&&i.trim()&&(await z(o,i.trim()),a(null),c(""))},[o,i,z]),H=l.useCallback(()=>{a(null),c("")},[]),V=l.useCallback(async P=>{const se=await G(P.id);se&&se.share?.url?xe.success("Session shared",{description:"You can copy the link from the menu."}):xe.error("Unable to share session")},[G]),L=l.useCallback((P,se)=>{navigator.clipboard.writeText(P).then(()=>{u(se),p.current&&clearTimeout(p.current),p.current=window.setTimeout(()=>{u(null),p.current=null},2e3)}).catch(()=>{xe.error("Failed to copy URL")})},[]),Q=l.useCallback(async P=>{await W(P)?xe.success("Session unshared"):xe.error("Unable to unshare session")},[W]),ke=l.useCallback(P=>{const se=[],re=pe=>{(X.get(pe)??[]).forEach(Je=>{se.push(Je),re(Je.id)})};return re(P),se},[X]),De=ge(P=>P.deleteSession),Oe=ge(P=>P.deleteSessions),ct=l.useCallback(async P=>{const se=ke(P.id);if(se.length===0)await De(P.id)?xe.success("Session deleted"):xe.error("Failed to delete session");else{const re=[P.id,...se.map(Je=>Je.id)],{deletedIds:pe,failedIds:Te}=await Oe(re);pe.length>0&&xe.success(`Deleted ${pe.length} session${pe.length===1?"":"s"}`),Te.length>0&&xe.error(`Failed to delete ${Te.length} session${Te.length===1?"":"s"}`)}},[ke,De,Oe]),Ue=l.useCallback(async P=>{if(!P){xe.error("No directory available for session creation");return}if(!b)try{k(!0);const se=await ye(void 0,P);if(!se){xe.error("Failed to create session");return}ie(se.id,$),je(se.id,P)}catch(se){const re=se instanceof Error?se.message:"Failed to create session";xe.error(re)}finally{k(!1)}},[ye,ie,je,$,b]),Ge=l.useCallback(()=>{cr.requestCreate({worktreeMode:"create"})},[]),Xe=l.useCallback(()=>{Ce&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(P=>{P.success&&P.path?F(P.path,{showOverlay:!0}):P.error&&P.error!=="Directory selection cancelled"&&xe.error("Failed to select directory",{description:P.error})}).catch(P=>{console.error("Desktop: Error selecting directory:",P),xe.error("Failed to select directory")}):cr.requestDirectoryDialog()},[Ce,F]),Ze=l.useCallback(P=>{m(se=>{const re=new Set(se);re.has(P)?re.delete(P):re.add(P);try{y.setItem(Si,JSON.stringify(Array.from(re)))}catch{}return re})},[y]),Be=l.useCallback(P=>{const se=X.get(P.id)??[];return{session:P,children:se.map(re=>Be(re))}},[X]),ze=l.useMemo(()=>{const P=new Map,se=vs(_??null),re=new Map,pe=new Set;Le.forEach(Re=>{if(Re.path){const qe=vs(Re.path)??Re.path;pe.add(qe),re.set(qe,Re)}});const Te=Re=>{const qe=vs(Re.directory??null),ut=Me.get(Re.id),pt=((ut?.path?pe.has(vs(ut.path)??ut.path):!1)?ut:null)??(qe?re.get(qe)??null:null),kt=!pt&&(qe&&se?qe===se:!qe&&!!se),bt=kt?"main":pt?.path??qe??Re.id,ht=pt?.path??qe??se??null;if(!P.has(bt)){const Et=kt?"Main workspace":pt?.label||pt?.branch||qn(ht||"",E)||"Worktree",I=pt?.relativePath?Vt(pt.relativePath,E):ht?Vt(ht,E):null;P.set(bt,{id:bt,label:Et,description:I,isMain:kt,worktree:pt,directory:ht,sessions:[]})}return P.get(bt)};return B.filter(Re=>{const qe=Re.parentID;return qe?!J.has(qe):!0}).forEach(Re=>{const qe=Te(Re),ut=Be(Re);qe.sessions.push(ut)}),P.has("main")||P.set("main",{id:"main",label:"Main workspace",description:se?Vt(se,E):null,isMain:!0,worktree:null,directory:se,sessions:[]}),re.forEach((Re,qe)=>{const ut=Re.path;P.has(ut)||P.set(ut,{id:ut,label:Re.label||Re.branch||qn(qe,E)||"Worktree",description:Re.relativePath?Vt(Re.relativePath,E):Vt(qe,E),isMain:!1,worktree:Re,directory:qe,sessions:[]})}),P.forEach(Re=>{Re.sessions.sort((qe,ut)=>(ut.session.time?.created||0)-(qe.session.time?.created||0))}),Array.from(P.values()).sort((Re,qe)=>Re.isMain!==qe.isMain?Re.isMain?-1:1:(Re.label||"").localeCompare(qe.label||""))},[B,Me,Le,_,E,Be,J]),dt=l.useCallback(P=>{v(se=>{const re=new Set(se);re.has(P)?re.delete(P):re.add(P);try{y.setItem(ji,JSON.stringify(Array.from(re)))}catch{}return re})},[y]),mt=l.useCallback(P=>{A(se=>{const re=new Set(se);return re.has(P)?re.delete(P):re.add(P),re})},[]),Se=l.useCallback((P,se=0,re)=>{const pe=P.session,Te=vs(pe.directory??null)??vs(re??null),Re=(Te?h.get(Te):null)==="missing",qe=ce.get(pe.id),ut=Y===pe.id,Dt=pe.title||"Untitled Session",pt=P.children.length>0,kt=f.has(pe.id),bt=pe.summary?.additions,ht=pe.summary?.deletions,Et=typeof bt=="number"||typeof ht=="number";if(o===pe.id)return e.jsxs("div",{className:"flex flex-col rounded-lg border border-transparent px-2 py-2",children:[e.jsxs("form",{className:"flex w-full items-center justify-between gap-2",onSubmit:ve=>{ve.preventDefault(),fe()},children:[e.jsx(Tt,{value:i,onChange:ve=>c(ve.target.value),className:"h-7 flex-1 border-none bg-transparent px-0 py-0 typography-micro focus-visible:ring-0 focus-visible:ring-offset-0",autoFocus:!0,placeholder:"Rename session",onKeyDown:ve=>{ve.key==="Escape"&&H()}}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ee,{size:"icon",variant:"ghost",className:"h-6 w-6 p-0",type:"submit",children:e.jsx(It,{className:"h-4 w-4"})}),e.jsx(Ee,{size:"icon",variant:"ghost",className:"h-6 w-6 p-0",type:"button",onClick:H,children:e.jsx(hs,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1 typography-micro text-muted-foreground/70 overflow-hidden",children:[e.jsx("span",{className:"flex-shrink-0",children:ki(pe.time?.created||Date.now())}),pe.share&&e.jsx(Vn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"})]})]},pe.id);const I=Ne?.get(pe.id)??"idle",ne=I==="busy"||I==="cooldown",we=qe&&qe.isZombie?e.jsx(vo,{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",ut?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",Re?"opacity-75":"",se>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:Re,onClick:()=>be(pe.id,Re),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",ne&&"animate-pulse [animation-duration:1.8s]"),children:Dt})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[pt?e.jsx("span",{role:"button",tabIndex:0,onClick:ve=>{ve.stopPropagation(),Ze(pe.id)},onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),ve.stopPropagation(),Ze(pe.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":kt?"Collapse subsessions":"Expand subsessions",children:kt?e.jsx(vt,{className:"h-3 w-3"}):e.jsx(gs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:ki(pe.time?.created||Date.now())}),pe.share?e.jsx(Vn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Et&&((bt??0)!==0||(ht??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,bt??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,ht??0)]})]}):null,pt?e.jsxs("span",{className:"truncate",children:[P.children.length," ",P.children.length===1?"task":"tasks"]}):null,Re?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(vo,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[we,e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx("button",{type:"button",className:T("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity opacity-0 group-hover:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50"),"aria-label":"Session menu",onClick:ve=>ve.stopPropagation(),onKeyDown:ve=>ve.stopPropagation(),children:e.jsx(On,{className:r?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Xt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(yt,{onClick:()=>{a(pe.id),c(Dt)},className:"[&>svg]:mr-1",children:[e.jsx(Ns,{className:"mr-1 h-4 w-4"}),"Rename"]}),pe.share?e.jsxs(e.Fragment,{children:[e.jsx(yt,{onClick:()=>{pe.share?.url&&L(pe.share.url,pe.id)},className:"[&>svg]:mr-1",children:d===pe.id?e.jsxs(e.Fragment,{children:[e.jsx(It,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(yt,{onClick:()=>Q(pe.id),className:"[&>svg]:mr-1",children:[e.jsx($d,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(yt,{onClick:()=>V(pe),className:"[&>svg]:mr-1",children:[e.jsx(Vn,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(yt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>ct(pe),children:[e.jsx(Us,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),pt&&kt?P.children.map(ve=>Se(ve,se+1,Te??re)):null]},pe.id)},[h,ce,Ne,Y,f,o,i,fe,H,Ze,be,V,L,Q,ct,d,r]);return e.jsxs("div",{className:T("flex h-full flex-col text-foreground overflow-x-hidden",r?"":Ce?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-14 select-none px-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center gap-0",children:[e.jsxs("button",{type:"button",onClick:Xe,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",!Ce&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:K||"/",children:[e.jsx("span",{className:T("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!Ce&&"bg-sidebar/60"),children:e.jsx(os,{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:te||"/"})})]}),S?e.jsx("button",{type:"button",onClick:Ge,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",!Ce&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",children:e.jsx(zd,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}):null]})}),e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:T("space-y-1 pb-1 pl-2.5 pr-1",""),children:ze.length===0?ae:n&&ze.length===1&&ze[0].isMain?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:ze[0].sessions.length===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."}):ze[0].sessions.map(P=>Se(P,0,ze[0].directory))}):ze.map(P=>e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>dt(P.id),className:T("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b",!Ce&&"bg-sidebar"),style:{borderColor:N===P.id?"var(--color-border)":j.has(P.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>M(P.id),onMouseLeave:()=>M(null),"aria-label":j.has(P.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:P.label}),!n&&e.jsx("span",{role:"button",tabIndex:0,"aria-disabled":b,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",b&&"opacity-40 cursor-default"),"aria-label":"Create session in this group",onClick:se=>{b||(se.stopPropagation(),Ue(P.directory))},onKeyDown:se=>{b||(se.key==="Enter"||se.key===" ")&&(se.stopPropagation(),Ue(P.directory))},children:e.jsx(ls,{className:"h-4.5 w-4.5"})})]})}),j.has(P.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const se=D.has(P.id),re=7,pe=P.sessions.length,Te=se?P.sessions:P.sessions.slice(0,re),Je=pe-Te.length;return e.jsxs(e.Fragment,{children:[Te.map(Re=>Se(Re,0,P.directory)),pe===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,Je>0&&!se?e.jsxs("button",{type:"button",onClick:()=>mt(P.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 ",Je," more ",Je===1?"session":"sessions"]}):null,se&&pe>re?e.jsx("button",{type:"button",onClick:()=>mt(P.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]})})()})]},P.id))})]})},ih=dl("inline-flex items-center justify-center gap-2 rounded-xl typography-ui-label font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",{variants:{variant:{default:"bg-transparent",outline:"border border-input bg-transparent shadow-none hover:bg-accent hover:text-accent-foreground"},size:{default:"h-9 px-2 min-w-9",sm:"h-8 px-1.5 min-w-8",lg:"h-10 px-2.5 min-w-10"}},defaultVariants:{variant:"default",size:"default"}});function lh({className:r,variant:s,size:t,...n}){return e.jsx(Hd,{"data-slot":"toggle",className:T(ih({variant:s,size:t,className:r})),...n})}const mc=()=>{const[r,s]=de.useState(!1);de.useEffect(()=>{s(Zt())},[]);const t=de.useCallback(async a=>r?await rm(a):{success:!0,path:a},[r]),n=de.useCallback(async a=>r?await nm(a):{success:!0},[r]),o=de.useCallback(async a=>r?await om(a):{success:!0},[r]);return{isDesktop:r,requestAccess:t,startAccessing:n,stopAccessing:o}},ch=({currentPath:r,onSelectPath:s,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:u})=>{const p=l.useMemo(()=>Zt(),[]),[f,m]=l.useState([]),[h,g]=l.useState(new Set),[x,y]=l.useState(!0),[b,k]=l.useState(!1),[j,v]=l.useState(""),[S,w]=l.useState(new Set),[D,A]=l.useState(null),[N,M]=l.useState(""),C=l.useRef(null),{requestAccess:E,startAccessing:F,isDesktop:$}=mc(),R=l.useRef(c),Y=l.useCallback(_=>{if(!_)return _;if(_==="/"||_.length===0)return"/";let te=_;for(;te.length>1&&te.endsWith("/");)te=te.slice(0,-1);return te.length===0?"/":te},[]),Z=l.useMemo(()=>{if(!j)return null;const _=j.replace(/\\/g,"/");return Y(_)},[j,Y]),z=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const _=d.replace(/\\/g,"/"),te=Y(_);if(te&&te!=="/")return te}return Z&&Z!=="/"?Z:null},[d,Z,Y]),G=l.useMemo(()=>typeof u=="boolean"?!!(u&&z):!!z,[u,z]);l.useEffect(()=>{G||(y(!0),m([]))},[G]);const W=l.useCallback(_=>{if(!_||!G||!z)return!1;const te=_.replace(/\\/g,"/"),K=Y(te)??te;if(K===z)return!0;const ae=`${z}/`;return K.startsWith(ae)},[G,z,Y]),ce=async _=>{if(G){if(a==="deferred"){s(_);return}if($){const te=await E(_);te.success&&te.path?(await F(te.path),s(te.path)):(console.error("Failed to get directory access:",te.error),s(_))}else s(_)}};l.useEffect(()=>{let _=!1;const te=be=>{if(!be)return!1;const fe=Y(be.replace(/\\/g,"/"));return!fe||fe==="/"?!1:(v(typeof fe=="string"?fe:be.replace(/\\/g,"/")),!0)};return(d?te(d):!1)||(async()=>{try{const be=await Ae.getFilesystemHome();if(!_&&te(be))return}catch(be){console.warn("Failed to resolve filesystem home directory:",be)}try{const be=await Ae.getSystemInfo();if(!_&&te(be?.homeDirectory))return}catch(be){console.warn("Failed to resolve home directory from system info:",be)}})(),()=>{_=!0}},[d,Y]),l.useEffect(()=>{let _=!1;const te=fe=>{if(_)return;const H=fe.filter(V=>typeof V=="string"&&V.length>0).map(V=>{const L=V.replace(/\\/g,"/");return Y(L)??L});w(new Set(H))},K=()=>{try{const fe=localStorage.getItem("pinnedDirectories");if(!fe)return;const H=JSON.parse(fe);Array.isArray(H)&&te(H)}catch(fe){console.warn("Failed to load pinned directories from local storage:",fe)}},ae=async()=>{try{let fe=[];if(p){const H=await Sl();fe=Array.isArray(H?.pinnedDirectories)?H.pinnedDirectories:[]}else{const H=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(H.ok){const V=await H.json();fe=Array.isArray(V?.pinnedDirectories)?V.pinnedDirectories:[]}}if(_)return;te(fe)}catch(fe){console.warn("Failed to load pinned directories:",fe)}};K();const be=fe=>{const H=fe.detail;H&&Array.isArray(H.pinnedDirectories)&&te(H.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",be),ae(),()=>{_=!0,window.removeEventListener("openchamber:settings-synced",be)}},[p,Y]);const Ne=l.useRef(!0);l.useEffect(()=>{if(Ne.current){Ne.current=!1;return}const _={pinnedDirectories:Array.from(S)};ks(_)},[S]),l.useEffect(()=>{z&&w(_=>{const te=Array.from(_).map(K=>Y(K.replace(/\\/g,"/"))??K).filter(K=>W(K));return new Set(te)})},[z,W,Y]),l.useEffect(()=>{R.current!==c&&(R.current=c,g(new Set))},[c]);const Me=_=>{w(te=>{if(!W(_))return te;const K=Y(_.replace(/\\/g,"/"))??_.replace(/\\/g,"/"),ae=new Set(te);return ae.has(K)?ae.delete(K):ae.add(K),ae})},Le=l.useMemo(()=>Array.from(S).map(_=>Y(_.replace(/\\/g,"/"))??_).filter(_=>W(_)).map(_=>({path:_,name:_.split("/").pop()||_})).sort((_,te)=>_.name.localeCompare(te.name)),[S,W,Y]),ye=l.useCallback(async _=>{const te=H=>c||!H.startsWith("."),K=z;if(!G||!K)return[];const ae=_&&_.length>0?_:K,be=ae?ae.replace(/\\/g,"/"):null,fe=be?Y(be)??be:null;if(fe){const H=`${K}/`;if(!(fe===K||fe.startsWith(H)))return[]}try{return(await Ae.listLocalDirectory(_)).filter(V=>{if(!V.isDirectory||!te(V.name))return!1;const L=V.path.replace(/\\/g,"/"),Q=Y(L)??L,ke=Q===K?K:`${K}/`;return Q===K||Q.startsWith(ke)}).map(V=>({name:V.name,path:V.path.replace(/\\/g,"/"),isDirectory:!0})).sort((V,L)=>V.name.localeCompare(L.name))}catch{try{const V=await Ae.getApiClient().file.list({query:{path:".",directory:_}});return V.data?V.data.filter(L=>{if(L.type!=="directory"||!L.name||!te(L.name))return!1;const Q=String(L.absolute||L.path||L.name).replace(/\\/g,"/"),ke=Y(Q)??Q,De=ke===K?K:`${K}/`;return ke===K||ke.startsWith(De)}).map(L=>({name:L.name||"",path:String(L.absolute||L.path||L.name).replace(/\\/g,"/"),isDirectory:!0})).filter(L=>L.name!=="").sort((L,Q)=>L.name.localeCompare(Q.name)):[]}catch{return[]}}},[c,z,Y,G]),ie=l.useCallback(async()=>{if(!G||!z){y(!0),m([]);return}y(!0);try{const _=await ye(z);m(_)}catch{}finally{y(!1)}},[G,z,ye]);l.useEffect(()=>{G&&(n==="inline"||b)&&ie()},[n,b,G,ie]);const je=async _=>{if(!G)return;const te=h.has(_.path),K=new Set(h);if(te){K.delete(_.path),g(K);return}K.add(_.path),g(K);const ae=await ye(_.path),be=fe=>fe.map(H=>H.path===_.path?{...H,children:ae}:H.children?{...H,children:be(H.children)}:H);m(fe=>be(fe))};l.useEffect(()=>{D&&C.current&&(C.current.focus(),C.current.select())},[D]);const Ce=(_,te=[])=>{const K="new_directory",ae=te.map(V=>V.name);if(!ae.includes(K))return K;let be=1;const fe=new RegExp(`^${K}(\\d+)$`);for(const V of ae){const L=V.match(fe);if(L){const Q=parseInt(L[1],10);Q>be&&(be=Q)}}let H=2;for(;ae.includes(`${K}${H}`);)H++;return`${K}${Math.max(H,be+1)}`},We=async _=>{if(G){if(h.has(_.path)){const te=Ce(_.path,_.children);M(te)}else{const te=new Set(h);if(te.add(_.path),g(te),_.children){const K=Ce(_.path,_.children);M(K)}else{const K=await ye(_.path),ae=fe=>fe.map(H=>H.path===_.path?{...H,children:K}:H.children?{...H,children:ae(H.children)}:H);m(fe=>ae(fe));const be=Ce(_.path,K);M(be)}}A(_.path)}},oe=async()=>{if(!D||!G)return;const _=N.trim()||"new_directory",te=`${D}/${_}`;try{await Ae.createDirectory(te);const K=await ye(D),ae=be=>be.map(fe=>fe.path===D?{...fe,children:K}:fe.children?{...fe,children:ae(fe.children)}:fe);m(be=>ae(be)),A(null),M("")}catch(K){console.error("Failed to create directory:",K)}},B=()=>{A(null),M("")},J=(_,te=0)=>{const K=h.has(_.path),ae=_.isDirectory,be=S.has(_.path),fe=r===_.path,H=n==="inline",V=e.jsxs(e.Fragment,{children:[ae&&e.jsx("button",{onClick:L=>{L.stopPropagation(),je(_)},className:"p-0.5 hover:bg-accent rounded",children:K?e.jsx(vt,{className:"h-3 w-3"}):e.jsx(gs,{className:"h-3 w-3"})}),!ae&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:L=>{L.stopPropagation(),ce(_.path),n==="dropdown"&&a==="immediate"&&k(!1)},onDoubleClick:L=>{L.stopPropagation(),i&&i(_.path)},className:T("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",H&&fe?"text-primary":"text-foreground"),children:[K?e.jsx(os,{className:T("h-3.5 w-3.5 text-muted-foreground",H&&fe&&"text-primary")}):e.jsx(os,{className:T("h-3.5 w-3.5 text-muted-foreground",H&&fe&&"text-primary")}),e.jsx("span",{className:T("typography-ui-label font-medium truncate",H&&fe?"text-primary":"text-foreground"),children:_.name})]}),e.jsx("button",{onClick:L=>{L.stopPropagation(),We(_)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Create new directory",children:e.jsx(ls,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:L=>{L.stopPropagation(),Me(_.path)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:be?"Unpin directory":"Pin directory",children:be?e.jsx(Gn,{className:"h-3 w-3 text-primary"}):e.jsx(Wd,{className:"h-3 w-3 text-muted-foreground"})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:T("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",fe?"text-primary":"text-foreground"),style:{paddingLeft:`${te*12+8}px`},children:V}),K&&e.jsxs(e.Fragment,{children:[D===_.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(te+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(os,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Tt,{ref:C,value:N,onChange:L=>M(L.target.value),onKeyDown:L=>{L.key==="Enter"?(L.preventDefault(),L.stopPropagation(),oe()):L.key==="Escape"&&(L.preventDefault(),L.stopPropagation(),B())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),oe()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(It,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),B()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(hs,{className:"h-3 w-3 text-muted-foreground"})})]}),_.children&&_.children.map(L=>J(L,te+1))]})]},_.path):e.jsxs("div",{children:[e.jsxs(yt,{className:T("flex items-center gap-1 cursor-pointer group",r===_.path&&"bg-accent"),style:{paddingLeft:`${te*12+8}px`},onSelect:L=>{L.preventDefault()},children:[ae&&e.jsx("button",{onClick:L=>{L.stopPropagation(),je(_)},className:"p-0.5 hover:bg-accent rounded",children:K?e.jsx(vt,{className:"h-3 w-3"}):e.jsx(gs,{className:"h-3 w-3"})}),!ae&&e.jsx("div",{className:"w-4"}),V]}),K&&e.jsxs("div",{children:[D===_.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(te+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(os,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Tt,{ref:C,value:N,onChange:L=>M(L.target.value),onKeyDown:L=>{L.key==="Enter"?(L.preventDefault(),L.stopPropagation(),oe()):L.key==="Escape"&&(L.preventDefault(),L.stopPropagation(),B())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),oe()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(It,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:L=>{L.preventDefault(),L.stopPropagation(),B()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(hs,{className:"h-3 w-3 text-muted-foreground"})})]}),_.children&&_.children.map(L=>J(L,te+1))]})]},_.path)},O=(_,te)=>{if(n==="inline"){const K=r===te;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:()=>ce(te),onDoubleClick:ae=>{ae.stopPropagation(),i&&i(te)},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",K?"text-primary":"text-foreground"),children:[e.jsx(os,{className:T("h-3.5 w-3.5 text-muted-foreground",K&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",K?"text-primary":"text-foreground"),children:_}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:Vt(te,j)})]})]}),e.jsx("button",{onClick:()=>Me(te),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Gn,{className:"h-3 w-3 text-primary"})})]},te)}return e.jsxs(yt,{onSelect:K=>{K.preventDefault(),ce(te),a==="immediate"&&k(!1)},className:T("flex items-start gap-2 cursor-pointer group py-2",r===te&&"bg-accent"),children:[e.jsx(os,{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.jsx("div",{className:"typography-meta text-muted-foreground",children:Vt(te,j)})]}),e.jsx("button",{onClick:K=>{K.stopPropagation(),K.preventDefault(),Me(te)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Gn,{className:"h-3 w-3 text-primary"})})]},te)},X=e.jsx(e.Fragment,{children:G?e.jsxs(e.Fragment,{children:[Le.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground",children:"Pinned"}),Le.map(({name:_,path:te})=>O(_,te)),n==="dropdown"&&e.jsx(Hr,{})]}),e.jsx("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground",children:"Browse"}),x?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):f.map(_=>J(_)),!x&&f.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:T("overflow-hidden rounded-xl border border-border/40 bg-sidebar/70",o),children:e.jsx(Ye,{outerClassName:"max-h-full",className:"w-full",children:X})}):e.jsxs(Kt,{open:b,onOpenChange:k,children:[e.jsx(Yt,{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(os,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:r,children:Vt(r,j)})]}),e.jsx(vt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Xt,{align:"start",className:"w-[350px]",children:e.jsx(Ye,{outerClassName:"h-full",className:"w-full",children:X})})]})},Ni="directoryTreeShowHidden",dh=({open:r,onOpenChange:s})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=jt(),[i,c]=l.useState(null),[d,u]=l.useState(!1),[p,f]=l.useState(!1),[m,h]=l.useState(()=>{if(typeof window>"u")return!1;try{const C=window.localStorage.getItem(Ni);if(C==="true")return!0;if(C==="false")return!1}catch{}return!1}),{isDesktop:g,requestAccess:x,startAccessing:y}=mc(),{isMobile:b}=At();l.useEffect(()=>{r&&(c(null),u(!1),f(!1))},[r]),l.useEffect(()=>{r&&!d&&!i&&n&&a&&(c(n),u(!0))},[r,d,i,n,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ni,m?"true":"false")}catch{}},[m]);const k=l.useMemo(()=>i?Vt(i,n):"Select a directory",[i,n]),j=l.useCallback(()=>{s(!1)},[s]),v=l.useCallback(async C=>{if(!(!C||p)){if(C===t){j();return}f(!0);try{let E=C;if(g){const F=await x(C);if(!F.success){xe.error("Unable to access directory",{description:F.error||"Desktop denied directory access."});return}E=F.path??C;const $=await y(E);if(!$.success){xe.error("Failed to open directory",{description:$.error||"Desktop could not grant file access."});return}}o(E),j()}catch(E){xe.error("Failed to select directory",{description:E instanceof Error?E.message:"Unknown error occurred."})}finally{f(!1)}}},[t,j,g,x,o,y,p]),S=l.useCallback(async()=>{i&&await v(i)},[v,i]),w=l.useCallback(C=>{c(C),u(!0)},[]),D=l.useCallback(async C=>{c(C),u(!0),await v(C)},[v]),A=e.jsxs(Fs,{className:"flex-shrink-0 px-4 pb-3 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-4 sm:pt-[calc(var(--oc-safe-area-top,0px)+0px)]",children:[e.jsx(Ps,{children:"Select project directory"}),e.jsx(nr,{className:"hidden sm:block",children:"Choose the working directory used for sessions, commands, and OpenCode operations."})]}),N=e.jsxs(Ye,{outerClassName:"flex-1 min-h-0 overflow-hidden",className:"directory-dialog-body px-2.5 pb-2.5 sm:px-0 sm:pb-0",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 px-3 py-2 sm:px-4 sm:py-3",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Currently selected"}),e.jsx("div",{className:"typography-ui-label font-medium text-foreground truncate",title:Vt(t,n),children:Vt(t,n)})]}),e.jsxs("div",{className:"directory-grid mt-2 grid gap-2 grid-cols-1 sm:mt-4 sm:gap-4 sm:grid-cols-[minmax(260px,340px)_minmax(0,1fr)]",children:[e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/70 p-1.5 sm:p-2 sm:h-auto",children:e.jsx(ch,{variant:"inline",currentPath:i??t,onSelectPath:w,onDoubleClickPath:D,className:"min-h-[280px] h-[55vh] sm:h-[440px]",selectionBehavior:"deferred",showHidden:m,rootDirectory:a?n:null,isRootReady:a})}),e.jsxs("div",{className:"flex flex-col gap-2.5 sm:gap-3",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 px-3 py-2 sm:px-4 sm:py-3",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Selected directory"}),e.jsx("div",{className:"typography-ui-label font-medium text-foreground truncate",title:i?k:void 0,children:k})]}),e.jsxs(lh,{pressed:m,onPressedChange:C=>h(!!C),variant:"outline",className:"w-full justify-start gap-2 rounded-xl border-border/40 bg-sidebar/60 px-3 py-2 text-foreground min-w-0 h-auto sm:px-4 sm:py-3",children:[m?e.jsx(Xo,{className:"h-4 w-4"}):e.jsx(Jo,{className:"h-4 w-4"}),"Show hidden directories"]}),e.jsx("div",{className:"hidden rounded-xl border border-dashed border-border/40 bg-sidebar/40 px-3 py-2 sm:block sm:px-4 sm:py-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Use the tree to browse, pin frequently used locations, or create a new directory. Select a folder, then confirm to update the working directory for OpenChamber."})})]})]})]}),M=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ee,{variant:"ghost",onClick:j,disabled:p,className:"w-full sm:w-auto",children:"Cancel"}),e.jsx(Ee,{onClick:S,disabled:p||!d||!i,className:"w-full sm:w-auto",children:p?"Applying...":"Use Selected Directory"})]});return b?e.jsx(qt,{open:r,onClose:()=>s(!1),title:"Select project directory",className:"max-w-full",footer:e.jsx("div",{className:"flex flex-col gap-2",children:M()}),children:N}):e.jsx(Ts,{open:r,onOpenChange:s,children:e.jsxs(Is,{className:T("flex w-full max-w-[min(640px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-4xl sm:p-6"),children:[A,N,e.jsx(Wr,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-col gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:flex-row sm:justify-end sm:gap-2 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0",children:M()})]})})},Pn=".openchamber",sn=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,uh=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),fc=r=>r.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),pc=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},rn=(r,s)=>{const t=pc(r),n=fc(s),o=!t||t==="/"?`/${Pn}`:`${t}/${Pn}`;return n?`${o}/${n}`:o},mh=()=>{const[r,s]=l.useState(!1),[t,n]=l.useState(!1),[o,a]=l.useState(""),[i,c]=l.useState([]),[d,u]=l.useState(!1),[p,f]=l.useState(null),[m,h]=l.useState(!1),[g,x]=l.useState(null),[y,b]=l.useState(!1),k=l.useRef(new Set),[j,v]=l.useState(null),[S,w]=l.useState([]),[D,A]=l.useState(!1),[N,M]=l.useState(!1),{sessions:C,createSession:E,deleteSession:F,deleteSessions:$,loadSessions:R,initializeNewOpenChamberSession:Y,setWorktreeMetadata:Z,setSessionDirectory:z,getWorktreeMetadata:G,isLoading:W}=ge(),{currentDirectory:ce,homeDirectory:Ne,hasPersistedDirectory:Me,isHomeReady:Le}=jt(),{agents:ye}=St(),{isSessionCreateDialogOpen:ie,setSessionCreateDialogOpen:je}=Fe(),{isMobile:Ce,isTablet:We,hasTouchInput:oe}=At(),B=Ce||We||oe,J=l.useMemo(()=>pc(ce),[ce]),O=l.useMemo(()=>uh(o),[o]),X=l.useMemo(()=>fc(O),[O]),_=l.useMemo(()=>!J||!X?"":rn(J,X),[J,X]),te=g===!0,K=l.useMemo(()=>(j?.worktree?.status?.isDirty??!1)||S.some(Se=>Se.metadata.status?.isDirty),[j?.worktree?.status?.isDirty,S]),ae=l.useMemo(()=>{const Se=j?.worktree;return Se&&typeof Se.branch=="string"&&Se.branch.trim().length>0?!0:S.length>0&&S.every(({metadata:P})=>typeof P.branch=="string"&&P.branch.trim().length>0)},[j?.worktree,S]),be=j?.mode==="worktree",fe=be,H=N||!be||!ae;l.useEffect(()=>{J&&(k.current.has(J)||Dm(J).then(()=>k.current.add(J)).catch(Se=>{console.warn("Failed to ensure .openchamber directory is ignored:",Se),k.current.delete(J)}))},[J]),l.useEffect(()=>{R()},[R,ce]),l.useEffect(()=>{!t&&Le&&!Me&&(s(!0),n(!0))},[Me,t,Le]),l.useEffect(()=>{if(!ie){a(""),c([]),f(null),u(!1),h(!1),x(null),b(!1);return}if(!J){c([]),x(null),h(!1);return}let Se=!1;return u(!0),h(!0),f(null),(async()=>{try{const P=await sa(J);if(Se)return;if(x(P),!P)c([]),f(null);else{const se=await Cn(J);if(Se)return;const re=se.map(Re=>Mn(J,Re)),Te=`${rn(J,"")}/`,Je=re.filter(Re=>Re.path.startsWith(Te));c(Je)}}catch(P){if(Se)return;const se=P instanceof Error?P.message:"Failed to load worktrees";f(se)}finally{Se||(u(!1),h(!1))}})(),()=>{Se=!0}},[ie,J]);const V=l.useCallback(Se=>{v({sessions:Se.sessions,dateLabel:Se.dateLabel,mode:Se.mode??"session",worktree:Se.worktree??null})},[]),L=l.useCallback(()=>{v(null),w([]),A(!1),M(!1)},[]);l.useEffect(()=>cr.onDeleteRequest(Se=>{V(Se)}),[V]),l.useEffect(()=>cr.onDirectoryRequest(()=>{s(!0)}),[]),l.useEffect(()=>cr.onCreateRequest(()=>{a(""),je(!0)}),[je]),l.useEffect(()=>{if(!j){w([]),A(!1);return}const Se=j.sessions.map(se=>{const re=G(se.id);return re?{session:se,metadata:re}:null}).filter(se=>!!se);if(w(Se),A(!1),Se.length===0)return;let P=!1;return(async()=>{const se=await Promise.all(Se.map(async({metadata:re})=>{if(re.status&&typeof re.status.isDirty=="boolean")return re.status;try{return await fn(re.path)}catch{return re.status}})).catch(re=>(console.warn("Failed to inspect worktree status before deletion:",re),Se.map(({metadata:pe})=>pe.status)));P||!Array.isArray(se)||w(re=>re.map((pe,Te)=>({session:pe.session,metadata:{...pe.metadata,status:se[Te]??pe.metadata.status}})))})(),()=>{P=!0}},[j,G]),l.useEffect(()=>{ae||A(!1)},[ae]);const Q=l.useCallback(Se=>{a(Se),f(null)},[]),ke=l.useCallback(async()=>{if(!(!J||!g))try{const P=(await Cn(J)).map(Te=>Mn(J,Te)),re=`${rn(J,"")}/`,pe=P.filter(Te=>Te.path.startsWith(re));c(pe)}catch{}},[J,g]),De=l.useRef(null);l.useEffect(()=>{De.current?.mode==="worktree"&&!j&&ke(),De.current=j},[j,ke]);const Oe=l.useCallback(()=>{if(!J){const re="Select a project directory first.";return f(re),xe.error(re),!1}const Se=O,P=X;if(!Se){const re="Provide a branch name for the new worktree.";return f(re),xe.error(re),!1}if(!P){const re="Provide a branch name that can be used as a folder.";return f(re),xe.error(re),!1}const se=rn(J,P);if(i.some(re=>re.path===se)){const re="A worktree with this folder already exists.";return f(re),xe.error(re),!1}return f(null),!0},[J,O,X,i]),ct=async()=>{if(y||W||!Oe())return;b(!0),f(null);let Se=null;try{const P=O,re=await Om({projectDirectory:J,worktreeSlug:X,branch:P,createBranch:!0});Se=re;let pe=await fn(re.path).catch(()=>{});try{await Em(re.path,{remote:"origin",branch:P,options:["--set-upstream"]}),pe=await fn(re.path).catch(()=>pe),xe.success(`Configured upstream for ${P}`)}catch(Re){const qe=Re instanceof Error?Re.message:"Unable to push new worktree branch.";xe.warning("Worktree created locally",{description:sn(`Upstream setup failed: ${qe}`)})}const Te=pe?{...re,status:pe}:re,Je=await E(void 0,re.path);if(!Je){await Fa({projectDirectory:J,path:re.path,force:!0}).catch(()=>{});const Re="Failed to create session for worktree";f(Re),xe.error(Re);return}Y(Je.id,ye),z(Je.id,re.path),Z(Je.id,Te),await ke(),a(""),xe.success("Worktree created")}catch(P){Se&&await Fa({projectDirectory:J,path:Se.path,force:!0}).catch(()=>{});const se=P instanceof Error?P.message:"Failed to create worktree";f(se),xe.error(se)}finally{b(!1)}},Ue=l.useCallback(Se=>{const P=C.filter(se=>G(se.id)?.path===Se.path);cr.requestDelete({sessions:P,mode:"worktree",worktree:Se})},[C,G]),Ge=l.useCallback(async()=>{if(j){M(!0);try{const Se=fe,P=Se&&D;if(j.sessions.length===1){const se=j.sessions[0];if(!await F(se.id,{archiveWorktree:Se,deleteRemoteBranch:P})){xe.error("Failed to delete session"),M(!1);return}const pe=Se?P?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;xe.success("Session deleted",{description:sn(pe)})}else{const se=j.sessions.map(Te=>Te.id),{deletedIds:re,failedIds:pe}=await $(se,{archiveWorktree:Se,deleteRemoteBranch:P});if(re.length>0){const Te=Se?P?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,Re=[pe.length>0?`${pe.length} session${pe.length===1?"":"s"} could not be deleted.`:j.dateLabel?`Removed all sessions from ${j.dateLabel}.`:void 0,Te].filter(Boolean).join(" ");xe.success(`Deleted ${re.length} session${re.length===1?"":"s"}`,{description:sn(Re||void 0)})}if(pe.length>0&&(xe.error(`Failed to delete ${pe.length} session${pe.length===1?"":"s"}`,{description:sn("Please try again in a moment.")}),re.length===0)){M(!1);return}}L()}finally{M(!1)}}},[j,D,F,$,L,fe]),Xe=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:Pn}),"."]})]}),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(Tt,{id:"worktree-branch-input",value:o,onChange:Se=>Q(Se.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!te||m,onKeyDown:Se=>{Se.key==="Enter"&&!y&&ct()}}),e.jsx(Ee,{onClick:ct,disabled:y||W||!te||!O,className:"h-8",children:y?"Creating…":"Create"})]}),O&&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:O})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:Vt(_,Ne)})]})]}),p&&e.jsx("p",{className:"typography-meta text-destructive",children:p}),!te&&!m&&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:Pn}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:i.map(Se=>{const P=Se.relativePath||(Se.path.startsWith(J+"/")?Se.path.slice(J.length+1):Se.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:Se.label||Se.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:P})]}),e.jsx("button",{type:"button",onClick:()=>Ue(Se),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 ${Se.branch||Se.label}`,children:e.jsx(Us,{className:"h-4 w-4"})})]},Se.path)})})]})]}),Ze=e.jsx(Ee,{variant:"ghost",onClick:()=>je(!1),disabled:y,children:"Close"}),Be=j?.worktree??S[0]?.metadata??null,ze=j?j.mode==="worktree"?`This removes the selected worktree and ${j.sessions.length===1?"1 linked session":`${j.sessions.length} linked sessions`}.`:`This action permanently removes ${j.sessions.length===1?"1 session":`${j.sessions.length} sessions`}${j.dateLabel?` from ${j.dateLabel}`:""}.`:"",dt=j?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:[j.sessions.slice(0,3).map(Se=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:Se.title||"Untitled Session"},Se.id)),j.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",j.sessions.length-3," more"]})]})}),be?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"}),Be?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Be.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Be?Vt(Be.path,Ne):"Worktree path unavailable."}),K&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),ae?e.jsxs("button",{type:"button",onClick:()=>{H||A(Se=>!Se)},disabled:H,className:T("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",H?"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:D?e.jsx(Xo,{className:"size-4 text-primary"}):e.jsx(Jo,{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:D?"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,mt=e.jsxs(e.Fragment,{children:[e.jsx(Ee,{variant:"ghost",onClick:L,disabled:N,children:"Cancel"}),e.jsx(Ee,{variant:"destructive",onClick:Ge,disabled:N,children:N?"Deleting…":be?"Delete worktree":j?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[B?e.jsx(qt,{open:ie,onClose:()=>je(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Ze}),children:e.jsx("div",{className:"space-y-2 pb-2",children:Xe})}):e.jsx(Ts,{open:ie,onOpenChange:je,children:e.jsxs(Is,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2 overflow-hidden",children:[e.jsx(Fs,{children:e.jsx(Ps,{children:"Worktree Manager"})}),Xe,e.jsx(Wr,{className:"mt-2 gap-2 pt-1 pb-1",children:Ze})]})}),B?e.jsx(qt,{open:!!j,onClose:()=>{N||L()},title:j?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:mt}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[ze&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:ze}),dt]})}):e.jsx(Ts,{open:!!j,onOpenChange:Se=>{if(!Se){if(N)return;L()}},children:e.jsxs(Is,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(Fs,{children:[e.jsx(Ps,{children:j?.sessions.length===1?"Delete session":"Delete sessions"}),ze&&e.jsx(nr,{children:ze})]}),dt,e.jsx(Wr,{className:"mt-2 gap-2 pt-1 pb-1",children:mt})]})}),e.jsx(dh,{open:r,onOpenChange:s})]})};function fh(){return new Worker(Ud,{type:"module"})}const ph=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function hh(r,s,t){const n=s.length>100?`${s.slice(0,50)}${s.slice(-50)}`:s,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${r}:${s.length}:${t.length}:${n.length}:${o.length}`}function Ci(r){if(typeof window>"u")return()=>{};const s=window.setTimeout(()=>r(void 0),0);return()=>window.clearTimeout(s)}const gh=({children:r})=>{const s=Gd(),t=Nt(c=>c.activeDirectory),n=Nt(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=Nt(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=bo(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(u,d)},[s]),de.useEffect(()=>{if(!s||!t||!n||o===0)return;const c=Nt.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 f=Array.from(c.diffCache.entries());let m=0;const h=g=>{if(u)return;const x=Date.now();for(;m<f.length&&!(g&&g.timeRemaining()<8||!g&&Date.now()-x>8);){const[y,b]=f[m];m+=1,Gr(y);const k=hh(y,b.original,b.modified),j={name:y,contents:b.original,cacheKey:`old-${k}`},v={name:y,contents:b.modified,cacheKey:`new-${k}`},S=bo(j,v),w={onHighlightSuccess:()=>{},onHighlightError:()=>{}};s.highlightDiffAST(w,S)}m<f.length&&(p=Ci(h))};return h(void 0),m<f.length&&(p=Ci(h)),()=>{u=!0,p?.()}},[s,t,n,o]),e.jsx(e.Fragment,{children:r})},xh=({children:r})=>{const t=ua()?.currentTheme?.metadata?.variant==="dark";Kl();const n=de.useMemo(()=>({theme:{dark:xr.dark,light:xr.light},themeType:t?"dark":"light",langs:ph}),[t]);return e.jsx(Vd,{poolOptions:{workerFactory:fh,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(gh,{children:r})})},yh=(r={})=>{const{edgeThreshold:s=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=r,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=Fe(),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},f=g=>{if(!d.current)return;const x=g.touches[0];if(!x)return;x.clientX-d.current.x>10&&g.preventDefault()},m=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:k}=d.current,{x:j,y:v,time:S}=u.current,w=j-y,D=v-b,A=S-k,N=Math.abs(D)<Math.abs(w),M=A<=n,C=Math.abs(D)<t;w>=t&&N&&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",f,{passive:!1,capture:!0}),document.addEventListener("touchend",m,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",p,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",m,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,s,t,n,i,c]),null},Er=r=>r==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:r==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;de.memo(()=>{const r=de.useRef(null),{addAttachedFile:s}=ge(),{isMobile:t}=Fe(),n=ca(),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 f=0;f<u.length;f++){const m=u[f],h=ge.getState().attachedFiles.length;try{await s(m),ge.getState().attachedFiles.length>h&&p++}catch(g){console.error("File attach failed",g),xe.error(g instanceof Error?g.message:"Failed to attach file")}}p>0&&xe.success(`Attached ${p} file${p>1?"s":""}`)},c=async u=>{const p=u.target.files;p&&(await i(p),r.current&&(r.current.value=""))},d=async()=>{try{const p=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(p?.files)?p.files:[],m=Array.isArray(p?.skipped)?p.skipped:[];if(m.length>0){const g=m.map(x=>`${x?.name||"file"}: ${x?.reason||"skipped"}`).join(`
|
|
65
|
-
`);xe.error(`Some files were skipped:
|
|
66
|
-
${g}`)}const h=f.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 k=atob(y),j=new Uint8Array(k.length);for(let S=0;S<k.length;S++)j[S]=k.charCodeAt(S);const v=new Blob([j],{type:b});return new File([v],g.name||"file",{type:b})}catch(x){return console.error("Failed to decode VS Code picked file",x),null}}).filter(Boolean);h.length>0&&await i(h)}catch(u){console.error("VS Code file pick failed",u),xe.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:r,type:"file",multiple:!0,className:"hidden",onChange:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():r.current?.click()},className: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(So,{className:T(a,"text-current")})})]})});const bh=de.memo(({file:r,onRemove:s})=>{const t=()=>r.mimeType.startsWith("image/")?e.jsx(gr,{className:"h-3.5 w-3.5"}):r.mimeType.includes("text")||r.mimeType.includes("code")?e.jsx(Qs,{className:"h-3.5 w-3.5"}):r.mimeType.includes("json")||r.mimeType.includes("xml")?e.jsx(Hn,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}),n=i=>i<1024?i+" B":i<1048576?(i/1024).toFixed(1)+" KB":(i/1048576).toFixed(1)+" MB",a=(i=>{const d=i.replace(/\\/g,"/").split("/");return d[d.length-1]||i})(r.filename);return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:r.source==="server"?"Server file":"Local file",children:r.source==="server"?e.jsx(qd,{className:"h-3 w-3 text-primary"}):e.jsx(gl,{className:"h-3 w-3 text-muted-foreground"})}),t(),e.jsx("span",{title:r.serverPath||a,children:a}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",n(r.size),")"]}),e.jsx("button",{onClick:s,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(hs,{className:"h-3 w-3"})})]})}),wh=de.memo(()=>{const{attachedFiles:r,removeAttachedFile:s}=ge();return r.length===0?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Attached:"}),r.map(t=>e.jsx(bh,{file:t,onRemove:()=>s(t.id)},t.id))]})})}),hc=de.memo(({files:r,onShowPopup:s})=>{const t=r.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const p=d.replace(/\\/g,"/").split("/");return p[p.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(gr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(Qs,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Hn,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}):e.jsx(Qs,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),c=l.useCallback(d=>{if(!s||!d?.url)return;const u=n(d.filename)||"Image",p={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};s(p)},[s]);return t.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const p=n(d.filename)||"Image";return e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{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:f=>{const m=f.target;m.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(gr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:p})]})}),e.jsx(ft,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:p})]},`img-${u}`)})})})]})}),gc=(r,s=200)=>{const[t,n]=de.useState(r);return de.useEffect(()=>{const o=window.setTimeout(()=>{n(r)},s);return()=>{window.clearTimeout(o)}},[r,s]),t},vh=l.forwardRef(({searchQuery:r,onFileSelect:s,onClose:t},n)=>{const{currentDirectory:o}=jt(),{addServerFile:a}=ge(),i=na(S=>S.searchFiles),c=gc(r,180),[d,u]=l.useState([]),[p,f]=l.useState(!1),[m,h]=l.useState(0),[g,x]=l.useState(null),y=l.useRef([]),b=l.useRef(null),k=l.useCallback((S,w)=>{const D=S.trim().toLowerCase();if(!D)return 0;const A=w.toLowerCase();let N=0,M=-1,C=0;for(let E=0;E<D.length;E+=1){const F=D[E];if(!F||F===" ")continue;const $=A.indexOf(F,M+1);if($===-1)return null;const R=$-M-1;if(R===0?C+=1:C=0,N+=10,N+=Math.max(0,18-$),N-=Math.max(0,R),$===0)N+=12;else{const Y=A[$-1];(Y==="/"||Y==="_"||Y==="-"||Y==="."||Y===" ")&&(N+=10)}N+=C>0?12:0,M=$}return N+=Math.max(0,24-Math.round(A.length/3)),N},[]);l.useEffect(()=>{const S=w=>{const D=w.target;!D||!b.current||b.current.contains(D)||t()};return document.addEventListener("pointerdown",S,!0),()=>{document.removeEventListener("pointerdown",S,!0)}},[t]),l.useEffect(()=>{if(!o){u([]);return}const w=(c??"").trim().toLowerCase();let D=!1;return f(!0),i(o,w,80).then(A=>{if(D)return;const N=w?A.map(M=>{const C=M.relativePath||M.name||M.path,E=k(w,C);return E===null?null:{file:M,score:E,labelLength:C.length}}).filter(Boolean):A.map(M=>({file:M,score:0,labelLength:(M.relativePath||M.name||M.path).length}));N.sort((M,C)=>C.score-M.score||M.labelLength-C.labelLength||M.file.path.localeCompare(C.file.path)),u(N.slice(0,15).map(M=>M.file))}).catch(()=>{D||u([])}).finally(()=>{D||f(!1)}),()=>{D=!0}},[o,c,k,i]),l.useEffect(()=>{h(0),x(null)},[d]),l.useEffect(()=>{y.current[m]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[m]);const j=l.useCallback(async S=>{await a(S.path,S.name),s(S)},[a,s]);l.useImperativeHandle(n,()=>({handleKeyDown:S=>{if(S==="Escape"){t();return}const w=d.length;if(w!==0){if(S==="ArrowDown"){h(D=>(D+1)%w);return}if(S==="ArrowUp"){h(D=>(D-1+w)%w);return}if(S==="Enter"||S==="Tab"){const D=(m%w+w)%w,A=d[D];A&&j(A)}}}}),[d,m,t,j]);const v=S=>{switch(S.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(zs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(zs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(gr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Hn,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:b,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(Ye,{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(Wn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((S,w)=>{const D=S.relativePath||S.name,A=wl(D,{maxLength:45}),N=m===w,C=N||g===w,E=e.jsxs("div",{ref:F=>{y.current[w]=F},className:T("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",N&&"bg-accent"),onClick:()=>j(S),onMouseEnter:()=>h(w),children:[v(S),e.jsx("span",{className:"flex-1 truncate max-w-[360px]","aria-label":D,children:A})]});return e.jsxs(gt,{open:C,delayDuration:C?0:120,onOpenChange:F=>{x($=>!F&&$===w?null:F?w:$)},children:[e.jsx(xt,{asChild:!0,children:E}),e.jsx(ft,{side:"right",align:"center",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:D})})]},S.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"})]})}),xc=l.forwardRef(({searchQuery:r,onCommandSelect:s,onClose:t},n)=>{const{hasMessagesInCurrentSession:o}=ge(Zo(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),f=l.useRef([]),m=l.useRef(null);l.useEffect(()=>{const g=x=>{const y=x.target;!y||!m.current||m.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 Ae.listCommands()).map(w=>({name:w.name,description:w.description,agent:w.agent,model:w.model,isBuiltIn:!1})),b=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],k=new Map;b.forEach(w=>k.set(w.name,w)),y.forEach(w=>k.set(w.name,w));const j=Array.from(k.values()),v=!o,S=(r?j.filter(w=>w.name.toLowerCase().includes(r.toLowerCase())||w.description&&w.description.toLowerCase().includes(r.toLowerCase())):j).filter(w=>v||w.name!=="init");S.sort((w,D)=>{const A=w.name.toLowerCase().startsWith(r.toLowerCase()),N=D.name.toLowerCase().startsWith(r.toLowerCase());return A&&!N?-1:!A&&N?1:w.name.localeCompare(D.name)}),i(S)}catch{const x=!o,y=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],b=(r?y.filter(k=>k.name.toLowerCase().includes(r.toLowerCase())||k.description&&k.description.toLowerCase().includes(r.toLowerCase())):y).filter(k=>x||k.name!=="init");i(b)}finally{d(!1)}})()},[r,o]),l.useEffect(()=>{p(0)},[a]),l.useEffect(()=>{f.current[u]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[u]),l.useImperativeHandle(n,()=>({handleKeyDown:g=>{const x=a.length;if(g==="Escape"){t();return}if(x!==0){if(g==="ArrowDown"){p(y=>(y+1)%x);return}if(g==="ArrowUp"){p(y=>(y-1+x)%x);return}if(g==="Enter"||g==="Tab"){const y=(u%x+x)%x,b=a[y];b&&s(b)}}}}),[a,u,t,s]);const h=g=>{switch(g.name){case"init":return e.jsx(Qs,{className:"h-3.5 w-3.5 text-green-500"});case"summarize":return e.jsx(Yd,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Ws,{className:"h-3.5 w-3.5 text-cyan-500"});default:return g.isBuiltIn?e.jsx(Kd,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(br,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:m,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(Ye,{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(Wn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[a.map((g,x)=>e.jsxs("div",{ref:y=>{f.current[x]=y},className:T("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",x===u&&"bg-accent"),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"})]})});xc.displayName="CommandAutocomplete";const jh=r=>r?r!=="primary":!1,yc=l.forwardRef(({searchQuery:r,onAgentSelect:s,onClose:t},n)=>{const o=l.useRef(null),[a,i]=l.useState(0),[c,d]=l.useState([]),{agents:u}=St();l.useEffect(()=>{const f=u.filter(g=>jh(g.mode)).map(g=>({name:g.name,description:g.description,mode:g.mode??void 0})),m=r.trim().toLowerCase(),h=m.length?f.filter(g=>g.name.toLowerCase().includes(m)):f;h.sort((g,x)=>g.name.localeCompare(x.name)),d(h),i(0)},[u,r]),l.useEffect(()=>{const f=m=>{const h=m.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",f,!0),()=>{document.removeEventListener("pointerdown",f,!0)}},[t]),l.useImperativeHandle(n,()=>({handleKeyDown:f=>{if(f==="Escape"){t();return}if(c.length){if(f==="ArrowDown"){i(m=>(m+1)%c.length);return}if(f==="ArrowUp"){i(m=>(m-1+c.length)%c.length);return}if(f==="Enter"||f==="Tab"){const m=c[(a+c.length)%c.length];m&&s(m.name)}}}}),[c,s,t,a]);const p=(f,m)=>e.jsx("div",{className:T("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",m===a&&"bg-accent"),onClick:()=>s(f.name),onMouseEnter:()=>i(m),children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["#",f.name]})}),f.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:f.description})]})},f.name);return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c.length?e.jsx("div",{children:c.map((f,m)=>p(f,m))}):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"})]})});yc.displayName="AgentMentionAutocomplete";function Sh({className:r,children:s,...t}){return e.jsxs(Xd,{"data-slot":"scroll-area",className:T("relative",r),...t,children:[e.jsx(Jd,{"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(kh,{}),e.jsx(Zd,{})]})}function kh({className:r,orientation:s="vertical",...t}){return e.jsx(Qd,{"data-slot":"scroll-area-scrollbar",orientation:s,className:T("flex touch-none p-px select-none",s==="vertical"&&"h-full w-2.5 border-l border-l-transparent",s==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",r),...t,children:e.jsx(eu,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Nh=({onFilesSelected:r,multiSelect:s=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=At(),c=ca(),d=i||c,{currentDirectory:u}=jt(),p=na(H=>H.searchFiles),[f,m]=l.useState(!1),[h,g]=l.useState(!1),[x,y]=l.useState(""),b=gc(x,200),[k,j]=l.useState(new Set),[v,S]=l.useState(new Set),[w,D]=l.useState({}),A=l.useRef(new Set),N=l.useRef(new Set),[M,C]=l.useState([]),[E,F]=l.useState(!1),[$,R]=l.useState(!1),[Y,Z]=l.useState(!1),[z,G]=l.useState(null),W=n??f,ce=o??m,Ne=l.useCallback(H=>H.slice().sort((V,L)=>V.type!==L.type?V.type==="directory"?-1:1:V.name.localeCompare(L.name)),[]),Me=l.useCallback((H,V)=>Ne(V.filter(L=>!L.name.startsWith(".")).map(L=>{const Q=L.name,ke=!L.isDirectory&&Q.includes(".")?Q.split(".").pop()?.toLowerCase():void 0;return{name:Q,path:L.path||`${H}/${Q}`,type:L.isDirectory?"directory":"file",size:0,extension:ke}})),[Ne]),Le=l.useCallback(async H=>{R(!0),G(null);try{const V=await Ae.listLocalDirectory(H),L=Me(H,V.map(Q=>({name:Q.name,path:Q.path,isDirectory:Q.isDirectory})));A.current=new Set([H]),N.current=new Set,D({[H]:L}),S(new Set)}catch{G("Failed to load directory contents"),A.current=new Set([H]),N.current=new Set,D({[H]:[]}),S(new Set)}finally{R(!1)}},[Me]),ye=l.useCallback(async H=>{const V=H.trim();if(V&&!A.current.has(V)&&!N.current.has(V)){N.current=new Set(N.current),N.current.add(V);try{const L=await Ae.listLocalDirectory(V),Q=Me(V,L.map(ke=>({name:ke.name,path:ke.path,isDirectory:ke.isDirectory})));A.current=new Set(A.current),A.current.add(V),D(ke=>({...ke,[V]:Q}))}catch{D(L=>L[V]?L:{...L,[V]:[]})}finally{N.current=new Set(N.current),N.current.delete(V)}}},[Me]);l.useEffect(()=>{(W||h)&&u&&Le(u)},[W,h,u,Le]),l.useEffect(()=>{if(!(W||h)||!u){C([]),F(!1);return}const H=b.trim();if(!H){C([]),F(!1);return}let V=!1;return F(!0),p(u,H,150).then(L=>{if(V)return;const Q=L.map(ke=>({name:ke.name,path:ke.path,type:"file",extension:ke.extension,relativePath:ke.relativePath,size:0}));C(Q)}).catch(()=>{V||C([])}).finally(()=>{V||F(!1)}),()=>{V=!0}},[W,h,u,b,p]),l.useEffect(()=>{!W&&!h&&(j(new Set),y(""),C([]),F(!1))},[W,h]);const ie=H=>{if(H.type==="directory")return v.has(H.path)?e.jsx(os,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(os,{className:"h-3.5 w-3.5 text-primary/60"});switch(H.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(zs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(zs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(ko,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(gr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(ko,{className:"h-3.5 w-3.5 text-muted-foreground"})}},je=async H=>{v.has(H)?S(L=>{const Q=new Set(L);return Q.delete(H),Q}):(S(L=>{const Q=new Set(L);return Q.add(H),Q}),await ye(H))},Ce=H=>{j(s?V=>{const L=new Set(V);return L.has(H)?L.delete(H):L.add(H),L}:new Set([H]))},We=async()=>{const H=new Map;Object.values(w).forEach(Q=>{Q.forEach(ke=>{ke.type==="file"&&H.set(ke.path,ke)})});const V=new Map(M.map(Q=>[Q.path,Q])),L=Array.from(k).map(Q=>H.get(Q)??V.get(Q)).filter(Q=>!!Q);Z(!0);try{await r(L),j(new Set),ce(!1),g(!1)}finally{Z(!1)}},oe=l.useMemo(()=>u?w[u]??[]:[],[w,u]),B=x.trim().length>0,J=H=>w[H]??[],O=H=>{if(u&&H.startsWith(u)){const V=H.substring(u.length);return V.startsWith("/")?V.substring(1):V}return H.split("/").pop()||H},X=(H,V)=>{const L=B?H.relativePath||O(H.path):H.name,Q=B&&L.includes("/")&&L.length>45,ke=Q?wl(L,{maxLength:d?42:48}):L,De=e.jsxs("div",{className:T("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-accent cursor-pointer typography-ui-label text-foreground text-left",H.type==="file"&&k.has(H.path)&&"bg-primary/10"),style:{paddingLeft:`${V*12}px`},onClick:Oe=>{Oe.preventDefault(),Oe.stopPropagation(),H.type==="file"&&Ce(H.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ie(H)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":L,children:ke})]}),H.type==="file"&&k.has(H.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return Q?e.jsxs(gt,{delayDuration:120,children:[e.jsx(xt,{asChild:!0,children:De}),e.jsx(ft,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:L})})]},H.path):l.cloneElement(De,{key:H.path})},_=(H,V)=>{const L=H.type==="directory",Q=L?J(H.path):[],ke=v.has(H.path),De=L&&ke&&N.current.has(H.path)&&Q.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",!L&&k.has(H.path)&&"bg-primary/10"),style:{paddingLeft:`${V*12}px`},onClick:Oe=>{Oe.preventDefault(),Oe.stopPropagation(),L?je(H.path):Ce(H.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ie(H)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:H.name}),!L&&k.has(H.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),L&&ke&&Q.length>0&&e.jsx("div",{children:Q.map(Oe=>_(Oe,V+1))}),L&&ke&&De&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(V+1)*12}px`},children:"Loading…"})]},H.path)},te=k.size>0?`${k.size} file${k.size!==1?"s":""} selected`:"No files selected",K=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:te}),e.jsx(Ee,{size:"sm",onClick:We,disabled:k.size===0||Y,className:"h-6 typography-meta",children:Y?"Attaching...":"Attach Files"})]}),ae=d?"flex-1 min-h-[240px]":"h-[300px]",be=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsx("div",{className:"font-medium typography-ui-label text-foreground",children:"Select Project Files"})}),e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Yo,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Tt,{value:x,onChange:H=>y(H.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:H=>H.stopPropagation()}),x&&e.jsx("button",{onClick:H=>{H.stopPropagation(),y("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-accent rounded",children:e.jsx(hs,{className:"h-3 w-3"})})]})}),e.jsxs(Sh,{className:ae,children:[$&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Loading files..."})}),z&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:z})}),!$&&!z&&e.jsxs("div",{className:"py-1 px-2",children:[B?E?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):M.map(H=>X(H,0)):oe.map(H=>_(H,0)),!B&&oe.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),B&&!E&&M.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),fe=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:H=>{H.preventDefault(),H.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:H=>{H.preventDefault(),H.stopPropagation(),ce(!0)},children:t}):null,e.jsx(qt,{open:W,onClose:()=>ce(!1),title:"Select Project Files",footer:K,children:e.jsx("div",{className:"flex flex-col gap-0",children:be})})]}):d?e.jsxs(e.Fragment,{children:[fe,e.jsx(qt,{open:h,onClose:()=>g(!1),title:"Select Project Files",footer:K,children:e.jsx("div",{className:"flex flex-col gap-0",children:be})})]}):e.jsxs(Kt,{open:W,onOpenChange:ce,children:[e.jsx(Yt,{asChild:!0,children:t}),e.jsxs(Xt,{className:T("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[be,e.jsx(Hr,{}),K]})]})},nn=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function _s(r){if(!r||r==="build")return nn[0];let s=0;for(let n=0;n<r.length;n++){const o=r.charCodeAt(n);s=(s<<5)-s+o,s=s&s}const t=1+Math.abs(s)%(nn.length-1);return nn[t]}const Ch=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),bc=r=>Ch(r),Mh=r=>r?typeof r=="string"?r==="ask":bc(r)?Object.values(r).some(s=>s==="ask"):!1:!1,Ah=r=>r?typeof r=="string"?r==="deny":bc(r)?Object.values(r).some(s=>s==="deny"):!1:!1,wc=({agentDefaultEditMode:r,webfetchPermission:s,bashPermission:t})=>{const n=Mh(t),o=Ah(t),a=!n&&!o,i=s==="allow",c=s!=="deny",d=r==="allow"||r==="full",u=r==="ask";let p=r;d&&i&&a?p="full":d&&n?p="allow":u&&(p="ask");const f={ask:u,allow:u||d&&n,full:r!=="deny"&&c&&n,deny:!1},m=f.allow||f.full;return{cascadeDefaultMode:p,modeAvailability:f,autoApproveAvailable:m,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:c}},on=r=>r==="primary"||r==="all"||r===void 0||r===null,Dh=[{key:"tool_call",icon:Qo,label:"Tool calling",isActive:r=>r?.tool_call===!0},{key:"reasoning",icon:Bn,label:"Reasoning",isActive:r=>r?.reasoning===!0}],Eh={text:{icon:xl,label:"Text"},image:{icon:gr,label:"Image"},video:{icon:su,label:"Video"},audio:{icon:tu,label:"Audio"},pdf:{icon:Hn,label:"PDF"}},Th=r=>r.trim().toLowerCase(),bs=(r,s)=>{const t=s==="input"?r?.modalities?.input:r?.modalities?.output;return!Array.isArray(t)||t.length===0?[]:Array.from(new Set(t.map(o=>Th(o)))).map(o=>{const a=Eh[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Ih=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Fh=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Rt=r=>{if(typeof r!="number"||Number.isNaN(r))return"—";if(r===0)return"0";const s=Ih.format(r);return s.endsWith(".0")?s.slice(0,-2):s},an=r=>typeof r!="number"||!Number.isFinite(r)?"—":Fh.format(r),Ar=r=>Dh.filter(s=>s.isActive(r)).map(s=>({key:s.key,icon:s.icon,label:s.label})),Mi=r=>{if(!r)return"—";const s=r.match(/^(\d{4})-(\d{2})$/);if(s){const t=Number.parseInt(s[1],10),n=Number.parseInt(s[2],10)-1,o=new Date(Date.UTC(t,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return r},Ai=r=>{if(!r)return"—";const s=new Date(r);return Number.isNaN(s.getTime())?r:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(s)},Di=({className:r})=>{const{providers:s,agents:t,currentProviderId:n,currentModelId:o,currentAgentName:a,setProvider:i,setModel:c,setAgent:d,getCurrentProvider:u,getModelMetadata:p,getCurrentAgent:f}=St(),{currentSessionId:m,messages:h,saveSessionAgentSelection:g,getSessionAgentSelection:x,saveAgentModelForSession:y,getAgentModelForSession:b,analyzeAndSaveExternalSessionChoices:k,getSessionAgentEditMode:j,setSessionAgentEditMode:v}=ge(),S=wt(q=>q.hasHydrated),{toggleFavoriteModel:w,isFavoriteModel:D,addRecentModel:A}=Fe(),{favoriteModelsList:N,recentModelsList:M}=nc(),{isMobile:C}=At(),E=ep(),F=ca(),$=C||F,[R,Y]=l.useState(null),[Z,z]=l.useState(null),[G,W]=l.useState(""),ce=l.useCallback(()=>Y(null),[]),Ne=l.useCallback(()=>z(null),[]),Me=l.useRef(void 0),[Le,ye]=l.useState(()=>{const q=new Set;return n&&q.add(n),q}),[ie,je]=l.useState(!1),[Ce,We]=l.useState(!1),[oe,B]=l.useState(!1),J=l.useId();l.useEffect(()=>{R==="model"&&ye(()=>{const q=new Set;return n&&q.add(n),q})},[R,n]),l.useEffect(()=>{R!=="agent"&&je(!1),R!=="model"&&W("")},[R]),l.useEffect(()=>{Ce||B(!1)},[Ce]);const O=f?.(),X=O?.permission?.edit;let _="ask";(X==="allow"||X==="ask"||X==="deny"||X==="full")&&(_=X);const te=O?O.tools?.edit!==!1:!1;(!O||!te)&&(_="deny");const K=O?.permission?.webfetch,ae=O?.permission?.bash,be=l.useMemo(()=>wc({agentDefaultEditMode:_,webfetchPermission:K,bashPermission:ae}),[_,K,ae]),{cascadeDefaultMode:fe,modeAvailability:H,autoApproveAvailable:V}=be,L=!!(m&&a),Q=L&&m&&a?j(m,a,fe):fe,ke={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},De=l.useCallback(q=>!H[q],[H]),Oe=l.useMemo(()=>!L||De(Q)&&Q!==fe?fe:Q,[fe,De,L,Q]),ct=[{mode:"ask",label:ke.ask,disabled:De("ask")},{mode:"allow",label:ke.allow,disabled:De("allow")},{mode:"full",label:ke.full,disabled:De("full")}],Ue=l.useMemo(()=>Er(Oe),[Oe]),Ge=!L||!V;l.useEffect(()=>{Ge&&(je(!1),B(!1))},[Ge]);const Xe=C?"mobile":F?"vscode":"default",Ze=Xe==="mobile"?"h-9":Xe==="vscode"?"h-6":"h-8",Be=Xe==="mobile"?"h-5 w-5":"h-4 w-4",ze=Xe==="mobile"?"h-5 w-5":"h-4 w-4",dt=$?"typography-micro":"typography-meta",mt=Xe==="mobile"?"gap-x-2":Xe==="vscode"?"gap-x-1":"gap-x-3",Se=ke[Oe],P=l.useCallback((q,le=Be)=>{const ee=T(le,"flex-shrink-0"),ue=Er(q),st={color:ue?ue.text:"var(--foreground)"};return q==="full"?e.jsx(Ns,{className:ee,style:st}):q==="allow"?e.jsx(un,{className:ee,style:st}):q==="deny"?e.jsx(hr,{className:ee,style:st}):e.jsx(Or,{className:ee,style:st})},[Be]),se=l.useCallback(q=>{Ge||!m||!a||De(q)||(v(m,a,q,fe),We(!1),je(!1),B(!1))},[fe,Ge,m,a,v,We,B,De]),re=u(),pe=Array.isArray(re?.models)?re.models:[],Te=n&&o?p(n,o):void 0,Je=Ar(Te),Re=bs(Te,"input"),qe=bs(Te,"output"),ut=[{label:"Input",value:an(Te?.cost?.input)},{label:"Output",value:an(Te?.cost?.output)},{label:"Cache read",value:an(Te?.cost?.cache_read)},{label:"Cache write",value:an(Te?.cost?.cache_write)}],Dt=[{label:"Context",value:Rt(Te?.limit?.context)},{label:"Output",value:Rt(Te?.limit?.output)}],pt=l.useRef(void 0),kt=m?h.get(m)?.length??-1:-1,bt=l.useRef(null),ht=l.useCallback((q,le,ee)=>{if(!q||!le)return"model-missing";const ue=s.find(he=>he.id===q);return ue?(Array.isArray(ue.models)?ue.models:[]).find(he=>he.id===le)?(i(q),c(le),m&&ee&&y(m,ee,q,le),"applied"):"model-missing":"provider-missing"},[s,i,c,m,y]);l.useEffect(()=>{if(!m){bt.current=null;return}if(!S||s.length===0||t.length===0)return;(!bt.current||bt.current.sessionId!==m)&&(bt.current={sessionId:m,resolved:!1,inFlight:!1});const q=bt.current;if(!q||q.resolved||q.inFlight)return;let le=!1;const ee=()=>{if(le)return;const he=bt.current;he&&he.sessionId===m&&(he.resolved=!0,he.inFlight=!1)},ue=()=>{const he=x(m);if(he){a!==he&&d(he);const Ke=b(m,he);if(Ke){const it=ht(Ke.providerId,Ke.modelId,he);if(it==="applied")return"resolved";if(it==="provider-missing")return"waiting"}else return"resolved"}for(const Ke of t){const it=b(m,Ke.name);if(!it)continue;a!==Ke.name&&d(Ke.name),g(m,Ke.name);const Wt=ht(it.providerId,it.modelId,Ke.name);if(Wt==="applied")return"resolved";if(Wt==="provider-missing")return"waiting"}return"continue"},tt=()=>{if(t.length===0)return;const he=t.filter(it=>on(it.mode)),Ke=t.find(it=>it.name==="build")||he[0]||t[0];Ke&&(g(m,Ke.name),a!==Ke.name&&d(Ke.name),Ke.model?.providerID&&Ke.model?.modelID&&ht(Ke.model.providerID,Ke.model.modelID,Ke.name))};return(async()=>{try{const he=ue();if(he==="resolved"){ee();return}if(he==="waiting"||kt===-1)return;if(kt>0){q.inFlight=!0;try{const Ke=await k(m,t);if(le)return;if(Ke.size>0){let it=null,Wt=-1/0;for(const[Ve,Pt]of Ke)Pt.timestamp>Wt&&(Wt=Pt.timestamp,it=Ve);if(it){g(m,it),a!==it&&d(it);const Ve=Ke.get(it);if(Ve){const Pt=ht(Ve.providerId,Ve.modelId,it);if(Pt==="applied"){ee();return}if(Pt==="provider-missing")return}else{ee();return}}}}catch(Ke){le||console.error("[ModelControls] Error resolving session from messages:",Ke)}finally{const Ke=bt.current;!le&&Ke&&Ke.sessionId===m&&(Ke.inFlight=!1)}}tt(),ee()}catch(he){le||console.error("[ModelControls] Error in session switch:",he)}})(),()=>{le=!0}},[m,kt,t,a,x,b,d,ht,k,g,S,s]),l.useEffect(()=>{if(!S||!m||s.length===0||t.length===0)return;const le=x(m)||a;if(!le)return;const ee=b(m,le);if(!ee)return;const ue=s.find(Ke=>Ke.id===ee.providerId);if(!ue||!(Array.isArray(ue.models)?ue.models.some(Ke=>Ke.id===ee.modelId):!1))return;const st=n===ee.providerId,he=o===ee.modelId;st&&he||(le!==a&&d(le),ht(ee.providerId,ee.modelId,le))},[S,m,a,n,o,s,t,x,b,ht,d]),l.useEffect(()=>{if(!S)return;(async()=>{try{if(a!==pt.current&&(pt.current=a,a&&m)){await new Promise(ue=>setTimeout(ue,50));const le=b(m,a);if(le){const ue=ht(le.providerId,le.modelId,a);if(ue==="applied"||ue==="provider-missing")return}const ee=t.find(ue=>ue.name===a);if(ee?.model?.providerID&&ee?.model?.modelID&&ht(ee.model.providerID,ee.model.modelID,a)==="provider-missing")return}}catch(le){console.error("[ModelControls] Agent change error:",le)}})()},[a,m,b,ht,t,S]);const Et=q=>{try{d(q),We(!1),m&&g(m,q),$&&ce()}catch(le){console.error("[ModelControls] Handle agent change error:",le)}},I=(q,le)=>{try{const ee=ht(q,le,a||void 0);if(ee!=="applied"){ee==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",q):ee==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:q,modelId:le});return}A(q,le),We(!1),$&&ce()}catch(ee){console.error("[ModelControls] Handle model change error:",ee)}},ne=q=>{const le=typeof q?.name=="string"?q.name:typeof q?.id=="string"?q.id:"";return le.length>40?le.substring(0,37)+"...":le},we=()=>s.find(le=>le.id===n)?.name||n,ve=()=>{if(!n||!o||pe.length===0)return"Not selected";const q=pe.find(le=>le.id===o);return ne(q)},me=()=>{if(!a){const le=t.filter(tt=>on(tt.mode)),ue=le.find(tt=>tt.name==="build")||le[0];return ue?Pe(ue.name):"Select Agent"}const q=t.find(le=>le.name===a);return Pe(q?q.name:a)},Pe=q=>q.charAt(0).toUpperCase()+q.slice(1),_e=(q,le,ee)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:le,"aria-label":le,role:"img",children:e.jsx(q,{className:"h-3.5 w-3.5"})},ee),nt=l.useCallback(q=>{ye(le=>{const ee=new Set(le);return ee.has(q)?ee.delete(q):ee.add(q),ee})},[]),Mt=l.useCallback(q=>{Me.current&&clearTimeout(Me.current),Me.current=setTimeout(()=>{z(q)},500)},[]),Qe=l.useCallback(()=>{Me.current&&clearTimeout(Me.current)},[]);l.useEffect(()=>()=>{Me.current&&clearTimeout(Me.current)},[]);const Ct=()=>!$||Z!=="model"?null:e.jsx(qt,{open:!0,onClose:Ne,title:Te?.name||ve(),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:we()})]}),Je.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:Je.map(({key:q,icon:le,label:ee})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[_e(le,ee,`cap-${q}`),e.jsx("span",{className:"typography-meta text-foreground",children:ee})]},q))})]}),(Re.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:[Re.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:Re.map(({key:q,icon:le,label:ee})=>_e(le,`${ee} input`,`input-${q}`))})]}),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:q,icon:le,label:ee})=>_e(le,`${ee} output`,`output-${q}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Rt(Te?.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:Rt(Te?.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:Mi(Te?.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:Ai(Te?.release_date)})]})]})]})]})}),Ft=()=>{if(!$||Z!=="agent"||!O)return null;const q=Object.entries(O.tools||{}).filter(([,he])=>he).map(([he])=>he).sort(),le=!!(O.prompt&&O.prompt.trim().length>0),ee=O.model?.providerID&&O.model?.modelID,ue=O.temperature!==void 0||O.topP!==void 0,tt=he=>P(he==="full"||he==="allow"||he==="deny"?he:"ask","h-3.5 w-3.5"),st=he=>he==="full"?"Full":he==="allow"?"Allow":he==="deny"?"Deny":"Ask";return e.jsx(qt,{open:!0,onClose:Ne,title:Pe(O.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[O.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:O.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:O.mode==="primary"?"Primary":O.mode==="subagent"?"Subagent":O.mode==="all"?"All":"—"})]}),(ee||ue)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),ee&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[O.model.providerID," / ",O.model.modelID]}),ue&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[O.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:O.temperature})]}),O.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:O.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Tools"}),q.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:q.map(he=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:he},he))}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[tt(O.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:st(O.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:[tt(typeof O.permission?.bash=="string"?O.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:st(typeof O.permission?.bash=="string"?O.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:[tt(O.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:st(O.permission?.webfetch)})]})]})]})]}),le&&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(un,{className:"h-4 w-4 text-foreground"})]})})]})})},U=()=>{if(!$)return null;const q=G.trim().toLowerCase(),le=s.map(ee=>{const ue=Array.isArray(ee.models)?ee.models:[],tt=q.length===0?!0:ee.name.toLowerCase().includes(q)||ee.id.toLowerCase().includes(q),st=q.length===0?ue:ue.filter(he=>{const Ke=ne(he).toLowerCase(),it=typeof he.id=="string"?he.id.toLowerCase():"";return Ke.includes(q)||it.includes(q)});return{provider:ee,providerModels:st,matchesProvider:tt}}).filter(({matchesProvider:ee,providerModels:ue})=>ee||ue.length>0);return e.jsx(qt,{open:R==="model",onClose:ce,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"px-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Yo,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(Tt,{value:G,onChange:ee=>W(ee.target.value),placeholder:"Search providers or models",className:"pl-7 h-8 typography-meta"}),G&&e.jsx("button",{type:"button",onClick:()=>W(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(hr,{className:"h-4 w-4"})})]})}),le.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."}),!G&&N.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(ms,{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:N.map(({model:ee,providerID:ue,modelID:tt})=>{const st=ue===n&&tt===o,he=p(ue,tt);return e.jsxs("button",{type:"button",onClick:()=>I(ue,tt),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",st?"bg-primary/15 text-primary":"hover:bg-accent/40"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ut,{providerId:ue,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ne(ee)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(he?.limit?.context||he?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[he?.limit?.context?`${Rt(he?.limit?.context)} ctx`:"",he?.limit?.context&&he?.limit?.output?" • ":"",he?.limit?.output?`${Rt(he?.limit?.output)} out`:""]})})]},`fav-mobile-${ue}-${tt}`)})})]}),!G&&M.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(jn,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:M.map(({model:ee,providerID:ue,modelID:tt})=>{const st=ue===n&&tt===o,he=p(ue,tt);return e.jsxs("button",{type:"button",onClick:()=>I(ue,tt),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",st?"bg-primary/15 text-primary":"hover:bg-accent/40"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Ut,{providerId:ue,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:ne(ee)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(he?.limit?.context||he?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[he?.limit?.context?`${Rt(he?.limit?.context)} ctx`:"",he?.limit?.context&&he?.limit?.output?" • ":"",he?.limit?.output?`${Rt(he?.limit?.output)} out`:""]})})]},`recent-mobile-${ue}-${tt}`)})})]}),le.map(({provider:ee,providerModels:ue})=>{if(ue.length===0&&!q.length)return null;const tt=ee.id===n,st=Le.has(ee.id)||q.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",onClick:()=>nt(ee.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":st,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ut,{providerId:ee.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ee.name}),tt&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),st?e.jsx(vt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(gs,{className:"h-3 w-3 text-muted-foreground"})]}),st&&ue.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:ue.map(he=>{const Ke=tt&&he.id===o,it=p(ee.id,he.id),Wt=Ar(it).slice(0,3),Ve=bs(it,"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",Ke?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>I(ee.id,he.id),className:T("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",!Ke&&"hover:bg-accent/40"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ne(he)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(it?.limit?.context||it?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[it?.limit?.context?e.jsxs("span",{children:[Rt(it?.limit?.context)," ctx"]}):null,it?.limit?.context&&it?.limit?.output?e.jsx("span",{children:"•"}):null,it?.limit?.output?e.jsxs("span",{children:[Rt(it?.limit?.output)," out"]}):null]}),(Wt.length>0||Ve.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Wt,...Ve].map(({key:Pt,icon:cs,label:Sa})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Sa,"aria-label":Sa,children:e.jsx(cs,{className:"h-3 w-3"})},`meta-${ee.id}-${he.id}-${Pt}`))})]})]}),e.jsx("button",{type:"button",onClick:Pt=>{Pt.preventDefault(),Pt.stopPropagation(),w(ee.id,he.id)},className:T("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",D(ee.id,he.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":D(ee.id,he.id)?"Unfavorite":"Favorite",title:D(ee.id,he.id)?"Remove from favorites":"Add to favorites",children:D(ee.id,he.id)?e.jsx(ms,{className:"h-4 w-4"}):e.jsx(Zs,{className:"h-4 w-4"})})]},he.id)})})]},ee.id)})]})})},Ie=()=>{if(!$)return null;const q=t.filter(le=>on(le.mode));return e.jsx(qt,{open:R==="agent",onClose:ce,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[q.map(le=>{const ee=le.name===a,ue=_s(le.name);return e.jsxs("button",{type:"button",className:T("flex w-full flex-col gap-1 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary agent-list-item",ue.class,ee?"active":"border-border/40"),onClick:()=>Et(le.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("h-2 w-2 rounded-full",ue.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:ee?{color:`var(${ue.var})`}:void 0,children:Pe(le.name)})]}),le.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:le.description})]},le.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:Ge,onClick:()=>{Ge||je(le=>!le)},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",Ge?"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:Ue?Ue.text:"var(--foreground)",mixBlendMode:"normal"},children:Se})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!Ue&&"text-muted-foreground"),style:Ue?{color:Ue.text}:void 0,children:P(Oe,Be)}),e.jsx(vt,{className:T("h-4 w-4 text-muted-foreground transition-transform",ie?"rotate-180":"")})]})]}),ie&&!Ge&&e.jsx("div",{className:"border-t border-border/40 bg-transparent px-2 py-1.5",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:ct.map(le=>{const ee=le.mode===Oe,ue=Er(le.mode);return e.jsxs("button",{type:"button",disabled:le.disabled,onClick:()=>se(le.mode),className:T("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",le.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",ee?"bg-primary/10":void 0),style:ee&&ue?{backgroundColor:ue.background??void 0}:void 0,children:[P(le.mode,Be),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:ue?ue.text:"var(--foreground)"},children:le.label})})]},le.mode)})})})]})]})})},$e=()=>e.jsx(ft,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Te?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:Te.name||ve()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:we()})]}),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:Je.length>0?Je.map(({key:q,icon:le,label:ee})=>_e(le,ee,`cap-${q}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),e.jsx("div",{className:"flex items-center gap-1.5",children:Re.length>0?Re.map(({key:q,icon:le,label:ee})=>_e(le,`${ee} input`,`input-${q}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:qe.length>0?qe.map(({key:q,icon:le,label:ee})=>_e(le,`${ee} output`,`output-${q}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),ut.map(q=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:q.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:q.value})]},q.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),Dt.map(q=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:q.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:q.value})]},q.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Mi(Te.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:Ai(Te.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),ot=()=>e.jsxs(gt,{delayDuration:1e3,children:[$?e.jsxs("button",{type:"button",onClick:()=>Y("model"),onTouchStart:()=>Mt("model"),onTouchEnd:Qe,onTouchCancel:Qe,className:T("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",C&&"flex-1","cursor-pointer hover:opacity-70",Ze),children:[n?e.jsx(Ut,{providerId:n,className:T(ze,"flex-shrink-0")}):e.jsx(Ns,{className:T(ze,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label typography-micro font-medium truncate min-w-0",C?"flex-1":"max-w-[220px]"),children:ve()})]}):e.jsxs(Kt,{open:Ce,onOpenChange:We,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Yt,{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",Ze),children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Ut,{providerId:n,className:T(ze,"flex-shrink-0")}),e.jsx(Ns,{className:T(ze,"text-primary/60 hidden")})]}):e.jsx(Ns,{className:T(ze,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label",dt,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:ve()},`${n}-${o}`)]})})}),e.jsxs(Xt,{className:"max-w-[300px]",children:[N.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(ms,{className:"h-3 w-3 flex-shrink-0 mr-2 text-primary"}),"Favorites"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ye,{outerClassName:"max-h-[320px] min-w-[200px]",children:N.map(({model:q,providerID:le,modelID:ee})=>{const ue=p(le,ee),tt=Ar(ue).map(Ve=>({...Ve,id:`cap-${Ve.key}`})),st=[...bs(ue,"input"),...bs(ue,"output")],he=Array.from(new Map(st.map(Ve=>[Ve.key,Ve])).values()).map(Ve=>({...Ve,id:`mod-${Ve.key}`})),Ke=[...tt,...he],it=Rt(ue?.limit?.context),Wt=Rt(ue?.limit?.output);return e.jsx(yt,{className:"typography-meta",onSelect:()=>{I(le,ee)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:ne(q)}),ue?.limit?.context||ue?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue?.limit?.context?`${it} ctx`:"",ue?.limit?.context&&ue?.limit?.output?" • ":"",ue?.limit?.output?`${Wt} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Ke.map(({id:Ve,icon:Pt,label:cs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":cs,role:"img",title:cs,children:e.jsx(Pt,{className:"h-3 w-3"})},Ve)),e.jsx("button",{onClick:Ve=>{Ve.preventDefault(),Ve.stopPropagation(),w(le,ee)},className:"model-favorite-button flex h-4 w-4 items-center justify-center text-yellow-500 hover:text-yellow-600","aria-label":"Unfavorite",title:"Remove from favorites",children:e.jsx(ms,{className:"h-3.5 w-3.5"})})]})]})},`fav-${le}-${ee}`)})})})]}),M.length>0&&e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(jn,{className:"h-3 w-3 flex-shrink-0 mr-2 text-muted-foreground"}),"Recent"]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ye,{outerClassName:"max-h-[320px] min-w-[200px]",children:M.map(({model:q,providerID:le,modelID:ee})=>{const ue=p(le,ee),tt=Ar(ue).map(Ve=>({...Ve,id:`cap-${Ve.key}`})),st=[...bs(ue,"input"),...bs(ue,"output")],he=Array.from(new Map(st.map(Ve=>[Ve.key,Ve])).values()).map(Ve=>({...Ve,id:`mod-${Ve.key}`})),Ke=[...tt,...he],it=Rt(ue?.limit?.context),Wt=Rt(ue?.limit?.output);return e.jsx(yt,{className:"typography-meta",onSelect:()=>{I(le,ee)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:ne(q)}),ue?.limit?.context||ue?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue?.limit?.context?`${it} ctx`:"",ue?.limit?.context&&ue?.limit?.output?" • ":"",ue?.limit?.output?`${Wt} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Ke.map(({id:Ve,icon:Pt,label:cs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":cs,role:"img",title:cs,children:e.jsx(Pt,{className:"h-3 w-3"})},Ve)),e.jsx("button",{onClick:Ve=>{Ve.preventDefault(),Ve.stopPropagation(),w(le,ee)},className:"model-favorite-button flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-yellow-600","aria-label":"Favorite",title:"Add to favorites",children:e.jsx(Zs,{className:"h-3.5 w-3.5"})})]})]})},`recent-${le}-${ee}`)})})})]}),(N.length>0||M.length>0)&&e.jsx(Hr,{}),s.map(q=>{const le=Array.isArray(q.models)?q.models:[];return le.length===0?e.jsxs(yt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Ut,{providerId:q.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),q.name," (No models)"]},q.id):e.jsxs(ur,{children:[e.jsxs(mr,{className:"typography-meta",children:[e.jsx(Ut,{providerId:q.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),q.name]}),e.jsx(fr,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ye,{outerClassName:"max-h-[320px] min-w-[200px]",children:le.map(ee=>{const ue=p(q.id,ee.id),tt=Ar(ue).map(Ve=>({...Ve,id:`cap-${Ve.key}`})),st=[...bs(ue,"input"),...bs(ue,"output")],he=Array.from(new Map(st.map(Ve=>[Ve.key,Ve])).values()).map(Ve=>({...Ve,id:`mod-${Ve.key}`})),Ke=[...tt,...he],it=Rt(ue?.limit?.context),Wt=Rt(ue?.limit?.output);return e.jsx(yt,{className:"typography-meta",onSelect:()=>{I(q.id,ee.id)},children:e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsxs("div",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:ne(ee)}),ue?.limit?.context||ue?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ue?.limit?.context?`${it} ctx`:"",ue?.limit?.context&&ue?.limit?.output?" • ":"",ue?.limit?.output?`${Wt} out`:""]}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Ke.map(({id:Ve,icon:Pt,label:cs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":cs,role:"img",title:cs,children:e.jsx(Pt,{className:"h-3 w-3"})},Ve)),e.jsx("button",{onClick:Ve=>{Ve.preventDefault(),Ve.stopPropagation(),w(q.id,ee.id)},className:T("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",D(q.id,ee.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":D(q.id,ee.id)?"Unfavorite":"Favorite",title:D(q.id,ee.id)?"Remove from favorites":"Add to favorites",children:D(q.id,ee.id)?e.jsx(ms,{className:"h-3.5 w-3.5"}):e.jsx(Zs,{className:"h-3.5 w-3.5"})})]})]})},ee.id)})})})]},q.id)})]})]}),$e()]}),at=()=>{if(!O)return e.jsx(ft,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"No agent selected."})});const q=Object.entries(O.tools||{}).filter(([,he])=>he).map(([he])=>he).sort(),le=!!(O.prompt&&O.prompt.trim().length>0),ee=O.model?.providerID&&O.model?.modelID,ue=O.temperature!==void 0||O.topP!==void 0,tt=he=>P(he==="full"||he==="allow"||he==="deny"?he:"ask","h-3.5 w-3.5"),st=he=>he==="full"?"Full":he==="allow"?"Allow":he==="deny"?"Deny":"Ask";return e.jsx(ft,{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:Pe(O.name)}),O.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:O.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:O.mode==="primary"?"Primary":O.mode==="subagent"?"Subagent":O.mode==="all"?"All":"—"})]}),(ee||ue)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),ee?e.jsxs("span",{className:"typography-meta text-foreground",children:[O.model.providerID," / ",O.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),ue&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[O.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:O.temperature})]}),O.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:O.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Tools"}),q.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:q.map(he=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:he},he))}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"All enabled"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[tt(O.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:st(O.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:[tt(typeof O.permission?.bash=="string"?O.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:st(typeof O.permission?.bash=="string"?O.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:[tt(O.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:st(O.permission?.webfetch)})]})]})]}),le&&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(un,{className:"h-4 w-4 text-foreground"})]})]})})},He=()=>$?e.jsxs("button",{type:"button",onClick:()=>Y("agent"),onTouchStart:()=>Mt("agent"),onTouchEnd:Qe,onTouchCancel:Qe,className:T("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ze,"cursor-pointer hover:opacity-70",$&&"ml-1"),children:[e.jsx(Br,{className:T(ze,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${_s(a).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",dt,"font-medium truncate min-w-0"),style:a?{color:`var(${_s(a).var})`}:void 0,children:me()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(gt,{delayDuration:1e3,children:[e.jsxs(Kt,{children:[e.jsx(xt,{asChild:!0,children:e.jsx(Yt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ze),children:[e.jsx(Br,{className:T(ze,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${_s(a).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",dt,"font-medium min-w-0 truncate",E?"max-w-[220px]":void 0),style:a?{color:`var(${_s(a).var})`}:void 0,children:me()})]})})}),e.jsxs(Xt,{align:"end",children:[t.filter(q=>on(q.mode)).map(q=>e.jsx(yt,{className:"typography-meta",onSelect:()=>Et(q.name),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("h-1 w-1 rounded-full agent-dot",_s(q.name).class)}),e.jsx("span",{className:"font-medium",children:Pe(q.name)})]}),q.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:q.description})]})},q.name)),e.jsx(Hr,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:Ge,onClick:()=>{Ge||B(q=>!q)},className:T("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",Ge?"cursor-not-allowed opacity-60":void 0),"aria-expanded":oe,"aria-controls":J,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:Ue?Ue.text:"var(--foreground)"},children:Se})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!Ue&&"text-muted-foreground"),style:Ue?{color:Ue.text}:void 0,children:P(Oe)}),e.jsx(vt,{className:T("h-3.5 w-3.5 transition-transform text-muted-foreground",oe?"rotate-180":"")})]})]}),oe&&!Ge&&e.jsx("div",{id:J,className:"flex flex-col gap-1 rounded-xl border border-border/40 px-2 py-2 bg-transparent",role:"group","aria-label":"Edit permission options",children:ct.map(q=>{const le=q.mode===Oe,ee=Er(q.mode);return e.jsxs("button",{type:"button",disabled:q.disabled,onClick:()=>se(q.mode),className:T("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",q.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",le?"bg-primary/10":void 0),style:le&&ee?{backgroundColor:ee.background??void 0}:void 0,children:[P(q.mode,Be),e.jsx("span",{className:"typography-meta font-medium",style:{color:ee?ee.text:"var(--foreground)"},children:q.label})]},q.mode)})})]})]})]}),at()]})}),et=T("@container/model-controls flex items-center min-w-0",mt,C&&"w-full",r);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:et,children:[e.jsx("div",{className:T("flex items-center min-w-0",C?"flex-1 min-w-0 overflow-hidden":"flex-1 min-w-0 justify-end"),children:ot()}),e.jsx("div",{className:T("flex items-center min-w-0",mt,C&&"flex-shrink-0"),children:He()})]}),U(),Ie(),Ct(),Ft()]})},Ph=r=>r?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(r):!0,Rh=(r,s)=>{if(typeof r!="string"||r.length===0)return{sanitizedText:r,mention:null};const t=s.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!r.includes("#"))return{sanitizedText:r,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(r))!==null;){const c=i.index,d=c+i[0].length,u=c>0?r[c-1]:null;if(!Ph(u))continue;const p={name:o.name,source:{value:i[0],start:c,end:d}};n||(n=p)}}return n?{sanitizedText:r,mention:n}:{sanitizedText:r,mention:null}},vc=r=>({id:r.id,content:r.content,status:r.status||"pending",priority:r.priority||"medium"}),Ro=Ot()(Ht((r,s)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){r({isLoading:!0});try{const o=(await Ae.getSessionTodos(t)).map(vc);r(a=>{const i=new Map(a.sessionTodos);return i.set(t,o),{sessionTodos:i,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),r({isLoading:!1})}}},updateTodos:(t,n)=>{r(o=>{const a=new Map(o.sessionTodos);return a.set(t,n),{sessionTodos:a}})},getTodosForSession:t=>s().sessionTodos.get(t)||[],clearTodos:t=>{r(n=>{const o=new Map(n.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),Lh=(r,s)=>{const t=s.map(vc);Ro.getState().updateTodos(r,t)},Ei=[{variant:"shine",component:({children:r,className:s,...t})=>e.jsx(Sr.span,{...t,className:T("bg-[linear-gradient(110deg,#bfbfbf,35%,#000,50%,#bfbfbf,75%,#bfbfbf)] dark:bg-[linear-gradient(110deg,#404040,35%,#fff,50%,#404040,75%,#404040)]","bg-[length:200%_100%] bg-clip-text text-transparent",s),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:r})},{variant:"generate-effect",component:({children:r,className:s,...t})=>typeof r!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:r.split("").map((n,o)=>de.createElement(Sr.span,{...t,key:n+String(o),className:T("inline-block whitespace-pre text-primary-foreground",s),initial:{opacity:0,filter:"blur(4px)",rotateX:90,y:5},whileInView:{opacity:1,filter:"blur(0px)",rotateX:0,y:0},transition:{ease:"easeOut",duration:.3,delay:o*.015},viewport:{once:!0}},n))})},{variant:"glitch",component:({children:r,className:s,...t})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...t,className:T("invisible",s),children:r}),e.jsx("span",{...t,className:T("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",s),children:r}),e.jsx("span",{...t,className:T("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",s),children:r})]})},{variant:"hover-enter",component:({children:r,className:s,...t})=>{if(typeof r!="string")return null;const n=.25,o=.025,a=r.split("").map(i=>i===" "?" ":i);return e.jsxs(Sr.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(Sr.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))}),e.jsx("div",{className:T("absolute inset-0"),children:a.map((i,c)=>e.jsx(Sr.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:i},String(c)))})]})}},{variant:"shake",component:({children:r,className:s,...t})=>e.jsx("span",{...t,className:T("text-primary-muted hover:animate-text-shake",s),children:r})},{variant:"hover-decoration",component:({children:r,className:s,...t})=>e.jsx("div",{className:T("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:e.jsx("span",{...t,className:T("text-primary-muted",s),children:r})})}];function co({variant:r="shine",className:s,...t}){const a=Ei.find(i=>i.variant===r)?.component||Ei[0].component;return e.jsx(cl,{children:e.jsx(a,{...t,className:s})})}const _h=2e3,Bh=1500;function Oh({statusText:r,isWaitingForPermission:s,wasAborted:t,completionId:n,isComplete:o}){const[a,i]=de.useState(null),[c,d]=de.useState(!1),[u,p]=de.useState(!1),[f,m]=de.useState(!1),[h,g]=de.useState(null),[x,y]=de.useState(!1),b=de.useRef(0),k=de.useRef([]),j=de.useRef(!1),v=de.useRef(null),S=de.useRef(null),w=de.useRef(null),D=de.useRef(null),A=de.useRef(0),N=de.useRef(null),M=de.useRef(!1),C=de.useRef(!1),E=de.useRef(!1),F=de.useRef(!0),$=de.useRef(null),R=de.useRef(null),Y=(W,ce)=>{if(v.current&&(clearTimeout(v.current),v.current=null),S.current&&(clearTimeout(S.current),S.current=null),w.current&&(clearTimeout(w.current),w.current=null),W==="aborted"){i(null),d(!1),m(!1),g("aborted"),y(!1),N.current="aborted",M.current=!0,C.current=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>p(!0)):p(!0);return}g(null),m(!1),N.current=W,M.current=!0,a!==null&&a!==W&&(y(!0),w.current=setTimeout(()=>{y(!1),w.current=null},150)),i(W),d(ce),u||(typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{p(!0)}):p(!0))};if(de.useEffect(()=>{const W=Date.now();r?(j.current=!1,a?(r!==a||!!s!==c)&&k.current.push({status:r,permission:!!s}):(Y(r,!!s),b.current=W,k.current=[])):j.current=!0},[r,s,a,c,t]),de.useEffect(()=>{t&&(C.current=!0)},[t]),de.useEffect(()=>{E.current=!!o},[o]),de.useEffect(()=>{o&&(j.current=!0)},[o]),de.useEffect(()=>{const W=Me=>{if(f)return;const Le=N.current!==null||M.current;Me&&Le?(m(!1),p(!0),i(null),d(!1),g(Me),N.current=null,y(!1),Me==="success"&&n&&($.current=n),R.current=Date.now(),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{p(!1),g(null),M.current=!1,S.current=null},Bh)):(m(!0),p(!1),g(null),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{i(null),d(!1),m(!1),M.current=!1,N.current=null,v.current=null},180)),C.current=!1},Ne=Me=>{if(Me-A.current<150){D.current=requestAnimationFrame(Ne);return}A.current=Me;const Le=Date.now(),ye=Le-b.current,ie=j.current&&E.current;if(!ie&&k.current.length>0&&ye<_h){D.current=requestAnimationFrame(Ne);return}if(j.current&&C.current)j.current=!1,k.current=[],W("aborted");else if(!ie&&k.current.length>0){const Ce=k.current[k.current.length-1];Y(Ce.status,Ce.permission),b.current=Le,k.current=[]}else if(j.current){j.current=!1,k.current.length>0&&(M.current=!0),k.current=[];let Ce=null;if(C.current?Ce="aborted":E.current&&(Ce="success",M.current=!0),Ce==="success"&&n&&$.current===n){i(null),d(!1),m(!1),p(!1),g(null),k.current=[],M.current=!1,N.current=null,j.current=!1,C.current=!1,D.current=requestAnimationFrame(Ne);return}W(Ce)}D.current=requestAnimationFrame(Ne)};return D.current=requestAnimationFrame(Ne),()=>{D.current!==null&&(cancelAnimationFrame(D.current),D.current=null)}},[f]),de.useEffect(()=>()=>{v.current&&clearTimeout(v.current),S.current&&clearTimeout(S.current),w.current&&clearTimeout(w.current)},[]),de.useEffect(()=>{if(typeof window>"u")return;F.current=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0;const W=()=>{F.current=!0},ce=()=>{F.current=!1};return window.addEventListener("focus",W),window.addEventListener("blur",ce),()=>{window.removeEventListener("focus",W),window.removeEventListener("blur",ce)}},[]),de.useEffect(()=>{const W=()=>{if(typeof document>"u"||typeof Date>"u"||document.visibilityState!=="visible")return;const ce=R.current;(h!==null||a!==null)&&ce&&Date.now()-ce>500&&(i(null),d(!1),m(!1),p(!1),g(null),k.current=[],M.current=!1,N.current=null,j.current=!1,C.current=!1)};return document.addEventListener("visibilitychange",W),window.addEventListener("focus",W),()=>{document.removeEventListener("visibilitychange",W),window.removeEventListener("focus",W)}},[a,h]),!a&&h===null)return null;let Z;h==="success"?Z="Done":h==="aborted"?Z="Aborted":a?Z=a.charAt(0).toUpperCase()+a.slice(1):Z="Working";const z=c?"assertive":"polite",G=h===null?`${Z}...`:Z;return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${u&&!f?"opacity-100":"opacity-0"}`,role:"status","aria-live":z,"aria-label":Z,"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 transition-opacity duration-150",style:{opacity:x?.6:1},children:G}),h==="success"&&e.jsx(co,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150",style:{opacity:x?.6:1},children:"Done"}),h==="aborted"&&e.jsx(co,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150 text-status-error",style:{opacity:x?.6:1},children:"Aborted"})]})})}const Ti={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},$h=({todo:r})=>{const s=Ti[r.status]||Ti.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:T("flex-1 typography-ui-label",s.textClassName),children:r.content})})},Ii=[],zh=({isWorking:r,statusText:s,isWaitingForPermission:t,wasAborted:n,abortActive:o,completionId:a,isComplete:i,showAbort:c,onAbort:d,showAbortStatus:u})=>{const[p,f]=l.useState(!1),m=ge(C=>C.currentSessionId),h=Ro(C=>m?C.sessionTodos.get(m)??Ii:Ii),g=Ro(C=>C.loadTodos),{isMobile:x}=Fe(),y=x||ss();l.useEffect(()=>{m&&g(m)},[m,g]);const b=l.useMemo(()=>{const C={in_progress:0,pending:1,completed:2,cancelled:3};return[...h].filter(E=>E.status!=="cancelled").sort((E,F)=>C[E.status]-C[F.status])},[h]),k=l.useMemo(()=>b.find(C=>C.status==="in_progress")||b.find(C=>C.status==="pending")||null,[b]),j=l.useMemo(()=>{const C=h.filter(F=>F.status!=="cancelled").length;return{completed:h.filter(F=>F.status==="completed").length,total:C}},[h]),v=b.length>0,S=!u&&(n||!o),w=r||v||u,D=l.useRef(null);if(l.useEffect(()=>{if(!p)return;const C=E=>{D.current&&!D.current.contains(E.target)&&f(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[p]),!w)return null;const A=()=>f(C=>!C),N=c&&d?e.jsx("button",{type:"button",onClick:d,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(hr,{size:18,"aria-hidden":"true"})}):null,M=v?e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!y&&k?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:k.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[j.completed,"/",j.total]}),p?e.jsx(zn,{className:"h-3.5 w-3.5"}):e.jsx(vt,{className:"h-3.5 w-3.5"})]}):null;return e.jsx("div",{className:"chat-column mb-1",style:{containerType:"inline-size"},children:e.jsxs("div",{className:"flex items-center justify-between pr-[2ch] py-0.5 gap-2 h-[1.2rem]",children:[e.jsx("div",{className:"flex-1 flex items-center overflow-hidden min-w-0",children:u?e.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-[2ch]",children:e.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[e.jsx(hr,{size:16,"aria-hidden":"true"}),"Aborted"]})}):S?e.jsx(Oh,{statusText:s,isWaitingForPermission:t,wasAborted:n,completionId:a??null,isComplete:i},m??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:D,children:[N,M,p&&v&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:T("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-muted shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[j.completed,"/",j.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($h,{todo:C},C.id))})]})]})]})})},Hh=r=>!r||typeof r!="object"?!1:!!r.synthetic,Lo=r=>!Array.isArray(r)||r.length===0?!1:r.every(s=>Hh(s)),Wh={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Uh(r){const s=ge(t=>!r||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(r)??"idle");return l.useMemo(()=>{if(s==="idle")return Wh;const t=s==="busy",n=s==="cooldown";return{phase:s,isWorking:t||n,isBusy:t,isCooldown:n}},[s])}function jc(){const r=ge(s=>s.currentSessionId);return Uh(r)}const Vh={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},Fi=r=>r.role==="assistant",Gh=r=>r.type==="reasoning",Sc=r=>r.type==="text",Pi=r=>{if(Sc(r))return r.text;const s=r;if(typeof s.text=="string")return s.text;if(typeof s.content=="string")return s.content;if(typeof s.value=="string")return s.value},Ri=r=>(Sc(r)||Gh(r),r.time),qh=r=>{if(r.tool)return r.tool;const s=r;return typeof s.name=="string"?s.name:"tool"};function kc(){const{currentSessionId:r,messages:s,permissions:t,sessionAbortFlags:n}=ge(Zo(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=jc(),c=l.useMemo(()=>r?s.get(r)??[]:[],[r,s]),d=l.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const h=c.filter(v=>Fi(v.info)&&!Lo(v.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const g=[...h].sort((v,S)=>{const w=typeof v.info.time?.created=="number"?v.info.time.created:null,D=typeof S.info.time?.created=="number"?S.info.time.created:null;return w!==null&&D!==null&&w!==D?w-D:v.info.id.localeCompare(S.info.id)}),x=g[g.length-1];let y,b;const k=new Set(["edit","write"]);for(let v=(x.parts??[]).length-1;v>=0;v-=1){const S=x.parts?.[v];if(S)switch(S.type){case"reasoning":{const w=S.time??Ri(S);(!w||typeof w.end>"u")&&!y&&(y="reasoning");break}case"tool":{const w=S.state?.status;if((w==="running"||w==="pending")&&!y){const D=qh(S);k.has(D)?y="editing":(y="tool",b=D)}break}case"text":{const w=Pi(S)??"";if(typeof w=="string"&&w.trim().length>0){const D=Ri(S);(!D||typeof D.end>"u")&&!y&&(y="text")}break}}}const j=y==="editing"?"editing":y==="tool"&&b?`using ${b}`:y==="reasoning"?"thinking":y==="text"?"composing":"working";return{activePartType:y,activeToolName:b,statusText:j}},[c]),u=l.useMemo(()=>{const h=r,g=h?n?.get(h)??null:null,x=!!(g&&!g.acknowledged);return{wasAborted:x,abortActive:x}},[r,n]),p=l.useMemo(()=>{if(u.wasAborted)return{...Vh,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]),f=l.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const g=c.filter(b=>Fi(b.info)&&!Lo(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 k=Pi(b)??"";typeof k=="string"&&k.trim().length>0&&(y+=k.length)}),{isActive:h,characterCount:y}},[c,a,d.activePartType]),m=l.useMemo(()=>{if(p.wasAborted||p.abortActive)return p;const h=r;return(h?t?.get(h)??[]:[]).length>0?{...p,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:p},[r,t,p]);return{forming:f,working:m}}const Kh=8,Yh=r=>r==="primary"||r==="all"||r===void 0||r===null,uo=({onOpenSettings:r,scrollToBottom:s})=>{const[t,n]=l.useState(""),[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(""),[p,f]=l.useState(!1),[m,h]=l.useState(""),[g,x]=l.useState(!1),[y,b]=l.useState(""),[k,j]=l.useState(null),v=l.useRef(null),S=l.useRef(null),w=l.useRef(null),D=l.useRef(null),A=l.useRef(null),N=ge(U=>U.sendMessage),M=ge(U=>U.currentSessionId),C=ge(U=>U.abortCurrentOperation),E=ge(U=>U.acknowledgeSessionAbort),F=ge(U=>U.abortPromptSessionId),$=ge(U=>U.abortPromptExpiresAt),R=ge(U=>U.clearAbortPrompt),Y=ge(U=>U.attachedFiles),Z=ge(U=>U.addAttachedFile),z=ge(U=>U.addServerFile),G=ge(U=>U.clearAttachedFiles),W=ge(U=>U.saveSessionAgentSelection),{currentProviderId:ce,currentModelId:Ne,currentAgentName:Me,agents:Le,setAgent:ye}=St(),{isMobile:ie}=Fe(),{working:je}=kc(),[Ce,We]=l.useState(!1),oe=l.useRef(null),B=l.useRef(!1),J=l.useRef(!1),O=l.useCallback(U=>{if(!ie||U.pointerType!=="touch")return;const Ie=v.current;if(!Ie||document.activeElement===Ie)return;U.preventDefault(),U.stopPropagation();const $e=document.scrollingElement;$e&&$e.scrollTop!==0&&($e.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Ie.focus({preventScroll:!0})}catch{Ie.focus()}const ot=Ie.value.length;try{Ie.setSelectionRange(ot,ot)}catch{}},[ie]),X=l.useMemo(()=>{if(Me)return Le.find(U=>U.name===Me)},[Le,Me]),_=l.useMemo(()=>{const U=X?.permission?.edit;let Ie="ask";(U==="allow"||U==="ask"||U==="deny"||U==="full")&&(Ie=U);const $e=X?X.tools?.edit!==!1:!1;return(!X||!$e)&&(Ie="deny"),Ie},[X]),te=ge(l.useCallback(U=>!M||!Me?void 0:U.sessionAgentEditModes.get(M)?.get(Me),[M,Me])),K=X?.permission?.webfetch,ae=X?.permission?.bash,be=l.useMemo(()=>wc({agentDefaultEditMode:_,webfetchPermission:K,bashPermission:ae}),[_,K,ae]),fe=!!(M&&Me),H=l.useMemo(()=>fe&&te&&be.modeAvailability[te]?te:be.cascadeDefaultMode,[be,fe,te]),V=l.useMemo(()=>Er(H),[H]),L=l.useCallback(U=>ss()?`color-mix(in srgb, ${U} 55%, transparent)`:U,[]),Q=l.useMemo(()=>{const U=ss()?1:2;if(!V)return{borderWidth:U};const Ie=V.border??V.text;return{borderColor:L(Ie),borderWidth:U}},[V,L]),ke=t.trim()||Y.length>0,De=je.isWorking,Oe=l.useMemo(()=>M?F===M&&!!$:!1,[F,$,M]),ct=async U=>{if(U?.preventDefault(),!ke||!M)return;const Ie=t.replace(/^\n+|\n+$/g,"");s?.({instant:!0,force:!0});const $e=Ie.trimStart();if($e.startsWith("/")&&$e.slice(1).trim().split(/\s+/)[0]?.toLowerCase()==="summarize"&&s?.({instant:!0,force:!0}),!ce||!Ne){console.warn("Cannot send message: provider or model not selected");return}const{sanitizedText:ot,mention:at}=Rh(Ie,Le),He=at?.name,et=Y.map(q=>({...q}));et.length>0&&G(),n(""),ie&&v.current?.blur(),await N(ot,ce,Ne,Me,et,He).catch(q=>{const le=q instanceof Error?q.message:typeof q=="string"?q:String(q??""),ee=le.toLowerCase();console.error("Message send failed:",le||q),!(ee.includes("timeout")||ee.includes("timed out")||ee.includes("may still be processing")||ee.includes("being processed")||ee.includes("failed to fetch")||ee.includes("networkerror")||ee.includes("network error")||ee.includes("gateway timeout")||ee==="failed to send message")&&(et.length>0&&Bs.setState({attachedFiles:et}),xe.error(le||"Message failed to send. Attachments restored."))}),ie||v.current?.focus()},Ue=U=>{if(p&&D.current&&(U.key==="Enter"||U.key==="ArrowUp"||U.key==="ArrowDown"||U.key==="Escape"||U.key==="Tab")){U.preventDefault(),D.current.handleKeyDown(U.key);return}if(g&&A.current&&(U.key==="Enter"||U.key==="ArrowUp"||U.key==="ArrowDown"||U.key==="Escape"||U.key==="Tab")){U.preventDefault(),A.current.handleKeyDown(U.key);return}if(i&&w.current&&(U.key==="Enter"||U.key==="ArrowUp"||U.key==="ArrowDown"||U.key==="Escape"||U.key==="Tab")){U.preventDefault(),w.current.handleKeyDown(U.key);return}if(U.key==="Tab"&&!p&&!i){U.preventDefault(),Ze();return}U.key==="Enter"&&!U.shiftKey&&!ie&&(U.preventDefault(),ct())},Ge=l.useCallback(()=>{oe.current&&(clearTimeout(oe.current),oe.current=null),We(!0),oe.current=setTimeout(()=>{We(!1),oe.current=null},1800)},[]),Xe=l.useCallback(()=>{R(),Ge(),C()},[C,R,Ge]),Ze=()=>{const U=Le.filter(at=>Yh(at.mode));if(U.length<=1)return;const $e=(U.findIndex(at=>at.name===Me)+1)%U.length,ot=U[$e];ye(ot.name),M&&W(M,ot.name)},Be=l.useCallback(()=>{const U=v.current;if(!U)return;U.style.height="auto";const Ie=U.ownerDocument?.defaultView,$e=Ie?Ie.getComputedStyle(U):null,ot=$e?parseFloat($e.lineHeight):NaN,at=$e?parseFloat($e.paddingTop):NaN,He=$e?parseFloat($e.paddingBottom):NaN,et=22,le=Number.isNaN(at)||Number.isNaN(He)?16:at+He,ue=(Number.isNaN(ot)?et:ot)*Kh+le,tt=U.scrollHeight||U.offsetHeight,st=Math.min(tt,ue);U.style.height=`${st}px`,U.style.maxHeight=`${ue}px`,j(he=>he&&he.height===st&&he.maxHeight===ue?he:{height:st,maxHeight:ue})},[]);l.useLayoutEffect(()=>{Be()},[Be,t,ie]);const ze=l.useCallback((U,Ie)=>{if(U.startsWith("/")){const He=U.indexOf(" "),et=U.indexOf(`
|
|
67
|
-
`),q=Math.min(He===-1?U.length:He,et===-1?U.length:et);if(Ie<=q&&He===-1){const le=U.substring(1,q);h(le),f(!0),c(!1),x(!1)}else f(!1);return}f(!1);const $e=U.substring(0,Ie),ot=$e.lastIndexOf("#");if(ot!==-1){const He=ot>0?$e[ot-1]:null,et=$e.substring(ot+1),q=et.includes(" ")||et.includes(`
|
|
68
|
-
`);if((!He||/\s/.test(He))&&!q){b(et),x(!0),c(!1);return}}x(!1),b("");const at=$e.lastIndexOf("@");if(at!==-1){const He=$e.substring(at+1);!He.includes(" ")&&!He.includes(`
|
|
69
|
-
`)?(u(He),c(!0)):c(!1)}else c(!1)},[b,h,u,x,f,c]),dt=l.useCallback(U=>{if(!U)return;const Ie=v.current;if(!Ie){const et=t+U;n(et),ze(et,et.length),requestAnimationFrame(()=>Be());return}const $e=Ie.selectionStart??t.length,ot=Ie.selectionEnd??t.length,at=`${t.substring(0,$e)}${U}${t.substring(ot)}`;n(at);const He=$e+U.length;requestAnimationFrame(()=>{const et=v.current;et&&(et.selectionStart=He,et.selectionEnd=He),Be()}),ze(at,He)},[Be,t,ze]),mt=U=>{const Ie=U.target.value,$e=U.target.selectionStart??Ie.length;n(Ie),Be(),ze(Ie,$e)},Se=l.useCallback(async U=>{const Ie=new Map;Array.from(U.clipboardData.files||[]).forEach(He=>{He.type.startsWith("image/")&&Ie.set(`${He.name}-${He.size}`,He)}),Array.from(U.clipboardData.items||[]).forEach(He=>{if(He.kind==="file"&&He.type.startsWith("image/")){const et=He.getAsFile();et&&Ie.set(`${et.name}-${et.size}`,et)}});const $e=Array.from(Ie.values());if($e.length===0||!M)return;U.preventDefault();const ot=U.clipboardData.getData("text");ot&&dt(ot);let at=0;for(const He of $e){const et=ge.getState().attachedFiles.length;try{await Z(He),ge.getState().attachedFiles.length>et&&(at+=1)}catch(q){console.error("Clipboard image attach failed",q),xe.error(q instanceof Error?q.message:"Failed to attach image from clipboard")}}at>0&&xe.success(`Attached ${at} image${at>1?"s":""} from clipboard`)},[Z,M,dt]),P=U=>{const Ie=v.current?.selectionStart||0,ot=t.substring(0,Ie).lastIndexOf("@");if(ot!==-1){const at=t.substring(0,ot)+U.name+t.substring(Ie);n(at)}c(!1),u(""),v.current?.focus()},se=U=>{const $e=v.current?.selectionStart??t.length,at=t.substring(0,$e).lastIndexOf("#");if(at!==-1){const He=t.substring(0,at)+`#${U} `+t.substring($e);n(He);const et=at+U.length+2;requestAnimationFrame(()=>{v.current&&(v.current.selectionStart=et,v.current.selectionEnd=et),Be(),ze(He,et)})}x(!1),b(""),v.current?.focus()},re=U=>{n(`/${U.name} `);const Ie=v.current;Ie&&(Ie._commandMetadata=U),f(!1),h(""),setTimeout(()=>{v.current&&(v.current.focus(),v.current.setSelectionRange(v.current.value.length,v.current.value.length))},0)};l.useEffect(()=>{M&&v.current&&!ie&&v.current.focus()},[M,ie]),l.useEffect(()=>{F&&F!==M&&R()},[F,M,R]);const pe=U=>{U.preventDefault(),U.stopPropagation(),M&&!o&&a(!0)},Te=U=>{U.preventDefault(),U.stopPropagation(),U.currentTarget===U.target&&a(!1)},Je=async U=>{if(U.preventDefault(),U.stopPropagation(),a(!1),!M)return;const Ie=Array.from(U.dataTransfer.files);let $e=0;for(const ot of Ie){const at=ge.getState().attachedFiles.length;try{await Z(ot),ge.getState().attachedFiles.length>at&&($e+=1)}catch(He){console.error("File attach failed",He),xe.error(He instanceof Error?He.message:"Failed to attach file")}}$e>0&&xe.success(`Attached ${$e} file${$e>1?"s":""}`)},Re=l.useCallback(async U=>{let Ie=0;for(const $e of U){const ot=ge.getState().attachedFiles.length;try{await z($e.path,$e.name),ge.getState().attachedFiles.length>ot&&(Ie+=1)}catch(at){console.error("Server file attach failed",at),xe.error(at instanceof Error?at.message:"Failed to attach file")}}Ie>0&&xe.success(`Attached ${Ie} file${Ie>1?"s":""}`)},[z]),qe=l.useRef(null),[ut,Dt]=l.useState(!1),pt=l.useCallback(async U=>{let Ie=0;const $e=Array.isArray(U)?U:Array.from(U);for(const ot of $e){const at=ge.getState().attachedFiles.length;try{await Z(ot),ge.getState().attachedFiles.length>at&&(Ie+=1)}catch(He){console.error("File attach failed",He),xe.error(He instanceof Error?He.message:"Failed to attach file")}}Ie>0&&xe.success(`Attached ${Ie} file${Ie>1?"s":""}`)},[Z]),kt=l.useCallback(async()=>{try{const Ie=await(await fetch("/api/vscode/pick-files")).json(),$e=Array.isArray(Ie?.files)?Ie.files:[],ot=Array.isArray(Ie?.skipped)?Ie.skipped:[];if(ot.length>0){const He=ot.map(et=>`${et?.name||"file"}: ${et?.reason||"skipped"}`).join(`
|
|
70
|
-
`);xe.error(`Some files were skipped:
|
|
71
|
-
${He}`)}const at=$e.map(He=>{if(!He?.dataUrl)return null;try{const[et,q]=He.dataUrl.split(","),le=He.mimeType||et?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!q)return null;const ee=atob(q),ue=new Uint8Array(ee.length);for(let st=0;st<ee.length;st++)ue[st]=ee.charCodeAt(st);const tt=new Blob([ue],{type:le});return new File([tt],He.name||"file",{type:le})}catch(et){return console.error("Failed to decode VS Code picked file",et),null}}).filter(Boolean);at.length>0&&await pt(at)}catch(U){console.error("VS Code file pick failed",U),xe.error(U instanceof Error?U.message:"Failed to pick files in VS Code")}},[pt]),bt=l.useCallback(()=>{if(ss()){kt();return}qe.current?.click()},[kt]),ht=l.useCallback(async U=>{const Ie=U.target.files;Ie&&(await pt(Ie),U.target.value="")},[pt]),Et="gap-x-1.5 gap-y-0",I=ss(),ne=ie?"px-1.5 py-1.5":I?"px-1.5 py-1":"px-2.5 py-1.5",we=ie?"h-9 w-9":I?"h-[22px] w-[22px]":"h-7 w-7",ve=ie?"h-5 w-5":I?"h-4 w-4":"h-[18px] w-[18px]",me=T(we,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),_e=!ie&&Oe&&De?e.jsx("button",{type:"button",onClick:Xe,className:T(me,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(hr,{className:T(ve)})}):e.jsx("button",{type:ie?"button":"submit",disabled:!ke||!M,onPointerDownCapture:U=>{!ie||U.pointerType!=="touch"||!ke||!M||(J.current=!0,U.preventDefault(),U.stopPropagation(),ct())},onClick:U=>{if(ie){if(J.current){J.current=!1;return}U.preventDefault(),ct()}},className:T(me,ke&&M?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(ru,{className:T(ve)})}),nt=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:qe,type:"file",multiple:!0,className:"hidden",onChange:ht,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(Nh,{onFilesSelected:Re,multiSelect:!0,presentation:ie||I?"modal":"dropdown",open:ut,onOpenChange:Dt,children:ie||I?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Kt,{children:[e.jsx(Yt,{asChild:!0,children:e.jsx("button",{type:"button",className:me,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(nu,{className:T(ve,"text-current")})})}),e.jsxs(Xt,{align:"start",children:[e.jsxs(yt,{onSelect:()=>{requestAnimationFrame(()=>bt())},children:[e.jsx(So,{}),"Attach files"]}),e.jsxs(yt,{onSelect:()=>{requestAnimationFrame(()=>{Dt(!0)})},children:[e.jsx(ou,{}),"Attach from project"]})]})]})]})]}),Mt=r?e.jsx("button",{type:"button",onClick:r,className:me,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(Br,{className:T(ve,"text-current")})}):null,Qe=e.jsxs(e.Fragment,{children:[nt,Mt]}),Ct=je.statusText;l.useEffect(()=>{const U=!!je.wasAborted;!B.current&&U&&!Ce&&(Ge(),M&&E(M)),B.current=U},[E,M,Ce,Ge,je.wasAborted]),l.useEffect(()=>()=>{oe.current&&(clearTimeout(oe.current),oe.current=null)},[]);const Ft=ie&&De;return e.jsxs("form",{onSubmit:ct,className:"pt-0 pb-4 bottom-safe-area",children:[e.jsx(zh,{isWorking:je.isWorking,statusText:Ct,isWaitingForPermission:je.isWaitingForPermission,wasAborted:je.wasAborted,abortActive:je.abortActive,completionId:je.lastCompletionId,isComplete:je.isComplete,showAbort:Ft,onAbort:Xe,showAbortStatus:Ce}),e.jsxs("div",{ref:S,className:T("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:pe,onDragLeave:Te,onDrop:Je,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:me,onClick:()=>bt(),title:"Attach files","aria-label":"Attach files",children:e.jsx(So,{className:T(ve,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(wh,{}),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:Q,children:[p&&e.jsx(xc,{ref:D,searchQuery:m,onCommandSelect:re,onClose:()=>f(!1)}),g&&e.jsx(yc,{ref:A,searchQuery:y,onAgentSelect:se,onClose:()=>x(!1)}),i&&e.jsx(vh,{ref:w,searchQuery:d,onFileSelect:P,onClose:()=>c(!1)}),e.jsx(tr,{ref:v,"data-chat-input":"true",value:t,onChange:mt,onKeyDown:Ue,onPaste:Se,onPointerDownCapture:O,placeholder:M?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!M,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",ie?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:k?`${k.height}px`:void 0,maxHeight:k?`${k.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:T("rounded-b-xl bg-transparent",ne,ie?"flex items-center gap-x-1.5":T("flex items-center justify-between",Et)),"data-chat-input-footer":"true",children:ie?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:Qe}),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(Di,{className:T("w-full flex items-center justify-end min-w-0")})}),_e]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("flex items-center flex-shrink-0",Et),children:Qe}),e.jsxs("div",{className:T("flex items-center flex-1 justify-end",Et,"md:gap-x-3"),children:[e.jsx(Di,{className:T("flex-1 min-w-0 justify-end")}),_e]})]})})]})]})]})};function mo({className:r,...s}){return e.jsx("div",{"data-slot":"skeleton",className:T("bg-accent animate-pulse rounded-xl",r),...s})}const Li=({className:r="",width:s=70,height:t=70,isAnimated:n=!1})=>{const o=ua();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const i=a?"white":"black",c="shimmer-gradient";return e.jsxs("svg",{width:s,height:t,viewBox:"0 0 70 70",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:r,role:"img","aria-label":"OpenChamber logo",children:[n&&e.jsx("defs",{children:e.jsxs("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:i,stopOpacity:"1"}),e.jsx("stop",{offset:"50%",stopColor:i,stopOpacity:"0.7"}),e.jsx("stop",{offset:"100%",stopColor:i,stopOpacity:"1"}),e.jsx("animate",{attributeName:"x1",from:"-100%",to:"200%",dur:"4s",repeatCount:"indefinite"}),e.jsx("animate",{attributeName:"y1",from:"-100%",to:"200%",dur:"4s",repeatCount:"indefinite"}),e.jsx("animate",{attributeName:"x2",from:"0%",to:"300%",dur:"4s",repeatCount:"indefinite"}),e.jsx("animate",{attributeName:"y2",from:"0%",to:"300%",dur:"4s",repeatCount:"indefinite"})]})}),e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M0 13H35V58H0V13ZM26.25 22.1957H8.75V48.701H26.25V22.1957Z",fill:n?`url(#${c})`:i}),e.jsx("path",{d:"M43.75 13H70V22.1957H52.5V48.701H70V57.8967H43.75V13Z",fill:n?`url(#${c})`:i})]})},Xh={'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"}},Jh={'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 Os{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Os.instance||(Os.instance=new Os),Os.instance}recordSessionStart(s){this.sessionStartTimes.set(s,Date.now())}getSessionStartTime(s){return this.sessionStartTimes.get(s)}shouldAnimateMessage(s,t){if(s.role!=="assistant"||this.seenMessageIds.has(s.id))return!1;const n=this.sessionStartTimes.get(t);if(!n)return this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created),!1;const o=s.time.created>n-5e3;return o||(this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created)),o}clearSession(s){this.sessionStartTimes.delete(s)}hasSessionTiming(s){return this.sessionStartTimes.has(s)}hasBeenAnimated(s){return this.seenMessageIds.has(s)}markMessageAsAnimated(s,t){this.seenMessageIds.add(s),this.messageCreationTimes.set(s,t)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function Nc(r){const s=r.colors.syntax,t=r.colors.surface;return{'code[class*="language-"]':{color:s.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:s.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:s.base.comment,fontStyle:"italic"},prolog:{color:s.base.comment},doctype:{color:s.base.comment},cdata:{color:s.base.comment},punctuation:{color:s.tokens?.punctuation||t.mutedForeground},property:{color:s.tokens?.variableProperty||s.base.variable},tag:{color:s.tokens?.tag||s.base.keyword},"attr-name":{color:s.tokens?.tagAttribute||s.base.variable},"attr-value":{color:s.tokens?.tagAttributeValue||s.base.string},boolean:{color:s.tokens?.boolean||s.base.number},number:{color:s.base.number},constant:{color:s.tokens?.constant||s.base.number},symbol:{color:s.tokens?.constant||s.base.number},string:{color:s.base.string},char:{color:s.base.string},function:{color:s.base.function},builtin:{color:s.tokens?.functionBuiltin||s.base.function},"class-name":{color:s.tokens?.className||s.base.type},namespace:{color:s.tokens?.namespace||s.base.type,opacity:.8},keyword:{color:s.base.keyword},atrule:{color:s.base.keyword},selector:{color:s.base.function},operator:{color:s.base.operator},variable:{color:s.base.variable},regex:{color:s.tokens?.regex||s.base.string},url:{color:s.base.function,textDecoration:"underline"},entity:{color:s.base.function,cursor:"help"},".language-css .token.string":{color:s.base.string},".style .token.string":{color:s.base.string},deleted:{color:r.colors.status.error,backgroundColor:r.colors.status.errorBackground},inserted:{color:r.colors.status.success,backgroundColor:r.colors.status.successBackground},title:{color:r.colors.primary.base,fontWeight:"bold"},"code-block":{color:s.base.string},"code-snippet":{color:s.base.string},list:{color:s.base.variable},hr:{color:t.mutedForeground},table:{color:s.base.function},blockquote:{color:t.mutedForeground,fontStyle:"italic"},important:{color:s.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:s.tokens?.decorator||s.base.function},annotation:{color:s.tokens?.decorator||s.base.function}}}const Gt=({children:r,className:s})=>{const[t,n]=l.useState(!1);return l.useEffect(()=>{let o=null;const a=()=>n(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:T("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",s),children:r})},Zh=({isUser:r,providerID:s,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=rc(s);return e.jsx(Gt,{children:e.jsx("div",{className:T("pl-3","mb-2"),children:e.jsx("div",{className:T("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:r?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx($n,{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(Bn,{className:"h-4 w-4",style:{color:`var(${_s(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:T("font-bold typography-ui-header tracking-tight leading-none",r?"text-primary":"text-foreground"),children:r?"You":n||"Assistant"}),!r&&t&&e.jsx("div",{className:T("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",_s(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},Qh=l.memo(Zh),_i=(r,s)=>{const t=r[Symbol.toPrimitive];if(typeof t=="function")try{if(t()===s)return r}catch{}try{Object.defineProperty(r,"toString",{value:()=>s,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(r,Symbol.toPrimitive,{value:()=>s,enumerable:!1,configurable:!0})}catch{}return r},Bi=()=>{if(!ss()||typeof window>"u")return ni;const r=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(r?.light&&r?.dark){const s=_i({...r.light},`vscode-shiki-light:${String(r.light?.name??"theme")}`),t=_i({...r.dark},`vscode-shiki-dark:${String(r.dark?.name??"theme")}`);return[s,t]}return ni},Cc=()=>{const[r,s]=l.useState(Bi);return l.useEffect(()=>{if(!ss()||typeof window>"u")return;const t=n=>{s(Bi())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),r},Mc=r=>{const s=[],t=[],n=r.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>s.push(i.innerText.trim()));const o=r.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const c=i.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:s,rows:t}},Ac=({headers:r,rows:s})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
72
|
-
`)?`"${o.replace(/"/g,'""')}"`:o,n=[];return r.length>0&&n.push(r.map(t).join(",")),s.forEach(o=>n.push(o.map(t).join(","))),n.join(`
|
|
73
|
-
`)},eg=({headers:r,rows:s})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return r.length>0&&n.push(r.map(t).join(" ")),s.forEach(o=>n.push(o.map(t).join(" "))),n.join(`
|
|
74
|
-
`)},tg=({headers:r,rows:s})=>{if(r.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${r.map(t).join(" | ")} |`),n.push(`| ${r.map(()=>"---").join(" | ")} |`),s.forEach(o=>{const a=r.map((i,c)=>t(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
|
|
75
|
-
`)},sg=(r,s,t)=>{const n=new Blob([s],{type:t}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=r,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},rg=({tableRef:r})=>{const[s,t]=l.useState(!1),[n,o]=l.useState(!1),a=l.useRef(null);l.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const i=async c=>{const d=r.current?.querySelector("table");if(d)try{const u=Mc(d),p=c==="csv"?Ac(u):eg(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([p],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),t(!0),o(!1),setTimeout(()=>t(!1),2e3)}catch(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:s?e.jsx(It,{className:"size-3.5"}):e.jsx(Rs,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("tsv"),children:"TSV"})]})]})},ng=({tableRef:r})=>{const[s,t]=l.useState(!1),n=l.useRef(null);l.useEffect(()=>{const a=i=>{n.current&&!n.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=r.current?.querySelector("table");if(i)try{const c=Mc(i),d=a==="csv"?Ac(c):tg(c);sg(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(c){console.error("Failed to download table:",c)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>t(!s),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(Wo,{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"})]})]})},og=({children:r,className:s})=>{const t=l.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:t,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(rg,{tableRef:t}),e.jsx(ng,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:T("w-full border-collapse border border-border",s),"data-streamdown":"table",children:r})})]})},ag=({children:r,className:s,style:t,...n})=>{const[o,a]=l.useState(!1),i=l.useRef(null),c=l.useMemo(()=>{if(!t)return t;const p={...t},f=g=>{if(typeof g!="string")return{value:void 0,vars:{}};const[x,...y]=g.split(";").map(k=>k.trim()).filter(Boolean),b={};for(const k of y){const j=k.indexOf(":");if(j===-1)continue;const v=k.slice(0,j).trim(),S=k.slice(j+1).trim();!v.startsWith("--")||S.length===0||(b[v]=S)}return{value:x,vars:b}},m=f(t.backgroundColor);m.value&&(p.backgroundColor=m.value,p["--shiki-light-bg"]=m.value);for(const[g,x]of Object.entries(m.vars))p[g]=x;const h=f(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(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:T(s),style:c,children:r}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(It,{className:"size-3.5"}):e.jsx(Rs,{className:"size-3.5"})})})]})},Dc={pre:ag,table:og},ig=({content:r,part:s,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const c=Cc(),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(yl,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:Dc,children:r})});return n?e.jsx(Gt,{children:p},d):p},Ur=({content:r,className:s,variant:t="assistant"})=>{const n=Cc(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:T("break-words",s),children:e.jsx(yl,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:Dc,children:r})})},lg={thinking:{label:"Thinking",Icon:Bn},justification:{label:"Justification",Icon:Uo}},Ec=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
|
|
76
|
-
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
77
|
-
`).trim(),cg=r=>{if(!r)return"";const s=r.trim(),t=s.indexOf(`
|
|
78
|
-
`),n=s.indexOf("."),o=[t>=0?t:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?s.substring(0,a).trim():s},xa=({text:r,variant:s,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>cg(r),[r]),{label:c,Icon:d}=lg[s];return l.useEffect(()=>{r.trim().length!==0&&t?.("structural")},[t,o,r]),!r||r.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(u=>!u),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(vt,{className:"h-3.5 w-3.5"}):e.jsx(gs,{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(Ye,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:r})})]})},Tc=({part:r,onContentChange:s,messageId:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>Ec(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(xa,{text:a,variant:"thinking",onContentChange:s,blockId:r.id||`${t}-reasoning`}):null},dg=r=>Ec(r),ug=({part:r,messageId:s,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=r,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",u=l.useMemo(()=>a?dg(d):d,[d,a]),p=t==="streaming",f=t==="cooldown",m=l.useRef(p);if(p||f)return m.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(xa,{text:u,variant:"justification",onContentChange:o,blockId:r.id||`${s}-reasoning-text`},r.id||`${s}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(ig,{content:u,part:r,messageId:s,isAnimated:n,isStreaming:!1})},r.id||`${s}-text`)},mg=r=>`https://opencode.ai/docs/agents/#${encodeURIComponent(r)}`,fg=({part:r,messageId:s,agentMention:t})=>{const n=r,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,c]=l.useState(!1),[d,u]=l.useState(!1),p=l.useRef(null);l.useEffect(()=>{const h=p.current;h&&!i&&u(h.scrollHeight>h.clientHeight)},[a,i]);const f=l.useCallback(()=>{(d||i)&&c(h=>!h)},[d,i]);if(!a||a.trim().length===0)return null;const m=()=>{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:mg(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:f,children:m()},r.id||`${s}-user-text`)},pg=l.memo(fg),hg=r=>{let s=r.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},Ic=r=>r?r.includes("<file_diagnostics>")||r.includes("This file has errors")||r.includes("please fix"):!1,gg=r=>r?r.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",Oi=(r,s)=>!r||typeof r!="object"?String(r):Qf(r,s||""),fo=(r,s,t)=>{let n=hg(r);if((s==="edit"||s==="multiedit")&&Ic(n)&&(n=gg(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},xg=(r,s)=>{try{const t=r.trim().split(`
|
|
79
|
-
`).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,c]=a,d=Math.floor(i.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:T("w-full min-w-0 font-mono space-y-0.5",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Cs.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},yg=(r,s,t)=>{try{const n=r.trim().split(`
|
|
80
|
-
`).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,c,d,u]=i,p=u!==void 0?d:"",f=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:p,content:f})}}),e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Cs.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:T("font-medium text-muted-foreground",s?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:T("flex items-start gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},bg=(r,s,t)=>{try{const n=r.trim().split(`
|
|
81
|
-
`).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",u=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Cs.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:T("font-medium text-muted-foreground",s?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:T("pl-4 grid gap-1",s?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:T("flex items-center gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},i))]})}catch{return null}},wg=(r,s)=>{try{const t=JSON.parse(r);if(!Array.isArray(t))return null;const n={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const i="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:i,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:i,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:T("space-y-3 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:Cs.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(It,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(It,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||i))})]})]})}catch{return null}},vg=(r,s,t)=>{try{return e.jsx("div",{className:T("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:Cs.tool.popup,children:e.jsx(Ur,{content:r,variant:"tool"})})}catch{return null}},jg=r=>{const s=r.split(`
|
|
82
|
-
`);let t="";const n=[];let o=0;for(;o<s.length;){const a=s[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let p=d,f=o+1;for(;f<s.length&&!s[f].startsWith("@@")&&!s[f].startsWith("Index:");){const m=s[f];m.startsWith("+")?(u.push({type:"added",lineNumber:p,content:m.substring(1)}),p++):m.startsWith("-")?u.push({type:"removed",lineNumber:null,content:m.substring(1)}):m.startsWith(" ")&&(u.push({type:"context",lineNumber:p,content:m.substring(1)}),p++),f++}n.push({file:t,oldStart:c,newStart:d,lines:u}),o=f;continue}o++}return n},_o=(r,s,t)=>Xf(s,r,t),Fc=r=>{const s="h-3.5 w-3.5 flex-shrink-0",t=r.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(au,{className:s}):t==="write"||t==="create"||t==="file_write"?e.jsx(iu,{className:s}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(ko,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Ws,{className:s}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(os,{className:s}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(lu,{className:s}):t==="glob"?e.jsx(cu,{className:s}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(No,{className:s}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(No,{className:s}):t==="todowrite"||t==="todoread"?e.jsx(du,{className:s}):t.startsWith("git")?e.jsx(zt,{className:s}):e.jsx(Qo,{className:s})},Sg=(r,s,t=Date.now())=>{const o=(s?s-r:t-r)/1e3;return`${(o<.05&&s!==void 0?.1:o).toFixed(1)}s`},kg=({start:r,end:s,active:t})=>{const[n,o]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:Sg(r,s,n)})},Ng=r=>{if(!r?.diff||typeof r.diff!="string")return null;const s=r.diff.split(`
|
|
83
|
-
`);let t=0,n=0;for(const o of s)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&n++;return t===0&&n===0?null:{added:t,removed:n}},Bo=(r,s,t)=>{if(t)return r.split("/").pop()||r;if(r.startsWith(s)){const n=r.substring(s.length);return n.startsWith("/")?n.substring(1):n}return r},Cg=(r,s,t,n)=>{const o=s,a=o.metadata,i=o.input;if((r.tool==="edit"||r.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return Bo(d,n,t)}if((r.tool==="read"||r.tool==="write")&&i){const d=i?.filePath||i?.file_path||i?.path;if(typeof d=="string")return Bo(d,n,t)}if(r.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
|
|
84
|
-
`)[0];return t?d.substring(0,50):d.substring(0,100)}if(r.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);const c=i?.description||a?.description||"title"in s&&s.title||"";return typeof c=="string"?c:""},Oo=({children:r,maxHeightClass:s="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(Ye,{outerClassName:T("w-full min-w-0 flex-none overflow-hidden",s,n),className:T("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",t),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:r})}),Mg=r=>{const s=r.state?.title;return typeof s=="string"&&s.trim().length>0?s:typeof r.tool=="string"&&r.tool.trim().length>0?r.tool:"tool"},Ag=r=>r.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Dg=({entries:r,isExpanded:s,hasPrevTool:t,hasNextTool:n,output:o})=>{const a=l.useMemo(()=>r.filter(m=>m.state?.status==="completed"),[r]),i=typeof o=="string"?Ag(o):"",c=i.length>0,[d,u]=l.useState(!1);if(a.length===0&&!c)return null;const p=s?a:a.slice(-6),f=Math.max(0,a.length-p.length);return e.jsxs("div",{className:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',t?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[a.length>0?e.jsx(Oo,{maxHeightClass:s?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[f>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",f," more…"]}):null,p.map((m,h)=>{const g=typeof m.tool=="string"&&m.tool.trim().length>0?m.tool:"tool",x=Mg(m),y=ia(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:Fc(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})]},m.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:m=>m.stopPropagation(),onClick:m=>{m.stopPropagation(),u(h=>!h)},children:[d?e.jsx(vt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(gs,{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(Oo,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Ur,{content:i,variant:"tool"})})}):null]}):null]})},Eg=({diff:r,syntaxTheme:s,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:jg(r).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:T("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ss,{style:s,language:Gr(typeof t?.file_path=="string"?t.file_path:typeof t?.filePath=="string"?t.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),Tg=({content:r,syntaxTheme:s,filePath:t,displayPath:n})=>{const o=r.split(`
|
|
85
|
-
`),a=Gr(t??"")||_o(r,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),c=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Ss,{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))})]})},Ig=({content:r,filePath:s,displayPath:t})=>{const n=Zf(s),o=s.toLowerCase().endsWith(".svg"),a=l.useMemo(()=>o&&!r.startsWith("data:")?`data:image/svg+xml;base64,${btoa(r)}`:r.startsWith("data:")?r:`data:${n};base64,${r}`,[r,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:t}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:t,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})},Fg=({part:r,state:s,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const c=s,d=c.metadata,u=c.input,p=c.output,f=typeof p=="string"&&p.length>0,m=typeof p=="string"?p:"",h=typeof d?.diff=="string"?d.diff:null,g=r.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,x=r.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,y=r.tool==="write"&&!!x,b=g?Ul(g):!1,k=y?g?Bo(g,o,n):"New file":null,j=l.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&r.tool==="bash"?Oi(u,r.tool):typeof u.content=="string"?u.content??"":Oi(u,r.tool),[u,r.tool]),v=j.trim().length>0,S=(D,A)=>e.jsx(Oo,{maxHeightClass:A?.maxHeightClass,className:A?.className,disableHorizontal:A?.disableHorizontal,outerClassName:A?.outerClassName,children:D}),w=()=>{if(r.tool==="todowrite"||r.tool==="todoread"){if(s.status==="completed"&&f){const D=wg(m,{unstyled:!0});return S(D??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return s.status==="error"&&"error"in s?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:s.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(r.tool==="list"&&f){const D=xg(m,{unstyled:!0});return S(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:m}))}if(r.tool==="grep"&&f){const D=yg(m,n,{unstyled:!0});return S(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:m}))}if(r.tool==="glob"&&f){const D=bg(m,n,{unstyled:!0});return S(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:m}))}if(r.tool==="task"&&f)return S(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Ur,{content:m,variant:"tool"})}));if((r.tool==="web-search"||r.tool==="websearch"||r.tool==="search_web")&&f){const D=vg(m,t,{unstyled:!0});return S(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:m}))}if(r.tool==="codesearch"&&f)return S(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Ur,{content:m,variant:"tool"})}));if((r.tool==="edit"||r.tool==="multiedit")&&(!f&&h||m.trim().length===0||Ic(m))&&h)return S(e.jsx(Eg,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&m.trim()){if(r.tool==="read"){const D=fo(m,r.tool,d),A=D.split(`
|
|
86
|
-
`),N=typeof u?.offset=="number"?u.offset:0,M=typeof u?.limit=="number"?u.limit:void 0,C=E=>E.trim().startsWith("(");return S(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:A.map((E,F)=>{const $=C(E),R=N+F+1,Y=!$&&(M===void 0||F<M);return e.jsxs("div",{className:T("typography-code font-mono flex w-full min-w-0",$&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:Y?R:""}),e.jsx("div",{className:"flex-1 min-w-0",children:$?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(Ss,{style:t,language:_o(D,r.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:E})})]},F)})}),{className:"p-1"})}return S(e.jsx(Ss,{style:t,language:_o(fo(m,r.tool,d),r.tool,u),PreTag:"div",customStyle:{...mn.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:fo(m,r.tool,d)}),{className:"p-1"})}return S(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:r.tool==="todowrite"||r.tool==="todoread"?w():e.jsxs(e.Fragment,{children:[y&&b?e.jsx("div",{className:"my-1",children:S(e.jsx(Ig,{content:x,filePath:g,displayPath:k??"New file"}))}):y?e.jsx("div",{className:"my-1",children:S(e.jsx(Tg,{content:x,syntaxTheme:t,filePath:g,displayPath:k??"New file"}))}):v?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:j}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,r.tool!=="write"&&s.status==="completed"&&"output"in s&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),w()]}),s.status==="error"&&"error"in s&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:s.error})]})]})})},yn=({part:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=r.state,u=jt($=>$.currentDirectory),p=r.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",m=d.status==="running"||d.status==="pending",h=d.status==="error",g=l.useRef(s);l.useEffect(()=>{!f&&!p||g.current!==s&&(g.current=s,typeof s=="boolean"&&a?.("structural"))},[s,f,p,a]);const x=d,y=x.metadata,b=x.input,k=x.time,j=l.useRef({}),v=l.useRef(r.id);if(v.current!==r.id&&(v.current=r.id,j.current={}),p){if(typeof k?.start=="number"){const $=j.current.start;(typeof $!="number"||k.start<$)&&(j.current.start=k.start)}typeof k?.end=="number"&&(j.current.end=k.end)}const S=p?j.current.start??k?.start:k?.start,w=p?j.current.end??k?.end:k?.end,D=l.useMemo(()=>{if(!p)return[];const $=y?.summary;return Array.isArray($)?$.filter(R=>typeof R=="object"&&R!==null):[]},[p,y]),A=l.useRef(D.length);l.useEffect(()=>{p&&A.current!==D.length&&(A.current=D.length,a?.("structural"))},[p,a,D.length]);const N=r.tool==="edit"||r.tool==="multiedit"?Ng(y):null,M=Cg(r,d,o,u),C=ia(r.tool).displayName,E=l.useContext(la),F=$=>{if(p||!E?.editor){t(r.id);return}let R;if((r.tool==="edit"||r.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(r.tool))&&(R=b?.filePath||b?.file_path||b?.path||y?.filePath||y?.file_path||y?.path),typeof R=="string"){$.stopPropagation();let Y=R;R.startsWith("/")||(Y=u.endsWith("/")?u+R:u+"/"+R),E.editor.openFile(Y)}else t(r.id)};return!f&&!p?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:F,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:$=>{$.stopPropagation(),t(r.id)},children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:!p&&h?{color:"var(--status-error)"}:{},children:Fc(r.tool)}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(vt,{className:"h-3.5 w-3.5"}):e.jsx(gs,{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}),N&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",N.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",N.removed]})]}),typeof S=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(kg,{start:S,end:typeof w=="number"?w:void 0,active:!!(p&&m&&typeof w!="number")})})]})]}),p&&(D.length>0||m||f)?e.jsx(Dg,{entries:D,isExpanded:s,hasPrevTool:i,hasNextTool:c,output:typeof x.output=="string"?x.output:void 0}):null,!p&&s?e.jsx(Fg,{part:r,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c}):null]})},Pg=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
|
|
87
|
-
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
88
|
-
`).trim(),Rg=({part:r,messageId:s,onContentChange:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>Pg(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(xa,{text:a,variant:"justification",onContentChange:t,blockId:r.id||`${s}-justification`}):null},Lg=l.memo(Rg),_g=r=>{const s={tools:r.filter(n=>n.kind==="tool").length,reasoning:r.filter(n=>n.kind==="reasoning").length,justifications:r.filter(n=>n.kind==="justification").length},t=[];return s.tools>0&&t.push(`${s.tools} tool${s.tools>1?"s":""}`),s.reasoning>0&&t.push(`${s.reasoning} reasoning`),s.justifications>0&&t.push(`${s.justifications} justification${s.justifications>1?"s":""}`),t.join(", ")},$i=r=>[...r].sort((s,t)=>{const n=typeof s.endedAt=="number"?s.endedAt:void 0,o=typeof t.endedAt=="number"?t.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),Bg=r=>{const s={},t=r.filter(n=>n.kind==="tool");return t.forEach((n,o)=>{const a=n.part.id;a&&(s[a]={hasPrev:o>0,hasNext:o<t.length-1})}),s},Og=({parts:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:p})=>{const f=l.useRef(s),[m,h]=l.useState(0);l.useEffect(()=>{if(f.current===s)return;const b=f.current===!1;f.current=s,c?.("structural"),s&&b&&h(k=>k+1)},[s,c]);const g=l.useMemo(()=>$i(d?r.filter(b=>b.part.id&&u.has(b.id)):r),[r,d,u]),x=_g(g),y=Bg(g);return g.length===0?null:e.jsx(Gt,{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(ml,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(vt,{className:"h-3.5 w-3.5"}):e.jsx(gs,{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,k)=>{const j=b.part.id||`group-part-${k}`,v=y[j],S=`${j}-exp${m}`;switch(b.kind){case"tool":return e.jsx(Gt,{children:e.jsx(yn,{part:b.part,isExpanded:a.has(j),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:v?.hasPrev??!1,hasNextTool:v?.hasNext??!1})},S);case"reasoning":return e.jsx(Gt,{children:e.jsx(Tc,{part:b.part,messageId:b.messageId,onContentChange:c})},S);case"justification":return e.jsx(Gt,{children:e.jsx(Lg,{part:b.part,messageId:b.messageId,onContentChange:c})},S);default:return null}})})]})})},$g=l.memo(Og),zg=({isMigrating:r,children:s,className:t})=>e.jsx("div",{className:T("w-full overflow-hidden",r&&"pointer-events-none",t),style:r?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:s}),po=l.memo(zg),Pc=r=>{const s=r,t=s.text;return typeof t=="string"?t:s.content||s.value||""},Rc=r=>{if(r.type!=="text")return!1;const s=Pc(r);return!s||s.trim().length===0},Hg=(r,s={})=>{const{includeReasoning:t=!0}=s;return r.filter(n=>!!n.synthetic||!t&&n.type==="reasoning"?!1:!(n.type==="patch"))},Wg=(r,s)=>{const t=l.useRef(null),n=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(r);i.current=r;const c=l.useRef(s);c.current=s;const d=l.useRef(!1),u=s.size>0;return l.useEffect(()=>{r&&r.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const p=i.current;if(!p)return;const f=Array.from(c.current);f.length>0&&p.markPartsPreviewed(f)},300)},1e3)))},[u,r]),l.useEffect(()=>{r&&(!r.isWorking||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[u,r]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},Ug=new Set(["task"]),lr=r=>typeof r=="string"&&Ug.has(r.toLowerCase()),Vg=({messageId:r,parts:s,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d})=>{const[u,p]=l.useState(!1),f=l.useRef(null),m=l.useMemo(()=>s.filter(w=>w.type!=="text"?!1:!Rc(w)),[s]),h=d?.token;let g=!1;const x=!!a,y=!!i,b=!!(n??t),k=!!o,j=l.useCallback(()=>{f.current!==null&&typeof window<"u"&&(window.clearTimeout(f.current),f.current=null)},[]),v=l.useCallback(()=>{!b||!x||!k||typeof window>"u"||(j(),p(!0),f.current=window.setTimeout(()=>{p(!1),f.current=null},1800))},[x,j,k,b]);l.useEffect(()=>{k||(p(!1),j())},[j,k]);const S=l.useCallback(w=>{!a||!k||(w.stopPropagation(),w.preventDefault(),a(),b&&v())},[k,b,a,v]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:b&&x&&k?v:void 0,children:[x&&e.jsx(Ee,{type:"button",variant:"ghost",size:"icon","data-visible":u||y?"true":void 0,className:T("absolute z-10 flex h-7 w-7 items-center justify-center rounded-full border border-border/40 shadow-none bg-background/95 supports-[backdrop-filter]:bg-background/80 hover:bg-accent duration-150","opacity-0 pointer-events-none disabled:opacity-30 disabled:text-muted-foreground/40",k&&"group-hover/message:opacity-60 group-hover/message:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",(u||y)&&"opacity-100 pointer-events-auto"),style:{insetInlineEnd:"0.32rem",insetBlockStart:"-0.28rem"},disabled:!k,"aria-label":"Copy message text","aria-hidden":!k,onPointerDown:w=>w.stopPropagation(),onClick:S,onFocus:()=>{k&&p(!0)},onBlur:()=>{y||p(!1)},children:y?e.jsx(It,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Rs,{className:"h-3.5 w-3.5 text-foreground hover:text-primary focus-visible:text-primary"})}),e.jsxs("div",{className:"px-3",children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/90",children:m.map((w,D)=>{let A;return d&&h&&!g&&Pc(w).includes(h)&&(A=d,g=!0),e.jsx(Gt,{children:e.jsx(pg,{part:w,messageId:r,isMobile:t,agentMention:A})},`user-text-${D}`)})}),e.jsx(hc,{files:s,onShowPopup:c})]})]})},Gg=({messageId:r,parts:s,isMessageCompleted:t,syntaxTheme:n,isMobile:o,hasTouchInput:a,copiedCode:i,onCopyCode:c,expandedTools:d,onToggleTool:u,onShowPopup:p,streamPhase:f,allowAnimation:m,onContentChange:h,shouldShowHeader:g=!0,hasTextContent:x=!1,onCopyMessage:y,copiedMessage:b=!1,onAuxiliaryContentComplete:k,showReasoningTraces:j=!1,turnGroupingContext:v})=>{const[S,w]=l.useState(!1),D=l.useRef(null),A=!!y,N=!!b,M=!!(a??o),C=!t,E=l.useMemo(()=>s.filter(I=>!Rc(I)).filter(I=>I.type!=="compaction"),[s]),F=l.useMemo(()=>E.filter(I=>I.type==="tool"),[E]),$=l.useMemo(()=>E.filter(I=>I.type==="text"),[E]),R=ge(I=>I.createSessionFromAssistantMessage),Y=v?.isLastAssistantInTurn??!1,Z=l.useMemo(()=>s.some(I=>I.type==="step-finish"&&I.reason==="stop"),[s]),z=F.length>0,G=l.useMemo(()=>F.some(I=>{const we=(I.state??{})?.status;return we==="pending"||we==="running"||we==="started"}),[F]),W=l.useCallback(I=>{const ne=I.state??{},we=ne?.status;if(we==="pending"||we==="running"||we==="started")return!1;const ve=ne?.time??{},me=typeof ve?.end=="number"?ve.end:void 0,Pe=typeof ve?.start=="number"?ve.start:void 0;return!(typeof me!="number"||typeof Pe=="number"&&me<Pe)},[]),ce=l.useMemo(()=>F.length===0?!0:G?!1:F.every(I=>W(I)),[F,G,W]),Ne=l.useMemo(()=>$.length===0?!0:$.every(I=>typeof I.time?.end=="number"),[$]),Me=l.useMemo(()=>E.filter(I=>I.type==="reasoning"),[E]),Le=l.useMemo(()=>Me.length===0?!0:Me.every(I=>typeof I.time?.end=="number"),[Me]),ie=l.useMemo(()=>{let I=0,ne=0;return E.forEach(we=>{we.type==="step-start"?I+=1:we.type==="step-finish"&&(ne+=1)}),{stepStarts:I,stepFinishes:ne,hasOpenStep:I>ne}},[E]).hasOpenStep,je=Me.length>0&&z&&(G||ie||!ce),Ce=l.useMemo(()=>z?$.length===0?ie||G||!ce:!0:$.length>0?je:!1,[$.length,ie,G,z,je,ce]),We=C||Ce&&(!Ne||!ce||G||ie)||je,oe=C||z&&(G||ie||!ce),B=C||je,J=z||Me.length>0,O=$.length===0,X=J&&O&&!oe&&!B&&ce&&Le,_=l.useRef(!1),te=l.useRef(!1);l.useEffect(()=>{te.current=!1},[r]),l.useEffect(()=>{if(!X){_.current=!1;return}_.current||(_.current=!0,k?.())},[X,k]),l.useEffect(()=>{if(C){te.current=!1;return}if(z){te.current=!1;return}Me.length!==0&&(B||!Le||te.current||(te.current=!0,h?.("structural")))},[C,z,h,Le,Me.length,B]);const K=!!x&&!C,ae=l.useCallback(()=>{D.current!==null&&typeof window<"u"&&(window.clearTimeout(D.current),D.current=null)},[]),be=l.useCallback(()=>{!M||!A||!K||typeof window>"u"||(ae(),w(!0),D.current=window.setTimeout(()=>{w(!1),D.current=null},1800))},[A,ae,K,M]);l.useEffect(()=>{K||(w(!1),ae())},[ae,K]);const fe=l.useCallback(I=>{!y||!K||(I.stopPropagation(),I.preventDefault(),y(),M&&be())},[K,M,y,be]),H=l.useCallback(I=>{I.stopPropagation(),I.preventDefault(),R&&R(r)},[R,r]);l.useEffect(()=>()=>{ae()},[ae]);const V=l.useMemo(()=>{const I={},ne=F.filter(we=>lr(we.tool)||oe?!1:W(we));return ne.forEach((we,ve)=>{I[we.id]={hasPrev:ve>0,hasNext:ve<ne.length-1}}),I},[F,oe,W]),L=l.useMemo(()=>v?.activityParts??[],[v]),Q=l.useMemo(()=>v?L.filter(I=>I.messageId===r):[],[L,r,v]),ke=l.useMemo(()=>{const I=new Map;return Q.forEach(ne=>{I.set(ne.part,ne)}),I},[Q]),De=l.useMemo(()=>v?(j?L:L.filter(ne=>ne.kind==="tool")).filter(ne=>{if(ne.kind!=="tool")return!0;const we=ne.part.tool;return!lr(we)}):[],[L,j,v]),[Oe,ct]=l.useState(!1);l.useEffect(()=>{v&&De.length>1&&ct(!0)},[v,De.length]);const Ue=!!(v&&Oe),Ge=l.useMemo(()=>{if(!v)return[];if(!Ue)return[];if(!v.isWorking)return[];const I=[];return Q.forEach(ne=>{if(v.previewedPartIds.has(ne.id)||!j&&ne.kind!=="tool")return;const we=ne.part;if(ne.kind==="tool"){const ve=we;if(lr(ve.tool)||oe||!W(ve))return}else if(ne.kind==="reasoning"){if(!j||B||typeof we.time?.end!="number")return}else if(ne.kind==="justification"&&(!j||We||typeof we.time?.end!="number"))return;I.push(ne)}),I},[Q,W,We,B,oe,j,Ue,v]),Xe=l.useMemo(()=>{const I=new Set;return Ge.forEach(ne=>{I.add(ne.id)}),I},[Ge]),{isAnimating:Ze}=Wg(v,Xe),Be=!!(v&&v.activityGroupAnchorMessageId===r&&Ue&&De.length>0),ze=l.useMemo(()=>F.filter(I=>lr(I.tool)),[F]),dt=l.useMemo(()=>{if(!v||!Be)return!1;if(!v.isWorking)return!0;const I=v.previewedPartIds;return De.some(ne=>I.has(ne.id))},[Be,v,De]),mt=l.useRef(null),Se=l.useRef(null);l.useEffect(()=>{mt.current=null,Se.current=null},[r]);const P=Date.now();ze.length>0&&mt.current===null&&(mt.current=P),dt&&Se.current===null&&(Se.current=P);const se=!!(ze.length>0&&dt&&typeof mt.current=="number"&&typeof Se.current=="number"&&Se.current>mt.current),re=l.useMemo(()=>{const I=[],ne=()=>{!v||!Be||I.push(e.jsx($g,{parts:De,isExpanded:v.isGroupExpanded,onToggle:v.toggleGroup,syntaxTheme:n,isMobile:o,expandedTools:d,onToggleTool:u,onShowPopup:p,onContentChange:h,isWorking:v.isWorking,previewedPartIds:v.previewedPartIds,diffStats:v.diffStats},"progressive-group"))};se||ne(),ze.forEach(ve=>{I.push(e.jsx(Gt,{children:e.jsx(yn,{part:ve,isExpanded:d.has(ve.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${ve.id}`))}),se&&ne();const we=[];return E.forEach((ve,me)=>{const Pe=ke.get(ve);if(!Pe||!v)return;let _e=null,nt=null;if(!Ue){if(Pe.kind==="tool"){const Qe=ve;if(lr(Qe.tool))return;const Ft=Qe.state?.time,U=W(Qe);if(!(!oe&&U))return;const $e=V[Qe.id];nt=e.jsx(Gt,{children:e.jsx(yn,{part:Qe,isExpanded:d.has(Qe.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:$e?.hasPrev??!1,hasNextTool:$e?.hasNext??!1})},`tool-${Qe.id}`),_e=U&&typeof Ft?.end=="number"?Ft.end:null}nt&&we.push({part:ve,index:me,endTime:_e,element:nt});return}if(!v.isWorking||v.isGroupExpanded||v.previewedPartIds.has(Pe.id)||!j&&Pe.kind!=="tool")return;const Mt=Xe.has(Pe.id);switch(Pe.kind){case"tool":{const Qe=ve;if(lr(Qe.tool))break;const Ft=Qe.state?.time,U=W(Qe);if(!(!oe&&U))break;const $e=V[Qe.id],ot=e.jsx(Gt,{children:e.jsx(yn,{part:Qe,isExpanded:d.has(Qe.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:$e?.hasPrev??!1,hasNextTool:$e?.hasNext??!1})},`tool-${Qe.id}`);nt=Mt?e.jsx(po,{isMigrating:Ze,children:ot},`migrating-tool-${Qe.id}`):ot,_e=U&&typeof Ft?.end=="number"?Ft.end:null;break}case"reasoning":{if(!j)break;const Qe=ve.time,Ct=typeof Qe?.end=="number";if(!(Ct&&!B))break;const U=e.jsx(Gt,{children:e.jsx(Tc,{part:ve,messageId:r,onContentChange:h})},`reasoning-${me}`);nt=Mt?e.jsx(po,{isMigrating:Ze,children:U},`migrating-reasoning-${me}`):U,_e=Ct?Qe?.end??null:null;break}case"justification":{if(!j)break;const Qe=ve.time,Ct=typeof Qe?.end=="number";if(!(Ct&&!We))break;const U=e.jsx(Gt,{children:e.jsx(ug,{part:ve,messageId:r,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${me}`);nt=Mt?e.jsx(po,{isMigrating:Ze,children:U},`migrating-text-${me}`):U,_e=Ct?Qe?.end??null:null;break}}nt&&we.push({part:ve,index:me,endTime:_e,element:nt})}),we.sort((ve,me)=>ve.endTime===null&&me.endTime===null?ve.index-me.index:ve.endTime===null?1:me.endTime===null?-1:ve.endTime-me.endTime),we.forEach(({element:ve})=>{I.push(ve)}),I},[ke,i,b,d,x,Ze,o,W,r,h,c,y,p,u,Xe,We,B,oe,Ue,g,j,n,V,v,De,E,F,ze,Be,se]),pe=v?.turnId,Te=ge(I=>I.currentSessionId),Je=lt(I=>{if(!pe||!Te)return;const ne=I.messages.get(Te);if(!ne)return;const we=ne.find(Pe=>Pe.info?.id===pe);if(!we)return;const me=we.info.summary?.body;return typeof me=="string"&&me.trim().length>0?me:void 0}),Re=typeof v?.summaryBody=="string"&&v.summaryBody.trim().length>0?v.summaryBody:Je,qe=l.useRef(void 0);Re&&Re.trim().length>0&&(qe.current=Re);const ut=l.useRef(pe);ut.current!==pe&&(ut.current=pe,qe.current=void 0);const Dt=qe.current,pt=v?.isLastAssistantInTurn&&Dt&&Dt.trim().length>0,kt=x&&$.length>0&&Z&&Y,[bt,ht]=l.useState(!1),Et=e.jsxs(e.Fragment,{children:[y&&e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Ee,{type:"button",variant:"ghost",size:"icon","data-visible":S||N?"true":void 0,className:T("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!K&&"opacity-50",(S||N)&&"text-primary"),disabled:!K,"aria-label":"Copy message text","aria-hidden":!K,onPointerDown:I=>I.stopPropagation(),onClick:fe,onFocus:()=>{K&&w(!0)},onBlur:()=>{N||w(!1)},children:N?e.jsx(It,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Rs,{className:"h-3.5 w-3.5"})})}),e.jsx(ft,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{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:I=>I.stopPropagation(),onClick:H,children:e.jsx(uu,{className:"h-4 w-4"})})}),e.jsx(ft,{sideOffset:6,children:"Start new session from this answer"})]})]});return e.jsx("div",{className:T("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:M&&A&&K?be:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[re,pt&&e.jsx(Gt,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>ht(!0),onMouseLeave:()=>ht(!1),children:[e.jsx(Ur,{content:Dt}),kt&&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",bt&&"opacity-100 pointer-events-auto"),children:Et})]})},"summary-body")]}),e.jsx(hc,{files:s,onShowPopup:p}),!pt&&kt&&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:Et})]})})},qg=({isUser:r,...s})=>r?e.jsx(Vg,{messageId:s.messageId,parts:s.parts,isMobile:s.isMobile,hasTouchInput:s.hasTouchInput,hasTextContent:s.hasTextContent,onCopyMessage:s.onCopyMessage,copiedMessage:s.copiedMessage,onShowPopup:s.onShowPopup,agentMention:s.agentMention}):e.jsx(Gg,{...s}),zi=l.memo(qg),ho=r=>{const s=r,t=s?.clientRole,n=s?.role;return s?.userMessageMarker===!0||t==="user"||n==="user"||s?.origin==="user"||s?.source==="user"?{role:"user",isUser:!0}:{role:t||n||"assistant",isUser:!1}},Kg=l.lazy(()=>_r(()=>import("./ToolOutputDialog-DUsgiKZ7.js"),__vite__mapDeps([2,0,1,3,4]))),Yg=new Set(["task","edit","multiedit","write","bash"]),Hi=r=>typeof r=="string"&&Yg.has(r.toLowerCase());function go(r){const s=l.useRef({hasValue:!1,value:void 0});return!s.current.hasValue&&r!==void 0&&r!==null&&(s.current={hasValue:!0,value:r}),s.current.hasValue?s.current.value:r}const ws=(r,s)=>{if(typeof r=="object"&&r!==null)return r[s]},Xg=({message:r,previousMessage:s,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=At(),{currentTheme:u}=jr(),p=l.useRef(null),f=ge(Zo(me=>({lifecyclePhase:me.messageStreamStates.get(r.info.id)?.phase??null,isStreamingMessage:(()=>{const Pe=r.info.sessionID??me.currentSessionId??null;return Pe?(me.streamingMessageIds.get(Pe)??null)===r.info.id:!1})(),currentSessionId:me.currentSessionId,getCurrentAgent:me.getCurrentAgent,getSessionAgentSelection:me.getSessionAgentSelection,getAgentModelForSession:me.getAgentModelForSession,getSessionModelSelection:me.getSessionModelSelection}))),{lifecyclePhase:m,isStreamingMessage:h,currentSessionId:g,getCurrentAgent:x,getSessionAgentSelection:y,getAgentModelForSession:b,getSessionModelSelection:k}=f,j=St(me=>me.providers),v=Fe(me=>me.showReasoningTraces),S=Fe(me=>me.toolCallExpansion);l.useEffect(()=>{g&&Os.getInstance().recordSessionStart(g)},[g]);const[w,D]=l.useState(null),[A,N]=l.useState(!1),[M,C]=l.useState(new Set),[E,F]=l.useState({open:!1,title:"",content:""});l.useEffect(()=>{C(new Set)},[r.info.id,S]);const R=l.useMemo(()=>ho(r.info),[r.info]).isUser,Y=l.useMemo(()=>R?r.parts.map(me=>me.type==="compaction"?{type:"text",text:"/summarize"}:me):r.parts,[R,r.parts]),Z=l.useMemo(()=>{if(R||!s)return null;const me=ws(s.info,"clientRole"),Pe=ws(s.info,"role");if((typeof me=="string"?me:typeof Pe=="string"?Pe:void 0)!=="user")return null;const nt=ws(s.info,"mode"),Mt=ws(s.info,"providerID"),Qe=ws(s.info,"modelID"),Ct=typeof nt=="string"&&nt.trim().length>0?nt:void 0,Ft=typeof Mt=="string"&&Mt.trim().length>0?Mt:void 0,U=typeof Qe=="string"&&Qe.trim().length>0?Qe:void 0;return!Ct&&!Ft&&!U?null:{agentName:Ct,providerId:Ft,modelId:U}},[R,s]),z=l.useMemo(()=>{if(R)return;const me=ws(r.info,"mode");if(typeof me=="string"&&me.trim().length>0)return me;if(Z?.agentName)return Z.agentName;const Pe=r.info.sessionID;if(!Pe)return;const _e=x(Pe);return _e||(y(Pe)??void 0)},[R,r.info,Z,x,y]),G=r.info.sessionID,W=R?null:ws(r.info,"providerID"),ce=R?null:ws(r.info,"modelID"),Ne=l.useMemo(()=>{if(R||!G)return null;if(Z?.providerId&&Z?.modelId)return{providerId:Z.providerId,modelId:Z.modelId};if(z){const Pe=b(G,z);if(Pe?.providerId&&Pe?.modelId)return Pe}const me=k(G);return me?.providerId&&me?.modelId?me:null},[R,G,z,Z,b,k]),Me=l.useMemo(()=>R?null:typeof W=="string"&&W.trim().length>0?W:Ne?.providerId??null,[R,W,Ne]),Le=l.useMemo(()=>R?null:typeof ce=="string"&&ce.trim().length>0?ce:Ne?.modelId??null,[R,ce,Ne]),ye=l.useMemo(()=>{if(!R&&Me&&Le&&j.length>0){const me=j.find(Pe=>Pe.id===Me);if(me?.models&&Array.isArray(me.models)){const nt=me.models.find(Mt=>Mt.id===Le)?.name;return typeof nt=="string"?nt:void 0}}},[R,Me,Le,j]),ie=go(z),je=go(Me??void 0),Ce=go(ye),We=ie??void 0,oe=je??null,B=Ce??void 0,J=l.useMemo(()=>{const me=r.info.time;return typeof me?.completed=="number"?me.completed:null},[r.info.time]),O=l.useMemo(()=>R?!0:!!(J&&J>0),[R,J]),X=l.useMemo(()=>Hg(Y,{includeReasoning:v}),[Y,v]),_=l.useMemo(()=>R||O?X:[],[R,O,X]),te=l.useMemo(()=>R?[]:X.filter(me=>me.type==="text"),[R,X]),K=l.useMemo(()=>R?[]:X.filter(Pe=>Pe.type==="tool"),[R,X]),ae=l.useMemo(()=>{if(S==="collapsed"||S==="activity")return M;const me=new Set;for(const _e of K){const nt=_e.tool;_e.id&&Hi(nt)&&me.add(_e.id)}if(i?.isFirstAssistantInTurn)for(const _e of i.activityParts){if(_e.kind!=="tool")continue;const nt=_e.part;nt.id&&Hi(nt.tool)&&me.add(nt.id)}const Pe=new Set(me);for(const _e of M)Pe.has(_e)?Pe.delete(_e):Pe.add(_e);return Pe},[M,S,K,i]),be=l.useMemo(()=>{if(!R)return;const me=r.parts.find(Mt=>Mt.type==="agent");if(!me)return;const Pe=me,_e=typeof Pe.name=="string"?Pe.name:void 0;if(!_e)return;const nt=Pe.source&&typeof Pe.source.value=="string"&&Pe.source.value.trim().length>0?Pe.source.value:`#${_e}`;return{name:_e,token:nt}},[R,r.parts]),H=l.useMemo(()=>{let me=0,Pe=0;return X.forEach(_e=>{_e.type==="step-start"?me+=1:_e.type==="step-finish"&&(Pe+=1)}),{hasOpenStep:me>Pe}},[X]).hasOpenStep,V=l.useMemo(()=>R?!1:te.length===0||K.length===0?H:!0,[te.length,K.length,H,R]),L=u?.metadata.variant,Q=l.useMemo(()=>L?L==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[L]),ke=l.useMemo(()=>u?Nc(u):Q?Xh:Jh,[u,Q]),De=l.useMemo(()=>R?!1:Os.getInstance().shouldAnimateMessage(r.info,g||r.info.sessionID),[r.info,g,R]),Oe=l.useMemo(()=>s?ho(s.info):null,[s]),ct=l.useMemo(()=>t?ho(t.info):null,[t]),Ue=l.useMemo(()=>R||!Oe?!0:Oe.isUser,[R,Oe]),Ge=l.useMemo(()=>R||!ct?!1:!ct.isUser&&ct.role==="assistant",[R,ct]),Xe=l.useMemo(()=>O?"completed":m||(h?"streaming":"completed"),[O,m,h]),Ze=l.useCallback(me=>{navigator.clipboard.writeText(me),D(me),setTimeout(()=>D(null),2e3)},[]),Be=i?.turnId,ze=lt(me=>{if(!Be)return;const Pe=r.info.sessionID;if(!Pe)return;const _e=me.messages.get(Pe);if(!_e)return;const nt=_e.find(Ct=>Ct.info?.id===Be);if(!nt)return;const Qe=nt.info.summary?.body;return typeof Qe=="string"&&Qe.trim().length>0?Qe:void 0}),dt=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:ze,mt=l.useRef(void 0);dt&&dt.trim().length>0&&(mt.current=dt);const Se=l.useRef(Be);Se.current!==Be&&(Se.current=Be,mt.current=void 0);const P=mt.current,se=l.useMemo(()=>R?_.filter(_e=>_e.type==="text").map(_e=>(_e.text||_e.content||"").trim()).filter(_e=>_e.length>0).join(`
|
|
89
|
-
`).replace(/\n\s*\n+/g,`
|
|
90
|
-
`):P&&P.trim().length>0?P:$l(_),[P,_,R]),re=se.length>0,pe=l.useCallback(()=>{navigator.clipboard.writeText(se),N(!0),setTimeout(()=>N(!1),2e3)},[se]),Te=l.useCallback(me=>{C(Pe=>{const _e=new Set(Pe);return _e.has(me)?_e.delete(me):_e.add(me),_e})},[]),Je=o??null,Re=l.useRef(!1),qe=l.useRef(!1),ut=l.useRef(!1),Dt=l.useRef(!1),pt=l.useRef(!1);l.useEffect(()=>{qe.current=!1,ut.current=!1,Dt.current=!1,pt.current=!1,Re.current=!1},[r.info.id]);const kt=l.useCallback(()=>{R||Re.current||(Re.current=!0,n?.("structural"))},[R,n]),bt=l.useCallback(me=>{me.image&&F(me)},[]),ht=l.useCallback(me=>{F(Pe=>({...Pe,open:me}))},[]),Et=!!ws(r.info,"animationSettled"),I=Xe==="streaming",ne=l.useMemo(()=>R?!1:X.some(me=>me.type==="reasoning"),[R,X]),we=De&&!Et&&!I,ve=!R&&De&&te.length>0&&!V;return l.useEffect(()=>{if(Je?.onStreamingCandidate){if(!ve){ut.current&&(ne&&Je?.onReasoningBlock?Je.onReasoningBlock():Je?.onReservationCancelled&&Je.onReservationCancelled(),ut.current=!1);return}pt.current||(pt.current=!0,Je.onStreamingCandidate(),ut.current=!0)}},[Je,ve,ne]),l.useEffect(()=>{Je?.onAnimationStart&&we&&(Dt.current||(Je.onAnimationStart(),Dt.current=!0))},[Je,we]),l.useEffect(()=>{if(R)return;const me=Je?.onAnimatedHeightChange;if(!me||!(we||ve))return;const _e=p.current;if(!_e)return;if(typeof window>"u"||typeof ResizeObserver>"u"){me(_e.getBoundingClientRect().height);return}let nt=null;const Mt=Ct=>{if(typeof window>"u"){me(Ct);return}nt!==null&&window.cancelAnimationFrame(nt),nt=window.requestAnimationFrame(()=>{me(Ct)})},Qe=new ResizeObserver(Ct=>{const Ft=Ct[0];Ft&&Mt(Ft.contentRect.height)});return Qe.observe(_e),Mt(_e.getBoundingClientRect().height),()=>{nt!==null&&(window.cancelAnimationFrame(nt),nt=null),Qe.disconnect()}},[we,R,Je,ve]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("group w-full",Ue?"pt-2":"pt-0",R?"pb-2":Ge?"pb-0":"pb-2"),"data-message-id":r.info.id,ref:p,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:R?e.jsx(Gt,{children:e.jsx("div",{className:T("rounded-xl border bg-input/10 dark:bg-input/30 pt-2 pb-2.5 relative"),style:{borderColor:"color-mix(in srgb, var(--primary-muted, var(--primary)) 40%, var(--interactive-border, transparent))"},children:e.jsx(zi,{messageId:r.info.id,parts:X,isUser:R,isMessageCompleted:O,syntaxTheme:ke,isMobile:c,hasTouchInput:d,copiedCode:w,onCopyCode:Ze,expandedTools:M,onToggleTool:Te,onShowPopup:bt,streamPhase:Xe,allowAnimation:we,onContentChange:n,shouldShowHeader:!1,hasTextContent:re,onCopyMessage:pe,copiedMessage:A,showReasoningTraces:v,onAuxiliaryContentComplete:kt,agentMention:be})})}):e.jsxs("div",{children:[Ue&&e.jsx(Qh,{isUser:R,providerID:oe,agentName:We,modelName:B,isDarkTheme:Q}),e.jsx(zi,{messageId:r.info.id,parts:X,isUser:R,isMessageCompleted:O,syntaxTheme:ke,isMobile:c,hasTouchInput:d,copiedCode:w,onCopyCode:Ze,expandedTools:ae,onToggleTool:Te,onShowPopup:bt,streamPhase:Xe,allowAnimation:we,onContentChange:n,shouldShowHeader:Ue,hasTextContent:re,onCopyMessage:pe,copiedMessage:A,onAuxiliaryContentComplete:kt,showReasoningTraces:v,agentMention:be,turnGroupingContext:i})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(Kg,{popup:E,onOpenChange:ht,syntaxTheme:ke,isMobile:c})})]})},Jg=l.memo(Xg),Zg=r=>{const s="h-3 w-3",t=r.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(Ns,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Ws,{className:s}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(No,{className:s}):e.jsx(Qo,{className:s})},Qg=r=>{const s=r.toLowerCase();return s==="edit"||s==="multiedit"||s==="str_replace"||s==="str_replace_based_edit_tool"?"edit":s==="bash"||s==="shell"||s==="cmd"||s==="terminal"||s==="shell_command"?"bash":s==="webfetch"||s==="fetch"||s==="curl"||s==="wget"?"webfetch":r},ex=({permission:r,onResponse:s})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=ge(),{currentTheme:c}=jr(),d=l.useMemo(()=>Nc(c),[c]),u=async b=>{n(!0);try{await i(r.sessionID,r.id,b),a(!0),s?.(b)}catch{}finally{n(!1)}};if(o)return null;const p=r.type||"Unknown Tool",f=p.toLowerCase(),m=(b,k="")=>{const j=r.metadata[b];return typeof j=="string"?j:typeof j=="number"?String(j):k},h=b=>{const k=r.metadata[b];return typeof k=="number"?k:void 0},g=b=>!!r.metadata[b],x=Qg(p),y=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const j=m("command")||m("cmd")||m("script"),v=m("description"),S=m("cwd")||m("working_directory")||m("directory")||m("path"),w=h("timeout"),D=r.title===j;return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),S&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Working Directory:"})," ",e.jsx("code",{className:"px-1 py-0.5 bg-muted/30 rounded",children:S})]}),w&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",w,"ms"]}),j&&!D&&e.jsx("div",{children:e.jsx(Ss,{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:j})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const j=m("path")||m("file_path")||m("filename")||m("filePath"),v=m("old_str")||m("oldString")||m("old_content")||m("before"),S=m("new_str")||m("newString")||m("new_content")||m("after"),w=m("changes")||m("diff"),D=g("replace_all")||g("replaceAll");return e.jsxs(e.Fragment,{children:[j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"File Path:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:j})]}),D&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),w?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Changes:"}),e.jsx(Ye,{outerClassName:"max-h-64",className:"overflow-x-auto p-0",children:e.jsx(Ss,{language:"diff",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!1,children:w})})]}):e.jsxs(e.Fragment,{children:[v&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Remove:"}),e.jsx(Ye,{outerClassName:"max-h-32 border border-red-500/20 rounded bg-red-500/5 p-2",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono text-red-600 dark:text-red-400 whitespace-pre-wrap break-all",children:v.length>500?v.substring(0,500)+"...":v})})]}),S&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Replace with:"}),e.jsx(Ye,{outerClassName:"max-h-32 border border-green-500/20 rounded bg-green-500/5 p-2",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono text-green-600 dark:text-green-400 whitespace-pre-wrap break-all",children:S.length>500?S.substring(0,500)+"...":S})})]})]})]})}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const j=m("url")||m("uri")||m("endpoint"),v=m("method")||"GET",S=r.metadata.headers&&typeof r.metadata.headers=="object"?r.metadata.headers:void 0,w=m("body")||m("data")||m("payload"),D=h("timeout"),A=m("format")||m("responseType");return e.jsxs(e.Fragment,{children:[j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"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:v}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:j})]})]}),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(Ye,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(Ss,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(S,null,2)})})]}),w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(Ye,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(Ss,{language:typeof w=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof w=="object"?JSON.stringify(w,null,2):String(w)})})]}),(D||A)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[D&&e.jsxs("span",{children:["Timeout: ",D,"ms"]}),D&&A&&e.jsx("span",{children:" • "}),A&&e.jsxs("span",{children:["Response format: ",A]})]})]})}const b=m("command")||m("content")||m("action")||m("operation"),k=m("description");return e.jsxs(e.Fragment,{children:[k&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:k}),b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(Ye,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(b)})})]}),Object.keys(r.metadata).length>0&&!b&&!k&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(Ye,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(r.metadata,null,2)})})]})]})};return e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20 bg-muted/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-3.5 w-3.5 text-yellow-500"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Permission Required"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Zg(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="",k="text",j=!1;f==="bash"||f==="shell"||f==="shell_command"?(b=m("command")||m("cmd")||m("script"),k="bash",j=!0):f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"?(b=m("path")||m("file_path")||m("filename")||m("filePath"),j=!1):(f==="webfetch"||f==="fetch")&&(b=m("url")||m("uri")||m("endpoint"),j=!1);const v=r.title===b;return v&&b&&j?e.jsx("div",{className:"mb-3",children:e.jsx(Ss,{language:k,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})}):v&&b&&!j?e.jsx("div",{className:"mb-3",children:e.jsx("code",{className:"typography-ui-label px-2 py-1 bg-muted/30 rounded block break-all",children:b})}):r.title?e.jsx("div",{className:T("typography-ui-label text-foreground mb-3",(j||b)&&"font-mono"),children:r.title}):null})(),y()]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:t,className: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(It,{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(jn,{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(hs,{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"})})]})]})})})},tx=new Set(["task"]),sx=r=>typeof r=="string"&&tx.has(r.toLowerCase()),rx=r=>{const s=[];let t=null;return r.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(t={turnId:n.info.id,userMessage:n,assistantMessages:[]},s.push(t)):o==="assistant"&&t&&t.assistantMessages.push(n)}),s},nx=r=>{for(const s of r.assistantMessages)for(const t of s.parts)if(t.type==="step-finish"){const n=t.reason,o=s.info.finish;if(n==="stop"||o==="stop"){const a=s.parts.find(i=>i.type==="text");if(a){const i=a.text??a.content;if(typeof i=="string"&&i.trim().length>0)return i}}}},ox=r=>{const s=nx(r);let t;const o=r.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let m=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),m+=y,h+=b}),g>0&&(t={additions:m,deletions:h,files:g})}let a=!1,i=!1;r.assistantMessages.forEach(m=>{m.parts.forEach(h=>{h.type==="tool"?a=!0:h.type==="reasoning"&&(i=!0)})});const c=[];let d=0;r.assistantMessages.forEach(m=>{const h=m.info.id;m.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,k=typeof b?.end=="number"?b.end:void 0;c.push({id:x,turnId:r.turnId,messageId:h,kind:"tool",part:g,endedAt:k});return}if(g.type==="reasoning"){const y=g.text??g.content;if(typeof y!="string"||y.trim().length===0)return;const b=g.time,k=typeof b?.end=="number"?b.end:void 0;c.push({id:x,turnId:r.turnId,messageId:h,kind:"reasoning",part:g,endedAt:k});return}})});const u=new Map;c.forEach(m=>{if(m.kind==="tool"){const h=m.part.tool;if(sx(h))return}u.set(m.messageId,(u.get(m.messageId)??0)+1)});let p,f=0;for(const m of r.assistantMessages)if(f+=u.get(m.info.id)??0,f>=2){p=m.info.id;break}return{activityParts:c,hasTools:a,hasReasoning:i,summaryBody:s,diffStats:t,activityGroupAnchorMessageId:p}},ax=r=>{const{isWorking:s}=jc(),t=l.useMemo(()=>rx(r),[r]),n=l.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=l.useMemo(()=>{const x=new Map;return t.forEach(y=>{x.set(y.userMessage.info.id,y),y.assistantMessages.forEach(b=>{x.set(b.info.id,y)})}),x},[t]),a=l.useMemo(()=>{const x=new Map;return t.forEach(y=>{x.set(y.turnId,ox(y))}),x},[t]),[i,c]=l.useState(()=>new Map),d=Fe(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]),f=l.useCallback(x=>{c(y=>{const b=new Map(y),k=b.get(x)??{isExpanded:u,previewedPartIds:new Set};return b.set(x,{...k,isExpanded:!k.isExpanded}),b})},[u]),m=l.useCallback((x,y)=>{y.length!==0&&c(b=>{const k=new Map(b),j=k.get(x)??{isExpanded:u,previewedPartIds:new Set},v=new Set(j.previewedPartIds);return y.forEach(S=>{S&&S.trim().length>0&&v.add(S)}),k.set(x,{...j,previewedPartIds:v}),k})},[]),h=l.useCallback(x=>o.get(x),[o]),g=l.useCallback(x=>{const y=o.get(x);if(!y||!y.assistantMessages.some($=>$.info.id===x))return;const k=a.get(y.turnId),j=k?.activityParts??[],v=!!k?.hasTools,S=!!k?.hasReasoning,w=k?.summaryBody,D=k?.diffStats,A=y.assistantMessages[0]?.info.id,N=x===A,M=y.assistantMessages[y.assistantMessages.length-1]?.info.id,C=x===M,E=p(y.turnId),F=s&&n===y.turnId;return{turnId:y.turnId,isFirstAssistantInTurn:N,isLastAssistantInTurn:C,summaryBody:w,activityParts:j,hasTools:v,hasReasoning:S,diffStats:D,activityGroupAnchorMessageId:k?.activityGroupAnchorMessageId,isWorking:F,isGroupExpanded:E.isExpanded,previewedPartIds:E.previewedPartIds,toggleGroup:()=>f(y.turnId),markPartsPreviewed:$=>m(y.turnId,$)}},[p,n,m,o,s,f,a]);return{turns:t,getTurnForMessage:h,getContextForMessage:g}},ix=({messages:r,permissions:s,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:c,pendingAnchorId:d})=>{l.useEffect(()=>{s.length!==0&&t("permission")},[s,t]);const u=l.useMemo(()=>r.filter(f=>!Lo(f.parts)),[r]),{getContextForMessage:p}=ax(u);return e.jsxs("div",{children:[o&&e.jsx("div",{className:"flex justify-center py-3",children:a?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:i,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((f,m)=>e.jsx(Jg,{message:f,previousMessage:m>0?u[m-1]:void 0,nextMessage:m<u.length-1?u[m+1]:void 0,onContentChange:t,animationHandlers:n(f.info.id),scrollToBottom:c,isPendingAnchor:d===f.info.id,turnGroupingContext:p(f.info.id)},f.info.id))}),s.length>0&&e.jsx("div",{children:s.map(f=>e.jsx(ex,{permission:f},f.id))})]})},lx=l.memo(ix);function cx(...r){return s=>{r.forEach(t=>{typeof t=="function"?t(s):t&&typeof t=="object"&&(t.current=s)})}}const Lc=l.forwardRef(({orientation:r="vertical",offset:s=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:c,children:d,...u},p)=>{const f=l.useRef(null),m=l.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const g=l.useMemo(()=>{const k={...i};return k["--scroll-shadow-size"]=`${t}px`,k},[t,i]),x=l.useCallback((k,j,v,S,w)=>{const D=`${S}${w.charAt(0).toUpperCase()}${w.slice(1)}Scroll`;j&&v?(k.dataset[D]="true",k.removeAttribute(`data-${S}-scroll`),k.removeAttribute(`data-${w}-scroll`)):(k.dataset[`${S}Scroll`]=String(j),k.dataset[`${w}Scroll`]=String(v),k.removeAttribute(`data-${S}-${w}-scroll`))},[]),y=l.useCallback(k=>{["top","bottom","top-bottom","left","right","left-right"].forEach(j=>{k.removeAttribute(`data-${j}-scroll`)})},[]),b=l.useCallback(()=>{const k=f.current;if(!k)return;if(!n){y(k);return}const j=r==="vertical"?k.scrollTop>s:k.scrollLeft>s;let v=r==="vertical"?k.scrollTop+k.clientHeight+s<k.scrollHeight:k.scrollLeft+k.clientWidth+s<k.scrollWidth;o&&r==="vertical"&&(v=!1),x(k,j,v,r==="vertical"?"top":"left",r==="vertical"?"bottom":"right");const S=j&&v?"both":j?r==="vertical"?"top":"left":v?r==="vertical"?"bottom":"right":"none";S!==m.current&&(m.current=S,a?.(S))},[y,o,n,s,a,r,x]);return l.useEffect(()=>{const k=f.current;if(!k)return;const j=()=>b(),v=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null,S=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return b(),k.addEventListener("scroll",j,{passive:!0}),v?.observe(k),S?.observe(k,{childList:!0,subtree:!0,characterData:!0}),()=>{k.removeEventListener("scroll",j),v?.disconnect(),S?.disconnect()}},[b]),e.jsx("div",{...u,ref:cx(f,p),className:c,"data-orientation":r,"data-scroll-shadow":h??!0,style:g,children:d})});Lc.displayName="ScrollShadow";const dx=160,ux=({containerRef:r})=>{const[s,t]=l.useState(!0),n=l.useRef(!0),o=l.useRef(!1),a=l.useRef(null),i=l.useRef(null),c=l.useRef(0),d=l.useRef(0),u=l.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),p=l.useCallback(j=>{const v=r.current;if(!v){u();return}i.current===null&&(i.current=j);const S=Math.min(1,(j-i.current)/dx),w=1-Math.pow(1-S,3),D=c.current,A=d.current,N=D+(A-D)*w;if(v.scrollTop=N,S<1){a.current=window.requestAnimationFrame(p);return}v.scrollTop=A,u(),n.current&&(n.current=!1,t(!1))},[u,r,t]),f=l.useCallback((j,v)=>{const S=r.current;if(!S)return;const w=Math.max(0,j),D=v?.instant??!1;if(o.current=!1,typeof window>"u"||D){u(),S.scrollTop=w;const N=w<=1;n.current!==N&&(n.current=N,t(N));return}if(u(),Math.abs(w-S.scrollTop)<=.5){S.scrollTop=w;const N=w<=1;n.current!==N&&(n.current=N,t(N));return}c.current=S.scrollTop,d.current=w,i.current=null,a.current=window.requestAnimationFrame(p)},[u,r,p,t]),m=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),g=l.useCallback(()=>o.current,[]),x=l.useCallback(()=>r.current?.scrollTop??0,[r]),y=l.useCallback(()=>r.current?.scrollHeight??0,[r]),b=l.useCallback(()=>r.current?.clientHeight??0,[r]),k=l.useCallback(()=>{const j=r.current;if(!j)return;o.current&&a.current!==null&&u();const v=j.scrollTop<=1;n.current!==v&&(n.current=v,t(v))},[u,r]);return l.useEffect(()=>{const j=r.current;if(j)return j.addEventListener("wheel",h,{passive:!0}),j.addEventListener("touchstart",h,{passive:!0}),()=>{j.removeEventListener("wheel",h),j.removeEventListener("touchstart",h)}},[r,h]),l.useEffect(()=>()=>{u()},[u]),l.useMemo(()=>({handleScroll:k,scrollToPosition:f,forceManualMode:m,isAtTop:s,isManualOverrideActive:g,getScrollTop:x,getScrollHeight:y,getClientHeight:b}),[k,f,m,s,g,x,y,b])},Wi=typeof window<"u"?l.useLayoutEffect:l.useEffect,Ui=50,Vi=40,mx=.2,fx=.1,px=150,ns=r=>{const s=r.info;return typeof s?.id=="string"?s.id:null},hx=r=>{const s=r.info;if(s?.userMessageMarker===!0)return!0;const t=s?.clientRole,n=s?.role;return t==="user"||n==="user"},gx=({currentSessionId:r,sessionMessages:s,updateViewportAnchor:t,isSyncing:n,isMobile:o,sessionActivityPhase:a})=>{const i=l.useRef(null),c=ux({containerRef:i}),[d,u]=l.useState(null),[p,f]=l.useState(0),[m,h]=l.useState(!1),[g,x]=l.useState(null),y=l.useRef(null),b=l.useRef(null),k=l.useRef(s.length),j=l.useRef(s.length>0?ns(s[0]):null),v=l.useRef(s.length>0?ns(s[s.length-1]):null),S=l.useRef(0),w=l.useRef(0),D=l.useRef(void 0),A=l.useRef(null),N=l.useRef(!1),M=l.useRef(!1),C=r?a?.get(r)??"idle":"idle",E=l.useCallback(ye=>{const ie=Math.max(0,ye);S.current!==ie&&(S.current=ie,f(ie))},[]),F=l.useCallback(()=>{const ye=i.current;ye&&(w.current=ye.clientHeight)},[]),$=l.useCallback(()=>{if(!d)return null;const ye=i.current;return ye?ye.querySelector(`[data-message-id="${d}"]`):null},[d]),R=l.useCallback(()=>{const ye=i.current,ie=S.current;if(!ye||ie<=0)return!0;const je=ye.scrollHeight-ie;return ye.scrollTop+ye.clientHeight<je},[]),Y=l.useCallback((ye,ie)=>{const je=ye.offsetHeight,Ce=ye.offsetTop;if(je>ie*mx){const oe=ie*fx;return Ce+je-oe}else return Ce-Ui},[]),Z=l.useCallback(()=>{const ye=i.current;if(!ye||!A.current)return;const ie=$();if(!ie)return;const je=ye.clientHeight,Ce=ye.scrollHeight,oe=Y(ie,je)+je,B=S.current,J=Ce-B;if(!N.current&&J<oe){const O=oe-J;O>B&&E(O)}},[Y,$,E]),z=l.useCallback(()=>{const ye=i.current;if(!ye){h(!1);return}if(g){h(!1);return}if(!(ye.scrollHeight>ye.clientHeight)){h(!1);return}const je=ye.scrollHeight-ye.scrollTop-ye.clientHeight,Ce=S.current;if(Ce>0){const We=ye.scrollHeight-Ce,oe=ye.scrollTop+ye.clientHeight;h(oe<We)}else h(je>Vi)},[g]),G=l.useCallback(ye=>{const ie=i.current;if(!ie)return;const je=ie.scrollHeight-ie.scrollTop-ie.clientHeight;if(M.current&&C==="idle"&&!n&&!ye?.force&&je>Vi)return;ye?.force&&(M.current=!1);const We=ie.scrollHeight-ie.clientHeight;c.scrollToPosition(Math.max(0,We),ye)},[C,n,c]),W=l.useCallback(ye=>{if(y.current===ye)return;y.current=ye,x(ye);const ie=i.current;if(!ie){x(null);return}const je=ie.scrollHeight,Ce=S.current,We=je-Ce,oe=w.current>0?w.current:ie.clientHeight,J=We-Ui,O=J+oe;let X=0;We<O&&(X=O-We),X!==Ce&&E(X),N.current=!0,window.requestAnimationFrame(()=>{c.scrollToPosition(J,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[c,E]),ce=l.useCallback(ye=>{const ie=i.current;if(!ie||!r)return;ye?.isTrusted&&(M.current=!0),c.handleScroll(),z(),C==="idle"&&S.current>0&&R()&&(E(0),A.current=null,u(null));const{scrollTop:je,scrollHeight:Ce,clientHeight:We}=ie,oe=(je+We/2)/Math.max(Ce,1),B=Math.floor(oe*s.length);t(r,B)},[r,C,R,c,s.length,z,E,t]);l.useEffect(()=>{const ye=i.current;if(ye)return ye.addEventListener("scroll",ce,{passive:!0}),()=>{ye.removeEventListener("scroll",ce)}},[ce]),Wi(()=>{if(typeof window>"u")return;F();const ye=()=>{D.current!==void 0&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{F()},px)};return window.addEventListener("resize",ye),()=>{window.removeEventListener("resize",ye),D.current!==void 0&&window.clearTimeout(D.current)}},[F]),l.useEffect(()=>{r&&r!==b.current&&(b.current=r,Os.getInstance().recordSessionStart(r),k.current=s.length,j.current=s.length>0?ns(s[0]):null,v.current=s.length>0?ns(s[s.length-1]):null,y.current=null,A.current=null,N.current=!1,u(null),S.current=0,f(0),M.current=!1)},[r,s.length]),Wi(()=>{if(n){k.current=s.length,j.current=s.length>0?ns(s[0]):null,v.current=s.length>0?ns(s[s.length-1]):null;return}if(b.current!==r)return;const ye=k.current,ie=s.length;if(ie>ye&&ye>0){const je=j.current,Ce=ns(s[0]),We=ns(s[ie-1]),oe=v.current,B=je!==null&&Ce!==je,J=oe!==null&&We!==oe,O=B&&!J,X=J&&!B;if(O){A.current=null,N.current=!1,u(null),E(0),k.current=ie,j.current=Ce,v.current=We;return}if(X){const te=s.slice(ye,ie).find(hx);if(te){const K=ns(te);K&&(A.current=K,u(K),W(K))}else Z()}}k.current=ie,j.current=s.length>0?ns(s[0]):null,v.current=s.length>0?ns(s[s.length-1]):null},[r,n,Z,W,s]),l.useEffect(()=>{const ye=i.current;if(!ye||typeof ResizeObserver>"u")return;const ie=new ResizeObserver(()=>{Z(),z()});return ie.observe(ye),()=>{ie.disconnect()}},[Z,z]),l.useEffect(()=>{d&&(Z(),z())},[d,Z,z]),l.useEffect(()=>{C==="idle"&&S.current>0&&R()&&(E(0),A.current=null,N.current=!1,u(null))},[C,R,E]),l.useEffect(()=>{z()},[p,z]);const Ne=l.useRef(new Map),Me=l.useCallback(()=>{Z(),z()},[Z,z]),Le=l.useCallback(ye=>{const ie=Ne.current.get(ye);if(ie)return ie;const je={onChunk:()=>{Z()},onComplete:()=>{Z()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{Z()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return Ne.current.set(ye,je),je},[Z]);return{scrollRef:i,handleMessageContentChange:Me,getAnimationHandlers:Le,showScrollButton:m,scrollToBottom:G,spacerHeight:p,pendingAnchorId:g,hasActiveAnchor:d!==null}},xx=()=>{const{currentSessionId:r,messages:s,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,sessionMemoryState:d,isSyncing:u,messageStreamStates:p,trimToViewportWindow:f,sessionActivityPhase:m}=ge(),h=l.useMemo(()=>r?n.get(r)??null:null,[r,n]),{isMobile:g}=At(),x=l.useMemo(()=>r?s.get(r)||[]:[],[r,s]),y=l.useMemo(()=>r?t.get(r)||[]:[],[r,t]),{scrollRef:b,handleMessageContentChange:k,getAnimationHandlers:j,showScrollButton:v,scrollToBottom:S,spacerHeight:w,pendingAnchorId:D,hasActiveAnchor:A}=gx({currentSessionId:r,sessionMessages:x,updateViewportAnchor:c,isSyncing:u,isMobile:g,sessionActivityPhase:m}),M=!!l.useMemo(()=>r?d.get(r)??null:null,[r,d])?.hasMoreAbove,[C,E]=l.useState(!1);l.useEffect(()=>{E(!1)},[r]);const F=l.useRef(null);l.useLayoutEffect(()=>{if(!r||r===F.current)return;F.current=r;const R=b.current;R&&(R.scrollTop=R.scrollHeight-R.clientHeight)},[r,b]);const $=l.useCallback(async()=>{if(!r||C)return;const R=b.current,Y=R?.scrollHeight??null,Z=R?.scrollTop??null;E(!0);try{if(await i(r,"up"),R&&Y!==null&&Z!==null){const z=R.scrollHeight-Y;R.scrollTop=Z+z}}finally{E(!1)}},[r,C,i,b]);return l.useEffect(()=>{if(!r||(s.has(r)?s.get(r)??[]:[]).length>0)return;(async()=>{try{await a(r)}finally{typeof window>"u"?S():window.requestAnimationFrame(()=>{S()})}})()},[r,a,s,S]),r?o&&x.length===0&&!h&&!s.has(r)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:g?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-column space-y-4",children:[1,2,3].map(Y=>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"})]})]},Y))})}),e.jsx(uo,{scrollToBottom:S})]}):x.length===0&&!h?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:g?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Li,{width:140,height:140,className:"opacity-20",isAnimated:!0})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(uo,{scrollToBottom:S})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:g?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(Lc,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:b,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!D,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(lx,{messages:x,permissions:y,onMessageContentChange:k,getAnimationHandlers:j,hasMoreAbove:M,isLoadingOlder:C,onLoadOlder:$,scrollToBottom:S,pendingAnchorId:D}),w>0&&A&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:w},"aria-hidden":"true"})]})}),e.jsx(aa,{containerRef:b})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[v&&x.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:()=>S({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(Ir,{className:"h-4 w-4"})})}),e.jsx(uo,{scrollToBottom:S})]})]}):e.jsx("div",{className:"flex flex-col h-full bg-background",style:g?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Li,{width:140,height:140,className:"opacity-20",isAnimated:!0})})})};class yx 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(ga,{className:"w-full max-w-md",children:[e.jsx(Yl,{className:"text-center",children:e.jsxs(Xl,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(mu,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Jl,{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(As,{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 $o=()=>{const r=ge(s=>s.currentSessionId);return e.jsx(yx,{sessionId:r||void 0,children:e.jsx(xx,{})})},Gi=12,bx=[{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"}],wx=({isActive:r,burstKey:s=0,className:t,durationMs:n=900,bursts:o=bx,onComplete:a})=>{const i=de.useRef(!1);de.useEffect(()=>{!r&&i.current&&a?.(),r&&(i.current=!0)},[r,a]);const c=de.useMemo(()=>Array.from({length:Gi},(d,u)=>{const p=Math.PI*2*u/Gi;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return r?e.jsx("div",{className:T("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:c.map((p,f)=>{const m=p.x*d.radius,h=p.y*d.radius,g={"--translate-x":`${m}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}-${f}-${s}`)})},`${d.id}-${s}`)})}):null},vx=({durationMs:r=3400}={})=>{const[s,t]=de.useState({isActive:!1,cycle:0}),n=de.useRef(null),o=de.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.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})),n.current=window.setTimeout(()=>{t(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},r)},[o,r]);return de.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:i,dismissFireworks:a}},_c=l.createContext(void 0),qi=({children:r})=>{const{isActive:s,burstKey:t,triggerFireworks:n,dismissFireworks:o}=vx(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(_c.Provider,{value:a,children:[r,e.jsx(wx,{isActive:s,burstKey:t})]})},jx=()=>{const r=l.useContext(_c);if(!r)throw new Error("useFireworksCelebration must be used within FireworksProvider");return r};function Sx({...r}){return e.jsx(fu,{"data-slot":"select",...r})}function kx({...r}){return e.jsx(gu,{"data-slot":"select-value",...r})}function Nx({className:r,size:s="default",children:t,...n}){return e.jsxs(pu,{"data-slot":"select-trigger","data-size":s,className:T("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-accent hover:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",r),...n,children:[t,e.jsx(hu,{asChild:!0,children:e.jsx(vt,{className:"size-4 opacity-50"})})]})}function Cx({className:r,children:s,position:t="popper",...n}){return e.jsx(xu,{children:e.jsxs(yu,{"data-slot":"select-content",className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:t,...n,children:[e.jsx(Ax,{}),e.jsx(Ye,{as:bu,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(Dx,{})]})})}function Mx({className:r,children:s,...t}){return e.jsxs(wu,{"data-slot":"select-item",className:T("hover:bg-accent hover:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",r),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(vu,{children:e.jsx(It,{className:"size-4"})})}),e.jsx(ju,{children:s})]})}function Ax({className:r,...s}){return e.jsx(Su,{"data-slot":"select-scroll-up-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(zn,{className:"size-4"})})}function Dx({className:r,...s}){return e.jsx(ku,{"data-slot":"select-scroll-down-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(vt,{className:"size-4"})})}const Ex=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Tx=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,Ix=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}];let Dr=null;const Fx=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=ge(),{currentDirectory:n}=jt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},Px=()=>{const{git:r}=rr(),s=Fx(),{currentSessionId:t,worktreeMetadata:n}=ge(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=Un(),u=Wl(s??null),p=Hl(s??null),f=Wf(s??null),m=Uf(s??null),h=Vf(s??null),g=Nt(I=>I.isLoadingStatus),x=Nt(I=>I.isLoadingLog),{setActiveDirectory:y,fetchAll:b,fetchStatus:k,fetchBranches:j,fetchLog:v,fetchIdentity:S,setLogMaxCount:w}=Nt(),D=l.useMemo(()=>!Dr||Dr.directory!==s?null:Dr,[s]),[A,N]=l.useState(D?.commitMessage??""),[M,C]=l.useState(""),E=l.useMemo(()=>Ex(M),[M]),[F,$]=l.useState(null),[R,Y]=l.useState(null),[Z,z]=l.useState(!1),[G,W]=l.useState(null),[ce,Ne]=l.useState(25),[Me,Le]=l.useState(!1),[ye,ie]=l.useState(!1),[je,Ce]=l.useState(""),[We]=l.useState(null),{triggerFireworks:oe}=jx(),[B,J]=l.useState(()=>new Set(D?.selectedPaths??[])),[O,X]=l.useState(!1),[_,te]=l.useState(new Set),[K,ae]=l.useState(!1),[be,fe]=l.useState([]),H=l.useCallback(()=>{fe([])},[]),[V,L]=l.useState(null),[Q,ke]=l.useState([]),[De,Oe]=l.useState(!1),ct=l.useMemo(()=>!V||!m?null:m.all.find(I=>I.hash===V)??null,[V,m]),Ue=l.useCallback(I=>{navigator.clipboard.writeText(I).then(()=>{xe.success("Commit hash copied")}).catch(()=>{xe.error("Failed to copy")})},[]);l.useEffect(()=>{if(!V||!s||!r){ke([]);return}let I=!1;return Oe(!0),r.getCommitFiles(s,V).then(ne=>{I||ke(ne.files)}).catch(ne=>{console.error("Failed to fetch commit files:",ne),I||ke([])}).finally(()=>{I||Oe(!1)}),()=>{I=!0}},[V,s,r]),l.useEffect(()=>()=>{if(!s){Dr=null;return}Dr={directory:s,selectedPaths:Array.from(B),commitMessage:A}},[A,s,B]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{s&&(y(s),Nt.getState().directories.get(s)?.status||b(s,r,{force:!0}))},[s,y,b,r]);const Ge=l.useCallback(async(I=!0)=>{if(s)try{await Promise.all([k(s,r),j(s,r)])}catch(ne){if(I){const we=ne instanceof Error?ne.message:"Failed to refresh repository state";xe.error(we)}}},[s,r,k,j]),Xe=l.useCallback(async()=>{s&&await v(s,r,ce)},[s,r,v,ce]),Ze=l.useCallback(async()=>{s&&await S(s,r)},[s,r,S]),Be=l.useMemo(()=>{if(!p)return[];const I=p.files??[],ne=new Map;return I.forEach(we=>{ne.set(we.path,we)}),Array.from(ne.values()).sort((we,ve)=>we.path.localeCompare(ve.path))},[p]);l.useEffect(()=>{if(!p||Be.length===0){J(new Set),X(!1);return}J(I=>{const ne=new Set,we=I??new Set;return Be.forEach(ve=>{we.has(ve.path)?ne.add(ve.path):O||ne.add(ve.path)}),ne})},[p,Be,O]);const ze=async I=>{if(s){$(I);try{if(I==="fetch")await r.gitFetch(s),xe.success("Fetched latest updates");else if(I==="pull"){const ne=await r.gitPull(s);xe.success(`Pulled ${ne.files.length} file${ne.files.length===1?"":"s"}`)}else I==="push"&&(await r.gitPush(s),xe.success("Pushed to remote"));W(`${I.toUpperCase()} completed at ${new Date().toLocaleTimeString()}`),await Ge(!1),await Xe()}catch(ne){const we=ne instanceof Error?ne.message:`Failed to ${I==="pull"?"pull":I}`;xe.error(we)}finally{$(null)}}},dt=async(I={})=>{if(!s)return;if(!A.trim()){xe.error("Please enter a commit message");return}const ne=Array.from(B).sort();if(ne.length===0){xe.error("Select at least one file to commit");return}const we=I.pushAfter?"commitAndPush":"commit";Y(we);try{await r.createGitCommit(s,A.trim(),{files:ne}),xe.success("Commit created successfully"),N(""),J(new Set),X(!1),await Ge(),I.pushAfter?(await r.gitPush(s),xe.success("Pushed to remote"),oe(),await Ge(!1)):await Ge(!1),await Xe()}catch(ve){const me=ve instanceof Error?ve.message:"Failed to create commit";xe.error(me)}finally{Y(null)}},mt=l.useCallback(async()=>{if(s){if(B.size===0){xe.error("Select at least one file to describe");return}ae(!0);try{const{message:I}=await r.generateCommitMessage(s,Array.from(B)),ne=I.subject?.trim()??"",we=Array.isArray(I.highlights)?I.highlights:[];ne&&N(ne),fe(we),xe.success("Commit message generated")}catch(I){const ne=I instanceof Error?I.message:"Failed to generate commit message";xe.error(ne)}finally{ae(!1)}}},[s,B,r]),Se=async()=>{if(!s||!p)return;const I=E;if(!I){xe.error('Provide a branch name using letters, numbers, ".", "_", "-" or "/".');return}const ne=p.current??null;z(!0);try{await r.createBranch(s,I,ne??"HEAD"),xe.success(`Created branch ${I}`);let we=!1;try{await r.checkoutBranch(s,I),await r.gitPush(s,{remote:"origin",branch:I,options:["--set-upstream"]}),we=!0}catch(ve){const me=ve instanceof Error?ve.message:"Unable to push new branch to origin.";xe.warning("Branch created locally",{description:Tx(`Upstream setup failed: ${me}`)})}finally{if(ne)try{await r.checkoutBranch(s,ne)}catch(ve){console.warn("Failed to restore original branch after creation:",ve)}}C(""),await Ge(),await Xe(),we&&xe.success(`Upstream set for ${I}`)}catch(we){const ve=we instanceof Error?we.message:"Failed to create branch";xe.error(ve)}finally{z(!1)}},P=async I=>{if(!s)return;const ne=I.replace(/^remotes\//,"");if(p?.current===ne){ie(!1);return}try{await r.checkoutBranch(s,ne),xe.success(`Checked out ${ne}`),ie(!1),Ce(""),await Ge();const we=p?.current;we&&(await r.checkoutBranch(s,we),xe.success(`Checked out ${we}`)),await Xe()}catch(we){const ve=we instanceof Error?we.message:`Failed to checkout ${ne}`;xe.error(ve)}},se=async I=>{if(s){Le(!0);try{await r.setGitIdentity(s,I.id),xe.success(`Applied "${I.name}" to repository`),await Ze()}catch(ne){const we=ne instanceof Error?ne.message:"Failed to apply git identity";xe.error(we)}finally{Le(!1)}}},re=l.useMemo(()=>f?.all?f.all.filter(I=>!I.startsWith("remotes/")).sort():[],[f]),pe=l.useMemo(()=>f?.all?f.all.filter(I=>I.startsWith("remotes/")).map(I=>I.replace(/^remotes\//,"")).sort():[],[f]),Te=l.useMemo(()=>{const I=je.trim().toLowerCase();return I?{locals:re.filter(ne=>ne.toLowerCase().includes(I)),remotes:pe.filter(ne=>ne.toLowerCase().includes(I))}:{locals:re,remotes:pe}},[je,re,pe]);l.useEffect(()=>{ye||Ce("")},[ye]);const Je=l.useMemo(()=>{const I=new Map;i&&I.set(i.id,i);for(const ne of a)I.set(ne.id,ne);return Array.from(I.values())},[a,i]),Re=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const I=a.find(ne=>ne.userName===h.userName&&ne.userEmail===h.userEmail);return I||(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]),qe=Be.length,ut=B.size,Dt=g||F!==null||R!==null,pt=I=>{J(ne=>{const we=new Set(ne);return we.has(I)?we.delete(I):we.add(I),we}),X(!0)},kt=()=>{const I=new Set(Be.map(ne=>ne.path));J(I),X(!0)},bt=()=>{J(new Set),X(!0)},ht=l.useCallback(async I=>{if(s){te(ne=>{const we=new Set(ne);return we.add(I),we});try{await r.revertGitFile(s,I),xe.success(`Reverted ${I}`),await Ge(!1)}catch(ne){const we=ne instanceof Error?ne.message:"Failed to revert changes";xe.error(we)}finally{te(ne=>{const we=new Set(ne);return we.delete(I),we})}}},[s,Ge,r]);if(!s)return 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."})});if(g&&u===null)return 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($t,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository…"})]})});if(u===!1)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(zt,{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."})]});const Et=qe>0;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[p&&e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 border-b border-border/40 px-3 py-2 bg-background",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zt,{className:"size-4 text-primary"}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:p.current||"Detached HEAD"}),p.tracking&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["→ ",p.tracking]})]}),e.jsxs("div",{className:"flex items-center gap-3 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx(Tr,{className:"inline size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground ml-0.5",children:p.ahead})]}),e.jsxs("span",{children:[e.jsx(Ir,{className:"inline size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground ml-0.5",children:p.behind})]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:p.files.length})," changes"]})]}),e.jsx("div",{className:"flex-1"}),e.jsx(_x,{activeProfile:Re,identities:Je,onSelect:se,isApplying:Me})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 px-3 py-2 border-b border-border/40 bg-background/80",children:[e.jsxs(Ls,{variant:"default",onClick:()=>ze("fetch"),disabled:F!==null||!p,children:[F==="fetch"?e.jsx($t,{size:16,className:"animate-spin"}):e.jsx(Wn,{size:16}),"Fetch"]}),e.jsxs(Ls,{variant:"default",onClick:()=>ze("pull"),disabled:F!==null||!p,children:[F==="pull"?e.jsx($t,{size:16,className:"animate-spin"}):e.jsx(Ir,{size:16}),"Pull"]}),e.jsxs(Ls,{variant:"default",onClick:()=>ze("push"),disabled:F!==null||!p,children:[F==="push"?e.jsx($t,{size:16,className:"animate-spin"}):e.jsx(Tr,{size:16}),"Push"]}),e.jsx("div",{className:"hidden sm:block w-px h-6 bg-border/60 mx-1"}),!o&&e.jsxs(e.Fragment,{children:[e.jsxs(Kt,{open:ye,onOpenChange:ie,children:[e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Yt,{asChild:!0,children:e.jsxs(Ee,{variant:"outline",size:"sm",className:"gap-1.5 px-2 py-1 h-8",children:[e.jsx(zt,{className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:p?.current||"Branch"}),e.jsx(vt,{className:"size-4 opacity-60"})]})})}),e.jsxs(ft,{sideOffset:8,children:["Switch branch (",re.length," local · ",pe.length," remote)"]})]}),e.jsx(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(lc,{className:"h-full min-h-0",children:[e.jsx(cc,{placeholder:"Search branches…",value:je,onValueChange:Ce}),e.jsxs(dc,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(uc,{children:"No branches found."}),e.jsxs(Lr,{heading:"Local branches",children:[Te.locals.map(I=>e.jsxs(_t,{onSelect:()=>P(I),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:I}),f?.branches?.[I]?.ahead||f?.branches?.[I]?.behind?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[f.branches[I].ahead||0," ahead ·"," ",f.branches[I].behind||0," behind"]}):null]}),p?.current===I&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${I}`)),Te.locals.length===0&&e.jsx(_t,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Fo,{}),e.jsxs(Lr,{heading:"Remote branches",children:[Te.remotes.map(I=>e.jsx(_t,{onSelect:()=>P(I),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:I})},`remote-${I}`)),Te.remotes.length===0&&e.jsx(_t,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]}),e.jsx(Tt,{placeholder:"New branch",value:M,onChange:I=>C(I.target.value),className:"h-8 w-32 sm:w-40 rounded-lg bg-background/80 text-sm"}),e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Ee,{variant:"default",size:"sm",className:"h-8 px-2",onClick:Se,disabled:Z||!E,children:Z?e.jsx($t,{className:"size-4 animate-spin"}):e.jsx(ls,{className:"size-4"})})}),e.jsx(ft,{sideOffset:8,children:E?`Create branch "${E}"`:"Enter branch name"})]})]}),e.jsx("div",{className:"flex-1"}),G&&e.jsx("span",{className:"typography-micro text-muted-foreground hidden lg:inline",children:G})]}),We&&e.jsxs("div",{className:"mx-3 mt-3 rounded-xl border border-destructive/30 bg-destructive/10 px-3 py-2",children:[e.jsx("p",{className:"typography-ui-label text-destructive",children:We}),e.jsx("p",{className:"typography-meta text-destructive/80",children:"Try refreshing or confirm the repository is accessible."})]}),e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[e.jsxs("section",{className:"flex flex-col rounded-2xl border border-border/60 bg-background/70 min-h-[280px] max-h-[400px]",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:[ut,"/",qe]}),qe>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ee,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:kt,children:"All"}),e.jsx(Ee,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:bt,disabled:ut===0,children:"None"})]})]})]}),e.jsx(Ye,{outerClassName:"flex-1 min-h-0",className:"w-full",children:p?.isClean||qe===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("div",{className:"text-center",children:e.jsxs("div",{className:"inline-flex items-center gap-2 rounded-xl border border-emerald-500/40 bg-emerald-500/10 px-4 py-3",children:[e.jsx(wo,{className:"size-5",style:{color:"var(--status-success)"}}),e.jsx("p",{className:"typography-ui-label",style:{color:"var(--status-success)"},children:"Working tree clean"})]})})}):e.jsx("ul",{className:"divide-y divide-border/60",children:Be.map(I=>e.jsx(Rx,{file:I,checked:B.has(I.path),stats:p?.diffStats?.[I.path],onToggle:()=>pt(I.path),onViewDiff:()=>Fe.getState().navigateToDiff(I.path),onRevert:()=>ht(I.path),isReverting:_.has(I.path)},I.path))})})]}),e.jsxs("section",{className:"flex flex-col rounded-2xl border border-border/60 bg-background/70 min-h-[280px]",children:[e.jsx("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:"Commit"})}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col p-3 gap-3",children:[be.length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-background/60 px-3 py-2 shrink-0",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(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Ee,{variant:"ghost",size:"icon",className:"size-6",onClick:()=>{if(be.length===0)return;const I=be.map(ne=>ne.trim()).filter(Boolean);if(I.length===0){H();return}N(ne=>{const we=ne.trim(),ve=we.length>0?`
|
|
91
|
-
|
|
92
|
-
`:"";return`${we}${ve}${I.join(`
|
|
93
|
-
`)}`.trim()}),H()},"aria-label":"Insert highlights into commit message",children:e.jsx(Ir,{className:"size-4"})})}),e.jsx(ft,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:be.map((I,ne)=>e.jsx("li",{className:"typography-meta text-foreground",children:I},ne))})]}),e.jsx(tr,{value:A,onChange:I=>N(I.target.value),placeholder:Et?"Commit message":"No changes to commit",rows:be.length>0?4:8,disabled:R!==null||!Et,className:T("flex-1 rounded-lg bg-background/80 resize-none",be.length>0?"min-h-[80px]":"min-h-[180px]")}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Ls,{variant:"ghost",onClick:mt,disabled:K||R!==null||ut===0||Dt,className:"px-3","aria-label":"Generate commit message",children:K?e.jsx($t,{className:"size-4 animate-spin"}):e.jsx(Nu,{className:"size-4 text-primary"})})}),e.jsx(ft,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Ls,{variant:"outline",onClick:()=>{H(),dt({pushAfter:!1})},disabled:R!==null||!A.trim()||ut===0||K,children:R==="commit"?e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"size-4 animate-spin"}),"Committing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(wo,{className:"size-4"}),"Commit"]})}),e.jsx(Ls,{variant:"default",onClick:()=>{H(),dt({pushAfter:!0})},disabled:R!==null||!A.trim()||ut===0||K,children:R==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx($t,{className:"size-4 animate-spin"}),"Pushing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Tr,{className:"size-4"}),"Commit & Push"]})})]})]})]}),m&&e.jsxs("section",{className:"lg:col-span-2 rounded-2xl border border-border/60 bg-background/70 flex flex-col min-h-[200px]",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40 shrink-0",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"History"}),e.jsxs(Sx,{value:String(ce),onValueChange:I=>{const ne=Number(I);Ne(ne),s&&(w(s,ne),v(s,r,ne))},disabled:x,children:[e.jsx(Nx,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:x,children:e.jsx(kx,{placeholder:"Commits"})}),e.jsx(Cx,{children:Ix.map(I=>e.jsx(Mx,{value:String(I.value),children:I.label},I.value))})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 grid grid-cols-1 lg:grid-cols-2 divide-y lg:divide-y-0 lg:divide-x divide-border/40",children:[e.jsx(Ye,{outerClassName:"min-h-0 max-h-48 lg:max-h-64",className:"w-full",children:m.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:m.all.map(I=>e.jsx(Lx,{entry:I,isSelected:V===I.hash,onSelect:()=>L(I.hash)},I.hash))})}),e.jsx("div",{className:"flex flex-col min-h-[120px] lg:min-h-0 overflow-hidden",children:ct?e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[e.jsxs("div",{className:"p-3 pb-2 shrink-0 border-b border-border/40",children:[e.jsx("p",{className:"typography-ui-label font-semibold text-foreground line-clamp-2",children:ct.message}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[e.jsx("span",{className:"text-foreground",children:ct.author_name}),e.jsx("span",{children:Oc(ct.date)}),e.jsx("code",{className:"font-mono",children:ct.hash.slice(0,8)}),e.jsxs(gt,{delayDuration:500,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Ee,{variant:"ghost",size:"sm",className:"h-5 px-1.5 -ml-1",onClick:()=>Ue(ct.hash),children:e.jsx(Rs,{className:"size-3"})})}),e.jsx(ft,{sideOffset:8,children:"Copy SHA"})]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden",children:[e.jsx("div",{className:"px-3 py-2 border-b border-border/40 shrink-0",children:e.jsx("span",{className:"typography-micro text-muted-foreground",children:De?"Loading...":`${Q.length} file${Q.length===1?"":"s"}`})}),e.jsx(Ye,{outerClassName:"flex-1 min-h-0 max-h-32",className:"w-full",children:De?e.jsx("div",{className:"flex items-center justify-center p-3",children:e.jsx($t,{className:"size-4 animate-spin text-muted-foreground"})}):Q.length===0?e.jsx("div",{className:"p-3 text-center",children:e.jsx("p",{className:"typography-micro text-muted-foreground",children:"No files"})}):e.jsx("ul",{className:"divide-y divide-border/40",children:Q.map(I=>e.jsxs("li",{className:"flex items-center gap-2 px-3 py-1.5",children:[e.jsx("span",{className:T("typography-micro font-semibold w-4 shrink-0 text-center",I.changeType==="A"&&"text-emerald-500",I.changeType==="D"&&"text-red-500",I.changeType==="M"&&"text-amber-500",I.changeType==="R"&&"text-blue-500"),children:I.changeType}),e.jsx("span",{className:"typography-micro text-foreground truncate flex-1",title:I.path,children:I.path}),!I.isBinary&&e.jsxs("span",{className:"typography-micro shrink-0",children:[e.jsxs("span",{className:"font-semibold",style:{color:"var(--status-success)"},children:["+",I.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{className:"font-semibold",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))})})]})]}):e.jsx("div",{className:"flex h-full items-center justify-center text-center p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a commit to view details"})})})]})]})]})})]})},Rx=({file:r,checked:s,onToggle:t,onViewDiff:n,onRevert:o,isReverting:a,stats:i})=>{const c=l.useMemo(()=>Bx(r),[r]),d=c.description??c.code,u=i?.insertions??0,p=i?.deletions??0;return e.jsx("li",{children:e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 hover:bg-sidebar/40 cursor-pointer",role:"button",tabIndex:0,onClick:n,onKeyDown:f=>{f.key===" "?(f.preventDefault(),t()):f.key==="Enter"&&(f.preventDefault(),n())},children:[e.jsx("button",{type:"button",onClick:f=>{f.preventDefault(),f.stopPropagation(),t()},"aria-pressed":s,"aria-label":`Select ${r.path}`,className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:s?e.jsx(Xo,{className:"size-4 text-primary"}):e.jsx(Jo,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold uppercase tracking-wide",style:{color:c.color},title:d,"aria-label":d,children:c.code}),e.jsx("span",{className:"flex-1 min-w-0 break-words typography-ui-label text-foreground",title:r.path,children:r.path}),e.jsxs("span",{className:"shrink-0 typography-micro font-semibold",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",u]}),e.jsx("span",{className:"mx-0.5 text-muted-foreground",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",p]})]}),e.jsxs(gt,{delayDuration:200,children:[e.jsx(xt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f=>{f.preventDefault(),f.stopPropagation(),o()},disabled:a,className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:a?e.jsx($t,{className:"size-4 animate-spin"}):e.jsx(Wn,{className:"size-4"})})}),e.jsx(ft,{sideOffset:8,children:"Revert changes"})]})]})})},Lx=({entry:r,isSelected:s,onSelect:t})=>e.jsxs("li",{className:T("flex items-start gap-3 px-3 py-2 cursor-pointer transition-colors",s?"bg-sidebar/90":"hover:bg-sidebar/40"),onClick:t,role:"button",tabIndex:0,onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),t?.())},children:[e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:r.message}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[r.author_name," · ",Oc(r.date)]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:r.hash.slice(0,8)})]})]}),_x=({activeProfile:r,identities:s,onSelect:t,isApplying:n})=>{const o=n||s.length===0;return e.jsxs(Kt,{children:[e.jsxs(gt,{delayDuration:1e3,children:[e.jsx(xt,{asChild:!0,children:e.jsx(Yt,{asChild:!0,children:e.jsxs(Ee,{variant:"outline",size:"sm",className:"gap-2 px-3 py-1 typography-ui-label",style:{color:Bc(r?.color)},disabled:o,children:[n?e.jsx($t,{className:"size-4 animate-spin"}):e.jsx(Ki,{icon:r?.icon,colorToken:r?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[180px] truncate",children:r?.name||"No identity"}),e.jsx(vt,{className:"size-4 opacity-60"})]})})}),e.jsxs(ft,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:r?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:r?.userEmail||"No email configured"})]})]}),e.jsx(Xt,{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(yt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ki,{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))})]})};function Bx(r){const s=r.index&&r.index.trim()&&r.index.trim()!=="?"?r.index.trim():r.working_dir&&r.working_dir.trim()?r.working_dir.trim():r.index||r.working_dir||" ";switch(s.trim().charAt(0)||s.trim()||"·"){case"?":return{code:"?",color:"var(--status-info)",description:"Untracked file"};case"A":return{code:"A",color:"var(--status-success)",description:"New file"};case"D":return{code:"D",color:"var(--status-error)",description:"Deleted file"};case"R":return{code:"R",color:"var(--status-info)",description:"Renamed file"};case"C":return{code:"C",color:"var(--status-info)",description:"Copied file"};default:return{code:"M",color:"var(--status-warning)",description:"Modified file"}}}const Ox={branch:zt,briefcase:Ko,house:qo,graduation:Go,code:zs,heart:hl,user:$n},$x={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 Bc(r){return r&&$x[r]||"var(--primary)"}const Ki=({icon:r,className:s,colorToken:t})=>{const n=Ox[r??"branch"]??$n;return e.jsx(n,{className:s,style:{color:Bc(t)}})};function Oc(r){const s=new Date(r);return Number.isNaN(s.getTime())?r:s.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const zx=256e3;function Xs(r){let s=r.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const ln=r=>({directory:r,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Yi=Ot((r,s)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=Xs(t);return s().sessions.get(n)},setTerminalSession:(t,n)=>{const o=Xs(t);r(a=>{const i=new Map(a.sessions),c=i.get(o),u=!c||c.terminalSessionId!==n.sessionId?ln(o):c??ln(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=Xs(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??ln(o);return i.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=Xs(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??ln(o),d=a.nextChunkId,u={id:d,data:n},p=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>zx&&p.length>1;){const h=p.shift();if(!h)break;f-=h.data.length}const m=p.map(h=>h.data).join("");return i.set(o,{...c,buffer:m,bufferChunks:p,bufferLength:f,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=Xs(t);r(o=>{const a=new Map(o.sessions),i=a.get(n);return i&&a.set(n,{...i,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const n=Xs(t);r(o=>{const a=new Map(o.sessions),i=a.get(n);return i?(a.set(n,{...i,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const n=Xs(t);r(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{r({sessions:new Map,nextChunkId:1})}})),$c=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Hx=[{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'}],Wx=[{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'}],zc=r=>Object.fromEntries(r.map(s=>[s.id,s])),Xi=zc(Hx),Js=zc(Wx),Ux="ibm-plex-sans",bn="ibm-plex-mono";function Vx(r){const{colors:s}=r,t=s.syntax.base;return{background:s.surface.background,foreground:t.foreground,cursor:s.interactive.cursor,cursorAccent:s.surface.background,selectionBackground:s.interactive.selection,selectionForeground:s.interactive.selectionForeground,selectionInactiveBackground:s.interactive.selection+"50",black:s.surface.muted,red:s.status.error,green:s.status.success,yellow:s.status.warning,blue:t.function,magenta:t.keyword,cyan:t.type,white:t.foreground,brightBlack:t.comment,brightRed:s.status.error,brightGreen:s.status.success,brightYellow:s.status.warning,brightBlue:t.function,brightMagenta:t.keyword,brightCyan:t.type,brightWhite:s.surface.elevatedForeground}}function Ji(r,s,t){return{fontFamily:`${r}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`,fontSize:s,lineHeight:1,cursorBlink:!0,cursorStyle:"block",theme:t,allowTransparency:!1,scrollback:1e4,minimumContrastRatio:1,fastScrollModifier:"shift",fastScrollSensitivity:5,scrollSensitivity:3,macOptionIsMeta:!0,macOptionClickForcesSelection:!1,rightClickSelectsWord:!0}}const zo=l.forwardRef(({sessionKey:r,chunks:s,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:c,enableTouchScroll:d},u)=>{const p=l.useRef(null),f=l.useRef(null),m=l.useRef(null),h=l.useRef(null),g=l.useRef(t),x=l.useRef(n),y=l.useRef([]),b=l.useRef(!1),k=l.useRef(0),j=l.useRef(null),v=l.useRef(null),[,S]=l.useReducer(C=>C+1,0);g.current=t,x.current=n;const w=l.useCallback(()=>{y.current=[],b.current=!1,k.current=0,j.current=null},[]),D=l.useCallback(()=>{const C=h.current,E=m.current,F=p.current;if(!C||!E||!F)return;const $=F.getBoundingClientRect();if(!($.width<24||$.height<24))try{C.fit(),x.current(E.cols,E.rows)}catch{}},[]),A=l.useCallback(()=>{if(b.current)return;const C=()=>{const E=m.current;if(!E){w();return}const F=y.current.shift();if(F===void 0){b.current=!1;return}b.current=!0,E.write(F,()=>{b.current=!1,y.current.length>0&&(typeof window<"u"?window.setTimeout(C,0):C())})};C()},[w]),N=l.useCallback(C=>{C&&(y.current=[C],b.current=!1,A())},[A]),M=l.useCallback(()=>{if(v.current?.(),v.current=null,!d)return;const C=p.current;if(!C)return;const E=C.querySelector(".xterm-viewport");if(!E)return;const F=2.2,$=2.8,R=25,Y=.25,Z=8,z=.05,G=.015,W={lastY:null,lastTime:null,velocity:0,rafId:null},ce=()=>typeof performance<"u"?performance.now():Date.now(),Ne=()=>Math.max(0,E.scrollHeight-E.clientHeight),Me=J=>{const O=Ne();E.scrollTop=Math.max(0,Math.min(O,J))},Le=J=>{if(!J)return;const O=E.scrollTop;return Me(O+J),E.scrollTop!==O},ye=()=>{W.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(W.rafId),W.rafId=null},ie={passive:!1,capture:!0};if(typeof window<"u"&&"PointerEvent"in window){const J=Object.assign(W,{pointerId:null}),O=K=>{if(K.pointerType==="touch"){ye(),J.pointerId=K.pointerId,J.lastY=K.clientY,J.lastTime=ce(),J.velocity=0;try{C.setPointerCapture(K.pointerId)}catch{}}},X=K=>{if(K.pointerType!=="touch"||J.pointerId!==K.pointerId)return;if(J.lastY===null){J.lastY=K.clientY,J.lastTime=ce();return}const ae=J.lastY,be=J.lastTime??ce(),fe=ce();J.lastY=K.clientY,J.lastTime=fe;const H=ae-K.clientY;if(Math.abs(H)<1)return;const V=Math.max(fe-be,8),L=F+Math.min($,Math.abs(H)/R),Q=H*L,ke=Q/V;J.velocity=J.velocity*(1-Y)+ke*Y,J.velocity>Z?J.velocity=Z:J.velocity<-Z&&(J.velocity=-Z),K.cancelable&&K.preventDefault(),K.stopPropagation(),Le(Q)},_=K=>{if(K.pointerType!=="touch"||J.pointerId!==K.pointerId)return;J.pointerId=null,J.lastY=null,J.lastTime=null;try{C.releasePointerCapture(K.pointerId)}catch{}if(typeof window>"u")return;if(Math.abs(J.velocity)<z){J.velocity=0;return}let ae=ce();const be=()=>{const fe=ce(),H=Math.max(fe-ae,8);ae=fe;const V=Le(J.velocity*H)??!1,L=Math.sign(J.velocity),Q=Math.max(0,Math.abs(J.velocity)-G*H);if(J.velocity=Q*L,!V||Q<=z){ye(),J.velocity=0;return}J.rafId=window.requestAnimationFrame(be)};J.rafId=window.requestAnimationFrame(be)};C.addEventListener("pointerdown",O,ie),C.addEventListener("pointermove",X,ie),C.addEventListener("pointerup",_,ie),C.addEventListener("pointercancel",_,ie);const te=C.style.touchAction;C.style.touchAction="none",v.current=()=>{ye(),C.removeEventListener("pointerdown",O,ie),C.removeEventListener("pointermove",X,ie),C.removeEventListener("pointerup",_,ie),C.removeEventListener("pointercancel",_,ie),C.style.touchAction=te};return}const Ce=J=>{J.touches.length===1&&(ye(),W.lastY=J.touches[0].clientY,W.lastTime=ce(),W.velocity=0)},We=J=>{if(J.touches.length!==1){W.lastY=null,W.lastTime=null,W.velocity=0,ye();return}const O=J.touches[0].clientY;if(W.lastY===null){W.lastY=O,W.lastTime=ce();return}const X=W.lastY,_=W.lastTime??ce(),te=ce();W.lastY=O,W.lastTime=te;const K=X-O;if(Math.abs(K)<1)return;const ae=Math.max(te-_,8),be=F+Math.min($,Math.abs(K)/R),fe=K*be,H=fe/ae;W.velocity=W.velocity*(1-Y)+H*Y,W.velocity>Z?W.velocity=Z:W.velocity<-Z&&(W.velocity=-Z),J.preventDefault(),J.stopPropagation(),Le(fe)},oe=()=>{if(W.lastY=null,W.lastTime=null,typeof window>"u")return;if(Math.abs(W.velocity)<z){W.velocity=0;return}let J=ce();const O=()=>{const X=ce(),_=Math.max(X-J,8);J=X;const te=Le(W.velocity*_)??!1,K=Math.sign(W.velocity),ae=Math.max(0,Math.abs(W.velocity)-G*_);if(W.velocity=ae*K,!te||ae<=z){ye(),W.velocity=0;return}W.rafId=window.requestAnimationFrame(O)};W.rafId=window.requestAnimationFrame(O)};C.addEventListener("touchstart",Ce,ie),C.addEventListener("touchmove",We,ie),C.addEventListener("touchend",oe,ie),C.addEventListener("touchcancel",oe,ie);const B=C.style.touchAction;C.style.touchAction="none",v.current=()=>{ye(),C.removeEventListener("touchstart",Ce,ie),C.removeEventListener("touchmove",We,ie),C.removeEventListener("touchend",oe,ie),C.removeEventListener("touchcancel",oe,ie),C.style.touchAction=B}},[d]);return l.useEffect(()=>{const C=new Cu.Terminal(Ji(a,i,o)),E=new Mu.FitAddon;m.current=C,h.current=E,C.loadAddon(E);const F=p.current;if(F){C.open(F);const Y=F.querySelector(".xterm-viewport");Y&&(Y.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=Y,S()),D(),C.focus()}const $=[C.onData(Y=>{g.current(Y)})],R=new ResizeObserver(()=>{D()});return F&&R.observe(F),()=>{v.current?.(),v.current=null,$.forEach(Y=>Y.dispose()),R.disconnect(),C.dispose(),m.current=null,h.current=null,w()}},[D,a,i,o,w]),l.useEffect(()=>{const C=m.current;if(!C)return;const E=Ji(a,i,o);Object.assign(C.options,E),D()},[D,a,i,o]),l.useEffect(()=>{const C=m.current;C&&(C.reset(),w(),D(),C.focus())},[r,D,w]),l.useEffect(()=>(M(),()=>{v.current?.(),v.current=null}),[M,r]),l.useEffect(()=>{const C=m.current;if(!C)return;if(s.length===0){k.current!==0&&(C.reset(),w(),D());return}const E=s[0].id;if(j.current===null&&(j.current=E),(j.current!==E||k.current>s.length)&&(C.reset(),w(),j.current=E),k.current<s.length){const $=s.slice(k.current);N($.map(R=>R.data).join("")),k.current=s.length}},[s,N,D,w]),l.useImperativeHandle(u,()=>({focus:()=>{m.current?.focus()},clear:()=>{const C=m.current;C&&(C.reset(),w(),D())},fit:()=>{D()}}),[D,w]),e.jsx("div",{ref:p,className:T("relative h-full w-full",c),children:f.current?e.jsx(aa,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null})});zo.displayName="TerminalViewport";const Zi=13,Gx={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},cn={ctrl:"5",cmd:"3"},qx={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},Kx=(r,s)=>{if(s)switch(r){case"arrow-up":return`\x1B[1;${cn[s]}A`;case"arrow-down":return`\x1B[1;${cn[s]}B`;case"arrow-right":return`\x1B[1;${cn[s]}C`;case"arrow-left":return`\x1B[1;${cn[s]}D`}return Gx[r]??null},Yx=()=>{const{terminal:r}=rr(),{currentTheme:s}=jr(),{monoFont:t}=$c(),{isMobile:n,hasTouchInput:o}=At(),{currentSessionId:a,sessions:i,worktreeMetadata:c}=ge(),d=a?c.get(a)??void 0:void 0,u=l.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const V=i.find(Q=>Q.id===a),L=typeof V?.directory=="string"?V.directory:null;return L&&L.length>0?L:null},[a,i,d]),{currentDirectory:p,homeDirectory:f}=jt(),m=u||p||null,h=l.useMemo(()=>m?f?m===f?"~":m.startsWith(f+"/")?"~"+m.slice(f.length):m:m:"",[m,f]),g=Yi(),x=g.sessions,y=g.setTerminalSession,b=g.setConnecting,k=g.appendToBuffer,j=g.clearTerminalSession,v=g.removeTerminalSession,S=g.clearBuffer,w=l.useMemo(()=>{if(m)return x.get(m)},[x,m]),D=w?.terminalSessionId??null,A=w?.bufferChunks??[],N=w?.bufferLength??0,M=w?.isConnecting??!1,C=D,[E,F]=l.useState(null),[$,R]=l.useState(!1),[Y,Z]=l.useState(null),[z,G]=l.useState(!1),W=l.useRef(null),ce=l.useRef(null),Ne=l.useRef(C),Me=l.useRef(m),Le=l.useRef(null),ie=Fe(V=>V.activeMainTab)==="terminal";l.useEffect(()=>{Ne.current=C},[C]),l.useEffect(()=>{Me.current=m},[m]),l.useEffect(()=>{!n&&Y!==null&&Z(null)},[n,Y,Z]),l.useEffect(()=>{!C&&Y!==null&&Z(null)},[C,Y,Z]);const je=l.useCallback(()=>{W.current?.(),W.current=null,ce.current=null},[]);l.useEffect(()=>()=>{je(),Ne.current=null},[je]);const Ce=l.useCallback(V=>{if(ce.current===V)return;je();const L=r.connect(V,{onEvent:Q=>{const ke=Me.current;if(ke)switch(Q.type){case"connected":{b(ke,!1),F(null),R(!1),Le.current?.focus();break}case"reconnecting":{const De=Q.attempt??0,Oe=Q.maxAttempts??3;F(`Reconnecting (${De}/${Oe})...`),R(!1);break}case"data":{Q.data&&k(ke,Q.data);break}case"exit":{const De=typeof Q.exitCode=="number"?Q.exitCode:null,Oe=typeof Q.signal=="number"?Q.signal:null;k(ke,`\r
|
|
94
|
-
[Process exited${De!==null?` with code ${De}`:""}${Oe!==null?` (signal ${Oe})`:""}]\r
|
|
95
|
-
`),j(ke),b(ke,!1),F("Terminal session ended"),R(!1),je();break}}},onError:(Q,ke)=>{const De=Me.current;if(!De)return;const Oe=ke?`Connection failed: ${Q.message}`:Q.message||"Terminal stream connection error";F(Oe),R(!!ke),ke&&(b(De,!1),je(),v(De))}},qx);W.current=()=>{L.close(),ce.current=null},ce.current=V},[k,j,je,v,b,r,F]);l.useEffect(()=>{let V=!1;if(!m){F(a?"No working directory available for terminal.":"Select a session to open the terminal."),je();return}return(async()=>{const Q=m;if(!Me.current||Me.current!==Q)return;let De=Yi.getState().getTerminalSession(Q)?.terminalSessionId??null;if(!De){F(null),R(!1),b(Q,!0);try{const Oe=await r.createSession({cwd:Q});if(V){try{await r.close(Oe.sessionId)}catch{}return}y(Q,Oe),De=Oe.sessionId}catch(Oe){V||(F(Oe instanceof Error?Oe.message:"Failed to start terminal session"),R(!0),b(Q,!1));return}}!De||V||(Ne.current=De,Ce(De))})(),()=>{V=!0,Ne.current=null,je()}},[a,m,C,v,b,y,Ce,je,r]);const We=l.useCallback(async()=>{if(!m||z)return;G(!0),F(null),R(!1),je();const V=Ne.current;try{if(r.restartSession&&V){const L=await r.restartSession(V,{cwd:m});y(m,L),Ne.current=L.sessionId,Ce(L.sessionId)}else{if(V)try{await r.close(V)}catch{}v(m)}}catch(L){F(L instanceof Error?L.message:"Failed to restart terminal"),R(!0)}finally{G(!1)}},[m,z,je,r,y,Ce,v]),oe=l.useCallback(async()=>{if(m&&!z){G(!0),F(null),R(!1),je();try{r.forceKill&&await r.forceKill({cwd:m})}catch{}v(m),S(m),Le.current?.clear(),await new Promise(V=>setTimeout(V,100));try{b(m,!0);const V=await r.createSession({cwd:m});y(m,V),Ne.current=V.sessionId,Ce(V.sessionId)}catch(V){F(V instanceof Error?V.message:"Failed to create terminal"),R(!0),b(m,!1)}finally{G(!1)}}},[m,z,je,r,v,S,b,y,Ce]),B=l.useCallback(()=>{if(!m)return;S(m),Le.current?.clear(),Le.current?.focus();const V=Ne.current;V&&r.sendInput(V,"\f").catch(L=>{F(L instanceof Error?L.message:"Failed to refresh prompt")})},[S,m,F,r]),J=l.useCallback(V=>{if(!V)return;let L=V,Q=!1;if(Y&&V.length>0){const De=V[0];if(De.length===1&&/[a-zA-Z]/.test(De)){const Oe=De.toUpperCase();(Y==="ctrl"||Y==="cmd")&&(L=String.fromCharCode(Oe.charCodeAt(0)&31),Q=!0)}Q||(Q=!0)}const ke=Ne.current;ke&&(r.sendInput(ke,L).catch(De=>{F(De instanceof Error?De.message:"Failed to send input")}),Q&&(Z(null),Le.current?.focus()))},[Y,Z,r]),O=l.useCallback((V,L)=>{const Q=Ne.current;Q&&r.resize({sessionId:Q,cols:V,rows:L}).catch(()=>{})},[r]),X=l.useCallback(V=>{Z(L=>L===V?null:V),Le.current?.focus()},[Z]),_=l.useCallback(V=>{const L=Kx(V,Y);L&&(J(L),Z(null),Le.current?.focus())},[Y,J,Z]);l.useEffect(()=>{if(!n||!Y||!C)return;const V=L=>{if(L.repeat)return;const Q=L.key;if(!Q||Q==="Control"||Q==="Meta"||Q==="Alt"||Q==="Shift")return;const ke=Q.length===1?Q.toLowerCase():Q,De=L.code??"",Oe=De.startsWith("Key")&&De.length===4?De.slice(3).toUpperCase():null,ct=Q.length===1&&/[a-zA-Z]/.test(Q)?Q.toUpperCase():Oe,Ue={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(ke in Ue){L.preventDefault(),L.stopPropagation(),_(Ue[ke]);return}if(Y==="ctrl"&&ct&&ct.length===1&&ct>="A"&&ct<="Z"){const Ge=String.fromCharCode(ct.charCodeAt(0)&31);L.preventDefault(),L.stopPropagation(),J(Ge),Z(null),Le.current?.focus()}};return window.addEventListener("keydown",V),()=>{window.removeEventListener("keydown",V)}},[Y,_,J,n,Z,C]);const te=l.useMemo(()=>{const V=Js[bn].stack;if(typeof window>"u")return(Js[t]??Js[bn]).stack;const Q=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return Q&&Q.trim().length>0?Q.trim():(Js[t]??Js[bn]).stack??V},[t]),K=l.useMemo(()=>Vx(s),[s]),ae=l.useMemo(()=>`${m??"no-dir"}::${C??"pending"}`,[m,C]);l.useEffect(()=>{if(!ie)return;const V=Le.current;if(!V)return;const L=()=>{V.fit()};if(typeof window<"u"){const Q=window.requestAnimationFrame(()=>{L(),V.focus()}),ke=[220,400].map(De=>window.setTimeout(L,De));return()=>{window.cancelAnimationFrame(Q),ke.forEach(De=>window.clearTimeout(De))}}L()},[ie,ae,C]);const be=E?.includes("Reconnecting"),fe=E?be?e.jsx(Du,{size:20,className:"text-amber-400"}):e.jsx(hs,{size:20,className:"text-destructive"}):C&&!M&&!z?e.jsx(un,{size:20,className:"text-emerald-400"}):M||z?e.jsx(Aa,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Aa,{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(!m)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:We,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const H=!C||M||z;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:h})}),e.jsxs("div",{className:"flex items-center gap-2",children:[fe,e.jsxs(Ee,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:B,disabled:!N,title:"Clear output",type:"button",children:[e.jsx(Us,{size:16}),"Clear"]}),e.jsxs(Ee,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:We,disabled:z,title:"Restart terminal session",type:"button",children:[e.jsx(As,{size:16,className:T((M||z)&&"animate-spin")}),"Restart"]})]})]}),n?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:()=>_("esc"),disabled:H,children:"Esc"}),e.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>_("tab"),disabled:H,children:[e.jsx(Ma,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ee,{type:"button",size:"sm",variant:Y==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>X("ctrl"),disabled:H,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:Y==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>X("cmd"),disabled:H,children:[e.jsx(br,{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:()=>_("arrow-up"),disabled:H,children:[e.jsx(Tr,{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:()=>_("arrow-left"),disabled:H,children:[e.jsx(bl,{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:()=>_("arrow-down"),disabled:H,children:[e.jsx(Ir,{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:()=>_("arrow-right"),disabled:H,children:[e.jsx(Ma,{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:()=>_("enter"),disabled:H,children:[e.jsx(Au,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:K.background},children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:ie?n?e.jsx(zo,{ref:V=>{Le.current=V},sessionKey:ae,chunks:A,onInput:J,onResize:O,theme:K,fontFamily:te,fontSize:Zi,enableTouchScroll:o},ae):e.jsx(Ye,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(zo,{ref:V=>{Le.current=V},sessionKey:ae,chunks:A,onInput:J,onResize:O,theme:K,fontFamily:te,fontSize:Zi,enableTouchScroll:o},ae)}):null}),E&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:E}),$&&e.jsx(Ee,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:oe,disabled:z,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},Xx=()=>{const{isSidebarOpen:r,activeMainTab:s,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i}=Fe(),{isMobile:c}=At(),[d,u]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||u(typeof window.opencodeDesktop<"u")},[]),yh({enabled:!0}),l.useEffect(()=>{Fe.getState().isMobile!==c&&t(c)},[c,t]),l.useEffect(()=>{if(typeof window>"u")return;let m;const h=()=>{m!==void 0&&window.clearTimeout(m),m=window.setTimeout(()=>{Fe.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",h),()=>{window.removeEventListener("resize",h),m!==void 0&&window.clearTimeout(m)}},[]),l.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const m=document.documentElement;let h=0,g=!1,x=0;const y=()=>{h=0,g=!0,m.style.setProperty("--oc-keyboard-inset","0px")},b=()=>{const v=window.visualViewport,S=v?Math.round(v.height):window.innerHeight,w=v?Math.max(0,Math.round(v.offsetTop)):0;m.style.setProperty("--oc-visual-viewport-offset-top",`${w}px`);const D=document.activeElement,A=D?.tagName,M=A==="INPUT"||A==="TEXTAREA"||A==="SELECT"||!!D?.isContentEditable,C=Math.round(m.clientHeight||window.innerHeight),E=S+w,F=Math.max(0,C-E),R=F>=(M?120:180)?F:0;if(g)R===0&&(g=!1),h=0;else if(h===0)R>0&&M&&(h=R);else{const Y=S>x+6;R===0?h=0:Y?y():R>h&&(h=R)}if(m.style.setProperty("--oc-keyboard-inset",`${h}px`),x=S,c&&M){const Y=document.scrollingElement;Y&&Y.scrollTop!==0&&(Y.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};b();const k=window.visualViewport;k?.addEventListener("resize",b),k?.addEventListener("scroll",b),window.addEventListener("resize",b),window.addEventListener("orientationchange",b),document.addEventListener("focusin",b,!0);const j=v=>{const S=v.target;if(!S)return;const w=S.tagName;(w==="INPUT"||w==="TEXTAREA"||w==="SELECT"||S.isContentEditable)&&y()};return document.addEventListener("focusout",j,!0),()=>{k?.removeEventListener("resize",b),k?.removeEventListener("scroll",b),window.removeEventListener("resize",b),window.removeEventListener("orientationchange",b),document.removeEventListener("focusin",b,!0),document.removeEventListener("focusout",j,!0)}},[c]);const p=l.useMemo(()=>{switch(s){case"git":return e.jsx(Px,{});case"diff":return e.jsx(kp,{});case"terminal":return e.jsx(Yx,{});default:return null}},[s]),f=s==="chat";return e.jsx(xh,{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(th,{}),e.jsx(nh,{}),e.jsx(mh,{}),e.jsx(Qp,{isOpen:a,onClose:()=>i(!1)}),c?e.jsxs(e.Fragment,{children:[e.jsx(li,{}),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(as,{children:e.jsx($o,{})})}),p&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(as,{children:p})})]})}),e.jsx(qt,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Po,{mobileVariant:!0})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Tp,{isOpen:r,isMobile:c,children:e.jsx(Po,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(li,{}),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(as,{children:e.jsx($o,{})})}),p&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(as,{children:p})})]})})]})]}),e.jsx(Cp,{})]})})},Jx=()=>{const[r,s]=l.useState("sessions"),t=ge($=>$.currentSessionId),n=ge($=>$.sessions),o=ge($=>$.createSession),a=ge($=>$.setCurrentSession),[i,c]=l.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),[d,u]=l.useState(()=>typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.error:void 0),[p,f]=l.useState(()=>i==="connected"),[m,h]=l.useState(()=>i!=="connected"),g=l.useRef(null),x=St($=>$.isInitialized),y=St($=>$.initializeApp),b=ge($=>$.loadSessions),k=ge($=>$.loadMessages),j=ge($=>$.messages),[v,S]=l.useState(()=>x),[w,D]=l.useState(!1),A=l.useRef(!1),N=l.useRef(!1);l.useEffect(()=>{t&&s("chat")},[t]),l.useEffect(()=>{!t&&r==="chat"&&s("sessions")},[t,r]);const M=l.useCallback(()=>{s("sessions")},[]),C=l.useCallback(async()=>{(await o())?.id&&s("chat")},[o]);l.useEffect(()=>{const $=R=>{const Y=R.detail,Z=Y?.status;(Z==="connected"||Z==="connecting"||Z==="error"||Z==="disconnected")&&(c(Z),u(Y?.error),Z==="connected"&&f(!0))};return window.addEventListener("openchamber:connection-status",$),()=>window.removeEventListener("openchamber:connection-status",$)},[]);const E=l.useMemo(()=>v&&i==="connected"&&!w?!1:v?i==="error":i!=="connected"||w,[i,v,w]),F=p?800:250;return l.useEffect(()=>(g.current&&(window.clearTimeout(g.current),g.current=null),E?g.current=window.setTimeout(()=>h(!0),F):h(!1),()=>{g.current&&(window.clearTimeout(g.current),g.current=null)}),[F,E]),l.useEffect(()=>{(async()=>{if(!(w||v||i!=="connected")){D(!0);try{x||await y(),await b(),S(!0)}catch{}finally{D(!1)}}})()},[i,x,v,y,w,b]),l.useEffect(()=>{(async()=>{if(!v||i!=="connected"||r!=="chat")return;const R=t||n[0]?.id;if(!R)return;if(!(j.has(R)&&(j.get(R)?.length||0)>0)){t||a(R);try{await k(R)}catch{}}})()},[i,t,r,v,k,j,n,a]),l.useEffect(()=>{!v||A.current||!t&&n.length>0&&(a(n[0].id),A.current=!0)},[t,v,n,a]),l.useEffect(()=>{(async()=>{if(i!=="connected"||!v||N.current)return;const R=n.find(Z=>Z.id===t),Y=R?.title?.toLowerCase()?.startsWith("new session");if(R&&Y)a(R.id);else{const Z=n.find(z=>z.title?.toLowerCase()?.startsWith("new session"));if(Z)a(Z.id);else{const z=await o();z?.id&&a(z.id)}}N.current=!0})()},[i,o,t,v,n,a]),e.jsxs("div",{className:"h-full w-full bg-background text-foreground flex flex-col",children:[r==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(xo,{title:"Sessions",onNewSession:C,onSettings:()=>s("settings")}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Po,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>s("chat"),hideDirectoryControls:!0})})]}):r==="settings"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(xo,{title:"Settings",showBack:!0,onBack:M}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(Zx,{})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(xo,{title:n.find($=>$.id===t)?.title||"Chat",showBack:!0,onBack:M,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(as,{children:e.jsx($o,{})})})]}),m&&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($t,{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})]})]})},xo=({title:r,showBack:s,onBack:t,onNewSession:n,onSettings:o,showContextUsage:a})=>{const{getCurrentModel:i}=St(),c=ge(h=>h.getContextUsage),d=i(),u=d?.limit&&typeof d.limit=="object"?d.limit:null,p=typeof u?.context=="number"?u.context:0,f=typeof u?.output=="number"?u.output:0,m=c(p,f);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(bl,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",title:r,children:r}),n&&e.jsx("button",{onClick:n,className:"p-1 rounded hover:bg-muted transition-colors","aria-label":"New session",children:e.jsx(ls,{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(pr,{className:"h-5 w-5"})}),a&&m&&m.totalTokens>0&&e.jsx(Do,{totalTokens:m.totalTokens,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit??0,size:"compact"})]})},Zx=()=>e.jsx("div",{className:"flex flex-col h-full",children:e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(ic,{})})}),Qi=({...r})=>{const{theme:s="system"}=Eu();return e.jsx(Tu,{theme:s,className:"toaster group",closeButton:!0,style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--error-bg":"var(--popover)","--error-text":"var(--popover-foreground)","--error-border":"var(--border)","--success-bg":"var(--popover)","--success-text":"var(--popover-foreground)","--success-border":"var(--border)","--warning-bg":"var(--popover)","--warning-text":"var(--popover-foreground)","--warning-border":"var(--border)","--info-bg":"var(--popover)","--info-text":"var(--popover-foreground)","--info-border":"var(--border)"},...r})},Qx=(r=5e3)=>{const[s,t]=de.useState(null);return de.useEffect(()=>{if(!Zt())return;let n=!1,o=null;const a=async()=>{const i=await em();n||(t(i),o=setTimeout(a,r))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[r]),s},ey=({onClose:r})=>{const{sessions:s,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=ge(),c=Qx(4e3),d=l.useMemo(()=>{let f=0;return t.forEach(m=>{f+=m.length}),f},[t]),u=l.useMemo(()=>s.map(f=>{const m=t.get(f.id)?.length||0,h=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:m,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,m)=>m.lastAccessed-f.lastAccessed),[s,t,n,o]),p=t.size;return e.jsxs(ga,{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(Iu,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),r&&e.jsx(Ee,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:r,children:e.jsx(hs,{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," / ",Bt.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:[Bt.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:[Bt.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:[Bt.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(Ye,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(f=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${f.isCurrent?"bg-primary/10":"bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"truncate",children:f.title}),f.isStreaming&&e.jsx(Fu,{className:"h-3 w-3 text-primary animate-pulse"}),f.isZombie&&e.jsx("span",{className:"text-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${f.messageCount>Bt.VIEWPORT_MESSAGES?"text-warning":""}`,children:[f.messageCount," msgs"]}),f.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",f.backgroundCount]})]})]},f.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(Ee,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Us,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]}),e.jsx(Ee,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"}),e.jsx(Ee,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{},children:"Log State"})]})]})]})},ty="openchamber-message-cursors",yr="cursors",sy=1,Hc="openchamber.messageCursors",ya=()=>typeof window<"u",ba=()=>ya()&&typeof indexedDB<"u",Wc=()=>ba()?new Promise((r,s)=>{const t=indexedDB.open(ty,sy);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(yr)||n.createObjectStore(yr)},t.onerror=()=>{s(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{r(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),Uc=()=>{if(!ya())return{};try{const r=window.localStorage.getItem(Hc);if(!r)return{};const s=JSON.parse(r);return s&&typeof s=="object"?s:{}}catch{return{}}},ry=r=>{if(ya())try{window.localStorage.setItem(Hc,JSON.stringify(r))}catch{}},ny=async(r,s,t)=>{if(!r||!s)return;if(ba())try{const o=await Wc();await new Promise((a,i)=>{const c=o.transaction(yr,"readwrite");c.objectStore(yr).put({messageId:s,completedAt:t},r),c.oncomplete=()=>a(),c.onerror=()=>i(c.error??new Error("Cursor write failed")),c.onabort=()=>i(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=Uc();n[r]={messageId:s,completedAt:t},ry(n)},oy=async r=>{if(!r)return null;if(ba())try{const t=await Wc(),n=await new Promise((o,a)=>{const i=t.transaction(yr,"readonly"),d=i.objectStore(yr).get(r);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),i.onerror=()=>a(i.error??new Error("Cursor read failed")),i.onabort=()=>a(i.error??new Error("Cursor read aborted"))});return t.close(),n}catch{}return Uc()[r]??null},es=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},ay=50,el=new WeakMap,tl=r=>{if(!r||!Array.isArray(r))return 0;const s=el.get(r);if(s!==void 0)return s;let t=0;for(let n=0;n<r.length;n++){const o=r[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(t+=a.length)}}return el.set(r,t),t},Ho=new Map,sl=(r,s)=>{const t=`${r}:${s}`,n=Ho.get(t);if(n&&n.sessionId===r)return n.message;const i=(ge.getState().messages.get(r)||[]).find(c=>c.info.id===s)||null;return Ho.set(t,{sessionId:r,message:i}),i},iy=()=>{const{addStreamingPart:r,completeStreamingMessage:s,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:p}=ge(),{checkConnection:f}=St(),m=jt(oe=>oe.currentDirectory),h=l.useMemo(()=>{if(!a)return;try{const B=d?.(a);if(B?.path)return B.path}catch(B){console.warn("Failed to inspect worktree metadata for session directory:",B)}const oe=c.find(B=>B.id===a);if(oe&&typeof oe.directory=="string"&&oe.directory.trim().length>0)return oe.directory.trim()},[a,d,c]),g=l.useMemo(()=>{if(h&&h.length>0)return h;if(typeof m=="string"&&m.trim().length>0)return m.trim()},[h,m]),x=Fe(oe=>oe.setEventStreamStatus),y=l.useRef(null),b=l.useCallback((oe,B)=>{const J=B??null,O=y.current;if(!(O&&O.status===oe&&O.hint===J)){if(y.current={status:oe,hint:J},es()){const _={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[oe]??"[INFO]",te=J?`${_} SSE ${oe}: ${J}`:`${_} SSE ${oe}`;console.info(te)}x(oe,J)}},[x]),k=l.useCallback((oe,B,J)=>{es()&&console.debug(`[MessageTracker] ${oe}: ${B}`,J)},[]),j=l.useCallback(oe=>{es()&&console.debug(`[MessageTracker] ${oe}: reported`)},[]),v=l.useRef(null),S=l.useRef(null),w=l.useRef(0);l.useRef(new Set);const D=l.useRef(new Map),A=l.useRef(null),N=l.useRef(!1),M=l.useCallback(()=>{if(typeof document>"u")return"visible";const oe=document.visibilityState;return oe==="hidden"&&document.hasFocus()?"visible":oe},[]),C=l.useRef(M()),E=l.useRef(typeof navigator>"u"?!0:navigator.onLine),F=l.useRef(!1),$=l.useRef(null),R=l.useRef(null),Y=l.useRef(Date.now()),Z=l.useRef(!1);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(Z.current=!0)},[]);const z=l.useRef(new Map),G=l.useRef(new Map),W=l.useCallback(oe=>{if(!oe)return;const B=Date.now(),J=D.current,O=J.get(oe);O&&B-O<3e3||(J.set(oe,B),setTimeout(async()=>{try{const X=await Ae.getSession(oe);if(X){const _={};typeof X.title=="string"&&X.title.length>0&&(_.title=X.title),X.summary!==void 0&&(_.summary=X.summary),Object.keys(_).length>0&&i(oe,_)}}catch(X){console.warn("Failed to refresh session metadata:",X)}},100))},[i]),ce=l.useCallback(()=>{A.current||(A.current=setTimeout(()=>{A.current=null;try{p()}catch(oe){console.warn("Failed to refresh sessions after stream completion:",oe)}},500))},[p]),Ne=l.useCallback((oe,B)=>{if(G.current.get(oe)===B)return;const O=z.current.get(oe);if(O&&(clearTimeout(O),z.current.delete(oe)),G.current.set(oe,B),ge.setState({sessionActivityPhase:new Map(G.current)}),B==="cooldown"){const X=setTimeout(()=>{z.current.delete(oe),G.current.get(oe)==="cooldown"&&(G.current.set(oe,"idle"),ge.setState({sessionActivityPhase:new Map(G.current)}))},2e3);z.current.set(oe,X)}},[]),Me=l.useCallback(oe=>{if(Y.current=Date.now(),es()&&console.debug("[useEventStream] Received event:",oe.type,oe.properties),!oe.properties)return;const B=oe.properties;if(!new Set(["session.abort","session.error"]).has(oe.type)){const O=(typeof B.session=="object"&&B.session!==null?B.session:null)||(typeof B.sessionInfo=="object"&&B.sessionInfo!==null?B.sessionInfo:null);if(O){const X=O,_=typeof X.id=="string"&&X.id.length>0?X.id:typeof X.sessionID=="string"&&X.sessionID.length>0?X.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof B.id=="string"&&B.id.length>0?B.id:void 0;if(_){const te=typeof X.title=="string"?X.title:typeof B.title=="string"?B.title:void 0,K=typeof X.summary=="object"&&X.summary!==null?X.summary:typeof B.summary=="object"&&B.summary!==null?B.summary:void 0;if(te!==void 0||K!==void 0){const ae={};te!==void 0&&(ae.title=te),K!==void 0&&(ae.summary=K),i(_,ae)}}}}switch(oe.type){case"server.connected":f();break;case"openchamber:session-activity":{if(!Z.current)break;const O=typeof B.sessionId=="string"?B.sessionId:null,X=typeof B.phase=="string"?B.phase:null;O&&(X==="idle"||X==="busy"||X==="cooldown")&&(Ne(O,X),ce());break}case"session.status":if(Z.current)break;{const O=typeof B.sessionID=="string"?B.sessionID:null,X=typeof B.status=="object"&&B.status!==null?B.status:null,_=typeof X?.type=="string"?X.type:null;O&&_&&(Ne(O,_==="busy"||_==="retry"?"busy":"idle"),ce())}break;case"message.part.updated":{const O=typeof B.part=="object"&&B.part!==null?B.part:null;if(!O)break;const X=O,_=typeof B.info=="object"&&B.info!==null?B.info:B,te=typeof _.sessionID=="string"?_.sessionID:null,K=typeof X.sessionID=="string"&&X.sessionID.length>0?X.sessionID:typeof te=="string"&&te.length>0?te:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,ae=typeof _.id=="string"?_.id:null,be=typeof X.messageID=="string"&&X.messageID.length>0?X.messageID:typeof ae=="string"&&ae.length>0?ae:typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;if(!K||!be){es()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:X.sessionID??te??B.sessionID,messageID:X.messageID??ae??B.messageID});break}const fe=K,H=be;let V="assistant";if(_&&typeof _.role=="string")V=_.role;else{const Q=sl(fe,H);if(Q){const ke=Q.info.role;typeof ke=="string"&&(V=ke)}}if(k(H,"part_received",{role:V}),V==="user"&&X.synthetic===!0){k(H,"skipped_synthetic_user_part");break}const L={...O,type:O.type||"text"};k(H,"addStreamingPart_called"),r(fe,H,L,V);break}case"message.updated":{const O=typeof B.info=="object"&&B.info!==null?B.info:B,X=O,_=typeof X.sessionID=="string"&&X.sessionID.length>0?X.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,te=typeof X.id=="string"&&X.id.length>0?X.id:typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;if(!_||!te){es()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:X.sessionID??B.sessionID,messageID:X.id??B.messageID});break}const K=_,ae=te;if(Z.current&&es())try{const Ue=B.parts||X.parts||[],Xe=(Array.isArray(Ue)?Ue.filter(Ze=>Ze?.type==="text"):[]).map(Ze=>{const Be=Ze;return typeof Be?.text=="string"?Be.text:typeof Be?.content=="string"?Be.content:""}).join(`
|
|
96
|
-
`);console.info("[STREAM-TRACE] message.updated",{messageId:ae,role:X.role,status:X.status,textLen:Xe.length,textPreview:Xe.slice(0,120),partsCount:Array.isArray(Ue)?Ue.length:0})}catch{}if(k(ae,"message_updated",{role:X.role}),X.role==="user"){const Ue=B.parts||X.parts,Ge=Array.isArray(Ue)?Ue:[],Xe={...O,userMessageMarker:!0,clientRole:"user"};if(t(K,ae,Xe),Ge.length>0)for(let Ze=0;Ze<Ge.length;Ze++){const Be=Ge[Ze];if(Be.synthetic===!0)continue;const ze={...Be,type:Be?.type||"text",sessionID:Be?.sessionID||K,messageID:Be?.messageID||ae};r(K,ae,ze,"user")}k(ae,"user_message_created_from_event",{partsCount:Ge.length});break}const be=sl(K,ae),fe=tl(be?.parts||[]),H=be?.parts?.some(Ue=>Ue?.type==="step-finish"&&Ue.reason==="stop")??!1,V=B.parts||X.parts,L=Array.isArray(V)?V:[],Q=L.length>0,De=typeof(X.time||{})?.completed=="number";if(!Q&&!De)break;if(X.role==="assistant"&&Q){const Ue=tl(L),Ge=fe>0&&Ue+ay<fe,Xe=L.some(Ze=>Ze?.type==="step-finish"&&Ze.reason==="stop");if(Ge&&!Xe){k(ae,"skipped_shrinking_update",{incomingLen:Ue,existingLen:fe});break}if(Z.current){const Ze=fe>0&&Ue<fe,Be=L.some(dt=>{if(!dt||dt.type!=="text")return!1;const mt=dt;return typeof mt.text=="string"&&mt.text.length>0});if(Ze&&!(Xe&&Be)){k(ae,"desktop_shrinking_update_suppressed",{incomingLen:Ue,existingLen:fe});break}}}if(t(K,ae,O),Q&&X.role!=="user"){const Xe=(ge.getState().messages.get(K)||[]).find(ze=>ze.info.id===ae),Ze=!Xe||Xe.parts.length===0;k(ae,Ze?"server_parts_injected":"server_parts_refreshed",{count:L.length});const Be=Z.current&&X.role==="assistant"?L.filter(ze=>ze?.type!=="text"):L;for(let ze=0;ze<Be.length;ze++){const dt=Be[ze],mt={...dt,type:dt?.type||"text",sessionID:dt?.sessionID||K,messageID:dt?.messageID||ae};r(K,ae,mt,X.role),k(ae,`server_part_${ze}`)}}const Oe=O.time;if(O.role==="assistant"&&Oe?.completed!==void 0&&O.role==="assistant"){const Ge=ge.getState().messages.get(K)||[];let Xe=null,Ze="";for(let P=0;P<Ge.length;P++){const se=Ge[P];se.info.role==="assistant"&&se.info.id>Ze&&(Ze=se.info.id,Xe=se.info.id)}if(ae!==Xe)break;if(!(L.some(P=>P?.type==="step-finish"&&P.reason==="stop")||H)&&Z.current){k(ae,"desktop_completion_without_stop");break}const ze=Oe?.completed!==void 0?Oe?.completed:Date.now();if(Oe?.completed||t(K,ae,{...O,time:{...Oe??{},completed:ze}}),k(ae,"completed",{timeCompleted:ze}),j(ae),ny(K,ae,ze),s(K,ae),!Z.current){const P=O.sessionID,se=typeof P=="string"&&P.length>0?P:K;G.current.get(se)==="busy"&&Ne(se,"cooldown")}const dt=O.sessionID,mt=typeof dt=="string"&&dt.length>0?dt:K;W(mt),O.summary&&typeof mt=="string"&&n(mt,null)}break}case"session.updated":{const O=typeof B.info=="object"&&B.info!==null?B.info:typeof B.sessionInfo=="object"&&B.sessionInfo!==null?B.sessionInfo:typeof B.session=="object"&&B.session!==null?B.session:B,X=typeof O.id=="string"&&O.id.length>0?O.id:typeof O.sessionID=="string"&&O.sessionID.length>0?O.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof B.id=="string"&&B.id.length>0?B.id:void 0;if(X){const _=typeof O.time=="object"&&O.time!==null?O.time:typeof B.time=="object"&&B.time!==null?B.time:null,te=_&&typeof _.compacting=="number"?_.compacting:null;n(X,te)}break}case"session.abort":{const O=typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,X=typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;O&&X&&s(O,X);break}case"permission.updated":a===B.sessionID&&o(B);break;case"permission.replied":break;case"todo.updated":{const O=typeof B.sessionID=="string"?B.sessionID:null,X=Array.isArray(B.todos)?B.todos:[];O&&X.length>0&&Lh(O,X);break}}},[a,r,s,t,o,f,W,ce,n,i,k,j,Ne]),Le=l.useCallback(()=>{const oe=M();return C.current=oe,oe==="visible"&&E.current},[M]),ye=l.useCallback(()=>{es()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:Z.current,hasUnsubscribe:!!v.current,currentSessionId:a,effectiveDirectory:g,onlineStatus:E.current,visibilityState:C.current,lastEventTimestamp:Y.current,reconnectAttempts:w.current})},[a,g]),ie=l.useCallback(async()=>!0,[]),je=l.useCallback(()=>{if(N.current){es()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(N.current=!0,S.current&&(clearTimeout(S.current),S.current=null),v.current){const oe=v.current;v.current=null;try{oe()}catch(B){console.warn("[useEventStream] Error during unsubscribe:",B)}}N.current=!1},[]),Ce=l.useCallback(async oe=>{if(ye(),!Le()){F.current=!0,E.current?b("paused","Paused while hidden"):b("offline","Waiting for network");return}Z.current&&(await ie()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),oe?.resetAttempts&&(w.current=0),je(),Y.current=Date.now(),b("connecting",null),es()&&console.info("[useEventStream] Starting event stream...");const B=O=>{console.warn("Event stream error:",O)},J=()=>{const O=F.current;w.current=0,F.current=!1,Y.current=Date.now(),b("connected",null),f(),O&&a&&setTimeout(()=>{u(a).then(()=>W(a)).catch(X=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",X)})},0)};if(es()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:g,isCleaningUp:N.current}),N.current){es()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const O=Ae.subscribeToEvents(Me,B,J,g),X=()=>{try{O()}catch(_){console.warn("[useEventStream] Error during unsubscribe:",_)}};N.current?X():v.current=X}catch(O){console.error("[useEventStream] Error during subscription:",O),B(O)}},[Le,je,b,f,a,u,W,ce,s,Me,g,Ne,ie,ye]),We=l.useCallback(oe=>{if(!Le()){F.current=!0,je(),E.current?b("paused","Paused while hidden"):b("offline","Waiting for network");return}const B=w.current+1;w.current=B;const J=oe??`Retrying (${B})`;b("reconnecting",J);const O=B<=3?Math.min(1e3*Math.pow(2,B-1),8e3):Math.min(2e3*Math.pow(2,B-3),32e3),X=Math.floor(Math.random()*250),_=O+X;S.current&&clearTimeout(S.current),S.current=setTimeout(()=>{Ce({resetAttempts:!1})},_)},[Le,je,b,Ce]);l.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=k);let oe=null;Z.current&&typeof window<"u"&&(oe=ae=>{const be=typeof ae.detail?.sessionId=="string"?ae.detail.sessionId:null,fe=typeof ae.detail?.phase=="string"?ae.detail.phase:null;be&&(fe==="idle"||fe==="busy"||fe==="cooldown")&&(Ne(be,fe),ce())},window.addEventListener("openchamber:session-activity",oe));const B=()=>{$.current&&(clearTimeout($.current),$.current=null)},J=()=>{$.current||($.current=setTimeout(()=>{const ae=M();C.current=ae,ae!=="visible"?(je(),F.current=!0,b("paused","Paused while hidden")):B()},5e3))},O=()=>{C.current=M(),C.current==="visible"?(B(),(F.current||!v.current)&&(console.info("[useEventStream] Visibility restored, triggering soft refresh..."),Z.current||G.current.clear(),a&&(u(a).catch(()=>{}),W(a)),p(),b("connecting","Resuming stream"),Ce({resetAttempts:!0}))):(b("paused","Paused while hidden"),J())},X=()=>{C.current=M(),C.current==="visible"&&(B(),(F.current||!v.current)&&(console.info("[useEventStream] Window focused after pause, triggering soft refresh..."),Z.current||G.current.clear(),a&&(W(a),u(a).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(ae=>console.warn("[useEventStream] Failed to refresh messages:",ae))),p(),b("connecting","Resuming stream"),Ce({resetAttempts:!0})))},_=()=>{E.current=!0,(F.current||!v.current)&&(b("connecting","Network restored"),Ce({resetAttempts:!0}))},te=()=>{E.current=!1,F.current=!0,b("offline","Waiting for network"),je()};typeof document<"u"&&document.addEventListener("visibilitychange",O),typeof window<"u"&&(window.addEventListener("online",_),window.addEventListener("offline",te),window.addEventListener("focus",X));const K=setTimeout(()=>{Ce({resetAttempts:!0})},100);return R.current&&clearInterval(R.current),R.current=setInterval(()=>{if(!Le())return;Date.now()-Y.current>25e3&&Promise.resolve().then(async()=>{try{await Ae.checkHealth()?Y.current=Date.now():We("Refreshing stalled stream")}catch(be){console.warn("Health check after stale stream failed:",be),We("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(K),oe&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",oe),typeof document<"u"&&document.removeEventListener("visibilitychange",O),typeof window<"u"&&(window.removeEventListener("online",_),window.removeEventListener("offline",te),window.removeEventListener("focus",X)),B(),R.current&&(clearInterval(R.current),R.current=null);const ae=z.current,be=G.current;ae.forEach(fe=>clearTimeout(fe)),ae.clear(),be.clear(),Ho.clear(),F.current=!1,C.current=M(),E.current=typeof navigator>"u"?!0:navigator.onLine,je(),A.current&&(clearTimeout(A.current),A.current=null),b("idle",null)}},[a,g,k,M,je,b,Ce,We,u,W,Ne,Le])},ly=()=>{const{createSession:r,abortCurrentOperation:s,initializeNewOpenChamberSession:t,armAbortPrompt:n,clearAbortPrompt:o,currentSessionId:a}=ge(),{toggleCommandPalette:i,toggleHelpDialog:c,toggleSidebar:d,setSessionSwitcherOpen:u,setSessionCreateDialogOpen:p,setActiveMainTab:f,setSettingsDialogOpen:m}=Fe(),{agents:h}=St(),{themeMode:g,setThemeMode:x}=jr(),{working:y}=kc(),b=l.useRef(null),k=l.useRef(null),j=l.useRef(!1),v=l.useCallback(()=>{k.current&&(clearTimeout(k.current),k.current=null),b.current=null,o()},[o]);l.useEffect(()=>{const S=w=>{if(w.ctrlKey&&w.key==="x"&&(w.preventDefault(),i()),w.ctrlKey&&w.shiftKey&&w.key.toLowerCase()==="l"){const A=Al()?.diagnostics;if(!A||(w.preventDefault(),j.current))return;j.current=!0,A.downloadLogs().then(({fileName:N,content:M})=>{const C=new Blob([M],{type:"text/plain;charset=utf-8"}),E=URL.createObjectURL(C),F=document.createElement("a");F.href=E,F.download=N||"desktop.log",document.body.appendChild(F),F.click(),document.body.removeChild(F),URL.revokeObjectURL(E)}).finally(()=>{j.current=!1});return}if(w.ctrlKey&&w.key==="h"&&(w.preventDefault(),c()),w.ctrlKey&&!w.metaKey&&w.key.toLowerCase()==="n"){if(w.preventDefault(),w.shiftKey){p(!0);return}r().then(D=>{D&&t(D.id,h)})}if((w.metaKey||w.ctrlKey)&&w.key==="/"){w.preventDefault();const D=["light","dark","system"],N=(D.indexOf(g)+1)%D.length;x(D[N])}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="g"){w.preventDefault();const{activeMainTab:D}=Fe.getState();f(D==="git"?"chat":"git");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="t"){w.preventDefault();const{activeMainTab:D}=Fe.getState();f(D==="terminal"?"chat":"terminal");return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key===","){w.preventDefault();const{isSettingsDialogOpen:D}=Fe.getState();m(!D);return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="l"){w.preventDefault();const{isMobile:D,isSessionSwitcherOpen:A}=Fe.getState();D?u(!A):d();return}if(w.ctrlKey&&!w.metaKey&&!w.shiftKey&&w.key.toLowerCase()==="i"){w.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(w.key==="Escape"){const D=a;if(!(y.canAbort&&!!D)){v();return}const N=Date.now(),M=b.current;if(M&&N<M){w.preventDefault(),v(),s();return}w.preventDefault();const C=n(3e3)??N+3e3;b.current=C,k.current&&clearTimeout(k.current);const E=Math.max(C-N,0);k.current=setTimeout(()=>{b.current&&Date.now()>=b.current&&v()},E||0);return}};return window.addEventListener("keydown",S),()=>{window.removeEventListener("keydown",S)}},[r,s,i,c,d,u,p,f,m,x,g,t,h,y,n,v,a]),l.useEffect(()=>()=>{v()},[v])},cy=r=>r.role==="assistant",rl=r=>{const s=r.info;if(!cy(s))return;const t=s.time?.completed;return typeof t=="number"?t:void 0},wn=r=>{if(!r)return!1;if(r.role==="user")return!0;const s=r;return s.clientRole==="user"?!0:!!s.userMessageMarker},nl=r=>(Array.isArray(r?.parts)?r.parts:[]).map(n=>Rr(n)).join(" ").replace(/\s+/g," ").trim(),dy=(r,s)=>{if(!r||!wn(r.info))return-1;const t=nl(r),n=typeof r.info?.time?.created=="number"?r.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return s.forEach((i,c)=>{if(!wn(i.info))return;const d=nl(i),u=!!(t&&d&&d===t),p=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,f=typeof n=="number"&&typeof p=="number"?Math.abs(p-n):null;if(u){const m=typeof f=="number"?f:0;m<a&&(o=c,a=m);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?s.findIndex(i=>{if(!wn(i.info))return!1;const c=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},uy=()=>{const{currentSessionId:r,messages:s,streamingMessageIds:t}=ge(),n=l.useMemo(()=>r?t.get(r)??null:null,[r,t]),o=l.useRef(void 0),a=l.useRef(0),i=l.useCallback(async()=>{if(!r||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=s.get(r)||[],u=await Ae.getSessionMessages(r),p=await oy(r);if(!u)return;const f=d[d.length-1];if(f){const m=u.findIndex(x=>x.info.id===f.info.id),g=m===-1?dy(f,u):m;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}=ge.getState();b(r,y)}else{const x=u[g],y=d[d.length-1],b=rl(x),k=rl(y);if(b&&!k){console.log("[SYNC] Last message completed on server");const j=[...d.slice(0,-1),x],{syncMessages:v}=ge.getState();v(r,j)}}else if(wn(f.info)){const x=u.slice(-Bt.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:y}=ge.getState();y(r,x)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(p){const m=u.findIndex(h=>h.info.id===p.messageId);if(m!==-1){if(m<u.length-1){const g=u.slice(m+1).slice(-Bt.VIEWPORT_MESSAGES);if(g.length>0){console.log(`[SYNC] Restoring ${g.length} messages after cursor`);const{syncMessages:x}=ge.getState();x(r,g)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-Bt.VIEWPORT_MESSAGES),{syncMessages:g}=ge.getState();g(r,h)}}else if(u.length>0){const m=u.slice(-Bt.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${m.length} messages`);const{syncMessages:h}=ge.getState();h(r,m)}}catch(d){console.debug("Background sync failed:",d)}}},[r,s,n]);l.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[i]),l.useEffect(()=>{if(!r||n)return;const c=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[r,n,i]),l.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[i])},my=()=>{l.useEffect(()=>{let r=!1;return(async()=>{try{const t=await Ae.getSessionStatus();if(r||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,c=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&ge.setState({sessionActivityPhase:n})}catch{}})(),()=>{r=!0}},[])};function fy(){const{git:r}=rr(),s=jt(i=>i.currentDirectory),{setActiveDirectory:t,startPolling:n,stopPolling:o,fetchAll:a}=Nt();l.useEffect(()=>{if(!s||!r){o();return}return t(s),a(s,r),n(r),()=>{o()}},[s,r,t,n,o,a])}function py({children:r}){return fy(),e.jsx(e.Fragment,{children:r})}const hy=()=>{const[{isUpdating:r,message:s},t]=l.useState(()=>Gm());return l.useEffect(()=>Vm(t),[]),r?e.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-background/80 backdrop-blur-md",children:e.jsx("div",{className:"w-full max-w-sm rounded-xl border border-border/40 bg-card/90 px-6 py-8 text-center shadow-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full border-2 border-primary/30 border-t-transparent text-primary",children:e.jsx(As,{className:"h-7 w-7 animate-spin"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"typography-h3 font-semibold text-foreground",children:"Updating OpenCode"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:s})]})]})})}):null};function ol({apis:r,children:s}){return e.jsx(la.Provider,{value:r,children:s})}const gy="curl -fsSL https://opencode.ai/install | bash",xy=3e3;function yy({onCopy:r}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:r,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Rs,{className:"h-4 w-4"})})]})}const by=3e4;function wy({onCliAvailable:r}){const[s,t]=l.useState(!1),[n,o]=l.useState(!1),[a,i]=l.useState(!1);l.useEffect(()=>{const p=setTimeout(()=>o(!0),by);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:f}=await _r(async()=>{const{getCurrentWindow:h}=await import("./vendor-.pnpm-COYWCHRJ.js").then(g=>g.bY);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=l.useCallback(async()=>{try{const 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(gy),t(!0),setTimeout(()=>t(!1),2e3)}catch(p){console.error("Failed to copy:",p)}},[]);return l.useEffect(()=>{const p=async()=>{await d()&&r?.()},f=setInterval(p,xy);return p(),()=>clearInterval(f)},[d,r]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(jo,{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(It,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(yy,{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(jo,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."})]}),n&&e.jsxs("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["Already installed? Make sure ",e.jsx("code",{className:"text-foreground/70",children:"opencode"})," is in your PATH"]}),e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["or set ",e.jsx("code",{className:"text-foreground/70",children:"OPENCODE_BINARY"})," environment variable."]})]})]})}function vy({apis:r}){const{initializeApp:s,loadProviders:t,isInitialized:n}=St(),{error:o,clearError:a,loadSessions:i}=ge(),c=jt(v=>v.currentDirectory),d=jt(v=>v.isSwitchingDirectory),[u,p]=l.useState(!1),{uiFont:f,monoFont:m}=$c(),[h,g]=l.useState(()=>r.runtime.isDesktop),[x,y]=l.useState(()=>r.runtime.isVSCode),[b,k]=l.useState(()=>r.runtime.isDesktop?tm():!0);l.useEffect(()=>{g(r.runtime.isDesktop),y(r.runtime.isVSCode)},[r.runtime.isDesktop,r.runtime.isVSCode]),l.useEffect(()=>(Ra(r),()=>Ra(null)),[r]),l.useEffect(()=>{if(typeof document>"u")return;const v=document.documentElement,S=Xi[f]?.stack??Xi[Ux].stack,w=Js[m]?.stack??Js[bn].stack;v.style.setProperty("--font-sans",S),v.style.setProperty("--font-heading",S),v.style.setProperty("--font-family-sans",S),v.style.setProperty("--font-mono",w),v.style.setProperty("--font-family-mono",w),v.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=S)},[f,m]),l.useEffect(()=>{if(n){const S=setTimeout(()=>{const w=document.getElementById("initial-loading");w&&(w.classList.add("fade-out"),setTimeout(()=>{w.remove()},300))},150);return()=>clearTimeout(S)}},[n]),l.useEffect(()=>{const v=setTimeout(()=>{const S=document.getElementById("initial-loading");S&&!n&&(S.classList.add("fade-out"),setTimeout(()=>{S.remove()},300))},5e3);return()=>clearTimeout(v)},[n]),l.useEffect(()=>{(async()=>{await s(),await t()})()},[s,t]),l.useEffect(()=>{if(d)return;(async()=>{Ae.setDirectory(c),await i()})()},[c,d,i]),iy(),ly(),uy(),my(),l.useEffect(()=>{const v=S=>{(S.metaKey||S.ctrlKey)&&S.shiftKey&&S.key==="M"&&(S.preventDefault(),p(w=>!w))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]),l.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const j=l.useCallback(()=>{k(!0),window.location.reload()},[]);return h&&!b?e.jsx(as,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(wy,{onCliAvailable:j})})}):x?e.jsx(as,{children:e.jsx(ol,{apis:r,children:e.jsx(qi,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Jx,{}),e.jsx(Qi,{})]})})})}):e.jsx(as,{children:e.jsx(ol,{apis:r,children:e.jsx(py,{children:e.jsx(qi,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(Xx,{}),e.jsx(Qi,{}),e.jsx(hy,{}),u&&e.jsx(ey,{onClose:()=>p(!1)})]})})})})})}const Vc=async()=>{if(typeof window>"u")return;let r=null,s=null;try{r=window.localStorage.getItem("homeDirectory"),s=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const t=jt.getState();r&&t.homeDirectory!==r&&t.synchronizeHomeDirectory(r),s&&t.setDirectory(s,{showOverlay:!1})},Gc="/auth/session",jy=async()=>fetch(Gc,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Sy=async r=>fetch(Gc,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:r})}),wa=({children:r})=>e.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),e.jsx("div",{className:"relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:r})]}),ky=({message:r="Preparing workspace…"})=>e.jsx(wa,{children:e.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/90 px-6 py-5 text-center shadow-none backdrop-blur",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:r})})}),Ny=({onRetry:r})=>e.jsx(wa,{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:r,className:"w-full max-w-xs",children:"Retry"})]})}),Cy=({children:r})=>{const s=l.useMemo(()=>Zt(),[]),t=l.useMemo(()=>ss(),[]),n=s||t,[o,a]=l.useState(()=>n?"authenticated":"pending"),[i,c]=l.useState(""),[d,u]=l.useState(!1),[p,f]=l.useState(""),m=l.useRef(null),h=l.useRef(n),g=l.useCallback(async()=>{if(n){a("authenticated");return}a(y=>y==="authenticated"?y:"pending");try{const y=await jy();if(y.ok){a("authenticated"),f("");return}if(y.status===401){a("locked");return}a("error")}catch(y){console.warn("Failed to check session status:",y),a("error")}},[n]);l.useEffect(()=>{n||g()},[g,n]),l.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),l.useEffect(()=>{o==="locked"&&m.current&&(m.current.focus(),m.current.select())},[o]),l.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await Tl(),await Il(),await Vc()))())},[n,o]);const x=async y=>{if(y.preventDefault(),!(!i||d)){u(!0),f("");try{const b=await Sy(i);if(b.ok){c(""),a("authenticated");return}if(b.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(b){console.warn("Failed to submit UI password:",b),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(ky,{}):o==="error"?e.jsx(Ny,{onRetry:()=>void g()}):o==="locked"?e.jsx(wa,{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(Pu,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(Tt,{id:"openchamber-ui-password",ref:m,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:y=>{c(y.target.value),p&&f("")},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($t,{className:"h-4 w-4 animate-spin"}):e.jsx(Ru,{className:"h-4 w-4"})})]}),p&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:p})]})]})}):e.jsx(e.Fragment,{children:r})},yo=r=>{if(!r||typeof r!="string")return null;const s=r.trim();if(!s.startsWith("#"))return null;let t=s.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(c=>c+c).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,i=n&255;return`${o} ${a} ${i}`};class My{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(`
|
|
97
|
-
`)}generateTailwindVariables(s){const t=[];t.push(` --background: ${s.colors.surface.background} !important;`),t.push(` --foreground: ${s.colors.surface.foreground} !important;`),t.push(` --muted: ${s.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${s.colors.surface.mutedForeground} !important;`),t.push(` --card: ${s.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${s.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${s.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${s.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${s.colors.interactive.border} !important;`),t.push(` --input: ${s.colors.interactive.border} !important;`),t.push(` --primary: ${s.colors.primary.base} !important;`),t.push(` --primary-foreground: ${s.colors.primary.foreground} !important;`),t.push(` --secondary: ${s.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${s.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${s.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${s.colors.surface.foreground} !important;`),t.push(` --destructive: ${s.colors.status.error} !important;`),t.push(` --destructive-foreground: ${s.colors.status.errorForeground} !important;`),t.push(` --ring: ${s.colors.interactive.focusRing} !important;`),s.config?.radius?.md&&t.push(` --radius: ${s.config.radius.md} !important;`);const n=yo(s.colors.surface.muted),o=yo(s.colors.surface.subtle),a=yo(s.colors.interactive.border);t.push(` --sidebar-base: ${s.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${s.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${s.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${s.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${s.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${s.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${s.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${s.colors.interactive.focusRing} !important;`);const i=s.metadata.variant==="dark",c=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=s.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return s.colors.charts?.series&&Array.isArray(s.colors.charts.series)&&s.colors.charts.series.forEach((u,p)=>{t.push(` --chart-${p+1}: ${u};`)}),s.colors.loading?(t.push(` --loading-spinner: ${s.colors.loading.spinner||s.colors.primary.base};`),t.push(` --loading-spinner-track: ${s.colors.loading.spinnerTrack||s.colors.surface.muted};`)):(t.push(` --loading-spinner: ${s.colors.primary.base};`),t.push(` --loading-spinner-track: ${s.colors.surface.muted};`)),t}apply(s){const t=this.generate(s),n=document.createElement("style");n.id="opencode-theme-variables";let o="";s.metadata.variant==="dark"?(o=`:root {
|
|
98
|
-
${t}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
.dark {
|
|
102
|
-
${t}
|
|
103
|
-
}`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
|
|
104
|
-
${t}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
:root:not(.dark) {
|
|
108
|
-
${t}
|
|
109
|
-
}`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",s.metadata.variant)}generatePrimaryColors(s){const t=[];return t.push(` --primary-base: ${s.base};`),t.push(` --primary-hover: ${s.hover||this.darken(s.base,10)};`),t.push(` --primary-active: ${s.active||this.darken(s.base,20)};`),t.push(` --primary-foreground: ${s.foreground||"#ffffff"};`),t.push(` --primary-muted: ${s.muted||this.opacity(s.base,.5)};`),t.push(` --primary-emphasis: ${s.emphasis||this.lighten(s.base,10)};`),t}generateSurfaceColors(s){const t=[];return t.push(` --surface-background: ${s.background};`),t.push(` --surface-foreground: ${s.foreground};`),t.push(` --surface-muted: ${s.muted};`),t.push(` --surface-muted-foreground: ${s.mutedForeground};`),t.push(` --surface-elevated: ${s.elevated};`),t.push(` --surface-elevated-foreground: ${s.elevatedForeground};`),t.push(` --surface-overlay: ${s.overlay};`),t.push(` --surface-subtle: ${s.subtle};`),t}generateInteractiveColors(s){const t=[];return t.push(` --interactive-border: ${s.border};`),t.push(` --interactive-border-hover: ${s.borderHover};`),t.push(` --interactive-border-focus: ${s.borderFocus};`),t.push(` --interactive-selection: ${s.selection};`),t.push(` --interactive-selection-foreground: ${s.selectionForeground};`),t.push(` --interactive-focus: ${s.focus};`),t.push(` --interactive-focus-ring: ${s.focusRing};`),t.push(` --interactive-cursor: ${s.cursor};`),t.push(` --interactive-hover: ${s.hover};`),t.push(` --interactive-active: ${s.active};`),t}generateStatusColors(s){const t=[];return t.push(` --status-error: ${s.error};`),t.push(` --status-error-foreground: ${s.errorForeground};`),t.push(` --status-error-background: ${s.errorBackground};`),t.push(` --status-error-border: ${s.errorBorder};`),t.push(` --status-warning: ${s.warning};`),t.push(` --status-warning-foreground: ${s.warningForeground};`),t.push(` --status-warning-background: ${s.warningBackground};`),t.push(` --status-warning-border: ${s.warningBorder};`),t.push(` --status-success: ${s.success};`),t.push(` --status-success-foreground: ${s.successForeground};`),t.push(` --status-success-background: ${s.successBackground};`),t.push(` --status-success-border: ${s.successBorder};`),t.push(` --status-info: ${s.info};`),t.push(` --status-info-foreground: ${s.infoForeground};`),t.push(` --status-info-background: ${s.infoBackground};`),t.push(` --status-info-border: ${s.infoBorder};`),t}generateSyntaxColors(s){const t=[];t.push(` --syntax-background: ${s.base.background};`),t.push(` --syntax-foreground: ${s.base.foreground};`),t.push(` --syntax-comment: ${s.base.comment};`),t.push(` --syntax-keyword: ${s.base.keyword};`),t.push(` --syntax-string: ${s.base.string};`),t.push(` --syntax-number: ${s.base.number};`),t.push(` --syntax-function: ${s.base.function};`),t.push(` --syntax-variable: ${s.base.variable};`),t.push(` --syntax-type: ${s.base.type};`),t.push(` --syntax-operator: ${s.base.operator};`);const n=this.generateSyntaxTokens(s);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(s){const t=s.base,n=s.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(s,t){const n=[];return s.markdown?n.push(...this.generateMarkdownColors(s.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),s.chat?n.push(...this.generateChatColors(s.chat,t)):n.push(...this.generateDefaultChatColors(t)),s.tools?n.push(...this.generateToolColors(s.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(s,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${s.heading1||o};`),n.push(` --markdown-heading2: ${s.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${s.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${s.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${s.link||o};`),n.push(` --markdown-link-hover: ${s.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${s.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${s.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${s.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${s.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${s.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${s.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${s.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${s.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${s.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(s){const t=[],n=s.colors.primary.base,o=s.colors.chat?.background||s.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${s.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${s.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${s.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${s.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${s.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${s.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(s.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${s.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${s.colors.interactive.border};`),t}generateChatColors(s,t){const n=[],o=s.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${s.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${s.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${s.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${s.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${s.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${s.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${s.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(s){const t=[];return t.push(` --chat-background: ${s.colors.surface.background};`),t.push(` --chat-user-message: ${s.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${s.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${s.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${s.colors.surface.muted};`),t.push(` --chat-timestamp: ${s.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${s.colors.interactive.border};`),t.push(` --chat-typing: ${s.colors.surface.mutedForeground};`),t}generateToolColors(s,t){const n=[];return n.push(` --tools-background: ${s?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${s?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${s?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${s?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${s?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${s?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),s?.edit?(n.push(` --tools-edit-added: ${s.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${s.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${s.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${s.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${s.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${s.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${s.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(s){const t=[];return t.push(` --tools-background: ${this.opacity(s.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(s.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(s.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${s.colors.surface.mutedForeground};`),t.push(` --tools-title: ${s.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${s.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${s.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${s.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(s){const t=[];return s&&(s.fonts&&(s.fonts.sans&&(t.push(` --font-sans: ${s.fonts.sans};`),t.push(` --font-family-sans: ${s.fonts.sans};`)),s.fonts.mono&&(t.push(` --font-mono: ${s.fonts.mono};`),t.push(` --font-family-mono: ${s.fonts.mono};`)),s.fonts.heading&&t.push(` --font-heading: ${s.fonts.heading};`)),s.radius&&(s.radius.none&&t.push(` --radius-none: ${s.radius.none};`),s.radius.sm&&t.push(` --radius-sm: ${s.radius.sm};`),s.radius.md&&t.push(` --radius-md: ${s.radius.md};`),s.radius.lg&&t.push(` --radius-lg: ${s.radius.lg};`),s.radius.xl&&t.push(` --radius-xl: ${s.radius.xl};`),s.radius.full&&t.push(` --radius-full: ${s.radius.full};`)),s.transitions&&(s.transitions.fast&&t.push(` --transition-fast: ${s.transitions.fast};`),s.transitions.normal&&t.push(` --transition-normal: ${s.transitions.normal};`),s.transitions.slow&&t.push(` --transition-slow: ${s.transitions.slow};`))),t}generateTypographyVariables(){const s=[],t=ss()?Qu:ea;return s.push(" /* Semantic Typography Variables */"),s.push(" --ui-regular-font-weight: 400;"),s.push(" /* Markdown content - all markdown elements use same size */"),s.push(` --text-markdown: ${t.markdown};`),s.push(" /* Code content - all code elements use same size */"),s.push(` --text-code: ${t.code};`),s.push(" /* UI headers - dialog titles, panel headers */"),s.push(` --text-ui-header: ${t.uiHeader};`),s.push(" /* UI labels - buttons, menus, navigation */"),s.push(` --text-ui-label: ${t.uiLabel};`),s.push(" /* Metadata - timestamps, status, helper text */"),s.push(` --text-meta: ${t.meta};`),s.push(" /* Micro text - badges, shortcuts, indicators */"),s.push(` --text-micro: ${t.micro};`),s.push(" /* Heading line height and letter spacing */"),s.push(" --h1-line-height: 1.25rem;"),s.push(" --h2-line-height: 1.25rem;"),s.push(" --h3-line-height: 1.5rem;"),s.push(" --h4-line-height: 1.5rem;"),s.push(" --h5-line-height: 1.5rem;"),s.push(" --h6-line-height: 1.5rem;"),s.push(" --h1-letter-spacing: -0.025em;"),s.push(" --h2-letter-spacing: -0.02em;"),s.push(" --h3-letter-spacing: -0.015em;"),s.push(" --h4-letter-spacing: -0.01em;"),s.push(" --h5-letter-spacing: 0;"),s.push(" --h6-letter-spacing: 0.01em;"),s.push(" /* UI element line height and letter spacing */"),s.push(" --ui-button-line-height: 1.375rem;"),s.push(" --ui-button-letter-spacing: 0.02em;"),s.push(" --ui-button-font-weight: 500;"),s.push(" --ui-label-line-height: 1rem;"),s.push(" --ui-label-letter-spacing: 0.03em;"),s.push(" --ui-label-font-weight: 500;"),s.push(" --ui-caption-line-height: 1rem;"),s.push(" --ui-caption-letter-spacing: 0.025em;"),s.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Markdown line height and letter spacing */"),s.push(" --markdown-body-line-height: 1.5rem;"),s.push(" --markdown-body-letter-spacing: 0;"),s.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-h1-line-height: 1.25rem;"),s.push(" --markdown-h1-letter-spacing: -0.025em;"),s.push(" --markdown-h2-line-height: 1.25rem;"),s.push(" --markdown-h2-letter-spacing: -0.02em;"),s.push(" --markdown-h3-line-height: 1.5rem;"),s.push(" --markdown-h3-letter-spacing: -0.015em;"),s.push(" --markdown-h4-line-height: 1.5rem;"),s.push(" --markdown-h4-letter-spacing: -0.01em;"),s.push(" --markdown-h5-line-height: 1.5rem;"),s.push(" --markdown-h5-letter-spacing: 0;"),s.push(" --markdown-h6-line-height: 1.5rem;"),s.push(" --markdown-h6-letter-spacing: 0.01em;"),s.push(" --markdown-list-line-height: 1.375rem;"),s.push(" --markdown-code-block-line-height: 1rem;"),s.push(" --ui-button-small-line-height: 1.25rem;"),s.push(" --ui-button-small-letter-spacing: 0.02em;"),s.push(" --ui-button-small-font-weight: 500;"),s.push(" --markdown-body-small-line-height: 1.375rem;"),s.push(" --markdown-body-small-letter-spacing: 0;"),s.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-button-large-line-height: 1.5rem;"),s.push(" --ui-button-large-letter-spacing: 0.02em;"),s.push(" --ui-button-large-font-weight: 500;"),s.push(" --markdown-body-large-line-height: 1.625rem;"),s.push(" --markdown-body-large-letter-spacing: 0;"),s.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Code line height and letter spacing */"),s.push(" --code-inline-line-height: 1rem;"),s.push(" --code-inline-letter-spacing: 0;"),s.push(" --code-inline-font-weight: 400;"),s.push(" --code-block-line-height: 1.4rem;"),s.push(" --code-block-letter-spacing: 0;"),s.push(" --code-block-font-weight: 400;"),s.push(" --code-line-numbers-line-height: 1.25rem;"),s.push(" --code-line-numbers-letter-spacing: 0;"),s.push(" --code-line-numbers-font-weight: 400;"),s.push(" /* Additional UI element line height and letter spacing */"),s.push(" --ui-badge-line-height: 1rem;"),s.push(" --ui-badge-letter-spacing: 0.025em;"),s.push(" --ui-badge-font-weight: 500;"),s.push(" --ui-tooltip-line-height: 1rem;"),s.push(" --ui-tooltip-letter-spacing: 0.025em;"),s.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-input-line-height: 1.375rem;"),s.push(" --ui-input-letter-spacing: 0.02em;"),s.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --ui-helper-text-line-height: 1rem;"),s.push(" --ui-helper-text-letter-spacing: 0.025em;"),s.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" /* Additional markdown line height and letter spacing */"),s.push(" --markdown-blockquote-line-height: 1.5rem;"),s.push(" --markdown-blockquote-letter-spacing: 0;"),s.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-list-letter-spacing: 0;"),s.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-link-line-height: 1.5rem;"),s.push(" --markdown-link-letter-spacing: 0;"),s.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),s.push(" --markdown-code-line-height: 1.35;"),s.push(" --markdown-code-letter-spacing: 0;"),s.push(" --markdown-code-font-weight: 400;"),s.push(" --markdown-code-block-letter-spacing: 0;"),s.push(" --markdown-code-block-font-weight: 400;"),s}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(s,t){return s.startsWith("#")?`${s}${Math.round(t*255).toString(16).padStart(2,"0")}`:s.startsWith("rgb")?s.replace("rgb","rgba").replace(")",`, ${t})`):s}removeTransparency(s){return s.startsWith("#")?s.length===9?s.slice(0,7):s.length===5?s.slice(0,4):s:s.startsWith("rgba")?s.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):s}addTransparency(s,t){if(s.startsWith("#")){const n=s.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),i=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${i}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${i}, ${t})`}}return s.startsWith("rgb")?s.replace("rgb","rgba").replace(")",`, ${t})`):s}darken(s,t){if(s.startsWith("#")){const n=parseInt(s.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,i=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return s}lighten(s,t){if(s.startsWith("#")){const n=parseInt(s.slice(1),16),o=Math.round(2.55*t),a=(n>>16)+o,i=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(c<255?c<0?0:c:255)).toString(16).slice(1)}return s}adjustHue(s,t){return this.lighten(s,t/10)}emphasize(s){return this.lighten(s,15)}kebabCase(s){return s.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const va={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"}}},ja={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"}}},Vr=[va,ja];function Rn(r){return Vr.find(s=>s.metadata.id===r)}const qc=va.metadata.id,Kc=ja.metadata.id,Ay=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Yc=r=>r==="dark"?ja:va,Dy=r=>(Vr.find(t=>t.metadata.variant===r)??Yc(r)).metadata.id,dn=(r,s)=>{const t=Rn(r);return t&&t.metadata.variant===s?t:Vr.find(o=>o.metadata.variant===s)??Yc(s)},Ey=typeof window<"u"?l.useLayoutEffect:l.useEffect,Ln=(r,s)=>{if(!r)return s==="light"?qc:Kc;const t=Rn(r);return t&&t.metadata.variant===s?t.metadata.id:Dy(s)},Ty=r=>{let s=qc,t=Kc,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const f=Rn(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?t=f.metadata.id:s=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);s=Ln(a,"light"),t=Ln(i,"dark")}if(r){const o=Rn(r);o&&(o.metadata.variant==="light"?s=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:s,darkThemeId:t}};function Iy({children:r,defaultThemeId:s}){const t=de.useMemo(()=>new My,[]),[n,o]=de.useState(()=>Ty(s)),[a,i]=de.useState(()=>Ay()),[c,d]=de.useState(()=>typeof window>"u"||!ss()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=de.useMemo(()=>ss(),[]),p=de.useMemo(()=>u&&c?c:n.themeMode==="light"?dn(n.lightThemeId,"light"):n.themeMode==="dark"||a?dn(n.darkThemeId,"dark"):dn(n.lightThemeId,"light"),[u,n,a,c]),f=de.useMemo(()=>u&&c?[c,...Vr]:Vr,[u,c]);de.useEffect(()=>{if(!u)return;const v=D=>{d(D);const A=D.metadata.variant==="dark"?"dark":"light",N=Fe.getState();N.theme!==A&&N.setTheme(A)},S=D=>{const A=D.detail;A?.theme&&v(A.theme)},w=window.__OPENCHAMBER_VSCODE_THEME__;return w&&v(w),window.addEventListener("openchamber:vscode-theme",S),()=>window.removeEventListener("openchamber:vscode-theme",S)},[u]);const m=de.useCallback(v=>{if(typeof document>"u")return;const S=v.colors.surface.background;Zt()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=S;let w=document.querySelector('meta[name="theme-color"]');w||(w=document.createElement("meta"),w.setAttribute("name","theme-color"),document.head.appendChild(w)),w.setAttribute("content",S);const D=v.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let A=document.querySelector(`meta[name="theme-color"][media="${D}"]`);A||(A=document.createElement("meta"),A.setAttribute("name","theme-color"),A.setAttribute("media",D),document.head.appendChild(A)),A.setAttribute("content",S)},[]),h=de.useCallback(v=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",v)},[]);Ey(()=>{if(typeof window>"u")return;t.apply(p),h(u),m(p);const v=document.documentElement;v.classList.remove("light","dark"),v.classList.add(p.metadata.variant)},[h,t,p,u,m]),de.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const v=window.matchMedia("(prefers-color-scheme: dark)"),S=w=>{i(w.matches)};return i(v.matches),v.addEventListener("change",S),()=>v.removeEventListener("change",S)},[n.themeMode]),de.useEffect(()=>{typeof window>"u"||(localStorage.setItem("themeMode",n.themeMode),localStorage.setItem("lightThemeId",n.lightThemeId),localStorage.setItem("darkThemeId",n.darkThemeId),localStorage.setItem("useSystemTheme",String(n.themeMode==="system")),localStorage.setItem("selectedThemeId",p.metadata.id),localStorage.setItem("selectedThemeVariant",p.metadata.variant==="light"?"light":"dark"))},[n,p]),de.useEffect(()=>{ks({themeId:p.metadata.id,themeVariant:p.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[p.metadata.id,p.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),de.useEffect(()=>{if(typeof window>"u")return;const v=S=>{const w=S.detail;w&&o(D=>{let A=D.themeMode;w.useSystemTheme===!0?A="system":w.useSystemTheme===!1&&(w.themeVariant==="dark"||w.themeVariant==="light")&&(A=w.themeVariant);let N=D.lightThemeId;typeof w.lightThemeId=="string"&&w.lightThemeId.length>0&&(N=Ln(w.lightThemeId,"light"));let M=D.darkThemeId;return typeof w.darkThemeId=="string"&&w.darkThemeId.length>0&&(M=Ln(w.darkThemeId,"dark")),A===D.themeMode&&N===D.lightThemeId&&M===D.darkThemeId?D:{themeMode:A,lightThemeId:N,darkThemeId:M}})};return window.addEventListener("openchamber:settings-synced",v),()=>window.removeEventListener("openchamber:settings-synced",v)},[]);const g=de.useCallback(v=>{const S=f.find(w=>w.metadata.id===v);S&&o(w=>S.metadata.variant==="dark"?w.darkThemeId===S.metadata.id&&w.themeMode==="dark"?w:{...w,darkThemeId:S.metadata.id,themeMode:"dark"}:w.lightThemeId===S.metadata.id&&w.themeMode==="light"?w:{...w,lightThemeId:S.metadata.id,themeMode:"light"})},[f]),x=de.useCallback(v=>{o(S=>S.themeMode===v?S:{...S,themeMode:v})},[]),y=de.useCallback(v=>{if(v){o(w=>w.themeMode==="system"?w:{...w,themeMode:"system"});return}const S=p.metadata.variant==="dark"?"dark":"light";o(w=>w.themeMode===S?w:{...w,themeMode:S})},[p.metadata.variant]),b=de.useCallback(v=>{const S=f.find(w=>w.metadata.id===v&&w.metadata.variant==="light");S&&o(w=>w.lightThemeId===S.metadata.id?w:{...w,lightThemeId:S.metadata.id})},[f]),k=de.useCallback(v=>{const S=f.find(w=>w.metadata.id===v&&w.metadata.variant==="dark");S&&o(w=>w.darkThemeId===S.metadata.id?w:{...w,darkThemeId:S.metadata.id})},[f]),j={currentTheme:p,availableThemes:f,setTheme:g,isSystemPreference:n.themeMode==="system",setSystemPreference:y,themeMode:n.themeMode,setThemeMode:x,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:b,setDarkThemePreference:k};return e.jsx(da.Provider,{value:j,children:r})}const Fy=({children:r})=>{const{theme:s,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=Fe();return l.useLayoutEffect(()=>{t(),o(),i()},[s,t,n,o,a,i]),l.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{s==="system"&&t()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[s,t]),e.jsx(e.Fragment,{children:r})},Py={getLastAssistantMessage(){const r=ge.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const t=r.messages.get(s);if(!t||t.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=t.length-1;n>=0;n--){const o=t[n];if(o.info.role==="assistant"){const a=o.parts.map(m=>{const h={id:m.id,type:m.type};return m.type==="text"?(h.text=m.text,h.textLength=m.text?.length||0):m.type==="tool"?(h.tool=m.tool,h.state=m.state?.status):(m.type==="step-start"||m.type==="step-finish")&&(h.isStepMarker=!0),h}),i=a.some(m=>m.type==="text"&&m.text&&m.text.trim().length>0),c=a.some(m=>m.type==="tool"),d=a.some(m=>m.type==="step-start"||m.type==="step-finish"),u=a.length===0,p=!i&&!c&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:p,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:i,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!c}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!c&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(r,s=80){return!r||typeof r!="string"||r.length<=s?r:r.substring(0,s)+"…"},truncateMessages(r){return r.map(s=>({...s,parts:(s.parts||[]).map(t=>{const n={...t};return"text"in t&&(n.text=this.truncateString(t.text)),"textPreview"in t&&(n.textPreview=this.truncateString(t.textPreview)),t.state&&(n.state={...t.state},"output"in t.state&&(n.state.output=this.truncateString(t.state.output)),"error"in t.state&&(n.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(n.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),n})}))},getAllMessages(r=!1){const s=ge.getState(),t=s.currentSessionId;if(!t)return console.log("[ERROR] No active session"),[];const n=s.messages.get(t)||[];return console.log(`[MESSAGES] Total messages in session: ${n.length}`),n.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),r?this.truncateMessages(n):n},checkLastMessage(){const r=this.getLastAssistantMessage();if(!r)return!1;const s=r.isEmpty||r.isEmptyResponse;return s?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:r.messageId,isEmpty:r.isEmpty,isEmptyResponse:r.isEmptyResponse,partsCount:r.partsCount}),r.parts.length>0&&console.log("Parts:",r.parts)):console.log("[OK] Last message looks good!"),s},getStreamingState(){const r=ge.getState(),s=r.currentSessionId?r.streamingMessageIds.get(r.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:s,streamingMessageIds:Array.from(r.streamingMessageIds.entries()),messageStreamStates:Array.from(r.messageStreamStates.entries())}),{streamingMessageId:s,streamingMessageIds:r.streamingMessageIds,streamStates:r.messageStreamStates}},findEmptyMessages(){const r=ge.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),[];const n=(r.messages.get(s)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!i&&!c});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
|
|
110
|
-
`),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
|
|
111
|
-
`),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
|
|
112
|
-
`),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)
|
|
113
|
-
`),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(r={}){const{includeNonAssistant:s=!1,verbose:t=!0,maxTableRows:n=25}=r,o=ge.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(m=>m.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=m=>typeof m=="number"&&Number.isFinite(m)?m:null,p=m=>{const h=m.filter(g=>typeof g=="number");return h.length>0?Math.max(...h):null},f=c.map((m,h)=>{const g=m.info??{},x=Array.isArray(m.parts)?m.parts:[],y=g.time??{},b=u(y.completed),k=b!==null,j=x.filter(E=>E.type==="tool"),v=x.filter(E=>E.type==="reasoning"),S=p(j.map(E=>u(E.state?.time?.end??E.state?.time?.start))),w=p(v.map(E=>u(E.time?.end??E.time?.start))),D=p([S,w].filter(E=>E!==null)),A=j.some(E=>["pending","running","started"].includes(E.state?.status)),N=v.some(E=>typeof E.time?.end!="number");j.length>0&&(d.withTools+=1),v.length>0&&(d.withReasoning+=1),k||(d.completedMissing+=1);const M=!!(k&&typeof S=="number"&&b<S);M&&(d.completedBeforeTool+=1);const C=!!(k&&typeof w=="number"&&b<w);return C&&(d.completedBeforeReasoning+=1),k&&A&&(d.runningToolsWhenCompleted+=1),k&&N&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:b,latestToolTimestamp:S,latestReasoningTimestamp:w,latestPartTimestamp:D,completed_missing:!k,completed_before_tool:M,completed_before_reasoning:C,running_tools_when_completed:!!(k&&A),reasoning_open_when_completed:!!(k&&N),has_tools:j.length>0,has_reasoning:v.length>0}});return t&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const r=ge.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const n=(r.messages.get(s)||[]).filter(y=>y.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(y=>y.type==="step-finish"),i=o.parts.some(y=>y.type==="step-finish"&&y.reason==="stop"),d=o.info.time?.completed,u=o.info.status,p=typeof d=="number"&&d>0||u==="completed",f=!!(p&&i),m=r.messageStreamStates,h=o.info.sessionID?r.streamingMessageIds.get(o.info.sessionID)??null:null,g=m.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:",f),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:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Py,console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message"),window.addEventListener("error",r=>{try{const s=r.message||"",t=r.filename||"";typeof s=="string"&&s.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&r.preventDefault()}catch{}}));let al=!1;const Ry=()=>{if(al||typeof window>"u")return;al=!0;let r={showReasoningTraces:Fe.getState().showReasoningTraces},s=null,t=null;const n=()=>{const a=s;s=null,t=null,a&&Object.keys(a).length>0&&ks(a)},o=a=>{s={...s??{},...a},!t&&(t=setTimeout(n,150))};Fe.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces},c={};i.showReasoningTraces!==r.showReasoningTraces&&(c.showReasoningTraces=i.showReasoningTraces),r=i,Object.keys(c).length>0&&o(c)})};let il=!1;const ll="openchamber-typography-base",Ly=()=>{if(typeof document>"u")return;const s=`:root {
|
|
114
|
-
${Object.entries(ea).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
|
|
115
|
-
`)}
|
|
116
|
-
}
|
|
117
|
-
`,t=document.getElementById(ll);if(t){t.textContent=s;return}const n=document.createElement("style");n.id=ll,n.textContent=s,document.head.appendChild(n)},_y=()=>{il||typeof window>"u"||(il=!0,Ly())},By=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Tl();await Il();Ry();_y();await Vc();typeof window<"u"&&(window.debugContextTokens=()=>{const r=window.__zustand_session_store__;if(!r)return;const s=r.getState(),t=s.currentSessionId;if(!t)return;const o=(s.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const i=o[o.length-1].info.tokens;i&&typeof i=="object"&&console.debug("Token breakdown:",{base:(i.input||0)+(i.output||0)+(i.reasoning||0),cache:i.cache?(i.cache.read||0)+(i.cache.write||0):0}),s.sessionContextUsage.get(t);const c=window.__zustand_config_store__;if(c){const d=c.getState().getCurrentModel(),u=d?.limit?.context||0,p=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&s.getContextUsage(u,p)}});const Xc=document.getElementById("root");if(!Xc)throw new Error("Root element not found");Lu.createRoot(Xc).render(e.jsx(de.StrictMode,{children:e.jsx(Iy,{children:e.jsx(Fy,{children:e.jsx(Cy,{children:e.jsx(vy,{apis:By})})})})}));if(typeof window<"u"){const r=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(s){console.warn("Failed to notify desktop runtime that renderer is ready:",s)}};r(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&r()})}const zy=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{Ts as D,Ur as S,Is as a,sp as b,T as c,xg as d,yg as e,Oi as f,Gr as g,bg as h,vg as i,zy as m,jg as p,wg as r,mn as t};
|