@openchamber/web 1.1.4 → 1.1.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.
@@ -0,0 +1,75 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.pnpm-BKK22KLz.js","assets/vendor--B3aGWKBE.css","assets/ToolOutputDialog-DYcEnIQc.js","assets/index-0hunkiaS.js","assets/index-QJKmukSI.css"])))=>i.map(i=>d[i]);
2
+ import{t as jc,c as kc,j as e,R as Nc,T as Cc,P as Mc,C as Ac,A as Dc,a as Ec,S as Ri,b as Li,d as It,e as Bt,p as as,f as is,g as Tc,I as Ic,h as l,i as Fc,k as Pc,l as Rc,m as Lc,n as _c,o as Bc,q as Oc,s as Nt,r as $c,u as zc,v as Hc,w as Wc,x as xs,y as Uc,z as Vc,B as Gc,D as fe,E as na,F as qc,G as Kc,H as wt,K as so,J as Yc,U as Ft,_ as jr,Z as Xc,Y as Ts,Q as Fs,W as Tt,O as kr,V as jo,L as ro,M as rr,N as _i,X as Jc,$ as Zc,a0 as Qc,a1 as os,a2 as ed,a3 as td,a4 as sd,a5 as rd,a6 as nd,a7 as no,a8 as ko,a9 as od,aa as on,ab as No,ac as Sn,ad as nr,ae as ad,af as Zt,ag as an,ah as jn,ai as ks,aj as Ps,ak as Bi,al as Oi,am as Nr,an as ge,ao as id,ap as ps,aq as Gt,ar as oa,as as Co,at as $i,au as Mo,av as Ao,aw as Do,ax as kn,ay as aa,az as Vs,aA as Eo,aB as gr,aC as Cr,aD as ld,aE as cd,aF as zi,aG as Hi,aH as Zs,aI as dd,aJ as ud,aK as Dn,aL as md,aM as Yt,aN as fd,aO as pd,aP as En,aQ as hd,aR as To,aS as Io,aT as gd,aU as yd,aV as oo,aW as xd,aX as er,aY as Hs,aZ as Nn,a_ as Cn,a$ as Fo,b0 as bd,b1 as wd,b2 as vd,b3 as Sd,b4 as jd,b5 as kd,b6 as Nd,b7 as ao,b8 as Xr,b9 as Po,ba as Cd,bb as Md,bc as lr,bd as Ad,be as Dd,bf as Ed,bg as Mr,bh as Td,bi as Id,bj as Fd,bk as Pd,bl as io,bm as Rd,bn as ms,bo as Ld,bp as _d,bq as Bd,br as yr,bs as Od,bt as $d,bu as zd,bv as Hd,bw as Wd,bx as Ud,by as Vd,bz as Gd,bA as qd,bB as Kd,bC as Yd,bD as Xd,bE as Jd,bF as Zd,bG as Qd,bH as eu,bI as ia,bJ as Wi,bK as tu,bL as su,bM as la,bN as ru,bO as nu,bP as ou,bQ as au,bR as iu}from"./vendor-.pnpm-BKK22KLz.js";import{c as lu,l as cu,g as du,r as uu,d as mu,a as fu,b as pu,u as hu,e as gu,f as yu,h as xu,i as bu,j as wu,k as vu}from"./index-0hunkiaS.js";function T(...r){return jc(kc(r))}const Ui=(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 m=c?`${c}/${d}`:d;if(m.length>i)break;c=m}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},ln=r=>r?r==="/"?"/":r.replace(/\/+$/,""):"";function Pt(r,s){if(!r)return"";const t=ln(r);if(t==="/")return"/";const n=s?ln(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 Tn(r,s){if(!r)return"/";const t=ln(r);if(!t||t==="/")return"/";const n=s?ln(s):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Su({delayDuration:r=0,...s}){return e.jsx(Ec,{"data-slot":"tooltip-provider",delayDuration:r,...s})}function ut({delayDuration:r=0,...s}){return e.jsx(Su,{delayDuration:r,children:e.jsx(Nc,{"data-slot":"tooltip",...s})})}function mt({...r}){return e.jsx(Cc,{"data-slot":"tooltip-trigger",...r})}function lt({className:r,sideOffset:s=0,children:t,...n}){return e.jsx(Mc,{children:e.jsxs(Ac,{"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(Dc,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}const ju=Li("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg typography-ui-label font-medium transition-[background-color,border-color,color,box-shadow,opacity] duration-150 ease-in-out disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-none hover:bg-primary/90",destructive:"bg-destructive text-white shadow-none hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-none hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-none hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-lg gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-lg px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function De({className:r,variant:s,size:t,asChild:n=!1,...o}){const a=n?Ri:"button";return e.jsx(a,{"data-slot":"button",className:T(ju({variant:s,size:t,className:r})),...o})}let In=null;const ca=()=>{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}}},ku=()=>{if(typeof window>"u"||!window.localStorage)return ca();const r=window.localStorage,s=ca();let t=!0;const n=()=>{t=!1};return{getItem:m=>{if(t)try{const f=r.getItem(m);if(f!==null)return f}catch{n()}return s.getItem(m)},setItem:(m,f)=>{if(t)try{r.setItem(m,f),s.removeItem(m);return}catch{n()}s.setItem(m,f)},removeItem:m=>{if(t)try{r.removeItem(m)}catch{n()}s.removeItem(m)},clear:()=>{if(t)try{r.clear()}catch{n()}s.clear()},key:m=>{if(t)try{return r.key(m)}catch{n()}return s.key(m)},get length(){if(t)try{return r.length+s.length}catch{n()}return s.length}}},Ut=()=>(In||(In=ku()),In),Re=It()(Bt(as((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,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})},setDiffLayoutPreference:t=>{r({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{r(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{r({diffWrapLines:t})},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:is(()=>Ut()),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,diffLayoutPreference:r.diffLayoutPreference,diffWrapLines:r.diffWrapLines})}),{name:"ui-store"})),Ht=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",rs=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Rs=()=>Ht()?window.opencodeDesktop??null:null,Vi=()=>{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},Gi=async()=>{const r=Rs();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},Nu=async()=>{const r=Rs();if(!r)return null;try{return await r.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},Cu=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,qi=async()=>{const r=Vi();if(!r)return null;try{return await r.getSettings()}catch(s){return console.warn("Failed to read desktop settings",s),null}},Mu=async r=>{const s=Vi();if(!s)return null;try{return await s.updateSettings(r)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},Au=async r=>{const s=Rs();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)}}},Du=async r=>{const s=Rs();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)}}},Eu=async r=>{const s=Rs();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)}}},Tu=async()=>{const r=Rs();if(!r||!r.checkForUpdates)return null;try{return await r.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},Iu=async r=>{const s=Rs();if(!s||!s.downloadUpdate)return!1;try{return await s.downloadUpdate(r),!0}catch(t){return console.warn("Failed to download update",t),!1}},Fu=async()=>{const r=Rs();if(!r||!r.restartToUpdate)return!1;try{return await r.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}},Pu="/api",Ru=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Lu=r=>{const s=typeof r=="string"&&r.trim().length>0?r.trim():"/api";if(Ru.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}},_u=()=>{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},Fr=r=>r.replace(/\\/g,"/"),Fn=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_RUNTIME_APIS__;return r&&r.runtime?.isDesktop&&r.files?r.files:null};class Bu{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=Pu){const n=_u()||s;this.baseUrl=Lu(n),this.client=Tc({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 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 m=await this.client.event.subscribe({query:i?{directory:i}:void 0,signal:a.signal,sseMaxRetryAttempts:2,sseDefaultRetryDelay:500,sseMaxRetryDelay:8e3,onSseError:f=>{f instanceof Error&&f.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",f),t&&!a.signal.aborted&&t(f))},onSseEvent:f=>{if(!a.signal.aborted){const u=f.data;u&&typeof u=="object"&&s(u)}}});n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const f of m.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(m){if(m?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",m),t&&t(m);const f=Math.min(500*Math.pow(2,d),8e3);await new Promise(u=>setTimeout(u,f)),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=Fn();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=Fn();if(t)try{const n=await t.listDirectory(s||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:Fr(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=Fn(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Fr(o):null;if(n)try{const f=await n.search({directory:o||"",query:s,maxResults:t?.limit});return Array.isArray(f)?f.map(u=>{const p=Fr(u.path),h=p.split("/").filter(Boolean).pop()||p,g=u.preview&&u.preview.length>0&&typeof u.preview[0]=="string"?Fr(u.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:g,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(f){throw console.error("Failed to search files:",f),f}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 f=await d.json().catch(()=>({})),u=typeof f.error=="string"?f.error:"Failed to search files";throw new Error(u)}const m=await d.json();return!m||!Array.isArray(m.files)?[]:m.files}async getFilesystemHome(){const s=await Gi();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 Bu,lo=new Set;function Ro(r){return lo.add(r),()=>{lo.delete(r)}}function ys(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 lo)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 cn(r,s){return r.scopes.includes("all")||r.scopes.includes(s)}const Ou="https://models.dev/api.json",$u="/api/openchamber/models-metadata",zu=r=>r?.toLowerCase?.()??"",Hu=r=>r==="primary"||r==="all"||r===void 0||r===null,Ar=r=>typeof r=="object"&&r!==null,dn=r=>Array.isArray(r)&&r.every(s=>typeof s=="string"),Wu=r=>{if(!Ar(r))return!1;const s=r;if(s.modalities){const{input:t,output:n}=s.modalities;if(t&&!dn(t)||n&&!dn(n))return!1}return!0},Uu=r=>{if(!Ar(r))return!1;const s=r;return s.models===void 0||Ar(s.models)},Ki=(r,s)=>{const t=zu(r);return!t||!s?"":`${t}/${s}`},Vu=r=>{const s=new Map;if(!Ar(r))return s;for(const[t,n]of Object.entries(r)){if(!Uu(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!Ar(a)))for(const[i,c]of Object.entries(a)){if(!Wu(c))continue;const d=typeof i=="string"&&i.length>0?i:c.id;if(!d||typeof d!="string"||d.length===0)continue;const m={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:dn(c.modalities.input)?c.modalities.input:void 0,output:dn(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},f=Ki(o,d);f&&s.set(f,m)}}return s},Gu=async()=>{if(typeof fetch!="function")return new Map;const r=[$u,Ou];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 Vu(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},qu=r=>new Promise(s=>setTimeout(s,r)),xt=It()(Bt(as((r,s)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,loadProviders:async()=>{try{const t=Gu(),n=await Ae.getProviders(),o=Array.isArray(n?.providers)?n.providers:[],a=n?.default||{},i=o.map(u=>{const p=u.models??{},h=Object.keys(p).map(g=>p[g]);return{...u,models:h}}),c=a.provider||i[0]?.id||"",d=i.find(u=>u.id===c),m=a.model||d?.models?.[0]?.id||"";r({providers:i,defaultProviders:a,currentProviderId:c,currentModelId:m});const f=await t;f.size>0&&r({modelsMetadata:f})}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(u=>Hu(u.mode)),f=d.find(u=>u.name==="build")||d[0]||i[0];if(r({currentAgentName:f.name}),f?.model?.providerID&&f?.model?.modelID){const u=c.find(p=>p.id===f.model.providerID);u&&u.models.find(h=>h.id===f.model.modelID)&&r({currentProviderId:f.model.providerID,currentModelId:f.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:m,getAgentModelForSession:f}=i;c&&a.setState(u=>{const p=new Map(u.currentAgentContext);return p.set(c,t),{currentAgentContext:p}}),c&&d(c)&&(f(c,t)||m(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(m=>m.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 qu(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=Ki(t,n);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)}}),{name:"config-store",storage:is(()=>Ut()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=xt);let da=null;da||(da=Ro(async r=>{const s=[];if(cn(r,"agents")){const{loadAgents:t}=xt.getState();s.push(t().then(()=>{}))}if(cn(r,"providers")){const{loadProviders:t}=xt.getState();s.push(t())}s.length>0&&await Promise.all(s)}));const Dt={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Ku=180,Ot=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Lo(r){const s=Ot();return s?s.checkIsGitRepository(r):lu(r)}async function Yu(r){const s=Ot();return s?s.getGitStatus(r):du(r)}async function Xu(r,s){const t=Ot();return t?t.deleteGitBranch(r,s):mu(r,s)}async function Ju(r,s){const t=Ot();return t?t.deleteRemoteBranch(r,s):fu(r,s)}async function Zu(r){const s=Ot();return s?s.listGitWorktrees(r):cu(r)}async function Qu(r,s){const t=Ot();return t?t.addGitWorktree(r,s):vu(r,s)}async function Yi(r,s){const t=Ot();return t?t.removeGitWorktree(r,s):uu(r,s)}async function em(r){const s=Ot();return s?s.ensureOpenChamberIgnored(r):bu(r)}async function tm(r,s={}){const t=Ot();return t?t.gitPush(r,s):wu(r,s)}async function sm(){const r=Ot();return r?r.getGitIdentities():xu()}async function rm(r){const s=Ot();return s?s.createGitIdentity(r):gu(r)}async function nm(r,s){const t=Ot();return t?t.updateGitIdentity(r,s):hu(r,s)}async function om(r){const s=Ot();return s?s.deleteGitIdentity(r):pu(r)}async function am(r){const s=Ot();return s?s.getCurrentGitIdentity(r):yu(r)}const im=".openchamber",bs=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},ua=(r,s)=>{const t=bs(r),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Xi=r=>r?r.startsWith("refs/heads/")?r.substring(11):r.startsWith("heads/")?r.substring(6):r.startsWith("refs/")?r.substring(5):r:"",lm=async r=>{try{await Ae.createDirectory(r)}catch(s){if(s instanceof Error&&/exist/i.test(s.message))return;throw s}};async function cm(r,s){const t=bs(r),n=ua(t,im);return await lm(n),ua(n,s)}async function dm(r){const{projectDirectory:s,worktreeSlug:t,branch:n,createBranch:o}=r,a=bs(s),i=await cm(a,t);return await Qu(a,{path:i,branch:n,createBranch:!!o}),{path:i,branch:n,label:Xi(n),projectDirectory:a,relativePath:i.startsWith(`${a}/`)?i.slice(a.length+1):i}}async function ma(r){const{projectDirectory:s,path:t,force:n}=r,o=bs(s);await Yi(o,{path:t,force:n})}async function um(r){const{projectDirectory:s,path:t,branch:n,force:o,deleteRemote:a,remote:i}=r,c=bs(s),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Yi(c,{path:t,force:o}),d&&(await Xu(c,{branch:d,force:!0}),a))try{await Ju(c,{branch:d,remote:i})}catch(m){console.warn("Failed to delete remote branch during worktree archive:",m)}}async function un(r){const s=bs(r);return Zu(s)}async function Jr(r){const s=bs(r),t=await Yu(s);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function mn(r,s){const t=bs(r),n=bs(s.worktree);return{path:n,branch:s.branch??"",label:Xi(s.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const fa=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},mm=r=>!r||typeof r!="object"?null:{showReasoningTraces:r.showReasoningTraces},fm=r=>{const s=Re.getState();typeof r.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(r.showReasoningTraces)},pm=async()=>{if(typeof window>"u")return null;if(Ht()){const s=window.opencodeAppearance;if(!s||typeof s.load!="function")return null;try{const t=await s.load();return fa(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=mm(s);return fa(t)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let Ji=null;const pa=r=>{Ji=r},Zi=()=>Ji,Zr=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"))},Qi=()=>{const r=Re.persist;if(r&&typeof r=="object")return r},el=()=>Zi()?.settings??null,Qr=r=>{const s=Re.getState();typeof r.showReasoningTraces=="boolean"&&r.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(r.showReasoningTraces)},ha=r=>{if(!r||typeof r!="object")return null;const s=r,t={};return typeof s.themeId=="string"&&s.themeId.length>0&&(t.themeId=s.themeId),(s.useSystemTheme===!0||s.useSystemTheme===!1)&&(t.useSystemTheme=s.useSystemTheme),typeof s.themeVariant=="string"&&(s.themeVariant==="light"||s.themeVariant==="dark")&&(t.themeVariant=s.themeVariant),typeof s.lightThemeId=="string"&&s.lightThemeId.length>0&&(t.lightThemeId=s.lightThemeId),typeof s.darkThemeId=="string"&&s.darkThemeId.length>0&&(t.darkThemeId=s.darkThemeId),typeof s.lastDirectory=="string"&&s.lastDirectory.length>0&&(t.lastDirectory=s.lastDirectory),typeof s.homeDirectory=="string"&&s.homeDirectory.length>0&&(t.homeDirectory=s.homeDirectory),Array.isArray(s.approvedDirectories)&&(t.approvedDirectories=s.approvedDirectories.filter(n=>typeof n=="string"&&n.length>0)),Array.isArray(s.securityScopedBookmarks)&&(t.securityScopedBookmarks=s.securityScopedBookmarks.filter(n=>typeof n=="string"&&n.length>0)),Array.isArray(s.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(s.pinnedDirectories.filter(n=>typeof n=="string"&&n.length>0)))),typeof s.showReasoningTraces=="boolean"&&(t.showReasoningTraces=s.showReasoningTraces),t},hm=async()=>{const r=el();if(r)try{const s=await r.load();return ha(s.settings)}catch(s){console.warn("Failed to load shared settings from runtime settings API:",s)}try{const s=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)return null;const t=await s.json().catch(()=>null);return ha(t)}catch(s){return console.warn("Failed to load shared settings from server:",s),null}},tl=async()=>{if(typeof window>"u")return;const r=Qi(),s=t=>{Zr(t);const n=()=>Qr(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=Ht()?await qi():await hm();t&&s(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},fs=async r=>{if(typeof window>"u")return;if(Ht()){try{const t=await Mu(r);t&&(Zr(t),Qr(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&&(Zr(t),Qr(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&&(Zr(n),Qr(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},sl=async()=>{if(typeof window>"u")return;const r=Qi();try{const s=await pm();if(!s)return;const t=()=>fm(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)}},_o="Updating OpenCode configuration...";let ns=0,Is=_o;const co=new Set;function fn(){const r={isUpdating:ns>0,message:Is};co.forEach(s=>s(r))}function Es(r){ns+=1,ns===1?(Is=r||_o,fn()):r&&(Is=r,fn())}function qt(){ns!==0&&(ns-=1,ns===0&&(Is=_o,fn()))}function Jt(r){Is===r&&ns>0||(Is=r,ns>0&&fn())}function gm(r){return co.add(r),r({isUpdating:ns>0,message:Is}),()=>{co.delete(r)}}function ym(){return{isUpdating:ns>0,message:Is}}const xr="useAgentsStore",pn=r=>new Promise(s=>setTimeout(s,r)),xm=2e4,ga=300,ya=4,bm=800,wm=200,vm=2e3,or=It()(Bt(as((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=>{Es("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 m=i?.error||"Failed to create agent";throw new Error(m)}if(console.log("[AgentsStore] Agent created successfully"),i?.requiresReload??!0)return n=!0,await Qs({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadAgents();return d&&ys("agents",{source:xr}),d}catch(o){return console.error("[AgentsStore] Failed to create agent:",o),!1}finally{n||qt()}},updateAgent:async(t,n)=>{Es("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 f=c?.error||"Failed to update agent";throw new Error(f)}if(console.log("[AgentsStore] Agent updated successfully"),c?.requiresReload??!0)return o=!0,await Qs({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const m=await s().loadAgents();return m&&ys("agents",{source:xr}),m}catch(a){return console.error("[AgentsStore] Failed to update agent:",a),!1}finally{o||qt()}},deleteAgent:async t=>{Es("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 Qs({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadAgents();return c&&ys("agents",{source:xr}),s().selectedAgentName===t&&r({selectedAgentName:null}),c}catch(o){return console.error("Failed to delete agent:",o),!1}finally{n||qt()}},getAgentByName:t=>{const{agents:n}=s();return n.find(o=>o.name===t)}}),{name:"agents-store",storage:is(()=>Ut()),partialize:r=>({selectedAgentName:r.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=or);async function Sm(r){const s=typeof r=="number"&&r>0?Math.min(r,ga):0;s>0&&await pn(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<xm;){n+=1,Jt(`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<=ya&&a<1200?ga:Math.min(bm+Math.max(0,n-ya)*wm,vm);await pn(i)}throw o||new Error("OpenCode did not become ready in time")}async function Qs(r={}){const{message:s,delayMs:t}=r;try{Jt(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 Sm(t),Jt("Refreshing providers and agents…");const n=xt.getState(),o=or.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),ys("agents",{source:xr})}catch(n){console.error("[AgentsStore] Failed to refresh configuration after OpenCode restart:",n),Jt("OpenCode reload failed. Please retry refreshing configuration manually."),await pn(1500)}finally{qt()}}async function jm(r){await Qs(r)}async function km(r){Es("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 Qs({message:t.message,delayMs:t.reloadDelayMs}):await Qs(r)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),Jt("Failed to reload configuration. Please try again."),await pn(2e3),qt(),s}}let xa=null;xa||(xa=Ro(r=>{if(r.source!==xr&&cn(r,"agents")){const{loadAgents:s}=or.getState();s()}}));const br="useCommandsStore",uo=r=>new Promise(s=>setTimeout(s,r)),Nm=2e4,ba=300,wa=4,Cm=800,Mm=200,Am=2e3,ar=It()(Bt(as((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=>{Es("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 m=i?.error||"Failed to create command";throw new Error(m)}if(console.log("[CommandsStore] Command created successfully"),i?.requiresReload??!0)return n=!0,await Pn({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadCommands();return d&&ys("commands",{source:br}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||qt()}},updateCommand:async(t,n)=>{Es("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 f=c?.error||"Failed to update command";throw new Error(f)}if(console.log("[CommandsStore] Command updated successfully"),c?.requiresReload??!0)return o=!0,await Pn({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const m=await s().loadCommands();return m&&ys("commands",{source:br}),m}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||qt()}},deleteCommand:async t=>{Es("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 Pn({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadCommands();return c&&ys("commands",{source:br}),s().selectedCommandName===t&&r({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||qt()}},getCommandByName:t=>{const{commands:n}=s();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:is(()=>Ut()),partialize:r=>({selectedCommandName:r.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=ar);async function Dm(r){const s=typeof r=="number"&&r>0?Math.min(r,ba):0;s>0&&await uo(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Nm;){n+=1,Jt(`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<=wa&&a<1200?ba:Math.min(Cm+Math.max(0,n-wa)*Mm,Am);await uo(i)}throw o||new Error("OpenCode did not become ready in time")}async function Pn(r={}){const{message:s,delayMs:t}=r;try{Jt(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 Dm(t),Jt("Refreshing providers and commands…");const n=xt.getState(),o=ar.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),ys("commands",{source:br})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Jt("OpenCode reload failed. Please retry refreshing configuration manually."),await uo(1500)}finally{qt()}}let va=null;va||(va=Ro(r=>{if(r.source!==br&&cn(r,"commands")){const{loadCommands:s}=ar.getState();s()}}));const Em=3e4,Tm=40,Im=60,Fm=(r,s,t)=>{const n=r.trim(),o=s.trim().toLowerCase();return`${n}::${o}::${t}`},Bo=It()(Bt((r,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=Im){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=Fm(a,i,o),d=Date.now(),m=s().cache[c];if(m&&d-m.timestamp<Em)return m.files;const f=s().inFlight[c];if(f)return f;const u=Ae.searchFiles(i,{directory:a,limit:o}).then(p=>(r(h=>{const g={...h.cache,[c]:{files:p,timestamp:Date.now()}},x=h.cacheKeys.filter(S=>S!==c);for(x.push(c);x.length>Tm;){const S=x.shift();S&&delete g[S]}return{cache:g,cacheKeys:x}}),p)).finally(()=>{r(p=>{const h={...p.inFlight};return delete h[c],{inFlight:h}})});return r(p=>({inFlight:{...p.inFlight,[c]:u}})),u},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(f=>f.startsWith(o)?(delete i[f],!1):!0),d=Object.entries(a.inFlight).filter(([f])=>!f.startsWith(o)),m=Object.fromEntries(d);return{cache:i,cacheKeys:c,inFlight:m}})}}),{name:"file-search-store"}));var Pm={};let hs=null;const ts=Ut(),Sa=ts.getItem("lastDirectory"),Rm=typeof Sa=="string"&&Sa.length>0,Pr=(r,s)=>((s?.showOverlay??!0)&&Es("Switching project directory…"),Ae.setOpenCodeWorkingDirectory(r).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),Rr=(r,s,t)=>{const{showOverlay:n}=s,o=()=>{try{ye.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&&(Jt("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),qt()),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 jm({message:"Refreshing OpenCode configuration…"});try{await ar.getState().loadCommands();try{ys("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&&qt()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(Jt("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),qt())}finally{t?.(a),o()}})()},Lr=r=>{try{Bo.getState().invalidateDirectory(r)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},hn=()=>{if(typeof window<"u"){const s=ts.getItem("lastDirectory");if(s)return s;if(hs)return hs;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 hs=t,ts.setItem("homeDirectory",t),t;const n=ts.getItem("homeDirectory");if(n)return hs=n,n}const r=typeof process<"u"&&Pm?.HOME;return r||process?.cwd?.()||"/"},Lm=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},_m=r=>(hs=r,typeof window<"u"&&ts.setItem("homeDirectory",r),fs({homeDirectory:r}),r),rl=async()=>{const r=n=>{const o=Lm(n);return o?_m(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 Gi(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const s=hn(),t=r(s);return t||s},Ws=hn();Ws&&Ae.setDirectory(Ws);const Bm=!!(Ws&&Ws!=="/"),yt=It()(Bt((r,s)=>({currentDirectory:Ws,directoryHistory:[Ws],historyIndex:0,homeDirectory:Ws,hasPersistedDirectory:Rm,isHomeReady:Bm,isSwitchingDirectory:!1,setDirectory:(t,n)=>{console.log("[DirectoryStore] setDirectory called with path:",t);const o=n?.showOverlay??!0;Ae.setDirectory(t),Lr();const a=Pr(t,{showOverlay:o});console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),r(i=>{const c=[...i.directoryHistory.slice(0,i.historyIndex+1),t];return ts.setItem("lastDirectory",t),fs({lastDirectory:t}),{currentDirectory:t,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),Rr(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),Lr();const a=Pr(o);ts.setItem("lastDirectory",o),fs({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Rr(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),Lr();const a=Pr(o);ts.setItem("lastDirectory",o),fs({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Rr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=s(),o=hs||s().homeDirectory||hn();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=hs||hn();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=hs||s().homeDirectory||await rl();s().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=s(),o=t;hs=o;const a=n.homeDirectory!==o,i=ts.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 m=typeof o=="string"&&o!==""&&o!=="/",f={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:m};if(d&&(f.currentDirectory=o,f.directoryHistory=[o],f.historyIndex=0,f.isSwitchingDirectory=!0),r(()=>f),d&&m){Ae.setDirectory(o),Lr(),ts.setItem("lastDirectory",o),fs({lastDirectory:o});const u=Pr(o,{showOverlay:!1});Rr(u,{showOverlay:!1},()=>{r(p=>p.currentDirectory!==o?{}:p.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}fs({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&rl().then(r=>{yt.getState().synchronizeHomeDirectory(r)});const nl=Ut(),ol="oc.sessionSelectionByDirectory",ja=".openchamber",Om=()=>{try{const r=nl.getItem(ol);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 en=null;const Oo=()=>(en||(en=Om()),en),al=r=>{en=r;try{nl.setItem(ol,JSON.stringify(r))}catch{}},il=r=>{if(!r)return null;const t=Oo()[r];return typeof t=="string"?t:null},Ls=(r,s)=>{if(!r)return;const t={...Oo()};s?t[r]=s:delete t[r],al(t)},$m=(r,s)=>{if(!r)return;const t=il(r);if(!t)return;if(!new Set(s).has(t)){const o={...Oo()};delete o[r],al(o)}},ka=async(r,s)=>{const t=r.status??await Jr(r.path).catch(()=>{});await um({projectDirectory:r.projectDirectory,path:r.path,branch:r.branch,force:!!t?.isDirty,deleteRemote:!!s?.deleteRemoteBranch,remote:s?.remoteName})},Mt=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},Ks=(r,s)=>{const t=r.find(n=>n.id===s);return t?Mt(t.directory??null):null},zm=async(r,s,t)=>{const n=Mt(s);if(!n||r.length===0)return null;const o=r.map(m=>({id:m.id,directory:Mt(m.directory)})).filter(m=>!!m.directory);if(o.length===0)return null;let a;try{a=await un(n)}catch(m){return console.debug("Failed to hydrate worktree metadata from git worktree list:",m),null}if(!Array.isArray(a)||a.length===0){let m=!1;const f=new Map(t);return o.forEach(({id:u})=>{f.delete(u)&&(m=!0)}),m?f:null}const i=new Map;a.forEach(m=>{const f=mn(n,m),u=Mt(f.path)??f.path;u!==n&&i.set(u,f)});let c=!1;const d=new Map(t);return o.forEach(({id:m,directory:f})=>{const u=i.get(f);if(!u){d.delete(m)&&(c=!0);return}const p=d.get(m);(!p||p.path!==u.path||p.branch!==u.branch||p.label!==u.label)&&(d.set(m,u),c=!0)}),c?d:null},Xe=It()(Bt(as((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=yt.getState().currentDirectory??Ae.getDirectory()??null,o=Ae.getApiClient(),a=async M=>{const N=await o.session.list({query:M?{directory:M}:void 0});return Array.isArray(N.data)?N.data:[]},i=Mt(n),c=i?await Lo(i).catch(()=>!1):!1,d=await a(i||null),m=[];let f=[];if(n&&c&&i){const M=`${i}/${ja}`;try{const N=new Set;M&&(await Ae.listLocalDirectory(M)).filter(I=>I.isDirectory).forEach(I=>{const E=/^([A-Za-z]:)?\//.test(I.path)?I.path:`${M}/${I.name}`;N.add(Mt(E)??E)});const A=await un(i);Array.isArray(A)&&(f=A.map(D=>mn(i,D)).filter(D=>D.path.includes(`/${ja}/`)),f.forEach(D=>N.add(D.path))),N.size>0&&(await Promise.allSettled(Array.from(N).map(I=>a(I)))).forEach(I=>{I.status==="fulfilled"&&Array.isArray(I.value)&&m.push(...I.value)})}catch{f=[]}}const u=new Set;i&&u.add(i),f.forEach(M=>{const N=Mt(M.path);N&&u.add(N)});const p=[...d,...m].filter(M=>{const N=M.directory??i??null,A=Mt(N);return A?u.has(A):!1}),h=s(),g=h.lastLoadedDirectory??null,x=n!==g;let S=[...p],v=h.currentSessionId;const k=M=>{S=[M,...S.filter(N=>N.id!==M.id)]};if(x)v=S.length>0?S[0].id:null;else if(v){if(!S.some(N=>N.id===v)){const N=h.sessions.find(A=>A.id===v);if(N)k(N);else try{const A=await Ae.getSession(v);k(A)}catch{v=S.length>0?S[0].id:null}}}else v=S.length>0?S[0].id:null;const b=S.reduce((M,N)=>(M.some(A=>A.id===N.id)||M.push(N),M),[]);v&&!b.some(M=>M.id===v)&&(v=b.length>0?b[0].id:null);const w=new Set(b.map(M=>M.id));if(n){$m(n,w);const M=il(n);M&&w.has(M)&&(v=M)}let j=null;try{j=await zm(b,n,h.worktreeMetadata)}catch(M){console.debug("Failed to refresh worktree metadata during session load:",M)}const y=(()=>{const M=j??h.worktreeMetadata;if(!x||!i)return M;const N=new Map;return M.forEach((A,D)=>{Mt(A.projectDirectory)===i&&N.set(D,A)}),N})(),C=(()=>{if(!v)return i??null;const M=y.get(v)?.path;if(M)return Mt(M)??M;const N=Ks(b,v);return N||(i??null)})();try{Ae.setDirectory(C??void 0)}catch(M){console.warn("Failed to sync OpenCode directory after session load:",M)}r({sessions:b,currentSessionId:v,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:y,availableWorktrees:f}),Ls(C??n,v)}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=yt.getState(),i=Mt(a.currentDirectory),c=Mt(n??Ae.getDirectory()??i),d=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=s(),f=new Set(m.sessions.map(g=>g.id)),u={id:d,title:t||"New session",parentID:o??void 0,directory:c??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(r(g=>({sessions:[u,...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 p=g=>{r(x=>({sessions:x.sessions.map(v=>v.id===d?g:v),currentSessionId:g.id,webUICreatedSessions:new Set([...Array.from(x.webUICreatedSessions).filter(v=>v!==d),g.id])})),Ls(c??null,g.id)},h=async()=>{const g=Ae.getApiClient(),x=20;for(let S=0;S<x;S+=1){try{const v=await g.session.list({query:c?{directory:c}:void 0}),b=(Array.isArray(v.data)?v.data:[]).find(w=>!(f.has(w.id)||t&&w.title&&w.title!==t));if(b)return b}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,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(S){console.warn("Direct session create failed or timed out, falling back to polling:",S)}return x||(x=await h()),x?(p(x),x):(r(S=>({sessions:S.sessions.filter(v=>v.id!==d),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(S.webUICreatedSessions).filter(v=>v!==d)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return r(x=>({sessions:x.sessions.filter(S=>S.id!==d),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(x.webUICreatedSessions).filter(S=>S!==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=Ks(s().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await ka(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Ae.deleteSession(t);if(!(i?await Ae.withDirectory(i,d):await d()))return r(p=>{const h={isLoading:!1,error:"Failed to delete session"};if(c){const g=new Map(p.worktreeMetadata);g.delete(t),h.worktreeMetadata=g}return h}),!1;let f=null;r(p=>{const h=p.sessions.filter(S=>S.id!==t);f=p.currentSessionId===t?null:p.currentSessionId;const g=new Map(p.worktreeMetadata);g.delete(t);const x=n?.archiveWorktree&&o?p.availableWorktrees.filter(S=>Mt(S.path)!==Mt(o.path)):p.availableWorktrees;return{sessions:h,currentSessionId:f,isLoading:!1,worktreeMetadata:g,availableWorktrees:x}});const u=i??Ae.getDirectory()??null;return Ls(u,f),!0}catch(d){const m=d instanceof Error?d.message:"Failed to delete session";return r(c?f=>{const u=new Map(f.worktreeMetadata);return u.delete(t),{worktreeMetadata:u,error:m,isLoading:!1}}:{error:m,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=[],m=new Set;for(const x of o)try{const S=s().worktreeMetadata.get(x),v=Ks(s().sessions,x),k=S?.path??v;S&&n?.archiveWorktree&&!m.has(S.path)&&(await ka(S,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c.add(x),d.push({path:S.path,projectDirectory:S.projectDirectory}),m.add(S.path));const b=()=>Ae.deleteSession(x);(k?await Ae.withDirectory(k,b):await b())?(a.push(x),S?.path&&!d.some(j=>j.path===S.path)&&d.push({path:S.path,projectDirectory:S.projectDirectory})):i.push(x)}catch{i.push(x)}const f=yt.getState();d.forEach(({path:x,projectDirectory:S})=>{f.currentDirectory===x&&f.setDirectory(S,{showOverlay:!1})});const u=new Set(a),p=i.length>0?i.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let h=null;r(x=>{const S=x.sessions.filter(w=>!u.has(w.id));x.currentSessionId&&u.has(x.currentSessionId)?h=S.length>0?S[0].id:null:h=x.currentSessionId;const v=new Map(x.worktreeMetadata);for(const w of u)v.delete(w);for(const w of c)v.delete(w);const k=new Set(d.map(w=>Mt(w.path)).filter(w=>!!w)),b=k.size>0?x.availableWorktrees.filter(w=>!k.has(Mt(w.path)??w.path)):x.availableWorktrees;return{sessions:S,currentSessionId:h,isLoading:!1,worktreeMetadata:v,availableWorktrees:b,error:p}});const g=Ae.getDirectory()??null;return Ls(g,h),{deletedIds:a,failedIds:i}},updateSessionTitle:async(t,n)=>{try{const o=Ks(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(m=>({sessions:m.sessions.map(f=>f.id===t?d:f)}))}catch(o){r({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=Ks(s().sessions,t),o=Ae.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const m=n??Ae.getDirectory();return o.session.share({path:{id:t},query:m?{directory:m}:void 0})},d=i?await Ae.withDirectory(i,c):await c();return d.data?(r(m=>({sessions:m.sessions.map(f=>f.id===t?d.data:f)})),d.data):null}catch(n){return r({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=Ks(s().sessions,t),o=Ae.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const m=n??Ae.getDirectory();return o.session.unshare({path:{id:t},query:m?{directory:m}:void 0})},d=i?await Ae.withDirectory(i,c):await c();return d.data?(r(m=>({sessions:m.sessions.map(f=>f.id===t?d.data:f)})),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;Ls(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,m=n.share===void 0?i.share:n.share||void 0,f={...i,...n,time:c,summary:d,share:m},u=f.title!==i.title||f.parentID!==i.parentID||f.directory!==i.directory||f.version!==i.version||f.projectID!==i.projectID||JSON.stringify(f.time)!==JSON.stringify(i.time)||JSON.stringify(f.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(f.share??null)!==JSON.stringify(i.share??null),p=[...o.sessions];return p[a]=u?f:i,u?{sessions:p}: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(m=>m.id===t);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(r(m=>{const f=[...m.sessions],u={...f[a]};return d!==void 0?u.directory=d:delete u.directory,f[a]=u,{sessions:f}}),c&&Ls(c,null),n&&Ls(n,t))},updateSession:t=>{r(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:is(()=>Ut()),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(!(m=>typeof m=="object"&&m!==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"})),ll="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.",Rn=r=>typeof r=="string"&&r.trim()===ll.trim(),Ln=(r,s)=>{const t=Date.now(),n=r.get(s),o=new Map(r);return o.set(s,{phase:"streaming",startedAt:n?.startedAt??t,lastUpdateAt:t}),o},cr=(r,s)=>{const t=Array.from(s);if(!t.some(a=>r.has(a)))return r;const o=new Map(r);return t.forEach(a=>{o.delete(a)}),o},Na=new Map,cl=r=>{const s=Na.get(r);s&&(clearTimeout(s),Na.delete(r))},_s=r=>{for(const s of r)cl(s)},Dr=r=>{if(!r)return"";if(typeof r=="string")return r;if(Array.isArray(r))return r.map(s=>Dr(s)).join("");if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(Array.isArray(r.content))return r.content.map(s=>Dr(s)).join("")}return""},wr=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:wr(n)).join("");const t=Dr(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||Dr(o.delta)||""}return""}).join(""):"")},dr=(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=Dr(r.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},Ca=10*1024*1024,Hm=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"}},Wm=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"}},Um=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},Vm=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},As=It()(Bt(as((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=Ca;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=Wm(t);!i.some(g=>c.startsWith(g)||c===g||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const m=new FileReader,f=await new Promise((g,x)=>{m.onload=()=>g(m.result),m.onerror=x,m.readAsDataURL(t)}),u=f.startsWith("data:")?f.replace(/^data:[^;]*/,`data:${c}`):f,p=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:u,mimeType:c,filename:p(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(v=>v.serverPath===t&&v.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o,d,m;if(!c)try{const v=Ae.getApiClient(),k=t.lastIndexOf("/"),b=k>0?t.substring(0,k):"/",w=k>0?t.substring(k+1):t,j=await v.file.read({query:{path:w,directory:b}});j.data&&"content"in j.data?(c=j.data.content,d=j.data.encoding??void 0,m=j.data.mimeType??void 0):c=""}catch(v){console.error("Failed to read server file:",v),c=`[File: ${n}]`}const f=m||Hm(n),u=f&&f.trim().length>0?f:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const k=new TextEncoder().encode(c||"");return Vm(k)})(),h=d==="base64"?Um(p):new TextEncoder().encode(c||"").length;if(h>Ca)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const g=new File([],n,{type:u}),x=`data:${u};base64,${p}`,S={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:g,dataUrl:x,mimeType:u,filename:n,size:h,source:"server",serverPath:t};r(v=>({attachedFiles:[...v.attachedFiles,S]}))},removeAttachedFile:t=>{r(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{r({attachedFiles:[]})}}),{name:"file-store",storage:is(()=>Ut()),partialize:r=>({attachedFiles:r.attachedFiles})}),{name:"file-store"}));let _n=[],Bn=null;const Gm=50,qm=3e4,Bs=new Map,_r=new Map,Ys=new Map,Km=10,gn=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<Km?null:n},Ma=(r,s)=>{const t=gn(r),n=gn(s);return!t||!n||t.length!==n.length?!0:t>n},Ym=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Br=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),Aa=r=>Array.isArray(r)?r.some(s=>s?.type==="step-finish"&&s?.reason==="stop"):!1,Da=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??""}`}}},Ea=new Set,Ta=(r=[],s=[])=>{if(!s.length)return[...r];const t=[...r],n=new Set(r.map(Da).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=Da(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},Xm=(r,s)=>{let t=s,n=s?gn(s):null;for(const o of r){const a=o?.info?.id,i=gn(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Qt=(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},Xs=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return o.set(s,t),o},Or=(r,s)=>{const t=new Map(r);let n=!1;for(const o of s)t.delete(o)&&(n=!0);return n?t:r},Jm=(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},Ia=(r,s,t)=>r.streamingMessageIds.get(s)===t?!0:r.messageSessionIndex.get(t)===s&&r.messageStreamStates.has(t),Zm=async r=>{if(r)try{const s=Xe.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}},On=async(r,s)=>{const t=await Zm(r);return t?Ae.withDirectory(t,s):s()},st=It()(Bt(as((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=Dt.VIEWPORT_MESSAGES)=>{const o=await On(t,()=>Ae.getSessionMessages(t)),a=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=(a?o.filter(d=>{const m=d?.info?.id;return m?Ma(m,a):!0}):o).slice(-n);r(d=>{const m=new Map(d.messages),f=d.messages.get(t)||[],u=new Map(f.filter(C=>typeof C.info?.id=="string").map(C=>[C.info.id,C])),h=c.map(C=>{const M={...C.info,clientRole:C.info?.clientRole??C.info.role,userMessageMarker:C.info.role==="user"?!0:C.info?.userMessageMarker},N=(Array.isArray(C.parts)?C.parts:[]).map(D=>{if(D?.type==="text"){const I=D.text??D.content??"";if(Rn(I))return{...D,synthetic:!0}}return D}),A=M?.id?u.get(M.id):void 0;if(A&&A.info.role==="assistant"){const D=Array.isArray(A.parts)?A.parts:[],I=Br(D),z=Br(N);if(Aa(D)&&I>z){const $=Ta(D,N);return{...C,info:M,parts:$}}}return{...C,info:M,parts:N}}),g=new Set(f.map(C=>C.info.id)),x=new Set(h.map(C=>C.info.id)),S=[];g.forEach(C=>{x.has(C)||S.push(C)}),m.set(t,h);const v=new Map(d.sessionMemoryState),k=d.sessionMemoryState.get(t);v.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 b={messages:m,sessionMemoryState:v};_s(S);const w=cr(d.messageStreamStates,S);if(w!==d.messageStreamStates&&(b.messageStreamStates=w),S.length>0){const C=d.streamingMessageIds.get(t);C&&S.includes(C)&&(b.streamingMessageIds=Qt(b.streamingMessageIds??d.streamingMessageIds,t,null))}if(S.length>0){const C=Or(b.messageSessionIndex??d.messageSessionIndex,S);C!==(b.messageSessionIndex??d.messageSessionIndex)&&(b.messageSessionIndex=C)}if(S.length>0){const C=new Map(d.pendingAssistantParts);let M=!1;S.forEach(N=>{C.delete(N)&&(M=!0)}),M&&(b.pendingAssistantParts=C)}const j=b.messageSessionIndex??d.messageSessionIndex;let y=j;return h.forEach(C=>{const M=C?.info?.id;typeof M=="string"&&M.length>0&&(y=Xs(y,M,t))}),y!==j&&(b.messageSessionIndex=y),b})},sendMessage:async(t,n,o,a,i,c,d)=>{if(!i)throw new Error("No session selected");const m=i;s().sessionAbortFlags.has(m)&&r(f=>{const u=new Map(f.sessionAbortFlags);return u.delete(m),{sessionAbortFlags:u}}),await On(m,async()=>{try{let f=t;if(t.startsWith("/")){const p=t.indexOf(" "),h=p===-1?t.substring(1):t.substring(1,p),g=p===-1?"":t.substring(p+1).trim(),x=Ae.getApiClient(),S=Ae.getDirectory();if(h==="init"){const v=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await x.session.init({path:{id:m},body:{messageID:v,providerID:n,modelID:o},query:S?{directory:S}:void 0});return}if(h==="summarize"){await x.session.summarize({path:{id:m},body:{providerID:n,modelID:o},query:S?{directory:S}:void 0});return}try{const v=await Ae.getCommandDetails(h);v?.template?f=v.template.replace(/\$ARGUMENTS/g,g):f=t}catch(v){console.error("Command template resolution failed:",v),f=t}}r({lastUsedProvider:{providerID:n,modelID:o}}),r(p=>{const h=p.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=Ys.get(m);g&&(clearTimeout(g),Ys.delete(m));const x=new Map(p.sessionMemoryState);return x.set(m,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:x}});try{const p=new AbortController;r(g=>{const x=new Map(g.abortControllers);return x.set(m,p),{abortControllers:x}});const h=(c??[]).map(g=>({type:"file",mime:g.mimeType,filename:g.filename,url:g.dataUrl}));if(await Ae.sendMessage({id:m,providerID:n,modelID:o,text:f,agent:a,files:h.length>0?h:void 0,agentMentions:d?[{name:d}]:void 0}),h.length>0)try{As.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(m),{abortControllers:x}})}catch(p){let h="Network error while sending message. The message may still be processing.";if(p.name==="AbortError")h="Request timed out. The message may still be processing.";else if(p.message?.includes("504")||p.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(m),{abortControllers:x}});return}else p.message&&(h=p.message);throw r(g=>{const x=new Map(g.abortControllers);return x.delete(m),{abortControllers:x}}),new Error(h)}}catch(f){let u="Network error while sending message. The message may still be processing.";throw f.name==="AbortError"?u="Request timed out. The message may still be processing.":f.response?.status===401?u="Session not found or unauthorized. Please refresh the page.":f.response?.status===502?u="OpenCode is restarting. Please wait a moment and try again.":f.message?.includes("504")||f.message?.includes("Gateway")?u="Gateway timeout - your message is being processed. Please wait for response.":f.message&&(u=f.message),r(p=>{const h=new Map(p.abortControllers);return h.delete(m),{abortControllers:h}}),new Error(u)}})},abortCurrentOperation:async t=>{if(!t)return;const n=s(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=Jm(n,t);if(c.size===0){const m=t?a.get(t)??[]:[];let f=null;for(let u=m.length-1;u>=0;u-=1){const p=m[u];if(!p||p.info.role!=="assistant")continue;if(f||(f=p.info.id),(p.parts??[]).some(g=>g.type==="reasoning"||g.type==="tool"||g.type==="step-start")){c.add(p.info.id);break}}c.size===0&&f&&c.add(f)}for(const m of c){const f=Bs.get(m);f&&(clearTimeout(f),Bs.delete(m),_r.delete(m))}c.size>0&&_s(c);const d=Date.now();r(m=>{const f=cr(m.messageStreamStates,c),u=m.messages.get(t)??[];let p=!1,h=m.messages;if(u.length>0&&c.size>0){const v=u.map(k=>{if(!c.has(k.info.id)&&c.size>0)return k;const b=(k.parts??[]).map(w=>{if(w.type==="reasoning"){const j=w,y={...j.time??{}};return typeof y.end!="number"&&(y.end=d),{...j,time:y}}if(w.type==="tool"){const j=w,y={...j.state??{}};return(y.status==="running"||y.status==="pending")&&(y.status="aborted"),{...j,state:y}}return w.type==="step-start"?{...w,type:"step-finish",aborted:!0}:w});return p=!0,{...k,info:{...k.info,abortedAt:d,streaming:!1,status:"aborted"},parts:b}});p&&(h=new Map(m.messages),h.set(t,v))}const g=m.sessionMemoryState.get(t);let x=m.sessionMemoryState;if(g){const v=new Map(m.sessionMemoryState);v.set(t,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),x=v}const S=new Map(m.sessionAbortFlags);return S.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:f,sessionMemoryState:x,sessionAbortFlags:S,abortControllers:(()=>{const v=new Map(m.abortControllers);return v.delete(t),v})(),streamingMessageIds:Qt(m.streamingMessageIds,t,null),...p?{messages:h}:{}}}),Ae.abortSession(t).catch(m=>{console.warn("Abort request failed:",m)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=s();if(Ea.has(n))return;const d=c.messages.get(t)||[],m=d.find(h=>h.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",u=s().sessionMemoryState.get(t);if(u?.streamStartTime&&Date.now()-u.streamStartTime>Dt.ZOMBIE_TIMEOUT){u.isZombie||r(g=>{const x=new Map(g.sessionMemoryState);return x.set(t,{...u,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)||[]],S={},v=Xs(h.messageSessionIndex,n,t);v!==h.messageSessionIndex&&(S.messageSessionIndex=v);const k=N=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(t)))return N;const D=new Map(h.sessionAbortFlags);return D.delete(t),{...N,sessionAbortFlags:D}},b=N=>{const A=N||"",D=_r.get(n);if(A&&D===A){const E=s();if(Ia(E,t,n)){const $=Bs.get(n);$&&(clearTimeout($),Bs.delete(n)),setTimeout(()=>{const V=s();typeof V.forceCompleteMessage=="function"&&V.forceCompleteMessage(t,n,"timeout"),V.completeStreamingMessage(t,n)},100)}}_r.set(n,A);const I=Bs.get(n);I&&clearTimeout(I);const z=setTimeout(()=>{const E=s();typeof E.forceCompleteMessage=="function"&&E.forceCompleteMessage(t,n,"timeout"),Ia(E,t,n)&&E.completeStreamingMessage(t,n),Bs.delete(n),_r.delete(n)},8e3);Bs.set(n,z)},w=t!==i,j=h.sessionMemoryState.get(t);if(w&&j?.isStreaming){x.length>=Dt.BACKGROUND_STREAMING_BUFFER&&x.shift();const N=new Map(h.sessionMemoryState);N.set(t,{...j,backgroundMessageCount:(j.backgroundMessageCount||0)+1}),h.sessionMemoryState=N}if(f==="assistant"){const N=h.sessionMemoryState.get(t);if(N){const A=Date.now(),D=new Map(h.sessionMemoryState);D.set(t,{...N,isStreaming:!0,streamStartTime:N.streamStartTime??A,lastAccessedAt:A,isZombie:!1}),h.sessionMemoryState=D}}const y=wr(o);if(Rn(y)&&(o.synthetic=!0),Ym()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:y.length,snapshotParts:d.length})}catch{}const C=S.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const N=Qt(C,t,n);N!==C&&(S.streamingMessageIds=N,window.__messageTracker?.(n,"streamingId_set_latest"))}const M=x.findIndex(N=>N.info.id===n);if(M!==-1&&f==="user"){const N=x[M],A=N.parts.findIndex($=>$.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const D=dr(o,A!==-1?N.parts[A]:void 0);window.__messageTracker?.(n,`user_part_type:${D.type||"unknown"}`);const I={...N};A!==-1?I.parts=I.parts.map(($,V)=>V===A?D:$):I.parts=[...I.parts,D];const z=[...x];z[M]=I;const E=new Map(h.messages);return E.set(t,z),k({messages:E})}if(f==="assistant"&&M!==-1){const N=x[M],A=N.parts.findIndex(V=>V.id===o.id),D=dr(o,A!==-1?N.parts[A]:void 0);window.__messageTracker?.(n,`part_type:${D.type||"unknown"}`);const I={...N};A!==-1?I.parts=I.parts.map((V,Y)=>Y===A?D:V):I.parts=[...I.parts,D];const z=[...x];z[M]=I;const E=new Map(h.messages);E.set(t,z),S.messageStreamStates=Ln(h.messageStreamStates,n);const $=Qt(S.streamingMessageIds??h.streamingMessageIds,t,n);return $!==(S.streamingMessageIds??h.streamingMessageIds)&&(S.streamingMessageIds=$,window.__messageTracker?.(n,"streamingId_set")),D.type==="text"?b(D.text||""):b(""),k({messages:E,...S})}if(M===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const L=dr(o);window.__messageTracker?.(n,`new_user_part_type:${L.type||"unknown"}`);const _={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,time:{created:Date.now()}},parts:[L]},W=[...x,_];W.sort((je,Me)=>{const $e=je.info?.time?.created||0,he=Me.info?.time?.created||0;return $e-he});const ae=new Map(h.messages);return ae.set(t,W),k({messages:ae})}if(o?.type==="text"){const L=wr(o).trim();if(L.length>0){const _=[...x].reverse().find(W=>W.info.role==="user");if(_){const W=_.parts.map(ae=>wr(ae)).join("").trim();if(W.length>0&&W===L)return Ea.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const N=dr(o);window.__messageTracker?.(n,`part_type:${N.type||"unknown"}`),N.type==="text"?b(N.text||""):b("");const A=h.pendingAssistantParts.get(n),D=A?[...A.parts]:[],I=D.findIndex(L=>L.id===N.id);I!==-1?D[I]=N:D.push(N);const z=new Map(h.pendingAssistantParts);z.set(n,{sessionId:t,parts:D});const $={info:{id:n,sessionID:t,role:f,clientRole:f,providerID:h.lastUsedProvider?.providerID||"",modelID:h.lastUsedProvider?.modelID||"",time:{created:Date.now()},animationSettled:f==="assistant"?!1:void 0,streaming:f==="assistant"?!0:void 0},parts:D},V=[...x,$],Y=new Map(h.messages);if(Y.set(t,V),f==="assistant"){S.messageStreamStates=Ln(h.messageStreamStates,n);const L=Qt(S.streamingMessageIds??h.streamingMessageIds,t,n);L!==(S.streamingMessageIds??h.streamingMessageIds)&&(S.streamingMessageIds=L,window.__messageTracker?.(n,"streamingId_set"))}return k({messages:Y,pendingAssistantParts:z,...S})}else{const N=x[M],A=N.parts.findIndex($=>$.id===o.id),D=dr(o,A!==-1?N.parts[A]:void 0);window.__messageTracker?.(n,`part_type:${D.type||"unknown"}`);const I={...N};A!==-1?I.parts=I.parts.map(($,V)=>V===A?D:$):I.parts=[...I.parts,D];const z=[...x];z[M]=I;const E=new Map(h.messages);if(E.set(t,z),I.info.role==="assistant"){S.messageStreamStates=Ln(h.messageStreamStates,n);const $=Qt(S.streamingMessageIds??h.streamingMessageIds,t,n);$!==(S.streamingMessageIds??h.streamingMessageIds)&&(S.streamingMessageIds=$,window.__messageTracker?.(n,"streamingId_set"))}return D.type==="text"?b(D.text||""):b(""),k({messages:E,...S})}}),o?.type==="step-finish"&&f!=="user"&&setTimeout(()=>{s().completeStreamingMessage(t,n)},0)},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){s()._addStreamingPartImmediate(t,n,o,a,i);return}_n.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),Bn||(Bn=setTimeout(()=>{const c=[..._n];_n=[],Bn=null;const d=s();for(const m of c)d._addStreamingPartImmediate(m.sessionId,m.messageId,m.part,m.role,m.currentSessionId)},Gm))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(m=>m.info.id===n))return c;return null};r(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],m=d.findIndex(j=>j.info.id===n);if(m===-1)return i;const f=d[m];if(!f)return i;const u=Date.now(),p=f.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let g=!1;const x={...p};h||(x.time={...p.time??{},completed:u},g=!0),x.status!=="completed"&&(x.status="completed",g=!0),x.streaming&&(x.streaming=!1,g=!0);let S=!1;const v=f.parts.map(j=>{if(!j)return j;if(j.type==="tool"){const y=j.state;if(!y)return j;const C=y.status,M=C==="running"||C==="pending"||C==="started",N=!y.time||typeof y.time?.end!="number";if(M||N){const A={...y};return M&&(A.status="completed"),N&&(A.time={...y.time??{},end:u}),S=!0,{...j,state:A}}return j}if(j.type==="reasoning"){const y=j.time;return!y||typeof y.end!="number"?(S=!0,{...j,time:{...y??{},end:u}}):j}if(j.type==="text"){const y=j.time;return y&&typeof y.end!="number"?(S=!0,{...j,time:{...y,end:u}}):j}return j});if(!g&&!S)return i;window.__messageTracker?.(n,`force_complete:${o}`);const k={...f,info:x,parts:S?v:f.parts},b=[...d];b[m]=k;const w=new Map(i.messages);return w.set(c,b),{messages:w}})},markMessageStreamSettled:t=>{r(n=>{cl(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,m)=>{if(i)return;const f=d.findIndex(x=>x.info.id===t);if(f===-1)return;const u=d[f];if(u.info?.animationSettled)return;const p={...u,info:{...u.info,animationSettled:!0}},h=[...d];h[f]=p;const g=new Map(n.messages);g.set(m,h),a=g,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),_s([t])},updateMessageInfo:(t,n,o)=>{r(a=>{const c=[...a.messages.get(t)??[]],d=c.findIndex(j=>j.info.id===n),m=a.pendingAssistantParts.get(n),f=(j=[],y=[])=>{if(!y.length)return j;const C=[...j];return y.forEach(M=>{const N=C.findIndex(A=>A.id===M.id);N===-1?C.push(M):C[N]=M}),C},u=j=>{if(!j)return j;const y=j.clientRole??j.role,C=y==="user"?!0:j.userMessageMarker;return{...j,clientRole:y,...C?{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 z=c[0]?.info,E=typeof z?.time?.created=="number"?z.time.created:null,$=typeof z?.id=="string"?z.id:null,V=o,Y=typeof V?.time?.created=="number"?V.time.created:null,L=typeof V?.id=="string"?V.id:n;let _=!1;if(Y!==null&&E!==null&&(_=Y<E),!_&&L&&$&&(_=L.localeCompare($)<0),_)return window.__messageTracker?.(n,"skipped_evicted_message_update"),a}const j=u(o);if(j&&j.role==="user"){const I=m?.parts??[],z={info:{...j,userMessageMarker:!0,clientRole:"user"},parts:I.length>0?[...I]:[]},E=new Map(a.messages),$=[...c,z];$.sort((L,_)=>{const W=L.info?.time?.created||0,ae=_.info?.time?.created||0;return W-ae}),E.set(t,$);const V={messages:E},Y=Xs(V.messageSessionIndex??a.messageSessionIndex,n,t);if(Y!==(V.messageSessionIndex??a.messageSessionIndex)&&(V.messageSessionIndex=Y),m){const L=new Map(a.pendingAssistantParts);L.delete(n),V.pendingAssistantParts=L}return V}if(!j||j.role!=="assistant")return a;const y=m?.parts??[],C={info:{...j,animationSettled:j?.animationSettled??!1},parts:y.length>0?[...y]:[]},M=new Map(a.messages),N=[...c,C];M.set(t,N);const A={messages:M},D=Xs(A.messageSessionIndex??a.messageSessionIndex,n,t);if(D!==(A.messageSessionIndex??a.messageSessionIndex)&&(A.messageSessionIndex=D),m){const I=new Map(a.pendingAssistantParts);I.delete(n),A.pendingAssistantParts=I}return A}const p=c[d],h=p.info;if(h.userMessageMarker===!0||h.clientRole==="user"||h.role==="user"){const j={...p.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:h.providerID||void 0,modelID:h.modelID||void 0},y={...p,info:j},C=new Map(a.messages),M=[...c];return M[d]=y,C.set(t,M),{messages:C}}const x={...p.info,...o};o.role&&o.role!==p.info.role&&(x.role=p.info.role),x.clientRole=x.clientRole??p.info.clientRole??p.info.role,x.clientRole==="user"&&(x.userMessageMarker=!0);const S=m?.parts?f(p.parts,m.parts):p.parts,v={...p,info:x,parts:S},k=new Map(a.messages),b=[...c];b[d]=v,k.set(t,b);const w={messages:k};if(m){const j=new Map(a.pendingAssistantParts);j.delete(n),w.pendingAssistantParts=j}return w})},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=Qt(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 m=new Map(d.pendingAssistantParts);return m.delete(n),{pendingAssistantParts:m}}),_s([n]);let c=!1;if(r(d=>{const m=d.sessionMemoryState.get(t);if(!m||!m.isStreaming)return d;const f=new Map(d.sessionMemoryState),u=Date.now(),p={...m,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:u,streamingCooldownUntil:u+2e3};return f.set(t,p),c=!0,{sessionMemoryState:f}}),c){const d=Ys.get(t);d&&(clearTimeout(d),Ys.delete(t));const m=setTimeout(()=>{r(f=>{const u=f.sessionMemoryState.get(t);if(!u||u.isStreaming)return f;const p=new Map(f.sessionMemoryState),{streamingCooldownUntil:h,...g}=u;return p.set(t,g),{sessionMemoryState:p}}),Ys.delete(t)},2e3);Ys.set(t,m)}},syncMessages:(t,n)=>{const o=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,a=o?n.filter(i=>{const c=i?.info?.id;return c?Ma(c,o):!0}):n;r(i=>{const c=new Map(i.messages),d=i.messages.get(t)||[],m=new Map(d.filter(b=>typeof b.info?.id=="string").map(b=>[b.info.id,b])),u=a.map(b=>{const w={...b.info,clientRole:b.info?.clientRole??b.info.role,userMessageMarker:b.info.role==="user"?!0:b.info?.userMessageMarker,animationSettled:b.info.role==="assistant"?b.info?.animationSettled??!0:b.info?.animationSettled},j=(Array.isArray(b.parts)?b.parts:[]).map(M=>{if(M?.type==="text"){const N=M.text??M.content??"";if(Rn(N))return{...M,synthetic:!0}}return M}),y=typeof w?.id=="string"?w.id:void 0,C=y?m.get(y):void 0;if(C&&C.info.role==="assistant"){const M=Array.isArray(C.parts)?C.parts:[],N=Br(M),A=Br(j);if(Aa(M)&&N>A){const I=Ta(M,j);return{...b,info:w,parts:I}}}return{...b,info:w,parts:j}}),p=new Set(d.map(b=>b.info.id)),h=new Set(u.map(b=>b.info.id)),g=[];p.forEach(b=>{h.has(b)||g.push(b)}),c.set(t,u);const x={messages:c,isSyncing:!0};_s(g);const S=cr(i.messageStreamStates,g);if(S!==i.messageStreamStates&&(x.messageStreamStates=S),g.length>0){const b=i.streamingMessageIds.get(t);b&&g.includes(b)&&(x.streamingMessageIds=Qt(x.streamingMessageIds??i.streamingMessageIds,t,null))}if(g.length>0){const b=Or(x.messageSessionIndex??i.messageSessionIndex,g);b!==(x.messageSessionIndex??i.messageSessionIndex)&&(x.messageSessionIndex=b)}if(g.length>0){const b=new Map(i.pendingAssistantParts);let w=!1;g.forEach(j=>{b.delete(j)&&(w=!0)}),w&&(x.pendingAssistantParts=b)}const v=x.messageSessionIndex??i.messageSessionIndex;let k=v;return u.forEach(b=>{const w=b?.info?.id;typeof w=="string"&&w.length>0&&(k=Xs(k,w,t))}),k!==v&&(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+qm;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=Dt.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 m=Math.max(0,d-Math.floor(n/2));const f=Math.min(i.length,m+n);f===i.length&&f-m<n&&(m=Math.max(0,f-n));const u=i.slice(m,f),p=i.slice(0,m),h=new Set(u.map(x=>x.info.id)),g=i.filter(x=>!h.has(x.info.id)).map(x=>x.info.id);r(x=>{const S=new Map(x.messages);S.set(t,u);const v=new Map(x.sessionMemoryState),k={...c,viewportAnchor:d-m,trimmedHeadMaxId:Xm(p,c.trimmedHeadMaxId)};v.set(t,k);const b={messages:S,sessionMemoryState:v};_s(g);const w=cr(x.messageStreamStates,g);if(w!==x.messageStreamStates&&(b.messageStreamStates=w),g.length>0){const C=x.streamingMessageIds.get(t);C&&g.includes(C)&&(b.streamingMessageIds=Qt(b.streamingMessageIds??x.streamingMessageIds,t,null))}if(g.length>0){const C=Or(b.messageSessionIndex??x.messageSessionIndex,g);C!==(b.messageSessionIndex??x.messageSessionIndex)&&(b.messageSessionIndex=C)}const j=b.messageSessionIndex??x.messageSessionIndex;let y=j;return u.forEach(C=>{const M=C?.info?.id;typeof M=="string"&&M.length>0&&(y=Xs(y,M,t))}),y!==j&&(b.messageSessionIndex=y),b})},evictLeastRecentlyUsed:t=>{const n=s();if(n.messages.size<=Dt.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,m)=>{const f=n.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([m,f])});const i=a.filter(([d,m])=>d!==t&&!m.isStreaming);if(i.length===0)return;i.sort((d,m)=>d[1].lastAccessedAt-m[1].lastAccessedAt);const c=i[0][0];r(d=>{const f=(d.messages.get(c)||[]).map(w=>w.info.id),u=new Map(d.messages),p=new Map(d.sessionMemoryState);u.delete(c),p.delete(c);const h={messages:u,sessionMemoryState:p},g=new Map(d.pendingAssistantParts);let x=!1;g.forEach((w,j)=>{w.sessionId===c&&(g.delete(j),x=!0)}),x&&(h.pendingAssistantParts=g);const S=new Map(d.sessionCompactionUntil);S.delete(c)&&(h.sessionCompactionUntil=S),_s(f);const v=cr(d.messageStreamStates,f);v!==d.messageStreamStates&&(h.messageStreamStates=v);const k=Or(h.messageSessionIndex??d.messageSessionIndex,f);k!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=k);const b=Qt(d.streamingMessageIds,c,null);if(b!==d.streamingMessageIds&&(h.streamingMessageIds=b),d.abortControllers.has(c)){const w=new Map(d.abortControllers);w.delete(c),h.abortControllers=w}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 On(t,()=>Ae.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],m=c.findIndex(f=>f.info.id===d.info.id);if(m>0){const f=Math.min(Dt.VIEWPORT_MESSAGES,m),u=c.slice(m-f,m);r(p=>{const h=[...u,...a],g=new Map(p.messages);g.set(t,h);const x=new Map(p.sessionMemoryState);return x.set(t,{...i,viewportAnchor:i.viewportAnchor+u.length,hasMoreAbove:m-f>0,totalAvailableMessages:c.length}),{messages:g,sessionMemoryState:x}})}else m===0&&r(f=>{const u=new Map(f.sessionMemoryState);return u.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:u}})}},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:is(()=>Ut()),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"})),Qm=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),ef=r=>r?Qm.has(r.toLowerCase()):!1,tf=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},sf=r=>{if(r)try{const s=tf();if(s?.getState)return s.getState().agents?.find?.(n=>n.name===r)}catch{}},tn=r=>{const s=sf(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"},Fa=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},$n=r=>{const s=r.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return Fa(s);const t=r.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:Fa(t.tokens)},zn=(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,m=d>0?r/d*100:0;return{percentage:Math.min(m,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},ur=["ask","allow","full"],ht=It()(Bt(as((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=(u,p)=>{if("mode"in u&&u.mode&&typeof u.mode=="string"&&n.find(S=>S.name===u.mode))return u.mode;if(u.providerID&&u.modelID){const x=n.find(S=>S.model?.providerID===u.providerID&&S.model?.modelID===u.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(p>0&&u.providerID&&u.modelID){const S=(o.get(t)||[]).filter(v=>v.info.role==="assistant").sort((v,k)=>v.info.time.created-k.info.time.created);for(let v=p-1;v>=0;v--){const b=S[v].info;if(b.providerID===u.providerID&&b.modelID===u.modelID){if(b.mode&&typeof b.mode=="string"&&n.find(y=>y.name===b.mode))return b.mode;const w=n.find(j=>j.model?.providerID===b.providerID&&j.model?.modelID===b.modelID);if(w)return w.name}}}return u.providerID&&u.modelID&&n.find(S=>S.name==="build")?"build":null},d=o.get(t)||[],m=d.filter(u=>u.info.role==="assistant"||u.info.role==="user").sort((u,p)=>u.info.time.created-p.info.time.created),f=d.filter(u=>u.info.role==="assistant").sort((u,p)=>u.info.time.created-p.info.time.created);for(let u=0;u<m.length;u++){const p=m[u],{info:h}=p,g=h;if(g.providerID&&g.modelID){const x=c(g,f.indexOf(p));if(x&&n.find(S=>S.name===x)){const S={providerId:g.providerID,modelId:g.modelID,timestamp:h.time.created},v=i.get(x);(!v||S.timestamp>v.timestamp)&&i.set(x,S)}}}for(const[u,p]of i)a(t,u,p.providerId,p.modelId);return i},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=zn(0,n,o),c=i.contextLimit,d=i.normalizedOutput??0,m=i.thresholdLimit;if(c===0||m===0)return null;const u=(a.get(t)||[]).filter(b=>b.info.role==="assistant");if(u.length===0)return null;const p=u[u.length-1],h=p.info.id,g=b=>{const w=()=>{r(j=>{const y=j.sessionContextUsage.get(t);if(y&&y.totalTokens===b.totalTokens&&y.percentage===b.percentage&&y.contextLimit===b.contextLimit&&(y.outputLimit??0)===(b.outputLimit??0)&&(y.normalizedOutput??0)===(b.normalizedOutput??0)&&y.thresholdLimit===b.thresholdLimit&&y.lastMessageId===b.lastMessageId)return j;const C=new Map(j.sessionContextUsage);return C.set(t,b),{sessionContextUsage:C}})};typeof queueMicrotask=="function"?queueMicrotask(w):typeof window<"u"?window.setTimeout(w,0):setTimeout(w,0)},x=s().sessionContextUsage.get(t);if(x&&x.lastMessageId===h){const b=x.normalizedOutput??x.outputLimit??0,w=x.contextLimit!==c||b!==d||x.thresholdLimit!==m;if(w&&x.totalTokens>0){const j=x.totalTokens/m*100,y={totalTokens:x.totalTokens,percentage:Math.min(j,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:m,lastMessageId:h};return g(y),y}if(!w&&x.totalTokens>0)return x}const S=$n(p);if(S===0)return x||null;const v=zn(S,n,o),k={totalTokens:S,percentage:v.percentage,contextLimit:v.contextLimit,outputLimit:v.outputLimit,normalizedOutput:v.normalizedOutput,thresholdLimit:v.thresholdLimit,lastMessageId:h};return g(k),k},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(u=>u.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],m=$n(d);if(m===0)return;const f=zn(m,n,o);r(u=>{const p=new Map(u.sessionContextUsage);return p.set(t,{totalTokens:m,percentage:f.percentage,contextLimit:f.contextLimit,outputLimit:f.outputLimit,normalizedOutput:f.normalizedOutput,thresholdLimit:f.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},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 m=(o.get(t)||[]).find(f=>f.info.id===n);if(m&&m.info.role==="assistant"&&$n(m)>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=tn(n))=>!t||!n?o:s().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=tn(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||ur.includes(o)&&r(c=>{const d=new Map(c.sessionAgentEditModes),m=new Map(d.get(t)??new Map);return o===i?(m.delete(n),m.size===0?d.delete(t):d.set(t,m)):(m.set(n,o),d.set(t,m)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=tn(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=s().getSessionAgentEditMode(t,n,a),c=ur.indexOf(i),d=ur.indexOf(a),f=((c>=0?c:d>=0?d:0)+1)%ur.length,u=ur[f];s().setSessionAgentEditMode(t,n,u,a)}}),{name:"context-store",storage:is(()=>Ut()),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"})),rf=r=>typeof r=="object"&&r!==null,nf=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},of=async(r,s)=>{try{const t=Xe.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()},yn=It()(Bt(as((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 f=window.__zustand_config_store__;f?.getState&&(i=f.getState().currentAgentName??void 0)}const c=tn(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&ef(a)){s().respondToPermission(o,t.id,"once").catch(()=>{});return}r(f=>{const u=f.permissions.get(o)||[],p=new Map(f.permissions);return p.set(o,[...u,t]),{permissions:p}})},respondToPermission:async(t,n,o)=>{await of(t,()=>Ae.respondToPermission(t,n,o)),o==="reject"&&await st.getState().abortCurrentOperation(t),r(a=>{const c=(a.permissions.get(t)||[]).filter(m=>m.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:is(()=>Ut()),partialize:r=>({permissions:Array.from(r.permissions.entries())}),merge:(r,s)=>{if(!rf(r))return s;const t=nf(r.permissions);return{...s,permissions:new Map(t)}}}),{name:"permission-store"})),dl=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
+ `),Pa=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},Ra=(r,s,t)=>{if(!s)return null;const n=t(s)?.path;if(typeof n=="string"&&n.trim().length>0)return Pa(n);const o=r.find(a=>a.id===s);return o?Pa(o.directory??null):null},ye=It()(Bt((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)=>ht.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>ht.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>ht.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>Xe.getState().loadSessions(),createSession:async(t,n,o)=>{const a=await Xe.getState().createSession(t,n,o);return a?.id&&await s().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=st.getState(),{messages:o,lastUsedProvider:a}=n;let i,c;if(o.forEach((v,k)=>{const b=v.find(w=>w.info?.id===t);b&&!i&&(i=b,c=k)}),!i||i.info.role!=="assistant")return;const d=dl(i.parts);if(!d.trim())return;const m=Xe.getState(),f=Ra(m.sessions,c??null,m.getWorktreeMetadata),u=await s().createSession(void 0,f??null,null);if(!u)return;const{currentProviderId:p,currentModelId:h,currentAgentName:g}=xt.getState(),x=p||a?.providerID,S=h||a?.modelID;!x||!S||await Ae.sendMessage({id:u.id,providerID:x,modelID:S,text:d,prefaceText:ll,agent:g??void 0})},deleteSession:(t,n)=>Xe.getState().deleteSession(t,n),deleteSessions:(t,n)=>Xe.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>Xe.getState().updateSessionTitle(t,n),shareSession:t=>Xe.getState().shareSession(t),unshareSession:t=>Xe.getState().unshareSession(t),setCurrentSession:async t=>{const n=s().currentSessionId,o=Ra(Xe.getState().sessions,t,Xe.getState().getWorktreeMetadata),a=Ae.getDirectory()??yt.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,Dt.VIEWPORT_MESSAGES)}Xe.getState().setCurrentSession(t),t&&(s().messages.get(t)||await s().loadMessages(t),s().trimToViewportWindow(t,Ku)),s().evictLeastRecentlyUsed()},loadMessages:t=>st.getState().loadMessages(t),sendMessage:(t,n,o,a,i,c)=>{const d=Xe.getState().currentSessionId;return st.getState().sendMessage(t,n,o,a,d||void 0,i,c)},abortCurrentOperation:()=>{const t=Xe.getState().currentSessionId;return st.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=Xe.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&&st.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=Xe.getState().currentSessionId||t;return st.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>st.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>st.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>st.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>st.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:ht.getState().currentAgentContext,sessionAgentSelections:ht.getState().sessionAgentSelections,getSessionAgentEditMode:ht.getState().getSessionAgentEditMode};return yn.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>yn.getState().respondToPermission(t,n,o),clearError:()=>Xe.getState().clearError(),getSessionsByDirectory:t=>Xe.getState().getSessionsByDirectory(t),getLastMessageModel:t=>st.getState().getLastMessageModel(t),getCurrentAgent:t=>ht.getState().getCurrentAgent(t),syncMessages:(t,n)=>st.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>Xe.getState().applySessionMetadata(t,n),addAttachedFile:t=>As.getState().addAttachedFile(t),addServerFile:(t,n,o)=>As.getState().addServerFile(t,n,o),removeAttachedFile:t=>As.getState().removeAttachedFile(t),clearAttachedFiles:()=>As.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>st.getState().updateViewportAnchor(t,n),trimToViewportWindow:(t,n)=>{const o=Xe.getState().currentSessionId;return st.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=Xe.getState().currentSessionId;return st.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>st.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>ht.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>ht.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>ht.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>ht.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>ht.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>ht.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=st.getState().messages;return ht.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>Xe.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>Xe.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>Xe.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>Xe.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>Xe.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>Xe.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{const o=Xe.getState().currentSessionId;if(!o)return null;const a=st.getState().messages;return ht.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=st.getState().messages;return ht.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=st.getState().messages;return ht.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=st.getState().messages.get(t)||[],o=Xe.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=st.getState().messages;return ht.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>Xe.getState().updateSession(t)}),{name:"composed-session-store"}));Xe.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||ye.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})});st.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 m=d.trim();if(m.length>0){const f=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:m,createdAt:f});break}}}}}),ye.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})});As.subscribe((r,s)=>{r.attachedFiles!==s.attachedFiles&&ye.setState({attachedFiles:r.attachedFiles})});ht.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||ye.setState({sessionModelSelections:r.sessionModelSelections,sessionAgentSelections:r.sessionAgentSelections,sessionAgentModelSelections:r.sessionAgentModelSelections,currentAgentContext:r.currentAgentContext,sessionContextUsage:r.sessionContextUsage,sessionAgentEditModes:r.sessionAgentEditModes})});yn.subscribe((r,s)=>{r.permissions!==s.permissions&&ye.setState({permissions:r.permissions})});ye.setState({sessions:Xe.getState().sessions,currentSessionId:Xe.getState().currentSessionId,lastLoadedDirectory:Xe.getState().lastLoadedDirectory,isLoading:Xe.getState().isLoading,error:Xe.getState().error,webUICreatedSessions:Xe.getState().webUICreatedSessions,worktreeMetadata:Xe.getState().worktreeMetadata,availableWorktrees:Xe.getState().availableWorktrees,messages:st.getState().messages,sessionMemoryState:st.getState().sessionMemoryState,messageStreamStates:st.getState().messageStreamStates,sessionCompactionUntil:st.getState().sessionCompactionUntil,sessionAbortFlags:st.getState().sessionAbortFlags,streamingMessageIds:st.getState().streamingMessageIds,abortControllers:st.getState().abortControllers,lastUsedProvider:st.getState().lastUsedProvider,isSyncing:st.getState().isSyncing,permissions:yn.getState().permissions,attachedFiles:As.getState().attachedFiles,sessionModelSelections:ht.getState().sessionModelSelections,sessionAgentSelections:ht.getState().sessionAgentSelections,sessionAgentModelSelections:ht.getState().sessionAgentModelSelections,currentAgentContext:ht.getState().currentAgentContext,sessionContextUsage:ht.getState().sessionContextUsage,sessionAgentEditModes:ht.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=ye);const mo=({totalTokens:r,percentage:s,contextLimit:t,outputLimit:n,size:o="default"})=>{const a=f=>f>=1e6?`${(f/1e6).toFixed(1)}M`:f>=1e3?`${(f/1e3).toFixed(1)}K`:f.toFixed(1).replace(/\.0$/,""),i=f=>f>=90?"text-status-error":f>=75?"text-status-warning":"text-status-success",c=typeof n=="number"?Math.max(n,0):0,d=[`Used tokens: ${a(r)}`,`Context limit: ${a(t)}`,`Output limit: ${a(c)}`],m=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",children:[e.jsx(Ic,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:T(i(s),"font-medium"),children:[Math.min(s,999).toFixed(1),"%"]})]});return e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:m}),e.jsx(lt,{children:e.jsx("div",{className:"space-y-0.5",children:d.map(f=>e.jsx("p",{className:"typography-micro leading-tight",children:f},f))})})]})},mr={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},ul=(r,s,t)=>{if(typeof window>"u")return;const n=document.documentElement,o=s==="mobile",a=s==="tablet";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 Hn(){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,m=r>mr.md&&r<=mr.lg,f=r<=mr.md;let u=d&&f,p=d&&!u&&m,h=!d||r>mr.lg,g="desktop";c?(u=!1,p=!1,h=!0,g="desktop"):u?g="mobile":p?g="tablet":(h=!0,g="desktop"),ul(c,g,d);let x="xs";for(const[S,v]of Object.entries(mr))r>=v&&(x=S);return{isMobile:u,isTablet:p,isDesktop:h,deviceType:g,screenWidth:r,breakpoint:x,hasTouchInput:d}}function Ct(){const[r,s]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Hn());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{s(Hn())};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(Hn())},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,m=i||c||d>0;ul(t,r.deviceType,m)},[r.deviceType,r.hasTouchInput]),r}const $r=1e4,af=2e4,lf=5e3,cf=3e4,es=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),df=(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},uf=(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!!df(r.diffStats,s.diffStats)},jt=It()(Bt((r,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:$r,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=s();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,es()),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=es()),a||r({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const u=new Map(i);return u.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),r({directories:u,isLoadingStatus:!1}),!1}const f=await n.getGitStatus(t);if(uf(c.status,f)){d=!0;const u=new Map(s().directories),p=u.get(t)??es();u.set(t,{...p,isGitRepo:!0,status:f,diffCache:new Map,lastStatusFetch:Date.now(),lastStatusChange:Date.now()}),r({directories:u})}else{const u=new Map(s().directories),p=u.get(t)??es();u.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),r({directories:u})}}catch(m){console.error("Failed to fetch git status:",m)}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)??es();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}),m=new Map(s().directories),f=m.get(t)??es();m.set(t,{...f,log:d,lastLogFetch:Date.now(),logMaxCount:c}),r({directories:m})}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)??es();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=es();const u=new Map(a);u.set(t,i),r({directories:u})}const{force:c=!1}=o,d=Date.now();await s().fetchStatus(t,n);const m=s().directories.get(t);if(!m?.isGitRepo)return;await s().fetchBranches(t,n);const f=d-(m.lastLogFetch||0);(c||f>cf||!m.log)&&await s().fetchLog(t,n),await s().fetchIdentity(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)??es(),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}))},setLogMaxCount:(t,n)=>{const o=new Map(s().directories),a=o.get(t)??es();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),r({currentPollInterval:$r});else{const f=Math.min(a+lf,af);r({currentPollInterval:f})}const{pollIntervalId:m}=s();m!==null&&r({pollIntervalId:o()})},a)};r({pollIntervalId:o(),currentPollInterval:$r})},stopPolling:()=>{const{pollIntervalId:t}=s();t&&(clearTimeout(t),r({pollIntervalId:null,currentPollInterval:$r}))},refresh:async(t,n={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,t,n)}}),{name:"git-store"})),ml=r=>jt(s=>r?s.directories.get(r)?.status??null:null),mf=r=>jt(s=>r?s.directories.get(r)?.branches??null:null),ff=r=>jt(s=>r?s.directories.get(r)?.log??null:null),pf=r=>jt(s=>r?s.directories.get(r)?.identity??null:null),fl=r=>jt(s=>r?s.directories.get(r)?.isGitRepo??null:null),hf=r=>jt(s=>r?s.directories.get(r)?.status?.files?.length??0:0);function Rt({...r}){return e.jsx(Fc,{"data-slot":"dropdown-menu",...r})}function Lt({...r}){return e.jsx(Pc,{"data-slot":"dropdown-menu-trigger",...r})}function _t({className:r,sideOffset:s=4,...t}){return e.jsx(Rc,{children:e.jsx(Lc,{"data-slot":"dropdown-menu-content",sideOffset:s,className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...t})})}function gt({className:r,inset:s,variant:t="default",...n}){return e.jsx($c,{"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 gf({...r}){return e.jsx(_c,{"data-slot":"dropdown-menu-radio-group",...r})}function yf({className:r,children:s,...t}){return e.jsxs(Bc,{"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(Oc,{children:e.jsx(Nt,{className:"size-3"})})}),s]})}function $o({className:r,...s}){return e.jsx(zc,{"data-slot":"dropdown-menu-separator",className:T("bg-border -mx-1 my-0.5 h-px",r),...s})}function pl({...r}){return e.jsx(Hc,{"data-slot":"dropdown-menu-sub",...r})}function hl({className:r,inset:s,children:t,...n}){return e.jsxs(Wc,{"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(xs,{className:"ml-auto size-3.5"})]})}function gl({className:r,...s}){return e.jsx(Uc,{"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 xf={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 yl(r){return xf[r]||{displayName:r.charAt(0).toUpperCase()+r.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function bf(r,s,t){const n=yl(r);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=Mn(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 Mn(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}function wf(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 zo=l.createContext(null),Gs=()=>{const r=l.useContext(zo);if(!r)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return r},xl=r=>{const s=Gs();return r(s)},vf=()=>xl(r=>r.runtime.isDesktop),Ho=()=>xl(r=>r.runtime.isVSCode),Sf=({mode:r,onModeChange:s,className:t})=>{const n=l.useCallback(o=>{o.stopPropagation(),s(r==="side-by-side"?"unified":"side-by-side")},[r,s]);return e.jsx(De,{size:"sm",variant:"ghost",className: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(Vc,{className:"h-3 w-3"}):e.jsx(Gc,{className:"h-3 w-3"})})},Wo=fe.createContext(void 0);function ir(){const r=fe.useContext(Wo);if(!r)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return r}function Uo(){return fe.useContext(Wo)}const Vo=({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}),[m,f]=l.useState({length:0,offset:0}),u=l.useRef(null),p=l.useRef(null),h=l.useRef(!1),g=l.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),x=l.useRef(null),S=l.useCallback(()=>{const N=r.current;if(!N)return;const{scrollHeight:A,clientHeight:D,scrollTop:I,scrollWidth:z,clientWidth:E,scrollLeft:$}=N,V=8;if(A>D){const Y=Math.max(D-V*2,0),L=D/A*Y,_=Math.max(s,Math.min(Y,L)),W=Math.max(Y-_,0),ae=Math.max(A-D,1),je=I/ae*W;d({length:_,offset:je})}else d({length:0,offset:0});if(!o&&z>E){const Y=Math.max(E-V*2,0),L=E/z*Y,_=Math.max(s,Math.min(Y,L)),W=Math.max(Y-_,0),ae=Math.max(z-E,1),je=$/ae*W;f({length:_,offset:je})}else f({length:0,offset:0})},[r,s,o]),v=l.useCallback(()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>i(!1),t)},[t]),k=l.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{S(),i(!0),v()})},[v,S]);l.useEffect(()=>{const N=r.current;if(!N)return;S(),i(!0),v(),N.addEventListener("scroll",k,{passive:!0});const A=typeof ResizeObserver<"u"?new ResizeObserver(()=>S()):null;A?.observe(N);const D=typeof MutationObserver<"u"?new MutationObserver(()=>S()):null;return D?.observe(N,{childList:!0,subtree:!0,characterData:!0}),()=>{N.removeEventListener("scroll",k),A?.disconnect(),D?.disconnect(),u.current&&clearTimeout(u.current),p.current&&cancelAnimationFrame(p.current)}},[r,k,v,S]);const b=(N,A)=>{const D=r.current;D&&(h.current=!0,g.current={pointerX:N.clientX,pointerY:N.clientY,scrollTop:D.scrollTop,scrollLeft:D.scrollLeft},x.current=A,i(!0),u.current&&clearTimeout(u.current),N.currentTarget.setPointerCapture(N.pointerId))},w=N=>{if(!h.current)return;const A=r.current;if(!A)return;const D=x.current;if(D==="vertical"){const{pointerY:I,scrollTop:z}=g.current,E=N.clientY-I,$=A.clientHeight,V=Math.max($-c.length,1),Y=Math.max(A.scrollHeight-A.clientHeight,1),L=E/V*Y;A.scrollTop=z+L}else if(D==="horizontal"){const{pointerX:I,scrollLeft:z}=g.current,E=N.clientX-I,$=A.clientWidth,V=Math.max($-m.length,1),Y=Math.max(A.scrollWidth-A.clientWidth,1),L=E/V*Y;A.scrollLeft=z+L}},j=N=>{h.current&&(h.current=!1,N.currentTarget.releasePointerCapture(N.pointerId),v())},y=c.length>0,C=m.length>0;if(!y&&!C)return null;const M=8;return e.jsxs("div",{className:T("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[y&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${M+c.offset}px`,right:`${M/2}px`},onPointerDown:N=>b(N,"vertical"),onPointerMove:w,onPointerUp:j,onPointerCancel:j}),C&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${m.length}px`,left:`${M+m.offset}px`,bottom:`${M/2}px`},onPointerDown:N=>b(N,"horizontal"),onPointerMove:w,onPointerUp:j,onPointerCancel:j})]})},Je=l.forwardRef(({className:r,outerClassName:s,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:m=!0,...f},u)=>{const p=l.useRef(null);return l.useImperativeHandle(u,()=>p.current,[]),e.jsxs("div",{className:T("relative flex flex-col min-h-0 w-full overflow-hidden",s),children:[e.jsx(i,{ref:p,className:T("overlay-scrollbar-target overlay-scrollbar-container",m?"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,...f,children:t}),e.jsx(Vo,{containerRef:p,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});Je.displayName="ScrollableOverlay";const jf="Flexoki",kf="dark",Nf={"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"},Cf=[{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"}}],Mf={name:jf,type:kf,colors:Nf,tokenColors:Cf},Af="Flexoki",Df="light",Ef={"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"},Tf=[{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"}}],If={name:Af,type:Df,colors:Ef,tokenColors:Tf},Go="flexoki-dark",qo="flexoki-light",Ff=Mf,Pf=If;function bl(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 wl(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 Ko=wl(Ff,Go,"dark"),Yo=wl(Pf,qo,"light");bl(Ko,Go);bl(Yo,qo);const tr={dark:Go,light:qo},La=[Yo,Ko];let _a=!1;function vl(){_a||(na(tr.dark,async()=>Ko),na(tr.light,async()=>Yo),_a=!0)}const Rf=`
7
+ :host, pre, [data-diffs], [data-code] {
8
+ transform: translateZ(0);
9
+ -webkit-transform: translateZ(0);
10
+ -webkit-backface-visibility: hidden;
11
+ backface-visibility: hidden;
12
+ }
13
+ [data-code] {
14
+ -webkit-overflow-scrolling: touch;
15
+ }
16
+ `;function Lf(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 Ba=({original:r,modified:s,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const c=Uo()?.currentTheme?.metadata?.variant==="dark";vl();const d=fe.useRef(null),m=fe.useMemo(()=>{const u=Lf(n,r,s);if(d.current?.key===u)return d.current.fileDiff;const p={name:n,contents:r,cacheKey:`old-${u}`},h={name:n,contents:s,cacheKey:`new-${u}`},g=qc(p,h);return d.current={key:u,fileDiff:g},g},[n,r,s,t]),f=fe.useMemo(()=>({theme:{dark:tr.dark,light:tr.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:Rf}),[c,o,a]);return typeof window>"u"?null:e.jsx(Je,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(Kc,{fileDiff:m,options:f})})},_f=1100,Bf=r=>{const{index:s,working_dir:t}=r;return s==="A"||t==="A"||s==="?"||t==="?"},Oa=(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]})},Of=l.memo(({changedFiles:r,selectedFile:s,selectedFileEntry:t,onSelectFile:n})=>r.length===0?null:e.jsxs(Rt,{children:[e.jsx(Lt,{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 items-center gap-3",children:[e.jsx("span",{className:"truncate typography-meta",children:t.path}),Oa(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(wt,{className:"size-4 opacity-50"})]})}),e.jsx(_t,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(gf,{value:s??"",onValueChange:n,children:r.map(o=>e.jsx(yf,{value:o.path,children:e.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[e.jsx("span",{className:"truncate typography-meta",children:o.path}),Oa(o.insertions,o.deletions)]})},o.path))})})]})),$f=l.memo(({filePath:r,diff:s,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=l.useMemo(()=>Mn(r)||"text",[r]);return t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(Ba,{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(Ba,{original:s.original,modified:s.modified,language:a,fileName:r,renderSideBySide:n,wrapLines:o})})}),zf=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=ye(),{currentDirectory:n}=yt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},Hf=()=>{const{git:r}=Gs(),s=zf(),{screenWidth:t}=Ct(),n=fl(s??null),o=ml(s??null),a=jt(E=>E.isLoadingStatus),{setActiveDirectory:i,fetchStatus:c,setDiff:d}=jt(),[m,f]=l.useState(null),[u,p]=l.useState(new Map),[h,g]=l.useState(new Set),x=Re(E=>E.pendingDiffFile),S=Re(E=>E.setPendingDiffFile),v=Re(E=>E.diffLayoutPreference),k=Re(E=>E.diffFileLayout),b=Re(E=>E.setDiffFileLayout),w=Re(E=>E.diffWrapLines),j=Re(E=>E.setDiffWrapLines),y=jt(l.useCallback(E=>s?E.directories.get(s)?.lastStatusChange??0:0,[s])),C=l.useMemo(()=>{if(!o?.files)return[];const E=o.diffStats??{};return o.files.map($=>({...$,insertions:E[$.path]?.insertions??0,deletions:E[$.path]?.deletions??0,isNew:Bf($)})).sort(($,V)=>$.path.localeCompare(V.path))},[o]),M=l.useMemo(()=>m?C.find(E=>E.path===m)??null:null,[C,m]),N=l.useMemo(()=>{if(!M)return null;const E=k[M.path];if(E)return E;if(v==="inline")return"inline";if(v==="side-by-side")return"side-by-side";const $=t<_f;return M.isNew||$?"inline":"side-by-side"},[M,k,v,t]);l.useEffect(()=>{s&&(i(s),jt.getState().directories.get(s)?.status||c(s,r))},[s,i,c,r]),l.useEffect(()=>{x&&(f(x),S(null))},[x,S]),l.useEffect(()=>{!m&&C.length>0&&f(C[0].path)},[C,m]),l.useEffect(()=>{m&&C.length>0&&(C.some($=>$.path===m)||f(C[0]?.path??null))},[C,m]),l.useEffect(()=>{if(!s||C.length===0)return;(async()=>{const $=C.filter(Y=>!u.has(Y.path));if($.length===0)return;g(Y=>{const L=new Set(Y);return $.forEach(_=>L.add(_.path)),L});const V=await Promise.allSettled($.map(async Y=>{const L=jt.getState().directories.get(s),_=L?.diffCache.get(Y.path);if(_&&_.fetchedAt>=(L?.lastStatusChange||0))return{path:Y.path,diff:{original:_.original,modified:_.modified}};const W=await r.getGitFileDiff(s,{path:Y.path}),ae={original:W.original??"",modified:W.modified??""};return d(s,Y.path,ae),{path:Y.path,diff:ae}}));p(Y=>{const L=new Map(Y);return V.forEach(_=>{_.status==="fulfilled"&&L.set(_.value.path,_.value.diff)}),L}),g(Y=>{const L=new Set(Y);return $.forEach(_=>L.delete(_.path)),L})})()},[s,C,r,d]),l.useEffect(()=>{p(new Map),g(new Set)},[s]),l.useEffect(()=>{if(!s||!y||C.length===0)return;(async()=>{const $=jt.getState().directories.get(s);if(!$)return;const V=C.filter(L=>{const _=$.diffCache.get(L.path);return!_||_.fetchedAt<y});if(V.length===0)return;g(L=>{const _=new Set(L);return V.forEach(W=>_.add(W.path)),_});const Y=await Promise.allSettled(V.map(async L=>{const _=await r.getGitFileDiff(s,{path:L.path}),W={original:_.original??"",modified:_.modified??""};return d(s,L.path,W),{path:L.path,diff:W}}));p(L=>{const _=new Map(L);Y.forEach(W=>{W.status==="fulfilled"&&_.set(W.value.path,W.value.diff)});for(const[W]of L)C.some(ae=>ae.path===W)||_.delete(W);return _}),g(L=>{const _=new Set(L);return V.forEach(W=>_.delete(W.path)),_})})()},[s,y,C,r,d]);const A=l.useCallback(E=>{f(E)},[]),D=(N??"side-by-side")==="side-by-side",I=()=>u.size===0?null:Array.from(u.entries()).map(([E,$])=>e.jsx($f,{filePath:E,diff:$,isVisible:E===m,renderSideBySide:D,wrapLines:w},E)),z=()=>{if(!s)return e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});if(a&&!o)return e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ft,{size:16,className:"animate-spin"}),"Loading repository status…"]});if(n===!1)return 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."});if(C.length===0)return e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Working tree clean — no changes to display"});const E=m&&h.has(m),$=m&&u.has(m);return e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[I(),E&&!$&&e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ft,{size:16,className:"animate-spin"}),"Loading diff…"]})]})};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:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(so,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:a&&!o?"Loading changes…":`${C.length} ${C.length===1?"file":"files"} changed`})]}),e.jsx(Of,{changedFiles:C,selectedFile:m,selectedFileEntry:M,onSelectFile:A}),e.jsx("div",{className:"flex-1"}),M&&e.jsx("button",{type:"button",onClick:()=>j(!w),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${w?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:w?"Disable line wrap":"Enable line wrap",children:e.jsx(Yc,{className:"size-4"})}),M&&N&&e.jsx(Sf,{mode:N==="side-by-side"?"side-by-side":"unified",onModeChange:E=>{if(!M)return;const $=E==="side-by-side"?"side-by-side":"inline";b(M.path,$)}})]}),z()]})},Wf=()=>{const{git:r}=Gs(),{currentSessionId:s,sessions:t,worktreeMetadata:n}=ye(),{currentDirectory:o}=yt(),a=s?n.get(s)??void 0:void 0,c=t.find(p=>p.id===s)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:m,fetchStatus:f}=jt(),u=hf(d??null);return l.useEffect(()=>{d&&(m(d),jt.getState().directories.get(d)?.status||f(d,r))},[d,m,f,r]),u},Uf=()=>{const r=Re(d=>d.setSessionSwitcherOpen),s=Re(d=>d.toggleSidebar),{isMobile:t}=Ct(),[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"},children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Open sessions",className:c,children:e.jsx(kr,{className:"h-5 w-5"})})})},$a=()=>{const r=Re(L=>L.setSessionSwitcherOpen),s=Re(L=>L.toggleSidebar),t=Re(L=>L.isSidebarOpen),n=Re(L=>L.sidebarWidth),o=Re(L=>L.activeMainTab),a=Re(L=>L.setActiveMainTab),{getCurrentModel:i}=xt(),c=ye(L=>L.getContextUsage),{isMobile:d}=Ct(),m=Wf(),f=l.useRef(null),[u,p]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),h=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);fe.useEffect(()=>{if(typeof window>"u")return;const L=typeof window.opencodeDesktop<"u";p(L)},[]);const g=i(),x=g&&typeof g.limit=="object"&&g.limit!==null?g.limit:null,S=x&&typeof x.context=="number"?x.context:0,v=x&&typeof x.output=="number"?x.output:0,k=c(S,v),[b,w]=l.useState(!1),j=Re(L=>L.isSessionSwitcherOpen),y=l.useCallback(()=>{if(d){r(!j);return}s()},[d,j,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",M=l.useMemo(()=>u&&h?t?"pl-0":"pl-[8.0rem]":"pl-3",[u,h,t]),N=l.useCallback(()=>{if(typeof document>"u")return;const L=f.current?.getBoundingClientRect().height;L&&document.documentElement.style.setProperty("--oc-header-height",`${L}px`)},[]);fe.useEffect(()=>{if(typeof window>"u")return;N();const L=f.current;if(!L||typeof ResizeObserver>"u")return()=>{};const _=new ResizeObserver(()=>{N()});return _.observe(L),window.addEventListener("resize",N),window.addEventListener("orientationchange",N),()=>{_.disconnect(),window.removeEventListener("resize",N),window.removeEventListener("orientationchange",N)}},[N]),fe.useEffect(()=>{N()},[N,d,b]);const A=l.useCallback(L=>L>=1e6?`${(L/1e6).toFixed(1)}M`:L>=1e3?`${(L/1e3).toFixed(1)}K`:L.toFixed(1).replace(/\.0$/,""),[]),D=l.useCallback(async L=>{if(!L.target.closest("button, a, input, select, textarea")&&L.button===0&&u)try{const{getCurrentWindow:_}=await jr(async()=>{const{getCurrentWindow:ae}=await import("./vendor-.pnpm-BKK22KLz.js").then(je=>je.bS);return{getCurrentWindow:ae}},__vite__mapDeps([0,1]));await _().startDragging()}catch(_){console.error("Failed to start window dragging:",_)}},[u]),I=l.useCallback(async L=>{if(L.button===0&&u)try{const{getCurrentWindow:_}=await jr(async()=>{const{getCurrentWindow:ae}=await import("./vendor-.pnpm-BKK22KLz.js").then(je=>je.bS);return{getCurrentWindow:ae}},__vite__mapDeps([0,1]));await _().startDragging()}catch(_){console.error("Failed to start window dragging:",_)}},[u]),z=l.useMemo(()=>[{id:"chat",label:"Chat",icon:Xc},{id:"diff",label:"Diff",icon:Ts,badge:m>0?m:void 0},{id:"terminal",label:"Terminal",icon:Fs},{id:"git",label:"Git",icon:Tt}],[m]);fe.useEffect(()=>{const L=_=>{if((_.metaKey||_.ctrlKey)&&!_.shiftKey&&!_.altKey){const W=parseInt(_.key,10);W>=1&&W<=z.length&&(_.preventDefault(),a(z[W-1].id))}};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[z,a]);const E=(L,_)=>{const W=o===L.id,ae=L.icon,je=L.id==="chat",Me=L.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>a(L.id),onMouseDown:W?I: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&&je&&t&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",je&&!(u&&h&&t)&&"border-l",Me&&"border-r",je&&!d&&"min-w-[165px]"),style:{...W&&je&&t?{"--sidebar-w":u&&h?`${n}px`:"64px"}:{},...je&&!(u&&h&&t)||Me?{borderColor:"var(--interactive-border)"}:{}},"aria-selected":W,role:"tab",children:[d?e.jsx(ae,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),e.jsx("span",{children:L.label})]}),je&&!d&&k&&k.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(mo,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:L.badge})]}),!_&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},L.id)},$=()=>e.jsxs("div",{onMouseDown:D,className:T("app-region-drag relative flex h-12 select-none items-center",M),role:"tablist","aria-label":"Main navigation",children:[!(u&&h)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:y,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(kr,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:z.map((L,_)=>E(L,_===z.length-1))}),e.jsx("div",{className:"flex-1"})]}),V=()=>e.jsxs("div",{className:"app-region-drag relative flex flex-col gap-1 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:y,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open sessions",children:e.jsx(kr,{className:"h-5 w-5"})}),k&&k.totalTokens>0&&o==="chat"&&e.jsx(mo,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})]}),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:z.map(L=>{const _=o===L.id,W=L.icon;return e.jsxs(ut,{delayDuration:500,children:[e.jsx(mt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>a(L.id),"aria-label":L.label,"aria-selected":_,role:"tab",className:T(C,_&&"text-foreground"),children:[e.jsx(W,{className:"h-5 w-5"}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:L.badge})]})}),e.jsx(lt,{children:e.jsx("p",{children:L.label})})]},L.id)})}),e.jsx(De,{type:"button",variant:"ghost",size:"icon","aria-expanded":b,"aria-controls":"mobile-header-details",onClick:()=>w(L=>!L),className:"app-region-no-drag h-8 w-8",children:b?e.jsx(jo,{className:"h-4 w-4"}):e.jsx(wt,{className:"h-4 w-4"})})]})]}),b&&e.jsx("div",{id:"mobile-header-details",className:"app-region-no-drag absolute left-0 right-0 top-full z-40 translate-y-2 px-3",children:e.jsx("div",{className:"flex flex-col gap-4 rounded-xl border border-border/40 bg-background/95 px-3 py-3 shadow-none",children:k&&k.totalTokens>0&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Context usage"}),e.jsxs("div",{className:"rounded-lg border border-border/40 bg-muted/10 px-3 py-2 space-y-0.5",children:[e.jsxs("p",{className:"typography-meta",children:["Used tokens: ",e.jsx("span",{className:"font-semibold text-foreground",children:A(k.totalTokens)})]}),e.jsxs("p",{className:"typography-meta",children:["Context limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:A(k.contextLimit)})]}),e.jsxs("p",{className:"typography-meta",children:["Output limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:A(k.outputLimit??0)})]})]})]})})})]}),Y=T("header-safe-area border-b relative z-10",u?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:f,className:Y,style:{borderColor:"var(--interactive-border)"},children:d?V():$()})};function Xo({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 Sl({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 jl({className:r,...s}){return e.jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",r),...s})}function kl({className:r,...s}){return e.jsx("div",{"data-slot":"card-content",className:T("px-6",r),...s})}class Xt 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(Xo,{className:"w-full max-w-md",children:[e.jsx(Sl,{className:"text-center",children:e.jsxs(jl,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(ro,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(kl,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The application encountered an unexpected error. This has been logged for debugging."}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(rr,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}const fo=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_MOCK_UPDATE__;return r?r===!0?{currentVersion:"1.0.3",newVersion:"1.0.8"}:r:null},za=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}),Ha=()=>fo()!==null,Vf=(r=!0)=>{const[s,t]=fe.useState({checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null}),[n]=fe.useState(Ha),[o,a]=fe.useState(()=>{if(Ha()){const u=fo();return u?za(u):null}return null}),i=fe.useCallback(async()=>{if(n){const u=fo();if(u){const p=za(u);p.info={...p.info,body:`## [${u.newVersion}] - 2025-01-01
17
+ - Mock update for UI testing`},a(p)}return}if(Ht()){t(u=>({...u,checking:!0,error:null}));try{const u=await Tu();t(p=>({...p,checking:!1,available:u?.available??!1,info:u}))}catch(u){t(p=>({...p,checking:!1,error:u instanceof Error?u.message:"Failed to check for updates"}))}}},[n]),c=fe.useCallback(async()=>{if(n){a(h=>h&&{...h,downloading:!0});let u=0;const p=setInterval(()=>{u+=20,a(h=>h&&{...h,progress:{downloaded:u*1e3,total:1e5}}),u>=100&&(clearInterval(p),a(h=>h&&{...h,downloading:!1,downloaded:!0,progress:null}))},500);return}if(!(!Ht()||!s.available)){t(u=>({...u,downloading:!0,error:null,progress:null}));try{await Iu(u=>{t(p=>({...p,progress:u}))}),t(u=>({...u,downloading:!1,downloaded:!0}))}catch(u){t(p=>({...p,downloading:!1,error:u instanceof Error?u.message:"Failed to download update"}))}}},[n,s.available]),d=fe.useCallback(async()=>{if(!n&&!(!Ht()||!s.downloaded))try{await Fu()}catch(u){t(p=>({...p,error:u instanceof Error?u.message:"Failed to restart"}))}},[n,s.downloaded]),m=fe.useCallback(()=>{if(n){a(null);return}t(u=>({...u,available:!1,downloaded:!1,info:null}))},[n]);return fe.useEffect(()=>{if(r&&(Ht()||n)){const u=setTimeout(()=>{i()},3e3);return()=>clearTimeout(u)}},[r,i,n]),{...n&&o?o:s,checkForUpdates:i,downloadUpdate:c,restartToUpdate:d,dismiss:m}};let zr=0;function ws({...r}){return e.jsx(Jc,{"data-slot":"dialog",...r})}function Nl({...r}){return e.jsx(rd,{"data-slot":"dialog-trigger",...r})}function Gf({...r}){return e.jsx(ed,{"data-slot":"dialog-portal",...r})}const Cl=fe.forwardRef(({className:r,...s},t)=>(fe.useEffect(()=>(zr+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{zr=Math.max(0,zr-1),zr===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(_i,{ref:t,"data-slot":"dialog-overlay",className:T("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",r),...s})));Cl.displayName=_i.displayName;function vs({className:r,children:s,showCloseButton:t=!0,...n}){return e.jsxs(Gf,{"data-slot":"dialog-portal",children:[e.jsx(Cl,{className:"rounded-none"}),e.jsxs(Zc,{"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(Qc,{"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(os,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function Ss({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 Er({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 js({className:r,...s}){return e.jsx(td,{"data-slot":"dialog-title",className:T("typography-markdown leading-none font-semibold text-foreground",r),...s})}function qs({className:r,...s}){return e.jsx(sd,{"data-slot":"dialog-description",className:T("text-muted-foreground typography-ui-label",r),...s})}const Wa="https://github.com/btriapitsyn/openchamber/releases",qf=({open:r,onOpenChange:s,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d})=>{const m=t?.version?`${Wa}/tag/v${t.version}`:Wa,f=a?.total?Math.round(a.downloaded/a.total*100):0;return e.jsx(ws,{open:r,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-md",children:[e.jsx(Ss,{children:e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(nd,{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(Je,{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.replace(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm,`— v$1 —
18
+ `).replace(/^- /gm,"• ").trim()})}),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:[f,"%"]})]}),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:`${f}%`}})})]}),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:m,target:"_blank",rel:"noopener noreferrer",className:T("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(no,{className:"h-4 w-4"}),"GitHub"]}),!o&&!n&&e.jsxs("button",{onClick:c,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(ko,{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(od,{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(rr,{className:"h-4 w-4"}),"Restart to Update"]})]})]})]})})},xn=264,Ua=200,Va=500,Kf=40,Yf=({isOpen:r,isMobile:s,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a}=Re(),[i,c]=l.useState(!1),d=l.useRef(0),m=l.useRef(n||xn),[f,u]=l.useState(!1),p=Vf(),[h,g]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const w=typeof window.opencodeDesktop<"u";g(w)},[]),l.useEffect(()=>{if(s||!i)return;const w=y=>{const C=y.clientX-d.current,M=Math.min(Va,Math.max(Ua,m.current+C));o(M)},j=()=>{c(!1)};return window.addEventListener("pointermove",w),window.addEventListener("pointerup",j,{once:!0}),()=>{window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",j)}},[s,i,o]),l.useEffect(()=>{s&&i&&c(!1)},[s,i]);const S=l.useCallback(async w=>{if(w.button===0&&h)try{const{getCurrentWindow:j}=await jr(async()=>{const{getCurrentWindow:C}=await import("./vendor-.pnpm-BKK22KLz.js").then(M=>M.bS);return{getCurrentWindow:C}},__vite__mapDeps([0,1]));await j().startDragging()}catch(j){console.error("Failed to start window dragging from sidebar:",j)}},[h]);if(s)return null;const v=r?Math.min(Va,Math.max(Ua,n||xn)):0,k=h&&x,b=w=>{r&&(c(!0),d.current=w.clientX,m.current=v,w.preventDefault())};return e.jsxs("aside",{className:T("relative flex h-full overflow-hidden border-r",h?"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:`${v}px`,minWidth:`${v}px`,maxWidth:`${v}px`,pointerEvents:r?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!r||v===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:b,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:`${v}px`,overflowX:"hidden"},"aria-hidden":!r,children:[k&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Kf}px`},onMouseDown:S,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Xt,{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(on,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),(p.available||p.downloaded)&&e.jsxs("button",{onClick:()=>u(!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(ko,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]})]})}),e.jsx(qf,{open:f,onOpenChange:u,info:p.info,downloading:p.downloading,downloaded:p.downloaded,progress:p.progress,error:p.error,onDownload:p.downloadUpdate,onRestart:p.restartToUpdate})]})]})},Ml=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:No},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:Sn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:nr},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Tt},{id:"settings",label:"Appearance",description:"Fine-tune themes, fonts, and typography across the interface.",icon:ad}],Xf={},Al={},Dl={};Ml.forEach(r=>{Xf[r.id]=r.label,Al[r.id]=r.description,Dl[r.id]=r});const Ga=Al,Jf=Dl;function Cs({className:r,variant:s,...t}){return e.jsx(De,{variant:s,size:"sm",className:T("h-7 px-2 py-0",r),...t})}function kt({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 Zf=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedAgentName:o,agents:a,setSelectedAgent:i,deleteAgent:c,loadAgents:d}=or(),{setSidebarOpen:m}=Re(),{isMobile:f}=Ct();l.useEffect(()=>{d()},[d]);const u=()=>{if(!r.trim()){ge.error("Agent name is required");return}if(a.some(v=>v.name===r)){ge.error("An agent with this name already exists");return}i(r),s(""),n(!1),f&&m(!1)},p=async v=>{if(v.builtIn){ge.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${v.name}"?`)&&(await c(v.name)?ge.success(`Agent "${v.name}" deleted successfully`):ge.error("Failed to delete agent"))},h=v=>{const k=v.name;let b=1,w=`${k} Copy`;for(;a.some(j=>j.name===w);)b++,w=`${k} Copy ${b}`;i(w),n(!1),f&&m(!1)},g=v=>{switch(v){case"primary":return e.jsx(Nr,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Oi,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(Bi,{className:"h-3 w-3 text-primary"});default:return null}},x=a.filter(v=>v.builtIn),S=a.filter(v=>!v.builtIn);return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(ws,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",f?"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(Nl,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(Zt,{className:"size-4"})})})]})]})}),e.jsx(Je,{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(an,{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(v=>e.jsx(qa,{agent:v,isSelected:o===v.name,onSelect:()=>{i(v.name),f&&m(!1)},onDuplicate:()=>h(v),getAgentModeIcon:g},v.name))]}),S.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"}),S.map(v=>e.jsx(qa,{agent:v,isSelected:o===v.name,onSelect:()=>{i(v.name),f&&m(!1)},onDelete:()=>p(v),onDuplicate:()=>h(v),getAgentModeIcon:g},v.name))]})]})}),e.jsxs(vs,{children:[e.jsxs(Ss,{children:[e.jsx(js,{children:"Create New Agent"}),e.jsx(qs,{children:"Enter a unique name for your new agent"})]}),e.jsx(kt,{value:r,onChange:v=>s(v.target.value),placeholder:"Agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:v=>{v.key==="Enter"&&u()}}),e.jsxs(Er,{children:[e.jsx(De,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cs,{onClick:u,children:"Create"})]})]})]})})},qa=({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(Rt,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(jn,{className:"h-3.5 w-3.5"})})}),e.jsxs(_t,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(gt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(ks,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),!r.builtIn&&n&&e.jsxs(gt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ps,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})});function vr({className:r,variant:s,...t}){return e.jsx(De,{variant:s,size:"sm",className:T("h-6 px-2 text-xs",r),...t})}const Us=fe.forwardRef(({className:r,...s},t)=>e.jsx(Je,{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}));Us.displayName="Textarea";const Ka="mobile-overlay-root",Qf=()=>{if(typeof document>"u")return null;let r=document.getElementById(Ka);return r||(r=document.createElement("div"),r.id=Ka,document.body.appendChild(r)),r},Wt=({open:r,title:s,onClose:t,children:n,footer:o,className:a,renderHeader:i})=>{const c=l.useRef(null);if(typeof document<"u"&&!c.current&&(c.current=Qf()),l.useEffect(()=>{if(!r)return;const m=document.body.style.overflow;document.body.style.overflow="hidden";const f=u=>{u.key==="Escape"&&t()};return document.addEventListener("keydown",f),()=>{document.body.style.overflow=m,document.removeEventListener("keydown",f)}},[r,t]),!r||!c.current)return null;const d=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:T("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),onClick:m=>m.stopPropagation(),children:[(()=>{const m=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(os,{className:"h-4 w-4"})});return i?i(m):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:s}),m]})})(),e.jsx(Je,{outerClassName:"max-h-[min(70vh,520px)]",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 id.createPortal(d,c.current)},ep="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",tp="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",sp=Object.assign({"../assets/provider-logos/gocode.svg":ep,"../assets/provider-logos/kimi-for-coding.svg":tp}),po=new Map;for(const[r,s]of Object.entries(sp)){const t=r.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&s&&po.set(t[1].toLowerCase(),s)}function El(r){const s=r?.toLowerCase()??null,t=s?po.has(s):!1,n=s?po.get(s)??null:null,[o,a]=fe.useState(t?"local":"remote");fe.useEffect(()=>{a(t?"local":"remote")},[t,s]);const i=fe.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 ss=({providerId:r,alt:s,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=El(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})},Tl=({providerId:r,modelId:s,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=xt(),i=Re(b=>b.isMobile),{isMobile:c}=Ct(),d=i||c,[m,f]=l.useState(!1),[u,p]=l.useState(new Set),h=()=>f(!1),g=b=>{p(w=>{const j=new Set(w);return j.has(b)?j.delete(b):j.add(b),j})},x=b=>{const w=b?.name||b?.id||"",j=String(w);return j.length>40?j.substring(0,37)+"...":j},S=(b,w)=>{const j=`${b}/${w}`;return a.get(j)},v=(b,w)=>{t(b,w)},k=()=>d?e.jsx(Wt,{open:m,onClose:h,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[o.map(b=>{const w=Array.isArray(b.models)?b.models:[];if(w.length===0)return null;const j=b.id===r,y=u.has(b.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left",onClick:()=>g(b.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{providerId:b.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:b.name}),j&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),y?e.jsx(wt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(xs,{className:"h-3 w-3 text-muted-foreground"})]}),y&&e.jsx("div",{className:"border-t border-border/20",children:w.map(C=>{const M=b.id===r&&C.id===s,N=S(b.id,C.id);return e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",M?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{v(b.id,C.id),h()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:x(C)}),typeof N?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:N.description})]}),M&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},C.id)})})]},b.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{v("",""),h()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[d?e.jsxs("button",{type:"button",onClick:()=>f(!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(ss,{providerId:r,className:"h-3.5 w-3.5"}):e.jsx(ps,{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(wt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Rt,{children:[e.jsx(Lt,{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(ss,{providerId:r,className:"h-3 w-3 flex-shrink-0"}),e.jsx(ps,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(ps,{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(wt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(_t,{className:"max-w-[300px]",children:[o.map(b=>{const w=Array.isArray(b.models)?b.models:[];return w.length===0?e.jsxs(gt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(ss,{providerId:b.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),b.name," (No models)"]},b.id):e.jsxs(pl,{children:[e.jsxs(hl,{className:"typography-meta",children:[e.jsx(ss,{providerId:b.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),b.name]}),e.jsx(gl,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Je,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:w.map(j=>{const y=S(b.id,j.id);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{v(b.id,j.id)},children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:x(j)}),typeof y?.description=="string"&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:y.description})]})},j.id)})})})]},b.id)}),e.jsx(gt,{className:"typography-meta",onSelect:()=>v("",""),children:e.jsx("span",{className:"text-muted-foreground",children:"No model (optional)"})})]})]}),k()]})},rp=()=>{const{tools:r}=Gs(),[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 m=await r.getAvailableTools();if(c)return;t(m)}catch(m){if(c)return;const f=m instanceof Error?m.message:"Failed to fetch tools";console.error("Failed to fetch available tools:",f),i(f),t([])}finally{c||o(!1)}})(),()=>{c=!0}},[r]),{tools:s,isLoading:n,error:a}},np=()=>{const{selectedAgentName:r,getAgentByName:s,createAgent:t,updateAgent:n,agents:o}=or();xt();const{tools:a}=rp(),i=r?s(r):null,c=r&&!i,[d,m]=l.useState(""),[f,u]=l.useState(""),[p,h]=l.useState("subagent"),[g,x]=l.useState(""),[S,v]=l.useState(void 0),[k,b]=l.useState(void 0),[w,j]=l.useState(""),[y,C]=l.useState({}),[M,N]=l.useState("allow"),[A,D]=l.useState("allow"),[I,z]=l.useState("ask"),[E,$]=l.useState(!1);l.useEffect(()=>{if(c)m(r||""),u(""),h("subagent"),x(""),v(void 0),b(void 0),j(""),C({}),N("allow"),D("allow"),z("ask");else if(i&&(m(i.name),u(i.description||""),h(i.mode||"subagent"),i.model?.providerID&&i.model?.modelID?x(`${i.model.providerID}/${i.model.modelID}`):x(""),v(i.temperature),b(i.topP),j(i.prompt||""),C(i.tools||{}),i.permission)){const _=i.permission.edit;(_==="allow"||_==="ask"||_==="deny"||_==="full")&&N(_),i.permission.webfetch&&D(i.permission.webfetch),typeof i.permission.bash=="string"&&z(i.permission.bash)}},[i,c,r,o]);const V=async()=>{if(!d.trim()){ge.error("Agent name is required");return}$(!0);try{const _=g.trim(),W={name:d.trim(),description:f.trim()||void 0,mode:p,model:_===""?null:_,temperature:S,top_p:k,prompt:w.trim()||void 0,tools:Object.keys(y).length>0?y:void 0,permission:{edit:M,webfetch:A,bash:I}};let ae;c?ae=await t(W):ae=await n(d,W),ae?ge.success(c?"Agent created successfully":"Agent updated successfully"):ge.error(c?"Failed to create agent":"Failed to update agent")}catch(_){console.error("Error saving agent:",_),ge.error("An error occurred while saving")}finally{$(!1)}},Y=_=>{C(W=>({...W,[_]:!W[_]}))},L=_=>{const W={};a.forEach(ae=>{W[ae]=_}),C(W)};return r?e.jsxs(Je,{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(kt,{value:d,onChange:_=>m(_.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(Us,{value:f,onChange:_=>u(_.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(vr,{variant:p==="primary"?"default":"outline",onClick:()=>h("primary"),className:T("gap-2",p==="primary"?void 0:"text-foreground"),children:[e.jsx(Nr,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(vr,{variant:p==="subagent"?"default":"outline",onClick:()=>h("subagent"),className:T("gap-2",p==="subagent"?void 0:"text-foreground"),children:[e.jsx(Bi,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(vr,{variant:p==="all"?"default":"outline",onClick:()=>h("all"),className:T("gap-2",p==="all"?void 0:"text-foreground"),children:[e.jsx(Oi,{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(Tl,{providerId:g?g.split("/")[0]:"",modelId:g?g.split("/")[1]:"",onChange:(_,W)=>{x(_&&W?`${_}/${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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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,(S!==void 0?S:.7)-.1);v(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(oa,{className:"h-3.5 w-3.5"})}),e.jsx(kt,{type:"text",inputMode:"decimal",value:S!==void 0?S:"",onChange:_=>{const W=_.target.value;if(W===""){v(void 0);return}const ae=parseFloat(W);!isNaN(ae)&&ae>=0&&ae<=2&&v(ae)},onBlur:_=>{const W=_.target.value;if(W!==""){const ae=parseFloat(W);if(!isNaN(ae)){const je=Math.max(0,Math.min(2,ae));v(parseFloat(je.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,(S!==void 0?S:.7)+.1);v(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(Zt,{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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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);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(oa,{className:"h-3.5 w-3.5"})}),e.jsx(kt,{type:"text",inputMode:"decimal",value:k!==void 0?k:"",onChange:_=>{const W=_.target.value;if(W===""){b(void 0);return}const ae=parseFloat(W);!isNaN(ae)&&ae>=0&&ae<=1&&b(ae)},onBlur:_=>{const W=_.target.value;if(W!==""){const ae=parseFloat(W);if(!isNaN(ae)){const je=Math.max(0,Math.min(1,ae));b(parseFloat(je.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);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(Zt,{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(Us,{value:w,onChange:_=>j(_.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Available Tools"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select tools this agent can access"})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{variant:"outline",size:"sm",onClick:()=>L(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(De,{variant:"outline",size:"sm",onClick:()=>L(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(_=>e.jsx("button",{type:"button",onClick:()=>Y(_),className:T("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",y[_]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:_},_))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure permission levels for different operations"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Edit Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:M==="full"?"default":"outline",onClick:()=>N("full"),className:"h-6 px-2 text-xs",children:"Full"}),e.jsx(De,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>N("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>N("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:M==="deny"?"default":"outline",onClick:()=>N("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Controls file editing permissions."}),e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Full:"})," Auto-approves all tool requests"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Allows file editing with standard checks"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompts for confirmation before editing"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Blocks all file editing operations"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Bash Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:I==="allow"?"default":"outline",onClick:()=>z("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:I==="ask"?"default":"outline",onClick:()=>z("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:I==="deny"?"default":"outline",onClick:()=>z("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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run bash commands without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before execution"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all bash command execution"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"WebFetch Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(De,{size:"sm",variant:A==="allow"?"default":"outline",onClick:()=>D("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(De,{size:"sm",variant:A==="ask"?"default":"outline",onClick:()=>D("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(De,{size:"sm",variant:A==="deny"?"default":"outline",onClick:()=>D("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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Fetch web content without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before fetching"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all web content access"]})]})})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(De,{size:"sm",variant:"default",onClick:V,disabled:E,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Co,{className:"h-3 w-3"}),E?"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(an,{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"})]})})},op=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedCommandName:o,commands:a,setSelectedCommand:i,deleteCommand:c,loadCommands:d}=ar(),{setSidebarOpen:m}=Re(),{isMobile:f}=Ct();l.useEffect(()=>{d()},[d]);const u=()=>{if(!r.trim()){ge.error("Command name is required");return}const g=r.trim().replace(/\s+/g,"-");if(a.some(x=>x.name===g)){ge.error("A command with this name already exists");return}i(g),s(""),n(!1),f&&m(!1)},p=async g=>{window.confirm(`Are you sure you want to delete command "${g.name}"?`)&&(await c(g.name)?ge.success(`Command "${g.name}" deleted successfully`):ge.error("Failed to delete command"))},h=g=>{const x=g.name;let S=1,v=`${x}-copy`;for(;a.some(k=>k.name===v);)S++,v=`${x}-copy-${S}`;i(v),n(!1),f&&m(!1)};return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(ws,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",f?"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(Nl,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(Zt,{className:"size-4"})})})]})]})}),e.jsx(Je,{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(Fs,{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(ap,{command:g,isSelected:o===g.name,onSelect:()=>{i(g.name),f&&m(!1)},onDelete:()=>p(g),onDuplicate:()=>h(g)},g.name))})}),e.jsxs(vs,{children:[e.jsxs(Ss,{children:[e.jsx(js,{children:"Create New Command"}),e.jsx(qs,{children:"Enter a unique name for your new slash command"})]}),e.jsx(kt,{value:r,onChange:g=>s(g.target.value),placeholder:"Command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:g=>{g.key==="Enter"&&u()}}),e.jsxs(Er,{children:[e.jsx(De,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Cs,{onClick:u,children:"Create"})]})]})]})})},ap=({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(Rt,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(jn,{className:"h-3.5 w-3.5"})})}),e.jsxs(_t,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(gt,{onClick:a=>{a.stopPropagation(),o()},children:[e.jsx(ks,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(gt,{onClick:a=>{a.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ps,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})}),ip=({agentName:r,onChange:s,className:t})=>{const{agents:n,loadAgents:o}=or(),a=Re(h=>h.isMobile),{isMobile:i}=Ct(),c=a||i,[d,m]=l.useState(!1);l.useEffect(()=>{o()},[o]);const f=()=>m(!1),u=h=>{s(h)},p=()=>c?e.jsx(Wt,{open:d,onClose:f,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:()=>{u(h.name),f()},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:()=>{u(""),f()},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:()=>m(!0),className:T("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(an,{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(wt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Rt,{children:[e.jsx(Lt,{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(an,{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(wt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(_t,{className:"max-w-[300px]",children:[n.map(h=>e.jsx(gt,{className:"typography-meta",onSelect:()=>u(h.name),children:e.jsx("span",{className:"font-medium",children:h.name})},h.name)),e.jsx(gt,{className:"typography-meta",onSelect:()=>u(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),p()]})},lp=()=>{const{selectedCommandName:r,getCommandByName:s,createCommand:t,updateCommand:n,commands:o}=ar(),a=r?s(r):null,i=r&&!a,[c,d]=l.useState(""),[m,f]=l.useState(""),[u,p]=l.useState(""),[h,g]=l.useState(""),[x,S]=l.useState(""),[v,k]=l.useState(!1),[b,w]=l.useState(!1);l.useEffect(()=>{i?(d(r||""),f(""),p(""),g(""),S(""),k(!1)):a&&(d(a.name),f(a.description||""),p(a.agent||""),g(a.model||""),S(a.template||""),k(a.subtask||!1))},[a,i,r,o]);const j=async()=>{if(!c.trim()){ge.error("Command name is required");return}if(!x.trim()){ge.error("Command template is required");return}w(!0);try{const y=u.trim(),C=h.trim(),M=x.trim(),N={name:c.trim(),description:m.trim()||void 0,agent:y===""?null:y,model:C===""?null:C,template:M,subtask:v};let A;i?A=await t(N):A=await n(c,N),A?ge.success(i?"Command created successfully":"Command updated successfully"):ge.error(i?"Failed to create command":"Failed to update command")}catch(y){console.error("Error saving command:",y),ge.error("An error occurred while saving")}finally{w(!1)}};return r?e.jsxs(Je,{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(kt,{value:c,onChange:y=>d(y.target.value),placeholder:"my-command",disabled:!i}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Used with slash (/) prefix in chat"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Us,{value:m,onChange:y=>f(y.target.value),placeholder:"What does this command do?",rows:3})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model & Agent Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and agent for command execution"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(ip,{agentName:u,onChange:y=>p(y)}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Agent to execute this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(Tl,{providerId:h?h.split("/")[0]:"",modelId:h?h.split("/")[1]:"",onChange:(y,C)=>{g(y&&C?`${y}/${C}`:"")}}),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:v,onChange:y=>k(y.target.checked),className:"sr-only"}),e.jsx("div",{className:T("w-5 h-5 rounded border-2 flex items-center justify-center",v?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:v&&e.jsx(Nt,{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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(Us,{value:x,onChange:y=>S(y.target.value),placeholder:`Your command template here...
19
+
20
+ Use $ARGUMENTS to reference user input.
21
+ Use !\`shell command\` to inject shell output.
22
+ 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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Replaces with the full contents of the specified file.",e.jsx("br",{}),"Example: @package.json includes the package.json content in the prompt"]})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(De,{size:"sm",variant:"default",onClick:j,disabled:b,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Co,{className:"h-3 w-3"}),b?"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(Fs,{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"})]})})},Il=({sectionId:r,variant:s})=>{const t=Jf[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:Ga[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:Ga[r]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60",children:"Coming soon..."})]})},cp=()=>e.jsx(Je,{outerClassName:"h-full",className:"px-3 py-2",children:e.jsx(Il,{sectionId:"providers",variant:"sidebar"})}),dp=()=>e.jsx(Je,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:e.jsx(Il,{sectionId:"providers",variant:"page"})}),An=It()(Bt(as((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 sm();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 am("");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 rm(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 nm(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 om(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:is(()=>Ut()),partialize:r=>({selectedProfileId:r.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=An);const up={branch:Tt,briefcase:Do,house:Ao,graduation:Mo,code:Ts,heart:$i},mp={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},fp=()=>{const{selectedProfileId:r,profiles:s,globalIdentity:t,setSelectedProfile:n,deleteProfile:o,loadProfiles:a,loadGlobalIdentity:i}=An(),{setSidebarOpen:c}=Re(),{isMobile:d}=Ct();l.useEffect(()=>{a(),i()},[a,i]);const m=()=>{n("new"),d&&c(!1)},f=async u=>{window.confirm(`Are you sure you want to delete profile "${u.name}"?`)&&(await o(u.id)?ge.success(`Profile "${u.name}" deleted successfully`):ge.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(De,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",onClick:m,children:e.jsx(Zt,{className:"size-4"})})]})]})}),e.jsxs(Je,{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(Ya,{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(Tt,{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(u=>e.jsx(Ya,{profile:u,isSelected:r===u.id,onSelect:()=>{n(u.id),d&&c(!1)},onDelete:()=>f(u)},u.id))})]})]})},Ya=({profile:r,isSelected:s,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=up[r.icon||"branch"]||Tt,i=mp[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(Rt,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(jn,{className:"h-3.5 w-3.5"})})}),e.jsx(_t,{align:"end",className:"w-fit min-w-20",children:e.jsxs(gt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ps,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})})},Xa=[{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)"}],pp=[{key:"branch",Icon:Tt,label:"Branch"},{key:"briefcase",Icon:Do,label:"Work"},{key:"house",Icon:Ao,label:"Personal"},{key:"graduation",Icon:Mo,label:"School"},{key:"code",Icon:Ts,label:"Code"}],hp=()=>{const{selectedProfileId:r,getProfileById:s,createProfile:t,updateProfile:n,deleteProfile:o}=An(),a=l.useMemo(()=>r&&r!=="new"?s(r):null,[r,s]),i=r==="new",c=r==="global",[d,m]=l.useState(""),[f,u]=l.useState(""),[p,h]=l.useState(""),[g,x]=l.useState(""),[S,v]=l.useState("keyword"),[k,b]=l.useState("branch"),[w,j]=l.useState(!1);l.useEffect(()=>{i?(m(""),u(""),h(""),x(""),v("keyword"),b("branch")):a&&(m(a.name),u(a.userName),h(a.userEmail),x(a.sshKey||""),v(a.color||"keyword"),b(a.icon||"branch"))},[a,i,r]);const y=async()=>{if(!f.trim()||!p.trim()){ge.error("User name and email are required");return}j(!0);try{const N={name:d.trim()||f.trim(),userName:f.trim(),userEmail:p.trim(),sshKey:g.trim()||null,color:S,icon:k};let A;if(i)A=await t(N);else if(r)A=await n(r,N);else return;A?ge.success(i?"Profile created successfully":"Profile updated successfully"):ge.error(i?"Failed to create profile":"Failed to update profile")}catch(N){console.error("Error saving profile:",N),ge.error("An error occurred while saving")}finally{j(!1)}},C=async()=>{if(!(!r||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(r)?ge.success("Profile deleted successfully"):ge.error("Failed to delete profile")}catch(N){console.error("Error deleting profile:",N),ge.error("An error occurred while deleting")}},M=l.useMemo(()=>Xa.find(A=>A.key===S)?.cssVar||"var(--syntax-keyword)",[S]);return r?e.jsxs(Je,{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(kt,{value:d,onChange:N=>m(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:Xa.map(N=>e.jsx("button",{onClick:()=>v(N.key),className:T("w-8 h-8 rounded-lg border-2 transition-all",S===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:pp.map(N=>{const A=N.Icon;return e.jsx("button",{onClick:()=>b(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(A,{className:"w-4 h-4",style:{color:M}})},N.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(kt,{value:f,onChange:N=>u(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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(kt,{type:"email",value:p,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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Gt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(kt,{value:g,onChange:N=>x(N.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!c&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(De,{size:"sm",variant:"destructive",onClick:C,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Ps,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:T("flex gap-2",i&&"ml-auto"),children:e.jsxs(De,{size:"sm",variant:"default",onClick:y,disabled:w,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Co,{className:"h-3 w-3"}),w?"Saving...":"Save Profile"]})})]})]})]}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(kn,{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"})]})})},gp=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Ja=[{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."}],yp=()=>{const r=Re(i=>i.showReasoningTraces),s=Re(i=>i.setShowReasoningTraces),t=Re(i=>i.diffLayoutPreference),n=Re(i=>i.setDiffLayoutPreference),{themeMode:o,setThemeMode:a}=ir();return e.jsxs("div",{className:"w-full space-y-8",children:[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:gp.map(i=>e.jsx(vr,{variant:o===i.value?"default":"outline",className:T(o===i.value?void 0:"text-foreground"),onClick:()=>a(i.value),children:i.label},i.value))})]}),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:Ja.map(i=>e.jsx(vr,{variant:t===i.id?"default":"outline",className:T(t===i.id?void 0:"text-foreground"),onClick:()=>n(i.id),children:i.label},i.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Ja.find(i=>i.id===t)?.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:r,onChange:i=>s(i.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]})]})},xp=()=>e.jsx(Je,{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(yp,{})}),Za=(()=>{const r=Ml.filter(n=>n.id!=="sessions"),s=r.find(n=>n.id==="settings"),t=r.filter(n=>n.id!=="settings");return s?[s,...t]:r})(),bp=({isOpen:r,onClose:s})=>{const[t,n]=l.useState("settings"),[o,a]=l.useState(!1),{isMobile:i}=Ct();l.useEffect(()=>{r&&(n("settings"),a(!1))},[r]);const c=l.useCallback(S=>{n(S),i&&a(!1)},[i]),d=l.useCallback(()=>{i&&a(!0)},[i]),m=()=>{if(t==="settings")return null;const S=(()=>{switch(t){case"agents":return e.jsx(Zf,{});case"commands":return e.jsx(op,{});case"providers":return e.jsx(cp,{});case"git-identities":return e.jsx(fp,{});default:return null}})();return i?e.jsx("div",{onClick:d,children:S}):S},f=()=>{switch(t){case"agents":return e.jsx(np,{});case"commands":return e.jsx(lp,{});case"providers":return e.jsx(dp,{});case"git-identities":return e.jsx(hp,{});case"settings":return e.jsx(xp,{});default:return null}},u=Za.find(S=>S.id===t),p=i,h=e.jsxs(Ss,{className:"border-b border-border/40 px-6 pb-4 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)]",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[i&&o&&e.jsxs(De,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(aa,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx(js,{className:"typography-ui-header",children:"Settings"})]}),u&&e.jsx(qs,{className:"typography-meta text-muted-foreground hidden sm:block",children:u.description})]}),g=e.jsxs("div",{className:"flex flex-1 flex-col 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:Za.map(({id:S,label:v,icon:k})=>{const b=t===S,w=k;return e.jsxs("button",{onClick:()=>c(S),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",b?"text-primary":"text-muted-foreground hover:text-foreground"),"aria-pressed":b,"aria-label":v,children:[e.jsx(w,{className:T("h-5 w-5 sm:h-4 sm:w-4"),weight:"regular"}),e.jsx("span",{className:"hidden sm:inline",children:v})]},S)})}),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:`${xn}px`,minWidth:`${xn}px`},children:e.jsx(Xt,{children:m()})}),(t==="settings"||!i||o)&&e.jsx("div",{className:T("flex-1 overflow-hidden bg-background",i&&"w-full"),children:e.jsx(Xt,{children:f()})})]})]}),x=e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[!p&&h,g]});return p?e.jsx(Wt,{open:r,onClose:s,title:"Settings",className:"max-w-full",renderHeader:S=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsxs("div",{className:"relative flex flex-1 items-center justify-center",children:[o&&e.jsxs(De,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(aa,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx("span",{className:"typography-ui-header",children:"Settings"})]}),S]}),children:g}):e.jsx(ws,{open:r,onOpenChange:S=>!S&&s(),children:e.jsx(vs,{className:T("flex flex-col gap-0 p-0","h-[88vh] w-[65vw] max-w-[900px]"),children:x})})};function Fl({className:r,...s}){return e.jsx(Vs,{"data-slot":"command",className:T("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",r),...s})}function wp({title:r="Command Palette",description:s="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(ws,{...a,children:[e.jsxs(Ss,{className:"sr-only",children:[e.jsx(js,{children:r}),e.jsx(qs,{children:s})]}),e.jsx(vs,{className:T("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Fl,{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 Pl({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(Eo,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Vs.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 Rl({className:r,children:s,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(Je,{as:Vs.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 Ll({...r}){return e.jsx(Vs.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...r})}function Sr({className:r,...s}){return e.jsx(Vs.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 ho({className:r,...s}){return e.jsx(Vs.Separator,{"data-slot":"command-separator",className:T("bg-border -mx-1 h-px",r),...s})}function At({className:r,...s}){return e.jsx(Vs.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 Os({className:r,...s}){const t=a=>{const i=a.trim().toLowerCase();return i==="ctrl"||i==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?e.jsx(nr,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(gr,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof s.children=="string"?s.children:"",o=n?n.split("+").map(a=>a.trim()).filter(Boolean):[];return e.jsx("span",{"data-slot":"command-shortcut",className:T("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",r),...s,children:o.length>0?o.map((a,i)=>e.jsxs(fe.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):s.children})}const vp=()=>{const{isCommandPaletteOpen:r,setCommandPaletteOpen:s,setHelpDialogOpen:t,setSessionCreateDialogOpen:n,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,toggleSidebar:c}=Re(),{createSession:d,setCurrentSession:m,getSessionsByDirectory:f,initializeNewOpenChamberSession:u}=ye(),{currentDirectory:p}=yt(),{agents:h}=xt(),{themeMode:g,setThemeMode:x}=ir(),S=()=>{s(!1)},v=async()=>{const E=await d();E&&u(E.id,h),S()},k=E=>{m(E),S()},b=E=>{x(E),S()},w=()=>{t(!0),S()},j=()=>{n(!0),S()},{isMobile:y}=Ct(),C=()=>{if(y){const{isSessionSwitcherOpen:E}=Re.getState();i(!E)}else c();S()},M=()=>{o("git"),S()},N=()=>{o("terminal"),S()},A=()=>{a(!0),S()},D=()=>{km(),S()},I=f(p??""),z=l.useMemo(()=>I.slice(0,5),[I]);return e.jsxs(wp,{open:r,onOpenChange:s,children:[e.jsx(Pl,{placeholder:"Type a command or search..."}),e.jsxs(Rl,{children:[e.jsx(Ll,{children:"No results found."}),e.jsxs(Sr,{heading:"Actions",children:[e.jsxs(At,{onSelect:C,children:[e.jsx(kr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsx(Os,{children:"Ctrl + L"})]}),e.jsxs(At,{onSelect:v,children:[e.jsx(Zt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Os,{children:"Ctrl + N"})]}),e.jsxs(At,{onSelect:j,children:[e.jsx(Tt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Os,{children:"Shift + Ctrl + N"})]}),e.jsxs(At,{onSelect:w,children:[e.jsx(Cr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsx(Os,{children:"Ctrl + H"})]}),e.jsxs(At,{onSelect:M,children:[e.jsx(Tt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsx(Os,{children:"Ctrl + G"})]}),e.jsxs(At,{onSelect:N,children:[e.jsx(Fs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsx(Os,{children:"Ctrl + T"})]}),e.jsxs(At,{onSelect:A,children:[e.jsx(on,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsx(Os,{children:"Ctrl + ,"})]}),e.jsxs(At,{onSelect:D,children:[e.jsx(rr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(ho,{}),e.jsxs(Sr,{heading:"Theme",children:[e.jsxs(At,{onSelect:()=>b("light"),children:[e.jsx(ld,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),g==="light"&&e.jsx(Nt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(At,{onSelect:()=>b("dark"),children:[e.jsx(cd,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),g==="dark"&&e.jsx(Nt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(At,{onSelect:()=>b("system"),children:[e.jsx(zi,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),g==="system"&&e.jsx(Nt,{className:"ml-auto h-4 w-4"})]})]}),z.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ho,{}),e.jsx(Sr,{heading:"Recent Sessions",children:z.map(E=>e.jsxs(At,{onSelect:()=>k(E.id),children:[e.jsx(No,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:E.title||"Untitled Session"})]},E.id))})]})]})]})},Sp=(r,s)=>{const t=r.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(jo,{className:"h-3.5 w-3.5"},`ctrl-${s}`):t==="shift"||t==="⇧"?e.jsx(ud,{className:"h-3.5 w-3.5"},`shift-${s}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(nr,{className:"h-3.5 w-3.5"},`cmd-${s}`):e.jsx("span",{className:"text-xs font-medium",children:r.trim()},`key-${s}`)},jp=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:"+"}),Sp(t,n)]},`${t}-${n}`))},kp=()=>{const{isHelpDialogOpen:r,setHelpDialogOpen:s}=Re(),t=[{category:"Navigation & Commands",items:[{keys:["Ctrl + X"],description:"Open Command Palette",icon:nr},{keys:["Ctrl + H"],description:"Show Keyboard Shortcuts (this dialog)",icon:Cr},{keys:["Ctrl + L"],description:"Toggle Session Sidebar",icon:kr}]},{category:"Session Management",items:[{keys:["Ctrl + N"],description:"Create New Session",icon:Zt},{keys:["Shift + Ctrl + N"],description:"Open Session Creator (worktree support)",icon:Tt},{keys:["Ctrl + I"],description:"Focus Chat Input",icon:Hi},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Zs}]},{category:"Interface",items:[{keys:["⌘ + /","Ctrl + /"],description:"Cycle Theme (Light → Dark → System)",icon:dd},{keys:["Ctrl + G"],description:"Open Git Panel",icon:Tt},{keys:["Ctrl + T"],description:"Open Terminal",icon:Fs},{keys:["Ctrl + ,"],description:"Open Settings",icon:on}]}];return e.jsx(ws,{open:r,onOpenChange:s,children:e.jsxs(vs,{className:"max-w-2xl",children:[e.jsxs(Ss,{children:[e.jsxs(js,{className:"flex items-center gap-2",children:[e.jsx(on,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(qs,{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:jp(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(Cr,{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"})]})]})]})})]})})},Wn=new Set,Un=new Set,Vn=new Set,Js={onDeleteRequest(r){return Wn.add(r),()=>{Wn.delete(r)}},requestDelete(r){r.sessions.length&&Wn.forEach(s=>s(r))},onCreateRequest(r){return Un.add(r),()=>{Un.delete(r)}},requestCreate(r){const s=r??{};Un.forEach(t=>t(s))},onDirectoryRequest(r){return Vn.add(r),()=>{Vn.delete(r)}},requestDirectoryDialog(){Vn.forEach(r=>r())}},Np=".openchamber",Qa="oc.sessions.groupCollapse",ei="oc.sessions.expandedParents",ti=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(",","")},us=r=>{if(!r)return null;const s=r.replace(/\\/g,"/").replace(/\/+$/,"");return s.length===0?"/":s},Cp=(r,s)=>{const t=us(r),n=Array.from(s.values())[0];if(n?.projectDirectory)return us(n.projectDirectory);if(!t)return null;const o=`/${Np}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},go=({mobileVariant:r=!1,onSessionSelected:s,allowReselect:t=!1,hideDirectoryControls:n=!1})=>{const[o,a]=l.useState(null),[i,c]=l.useState(""),[d,m]=l.useState(null),f=l.useRef(null),[u,p]=l.useState(new Set),[h,g]=l.useState(()=>new Map),x=l.useRef(new Set),S=l.useMemo(()=>Ut(),[]),[v,k]=l.useState(!1),[b,w]=l.useState(new Set),[j,y]=l.useState(null),[C,M]=l.useState(new Set),[N,A]=l.useState(null),D=yt(R=>R.currentDirectory),I=yt(R=>R.homeDirectory),z=yt(R=>R.setDirectory),E=xt(R=>R.agents),$=ye(R=>R.getSessionsByDirectory),V=ye(R=>R.currentSessionId),Y=ye(R=>R.setCurrentSession),L=ye(R=>R.updateSessionTitle),_=ye(R=>R.shareSession),W=ye(R=>R.unshareSession),ae=ye(R=>R.sessionMemoryState),je=ye(R=>R.sessionActivityPhase),Me=ye(R=>R.worktreeMetadata),$e=ye(R=>R.availableWorktrees),he=ye(R=>R.createSession),ie=ye(R=>R.initializeNewOpenChamberSession),Ne=ye(R=>R.setSessionDirectory),[Q,We]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const R=S.getItem(Qa);if(R){const J=JSON.parse(R);Array.isArray(J)&&w(new Set(J.filter(ue=>typeof ue=="string")))}const te=S.getItem(ei);if(te){const J=JSON.parse(te);Array.isArray(J)&&p(new Set(J.filter(ue=>typeof ue=="string")))}}catch{}},[S]),l.useEffect(()=>{typeof window>"u"||We(typeof window.opencodeDesktop<"u")},[]);const ne=$(D),B=l.useMemo(()=>[...ne].sort((R,te)=>(te.time?.created||0)-(R.time?.created||0)),[ne]);l.useEffect(()=>{if(!D){y(null);return}let R=!1;return Lo(D).then(te=>{R||y(te)}).catch(()=>{R||y(null)}),()=>{R=!0}},[D]);const we=l.useMemo(()=>new Map(B.map(R=>[R.id,R])),[B]),oe=l.useMemo(()=>{const R=new Map;return B.forEach(te=>{const J=te.parentID;J&&R.set(te.id,J)}),R},[B]),Z=l.useMemo(()=>{const R=new Map;return B.forEach(te=>{const J=te.parentID;if(!J)return;const ue=R.get(J)??[];ue.push(te),R.set(J,ue)}),R.forEach(te=>te.sort((J,ue)=>(ue.time?.created||0)-(J.time?.created||0))),R},[B]);l.useEffect(()=>{V&&p(R=>{const te=new Set(R);let J=oe.get(V)||null,ue=!1;for(;J;)te.has(J)||(te.add(J),ue=!0),J=oe.get(J)||null;return ue?te:R})},[V,oe]);const O=l.useMemo(()=>Cp(D,Me),[D,Me]);l.useEffect(()=>{const R=new Set;B.forEach(te=>{const J=us(te.directory??null);J&&R.add(J)}),O&&R.add(O),R.forEach(te=>{const J=h.get(te);J&&J!=="unknown"||x.current.has(te)||(x.current.add(te),Ae.listLocalDirectory(te).then(()=>{g(ue=>{const _e=new Map(ue);return _e.get(te)==="exists"?ue:(_e.set(te,"exists"),_e)})}).catch(()=>{g(ue=>{const _e=new Map(ue);return _e.get(te)==="missing"?ue:(_e.set(te,"missing"),_e)})}).finally(()=>{x.current.delete(te)}))})},[B,O,h]),l.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const re=l.useMemo(()=>Tn(D,I),[D,I]),ee=l.useMemo(()=>Pt(D,I),[D,I]),le=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."})]}),Se=l.useCallback((R,te)=>{if(!te){if(!t&&R===V){s?.(R);return}Y(R),s?.(R)}},[t,V,s,Y]),xe=l.useCallback(async()=>{o&&i.trim()&&(await L(o,i.trim()),a(null),c(""))},[o,i,L]),F=l.useCallback(()=>{a(null),c("")},[]),G=l.useCallback(async R=>{const te=await _(R.id);te&&te.share?.url?ge.success("Session shared",{description:"You can copy the link from the menu."}):ge.error("Unable to share session")},[_]),P=l.useCallback((R,te)=>{navigator.clipboard.writeText(R).then(()=>{m(te),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{ge.error("Failed to copy URL")})},[]),de=l.useCallback(async R=>{await W(R)?ge.success("Session unshared"):ge.error("Unable to unshare session")},[W]),be=l.useCallback(R=>{const te=[],J=ue=>{(Z.get(ue)??[]).forEach(it=>{te.push(it),J(it.id)})};return J(R),te},[Z]),Ie=ye(R=>R.deleteSession),Ye=ye(R=>R.deleteSessions),ct=l.useCallback(async R=>{const te=be(R.id);if(te.length===0)await Ie(R.id)?ge.success("Session deleted"):ge.error("Failed to delete session");else{const J=[R.id,...te.map(it=>it.id)],{deletedIds:ue,failedIds:_e}=await Ye(J);ue.length>0&&ge.success(`Deleted ${ue.length} session${ue.length===1?"":"s"}`),_e.length>0&&ge.error(`Failed to delete ${_e.length} session${_e.length===1?"":"s"}`)}},[be,Ie,Ye]),ze=l.useCallback(async R=>{if(!R){ge.error("No directory available for session creation");return}if(!v)try{k(!0);const te=await he(void 0,R);if(!te){ge.error("Failed to create session");return}ie(te.id,E),Ne(te.id,R)}catch(te){const J=te instanceof Error?te.message:"Failed to create session";ge.error(J)}finally{k(!1)}},[he,ie,Ne,E,v]),et=l.useCallback(()=>{Js.requestCreate({worktreeMode:"create"})},[]),Qe=l.useCallback(()=>{Q&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(R=>{R.success&&R.path?z(R.path,{showOverlay:!0}):R.error&&R.error!=="Directory selection cancelled"&&ge.error("Failed to select directory",{description:R.error})}).catch(R=>{console.error("Desktop: Error selecting directory:",R),ge.error("Failed to select directory")}):Js.requestDirectoryDialog()},[Q,z]),Ge=l.useCallback(R=>{p(te=>{const J=new Set(te);J.has(R)?J.delete(R):J.add(R);try{S.setItem(ei,JSON.stringify(Array.from(J)))}catch{}return J})},[S]),Le=l.useCallback(R=>{const te=Z.get(R.id)??[];return{session:R,children:te.map(J=>Le(J))}},[Z]),He=l.useMemo(()=>{const R=new Map,te=us(O??null),J=new Map,ue=new Set;$e.forEach(Ee=>{if(Ee.path){const Be=us(Ee.path)??Ee.path;ue.add(Be),J.set(Be,Ee)}});const _e=Ee=>{const Be=us(Ee.directory??null),me=Me.get(Ee.id),Te=((me?.path?ue.has(us(me.path)??me.path):!1)?me:null)??(Be?J.get(Be)??null:null),qe=!Te&&(Be&&te?Be===te:!Be&&!!te),at=qe?"main":Te?.path??Be??Ee.id,rt=Te?.path??Be??te??null;if(!R.has(at)){const ft=qe?"Main workspace":Te?.label||Te?.branch||Tn(rt||"",I)||"Worktree",U=Te?.relativePath?Pt(Te.relativePath,I):rt?Pt(rt,I):null;R.set(at,{id:at,label:ft,description:U,isMain:qe,worktree:Te,directory:rt,sessions:[]})}return R.get(at)};return B.filter(Ee=>{const Be=Ee.parentID;return Be?!we.has(Be):!0}).forEach(Ee=>{const Be=_e(Ee),me=Le(Ee);Be.sessions.push(me)}),R.has("main")||R.set("main",{id:"main",label:"Main workspace",description:te?Pt(te,I):null,isMain:!0,worktree:null,directory:te,sessions:[]}),J.forEach((Ee,Be)=>{const me=Ee.path;R.has(me)||R.set(me,{id:me,label:Ee.label||Ee.branch||Tn(Be,I)||"Worktree",description:Ee.relativePath?Pt(Ee.relativePath,I):Pt(Be,I),isMain:!1,worktree:Ee,directory:Be,sessions:[]})}),R.forEach(Ee=>{Ee.sessions.sort((Be,me)=>(me.session.time?.created||0)-(Be.session.time?.created||0))}),Array.from(R.values()).sort((Ee,Be)=>Ee.isMain!==Be.isMain?Ee.isMain?-1:1:(Ee.label||"").localeCompare(Be.label||""))},[B,Me,$e,O,I,Le,we]),ot=l.useCallback(R=>{w(te=>{const J=new Set(te);J.has(R)?J.delete(R):J.add(R);try{S.setItem(Qa,JSON.stringify(Array.from(J)))}catch{}return J})},[S]),dt=l.useCallback(R=>{M(te=>{const J=new Set(te);return J.has(R)?J.delete(R):J.add(R),J})},[]),pe=l.useCallback((R,te=0,J)=>{const ue=R.session,_e=us(ue.directory??null)??us(J??null),Ee=(_e?h.get(_e):null)==="missing",Be=ae.get(ue.id),me=V===ue.id,Oe=ue.title||"Untitled Session",Te=R.children.length>0,qe=u.has(ue.id),at=ue.summary?.additions,rt=ue.summary?.deletions,ft=typeof at=="number"||typeof rt=="number";if(o===ue.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(),xe()},children:[e.jsx(kt,{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"&&F()}}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6 p-0",type:"submit",children:e.jsx(Nt,{className:"h-4 w-4"})}),e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6 p-0",type:"button",onClick:F,children:e.jsx(os,{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:ti(ue.time?.created||Date.now())}),ue.share&&e.jsx(Dn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"})]})]},ue.id);const U=je?.get(ue.id)??"idle",ce=U==="busy"||U==="cooldown",se=Be&&Be.isZombie?e.jsx(ro,{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",me?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",Ee?"opacity-75":"",te>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:Ee,onClick:()=>Se(ue.id,Ee),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",ce&&"animate-pulse [animation-duration:1.8s]"),children:Oe})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Te?e.jsx("span",{role:"button",tabIndex:0,onClick:ve=>{ve.stopPropagation(),Ge(ue.id)},onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),ve.stopPropagation(),Ge(ue.id))},className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 flex-shrink-0 rounded-sm","aria-label":qe?"Collapse subsessions":"Expand subsessions",children:qe?e.jsx(wt,{className:"h-3 w-3"}):e.jsx(xs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:ti(ue.time?.created||Date.now())}),ue.share?e.jsx(Dn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,ft&&((at??0)!==0||(rt??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,at??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,rt??0)]})]}):null,Te?e.jsxs("span",{className:"truncate",children:[R.children.length," ",R.children.length===1?"task":"tasks"]}):null,Ee?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(ro,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[se,e.jsxs(Rt,{children:[e.jsx(Lt,{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(jn,{className:r?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(_t,{align:"end",className:"min-w-[180px]",children:[e.jsxs(gt,{onClick:()=>{a(ue.id),c(Oe)},className:"[&>svg]:mr-1",children:[e.jsx(ps,{className:"mr-1 h-4 w-4"}),"Rename"]}),ue.share?e.jsxs(e.Fragment,{children:[e.jsx(gt,{onClick:()=>{ue.share?.url&&P(ue.share.url,ue.id)},className:"[&>svg]:mr-1",children:d===ue.id?e.jsxs(e.Fragment,{children:[e.jsx(Nt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(ks,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(gt,{onClick:()=>de(ue.id),className:"[&>svg]:mr-1",children:[e.jsx(md,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(gt,{onClick:()=>G(ue),className:"[&>svg]:mr-1",children:[e.jsx(Dn,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(gt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>ct(ue),children:[e.jsx(Ps,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Te&&qe?R.children.map(ve=>pe(ve,te+1,_e??J)):null]},ue.id)},[h,ae,je,V,u,o,i,xe,F,Ge,Se,G,P,de,ct,d,r]);return e.jsxs("div",{className:T("flex h-full flex-col text-foreground overflow-x-hidden",r?"":Q?"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:Qe,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",!Q&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:ee||"/",children:[e.jsx("span",{className:T("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!Q&&"bg-sidebar/60"),children:e.jsx(Yt,{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:re||"/"})})]}),j?e.jsx("button",{type:"button",onClick:et,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",!Q&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",children:e.jsx(fd,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}):null]})}),e.jsx(Je,{outerClassName:"flex-1 min-h-0",className:T("space-y-1 pb-1 pl-2.5 pr-1",""),children:He.length===0?le:n&&He.length===1&&He[0].isMain?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:He[0].sessions.length===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."}):He[0].sessions.map(R=>pe(R,0,He[0].directory))}):He.map(R=>e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>ot(R.id),className:T("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b",!Q&&"bg-sidebar"),style:{borderColor:N===R.id?"var(--color-border)":b.has(R.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>A(R.id),onMouseLeave:()=>A(null),"aria-label":b.has(R.id)?"Expand group":"Collapse group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1",children:[e.jsx("span",{className:"typography-micro font-medium text-muted-foreground truncate group-hover/header:text-foreground",children:R.label}),!n&&e.jsx("span",{role:"button",tabIndex:0,"aria-disabled":v,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",v&&"opacity-40 cursor-default"),"aria-label":"Create session in this group",onClick:te=>{v||(te.stopPropagation(),ze(R.directory))},onKeyDown:te=>{v||(te.key==="Enter"||te.key===" ")&&(te.stopPropagation(),ze(R.directory))},children:e.jsx(Zt,{className:"h-4.5 w-4.5"})})]})}),b.has(R.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const te=C.has(R.id),J=7,ue=R.sessions.length,_e=te?R.sessions:R.sessions.slice(0,J),it=ue-_e.length;return e.jsxs(e.Fragment,{children:[_e.map(Ee=>pe(Ee,0,R.directory)),ue===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,it>0&&!te?e.jsxs("button",{type:"button",onClick:()=>dt(R.id),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",it," more ",it===1?"session":"sessions"]}):null,te&&ue>J?e.jsx("button",{type:"button",onClick:()=>dt(R.id),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})})()})]},R.id))})]})},Mp=Li("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 Ap({className:r,variant:s,size:t,...n}){return e.jsx(pd,{"data-slot":"toggle",className:T(Mp({variant:s,size:t,className:r})),...n})}const _l=()=>{const[r,s]=fe.useState(!1);fe.useEffect(()=>{s(Ht())},[]);const t=fe.useCallback(async a=>r?await Au(a):{success:!0,path:a},[r]),n=fe.useCallback(async a=>r?await Du(a):{success:!0},[r]),o=fe.useCallback(async a=>r?await Eu(a):{success:!0},[r]);return{isDesktop:r,requestAccess:t,startAccessing:n,stopAccessing:o}},Dp=({currentPath:r,onSelectPath:s,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:m})=>{const f=l.useMemo(()=>Ht(),[]),[u,p]=l.useState([]),[h,g]=l.useState(new Set),[x,S]=l.useState(!0),[v,k]=l.useState(!1),[b,w]=l.useState(""),[j,y]=l.useState(new Set),[C,M]=l.useState(null),[N,A]=l.useState(""),D=l.useRef(null),{requestAccess:I,startAccessing:z,isDesktop:E}=_l(),$=l.useRef(c),V=l.useCallback(O=>{if(!O)return O;if(O==="/"||O.length===0)return"/";let re=O;for(;re.length>1&&re.endsWith("/");)re=re.slice(0,-1);return re.length===0?"/":re},[]),Y=l.useMemo(()=>{if(!b)return null;const O=b.replace(/\\/g,"/");return V(O)},[b,V]),L=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const O=d.replace(/\\/g,"/"),re=V(O);if(re&&re!=="/")return re}return Y&&Y!=="/"?Y:null},[d,Y,V]),_=l.useMemo(()=>typeof m=="boolean"?!!(m&&L):!!L,[m,L]);l.useEffect(()=>{_||(S(!0),p([]))},[_]);const W=l.useCallback(O=>{if(!O||!_||!L)return!1;const re=O.replace(/\\/g,"/"),ee=V(re)??re;if(ee===L)return!0;const le=`${L}/`;return ee.startsWith(le)},[_,L,V]),ae=async O=>{if(_){if(a==="deferred"){s(O);return}if(E){const re=await I(O);re.success&&re.path?(await z(re.path),s(re.path)):(console.error("Failed to get directory access:",re.error),s(O))}else s(O)}};l.useEffect(()=>{let O=!1;const re=Se=>{if(!Se)return!1;const xe=V(Se.replace(/\\/g,"/"));return!xe||xe==="/"?!1:(w(typeof xe=="string"?xe:Se.replace(/\\/g,"/")),!0)};return(d?re(d):!1)||(async()=>{try{const Se=await Ae.getFilesystemHome();if(!O&&re(Se))return}catch(Se){console.warn("Failed to resolve filesystem home directory:",Se)}try{const Se=await Ae.getSystemInfo();if(!O&&re(Se?.homeDirectory))return}catch(Se){console.warn("Failed to resolve home directory from system info:",Se)}})(),()=>{O=!0}},[d,V]),l.useEffect(()=>{let O=!1;const re=xe=>{if(O)return;const F=xe.filter(G=>typeof G=="string"&&G.length>0).map(G=>{const P=G.replace(/\\/g,"/");return V(P)??P});y(new Set(F))},ee=()=>{try{const xe=localStorage.getItem("pinnedDirectories");if(!xe)return;const F=JSON.parse(xe);Array.isArray(F)&&re(F)}catch(xe){console.warn("Failed to load pinned directories from local storage:",xe)}},le=async()=>{try{let xe=[];if(f){const F=await qi();xe=Array.isArray(F?.pinnedDirectories)?F.pinnedDirectories:[]}else{const F=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(F.ok){const G=await F.json();xe=Array.isArray(G?.pinnedDirectories)?G.pinnedDirectories:[]}}if(O)return;re(xe)}catch(xe){console.warn("Failed to load pinned directories:",xe)}};ee();const Se=xe=>{const F=xe.detail;F&&Array.isArray(F.pinnedDirectories)&&re(F.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",Se),le(),()=>{O=!0,window.removeEventListener("openchamber:settings-synced",Se)}},[f,V]);const je=l.useRef(!0);l.useEffect(()=>{if(je.current){je.current=!1;return}const O={pinnedDirectories:Array.from(j)};fs(O)},[j]),l.useEffect(()=>{L&&y(O=>{const re=Array.from(O).map(ee=>V(ee.replace(/\\/g,"/"))??ee).filter(ee=>W(ee));return new Set(re)})},[L,W,V]),l.useEffect(()=>{$.current!==c&&($.current=c,g(new Set))},[c]);const Me=O=>{y(re=>{if(!W(O))return re;const ee=V(O.replace(/\\/g,"/"))??O.replace(/\\/g,"/"),le=new Set(re);return le.has(ee)?le.delete(ee):le.add(ee),le})},$e=l.useMemo(()=>Array.from(j).map(O=>V(O.replace(/\\/g,"/"))??O).filter(O=>W(O)).map(O=>({path:O,name:O.split("/").pop()||O})).sort((O,re)=>O.name.localeCompare(re.name)),[j,W,V]),he=l.useCallback(async O=>{const re=F=>c||!F.startsWith("."),ee=L;if(!_||!ee)return[];const le=O&&O.length>0?O:ee,Se=le?le.replace(/\\/g,"/"):null,xe=Se?V(Se)??Se:null;if(xe){const F=`${ee}/`;if(!(xe===ee||xe.startsWith(F)))return[]}try{return(await Ae.listLocalDirectory(O)).filter(G=>{if(!G.isDirectory||!re(G.name))return!1;const P=G.path.replace(/\\/g,"/"),de=V(P)??P,be=de===ee?ee:`${ee}/`;return de===ee||de.startsWith(be)}).map(G=>({name:G.name,path:G.path.replace(/\\/g,"/"),isDirectory:!0})).sort((G,P)=>G.name.localeCompare(P.name))}catch{try{const G=await Ae.getApiClient().file.list({query:{path:".",directory:O}});return G.data?G.data.filter(P=>{if(P.type!=="directory"||!P.name||!re(P.name))return!1;const de=String(P.absolute||P.path||P.name).replace(/\\/g,"/"),be=V(de)??de,Ie=be===ee?ee:`${ee}/`;return be===ee||be.startsWith(Ie)}).map(P=>({name:P.name||"",path:String(P.absolute||P.path||P.name).replace(/\\/g,"/"),isDirectory:!0})).filter(P=>P.name!=="").sort((P,de)=>P.name.localeCompare(de.name)):[]}catch{return[]}}},[c,L,V,_]),ie=l.useCallback(async()=>{if(!_||!L){S(!0),p([]);return}S(!0);try{const O=await he(L);p(O)}catch{}finally{S(!1)}},[_,L,he]);l.useEffect(()=>{_&&(n==="inline"||v)&&ie()},[n,v,_,ie]);const Ne=async O=>{if(!_)return;const re=h.has(O.path),ee=new Set(h);if(re){ee.delete(O.path),g(ee);return}ee.add(O.path),g(ee);const le=await he(O.path),Se=xe=>xe.map(F=>F.path===O.path?{...F,children:le}:F.children?{...F,children:Se(F.children)}:F);p(xe=>Se(xe))};l.useEffect(()=>{C&&D.current&&(D.current.focus(),D.current.select())},[C]);const Q=(O,re=[])=>{const ee="new_directory",le=re.map(G=>G.name);if(!le.includes(ee))return ee;let Se=1;const xe=new RegExp(`^${ee}(\\d+)$`);for(const G of le){const P=G.match(xe);if(P){const de=parseInt(P[1],10);de>Se&&(Se=de)}}let F=2;for(;le.includes(`${ee}${F}`);)F++;return`${ee}${Math.max(F,Se+1)}`},We=async O=>{if(_){if(h.has(O.path)){const re=Q(O.path,O.children);A(re)}else{const re=new Set(h);if(re.add(O.path),g(re),O.children){const ee=Q(O.path,O.children);A(ee)}else{const ee=await he(O.path),le=xe=>xe.map(F=>F.path===O.path?{...F,children:ee}:F.children?{...F,children:le(F.children)}:F);p(xe=>le(xe));const Se=Q(O.path,ee);A(Se)}}M(O.path)}},ne=async()=>{if(!C||!_)return;const O=N.trim()||"new_directory",re=`${C}/${O}`;try{await Ae.createDirectory(re);const ee=await he(C),le=Se=>Se.map(xe=>xe.path===C?{...xe,children:ee}:xe.children?{...xe,children:le(xe.children)}:xe);p(Se=>le(Se)),M(null),A("")}catch(ee){console.error("Failed to create directory:",ee)}},B=()=>{M(null),A("")},we=(O,re=0)=>{const ee=h.has(O.path),le=O.isDirectory,Se=j.has(O.path),xe=r===O.path,F=n==="inline",G=e.jsxs(e.Fragment,{children:[le&&e.jsx("button",{onClick:P=>{P.stopPropagation(),Ne(O)},className:"p-0.5 hover:bg-accent rounded",children:ee?e.jsx(wt,{className:"h-3 w-3"}):e.jsx(xs,{className:"h-3 w-3"})}),!le&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:P=>{P.stopPropagation(),ae(O.path),n==="dropdown"&&a==="immediate"&&k(!1)},onDoubleClick:P=>{P.stopPropagation(),i&&i(O.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",F&&xe?"text-primary":"text-foreground"),children:[ee?e.jsx(Yt,{className:T("h-3.5 w-3.5 text-muted-foreground",F&&xe&&"text-primary")}):e.jsx(Yt,{className:T("h-3.5 w-3.5 text-muted-foreground",F&&xe&&"text-primary")}),e.jsx("span",{className:T("typography-ui-label font-medium truncate",F&&xe?"text-primary":"text-foreground"),children:O.name})]}),e.jsx("button",{onClick:P=>{P.stopPropagation(),We(O)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Create new directory",children:e.jsx(Zt,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:P=>{P.stopPropagation(),Me(O.path)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:Se?"Unpin directory":"Pin directory",children:Se?e.jsx(En,{className:"h-3 w-3 text-primary"}):e.jsx(hd,{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",xe?"text-primary":"text-foreground"),style:{paddingLeft:`${re*12+8}px`},children:G}),ee&&e.jsxs(e.Fragment,{children:[C===O.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(re+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Yt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{ref:D,value:N,onChange:P=>A(P.target.value),onKeyDown:P=>{P.key==="Enter"?(P.preventDefault(),P.stopPropagation(),ne()):P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),B())},onBlur:ne,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),ne()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Nt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),B()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(os,{className:"h-3 w-3 text-muted-foreground"})})]}),O.children&&O.children.map(P=>we(P,re+1))]})]},O.path):e.jsxs("div",{children:[e.jsxs(gt,{className:T("flex items-center gap-1 cursor-pointer group",r===O.path&&"bg-accent"),style:{paddingLeft:`${re*12+8}px`},onSelect:P=>{P.preventDefault()},children:[le&&e.jsx("button",{onClick:P=>{P.stopPropagation(),Ne(O)},className:"p-0.5 hover:bg-accent rounded",children:ee?e.jsx(wt,{className:"h-3 w-3"}):e.jsx(xs,{className:"h-3 w-3"})}),!le&&e.jsx("div",{className:"w-4"}),G]}),ee&&e.jsxs("div",{children:[C===O.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(re+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Yt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{ref:D,value:N,onChange:P=>A(P.target.value),onKeyDown:P=>{P.key==="Enter"?(P.preventDefault(),P.stopPropagation(),ne()):P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),B())},onBlur:ne,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),ne()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Nt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:P=>{P.preventDefault(),P.stopPropagation(),B()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(os,{className:"h-3 w-3 text-muted-foreground"})})]}),O.children&&O.children.map(P=>we(P,re+1))]})]},O.path)},oe=(O,re)=>{if(n==="inline"){const ee=r===re;return e.jsxs("div",{className:T("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>ae(re),onDoubleClick:le=>{le.stopPropagation(),i&&i(re)},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",ee?"text-primary":"text-foreground"),children:[e.jsx(Yt,{className:T("h-3.5 w-3.5 text-muted-foreground",ee&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",ee?"text-primary":"text-foreground"),children:O}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:Pt(re,b)})]})]}),e.jsx("button",{onClick:()=>Me(re),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(En,{className:"h-3 w-3 text-primary"})})]},re)}return e.jsxs(gt,{onSelect:ee=>{ee.preventDefault(),ae(re),a==="immediate"&&k(!1)},className:T("flex items-start gap-2 cursor-pointer group py-2",r===re&&"bg-accent"),children:[e.jsx(Yt,{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:O}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Pt(re,b)})]}),e.jsx("button",{onClick:ee=>{ee.stopPropagation(),ee.preventDefault(),Me(re)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(En,{className:"h-3 w-3 text-primary"})})]},re)},Z=e.jsx(e.Fragment,{children:_?e.jsxs(e.Fragment,{children:[$e.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"}),$e.map(({name:O,path:re})=>oe(O,re)),n==="dropdown"&&e.jsx($o,{})]}),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..."}):u.map(O=>we(O)),!x&&u.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(Je,{outerClassName:"max-h-full",className:"w-full",children:Z})}):e.jsxs(Rt,{open:v,onOpenChange:k,children:[e.jsx(Lt,{asChild:!0,children:e.jsxs(De,{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(Yt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:r,children:Pt(r,b)})]}),e.jsx(wt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(_t,{align:"start",className:"w-[350px]",children:e.jsx(Je,{outerClassName:"h-full",className:"w-full",children:Z})})]})},si="directoryTreeShowHidden",Ep=({open:r,onOpenChange:s})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=yt(),[i,c]=l.useState(null),[d,m]=l.useState(!1),[f,u]=l.useState(!1),[p,h]=l.useState(()=>{if(typeof window>"u")return!1;try{const D=window.localStorage.getItem(si);if(D==="true")return!0;if(D==="false")return!1}catch{}return!1}),{isDesktop:g,requestAccess:x,startAccessing:S}=_l(),{isMobile:v}=Ct();l.useEffect(()=>{r&&(c(null),m(!1),u(!1))},[r]),l.useEffect(()=>{r&&!d&&!i&&n&&a&&(c(n),m(!0))},[r,d,i,n,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(si,p?"true":"false")}catch{}},[p]);const k=l.useMemo(()=>i?Pt(i,n):"Select a directory",[i,n]),b=l.useCallback(()=>{s(!1)},[s]),w=l.useCallback(async D=>{if(!(!D||f)){if(D===t){b();return}u(!0);try{let I=D;if(g){const z=await x(D);if(!z.success){ge.error("Unable to access directory",{description:z.error||"Desktop denied directory access."});return}I=z.path??D;const E=await S(I);if(!E.success){ge.error("Failed to open directory",{description:E.error||"Desktop could not grant file access."});return}}o(I),b()}catch(I){ge.error("Failed to select directory",{description:I instanceof Error?I.message:"Unknown error occurred."})}finally{u(!1)}}},[t,b,g,x,o,S,f]),j=l.useCallback(async()=>{i&&await w(i)},[w,i]),y=l.useCallback(D=>{c(D),m(!0)},[]),C=l.useCallback(async D=>{c(D),m(!0),await w(D)},[w]),M=e.jsxs(Ss,{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(js,{children:"Select project directory"}),e.jsx(qs,{className:"hidden sm:block",children:"Choose the working directory used for sessions, commands, and OpenCode operations."})]}),N=e.jsxs(Je,{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:Pt(t,n),children:Pt(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(Dp,{variant:"inline",currentPath:i??t,onSelectPath:y,onDoubleClickPath:C,className:"min-h-[280px] h-[55vh] sm:h-[440px]",selectionBehavior:"deferred",showHidden:p,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(Ap,{pressed:p,onPressedChange:D=>h(!!D),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:[p?e.jsx(To,{className:"h-4 w-4"}):e.jsx(Io,{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."})})]})]})]}),A=()=>e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:b,disabled:f,className:"w-full sm:w-auto",children:"Cancel"}),e.jsx(De,{onClick:j,disabled:f||!d||!i,className:"w-full sm:w-auto",children:f?"Applying...":"Use Selected Directory"})]});return v?e.jsx(Wt,{open:r,onClose:()=>s(!1),title:"Select project directory",className:"max-w-full",footer:e.jsx("div",{className:"flex flex-col gap-2",children:A()}),children:N}):e.jsx(ws,{open:r,onOpenChange:s,children:e.jsxs(vs,{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:[M,N,e.jsx(Er,{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:A()})]})})},bn=".openchamber",Hr=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,Tp=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Bl=r=>r.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Ol=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Wr=(r,s)=>{const t=Ol(r),n=Bl(s),o=!t||t==="/"?`/${bn}`:`${t}/${bn}`;return n?`${o}/${n}`:o},Ip=()=>{const[r,s]=l.useState(!1),[t,n]=l.useState(!1),[o,a]=l.useState(""),[i,c]=l.useState([]),[d,m]=l.useState(!1),[f,u]=l.useState(null),[p,h]=l.useState(!1),[g,x]=l.useState(null),[S,v]=l.useState(!1),k=l.useRef(new Set),[b,w]=l.useState(null),[j,y]=l.useState([]),[C,M]=l.useState(!1),[N,A]=l.useState(!1),{sessions:D,createSession:I,deleteSession:z,deleteSessions:E,loadSessions:$,initializeNewOpenChamberSession:V,setWorktreeMetadata:Y,setSessionDirectory:L,getWorktreeMetadata:_,isLoading:W}=ye(),{currentDirectory:ae,homeDirectory:je,hasPersistedDirectory:Me,isHomeReady:$e}=yt(),{agents:he}=xt(),{isSessionCreateDialogOpen:ie,setSessionCreateDialogOpen:Ne}=Re(),{isMobile:Q,isTablet:We,hasTouchInput:ne}=Ct(),B=Q||We||ne,we=l.useMemo(()=>Ol(ae),[ae]),oe=l.useMemo(()=>Tp(o),[o]),Z=l.useMemo(()=>Bl(oe),[oe]),O=l.useMemo(()=>!we||!Z?"":Wr(we,Z),[we,Z]),re=g===!0,ee=l.useMemo(()=>(b?.worktree?.status?.isDirty??!1)||j.some(pe=>pe.metadata.status?.isDirty),[b?.worktree?.status?.isDirty,j]),le=l.useMemo(()=>{const pe=b?.worktree;return pe&&typeof pe.branch=="string"&&pe.branch.trim().length>0?!0:j.length>0&&j.every(({metadata:R})=>typeof R.branch=="string"&&R.branch.trim().length>0)},[b?.worktree,j]),Se=b?.mode==="worktree",xe=Se,F=N||!Se||!le;l.useEffect(()=>{we&&(k.current.has(we)||em(we).then(()=>k.current.add(we)).catch(pe=>{console.warn("Failed to ensure .openchamber directory is ignored:",pe),k.current.delete(we)}))},[we]),l.useEffect(()=>{$()},[$,ae]),l.useEffect(()=>{!t&&$e&&!Me&&(s(!0),n(!0))},[Me,t,$e]),l.useEffect(()=>{if(!ie){a(""),c([]),u(null),m(!1),h(!1),x(null),v(!1);return}if(!we){c([]),x(null),h(!1);return}let pe=!1;return m(!0),h(!0),u(null),(async()=>{try{const R=await Lo(we);if(pe)return;if(x(R),!R)c([]),u(null);else{const te=await un(we);if(pe)return;const J=te.map(Ee=>mn(we,Ee)),_e=`${Wr(we,"")}/`,it=J.filter(Ee=>Ee.path.startsWith(_e));c(it)}}catch(R){if(pe)return;const te=R instanceof Error?R.message:"Failed to load worktrees";u(te)}finally{pe||(m(!1),h(!1))}})(),()=>{pe=!0}},[ie,we]);const G=l.useCallback(pe=>{w({sessions:pe.sessions,dateLabel:pe.dateLabel,mode:pe.mode??"session",worktree:pe.worktree??null})},[]),P=l.useCallback(()=>{w(null),y([]),M(!1),A(!1)},[]);l.useEffect(()=>Js.onDeleteRequest(pe=>{G(pe)}),[G]),l.useEffect(()=>Js.onDirectoryRequest(()=>{s(!0)}),[]),l.useEffect(()=>Js.onCreateRequest(()=>{a(""),Ne(!0)}),[Ne]),l.useEffect(()=>{if(!b){y([]),M(!1);return}const pe=b.sessions.map(te=>{const J=_(te.id);return J?{session:te,metadata:J}:null}).filter(te=>!!te);if(y(pe),M(!1),pe.length===0)return;let R=!1;return(async()=>{const te=await Promise.all(pe.map(async({metadata:J})=>{if(J.status&&typeof J.status.isDirty=="boolean")return J.status;try{return await Jr(J.path)}catch{return J.status}})).catch(J=>(console.warn("Failed to inspect worktree status before deletion:",J),pe.map(({metadata:ue})=>ue.status)));R||!Array.isArray(te)||y(J=>J.map((ue,_e)=>({session:ue.session,metadata:{...ue.metadata,status:te[_e]??ue.metadata.status}})))})(),()=>{R=!0}},[b,_]),l.useEffect(()=>{le||M(!1)},[le]);const de=l.useCallback(pe=>{a(pe),u(null)},[]),be=l.useCallback(async()=>{if(!(!we||!g))try{const R=(await un(we)).map(_e=>mn(we,_e)),J=`${Wr(we,"")}/`,ue=R.filter(_e=>_e.path.startsWith(J));c(ue)}catch{}},[we,g]),Ie=l.useRef(null);l.useEffect(()=>{Ie.current?.mode==="worktree"&&!b&&be(),Ie.current=b},[b,be]);const Ye=l.useCallback(()=>{if(!we){const J="Select a project directory first.";return u(J),ge.error(J),!1}const pe=oe,R=Z;if(!pe){const J="Provide a branch name for the new worktree.";return u(J),ge.error(J),!1}if(!R){const J="Provide a branch name that can be used as a folder.";return u(J),ge.error(J),!1}const te=Wr(we,R);if(i.some(J=>J.path===te)){const J="A worktree with this folder already exists.";return u(J),ge.error(J),!1}return u(null),!0},[we,oe,Z,i]),ct=async()=>{if(S||W||!Ye())return;v(!0),u(null);let pe=null;try{const R=oe,J=await dm({projectDirectory:we,worktreeSlug:Z,branch:R,createBranch:!0});pe=J;let ue=await Jr(J.path).catch(()=>{});try{await tm(J.path,{remote:"origin",branch:R,options:["--set-upstream"]}),ue=await Jr(J.path).catch(()=>ue),ge.success(`Configured upstream for ${R}`)}catch(Ee){const Be=Ee instanceof Error?Ee.message:"Unable to push new worktree branch.";ge.warning("Worktree created locally",{description:Hr(`Upstream setup failed: ${Be}`)})}const _e=ue?{...J,status:ue}:J,it=await I(void 0,J.path);if(!it){await ma({projectDirectory:we,path:J.path,force:!0}).catch(()=>{});const Ee="Failed to create session for worktree";u(Ee),ge.error(Ee);return}V(it.id,he),L(it.id,J.path),Y(it.id,_e),await be(),a(""),ge.success("Worktree created")}catch(R){pe&&await ma({projectDirectory:we,path:pe.path,force:!0}).catch(()=>{});const te=R instanceof Error?R.message:"Failed to create worktree";u(te),ge.error(te)}finally{v(!1)}},ze=l.useCallback(pe=>{const R=D.filter(te=>_(te.id)?.path===pe.path);Js.requestDelete({sessions:R,mode:"worktree",worktree:pe})},[D,_]),et=l.useCallback(async()=>{if(b){A(!0);try{const pe=xe,R=pe&&C;if(b.sessions.length===1){const te=b.sessions[0];if(!await z(te.id,{archiveWorktree:pe,deleteRemoteBranch:R})){ge.error("Failed to delete session"),A(!1);return}const ue=pe?R?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;ge.success("Session deleted",{description:Hr(ue)})}else{const te=b.sessions.map(_e=>_e.id),{deletedIds:J,failedIds:ue}=await E(te,{archiveWorktree:pe,deleteRemoteBranch:R});if(J.length>0){const _e=pe?R?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,Ee=[ue.length>0?`${ue.length} session${ue.length===1?"":"s"} could not be deleted.`:b.dateLabel?`Removed all sessions from ${b.dateLabel}.`:void 0,_e].filter(Boolean).join(" ");ge.success(`Deleted ${J.length} session${J.length===1?"":"s"}`,{description:Hr(Ee||void 0)})}if(ue.length>0&&(ge.error(`Failed to delete ${ue.length} session${ue.length===1?"":"s"}`,{description:Hr("Please try again in a moment.")}),J.length===0)){A(!1);return}}P()}finally{A(!1)}}},[b,C,z,E,P,xe]),Qe=e.jsxs("div",{className:"space-y-4 w-full min-w-0",children:[e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Create worktree"}),e.jsxs("p",{className:"typography-meta text-muted-foreground/80",children:["Branch-specific directory under ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:bn}),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"worktree-branch-input",children:"Branch name"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(kt,{id:"worktree-branch-input",value:o,onChange:pe=>de(pe.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!re||p,onKeyDown:pe=>{pe.key==="Enter"&&!S&&ct()}}),e.jsx(De,{onClick:ct,disabled:S||W||!re||!oe,className:"h-8",children:S?"Creating…":"Create"})]}),oe&&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:oe})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:Pt(O,je)})]})]}),f&&e.jsx("p",{className:"typography-meta text-destructive",children:f}),!re&&!p&&e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Current directory is not a Git repository."})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border border-border/40 bg-sidebar/60 p-3 overflow-hidden min-w-0",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Existing worktrees"})}),d?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading worktrees…"}):i.length===0?e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["No worktrees found under ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:bn}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:i.map(pe=>{const R=pe.relativePath||(pe.path.startsWith(we+"/")?pe.path.slice(we.length+1):pe.path);return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/30 bg-sidebar-accent/20 px-3 py-2 min-w-0",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-meta font-medium text-foreground",children:pe.label||pe.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:R})]}),e.jsx("button",{type:"button",onClick:()=>ze(pe),className:"flex-shrink-0 flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete worktree ${pe.branch||pe.label}`,children:e.jsx(Ps,{className:"h-4 w-4"})})]},pe.path)})})]})]}),Ge=e.jsx(De,{variant:"ghost",onClick:()=>Ne(!1),disabled:S,children:"Close"}),Le=b?.worktree??j[0]?.metadata??null,He=b?b.mode==="worktree"?`This removes the selected worktree and ${b.sessions.length===1?"1 linked session":`${b.sessions.length} linked sessions`}.`:`This action permanently removes ${b.sessions.length===1?"1 session":`${b.sessions.length} sessions`}${b.dateLabel?` from ${b.dateLabel}`:""}.`:"",ot=b?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:[b.sessions.slice(0,3).map(pe=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:pe.title||"Untitled Session"},pe.id)),b.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",b.sessions.length-3," more"]})]})}),Se?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"}),Le?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Le.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Le?Pt(Le.path,je):"Worktree path unavailable."}),ee&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),le?e.jsxs("button",{type:"button",onClick:()=>{F||M(pe=>!pe)},disabled:F,className:T("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",F?"cursor-not-allowed opacity-60":"hover:bg-sidebar/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[e.jsx("span",{className:"mt-0.5 flex size-5 items-center justify-center text-muted-foreground",children:C?e.jsx(To,{className:"size-4 text-primary"}):e.jsx(Io,{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:C?"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,dt=e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",onClick:P,disabled:N,children:"Cancel"}),e.jsx(De,{variant:"destructive",onClick:et,disabled:N,children:N?"Deleting…":Se?"Delete worktree":b?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[B?e.jsx(Wt,{open:ie,onClose:()=>Ne(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Ge}),children:e.jsx("div",{className:"space-y-2 pb-2",children:Qe})}):e.jsx(ws,{open:ie,onOpenChange:Ne,children:e.jsxs(vs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2 overflow-hidden",children:[e.jsx(Ss,{children:e.jsx(js,{children:"Worktree Manager"})}),Qe,e.jsx(Er,{className:"mt-2 gap-2 pt-1 pb-1",children:Ge})]})}),B?e.jsx(Wt,{open:!!b,onClose:()=>{N||P()},title:b?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:dt}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[He&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:He}),ot]})}):e.jsx(ws,{open:!!b,onOpenChange:pe=>{if(!pe){if(N)return;P()}},children:e.jsxs(vs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(Ss,{children:[e.jsx(js,{children:b?.sessions.length===1?"Delete session":"Delete sessions"}),He&&e.jsx(qs,{children:He})]}),ot,e.jsx(Er,{className:"mt-2 gap-2 pt-1 pb-1",children:dt})]})}),e.jsx(Ep,{open:r,onOpenChange:s})]})};function Fp(){return new Worker(gd,{type:"module"})}const Pp=["typescript","javascript","tsx","json"],Rp=({children:r})=>{const t=Uo()?.currentTheme?.metadata?.variant==="dark";vl();const n=fe.useMemo(()=>({theme:{dark:tr.dark,light:tr.light},themeType:t?"dark":"light",langs:Pp}),[t]);return e.jsx(yd,{poolOptions:{workerFactory:Fp,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:r})},Lp=(r={})=>{const{edgeThreshold:s=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=r,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=Re(),d=fe.useRef(null),m=fe.useRef(null);return fe.useEffect(()=>{if(!o||!a)return;const f=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},u=g=>{if(!d.current)return;const x=g.touches[0];if(!x)return;x.clientX-d.current.x>10&&g.preventDefault()},p=g=>{if(!d.current)return;const x=g.changedTouches[0];if(!x){d.current=null,m.current=null;return}m.current={x:x.clientX,y:x.clientY,time:Date.now()};const{x:S,y:v,time:k}=d.current,{x:b,y:w,time:j}=m.current,y=b-S,C=w-v,M=j-k,N=Math.abs(C)<Math.abs(y),A=M<=n,D=Math.abs(C)<t;y>=t&&N&&A&&D&&!c&&i(!0),d.current=null,m.current=null},h=()=>{d.current=null,m.current=null};return document.addEventListener("touchstart",f,{passive:!0,capture:!0}),document.addEventListener("touchmove",u,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",h,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",f,{capture:!0}),document.removeEventListener("touchmove",u,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,s,t,n,i,c]),null},hr=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;fe.memo(()=>{const r=fe.useRef(null),{addAttachedFile:s}=ye(),{isMobile:t}=Re(),n=Ho(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",i=async m=>{let f=0;for(let u=0;u<m.length;u++){const p=m[u],h=ye.getState().attachedFiles.length;try{await s(p),ye.getState().attachedFiles.length>h&&f++}catch(g){console.error("File attach failed",g),ge.error(g instanceof Error?g.message:"Failed to attach file")}}f>0&&ge.success(`Attached ${f} file${f>1?"s":""}`)},c=async m=>{const f=m.target.files;f&&(await i(f),r.current&&(r.current.value=""))},d=async()=>{try{const f=await(await fetch("/api/vscode/pick-files")).json(),u=Array.isArray(f?.files)?f.files:[],p=Array.isArray(f?.skipped)?f.skipped:[];if(p.length>0){const g=p.map(x=>`${x?.name||"file"}: ${x?.reason||"skipped"}`).join(`
23
+ `);ge.error(`Some files were skipped:
24
+ ${g}`)}const h=u.map(g=>{if(!g?.dataUrl)return null;try{const[x,S]=g.dataUrl.split(","),v=g.mimeType||x?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!S)return null;const k=atob(S),b=new Uint8Array(k.length);for(let j=0;j<k.length;j++)b[j]=k.charCodeAt(j);const w=new Blob([b],{type:v});return new File([w],g.name||"file",{type:v})}catch(x){return console.error("Failed to decode VS Code picked file",x),null}}).filter(Boolean);h.length>0&&await i(h)}catch(m){console.error("VS Code file pick failed",m),ge.error(m instanceof Error?m.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(oo,{className:T(a,"text-current")})})]})});const _p=fe.memo(({file:r,onRemove:s})=>{const t=()=>r.mimeType.startsWith("image/")?e.jsx(er,{className:"h-3.5 w-3.5"}):r.mimeType.includes("text")||r.mimeType.includes("code")?e.jsx(Hs,{className:"h-3.5 w-3.5"}):r.mimeType.includes("json")||r.mimeType.includes("xml")?e.jsx(Nn,{className:"h-3.5 w-3.5"}):e.jsx(Hs,{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(xd,{className:"h-3 w-3 text-primary"}):e.jsx(zi,{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(os,{className:"h-3 w-3"})})]})}),Bp=fe.memo(()=>{const{attachedFiles:r,removeAttachedFile:s}=ye();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(_p,{file:t,onRemove:()=>s(t.id)},t.id))]})})}),$l=fe.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 f=d.replace(/\\/g,"/").split("/");return f[f.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(er,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(Hs,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Nn,{className:"h-3.5 w-3.5"}):e.jsx(Hs,{className:"h-3.5 w-3.5"}):e.jsx(Hs,{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 m=n(d.filename)||"Image",f={open:!0,title:m,content:"",metadata:{tool:"image-preview",filename:m,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:m}};s(f)},[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,m)=>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-${m}`))}),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,m)=>{const f=n(d.filename)||"Image";return e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{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":f,children:[d.url?e.jsx("img",{src:d.url,alt:f,className:"h-full w-full object-cover",loading:"lazy",onError:u=>{const p=u.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(er,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:f})]})}),e.jsx(lt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:f})]},`img-${m}`)})})})]})}),zl=(r,s=200)=>{const[t,n]=fe.useState(r);return fe.useEffect(()=>{const o=window.setTimeout(()=>{n(r)},s);return()=>{window.clearTimeout(o)}},[r,s]),t},Op=l.forwardRef(({searchQuery:r,onFileSelect:s,onClose:t},n)=>{const{currentDirectory:o}=yt(),{addServerFile:a}=ye(),i=Bo(j=>j.searchFiles),c=zl(r,180),[d,m]=l.useState([]),[f,u]=l.useState(!1),[p,h]=l.useState(0),[g,x]=l.useState(null),S=l.useRef([]),v=l.useRef(null),k=l.useCallback((j,y)=>{const C=j.trim().toLowerCase();if(!C)return 0;const M=y.toLowerCase();let N=0,A=-1,D=0;for(let I=0;I<C.length;I+=1){const z=C[I];if(!z||z===" ")continue;const E=M.indexOf(z,A+1);if(E===-1)return null;const $=E-A-1;if($===0?D+=1:D=0,N+=10,N+=Math.max(0,18-E),N-=Math.max(0,$),E===0)N+=12;else{const V=M[E-1];(V==="/"||V==="_"||V==="-"||V==="."||V===" ")&&(N+=10)}N+=D>0?12:0,A=E}return N+=Math.max(0,24-Math.round(M.length/3)),N},[]);l.useEffect(()=>{const j=y=>{const C=y.target;!C||!v.current||v.current.contains(C)||t()};return document.addEventListener("pointerdown",j,!0),()=>{document.removeEventListener("pointerdown",j,!0)}},[t]),l.useEffect(()=>{if(!o){m([]);return}const y=(c??"").trim().toLowerCase();let C=!1;return u(!0),i(o,y,80).then(M=>{if(C)return;const N=y?M.map(A=>{const D=A.relativePath||A.name||A.path,I=k(y,D);return I===null?null:{file:A,score:I,labelLength:D.length}}).filter(Boolean):M.map(A=>({file:A,score:0,labelLength:(A.relativePath||A.name||A.path).length}));N.sort((A,D)=>D.score-A.score||A.labelLength-D.labelLength||A.file.path.localeCompare(D.file.path)),m(N.slice(0,15).map(A=>A.file))}).catch(()=>{C||m([])}).finally(()=>{C||u(!1)}),()=>{C=!0}},[o,c,k,i]),l.useEffect(()=>{h(0),x(null)},[d]),l.useEffect(()=>{S.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]);const b=l.useCallback(async j=>{await a(j.path,j.name),s(j)},[a,s]);l.useImperativeHandle(n,()=>({handleKeyDown:j=>{if(j==="Escape"){t();return}const y=d.length;if(y!==0){if(j==="ArrowDown"){h(C=>(C+1)%y);return}if(j==="ArrowUp"){h(C=>(C-1+y)%y);return}if(j==="Enter"||j==="Tab"){const C=(p%y+y)%y,M=d[C];M&&b(M)}}}}),[d,p,t,b]);const w=j=>{switch(j.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(Ts,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Ts,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Hs,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(er,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Nn,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:v,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(Je,{outerClassName:"flex-1 min-h-0",className:"px-0",children:f?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Cn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((j,y)=>{const C=j.relativePath||j.name,M=Ui(C,{maxLength:45}),N=p===y,D=N||g===y,I=e.jsxs("div",{ref:z=>{S.current[y]=z},className:T("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",N&&"bg-accent"),onClick:()=>b(j),onMouseEnter:()=>h(y),children:[w(j),e.jsx("span",{className:"flex-1 truncate max-w-[360px]","aria-label":C,children:M})]});return e.jsxs(ut,{open:D,delayDuration:D?0:120,onOpenChange:z=>{x(E=>!z&&E===y?null:z?y:E)},children:[e.jsx(mt,{asChild:!0,children:I}),e.jsx(lt,{side:"right",align:"center",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:C})})]},j.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"})]})}),Hl=l.forwardRef(({searchQuery:r,onCommandSelect:s,onClose:t},n)=>{const{hasMessagesInCurrentSession:o}=ye(Fo(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),[m,f]=l.useState(0),u=l.useRef([]),p=l.useRef(null);l.useEffect(()=>{const g=x=>{const S=x.target;!S||!p.current||p.current.contains(S)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),l.useEffect(()=>{(async()=>{d(!0);try{const S=(await Ae.listCommands()).map(y=>({name:y.name,description:y.description,agent:y.agent,model:y.model,isBuiltIn:!1})),v=[...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;v.forEach(y=>k.set(y.name,y)),S.forEach(y=>k.set(y.name,y));const b=Array.from(k.values()),w=!o,j=(r?b.filter(y=>y.name.toLowerCase().includes(r.toLowerCase())||y.description&&y.description.toLowerCase().includes(r.toLowerCase())):b).filter(y=>w||y.name!=="init");j.sort((y,C)=>{const M=y.name.toLowerCase().startsWith(r.toLowerCase()),N=C.name.toLowerCase().startsWith(r.toLowerCase());return M&&!N?-1:!M&&N?1:y.name.localeCompare(C.name)}),i(j)}catch{const x=!o,S=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],v=(r?S.filter(k=>k.name.toLowerCase().includes(r.toLowerCase())||k.description&&k.description.toLowerCase().includes(r.toLowerCase())):S).filter(k=>x||k.name!=="init");i(v)}finally{d(!1)}})()},[r,o]),l.useEffect(()=>{f(0)},[a]),l.useEffect(()=>{u.current[m]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[m]),l.useImperativeHandle(n,()=>({handleKeyDown:g=>{const x=a.length;if(g==="Escape"){t();return}if(x!==0){if(g==="ArrowDown"){f(S=>(S+1)%x);return}if(g==="ArrowUp"){f(S=>(S-1+x)%x);return}if(g==="Enter"||g==="Tab"){const S=(m%x+x)%x,v=a[S];v&&s(v)}}}}),[a,m,t,s]);const h=g=>{switch(g.name){case"init":return e.jsx(Hs,{className:"h-3.5 w-3.5 text-green-500"});case"summarize":return e.jsx(wd,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Fs,{className:"h-3.5 w-3.5 text-cyan-500"});default:return g.isBuiltIn?e.jsx(bd,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(nr,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:p,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(Je,{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(Cn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[a.map((g,x)=>e.jsxs("div",{ref:S=>{u.current[x]=S},className:T("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",x===m&&"bg-accent"),onClick:()=>s(g),onMouseEnter:()=>f(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"})]})});Hl.displayName="CommandAutocomplete";const $p=r=>r?r!=="primary":!1,Wl=l.forwardRef(({searchQuery:r,onAgentSelect:s,onClose:t},n)=>{const o=l.useRef(null),[a,i]=l.useState(0),[c,d]=l.useState([]),{agents:m}=xt();l.useEffect(()=>{const u=m.filter(g=>$p(g.mode)).map(g=>({name:g.name,description:g.description,mode:g.mode??void 0})),p=r.trim().toLowerCase(),h=p.length?u.filter(g=>g.name.toLowerCase().includes(p)):u;h.sort((g,x)=>g.name.localeCompare(x.name)),d(h),i(0)},[m,r]),l.useEffect(()=>{const u=p=>{const h=p.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",u,!0),()=>{document.removeEventListener("pointerdown",u,!0)}},[t]),l.useImperativeHandle(n,()=>({handleKeyDown:u=>{if(u==="Escape"){t();return}if(c.length){if(u==="ArrowDown"){i(p=>(p+1)%c.length);return}if(u==="ArrowUp"){i(p=>(p-1+c.length)%c.length);return}if(u==="Enter"||u==="Tab"){const p=c[(a+c.length)%c.length];p&&s(p.name)}}}}),[c,s,t,a]);const f=(u,p)=>e.jsx("div",{className:T("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",p===a&&"bg-accent"),onClick:()=>s(u.name),onMouseEnter:()=>i(p),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:["#",u.name]})}),u.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:u.description})]})},u.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(Je,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c.length?e.jsx("div",{children:c.map((u,p)=>f(u,p))}):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"})]})});Wl.displayName="AgentMentionAutocomplete";function zp({className:r,children:s,...t}){return e.jsxs(vd,{"data-slot":"scroll-area",className:T("relative",r),...t,children:[e.jsx(Sd,{"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(Hp,{}),e.jsx(jd,{})]})}function Hp({className:r,orientation:s="vertical",...t}){return e.jsx(kd,{"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(Nd,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Wp=({onFilesSelected:r,multiSelect:s=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Ct(),c=Ho(),d=i||c,{currentDirectory:m}=yt(),f=Bo(F=>F.searchFiles),[u,p]=l.useState(!1),[h,g]=l.useState(!1),[x,S]=l.useState(""),v=zl(x,200),[k,b]=l.useState(new Set),[w,j]=l.useState(new Set),[y,C]=l.useState({}),M=l.useRef(new Set),N=l.useRef(new Set),[A,D]=l.useState([]),[I,z]=l.useState(!1),[E,$]=l.useState(!1),[V,Y]=l.useState(!1),[L,_]=l.useState(null),W=n??u,ae=o??p,je=l.useCallback(F=>F.slice().sort((G,P)=>G.type!==P.type?G.type==="directory"?-1:1:G.name.localeCompare(P.name)),[]),Me=l.useCallback((F,G)=>je(G.filter(P=>!P.name.startsWith(".")).map(P=>{const de=P.name,be=!P.isDirectory&&de.includes(".")?de.split(".").pop()?.toLowerCase():void 0;return{name:de,path:P.path||`${F}/${de}`,type:P.isDirectory?"directory":"file",size:0,extension:be}})),[je]),$e=l.useCallback(async F=>{$(!0),_(null);try{const G=await Ae.listLocalDirectory(F),P=Me(F,G.map(de=>({name:de.name,path:de.path,isDirectory:de.isDirectory})));M.current=new Set([F]),N.current=new Set,C({[F]:P}),j(new Set)}catch{_("Failed to load directory contents"),M.current=new Set([F]),N.current=new Set,C({[F]:[]}),j(new Set)}finally{$(!1)}},[Me]),he=l.useCallback(async F=>{const G=F.trim();if(G&&!M.current.has(G)&&!N.current.has(G)){N.current=new Set(N.current),N.current.add(G);try{const P=await Ae.listLocalDirectory(G),de=Me(G,P.map(be=>({name:be.name,path:be.path,isDirectory:be.isDirectory})));M.current=new Set(M.current),M.current.add(G),C(be=>({...be,[G]:de}))}catch{C(P=>P[G]?P:{...P,[G]:[]})}finally{N.current=new Set(N.current),N.current.delete(G)}}},[Me]);l.useEffect(()=>{(W||h)&&m&&$e(m)},[W,h,m,$e]),l.useEffect(()=>{if(!(W||h)||!m){D([]),z(!1);return}const F=v.trim();if(!F){D([]),z(!1);return}let G=!1;return z(!0),f(m,F,150).then(P=>{if(G)return;const de=P.map(be=>({name:be.name,path:be.path,type:"file",extension:be.extension,relativePath:be.relativePath,size:0}));D(de)}).catch(()=>{G||D([])}).finally(()=>{G||z(!1)}),()=>{G=!0}},[W,h,m,v,f]),l.useEffect(()=>{!W&&!h&&(b(new Set),S(""),D([]),z(!1))},[W,h]);const ie=F=>{if(F.type==="directory")return w.has(F.path)?e.jsx(Yt,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(Yt,{className:"h-3.5 w-3.5 text-primary/60"});switch(F.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(Ts,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(Ts,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(ao,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(er,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(ao,{className:"h-3.5 w-3.5 text-muted-foreground"})}},Ne=async F=>{w.has(F)?j(P=>{const de=new Set(P);return de.delete(F),de}):(j(P=>{const de=new Set(P);return de.add(F),de}),await he(F))},Q=F=>{b(s?G=>{const P=new Set(G);return P.has(F)?P.delete(F):P.add(F),P}:new Set([F]))},We=async()=>{const F=new Map;Object.values(y).forEach(de=>{de.forEach(be=>{be.type==="file"&&F.set(be.path,be)})});const G=new Map(A.map(de=>[de.path,de])),P=Array.from(k).map(de=>F.get(de)??G.get(de)).filter(de=>!!de);Y(!0);try{await r(P),b(new Set),ae(!1),g(!1)}finally{Y(!1)}},ne=l.useMemo(()=>m?y[m]??[]:[],[y,m]),B=x.trim().length>0,we=F=>y[F]??[],oe=F=>{if(m&&F.startsWith(m)){const G=F.substring(m.length);return G.startsWith("/")?G.substring(1):G}return F.split("/").pop()||F},Z=(F,G)=>{const P=B?F.relativePath||oe(F.path):F.name,de=B&&P.includes("/")&&P.length>45,be=de?Ui(P,{maxLength:d?42:48}):P,Ie=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",F.type==="file"&&k.has(F.path)&&"bg-primary/10"),style:{paddingLeft:`${G*12}px`},onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),F.type==="file"&&Q(F.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:ie(F)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":P,children:be})]}),F.type==="file"&&k.has(F.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return de?e.jsxs(ut,{delayDuration:120,children:[e.jsx(mt,{asChild:!0,children:Ie}),e.jsx(lt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:P})})]},F.path):l.cloneElement(Ie,{key:F.path})},O=(F,G)=>{const P=F.type==="directory",de=P?we(F.path):[],be=w.has(F.path),Ie=P&&be&&N.current.has(F.path)&&de.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!P&&k.has(F.path)&&"bg-primary/10"),style:{paddingLeft:`${G*12}px`},onClick:Ye=>{Ye.preventDefault(),Ye.stopPropagation(),P?Ne(F.path):Q(F.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:ie(F)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:F.name}),!P&&k.has(F.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),P&&be&&de.length>0&&e.jsx("div",{children:de.map(Ye=>O(Ye,G+1))}),P&&be&&Ie&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(G+1)*12}px`},children:"Loading…"})]},F.path)},re=k.size>0?`${k.size} file${k.size!==1?"s":""} selected`:"No files selected",ee=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:re}),e.jsx(De,{size:"sm",onClick:We,disabled:k.size===0||V,className:"h-6 typography-meta",children:V?"Attaching...":"Attach Files"})]}),le=d?"flex-1 min-h-[240px]":"h-[300px]",Se=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(Eo,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{value:x,onChange:F=>S(F.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:F=>F.stopPropagation()}),x&&e.jsx("button",{onClick:F=>{F.stopPropagation(),S("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-accent rounded",children:e.jsx(os,{className:"h-3 w-3"})})]})}),e.jsxs(zp,{className:le,children:[E&&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..."})}),L&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:L})}),!E&&!L&&e.jsxs("div",{className:"py-1 px-2",children:[B?I?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):A.map(F=>Z(F,0)):ne.map(F=>O(F,0)),!B&&ne.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),B&&!I&&A.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),xe=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:F=>{F.preventDefault(),F.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:F=>{F.preventDefault(),F.stopPropagation(),ae(!0)},children:t}):null,e.jsx(Wt,{open:W,onClose:()=>ae(!1),title:"Select Project Files",footer:ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:Se})})]}):d?e.jsxs(e.Fragment,{children:[xe,e.jsx(Wt,{open:h,onClose:()=>g(!1),title:"Select Project Files",footer:ee,children:e.jsx("div",{className:"flex flex-col gap-0",children:Se})})]}):e.jsxs(Rt,{open:W,onOpenChange:ae,children:[e.jsx(Lt,{asChild:!0,children:t}),e.jsxs(_t,{className:T("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[Se,e.jsx($o,{}),ee]})]})},Ur=[{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 Ms(r){if(!r||r==="build")return Ur[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)%(Ur.length-1);return Ur[t]}const Up=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),Ul=r=>Up(r),Vp=r=>r?typeof r=="string"?r==="ask":Ul(r)?Object.values(r).some(s=>s==="ask"):!1:!1,Gp=r=>r?typeof r=="string"?r==="deny":Ul(r)?Object.values(r).some(s=>s==="deny"):!1:!1,Vl=({agentDefaultEditMode:r,webfetchPermission:s,bashPermission:t})=>{const n=Vp(t),o=Gp(t),a=!n&&!o,i=s==="allow",c=s!=="deny",d=r==="allow"||r==="full",m=r==="ask";let f=r;d&&i&&a?f="full":d&&n?f="allow":m&&(f="ask");const u={ask:m,allow:m||d&&n,full:r!=="deny"&&c&&n,deny:!1},p=u.allow||u.full;return{cascadeDefaultMode:f,modeAvailability:u,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:c}},Vr=r=>r==="primary"||r==="all"||r===void 0||r===null,qp=[{key:"tool_call",icon:Po,label:"Tool calling",isActive:r=>r?.tool_call===!0},{key:"reasoning",icon:Sn,label:"Reasoning",isActive:r=>r?.reasoning===!0}],Kp={text:{icon:Hi,label:"Text"},image:{icon:er,label:"Image"},video:{icon:Md,label:"Video"},audio:{icon:Cd,label:"Audio"},pdf:{icon:Nn,label:"PDF"}},Yp=r=>r.trim().toLowerCase(),fr=(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=>Yp(o)))).map(o=>{const a=Kp[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Xp=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Jp=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Ns=r=>{if(typeof r!="number"||Number.isNaN(r))return"—";if(r===0)return"0";const s=Xp.format(r);return s.endsWith(".0")?s.slice(0,-2):s},Gr=r=>typeof r!="number"||!Number.isFinite(r)?"—":Jp.format(r),Gn=r=>qp.filter(s=>s.isActive(r)).map(s=>({key:s.key,icon:s.icon,label:s.label})),ri=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},ni=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)},oi=({className:r})=>{const{providers:s,agents:t,currentProviderId:n,currentModelId:o,currentAgentName:a,setProvider:i,setModel:c,setAgent:d,getCurrentProvider:m,getModelMetadata:f,getCurrentAgent:u}=xt(),{currentSessionId:p,messages:h,saveSessionAgentSelection:g,getSessionAgentSelection:x,saveAgentModelForSession:S,getAgentModelForSession:v,analyzeAndSaveExternalSessionChoices:k,getSessionAgentEditMode:b,setSessionAgentEditMode:w}=ye(),j=ht(H=>H.hasHydrated),{isMobile:y}=Ct(),C=vf(),M=Ho(),N=y||M,[A,D]=l.useState(null),[I,z]=l.useState(null),[E,$]=l.useState(""),V=l.useCallback(()=>D(null),[]),Y=l.useCallback(()=>z(null),[]),L=l.useRef(void 0),[_,W]=l.useState(()=>{const H=new Set;return n&&H.add(n),H}),[ae,je]=l.useState(!1),[Me,$e]=l.useState(!1),[he,ie]=l.useState(!1),Ne=l.useId();l.useEffect(()=>{A==="model"&&W(()=>{const H=new Set;return n&&H.add(n),H})},[A,n]),l.useEffect(()=>{A!=="agent"&&je(!1),A!=="model"&&$("")},[A]),l.useEffect(()=>{Me||ie(!1)},[Me]);const Q=u?.(),We=Q?.permission?.edit;let ne="ask";(We==="allow"||We==="ask"||We==="deny"||We==="full")&&(ne=We);const B=Q?Q.tools?.edit!==!1:!1;(!Q||!B)&&(ne="deny");const we=Q?.permission?.webfetch,oe=Q?.permission?.bash,Z=l.useMemo(()=>Vl({agentDefaultEditMode:ne,webfetchPermission:we,bashPermission:oe}),[ne,we,oe]),{cascadeDefaultMode:O,modeAvailability:re,autoApproveAvailable:ee}=Z,le=!!(p&&a),Se=le&&p&&a?b(p,a,O):O,xe={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},F=l.useCallback(H=>!re[H],[re]),G=l.useMemo(()=>!le||F(Se)&&Se!==O?O:Se,[O,F,le,Se]),P=[{mode:"ask",label:xe.ask,disabled:F("ask")},{mode:"allow",label:xe.allow,disabled:F("allow")},{mode:"full",label:xe.full,disabled:F("full")}],de=l.useMemo(()=>hr(G),[G]),be=!le||!ee;l.useEffect(()=>{be&&(je(!1),ie(!1))},[be]);const Ie=y?"mobile":M?"vscode":"default",Ye=Ie==="mobile"?"h-9":Ie==="vscode"?"h-6":"h-8",ct=Ie==="mobile"?"h-5 w-5":"h-4 w-4",ze=Ie==="mobile"?"h-5 w-5":"h-4 w-4",et=N?"typography-micro":"typography-meta",Qe=Ie==="mobile"?"gap-x-2":Ie==="vscode"?"gap-x-1":"gap-x-3",Ge=xe[G],Le=l.useCallback((H,K=ct)=>{const X=T(K,"flex-shrink-0"),ke=hr(H),Ze={color:ke?ke.text:"var(--foreground)"};return H==="full"?e.jsx(ps,{className:X,style:Ze}):H==="allow"?e.jsx(Xr,{className:X,style:Ze}):H==="deny"?e.jsx(Zs,{className:X,style:Ze}):e.jsx(Cr,{className:X,style:Ze})},[ct]),He=l.useCallback(H=>{be||!p||!a||F(H)||(w(p,a,H,O),$e(!1),je(!1),ie(!1))},[O,be,p,a,w,$e,ie,F]),ot=m(),dt=Array.isArray(ot?.models)?ot.models:[],pe=n&&o?f(n,o):void 0,R=Gn(pe),te=fr(pe,"input"),J=fr(pe,"output"),ue=[{label:"Input",value:Gr(pe?.cost?.input)},{label:"Output",value:Gr(pe?.cost?.output)},{label:"Cache read",value:Gr(pe?.cost?.cache_read)},{label:"Cache write",value:Gr(pe?.cost?.cache_write)}],_e=[{label:"Context",value:Ns(pe?.limit?.context)},{label:"Output",value:Ns(pe?.limit?.output)}],it=l.useRef(void 0),Ee=p?h.get(p)?.length??-1:-1,Be=l.useRef(null),me=l.useCallback((H,K,X)=>{if(!H||!K)return"model-missing";const ke=s.find(Ce=>Ce.id===H);return ke?(Array.isArray(ke.models)?ke.models:[]).find(Ce=>Ce.id===K)?(i(H),c(K),p&&X&&S(p,X,H,K),"applied"):"model-missing":"provider-missing"},[s,i,c,p,S]);l.useEffect(()=>{if(!p){Be.current=null;return}if(!j||s.length===0||t.length===0)return;(!Be.current||Be.current.sessionId!==p)&&(Be.current={sessionId:p,resolved:!1,inFlight:!1});const H=Be.current;if(!H||H.resolved||H.inFlight)return;let K=!1;const X=()=>{if(K)return;const Ce=Be.current;Ce&&Ce.sessionId===p&&(Ce.resolved=!0,Ce.inFlight=!1)},ke=()=>{const Ce=x(p);if(Ce){a!==Ce&&d(Ce);const Ve=v(p,Ce);if(Ve){const Ke=me(Ve.providerId,Ve.modelId,Ce);if(Ke==="applied")return"resolved";if(Ke==="provider-missing")return"waiting"}else return"resolved"}for(const Ve of t){const Ke=v(p,Ve.name);if(!Ke)continue;a!==Ve.name&&d(Ve.name),g(p,Ve.name);const Et=me(Ke.providerId,Ke.modelId,Ve.name);if(Et==="applied")return"resolved";if(Et==="provider-missing")return"waiting"}return"continue"},tt=()=>{if(t.length===0)return;const Ce=t.filter(Ke=>Vr(Ke.mode)),Ve=t.find(Ke=>Ke.name==="build")||Ce[0]||t[0];Ve&&(g(p,Ve.name),a!==Ve.name&&d(Ve.name),Ve.model?.providerID&&Ve.model?.modelID&&me(Ve.model.providerID,Ve.model.modelID,Ve.name))};return(async()=>{try{const Ce=ke();if(Ce==="resolved"){X();return}if(Ce==="waiting"||Ee===-1)return;if(Ee>0){H.inFlight=!0;try{const Ve=await k(p,t);if(K)return;if(Ve.size>0){let Ke=null,Et=-1/0;for(const[St,cs]of Ve)cs.timestamp>Et&&(Et=cs.timestamp,Ke=St);if(Ke){g(p,Ke),a!==Ke&&d(Ke);const St=Ve.get(Ke);if(St){const cs=me(St.providerId,St.modelId,Ke);if(cs==="applied"){X();return}if(cs==="provider-missing")return}else{X();return}}}}catch(Ve){K||console.error("[ModelControls] Error resolving session from messages:",Ve)}finally{const Ve=Be.current;!K&&Ve&&Ve.sessionId===p&&(Ve.inFlight=!1)}}tt(),X()}catch(Ce){K||console.error("[ModelControls] Error in session switch:",Ce)}})(),()=>{K=!0}},[p,Ee,t,a,x,v,d,me,k,g,j,s]),l.useEffect(()=>{if(!j||!p||s.length===0||t.length===0)return;const K=x(p)||a;if(!K)return;const X=v(p,K);if(!X)return;const ke=s.find(Ve=>Ve.id===X.providerId);if(!ke||!(Array.isArray(ke.models)?ke.models.some(Ve=>Ve.id===X.modelId):!1))return;const Ze=n===X.providerId,Ce=o===X.modelId;Ze&&Ce||(K!==a&&d(K),me(X.providerId,X.modelId,K))},[j,p,a,n,o,s,t,x,v,me,d]),l.useEffect(()=>{if(!j)return;(async()=>{try{if(a!==it.current&&(it.current=a,a&&p)){await new Promise(ke=>setTimeout(ke,50));const K=v(p,a);if(K){const ke=me(K.providerId,K.modelId,a);if(ke==="applied"||ke==="provider-missing")return}const X=t.find(ke=>ke.name===a);if(X?.model?.providerID&&X?.model?.modelID&&me(X.model.providerID,X.model.modelID,a)==="provider-missing")return}}catch(K){console.error("[ModelControls] Agent change error:",K)}})()},[a,p,v,me,t,j]);const Oe=H=>{try{d(H),$e(!1),p&&g(p,H),N&&V()}catch(K){console.error("[ModelControls] Handle agent change error:",K)}},Te=(H,K)=>{try{const X=me(H,K,a||void 0);if(X!=="applied"){X==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",H):X==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:H,modelId:K});return}N&&V()}catch(X){console.error("[ModelControls] Handle model change error:",X)}},qe=H=>{const K=typeof H?.name=="string"?H.name:typeof H?.id=="string"?H.id:"";return K.length>40?K.substring(0,37)+"...":K},at=()=>s.find(K=>K.id===n)?.name||n,rt=()=>{if(!n||!o||dt.length===0)return"Not selected";const H=dt.find(K=>K.id===o);return qe(H)},ft=()=>{if(!a){const K=t.filter(tt=>Vr(tt.mode)),ke=K.find(tt=>tt.name==="build")||K[0];return ke?U(ke.name):"Select Agent"}const H=t.find(K=>K.name===a);return U(H?H.name:a)},U=H=>H.charAt(0).toUpperCase()+H.slice(1),ce=(H,K,X)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:K,"aria-label":K,role:"img",children:e.jsx(H,{className:"h-3.5 w-3.5"})},X),se=l.useCallback(H=>{W(K=>{const X=new Set(K);return X.has(H)?X.delete(H):X.add(H),X})},[]),ve=l.useCallback(H=>{L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{z(H)},500)},[]),Pe=l.useCallback(()=>{L.current&&clearTimeout(L.current)},[]);l.useEffect(()=>()=>{L.current&&clearTimeout(L.current)},[]);const pt=()=>!N||I!=="model"?null:e.jsx(Wt,{open:!0,onClose:Y,title:pe?.name||rt(),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:at()})]}),R.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:R.map(({key:H,icon:K,label:X})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[ce(K,X,`cap-${H}`),e.jsx("span",{className:"typography-meta text-foreground",children:X})]},H))})]}),(te.length>0||J.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:[te.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:te.map(({key:H,icon:K,label:X})=>ce(K,`${X} input`,`input-${H}`))})]}),J.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:J.map(({key:H,icon:K,label:X})=>ce(K,`${X} output`,`output-${H}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ns(pe?.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:Ns(pe?.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:ri(pe?.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:ni(pe?.release_date)})]})]})]})]})}),bt=()=>{if(!N||I!=="agent"||!Q)return null;const H=Object.entries(Q.tools||{}).filter(([,Ce])=>Ce).map(([Ce])=>Ce).sort(),K=!!(Q.prompt&&Q.prompt.trim().length>0),X=Q.model?.providerID&&Q.model?.modelID,ke=Q.temperature!==void 0||Q.topP!==void 0,tt=Ce=>Le(Ce==="full"||Ce==="allow"||Ce==="deny"?Ce:"ask","h-3.5 w-3.5"),Ze=Ce=>Ce==="full"?"Full":Ce==="allow"?"Allow":Ce==="deny"?"Deny":"Ask";return e.jsx(Wt,{open:!0,onClose:Y,title:U(Q.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[Q.description&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsx("div",{className:"typography-meta text-foreground",children:Q.description})}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Mode"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:Q.mode==="primary"?"Primary":Q.mode==="subagent"?"Subagent":Q.mode==="all"?"All":"—"})]}),(X||ke)&&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"}),X&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[Q.model.providerID," / ",Q.model.modelID]}),ke&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[Q.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Q.temperature})]}),Q.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Q.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Tools"}),H.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:H.map(Ce=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:Ce},Ce))}):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(Q.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ze(Q.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 Q.permission?.bash=="string"?Q.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ze(typeof Q.permission?.bash=="string"?Q.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(Q.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ze(Q.permission?.webfetch)})]})]})]})]}),K&&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(Xr,{className:"h-4 w-4 text-foreground"})]})})]})})},vt=()=>{if(!N)return null;const H=E.trim().toLowerCase(),K=s.map(X=>{const ke=Array.isArray(X.models)?X.models:[],tt=H.length===0?!0:X.name.toLowerCase().includes(H)||X.id.toLowerCase().includes(H),Ze=H.length===0?ke:ke.filter(Ce=>{const Ve=qe(Ce).toLowerCase(),Ke=typeof Ce.id=="string"?Ce.id.toLowerCase():"";return Ve.includes(H)||Ke.includes(H)});return{provider:X,providerModels:Ze,matchesProvider:tt}}).filter(({matchesProvider:X,providerModels:ke})=>X||ke.length>0);return e.jsx(Wt,{open:A==="model",onClose:V,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(Eo,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(kt,{value:E,onChange:X=>$(X.target.value),placeholder:"Search providers or models",className:"pl-7 h-8 typography-meta"}),E&&e.jsx("button",{type:"button",onClick:()=>$(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Zs,{className:"h-4 w-4"})})]})}),K.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."}),K.map(({provider:X,providerModels:ke})=>{if(ke.length===0&&!H.length)return null;const tt=X.id===n,Ze=_.has(X.id)||H.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",onClick:()=>se(X.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Ze,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{providerId:X.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:X.name}),tt&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Ze?e.jsx(wt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(xs,{className:"h-3 w-3 text-muted-foreground"})]}),Ze&&ke.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:ke.map(Ce=>{const Ve=tt&&Ce.id===o,Ke=f(X.id,Ce.id),Et=Gn(Ke).slice(0,3),St=fr(Ke,"input");return e.jsxs("button",{type:"button",onClick:()=>Te(X.id,Ce.id),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",Ve?"bg-primary/15 text-primary":"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:qe(Ce)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Ke?.limit?.context||Ke?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Ke?.limit?.context?e.jsxs("span",{children:[Ns(Ke?.limit?.context)," ctx"]}):null,Ke?.limit?.context&&Ke?.limit?.output?e.jsx("span",{children:"•"}):null,Ke?.limit?.output?e.jsxs("span",{children:[Ns(Ke?.limit?.output)," out"]}):null]}),(Et.length>0||St.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Et,...St].map(({key:cs,icon:Ir,label:ra})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:ra,"aria-label":ra,children:e.jsx(Ir,{className:"h-3 w-3"})},`meta-${X.id}-${Ce.id}-${cs}`))})]})]},Ce.id)})})]},X.id)})]})})},$t=()=>{if(!N)return null;const H=t.filter(K=>Vr(K.mode));return e.jsx(Wt,{open:A==="agent",onClose:V,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[H.map(K=>{const X=K.name===a,ke=Ms(K.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",ke.class,X?"active":"border-border/40"),onClick:()=>Oe(K.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("h-2 w-2 rounded-full",ke.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:X?{color:`var(${ke.var})`}:void 0,children:U(K.name)})]}),K.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:K.description})]},K.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:be,onClick:()=>{be||je(K=>!K)},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",be?"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:de?de.text:"var(--foreground)",mixBlendMode:"normal"},children:Ge})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!de&&"text-muted-foreground"),style:de?{color:de.text}:void 0,children:Le(G,ct)}),e.jsx(wt,{className:T("h-4 w-4 text-muted-foreground transition-transform",ae?"rotate-180":"")})]})]}),ae&&!be&&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:P.map(K=>{const X=K.mode===G,ke=hr(K.mode);return e.jsxs("button",{type:"button",disabled:K.disabled,onClick:()=>He(K.mode),className:T("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",K.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",X?"bg-primary/10":void 0),style:X&&ke?{backgroundColor:ke.background??void 0}:void 0,children:[Le(K.mode,ct),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:ke?ke.text:"var(--foreground)"},children:K.label})})]},K.mode)})})})]})]})})},ls=()=>e.jsx(lt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:pe?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:pe.name||rt()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:at()})]}),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:R.length>0?R.map(({key:H,icon:K,label:X})=>ce(K,X,`cap-${H}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),e.jsx("div",{className:"flex items-center gap-1.5",children:te.length>0?te.map(({key:H,icon:K,label:X})=>ce(K,`${X} input`,`input-${H}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:J.length>0?J.map(({key:H,icon:K,label:X})=>ce(K,`${X} output`,`output-${H}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),ue.map(H=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:H.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:H.value})]},H.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),_e.map(H=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:H.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:H.value})]},H.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ri(pe.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:ni(pe.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),q=()=>e.jsxs(ut,{delayDuration:1e3,children:[N?e.jsxs("button",{type:"button",onClick:()=>D("model"),onTouchStart:()=>ve("model"),onTouchEnd:Pe,onTouchCancel:Pe,className:T("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none",y&&"flex-1","cursor-pointer hover:opacity-70",Ye),children:[n?e.jsx(ss,{providerId:n,className:T(ze,"flex-shrink-0")}):e.jsx(ps,{className:T(ze,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label typography-micro font-medium truncate min-w-0",y?"flex-1":"max-w-[220px]"),children:rt()})]}):e.jsxs(Rt,{open:Me,onOpenChange:$e,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Lt,{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",Ye),children:[n?e.jsxs(e.Fragment,{children:[e.jsx(ss,{providerId:n,className:T(ze,"flex-shrink-0")}),e.jsx(ps,{className:T(ze,"text-primary/60 hidden")})]}):e.jsx(ps,{className:T(ze,"text-muted-foreground")}),e.jsx("span",{className:T("model-controls__model-label",et,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:rt()},`${n}-${o}`)]})})}),e.jsx(_t,{className:"max-w-[300px]",children:s.map(H=>{const K=Array.isArray(H.models)?H.models:[];return K.length===0?e.jsxs(gt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(ss,{providerId:H.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),H.name," (No models)"]},H.id):e.jsxs(pl,{children:[e.jsxs(hl,{className:"typography-meta",children:[e.jsx(ss,{providerId:H.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),H.name]}),e.jsx(gl,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Je,{outerClassName:"max-h-[320px] min-w-[200px]",children:K.map(X=>{const ke=f(H.id,X.id),tt=Gn(ke).map(St=>({...St,id:`cap-${St.key}`})),Ze=[...fr(ke,"input"),...fr(ke,"output")],Ce=Array.from(new Map(Ze.map(St=>[St.key,St])).values()).map(St=>({...St,id:`mod-${St.key}`})),Ve=[...tt,...Ce],Ke=Ns(ke?.limit?.context),Et=Ns(ke?.limit?.output);return e.jsx(gt,{className:"typography-meta",onSelect:()=>{Te(H.id,X.id)},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:qe(X)}),ke?.limit?.context||ke?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ke?.limit?.context?`${Ke} ctx`:"",ke?.limit?.context&&ke?.limit?.output?" • ":"",ke?.limit?.output?`${Et} out`:""]}):null]}),e.jsx("div",{className:"ml-auto flex items-center gap-1",children:Ve.map(({id:St,icon:cs,label:Ir})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":Ir,role:"img",title:Ir,children:e.jsx(cs,{className:"h-3 w-3"})},St))})]})},X.id)})})})]},H.id)})})]}),ls()]}),Fe=()=>{if(!Q)return e.jsx(lt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"No agent selected."})});const H=Object.entries(Q.tools||{}).filter(([,Ce])=>Ce).map(([Ce])=>Ce).sort(),K=!!(Q.prompt&&Q.prompt.trim().length>0),X=Q.model?.providerID&&Q.model?.modelID,ke=Q.temperature!==void 0||Q.topP!==void 0,tt=Ce=>Le(Ce==="full"||Ce==="allow"||Ce==="deny"?Ce:"ask","h-3.5 w-3.5"),Ze=Ce=>Ce==="full"?"Full":Ce==="allow"?"Allow":Ce==="deny"?"Deny":"Ask";return e.jsx(lt,{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:U(Q.name)}),Q.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:Q.description})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Mode"}),e.jsx("span",{className:"typography-meta text-foreground",children:Q.mode==="primary"?"Primary":Q.mode==="subagent"?"Subagent":Q.mode==="all"?"All":"—"})]}),(X||ke)&&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"}),X?e.jsxs("span",{className:"typography-meta text-foreground",children:[Q.model.providerID," / ",Q.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),ke&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[Q.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Q.temperature})]}),Q.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Q.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Tools"}),H.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:H.map(Ce=>e.jsx("span",{className:"inline-flex items-center rounded-lg bg-muted/60 px-1.5 py-0.5 typography-meta text-foreground",children:Ce},Ce))}):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(Q.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ze(Q.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 Q.permission?.bash=="string"?Q.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ze(typeof Q.permission?.bash=="string"?Q.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(Q.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ze(Q.permission?.webfetch)})]})]})]}),K&&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(Xr,{className:"h-4 w-4 text-foreground"})]})]})})},Ue=()=>N?e.jsxs("button",{type:"button",onClick:()=>D("agent"),onTouchStart:()=>ve("agent"),onTouchEnd:Pe,onTouchCancel:Pe,className:T("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Ye,"cursor-pointer hover:opacity-70",N&&"ml-1"),children:[e.jsx(Nr,{className:T(ze,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Ms(a).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",et,"font-medium truncate min-w-0"),style:a?{color:`var(${Ms(a).var})`}:void 0,children:ft()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(ut,{delayDuration:1e3,children:[e.jsxs(Rt,{children:[e.jsx(mt,{asChild:!0,children:e.jsx(Lt,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Ye),children:[e.jsx(Nr,{className:T(ze,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Ms(a).var})`}:void 0}),e.jsx("span",{className:T("model-controls__agent-label",et,"font-medium min-w-0 truncate",C?"max-w-[220px]":void 0),style:a?{color:`var(${Ms(a).var})`}:void 0,children:ft()})]})})}),e.jsxs(_t,{align:"end",children:[t.filter(H=>Vr(H.mode)).map(H=>e.jsx(gt,{className:"typography-meta",onSelect:()=>Oe(H.name),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("h-1 w-1 rounded-full agent-dot",Ms(H.name).class)}),e.jsx("span",{className:"font-medium",children:U(H.name)})]}),H.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:H.description})]})},H.name)),e.jsx($o,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:be,onClick:()=>{be||ie(H=>!H)},className:T("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",be?"cursor-not-allowed opacity-60":void 0),"aria-expanded":he,"aria-controls":Ne,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:de?de.text:"var(--foreground)"},children:Ge})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:T("flex items-center justify-center p-1",!de&&"text-muted-foreground"),style:de?{color:de.text}:void 0,children:Le(G)}),e.jsx(wt,{className:T("h-3.5 w-3.5 transition-transform text-muted-foreground",he?"rotate-180":"")})]})]}),he&&!be&&e.jsx("div",{id:Ne,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:P.map(H=>{const K=H.mode===G,X=hr(H.mode);return e.jsxs("button",{type:"button",disabled:H.disabled,onClick:()=>He(H.mode),className:T("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",H.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",K?"bg-primary/10":void 0),style:K&&X?{backgroundColor:X.background??void 0}:void 0,children:[Le(H.mode,ct),e.jsx("span",{className:"typography-meta font-medium",style:{color:X?X.text:"var(--foreground)"},children:H.label})]},H.mode)})})]})]})]}),Fe()]})}),nt=T("@container/model-controls flex items-center min-w-0",Qe,y&&"w-full",r);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:nt,children:[e.jsx("div",{className:T("flex items-center min-w-0",y?"flex-1 min-w-0 overflow-hidden":"flex-1 min-w-0 justify-end"),children:q()}),e.jsx("div",{className:T("flex items-center min-w-0",Qe,y&&"flex-shrink-0"),children:Ue()})]}),vt(),$t(),pt(),bt()]})},Zp=r=>r?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(r):!0,Qp=(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,m=c>0?r[c-1]:null;if(!Zp(m))continue;const f={name:o.name,source:{value:i[0],start:c,end:d}};n||(n=f)}}return n?{sanitizedText:r,mention:n}:{sanitizedText:r,mention:null}},ai=[{variant:"shine",component:({children:r,className:s,...t})=>e.jsx(lr.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)=>fe.createElement(lr.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(lr.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(lr.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(lr.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 qn({variant:r="shine",className:s,...t}){const a=ai.find(i=>i.variant===r)?.component||ai[0].component;return e.jsx(Ri,{children:e.jsx(a,{...t,className:s})})}const eh=2e3,th=1500;function sh({statusText:r,isWaitingForPermission:s,wasAborted:t,completionId:n,isComplete:o}){const[a,i]=fe.useState(null),[c,d]=fe.useState(!1),[m,f]=fe.useState(!1),[u,p]=fe.useState(!1),[h,g]=fe.useState(null),[x,S]=fe.useState(!1),v=fe.useRef(0),k=fe.useRef([]),b=fe.useRef(!1),w=fe.useRef(null),j=fe.useRef(null),y=fe.useRef(null),C=fe.useRef(null),M=fe.useRef(0),N=fe.useRef(null),A=fe.useRef(!1),D=fe.useRef(!1),I=fe.useRef(!1),z=fe.useRef(!0),E=fe.useRef(null),$=fe.useRef(null),V=(W,ae)=>{if(w.current&&(clearTimeout(w.current),w.current=null),j.current&&(clearTimeout(j.current),j.current=null),y.current&&(clearTimeout(y.current),y.current=null),W==="aborted"){i(null),d(!1),p(!1),g("aborted"),S(!1),N.current="aborted",A.current=!0,D.current=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f(!0)):f(!0);return}g(null),p(!1),N.current=W,A.current=!0,a!==null&&a!==W&&(S(!0),y.current=setTimeout(()=>{S(!1),y.current=null},150)),i(W),d(ae),m||(typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{f(!0)}):f(!0))};if(fe.useEffect(()=>{const W=Date.now();r?(b.current=!1,a?(r!==a||!!s!==c)&&k.current.push({status:r,permission:!!s}):(V(r,!!s),v.current=W,k.current=[])):b.current=!0},[r,s,a,c,t]),fe.useEffect(()=>{t&&(D.current=!0)},[t]),fe.useEffect(()=>{I.current=!!o},[o]),fe.useEffect(()=>{o&&(b.current=!0)},[o]),fe.useEffect(()=>{const W=Me=>{if(u)return;const $e=N.current!==null||A.current;Me&&$e?(p(!1),f(!0),i(null),d(!1),g(Me),N.current=null,S(!1),Me==="success"&&n&&(E.current=n),$.current=Date.now(),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{f(!1),g(null),A.current=!1,j.current=null},th)):(p(!0),f(!1),g(null),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{i(null),d(!1),p(!1),A.current=!1,N.current=null,w.current=null},180)),D.current=!1},je=Me=>{if(Me-M.current<150){C.current=requestAnimationFrame(je);return}M.current=Me;const $e=Date.now(),he=$e-v.current,ie=b.current&&I.current;if(!ie&&k.current.length>0&&he<eh){C.current=requestAnimationFrame(je);return}if(b.current&&D.current)b.current=!1,k.current=[],W("aborted");else if(!ie&&k.current.length>0){const Q=k.current[k.current.length-1];V(Q.status,Q.permission),v.current=$e,k.current=[]}else if(b.current){b.current=!1,k.current.length>0&&(A.current=!0),k.current=[];let Q=null;if(D.current?Q="aborted":I.current&&(Q="success",A.current=!0),Q==="success"&&n&&E.current===n){i(null),d(!1),p(!1),f(!1),g(null),k.current=[],A.current=!1,N.current=null,b.current=!1,D.current=!1,C.current=requestAnimationFrame(je);return}W(Q)}C.current=requestAnimationFrame(je)};return C.current=requestAnimationFrame(je),()=>{C.current!==null&&(cancelAnimationFrame(C.current),C.current=null)}},[u]),fe.useEffect(()=>()=>{w.current&&clearTimeout(w.current),j.current&&clearTimeout(j.current),y.current&&clearTimeout(y.current)},[]),fe.useEffect(()=>{if(typeof window>"u")return;z.current=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0;const W=()=>{z.current=!0},ae=()=>{z.current=!1};return window.addEventListener("focus",W),window.addEventListener("blur",ae),()=>{window.removeEventListener("focus",W),window.removeEventListener("blur",ae)}},[]),fe.useEffect(()=>{const W=()=>{if(typeof document>"u"||typeof Date>"u"||document.visibilityState!=="visible")return;const ae=$.current;(h!==null||a!==null)&&ae&&Date.now()-ae>500&&(i(null),d(!1),p(!1),f(!1),g(null),k.current=[],A.current=!1,N.current=null,b.current=!1,D.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 Y;h==="success"?Y="Done":h==="aborted"?Y="Aborted":a?Y=a.charAt(0).toUpperCase()+a.slice(1):Y="Working";const L=c?"assertive":"polite",_=h===null?`${Y}...`:Y;return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${m&&!u?"opacity-100":"opacity-0"}`,role:"status","aria-live":L,"aria-label":Y,"data-waiting":c?"true":void 0,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[h===null&&e.jsx(qn,{variant:"shine",className:"typography-ui-header transition-opacity duration-150",style:{opacity:x?.6:1},children:_}),h==="success"&&e.jsx(qn,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150",style:{opacity:x?.6:1},children:"Done"}),h==="aborted"&&e.jsx(qn,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150 text-status-error",style:{opacity:x?.6:1},children:"Aborted"})]})})}const rh=r=>!r||typeof r!="object"?!1:!!r.synthetic,yo=r=>!Array.isArray(r)||r.length===0?!1:r.every(s=>rh(s)),nh={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function oh(r){const s=ye(t=>!r||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(r)??"idle");return l.useMemo(()=>{if(s==="idle")return nh;const t=s==="busy",n=s==="cooldown";return{phase:s,isWorking:t||n,isBusy:t,isCooldown:n}},[s])}function Gl(){const r=ye(s=>s.currentSessionId);return oh(r)}const ah={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},ii=r=>r.role==="assistant",ih=r=>r.type==="reasoning",ql=r=>r.type==="text",li=r=>{if(ql(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},ci=r=>(ql(r)||ih(r),r.time),lh=r=>{if(r.tool)return r.tool;const s=r;return typeof s.name=="string"?s.name:"tool"};function Kl(){const{currentSessionId:r,messages:s,permissions:t,sessionAbortFlags:n}=ye(Fo(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=Gl(),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(w=>ii(w.info)&&!yo(w.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const g=[...h].sort((w,j)=>{const y=typeof w.info.time?.created=="number"?w.info.time.created:null,C=typeof j.info.time?.created=="number"?j.info.time.created:null;return y!==null&&C!==null&&y!==C?y-C:w.info.id.localeCompare(j.info.id)}),x=g[g.length-1];let S,v;const k=new Set(["edit","write"]);for(let w=(x.parts??[]).length-1;w>=0;w-=1){const j=x.parts?.[w];if(j)switch(j.type){case"reasoning":{const y=j.time??ci(j);(!y||typeof y.end>"u")&&!S&&(S="reasoning");break}case"tool":{const y=j.state?.status;if((y==="running"||y==="pending")&&!S){const C=lh(j);k.has(C)?S="editing":(S="tool",v=C)}break}case"text":{const y=li(j)??"";if(typeof y=="string"&&y.trim().length>0){const C=ci(j);(!C||typeof C.end>"u")&&!S&&(S="text")}break}}}const b=S==="editing"?"editing":S==="tool"&&v?`using ${v}`:S==="reasoning"?"thinking":S==="text"?"composing":"working";return{activePartType:S,activeToolName:v,statusText:b}},[c]),m=l.useMemo(()=>{const h=r,g=h?n?.get(h)??null:null,x=!!(g&&!g.acknowledged);return{wasAborted:x,abortActive:x}},[r,n]),f=l.useMemo(()=>{if(m.wasAborted)return{...ah,wasAborted:!0,abortActive:m.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,g=o==="busy",x=i;let S="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?S="tooling":S=x?"cooldown":"streaming"),{activity:S,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,m]),u=l.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const g=c.filter(v=>ii(v.info)&&!yo(v.parts));if(g.length===0)return{isActive:h,characterCount:0};const x=g[g.length-1];let S=0;return(x.parts??[]).forEach(v=>{if(v.type!=="text")return;const k=li(v)??"";typeof k=="string"&&k.trim().length>0&&(S+=k.length)}),{isActive:h,characterCount:S}},[c,a,d.activePartType]),p=l.useMemo(()=>{if(f.wasAborted||f.abortActive)return f;const h=r;return(h?t?.get(h)??[]:[]).length>0?{...f,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:f},[r,t,f]);return{forming:u,working:p}}const ch=8,dh=r=>r==="primary"||r==="all"||r===void 0||r===null,Kn=({onOpenSettings:r,scrollToBottom:s})=>{const[t,n]=l.useState(""),[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,m]=l.useState(""),[f,u]=l.useState(!1),[p,h]=l.useState(""),[g,x]=l.useState(!1),[S,v]=l.useState(""),[k,b]=l.useState(null),w=l.useRef(null),j=l.useRef(null),y=l.useRef(null),C=l.useRef(null),M=l.useRef(null),N=ye(q=>q.sendMessage),A=ye(q=>q.currentSessionId),D=ye(q=>q.abortCurrentOperation),I=ye(q=>q.acknowledgeSessionAbort),z=ye(q=>q.abortPromptSessionId),E=ye(q=>q.abortPromptExpiresAt),$=ye(q=>q.clearAbortPrompt),V=ye(q=>q.attachedFiles),Y=ye(q=>q.addAttachedFile),L=ye(q=>q.addServerFile),_=ye(q=>q.clearAttachedFiles),W=ye(q=>q.saveSessionAgentSelection),{currentProviderId:ae,currentModelId:je,currentAgentName:Me,agents:$e,setAgent:he}=xt(),{isMobile:ie}=Re(),{working:Ne}=Kl(),[Q,We]=l.useState(!1),ne=l.useRef(null),B=l.useRef(!1),we=l.useMemo(()=>{if(Me)return $e.find(q=>q.name===Me)},[$e,Me]),oe=l.useMemo(()=>{const q=we?.permission?.edit;let Fe="ask";(q==="allow"||q==="ask"||q==="deny"||q==="full")&&(Fe=q);const Ue=we?we.tools?.edit!==!1:!1;return(!we||!Ue)&&(Fe="deny"),Fe},[we]),Z=ye(l.useCallback(q=>!A||!Me?void 0:q.sessionAgentEditModes.get(A)?.get(Me),[A,Me])),O=we?.permission?.webfetch,re=we?.permission?.bash,ee=l.useMemo(()=>Vl({agentDefaultEditMode:oe,webfetchPermission:O,bashPermission:re}),[oe,O,re]),le=!!(A&&Me),Se=l.useMemo(()=>le&&Z&&ee.modeAvailability[Z]?Z:ee.cascadeDefaultMode,[ee,le,Z]),xe=l.useMemo(()=>hr(Se),[Se]),F=l.useCallback(q=>rs()?`color-mix(in srgb, ${q} 55%, transparent)`:q,[]),G=l.useMemo(()=>{const q=rs()?1:2;if(!xe)return{borderWidth:q};const Fe=xe.border??xe.text;return{borderColor:F(Fe),borderWidth:q}},[xe,F]),P=t.trim()||V.length>0,de=Ne.isWorking,be=l.useMemo(()=>A?z===A&&!!E:!1,[z,E,A]),Ie=de&&(ie||be),Ye=async q=>{if(q?.preventDefault(),!P||!A)return;const Fe=t.replace(/^\n+|\n+$/g,"");s?.({instant:!0,force:!0});const Ue=Fe.trimStart();if(Ue.startsWith("/")&&Ue.slice(1).trim().split(/\s+/)[0]?.toLowerCase()==="summarize"&&s?.({instant:!0,force:!0}),!ae||!je){console.warn("Cannot send message: provider or model not selected");return}const{sanitizedText:nt,mention:H}=Qp(Fe,$e),K=H?.name,X=V.map(ke=>({...ke}));X.length>0&&_(),n(""),await N(nt,ae,je,Me,X,K).catch(ke=>{const tt=ke instanceof Error?ke.message:typeof ke=="string"?ke:String(ke??""),Ze=tt.toLowerCase();console.error("Message send failed:",tt||ke),!(Ze.includes("timeout")||Ze.includes("timed out")||Ze.includes("may still be processing")||Ze.includes("being processed")||Ze.includes("failed to fetch")||Ze.includes("networkerror")||Ze.includes("network error")||Ze.includes("gateway timeout")||Ze==="failed to send message")&&(X.length>0&&As.setState({attachedFiles:X}),ge.error(tt||"Message failed to send. Attachments restored."))}),w.current?.focus()},ct=q=>{if(f&&C.current&&(q.key==="Enter"||q.key==="ArrowUp"||q.key==="ArrowDown"||q.key==="Escape"||q.key==="Tab")){q.preventDefault(),C.current.handleKeyDown(q.key);return}if(g&&M.current&&(q.key==="Enter"||q.key==="ArrowUp"||q.key==="ArrowDown"||q.key==="Escape"||q.key==="Tab")){q.preventDefault(),M.current.handleKeyDown(q.key);return}if(i&&y.current&&(q.key==="Enter"||q.key==="ArrowUp"||q.key==="ArrowDown"||q.key==="Escape"||q.key==="Tab")){q.preventDefault(),y.current.handleKeyDown(q.key);return}if(q.key==="Tab"&&!f&&!i){q.preventDefault(),Qe();return}q.key==="Enter"&&!q.shiftKey&&!ie&&(q.preventDefault(),Ye())},ze=l.useCallback(()=>{ne.current&&(clearTimeout(ne.current),ne.current=null),We(!0),ne.current=setTimeout(()=>{We(!1),ne.current=null},1800)},[]),et=l.useCallback(()=>{$(),ze(),D()},[D,$,ze]),Qe=()=>{const q=$e.filter(H=>dh(H.mode));if(q.length<=1)return;const Ue=(q.findIndex(H=>H.name===Me)+1)%q.length,nt=q[Ue];he(nt.name),A&&W(A,nt.name)},Ge=l.useCallback(()=>{const q=w.current;if(!q)return;q.style.height="auto";const Fe=q.ownerDocument?.defaultView,Ue=Fe?Fe.getComputedStyle(q):null,nt=Ue?parseFloat(Ue.lineHeight):NaN,H=Ue?parseFloat(Ue.paddingTop):NaN,K=Ue?parseFloat(Ue.paddingBottom):NaN,X=22,tt=Number.isNaN(H)||Number.isNaN(K)?16:H+K,Ce=(Number.isNaN(nt)?X:nt)*ch+tt,Ve=q.scrollHeight||q.offsetHeight,Ke=Math.min(Ve,Ce);q.style.height=`${Ke}px`,q.style.maxHeight=`${Ce}px`,b(Et=>Et&&Et.height===Ke&&Et.maxHeight===Ce?Et:{height:Ke,maxHeight:Ce})},[]);l.useLayoutEffect(()=>{Ge()},[Ge,t,ie]);const Le=l.useCallback((q,Fe)=>{if(q.startsWith("/")){const K=q.indexOf(" "),X=q.indexOf(`
25
+ `),ke=Math.min(K===-1?q.length:K,X===-1?q.length:X);if(Fe<=ke&&K===-1){const tt=q.substring(1,ke);h(tt),u(!0),c(!1),x(!1)}else u(!1);return}u(!1);const Ue=q.substring(0,Fe),nt=Ue.lastIndexOf("#");if(nt!==-1){const K=nt>0?Ue[nt-1]:null,X=Ue.substring(nt+1),ke=X.includes(" ")||X.includes(`
26
+ `);if((!K||/\s/.test(K))&&!ke){v(X),x(!0),c(!1);return}}x(!1),v("");const H=Ue.lastIndexOf("@");if(H!==-1){const K=Ue.substring(H+1);!K.includes(" ")&&!K.includes(`
27
+ `)?(m(K),c(!0)):c(!1)}else c(!1)},[v,h,m,x,u,c]),He=l.useCallback(q=>{if(!q)return;const Fe=w.current;if(!Fe){const X=t+q;n(X),Le(X,X.length),requestAnimationFrame(()=>Ge());return}const Ue=Fe.selectionStart??t.length,nt=Fe.selectionEnd??t.length,H=`${t.substring(0,Ue)}${q}${t.substring(nt)}`;n(H);const K=Ue+q.length;requestAnimationFrame(()=>{const X=w.current;X&&(X.selectionStart=K,X.selectionEnd=K),Ge()}),Le(H,K)},[Ge,t,Le]),ot=q=>{const Fe=q.target.value,Ue=q.target.selectionStart??Fe.length;n(Fe),Ge(),Le(Fe,Ue)},dt=l.useCallback(async q=>{const Fe=new Map;Array.from(q.clipboardData.files||[]).forEach(K=>{K.type.startsWith("image/")&&Fe.set(`${K.name}-${K.size}`,K)}),Array.from(q.clipboardData.items||[]).forEach(K=>{if(K.kind==="file"&&K.type.startsWith("image/")){const X=K.getAsFile();X&&Fe.set(`${X.name}-${X.size}`,X)}});const Ue=Array.from(Fe.values());if(Ue.length===0||!A)return;q.preventDefault();const nt=q.clipboardData.getData("text");nt&&He(nt);let H=0;for(const K of Ue){const X=ye.getState().attachedFiles.length;try{await Y(K),ye.getState().attachedFiles.length>X&&(H+=1)}catch(ke){console.error("Clipboard image attach failed",ke),ge.error(ke instanceof Error?ke.message:"Failed to attach image from clipboard")}}H>0&&ge.success(`Attached ${H} image${H>1?"s":""} from clipboard`)},[Y,A,He]),pe=q=>{const Fe=w.current?.selectionStart||0,nt=t.substring(0,Fe).lastIndexOf("@");if(nt!==-1){const H=t.substring(0,nt)+q.name+t.substring(Fe);n(H)}c(!1),m(""),w.current?.focus()},R=q=>{const Ue=w.current?.selectionStart??t.length,H=t.substring(0,Ue).lastIndexOf("#");if(H!==-1){const K=t.substring(0,H)+`#${q} `+t.substring(Ue);n(K);const X=H+q.length+2;requestAnimationFrame(()=>{w.current&&(w.current.selectionStart=X,w.current.selectionEnd=X),Ge(),Le(K,X)})}x(!1),v(""),w.current?.focus()},te=q=>{n(`/${q.name} `);const Fe=w.current;Fe&&(Fe._commandMetadata=q),u(!1),h(""),setTimeout(()=>{w.current&&(w.current.focus(),w.current.setSelectionRange(w.current.value.length,w.current.value.length))},0)};l.useEffect(()=>{A&&w.current&&!ie&&w.current.focus()},[A,ie]),l.useEffect(()=>{z&&z!==A&&$()},[z,A,$]);const J=q=>{q.preventDefault(),q.stopPropagation(),A&&!o&&a(!0)},ue=q=>{q.preventDefault(),q.stopPropagation(),q.currentTarget===q.target&&a(!1)},_e=async q=>{if(q.preventDefault(),q.stopPropagation(),a(!1),!A)return;const Fe=Array.from(q.dataTransfer.files);let Ue=0;for(const nt of Fe){const H=ye.getState().attachedFiles.length;try{await Y(nt),ye.getState().attachedFiles.length>H&&(Ue+=1)}catch(K){console.error("File attach failed",K),ge.error(K instanceof Error?K.message:"Failed to attach file")}}Ue>0&&ge.success(`Attached ${Ue} file${Ue>1?"s":""}`)},it=l.useCallback(async q=>{let Fe=0;for(const Ue of q){const nt=ye.getState().attachedFiles.length;try{await L(Ue.path,Ue.name),ye.getState().attachedFiles.length>nt&&(Fe+=1)}catch(H){console.error("Server file attach failed",H),ge.error(H instanceof Error?H.message:"Failed to attach file")}}Fe>0&&ge.success(`Attached ${Fe} file${Fe>1?"s":""}`)},[L]),Ee=l.useRef(null),[Be,me]=l.useState(!1),Oe=l.useCallback(async q=>{let Fe=0;const Ue=Array.isArray(q)?q:Array.from(q);for(const nt of Ue){const H=ye.getState().attachedFiles.length;try{await Y(nt),ye.getState().attachedFiles.length>H&&(Fe+=1)}catch(K){console.error("File attach failed",K),ge.error(K instanceof Error?K.message:"Failed to attach file")}}Fe>0&&ge.success(`Attached ${Fe} file${Fe>1?"s":""}`)},[Y]),Te=l.useCallback(async()=>{try{const Fe=await(await fetch("/api/vscode/pick-files")).json(),Ue=Array.isArray(Fe?.files)?Fe.files:[],nt=Array.isArray(Fe?.skipped)?Fe.skipped:[];if(nt.length>0){const K=nt.map(X=>`${X?.name||"file"}: ${X?.reason||"skipped"}`).join(`
28
+ `);ge.error(`Some files were skipped:
29
+ ${K}`)}const H=Ue.map(K=>{if(!K?.dataUrl)return null;try{const[X,ke]=K.dataUrl.split(","),tt=K.mimeType||X?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!ke)return null;const Ze=atob(ke),Ce=new Uint8Array(Ze.length);for(let Ke=0;Ke<Ze.length;Ke++)Ce[Ke]=Ze.charCodeAt(Ke);const Ve=new Blob([Ce],{type:tt});return new File([Ve],K.name||"file",{type:tt})}catch(X){return console.error("Failed to decode VS Code picked file",X),null}}).filter(Boolean);H.length>0&&await Oe(H)}catch(q){console.error("VS Code file pick failed",q),ge.error(q instanceof Error?q.message:"Failed to pick files in VS Code")}},[Oe]),qe=l.useCallback(()=>{if(rs()){Te();return}Ee.current?.click()},[Te]),at=l.useCallback(async q=>{const Fe=q.target.files;Fe&&(await Oe(Fe),q.target.value="")},[Oe]),rt="gap-x-1.5 gap-y-0",ft=rs(),U=ie?"px-1.5 py-1.5":ft?"px-1.5 py-1":"px-2.5 py-1.5",ce=ie?"h-9 w-9":ft?"h-[22px] w-[22px]":"h-7 w-7",se=ie?"h-5 w-5":ft?"h-4 w-4":"h-[18px] w-[18px]",ve=T(ce,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Pe=e.jsx("button",{type:"submit",disabled:!P||!A,className:T(ve,P&&A?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Ad,{className:T(se)})}),pt=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:Ee,type:"file",multiple:!0,className:"hidden",onChange:at,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(Wp,{onFilesSelected:it,multiSelect:!0,presentation:ie||ft?"modal":"dropdown",open:Be,onOpenChange:me,children:ie||ft?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Rt,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx("button",{type:"button",className:ve,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(Dd,{className:T(se,"text-current")})})}),e.jsxs(_t,{align:"start",children:[e.jsxs(gt,{onSelect:()=>{requestAnimationFrame(()=>qe())},children:[e.jsx(oo,{}),"Attach files"]}),e.jsxs(gt,{onSelect:()=>{requestAnimationFrame(()=>{me(!0)})},children:[e.jsx(Ed,{}),"Attach from project"]})]})]})]})]}),bt=r?e.jsx("button",{type:"button",onClick:r,className:ve,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(Nr,{className:T(se,"text-current")})}):null,vt=e.jsxs(e.Fragment,{children:[pt,bt]}),$t=Ne.statusText;l.useEffect(()=>{const q=!!Ne.wasAborted;!B.current&&q&&!Q&&(ze(),A&&I(A)),B.current=q},[I,A,Q,ze,Ne.wasAborted]),l.useEffect(()=>()=>{ne.current&&(clearTimeout(ne.current),ne.current=null)},[]);const ls=!Q&&(Ne.wasAborted||!Ne.abortActive);return e.jsxs("form",{onSubmit:Ye,className:"pt-0 pb-4 bottom-safe-area",children:[e.jsxs("div",{className:"chat-column mb-1.5 h-[1.2rem] flex items-center justify-between gap-2 overflow-visible",children:[e.jsx("div",{className:"flex-1 flex items-center overflow-hidden",children:Q?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-header",children:[e.jsx(Zs,{size:18,"aria-hidden":"true"}),"Aborted"]})}):ls?e.jsx(sh,{statusText:$t,isWaitingForPermission:Ne.isWaitingForPermission,wasAborted:Ne.wasAborted,completionId:Ne.lastCompletionId,isComplete:Ne.isComplete},A??"no-session"):null}),Ie?e.jsx("div",{className:"flex-shrink-0 pr-[2ch]",children:ie?e.jsx("button",{type:"button",onClick:et,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","aria-label":"Stop generating",children:e.jsx(Zs,{size:18,"aria-hidden":"true"})}):e.jsxs("button",{type:"button",onClick:et,className:"inline-flex h-[1.2rem] items-center gap-0.5 rounded-md bg-[var(--status-error)]/70 px-1 text-[0.65rem] font-medium text-white hover:bg-[var(--status-error)]/85 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--status-error)]/40","aria-label":"Stop generating",children:[e.jsx(Zs,{size:11,className:"text-white","aria-hidden":"true"}),"Abort"]})}):null]}),e.jsxs("div",{ref:j,className:T("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:J,onDragLeave:ue,onDrop:_e,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:ve,onClick:()=>qe(),title:"Attach files","aria-label":"Attach files",children:e.jsx(oo,{className:T(se,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Bp,{}),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:G,children:[f&&e.jsx(Hl,{ref:C,searchQuery:p,onCommandSelect:te,onClose:()=>u(!1)}),g&&e.jsx(Wl,{ref:M,searchQuery:S,onAgentSelect:R,onClose:()=>x(!1)}),i&&e.jsx(Op,{ref:y,searchQuery:d,onFileSelect:pe,onClose:()=>c(!1)}),e.jsx(Us,{ref:w,"data-chat-input":"true",value:t,onChange:ot,onKeyDown:ct,onPaste:dt,placeholder:A?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!A,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",U,ie?"flex items-center gap-x-1.5":T("flex items-center justify-between",rt)),"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:vt}),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(oi,{className:T("w-full flex items-center justify-end min-w-0")})}),Pe]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("flex items-center flex-shrink-0",rt),children:vt}),e.jsxs("div",{className:T("flex items-center flex-1 justify-end",rt,"md:gap-x-3"),children:[e.jsx(oi,{className:T("flex-1 min-w-0 justify-end")}),Pe]})]})})]})]})]})};function Yn({className:r,...s}){return e.jsx("div",{"data-slot":"skeleton",className:T("bg-accent animate-pulse rounded-xl",r),...s})}const di=({className:r="",width:s=70,height:t=70,isAnimated:n=!1})=>{const o=Uo();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})]})},uh={'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"}},mh={'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 Ds{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Ds.instance||(Ds.instance=new Ds),Ds.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 Yl(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 zt=({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})},fh=({isUser:r,providerID:s,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=El(s);return e.jsx(zt,{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(kn,{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(Sn,{className:"h-4 w-4",style:{color:`var(${Ms(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",Ms(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},ph=l.memo(fh),ui=(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},mi=()=>{if(!rs()||typeof window>"u")return La;const r=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(r?.light&&r?.dark){const s=ui({...r.light},`vscode-shiki-light:${String(r.light?.name??"theme")}`),t=ui({...r.dark},`vscode-shiki-dark:${String(r.dark?.name??"theme")}`);return[s,t]}return La},Xl=()=>{const[r,s]=l.useState(mi);return l.useEffect(()=>{if(!rs()||typeof window>"u")return;const t=n=>{s(mi())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),r},Jl=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(m=>d.push(m.innerText.trim())),t.push(d)}),{headers:s,rows:t}},Zl=({headers:r,rows:s})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
30
+ `)?`"${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(`
31
+ `)},hh=({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(`
32
+ `)},gh=({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(`
33
+ `)},yh=(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)},xh=({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 m=Jl(d),f=c==="csv"?Zl(m):hh(m);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([f],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),t(!0),o(!1),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy table:",m)}};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(Nt,{className:"size-3.5"}):e.jsx(ks,{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"})]})]})},bh=({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=Jl(i),d=a==="csv"?Zl(c):gh(c);yh(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(ko,{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"})]})]})},wh=({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(xh,{tableRef:t}),e.jsx(bh,{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})})]})},vh=({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 f={...t},u=g=>{if(typeof g!="string")return{value:void 0,vars:{}};const[x,...S]=g.split(";").map(k=>k.trim()).filter(Boolean),v={};for(const k of S){const b=k.indexOf(":");if(b===-1)continue;const w=k.slice(0,b).trim(),j=k.slice(b+1).trim();!w.startsWith("--")||j.length===0||(v[w]=j)}return{value:x,vars:v}},p=u(t.backgroundColor);p.value&&(f.backgroundColor=p.value,f["--shiki-light-bg"]=p.value);for(const[g,x]of Object.entries(p.vars))f[g]=x;const h=u(t.color);h.value&&(f.color=h.value,f["--shiki-light"]=h.value);for(const[g,x]of Object.entries(h.vars))f[g]=x;return f},[t]),d=()=>i.current&&i.current.querySelector("code")?.innerText||"",m=async()=>{const f=d();if(f)try{await navigator.clipboard.writeText(f),a(!0),setTimeout(()=>a(!1),2e3)}catch(u){console.error("Failed to copy:",u)}};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:m,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(Nt,{className:"size-3.5"}):e.jsx(ks,{className:"size-3.5"})})})]})},Ql={pre:vh,table:wh},Sh=({content:r,part:s,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1})=>{const i=Xl(),c=l.useMemo(()=>`markdown-${s?.id?`part-${s.id}`:`message-${t}`}`,[t,s?.id]),d=e.jsx("div",{className:T("break-words",o),children:e.jsx(Mr,{mode:a?"streaming":"static",shikiTheme:i,className:"streamdown-content",controls:{code:!1,table:!1},components:Ql,children:r})});return n?e.jsx(zt,{children:d},c):d},jh=({content:r,className:s})=>{const t=Xl();return e.jsx("div",{className:T("break-words",s),children:e.jsx(Mr,{mode:"static",shikiTheme:t,className:"streamdown-content",controls:{code:!1,table:!1},components:Ql,children:r})})},kh={thinking:{label:"Thinking",Icon:Sn},justification:{label:"Justification",Icon:No}},ec=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
34
+ `).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
35
+ `).trim(),Nh=r=>{if(!r)return"";const s=r.trim(),t=s.indexOf(`
36
+ `),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},Jo=({text:r,variant:s,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>Nh(r),[r]),{label:c,Icon:d}=kh[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(m=>!m),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(wt,{className:"h-3.5 w-3.5"}):e.jsx(xs,{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(Je,{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(Jo,{text:a,variant:"thinking",onContentChange:s,blockId:r.id||`${t}-reasoning`}):null},Ch=r=>ec(r),Mh=({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||"",m=l.useMemo(()=>a?Ch(d):d,[d,a]),f=t==="streaming",u=t==="cooldown",p=l.useRef(f);if(f||u)return p.current=!0,null;const h=i.time;return!(h&&typeof h.end<"u")&&(!m||m.trim().length===0)||!m||m.trim().length===0?null:a?e.jsx(Jo,{text:m,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(Sh,{content:m,part:r,messageId:s,isAnimated:n,isStreaming:!1})},r.id||`${s}-text`)},Ah=r=>`https://opencode.ai/docs/agents/#${encodeURIComponent(r)}`,Dh=({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,m]=l.useState(!1),f=l.useRef(null);l.useEffect(()=>{const h=f.current;h&&!i&&m(h.scrollHeight>h.clientHeight)},[a,i]);const u=l.useCallback(()=>{(d||i)&&c(h=>!h)},[d,i]);if(!a||a.trim().length===0)return null;const p=()=>{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:Ah(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:S=>S.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:f,onClick:u,children:p()},r.id||`${s}-user-text`)},Eh=l.memo(Dh),sc={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Th={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"},gs={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)"}}},sn={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...gs.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:sn.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...gs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:sn.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...gs.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:sn.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...gs.tool.inline})},Ih=r=>{let s=r.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},rc=r=>r?r.includes("<file_diagnostics>")||r.includes("This file has errors")||r.includes("please fix"):!1,Fh=r=>r?r.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",fi=(r,s)=>!r||typeof r!="object"?String(r):wf(r,s||""),Xn=(r,s,t)=>{let n=Ih(r);if((s==="edit"||s==="multiedit")&&rc(n)&&(n=Fh(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Ph=(r,s)=>{try{const t=r.trim().split(`
37
+ `).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),m=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:m})}}),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:gs.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}},Rh=(r,s,t)=>{try{const n=r.trim().split(`
38
+ `).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,m]=i,f=m!==void 0?d:"",u=m!==void 0?m:d;o[c]||(o[c]=[]),o[c].push({lineNum:f,content:u})}}),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:gs.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}},Lh=(r,s,t)=>{try{const n=r.trim().split(`
39
+ `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",m=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(m)});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:gs.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}},_h=(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:gs.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(Nt,{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(Nt,{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}},Bh=(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:gs.tool.popup,children:e.jsx(Mr,{mode:"static",className:"streamdown-content streamdown-tool",children:r})})}catch{return null}},Oh=r=>{const s=r.split(`
40
+ `);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,m=[];let f=d,u=o+1;for(;u<s.length&&!s[u].startsWith("@@")&&!s[u].startsWith("Index:");){const p=s[u];p.startsWith("+")?(m.push({type:"added",lineNumber:f,content:p.substring(1)}),f++):p.startsWith("-")?m.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(m.push({type:"context",lineNumber:f,content:p.substring(1)}),f++),u++}n.push({file:t,oldStart:c,newStart:d,lines:m}),o=u;continue}o++}return n},xo=(r,s,t)=>bf(s,r,t),$h=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(Td,{className:s}):t==="write"||t==="create"||t==="file_write"?e.jsx(Id,{className:s}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(ao,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Fs,{className:s}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(Yt,{className:s}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(Fd,{className:s}):t==="glob"?e.jsx(Pd,{className:s}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(io,{className:s}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(io,{className:s}):t==="todowrite"||t==="todoread"?e.jsx(Rd,{className:s}):t.startsWith("git")?e.jsx(Tt,{className:s}):e.jsx(Po,{className:s})},zh=(r,s)=>{const n=(s?s-r:Date.now()-r)/1e3;return`${(n<.05&&s!==void 0?.1:n).toFixed(1)}s`},Hh=r=>{if(!r?.diff||typeof r.diff!="string")return null;const s=r.diff.split(`
41
+ `);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},Wh=(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(`
42
+ `)[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:""},Uh=({children:r,maxHeightClass:s="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(Je,{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})}),Vh=({diff:r,syntaxTheme:s,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Oh(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(ms,{style:s,language:Mn(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))}),Gh=({content:r,syntaxTheme:s,filePath:t,displayPath:n})=>{const o=r.split(`
43
+ `),a=Mn(t??"")||xo(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,m)=>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:m+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ms,{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||" "})})]},m))})]})},qh=({part:r,state:s,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const c=s,d=c.metadata,m=c.input,f=c.output,u=typeof f=="string"&&f.length>0,p=typeof f=="string"?f:"",h=typeof d?.diff=="string"?d.diff:null,g=r.tool==="write"?typeof m?.filePath=="string"?m.filePath:typeof m?.file_path=="string"?m.file_path:typeof m?.path=="string"?m.path:void 0:void 0,x=r.tool==="write"?typeof m?.content=="string"?m.content:typeof m?.text=="string"?m.text:null:null,S=r.tool==="write"&&!!x,v=S?g?bo(g,o,n):"New file":null,k=l.useMemo(()=>!m||typeof m!="object"||Object.keys(m).length===0?"":"command"in m&&typeof m.command=="string"&&r.tool==="bash"?fi(m,r.tool):typeof m.content=="string"?m.content??"":fi(m,r.tool),[m,r.tool]),b=k.trim().length>0,w=(y,C)=>e.jsx(Uh,{maxHeightClass:C?.maxHeightClass,className:C?.className,disableHorizontal:C?.disableHorizontal,outerClassName:C?.outerClassName,children:y}),j=()=>{if(r.tool==="todowrite"||r.tool==="todoread"){if(s.status==="completed"&&u){const y=_h(p,{unstyled:!0});return w(y??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"&&u){const y=Ph(p,{unstyled:!0});return w(y??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="grep"&&u){const y=Rh(p,n,{unstyled:!0});return w(y??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="glob"&&u){const y=Lh(p,n,{unstyled:!0});return w(y??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="task"&&u)return w(e.jsx("div",{className:"w-full min-w-0",style:{fontSize:"var(--text-code)"},children:e.jsx(Mr,{mode:"static",className:"streamdown-content streamdown-tool",children:p})}));if((r.tool==="web-search"||r.tool==="websearch"||r.tool==="search_web")&&u){const y=Bh(p,t,{unstyled:!0});return w(y??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="codesearch"&&u)return w(e.jsx("div",{className:"w-full min-w-0",style:{fontSize:"var(--text-code)"},children:e.jsx(Mr,{mode:"static",className:"streamdown-content streamdown-tool",children:p})}));if((r.tool==="edit"||r.tool==="multiedit")&&(!u&&h||p.trim().length===0||rc(p))&&h)return w(e.jsx(Vh,{diff:h,syntaxTheme:t,input:m}),{className:"p-1"});if(u&&p.trim()){if(r.tool==="read"){const y=Xn(p,r.tool,d),C=y.split(`
44
+ `),M=typeof m?.offset=="number"?m.offset:0,N=typeof m?.limit=="number"?m.limit:void 0,A=D=>D.trim().startsWith("(");return w(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:C.map((D,I)=>{const z=A(D),E=M+I+1,$=!z&&(N===void 0||I<N);return e.jsxs("div",{className:T("typography-code font-mono flex w-full min-w-0",z&&"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:$?E:""}),e.jsx("div",{className:"flex-1 min-w-0",children:z?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:D}):e.jsx(ms,{style:t,language:xo(y,r.tool,m),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:D})})]},I)})}),{className:"p-1"})}return w(e.jsx(ms,{style:t,language:xo(Xn(p,r.tool,d),r.tool,m),PreTag:"div",customStyle:{...sn.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Xn(p,r.tool,d)}),{className:"p-1"})}return w(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:r.tool==="todowrite"||r.tool==="todoread"?j():e.jsxs(e.Fragment,{children:[S?e.jsx("div",{className:"my-1",children:w(e.jsx(Gh,{content:x,syntaxTheme:t,filePath:g,displayPath:v??"New file"}))}):b?e.jsx("div",{className:"my-1",children:w(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:k}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,r.tool!=="write"&&s.status==="completed"&&"output"in s&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),j()]}),s.status==="error"&&"error"in s&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:s.error})]})]})})},wo=({part:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=r.state,m=yt(M=>M.currentDirectory),f=d.status==="completed"||d.status==="error",u=d.status==="running",p=d.status==="error",[h,g]=l.useState(Date.now());l.useEffect(()=>{if(u){const M=setInterval(()=>{g(Date.now())},100);return()=>clearInterval(M)}},[u]);const x=l.useRef(s);l.useEffect(()=>{f&&x.current!==s&&(x.current=s,typeof s=="boolean"&&a?.("structural"))},[s,f,a]);const S=d,v=S.metadata,k=S.input,b=r.tool==="edit"||r.tool==="multiedit"?Hh(v):null,w=Wh(r,d,o,m),j=yl(r.tool).displayName,y=l.useContext(zo),C=M=>{if(!y?.editor){t(r.id);return}let N;if((r.tool==="edit"||r.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(r.tool))&&(N=k?.filePath||k?.file_path||k?.path||v?.filePath||v?.file_path||v?.path),typeof N=="string"){M.stopPropagation();let A=N;N.startsWith("/")||(A=m.endsWith("/")?m+N:m+"/"+N),y.editor.openFile(A)}else t(r.id)};return f?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:C,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:M=>{M.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?{color:"var(--status-error)"}:{},children:$h(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(wt,{className:"h-3.5 w-3.5"}):e.jsx(xs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:p?{color:"var(--status-error)"}:{},children:j})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[w&&e.jsx("span",{className:T("truncate",o&&"max-w-[120px]"),children:w}),b&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",b.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",b.removed]})]}),"time"in d&&d.time&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:zh(d.time.start,f&&"end"in d.time?d.time.end:h)})]})]}),s&&e.jsx(qh,{part:r,state:d,syntaxTheme:n,isMobile:o,currentDirectory:m,hasPrevTool:i,hasNextTool:c})]}):null},Kh=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
45
+ `).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
46
+ `).trim(),Yh=({part:r,messageId:s,onContentChange:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>Kh(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Jo,{text:a,variant:"justification",onContentChange:t,blockId:r.id||`${s}-justification`}):null},Xh=l.memo(Yh),Jh=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(", ")},Jn=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}),Zh=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},Qh=({parts:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:m,diffStats:f})=>{const u=l.useRef(s);l.useEffect(()=>{u.current!==s&&(u.current=s,c?.("structural"))},[s,c]);const p=l.useMemo(()=>Jn(!d||s?r:r.filter(x=>x.part.id&&m.has(x.id))),[r,d,s,m]),h=Jh(p),g=Zh(p);return p.length===0?null:e.jsx(zt,{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(Ld,{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(wt,{className:"h-3.5 w-3.5"}):e.jsx(xs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(h||f)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[h&&e.jsx("span",{className:"truncate block",children:h}),f&&(f.additions>0||f.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,f.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,f.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:p.map((x,S)=>{const v=x.part.id||`group-part-${S}`,k=g[v];switch(x.kind){case"tool":return e.jsx(zt,{children:e.jsx(wo,{part:x.part,isExpanded:a.has(v),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:k?.hasPrev??!1,hasNextTool:k?.hasNext??!1})},v);case"reasoning":return e.jsx(zt,{children:e.jsx(tc,{part:x.part,messageId:x.messageId,onContentChange:c})},v);case"justification":return e.jsx(zt,{children:e.jsx(Xh,{part:x.part,messageId:x.messageId,onContentChange:c})},v);default:return null}})})]})})},eg=l.memo(Qh),tg=({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}),Zn=l.memo(tg),nc=r=>{const s=r,t=s.text;return typeof t=="string"?t:s.content||s.value||""},oc=r=>{if(r.type!=="text")return!1;const s=nc(r);return!s||s.trim().length===0},sg=(r,s={})=>{const{includeReasoning:t=!0}=s;return r.filter(n=>!!n.synthetic||!t&&n.type==="reasoning"?!1:!(n.type==="patch"))},rg=(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),m=s.size>0;return l.useEffect(()=>{r&&r.isWorking&&(r.isGroupExpanded||m&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const f=i.current;if(!f)return;const u=Array.from(c.current);u.length>0&&f.markPartsPreviewed(u)},300)},1e3))))},[m,r]),l.useEffect(()=>{r&&(!r.isWorking||r.isGroupExpanded||!m)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[m,r]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},ng=({messageId:r,parts:s,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d})=>{const[m,f]=l.useState(!1),u=l.useRef(null),p=l.useMemo(()=>s.filter(y=>y.type!=="text"?!1:!oc(y)),[s]),h=d?.token;let g=!1;const x=!!a,S=!!i,v=!!(n??t),k=!!o,b=l.useCallback(()=>{u.current!==null&&typeof window<"u"&&(window.clearTimeout(u.current),u.current=null)},[]),w=l.useCallback(()=>{!v||!x||!k||typeof window>"u"||(b(),f(!0),u.current=window.setTimeout(()=>{f(!1),u.current=null},1800))},[x,b,k,v]);l.useEffect(()=>{k||(f(!1),b())},[b,k]);const j=l.useCallback(y=>{!a||!k||(y.stopPropagation(),y.preventDefault(),a(),v&&w())},[k,v,a,w]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:v&&x&&k?w:void 0,children:[x&&e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":m||S?"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",(m||S)&&"opacity-100 pointer-events-auto"),style:{insetInlineEnd:"0.32rem",insetBlockStart:"-0.28rem"},disabled:!k,"aria-label":"Copy message text","aria-hidden":!k,onPointerDown:y=>y.stopPropagation(),onClick:j,onFocus:()=>{k&&f(!0)},onBlur:()=>{S||f(!1)},children:S?e.jsx(Nt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(ks,{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:p.map((y,C)=>{let M;return d&&h&&!g&&nc(y).includes(h)&&(M=d,g=!0),e.jsx(zt,{children:e.jsx(Eh,{part:y,messageId:r,isMobile:t,agentMention:M})},`user-text-${C}`)})}),e.jsx($l,{files:s,onShowPopup:c})]})]})},og=({messageId:r,parts:s,isMessageCompleted:t,syntaxTheme:n,isMobile:o,hasTouchInput:a,copiedCode:i,onCopyCode:c,expandedTools:d,onToggleTool:m,onShowPopup:f,streamPhase:u,allowAnimation:p,onContentChange:h,shouldShowHeader:g=!0,hasTextContent:x=!1,onCopyMessage:S,copiedMessage:v=!1,onAuxiliaryContentComplete:k,showReasoningTraces:b=!1,turnGroupingContext:w})=>{const[j,y]=l.useState(!1),C=l.useRef(null),M=!!S,N=!!v,A=!!(a??o),D=!t,I=l.useMemo(()=>s.filter(me=>!oc(me)).filter(me=>me.type!=="compaction"),[s]),z=l.useMemo(()=>I.filter(me=>me.type==="tool"),[I]),E=l.useMemo(()=>I.filter(me=>me.type==="text"),[I]),$=ye(me=>me.createSessionFromAssistantMessage),V=w?.isLastAssistantInTurn??!1,Y=l.useMemo(()=>s.some(me=>me.type==="step-finish"&&me.reason==="stop"),[s]),L=z.length>0,_=l.useMemo(()=>z.some(me=>{const Te=(me.state??{})?.status;return Te==="pending"||Te==="running"||Te==="started"}),[z]),W=l.useCallback(me=>{const Oe=me.state??{},Te=Oe?.status;if(Te==="pending"||Te==="running"||Te==="started")return!1;const qe=Oe?.time??{},at=typeof qe?.end=="number"?qe.end:void 0,rt=typeof qe?.start=="number"?qe.start:void 0;return!(typeof at!="number"||typeof rt=="number"&&at<rt)},[]),ae=l.useMemo(()=>z.length===0?!0:_?!1:z.every(me=>W(me)),[z,_,W]),je=l.useMemo(()=>E.length===0?!0:E.every(me=>typeof me.time?.end=="number"),[E]),Me=l.useMemo(()=>I.filter(me=>me.type==="reasoning"),[I]),$e=l.useMemo(()=>Me.length===0?!0:Me.every(me=>typeof me.time?.end=="number"),[Me]),ie=l.useMemo(()=>{let me=0,Oe=0;return I.forEach(Te=>{Te.type==="step-start"?me+=1:Te.type==="step-finish"&&(Oe+=1)}),{stepStarts:me,stepFinishes:Oe,hasOpenStep:me>Oe}},[I]).hasOpenStep,Ne=Me.length>0&&L&&(_||ie||!ae),Q=l.useMemo(()=>L?E.length===0?ie||_||!ae:!0:E.length>0?Ne:!1,[E.length,ie,_,L,Ne,ae]),We=D||Q&&(!je||!ae||_||ie)||Ne,ne=D||L&&(_||ie||!ae),B=D||Ne,we=L||Me.length>0,oe=E.length===0,Z=we&&oe&&!ne&&!B&&ae&&$e,O=l.useRef(!1),re=l.useRef(!1);l.useEffect(()=>{re.current=!1},[r]),l.useEffect(()=>{if(!Z){O.current=!1;return}O.current||(O.current=!0,k?.())},[Z,k]),l.useEffect(()=>{if(D){re.current=!1;return}if(L){re.current=!1;return}Me.length!==0&&(B||!$e||re.current||(re.current=!0,h?.("structural")))},[D,L,h,$e,Me.length,B]);const ee=!!x&&!D,le=l.useCallback(()=>{C.current!==null&&typeof window<"u"&&(window.clearTimeout(C.current),C.current=null)},[]),Se=l.useCallback(()=>{!A||!M||!ee||typeof window>"u"||(le(),y(!0),C.current=window.setTimeout(()=>{y(!1),C.current=null},1800))},[M,le,ee,A]);l.useEffect(()=>{ee||(y(!1),le())},[le,ee]);const xe=l.useCallback(me=>{!S||!ee||(me.stopPropagation(),me.preventDefault(),S(),A&&Se())},[ee,A,S,Se]),F=l.useCallback(me=>{me.stopPropagation(),me.preventDefault(),$&&$(r)},[$,r]);l.useEffect(()=>()=>{le()},[le]);const G=l.useMemo(()=>{const me={},Oe=z.filter(Te=>ne?!1:W(Te));return Oe.forEach((Te,qe)=>{me[Te.id]={hasPrev:qe>0,hasNext:qe<Oe.length-1}}),me},[z,ne,W]),P=l.useMemo(()=>w?.activityParts??[],[w]),de=l.useMemo(()=>w?P.filter(me=>me.messageId===r):[],[P,r,w]),be=l.useMemo(()=>{const me=new Map;return de.forEach(Oe=>{me.set(Oe.part,Oe)}),me},[de]),Ie=l.useMemo(()=>w?b?P:P.filter(me=>me.kind==="tool"):[],[P,b,w]),[Ye,ct]=l.useState(!1);l.useEffect(()=>{w&&Ie.length>1&&ct(!0)},[w,Ie.length]);const ze=!!(w&&Ye),et=l.useMemo(()=>{if(!w)return[];if(!ze)return[];if(!w.isWorking||w.isGroupExpanded)return[];const me=[];return de.forEach(Oe=>{if(w.previewedPartIds.has(Oe.id)||!b&&Oe.kind!=="tool")return;const Te=Oe.part;if(Oe.kind==="tool"){const qe=Te;if(ne||!W(qe))return}else if(Oe.kind==="reasoning"){if(!b||B||typeof Te.time?.end!="number")return}else if(Oe.kind==="justification"&&(!b||We||typeof Te.time?.end!="number"))return;me.push(Oe)}),me},[de,W,We,B,ne,b,ze,w]),Qe=l.useMemo(()=>{const me=new Set;return et.forEach(Oe=>{me.add(Oe.id)}),me},[et]),{isAnimating:Ge}=rg(w,Qe),Le=l.useMemo(()=>{const me=[];w&&w.isFirstAssistantInTurn&&ze&&Ie.length>0&&me.push(e.jsx(eg,{parts:Ie,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:n,isMobile:o,expandedTools:d,onToggleTool:m,onShowPopup:f,onContentChange:h,isWorking:w.isWorking,previewedPartIds:w.previewedPartIds,diffStats:w.diffStats},"progressive-group"));const Oe=[];return I.forEach((Te,qe)=>{const at=be.get(Te);if(!at||!w)return;let rt=null,ft=null;if(!ze){if(at.kind==="tool"){const ce=Te,ve=ce.state?.time,Pe=W(ce);if(!(!ne&&Pe))return;const bt=G[ce.id];ft=e.jsx(zt,{children:e.jsx(wo,{part:ce,isExpanded:d.has(ce.id),onToggle:m,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:bt?.hasPrev??!1,hasNextTool:bt?.hasNext??!1})},`tool-${ce.id}`),rt=Pe&&typeof ve?.end=="number"?ve.end:null}ft&&Oe.push({part:Te,index:qe,endTime:rt,element:ft});return}if(!w.isWorking||w.isGroupExpanded||w.previewedPartIds.has(at.id)||!b&&at.kind!=="tool")return;const U=Qe.has(at.id);switch(at.kind){case"tool":{const ce=Te,ve=ce.state?.time,Pe=W(ce);if(!(!ne&&Pe))break;const bt=G[ce.id],vt=e.jsx(zt,{children:e.jsx(wo,{part:ce,isExpanded:d.has(ce.id),onToggle:m,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:bt?.hasPrev??!1,hasNextTool:bt?.hasNext??!1})},`tool-${ce.id}`);ft=U?e.jsx(Zn,{isMigrating:Ge,children:vt},`migrating-tool-${ce.id}`):vt,rt=Pe&&typeof ve?.end=="number"?ve.end:null;break}case"reasoning":{if(!b)break;const ce=Te.time,se=typeof ce?.end=="number";if(!(se&&!B))break;const Pe=e.jsx(zt,{children:e.jsx(tc,{part:Te,messageId:r,onContentChange:h})},`reasoning-${qe}`);ft=U?e.jsx(Zn,{isMigrating:Ge,children:Pe},`migrating-reasoning-${qe}`):Pe,rt=se?ce?.end??null:null;break}case"justification":{if(!b)break;const ce=Te.time,se=typeof ce?.end=="number";if(!(se&&!We))break;const Pe=e.jsx(zt,{children:e.jsx(Mh,{part:Te,messageId:r,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${qe}`);ft=U?e.jsx(Zn,{isMigrating:Ge,children:Pe},`migrating-text-${qe}`):Pe,rt=se?ce?.end??null:null;break}}ft&&Oe.push({part:Te,index:qe,endTime:rt,element:ft})}),Oe.sort((Te,qe)=>Te.endTime===null&&qe.endTime===null?Te.index-qe.index:Te.endTime===null?1:qe.endTime===null?-1:Te.endTime-qe.endTime),Oe.forEach(({element:Te})=>{me.push(Te)}),me},[be,i,v,d,x,Ge,o,W,r,h,c,S,f,m,Qe,We,B,ne,ze,g,b,n,G,w,Ie,I]),He=w?.turnId,ot=ye(me=>me.currentSessionId),dt=st(me=>{if(!He||!ot)return;const Oe=me.messages.get(ot);if(!Oe)return;const Te=Oe.find(rt=>rt.info?.id===He);if(!Te)return;const at=Te.info.summary?.body;return typeof at=="string"&&at.trim().length>0?at:void 0}),pe=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:dt,R=l.useRef(void 0);pe&&pe.trim().length>0&&(R.current=pe);const te=l.useRef(He);te.current!==He&&(te.current=He,R.current=void 0);const J=R.current,ue=w?.isLastAssistantInTurn&&J&&J.trim().length>0,_e=x&&E.length>0&&Y&&V,[it,Ee]=l.useState(!1),Be=e.jsxs(e.Fragment,{children:[S&&e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(De,{type:"button",variant:"ghost",size:"icon","data-visible":j||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",!ee&&"opacity-50",(j||N)&&"text-primary"),disabled:!ee,"aria-label":"Copy message text","aria-hidden":!ee,onPointerDown:me=>me.stopPropagation(),onClick:xe,onFocus:()=>{ee&&y(!0)},onBlur:()=>{N||y(!1)},children:N?e.jsx(Nt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(ks,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(De,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:me=>me.stopPropagation(),onClick:F,children:e.jsx(_d,{className:"h-4 w-4"})})}),e.jsx(lt,{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:A&&M&&ee?Se: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:[Le,ue&&e.jsx(zt,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ee(!0),onMouseLeave:()=>Ee(!1),children:[e.jsx(jh,{content:J}),_e&&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",it&&"opacity-100 pointer-events-auto"),children:Be})]})},"summary-body")]}),e.jsx($l,{files:s,onShowPopup:f}),!ue&&_e&&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:Be})]})})},ag=({isUser:r,...s})=>r?e.jsx(ng,{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(og,{...s}),pi=l.memo(ag),Qn=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}},ig=l.lazy(()=>jr(()=>import("./ToolOutputDialog-DYcEnIQc.js"),__vite__mapDeps([2,0,1,3,4])));function eo(r){const s=l.useRef({hasValue:!1,value:void 0});return!s.current.hasValue&&r!==void 0&&r!==null&&(s.current={hasValue:!0,value:r}),s.current.hasValue?s.current.value:r}const ds=(r,s)=>{if(typeof r=="object"&&r!==null)return r[s]},lg=({message:r,previousMessage:s,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=Ct(),{currentTheme:m}=ir(),f=l.useRef(null),u=ye(Fo(se=>({lifecyclePhase:se.messageStreamStates.get(r.info.id)?.phase??null,isStreamingMessage:(()=>{const ve=r.info.sessionID??se.currentSessionId??null;return ve?(se.streamingMessageIds.get(ve)??null)===r.info.id:!1})(),currentSessionId:se.currentSessionId,getCurrentAgent:se.getCurrentAgent,getSessionAgentSelection:se.getSessionAgentSelection,getAgentModelForSession:se.getAgentModelForSession,getSessionModelSelection:se.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:g,getCurrentAgent:x,getSessionAgentSelection:S,getAgentModelForSession:v,getSessionModelSelection:k}=u,b=xt(se=>se.providers),w=Re(se=>se.showReasoningTraces);l.useEffect(()=>{g&&Ds.getInstance().recordSessionStart(g)},[g]);const[j,y]=l.useState(null),[C,M]=l.useState(!1),[N,A]=l.useState(new Set),[D,I]=l.useState({open:!1,title:"",content:""}),E=l.useMemo(()=>Qn(r.info),[r.info]).isUser,$=l.useMemo(()=>E?r.parts.map(se=>se.type==="compaction"?{type:"text",text:"/summarize"}:se):r.parts,[E,r.parts]),V=l.useMemo(()=>{if(E||!s)return null;const se=ds(s.info,"clientRole"),ve=ds(s.info,"role");if((typeof se=="string"?se:typeof ve=="string"?ve:void 0)!=="user")return null;const pt=ds(s.info,"mode"),bt=ds(s.info,"providerID"),vt=ds(s.info,"modelID"),$t=typeof pt=="string"&&pt.trim().length>0?pt:void 0,ls=typeof bt=="string"&&bt.trim().length>0?bt:void 0,q=typeof vt=="string"&&vt.trim().length>0?vt:void 0;return!$t&&!ls&&!q?null:{agentName:$t,providerId:ls,modelId:q}},[E,s]),Y=l.useMemo(()=>{if(E)return;const se=ds(r.info,"mode");if(typeof se=="string"&&se.trim().length>0)return se;if(V?.agentName)return V.agentName;const ve=r.info.sessionID;if(!ve)return;const Pe=x(ve);return Pe||(S(ve)??void 0)},[E,r.info,V,x,S]),L=r.info.sessionID,_=E?null:ds(r.info,"providerID"),W=E?null:ds(r.info,"modelID"),ae=l.useMemo(()=>{if(E||!L)return null;if(V?.providerId&&V?.modelId)return{providerId:V.providerId,modelId:V.modelId};if(Y){const ve=v(L,Y);if(ve?.providerId&&ve?.modelId)return ve}const se=k(L);return se?.providerId&&se?.modelId?se:null},[E,L,Y,V,v,k]),je=l.useMemo(()=>E?null:typeof _=="string"&&_.trim().length>0?_:ae?.providerId??null,[E,_,ae]),Me=l.useMemo(()=>E?null:typeof W=="string"&&W.trim().length>0?W:ae?.modelId??null,[E,W,ae]),$e=l.useMemo(()=>{if(!E&&je&&Me&&b.length>0){const se=b.find(ve=>ve.id===je);if(se?.models&&Array.isArray(se.models)){const pt=se.models.find(bt=>bt.id===Me)?.name;return typeof pt=="string"?pt:void 0}}},[E,je,Me,b]),he=eo(Y),ie=eo(je??void 0),Ne=eo($e),Q=he??void 0,We=ie??null,ne=Ne??void 0,B=l.useMemo(()=>{const se=r.info.time;return typeof se?.completed=="number"?se.completed:null},[r.info.time]),we=l.useMemo(()=>E?!0:!!(B&&B>0),[E,B]),oe=l.useMemo(()=>sg($,{includeReasoning:w}),[$,w]),Z=l.useMemo(()=>E||we?oe:[],[E,we,oe]),O=l.useMemo(()=>E?[]:oe.filter(se=>se.type==="text"),[E,oe]),re=l.useMemo(()=>E?[]:oe.filter(se=>se.type==="tool"),[E,oe]),ee=l.useMemo(()=>{if(!E)return;const se=r.parts.find(bt=>bt.type==="agent");if(!se)return;const ve=se,Pe=typeof ve.name=="string"?ve.name:void 0;if(!Pe)return;const pt=ve.source&&typeof ve.source.value=="string"&&ve.source.value.trim().length>0?ve.source.value:`#${Pe}`;return{name:Pe,token:pt}},[E,r.parts]),Se=l.useMemo(()=>{let se=0,ve=0;return oe.forEach(Pe=>{Pe.type==="step-start"?se+=1:Pe.type==="step-finish"&&(ve+=1)}),{hasOpenStep:se>ve}},[oe]).hasOpenStep,xe=l.useMemo(()=>E?!1:O.length===0||re.length===0?Se:!0,[O.length,re.length,Se,E]),F=m?.metadata.variant,G=l.useMemo(()=>F?F==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[F]),P=l.useMemo(()=>m?Yl(m):G?uh:mh,[m,G]),de=l.useMemo(()=>E?!1:Ds.getInstance().shouldAnimateMessage(r.info,g||r.info.sessionID),[r.info,g,E]),be=l.useMemo(()=>s?Qn(s.info):null,[s]),Ie=l.useMemo(()=>t?Qn(t.info):null,[t]),Ye=l.useMemo(()=>E||!be?!0:be.isUser,[E,be]),ct=l.useMemo(()=>E||!Ie?!1:!Ie.isUser&&Ie.role==="assistant",[E,Ie]),ze=l.useMemo(()=>we?"completed":p||(h?"streaming":"completed"),[we,p,h]),et=l.useCallback(se=>{navigator.clipboard.writeText(se),y(se),setTimeout(()=>y(null),2e3)},[]),Qe=i?.turnId,Ge=st(se=>{if(!Qe)return;const ve=r.info.sessionID;if(!ve)return;const Pe=se.messages.get(ve);if(!Pe)return;const pt=Pe.find($t=>$t.info?.id===Qe);if(!pt)return;const vt=pt.info.summary?.body;return typeof vt=="string"&&vt.trim().length>0?vt:void 0}),Le=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:Ge,He=l.useRef(void 0);Le&&Le.trim().length>0&&(He.current=Le);const ot=l.useRef(Qe);ot.current!==Qe&&(ot.current=Qe,He.current=void 0);const dt=He.current,pe=l.useMemo(()=>E?Z.filter(Pe=>Pe.type==="text").map(Pe=>(Pe.text||Pe.content||"").trim()).filter(Pe=>Pe.length>0).join(`
47
+ `).replace(/\n\s*\n+/g,`
48
+ `):dt&&dt.trim().length>0?dt:dl(Z),[dt,Z,E]),R=pe.length>0,te=l.useCallback(()=>{navigator.clipboard.writeText(pe),M(!0),setTimeout(()=>M(!1),2e3)},[pe]),J=l.useCallback(se=>{A(ve=>{const Pe=new Set(ve);return Pe.has(se)?Pe.delete(se):Pe.add(se),Pe})},[]),ue=o??null,_e=l.useRef(!1),it=l.useRef(!1),Ee=l.useRef(!1),Be=l.useRef(!1),me=l.useRef(!1);l.useEffect(()=>{it.current=!1,Ee.current=!1,Be.current=!1,me.current=!1,_e.current=!1},[r.info.id]);const Oe=l.useCallback(()=>{E||_e.current||(_e.current=!0,n?.("structural"))},[E,n]),Te=l.useCallback(se=>{se.image&&I(se)},[]),qe=l.useCallback(se=>{I(ve=>({...ve,open:se}))},[]),at=!!ds(r.info,"animationSettled"),rt=ze==="streaming",ft=l.useMemo(()=>E?!1:oe.some(se=>se.type==="reasoning"),[E,oe]),U=de&&!at&&!rt,ce=!E&&de&&O.length>0&&!xe;return l.useEffect(()=>{if(ue?.onStreamingCandidate){if(!ce){Ee.current&&(ft&&ue?.onReasoningBlock?ue.onReasoningBlock():ue?.onReservationCancelled&&ue.onReservationCancelled(),Ee.current=!1);return}me.current||(me.current=!0,ue.onStreamingCandidate(),Ee.current=!0)}},[ue,ce,ft]),l.useEffect(()=>{ue?.onAnimationStart&&U&&(Be.current||(ue.onAnimationStart(),Be.current=!0))},[ue,U]),l.useEffect(()=>{if(E)return;const se=ue?.onAnimatedHeightChange;if(!se||!(U||ce))return;const Pe=f.current;if(!Pe)return;if(typeof window>"u"||typeof ResizeObserver>"u"){se(Pe.getBoundingClientRect().height);return}let pt=null;const bt=$t=>{if(typeof window>"u"){se($t);return}pt!==null&&window.cancelAnimationFrame(pt),pt=window.requestAnimationFrame(()=>{se($t)})},vt=new ResizeObserver($t=>{const ls=$t[0];ls&&bt(ls.contentRect.height)});return vt.observe(Pe),bt(Pe.getBoundingClientRect().height),()=>{pt!==null&&(window.cancelAnimationFrame(pt),pt=null),vt.disconnect()}},[U,E,ue,ce]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("group w-full",Ye?"pt-2":"pt-0",E?"pb-2":ct?"pb-0":"pb-2"),"data-message-id":r.info.id,ref:f,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:E?e.jsx(zt,{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(pi,{messageId:r.info.id,parts:oe,isUser:E,isMessageCompleted:we,syntaxTheme:P,isMobile:c,hasTouchInput:d,copiedCode:j,onCopyCode:et,expandedTools:N,onToggleTool:J,onShowPopup:Te,streamPhase:ze,allowAnimation:U,onContentChange:n,shouldShowHeader:!1,hasTextContent:R,onCopyMessage:te,copiedMessage:C,showReasoningTraces:w,onAuxiliaryContentComplete:Oe,agentMention:ee})})}):e.jsxs("div",{children:[Ye&&e.jsx(ph,{isUser:E,providerID:We,agentName:Q,modelName:ne,isDarkTheme:G}),e.jsx(pi,{messageId:r.info.id,parts:oe,isUser:E,isMessageCompleted:we,syntaxTheme:P,isMobile:c,hasTouchInput:d,copiedCode:j,onCopyCode:et,expandedTools:N,onToggleTool:J,onShowPopup:Te,streamPhase:ze,allowAnimation:U,onContentChange:n,shouldShowHeader:Ye,hasTextContent:R,onCopyMessage:te,copiedMessage:C,onAuxiliaryContentComplete:Oe,showReasoningTraces:w,agentMention:ee,turnGroupingContext:i})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(ig,{popup:D,onOpenChange:qe,syntaxTheme:P,isMobile:c})})]})},cg=l.memo(lg),dg=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(ps,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Fs,{className:s}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(io,{className:s}):e.jsx(Po,{className:s})},ug=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},mg=({permission:r,onResponse:s})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=ye(),{currentTheme:c}=ir(),d=l.useMemo(()=>Yl(c),[c]),m=async v=>{n(!0);try{await i(r.sessionID,r.id,v),a(!0),s?.(v)}catch{}finally{n(!1)}};if(o)return null;const f=r.type||"Unknown Tool",u=f.toLowerCase(),p=(v,k="")=>{const b=r.metadata[v];return typeof b=="string"?b:typeof b=="number"?String(b):k},h=v=>{const k=r.metadata[v];return typeof k=="number"?k:void 0},g=v=>!!r.metadata[v],x=ug(f),S=()=>{if(u==="bash"||u==="shell"||u==="shell_command"){const b=p("command")||p("cmd")||p("script"),w=p("description"),j=p("cwd")||p("working_directory")||p("directory")||p("path"),y=h("timeout"),C=r.title===b;return e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:w}),j&&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:j})]}),y&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",y,"ms"]}),b&&!C&&e.jsx("div",{children:e.jsx(ms,{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:b})})]})}if(u==="edit"||u==="multiedit"||u==="str_replace"||u==="str_replace_based_edit_tool"){const b=p("path")||p("file_path")||p("filename")||p("filePath"),w=p("old_str")||p("oldString")||p("old_content")||p("before"),j=p("new_str")||p("newString")||p("new_content")||p("after"),y=p("changes")||p("diff"),C=g("replace_all")||g("replaceAll");return e.jsxs(e.Fragment,{children:[b&&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:b})]}),C&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),y?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Changes:"}),e.jsx(Je,{outerClassName:"max-h-64",className:"overflow-x-auto p-0",children:e.jsx(ms,{language:"diff",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!1,children:y})})]}):e.jsxs(e.Fragment,{children:[w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Remove:"}),e.jsx(Je,{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:w.length>500?w.substring(0,500)+"...":w})})]}),j&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Replace with:"}),e.jsx(Je,{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:j.length>500?j.substring(0,500)+"...":j})})]})]})]})}if(u==="webfetch"||u==="fetch"||u==="curl"||u==="wget"){const b=p("url")||p("uri")||p("endpoint"),w=p("method")||"GET",j=r.metadata.headers&&typeof r.metadata.headers=="object"?r.metadata.headers:void 0,y=p("body")||p("data")||p("payload"),C=h("timeout"),M=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:w}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:b})]})]}),j&&Object.keys(j).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(Je,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(ms,{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(j,null,2)})})]}),y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(Je,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(ms,{language:typeof y=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof y=="object"?JSON.stringify(y,null,2):String(y)})})]}),(C||M)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[C&&e.jsxs("span",{children:["Timeout: ",C,"ms"]}),C&&M&&e.jsx("span",{children:" • "}),M&&e.jsxs("span",{children:["Response format: ",M]})]})]})}const v=p("command")||p("content")||p("action")||p("operation"),k=p("description");return e.jsxs(e.Fragment,{children:[k&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:k}),v&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(Je,{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(v)})})]}),Object.keys(r.metadata).length>0&&!v&&!k&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(Je,{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(Cr,{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:[dg(f),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:x})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[(()=>{let v="",k="text",b=!1;u==="bash"||u==="shell"||u==="shell_command"?(v=p("command")||p("cmd")||p("script"),k="bash",b=!0):u==="edit"||u==="multiedit"||u==="str_replace"||u==="str_replace_based_edit_tool"?(v=p("path")||p("file_path")||p("filename")||p("filePath"),b=!1):(u==="webfetch"||u==="fetch")&&(v=p("url")||p("uri")||p("endpoint"),b=!1);const w=r.title===v;return w&&v&&b?e.jsx("div",{className:"mb-3",children:e.jsx(ms,{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:v})}):w&&v&&!b?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:v})}):r.title?e.jsx("div",{className:T("typography-ui-label text-foreground mb-3",(b||v)&&"font-mono"),children:r.title}):null})(),S()]}),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:()=>m("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:v=>{v.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:v=>{v.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Nt,{className:"h-3 w-3"}),"Allow Once"]}),e.jsxs("button",{onClick:()=>m("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:v=>{v.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:v=>{v.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Bd,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>m("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:v=>{v.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:v=>{v.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(os,{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"})})]})]})})})},fg=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},pg=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}}}},hg=r=>{const s=pg(r);let t;const o=r.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let m=0,f=0,u=0;o.forEach(p=>{if(!p)return;const h=typeof p.additions=="number"?p.additions:0,g=typeof p.deletions=="number"?p.deletions:0;(h!==0||g!==0)&&(u+=1),m+=h,f+=g}),u>0&&(t={additions:m,deletions:f,files:u})}let a=!1,i=!1;r.assistantMessages.forEach(m=>{m.parts.forEach(f=>{f.type==="tool"?a=!0:f.type==="reasoning"&&(i=!0)})});const c=[];let d=0;return r.assistantMessages.forEach(m=>{const f=m.info.id;m.parts.forEach(u=>{const p=typeof u.id=="string"&&u.id.trim().length>0?u.id:`${f}-activity-${d++}`;if(u.type==="tool"){const g=u.state?.time,x=typeof g?.end=="number"?g.end:void 0;c.push({id:p,turnId:r.turnId,messageId:f,kind:"tool",part:u,endedAt:x});return}if(u.type==="reasoning"){const h=u.text??u.content;if(typeof h!="string"||h.trim().length===0)return;const g=u.time,x=typeof g?.end=="number"?g.end:void 0;c.push({id:p,turnId:r.turnId,messageId:f,kind:"reasoning",part:u,endedAt:x});return}})}),{activityParts:c,hasTools:a,hasReasoning:i,summaryBody:s,diffStats:t}},gg=r=>{const{isWorking:s}=Gl(),t=l.useMemo(()=>fg(r),[r]),n=l.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=l.useMemo(()=>{const h=new Map;return t.forEach(g=>{h.set(g.userMessage.info.id,g),g.assistantMessages.forEach(x=>{h.set(x.info.id,g)})}),h},[t]),a=l.useMemo(()=>{const h=new Map;return t.forEach(g=>{h.set(g.turnId,hg(g))}),h},[t]),[i,c]=l.useState(()=>new Map),d=l.useCallback(h=>{const g=i.get(h);return g||{isExpanded:!1,previewedPartIds:new Set}},[i]),m=l.useCallback(h=>{c(g=>{const x=new Map(g),S=x.get(h)??{isExpanded:!1,previewedPartIds:new Set};return x.set(h,{...S,isExpanded:!S.isExpanded}),x})},[]),f=l.useCallback((h,g)=>{g.length!==0&&c(x=>{const S=new Map(x),v=S.get(h)??{isExpanded:!1,previewedPartIds:new Set},k=new Set(v.previewedPartIds);return g.forEach(b=>{b&&b.trim().length>0&&k.add(b)}),S.set(h,{...v,previewedPartIds:k}),S})},[]),u=l.useCallback(h=>o.get(h),[o]),p=l.useCallback(h=>{const g=o.get(h);if(!g||!g.assistantMessages.some(I=>I.info.id===h))return;const S=a.get(g.turnId),v=S?.activityParts??[],k=!!S?.hasTools,b=!!S?.hasReasoning,w=S?.summaryBody,j=S?.diffStats,y=g.assistantMessages[0]?.info.id,C=h===y,M=g.assistantMessages[g.assistantMessages.length-1]?.info.id,N=h===M,A=d(g.turnId),D=s&&n===g.turnId;return{turnId:g.turnId,isFirstAssistantInTurn:C,isLastAssistantInTurn:N,summaryBody:w,activityParts:v,hasTools:k,hasReasoning:b,diffStats:j,isWorking:D,isGroupExpanded:A.isExpanded,previewedPartIds:A.previewedPartIds,toggleGroup:()=>m(g.turnId),markPartsPreviewed:I=>f(g.turnId,I)}},[d,n,f,o,s,m,a]);return{turns:t,getTurnForMessage:u,getContextForMessage:p}},yg=({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 m=l.useMemo(()=>r.filter(u=>!yo(u.parts)),[r]),{getContextForMessage:f}=gg(m);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:m.map((u,p)=>e.jsx(cg,{message:u,previousMessage:p>0?m[p-1]:void 0,nextMessage:p<m.length-1?m[p+1]:void 0,onContentChange:t,animationHandlers:n(u.info.id),scrollToBottom:c,isPendingAnchor:d===u.info.id,turnGroupingContext:f(u.info.id)},u.info.id))}),s.length>0&&e.jsx("div",{children:s.map(u=>e.jsx(mg,{permission:u},u.id))})]})},xg=l.memo(yg);function bg(...r){return s=>{r.forEach(t=>{typeof t=="function"?t(s):t&&typeof t=="object"&&(t.current=s)})}}const ac=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,...m},f)=>{const u=l.useRef(null),p=l.useRef("none"),h=m["data-scroll-shadow"];delete m["data-scroll-shadow"];const g=l.useMemo(()=>{const k={...i};return k["--scroll-shadow-size"]=`${t}px`,k},[t,i]),x=l.useCallback((k,b,w,j,y)=>{const C=`${j}${y.charAt(0).toUpperCase()}${y.slice(1)}Scroll`;b&&w?(k.dataset[C]="true",k.removeAttribute(`data-${j}-scroll`),k.removeAttribute(`data-${y}-scroll`)):(k.dataset[`${j}Scroll`]=String(b),k.dataset[`${y}Scroll`]=String(w),k.removeAttribute(`data-${j}-${y}-scroll`))},[]),S=l.useCallback(k=>{["top","bottom","top-bottom","left","right","left-right"].forEach(b=>{k.removeAttribute(`data-${b}-scroll`)})},[]),v=l.useCallback(()=>{const k=u.current;if(!k)return;if(!n){S(k);return}const b=r==="vertical"?k.scrollTop>s:k.scrollLeft>s;let w=r==="vertical"?k.scrollTop+k.clientHeight+s<k.scrollHeight:k.scrollLeft+k.clientWidth+s<k.scrollWidth;o&&r==="vertical"&&(w=!1),x(k,b,w,r==="vertical"?"top":"left",r==="vertical"?"bottom":"right");const j=b&&w?"both":b?r==="vertical"?"top":"left":w?r==="vertical"?"bottom":"right":"none";j!==p.current&&(p.current=j,a?.(j))},[S,o,n,s,a,r,x]);return l.useEffect(()=>{const k=u.current;if(!k)return;const b=()=>v(),w=typeof ResizeObserver<"u"?new ResizeObserver(()=>v()):null,j=typeof MutationObserver<"u"?new MutationObserver(()=>v()):null;return v(),k.addEventListener("scroll",b,{passive:!0}),w?.observe(k),j?.observe(k,{childList:!0,subtree:!0,characterData:!0}),()=>{k.removeEventListener("scroll",b),w?.disconnect(),j?.disconnect()}},[v]),e.jsx("div",{...m,ref:bg(u,f),className:c,"data-orientation":r,"data-scroll-shadow":h??!0,style:g,children:d})});ac.displayName="ScrollShadow";const wg=160,vg=({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),m=l.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),f=l.useCallback(b=>{const w=r.current;if(!w){m();return}i.current===null&&(i.current=b);const j=Math.min(1,(b-i.current)/wg),y=1-Math.pow(1-j,3),C=c.current,M=d.current,N=C+(M-C)*y;if(w.scrollTop=N,j<1){a.current=window.requestAnimationFrame(f);return}w.scrollTop=M,m(),n.current&&(n.current=!1,t(!1))},[m,r,t]),u=l.useCallback((b,w)=>{const j=r.current;if(!j)return;const y=Math.max(0,b),C=w?.instant??!1;if(o.current=!1,typeof window>"u"||C){m(),j.scrollTop=y;const N=y<=1;n.current!==N&&(n.current=N,t(N));return}if(m(),Math.abs(y-j.scrollTop)<=.5){j.scrollTop=y;const N=y<=1;n.current!==N&&(n.current=N,t(N));return}c.current=j.scrollTop,d.current=y,i.current=null,a.current=window.requestAnimationFrame(f)},[m,r,f,t]),p=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),g=l.useCallback(()=>o.current,[]),x=l.useCallback(()=>r.current?.scrollTop??0,[r]),S=l.useCallback(()=>r.current?.scrollHeight??0,[r]),v=l.useCallback(()=>r.current?.clientHeight??0,[r]),k=l.useCallback(()=>{const b=r.current;if(!b)return;o.current&&a.current!==null&&m();const w=b.scrollTop<=1;n.current!==w&&(n.current=w,t(w))},[m,r]);return l.useEffect(()=>{const b=r.current;if(b)return b.addEventListener("wheel",h,{passive:!0}),b.addEventListener("touchstart",h,{passive:!0}),()=>{b.removeEventListener("wheel",h),b.removeEventListener("touchstart",h)}},[r,h]),l.useEffect(()=>()=>{m()},[m]),l.useMemo(()=>({handleScroll:k,scrollToPosition:u,forceManualMode:p,isAtTop:s,isManualOverrideActive:g,getScrollTop:x,getScrollHeight:S,getClientHeight:v}),[k,u,p,s,g,x,S,v])},hi=typeof window<"u"?l.useLayoutEffect:l.useEffect,gi=50,yi=40,Sg=.2,jg=.1,kg=150,Kt=r=>{const s=r.info;return typeof s?.id=="string"?s.id:null},Ng=r=>{const s=r.info;if(s?.userMessageMarker===!0)return!0;const t=s?.clientRole,n=s?.role;return t==="user"||n==="user"},Cg=({currentSessionId:r,sessionMessages:s,updateViewportAnchor:t,isSyncing:n,isMobile:o,sessionActivityPhase:a})=>{const i=l.useRef(null),c=vg({containerRef:i}),[d,m]=l.useState(null),[f,u]=l.useState(0),[p,h]=l.useState(!1),[g,x]=l.useState(null),S=l.useRef(null),v=l.useRef(null),k=l.useRef(s.length),b=l.useRef(s.length>0?Kt(s[0]):null),w=l.useRef(s.length>0?Kt(s[s.length-1]):null),j=l.useRef(0),y=l.useRef(0),C=l.useRef(void 0),M=l.useRef(null),N=l.useRef(!1),A=l.useRef(!1),D=r?a?.get(r)??"idle":"idle",I=l.useCallback(he=>{const ie=Math.max(0,he);j.current!==ie&&(j.current=ie,u(ie))},[]),z=l.useCallback(()=>{const he=i.current;he&&(y.current=he.clientHeight)},[]),E=l.useCallback(()=>{if(!d)return null;const he=i.current;return he?he.querySelector(`[data-message-id="${d}"]`):null},[d]),$=l.useCallback(()=>{const he=i.current,ie=j.current;if(!he||ie<=0)return!0;const Ne=he.scrollHeight-ie;return he.scrollTop+he.clientHeight<Ne},[]),V=l.useCallback((he,ie)=>{const Ne=he.offsetHeight,Q=he.offsetTop;if(Ne>ie*Sg){const ne=ie*jg;return Q+Ne-ne}else return Q-gi},[]),Y=l.useCallback(()=>{const he=i.current;if(!he||!M.current)return;const ie=E();if(!ie)return;const Ne=he.clientHeight,Q=he.scrollHeight,ne=V(ie,Ne)+Ne,B=j.current,we=Q-B;if(!N.current&&we<ne){const oe=ne-we;oe>B&&I(oe)}},[V,E,I]),L=l.useCallback(()=>{const he=i.current;if(!he){h(!1);return}if(g){h(!1);return}if(!(he.scrollHeight>he.clientHeight)){h(!1);return}const Ne=he.scrollHeight-he.scrollTop-he.clientHeight,Q=j.current;if(Q>0){const We=he.scrollHeight-Q,ne=he.scrollTop+he.clientHeight;h(ne<We)}else h(Ne>yi)},[g]),_=l.useCallback(he=>{const ie=i.current;if(!ie)return;const Ne=ie.scrollHeight-ie.scrollTop-ie.clientHeight;if(A.current&&D==="idle"&&!n&&!he?.force&&Ne>yi)return;he?.force&&(A.current=!1);const We=ie.scrollHeight-ie.clientHeight;c.scrollToPosition(Math.max(0,We),he)},[D,n,c]),W=l.useCallback(he=>{if(S.current===he)return;S.current=he,x(he);const ie=i.current;if(!ie){x(null);return}const Ne=ie.scrollHeight,Q=j.current,We=Ne-Q,ne=y.current>0?y.current:ie.clientHeight,we=We-gi,oe=we+ne;let Z=0;We<oe&&(Z=oe-We),Z!==Q&&I(Z),N.current=!0,window.requestAnimationFrame(()=>{c.scrollToPosition(we,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[c,I]),ae=l.useCallback(he=>{const ie=i.current;if(!ie||!r)return;he?.isTrusted&&(A.current=!0),c.handleScroll(),L(),D==="idle"&&j.current>0&&$()&&(I(0),M.current=null,m(null));const{scrollTop:Ne,scrollHeight:Q,clientHeight:We}=ie,ne=(Ne+We/2)/Math.max(Q,1),B=Math.floor(ne*s.length);t(r,B)},[r,D,$,c,s.length,L,I,t]);l.useEffect(()=>{const he=i.current;if(he)return he.addEventListener("scroll",ae,{passive:!0}),()=>{he.removeEventListener("scroll",ae)}},[ae]),hi(()=>{if(typeof window>"u")return;z();const he=()=>{C.current!==void 0&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{z()},kg)};return window.addEventListener("resize",he),()=>{window.removeEventListener("resize",he),C.current!==void 0&&window.clearTimeout(C.current)}},[z]),l.useEffect(()=>{r&&r!==v.current&&(v.current=r,Ds.getInstance().recordSessionStart(r),k.current=s.length,b.current=s.length>0?Kt(s[0]):null,w.current=s.length>0?Kt(s[s.length-1]):null,S.current=null,M.current=null,N.current=!1,m(null),j.current=0,u(0),A.current=!1)},[r,s.length]),hi(()=>{if(n){k.current=s.length,b.current=s.length>0?Kt(s[0]):null,w.current=s.length>0?Kt(s[s.length-1]):null;return}if(v.current!==r)return;const he=k.current,ie=s.length;if(ie>he&&he>0){const Ne=b.current,Q=Kt(s[0]),We=Kt(s[ie-1]),ne=w.current,B=Ne!==null&&Q!==Ne,we=ne!==null&&We!==ne,oe=B&&!we,Z=we&&!B;if(oe){M.current=null,N.current=!1,m(null),I(0),k.current=ie,b.current=Q,w.current=We;return}if(Z){const re=s.slice(he,ie).find(Ng);if(re){const ee=Kt(re);ee&&(M.current=ee,m(ee),W(ee))}else Y()}}k.current=ie,b.current=s.length>0?Kt(s[0]):null,w.current=s.length>0?Kt(s[s.length-1]):null},[r,n,Y,W,s]),l.useEffect(()=>{const he=i.current;if(!he||typeof ResizeObserver>"u")return;const ie=new ResizeObserver(()=>{Y(),L()});return ie.observe(he),()=>{ie.disconnect()}},[Y,L]),l.useEffect(()=>{d&&(Y(),L())},[d,Y,L]),l.useEffect(()=>{D==="idle"&&j.current>0&&$()&&(I(0),M.current=null,N.current=!1,m(null))},[D,$,I]),l.useEffect(()=>{L()},[f,L]);const je=l.useRef(new Map),Me=l.useCallback(()=>{Y(),L()},[Y,L]),$e=l.useCallback(he=>{const ie=je.current.get(he);if(ie)return ie;const Ne={onChunk:()=>{Y()},onComplete:()=>{Y()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{Y()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return je.current.set(he,Ne),Ne},[Y]);return{scrollRef:i,handleMessageContentChange:Me,getAnimationHandlers:$e,showScrollButton:p,scrollToBottom:_,spacerHeight:f,pendingAnchorId:g,hasActiveAnchor:d!==null}},Mg=()=>{const{currentSessionId:r,messages:s,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,sessionMemoryState:d,isSyncing:m,messageStreamStates:f,trimToViewportWindow:u,sessionActivityPhase:p}=ye(),h=l.useMemo(()=>r?n.get(r)??null:null,[r,n]),{isMobile:g}=Ct(),x=l.useMemo(()=>r?s.get(r)||[]:[],[r,s]),S=l.useMemo(()=>r?t.get(r)||[]:[],[r,t]),{scrollRef:v,handleMessageContentChange:k,getAnimationHandlers:b,showScrollButton:w,scrollToBottom:j,spacerHeight:y,pendingAnchorId:C,hasActiveAnchor:M}=Cg({currentSessionId:r,sessionMessages:x,updateViewportAnchor:c,isSyncing:m,isMobile:g,sessionActivityPhase:p}),A=!!l.useMemo(()=>r?d.get(r)??null:null,[r,d])?.hasMoreAbove,[D,I]=l.useState(!1);l.useEffect(()=>{I(!1)},[r]);const z=l.useRef(null);l.useLayoutEffect(()=>{if(!r||r===z.current)return;z.current=r;const $=v.current;$&&($.scrollTop=$.scrollHeight-$.clientHeight)},[r,v]);const E=l.useCallback(async()=>{if(!r||D)return;const $=v.current,V=$?.scrollHeight??null,Y=$?.scrollTop??null;I(!0);try{if(await i(r,"up"),$&&V!==null&&Y!==null){const L=$.scrollHeight-V;$.scrollTop=Y+L}}finally{I(!1)}},[r,D,i,v]);return l.useEffect(()=>{if(!r||(s.has(r)?s.get(r)??[]:[]).length>0)return;(async()=>{try{await a(r)}finally{typeof window>"u"?j():window.requestAnimationFrame(()=>{j()})}})()},[r,a,s,j]),r?o&&x.length===0&&!h&&!s.has(r)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-column space-y-4",children:[1,2,3].map(V=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Yn,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Yn,{className:"h-4 w-24"}),e.jsx(Yn,{className:"h-20 w-full"})]})]},V))})}),e.jsx(Kn,{scrollToBottom:j})]}):x.length===0&&!h?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(di,{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(Kn,{scrollToBottom:j})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(ac,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:v,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!C,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(xg,{messages:x,permissions:S,onMessageContentChange:k,getAnimationHandlers:b,hasMoreAbove:A,isLoadingOlder:D,onLoadOlder:E,scrollToBottom:j,pendingAnchorId:C}),y>0&&M&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:y},"aria-hidden":"true"})]})}),e.jsx(Vo,{containerRef:v})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[w&&x.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(De,{variant:"outline",size:"sm",onClick:()=>j({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(yr,{className:"h-4 w-4"})})}),e.jsx(Kn,{scrollToBottom:j})]})]}):e.jsx("div",{className:"flex flex-col h-full bg-background",children:e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(di,{width:140,height:140,className:"opacity-20",isAnimated:!0})})})};class Ag 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(Xo,{className:"w-full max-w-md",children:[e.jsx(Sl,{className:"text-center",children:e.jsxs(jl,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Od,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(kl,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data."}),this.props.sessionId&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Session: ",this.props.sessionId]}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(De,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(rr,{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 vo=()=>{const r=ye(s=>s.currentSessionId);return e.jsx(Ag,{sessionId:r||void 0,children:e.jsx(Mg,{})})},xi=12,Dg=[{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"}],Eg=({isActive:r,burstKey:s=0,className:t,durationMs:n=900,bursts:o=Dg,onComplete:a})=>{const i=fe.useRef(!1);fe.useEffect(()=>{!r&&i.current&&a?.(),r&&(i.current=!0)},[r,a]);const c=fe.useMemo(()=>Array.from({length:xi},(d,m)=>{const f=Math.PI*2*m/xi;return{x:Math.cos(f),y:Math.sin(f),delay:m*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 m={"--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:m,children:c.map((f,u)=>{const p=f.x*d.radius,h=f.y*d.radius,g={"--translate-x":`${p}px`,"--translate-y":`${h}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:g},`${d.id}-${u}-${s}`)})},`${d.id}-${s}`)})}):null},Tg=({durationMs:r=3400}={})=>{const[s,t]=fe.useState({isActive:!1,cycle:0}),n=fe.useRef(null),o=fe.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=fe.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=fe.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 fe.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:i,dismissFireworks:a}},ic=l.createContext(void 0),bi=({children:r})=>{const{isActive:s,burstKey:t,triggerFireworks:n,dismissFireworks:o}=Tg(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(ic.Provider,{value:a,children:[r,e.jsx(Eg,{isActive:s,burstKey:t})]})},Ig=()=>{const r=l.useContext(ic);if(!r)throw new Error("useFireworksCelebration must be used within FireworksProvider");return r};function Fg({...r}){return e.jsx($d,{"data-slot":"select",...r})}function Pg({...r}){return e.jsx(Wd,{"data-slot":"select-value",...r})}function Rg({className:r,size:s="default",children:t,...n}){return e.jsxs(zd,{"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(Hd,{asChild:!0,children:e.jsx(wt,{className:"size-4 opacity-50"})})]})}function Lg({className:r,children:s,position:t="popper",...n}){return e.jsx(Ud,{children:e.jsxs(Vd,{"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(Bg,{}),e.jsx(Je,{as:Gd,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(Og,{})]})})}function _g({className:r,children:s,...t}){return e.jsxs(qd,{"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(Kd,{children:e.jsx(Nt,{className:"size-4"})})}),e.jsx(Yd,{children:s})]})}function Bg({className:r,...s}){return e.jsx(Xd,{"data-slot":"select-scroll-up-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(jo,{className:"size-4"})})}function Og({className:r,...s}){return e.jsx(Jd,{"data-slot":"select-scroll-down-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(wt,{className:"size-4"})})}const $g=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),zg=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,Hg=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}];let pr=null;const Wg=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=ye(),{currentDirectory:n}=yt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},Ug=()=>{const{git:r}=Gs(),s=Wg(),{currentSessionId:t,worktreeMetadata:n}=ye(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=An(),m=fl(s??null),f=ml(s??null),u=mf(s??null),p=ff(s??null),h=pf(s??null),g=jt(U=>U.isLoadingStatus),x=jt(U=>U.isLoadingLog),{setActiveDirectory:S,fetchAll:v,fetchStatus:k,fetchBranches:b,fetchLog:w,fetchIdentity:j,setLogMaxCount:y}=jt(),C=l.useMemo(()=>!pr||pr.directory!==s?null:pr,[s]),[M,N]=l.useState(C?.commitMessage??""),[A,D]=l.useState(""),I=l.useMemo(()=>$g(A),[A]),[z,E]=l.useState(null),[$,V]=l.useState(null),[Y,L]=l.useState(!1),[_,W]=l.useState(null),[ae,je]=l.useState(25),[Me,$e]=l.useState(!1),[he,ie]=l.useState(!1),[Ne,Q]=l.useState(""),[We]=l.useState(null),{triggerFireworks:ne}=Ig(),[B,we]=l.useState(()=>new Set(C?.selectedPaths??[])),[oe,Z]=l.useState(!1),[O,re]=l.useState(new Set),[ee,le]=l.useState(!1),[Se,xe]=l.useState([]),F=l.useCallback(()=>{xe([])},[]),[G,P]=l.useState(null),[de,be]=l.useState([]),[Ie,Ye]=l.useState(!1),ct=l.useMemo(()=>!G||!p?null:p.all.find(U=>U.hash===G)??null,[G,p]),ze=l.useCallback(U=>{navigator.clipboard.writeText(U).then(()=>{ge.success("Commit hash copied")}).catch(()=>{ge.error("Failed to copy")})},[]);l.useEffect(()=>{if(!G||!s||!r){be([]);return}let U=!1;return Ye(!0),r.getCommitFiles(s,G).then(ce=>{U||be(ce.files)}).catch(ce=>{console.error("Failed to fetch commit files:",ce),U||be([])}).finally(()=>{U||Ye(!1)}),()=>{U=!0}},[G,s,r]),l.useEffect(()=>()=>{if(!s){pr=null;return}pr={directory:s,selectedPaths:Array.from(B),commitMessage:M}},[M,s,B]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{s&&(S(s),jt.getState().directories.get(s)?.status||v(s,r,{force:!0}))},[s,S,v,r]);const et=l.useCallback(async(U=!0)=>{if(s)try{await Promise.all([k(s,r),b(s,r)])}catch(ce){if(U){const se=ce instanceof Error?ce.message:"Failed to refresh repository state";ge.error(se)}}},[s,r,k,b]),Qe=l.useCallback(async()=>{s&&await w(s,r,ae)},[s,r,w,ae]),Ge=l.useCallback(async()=>{s&&await j(s,r)},[s,r,j]),Le=l.useMemo(()=>{if(!f)return[];const U=f.files??[],ce=new Map;return U.forEach(se=>{ce.set(se.path,se)}),Array.from(ce.values()).sort((se,ve)=>se.path.localeCompare(ve.path))},[f]);l.useEffect(()=>{if(!f||Le.length===0){we(new Set),Z(!1);return}we(U=>{const ce=new Set,se=U??new Set;return Le.forEach(ve=>{se.has(ve.path)?ce.add(ve.path):oe||ce.add(ve.path)}),ce})},[f,Le,oe]);const He=async U=>{if(s){E(U);try{if(U==="fetch")await r.gitFetch(s),ge.success("Fetched latest updates");else if(U==="pull"){const ce=await r.gitPull(s);ge.success(`Pulled ${ce.files.length} file${ce.files.length===1?"":"s"}`)}else U==="push"&&(await r.gitPush(s),ge.success("Pushed to remote"));W(`${U.toUpperCase()} completed at ${new Date().toLocaleTimeString()}`),await et(!1),await Qe()}catch(ce){const se=ce instanceof Error?ce.message:`Failed to ${U==="pull"?"pull":U}`;ge.error(se)}finally{E(null)}}},ot=async(U={})=>{if(!s)return;if(!M.trim()){ge.error("Please enter a commit message");return}const ce=Array.from(B).sort();if(ce.length===0){ge.error("Select at least one file to commit");return}const se=U.pushAfter?"commitAndPush":"commit";V(se);try{await r.createGitCommit(s,M.trim(),{files:ce}),ge.success("Commit created successfully"),N(""),we(new Set),Z(!1),await et(),U.pushAfter?(await r.gitPush(s),ge.success("Pushed to remote"),ne(),await et(!1)):await et(!1),await Qe()}catch(ve){const Pe=ve instanceof Error?ve.message:"Failed to create commit";ge.error(Pe)}finally{V(null)}},dt=l.useCallback(async()=>{if(s){if(B.size===0){ge.error("Select at least one file to describe");return}le(!0);try{const{message:U}=await r.generateCommitMessage(s,Array.from(B)),ce=U.subject?.trim()??"",se=Array.isArray(U.highlights)?U.highlights:[];ce&&N(ce),xe(se),ge.success("Commit message generated")}catch(U){const ce=U instanceof Error?U.message:"Failed to generate commit message";ge.error(ce)}finally{le(!1)}}},[s,B,r]),pe=async()=>{if(!s||!f)return;const U=I;if(!U){ge.error('Provide a branch name using letters, numbers, ".", "_", "-" or "/".');return}const ce=f.current??null;L(!0);try{await r.createBranch(s,U,ce??"HEAD"),ge.success(`Created branch ${U}`);let se=!1;try{await r.checkoutBranch(s,U),await r.gitPush(s,{remote:"origin",branch:U,options:["--set-upstream"]}),se=!0}catch(ve){const Pe=ve instanceof Error?ve.message:"Unable to push new branch to origin.";ge.warning("Branch created locally",{description:zg(`Upstream setup failed: ${Pe}`)})}finally{if(ce)try{await r.checkoutBranch(s,ce)}catch(ve){console.warn("Failed to restore original branch after creation:",ve)}}D(""),await et(),await Qe(),se&&ge.success(`Upstream set for ${U}`)}catch(se){const ve=se instanceof Error?se.message:"Failed to create branch";ge.error(ve)}finally{L(!1)}},R=async U=>{if(!s)return;const ce=U.replace(/^remotes\//,"");if(f?.current===ce){ie(!1);return}try{await r.checkoutBranch(s,ce),ge.success(`Checked out ${ce}`),ie(!1),Q(""),await et();const se=f?.current;se&&(await r.checkoutBranch(s,se),ge.success(`Checked out ${se}`)),await Qe()}catch(se){const ve=se instanceof Error?se.message:`Failed to checkout ${ce}`;ge.error(ve)}},te=async U=>{if(s){$e(!0);try{await r.setGitIdentity(s,U.id),ge.success(`Applied "${U.name}" to repository`),await Ge()}catch(ce){const se=ce instanceof Error?ce.message:"Failed to apply git identity";ge.error(se)}finally{$e(!1)}}},J=l.useMemo(()=>u?.all?u.all.filter(U=>!U.startsWith("remotes/")).sort():[],[u]),ue=l.useMemo(()=>u?.all?u.all.filter(U=>U.startsWith("remotes/")).map(U=>U.replace(/^remotes\//,"")).sort():[],[u]),_e=l.useMemo(()=>{const U=Ne.trim().toLowerCase();return U?{locals:J.filter(ce=>ce.toLowerCase().includes(U)),remotes:ue.filter(ce=>ce.toLowerCase().includes(U))}:{locals:J,remotes:ue}},[Ne,J,ue]);l.useEffect(()=>{he||Q("")},[he]);const it=l.useMemo(()=>{const U=new Map;i&&U.set(i.id,i);for(const ce of a)U.set(ce.id,ce);return Array.from(U.values())},[a,i]),Ee=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const U=a.find(ce=>ce.userName===h.userName&&ce.userEmail===h.userEmail);return U||(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]),Be=Le.length,me=B.size,Oe=g||z!==null||$!==null,Te=U=>{we(ce=>{const se=new Set(ce);return se.has(U)?se.delete(U):se.add(U),se}),Z(!0)},qe=()=>{const U=new Set(Le.map(ce=>ce.path));we(U),Z(!0)},at=()=>{we(new Set),Z(!0)},rt=l.useCallback(async U=>{if(s){re(ce=>{const se=new Set(ce);return se.add(U),se});try{await r.revertGitFile(s,U),ge.success(`Reverted ${U}`),await et(!1)}catch(ce){const se=ce instanceof Error?ce.message:"Failed to revert changes";ge.error(se)}finally{re(ce=>{const se=new Set(ce);return se.delete(U),se})}}},[s,et,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&&m===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(Ft,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository…"})]})});if(m===!1)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Tt,{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 ft=Be>0;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[f&&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(Tt,{className:"size-4 text-primary"}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:f.current||"Detached HEAD"}),f.tracking&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["→ ",f.tracking]})]}),e.jsxs("div",{className:"flex items-center gap-3 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[e.jsx(gr,{className:"inline size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground ml-0.5",children:f.ahead})]}),e.jsxs("span",{children:[e.jsx(yr,{className:"inline size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground ml-0.5",children:f.behind})]}),e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-foreground",children:f.files.length})," changes"]})]}),e.jsx("div",{className:"flex-1"}),e.jsx(qg,{activeProfile:Ee,identities:it,onSelect:te,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(Cs,{variant:"default",onClick:()=>He("fetch"),disabled:z!==null||!f,children:[z==="fetch"?e.jsx(Ft,{size:16,className:"animate-spin"}):e.jsx(Cn,{size:16}),"Fetch"]}),e.jsxs(Cs,{variant:"default",onClick:()=>He("pull"),disabled:z!==null||!f,children:[z==="pull"?e.jsx(Ft,{size:16,className:"animate-spin"}):e.jsx(yr,{size:16}),"Pull"]}),e.jsxs(Cs,{variant:"default",onClick:()=>He("push"),disabled:z!==null||!f,children:[z==="push"?e.jsx(Ft,{size:16,className:"animate-spin"}):e.jsx(gr,{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(Rt,{open:he,onOpenChange:ie,children:[e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Lt,{asChild:!0,children:e.jsxs(De,{variant:"outline",size:"sm",className:"gap-1.5 px-2 py-1 h-8",children:[e.jsx(Tt,{className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:f?.current||"Branch"}),e.jsx(wt,{className:"size-4 opacity-60"})]})})}),e.jsxs(lt,{sideOffset:8,children:["Switch branch (",J.length," local · ",ue.length," remote)"]})]}),e.jsx(_t,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Fl,{className:"h-full min-h-0",children:[e.jsx(Pl,{placeholder:"Search branches…",value:Ne,onValueChange:Q}),e.jsxs(Rl,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Ll,{children:"No branches found."}),e.jsxs(Sr,{heading:"Local branches",children:[_e.locals.map(U=>e.jsxs(At,{onSelect:()=>R(U),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:U}),u?.branches?.[U]?.ahead||u?.branches?.[U]?.behind?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[u.branches[U].ahead||0," ahead ·"," ",u.branches[U].behind||0," behind"]}):null]}),f?.current===U&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${U}`)),_e.locals.length===0&&e.jsx(At,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(ho,{}),e.jsxs(Sr,{heading:"Remote branches",children:[_e.remotes.map(U=>e.jsx(At,{onSelect:()=>R(U),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:U})},`remote-${U}`)),_e.remotes.length===0&&e.jsx(At,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]}),e.jsx(kt,{placeholder:"New branch",value:A,onChange:U=>D(U.target.value),className:"h-8 w-32 sm:w-40 rounded-lg bg-background/80 text-sm"}),e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(De,{variant:"default",size:"sm",className:"h-8 px-2",onClick:pe,disabled:Y||!I,children:Y?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Zt,{className:"size-4"})})}),e.jsx(lt,{sideOffset:8,children:I?`Create branch "${I}"`:"Enter branch name"})]})]}),e.jsx("div",{className:"flex-1"}),_&&e.jsx("span",{className:"typography-micro text-muted-foreground hidden lg:inline",children:_})]}),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(Je,{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:[me,"/",Be]}),Be>0&&e.jsxs(e.Fragment,{children:[e.jsx(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:qe,children:"All"}),e.jsx(De,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:at,disabled:me===0,children:"None"})]})]})]}),e.jsx(Je,{outerClassName:"flex-1 min-h-0",className:"w-full",children:f?.isClean||Be===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(so,{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:Le.map(U=>e.jsx(Vg,{file:U,checked:B.has(U.path),stats:f?.diffStats?.[U.path],onToggle:()=>Te(U.path),onViewDiff:()=>Re.getState().navigateToDiff(U.path),onRevert:()=>rt(U.path),isReverting:O.has(U.path)},U.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:[Se.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(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"icon",className:"size-6",onClick:()=>{if(Se.length===0)return;const U=Se.map(ce=>ce.trim()).filter(Boolean);if(U.length===0){F();return}N(ce=>{const se=ce.trim(),ve=se.length>0?`
49
+
50
+ `:"";return`${se}${ve}${U.join(`
51
+ `)}`.trim()}),F()},"aria-label":"Insert highlights into commit message",children:e.jsx(yr,{className:"size-4"})})}),e.jsx(lt,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:Se.map((U,ce)=>e.jsx("li",{className:"typography-meta text-foreground",children:U},ce))})]}),e.jsx(Us,{value:M,onChange:U=>N(U.target.value),placeholder:ft?"Commit message":"No changes to commit",rows:Se.length>0?4:8,disabled:$!==null||!ft,className:T("flex-1 rounded-lg bg-background/80 resize-none",Se.length>0?"min-h-[80px]":"min-h-[180px]")}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Cs,{variant:"ghost",onClick:dt,disabled:ee||$!==null||me===0||Oe,className:"px-3","aria-label":"Generate commit message",children:ee?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(Zd,{className:"size-4 text-primary"})})}),e.jsx(lt,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Cs,{variant:"outline",onClick:()=>{F(),ot({pushAfter:!1})},disabled:$!==null||!M.trim()||me===0||ee,children:$==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(Ft,{className:"size-4 animate-spin"}),"Committing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(so,{className:"size-4"}),"Commit"]})}),e.jsx(Cs,{variant:"default",onClick:()=>{F(),ot({pushAfter:!0})},disabled:$!==null||!M.trim()||me===0||ee,children:$==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(Ft,{className:"size-4 animate-spin"}),"Pushing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(gr,{className:"size-4"}),"Commit & Push"]})})]})]})]}),p&&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(Fg,{value:String(ae),onValueChange:U=>{const ce=Number(U);je(ce),s&&(y(s,ce),w(s,r,ce))},disabled:x,children:[e.jsx(Rg,{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(Pg,{placeholder:"Commits"})}),e.jsx(Lg,{children:Hg.map(U=>e.jsx(_g,{value:String(U.value),children:U.label},U.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(Je,{outerClassName:"min-h-0 max-h-48 lg:max-h-64",className:"w-full",children:p.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:p.all.map(U=>e.jsx(Gg,{entry:U,isSelected:G===U.hash,onSelect:()=>P(U.hash)},U.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:cc(ct.date)}),e.jsx("code",{className:"font-mono",children:ct.hash.slice(0,8)}),e.jsxs(ut,{delayDuration:500,children:[e.jsx(mt,{asChild:!0,children:e.jsx(De,{variant:"ghost",size:"sm",className:"h-5 px-1.5 -ml-1",onClick:()=>ze(ct.hash),children:e.jsx(ks,{className:"size-3"})})}),e.jsx(lt,{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:Ie?"Loading...":`${de.length} file${de.length===1?"":"s"}`})}),e.jsx(Je,{outerClassName:"flex-1 min-h-0 max-h-32",className:"w-full",children:Ie?e.jsx("div",{className:"flex items-center justify-center p-3",children:e.jsx(Ft,{className:"size-4 animate-spin text-muted-foreground"})}):de.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:de.map(U=>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",U.changeType==="A"&&"text-emerald-500",U.changeType==="D"&&"text-red-500",U.changeType==="M"&&"text-amber-500",U.changeType==="R"&&"text-blue-500"),children:U.changeType}),e.jsx("span",{className:"typography-micro text-foreground truncate flex-1",title:U.path,children:U.path}),!U.isBinary&&e.jsxs("span",{className:"typography-micro shrink-0",children:[e.jsxs("span",{className:"font-semibold",style:{color:"var(--status-success)"},children:["+",U.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{className:"font-semibold",style:{color:"var(--status-error)"},children:["-",U.deletions]})]}),U.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},U.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"})})})]})]})]})})]})},Vg=({file:r,checked:s,onToggle:t,onViewDiff:n,onRevert:o,isReverting:a,stats:i})=>{const c=l.useMemo(()=>Kg(r),[r]),d=c.description??c.code,m=i?.insertions??0,f=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:u=>{u.key===" "?(u.preventDefault(),t()):u.key==="Enter"&&(u.preventDefault(),n())},children:[e.jsx("button",{type:"button",onClick:u=>{u.preventDefault(),u.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(To,{className:"size-4 text-primary"}):e.jsx(Io,{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:["+",m]}),e.jsx("span",{className:"mx-0.5 text-muted-foreground",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",f]})]}),e.jsxs(ut,{delayDuration:200,children:[e.jsx(mt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:u=>{u.preventDefault(),u.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(Ft,{className:"size-4 animate-spin"}):e.jsx(Cn,{className:"size-4"})})}),e.jsx(lt,{sideOffset:8,children:"Revert changes"})]})]})})},Gg=({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," · ",cc(r.date)]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:r.hash.slice(0,8)})]})]}),qg=({activeProfile:r,identities:s,onSelect:t,isApplying:n})=>{const o=n||s.length===0;return e.jsxs(Rt,{children:[e.jsxs(ut,{delayDuration:1e3,children:[e.jsx(mt,{asChild:!0,children:e.jsx(Lt,{asChild:!0,children:e.jsxs(De,{variant:"outline",size:"sm",className:"gap-2 px-3 py-1 typography-ui-label",style:{color:lc(r?.color)},disabled:o,children:[n?e.jsx(Ft,{className:"size-4 animate-spin"}):e.jsx(wi,{icon:r?.icon,colorToken:r?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[180px] truncate",children:r?.name||"No identity"}),e.jsx(wt,{className:"size-4 opacity-60"})]})})}),e.jsxs(lt,{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(_t,{align:"end",className:"w-64",children:s.length===0?e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(a=>e.jsx(gt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(wi,{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 Kg(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 Yg={branch:Tt,briefcase:Do,house:Ao,graduation:Mo,code:Ts,heart:$i,user:kn},Xg={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 lc(r){return r&&Xg[r]||"var(--primary)"}const wi=({icon:r,className:s,colorToken:t})=>{const n=Yg[r??"branch"]??kn;return e.jsx(n,{className:s,style:{color:lc(t)}})};function cc(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 Jg=256e3;function $s(r){let s=r.trim();for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s}const qr=r=>({directory:r,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),vi=It((r,s)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=$s(t);return s().sessions.get(n)},setTerminalSession:(t,n)=>{const o=$s(t);r(a=>{const i=new Map(a.sessions),c=i.get(o),m=!c||c.terminalSessionId!==n.sessionId?qr(o):c??qr(o);return i.set(o,{...m,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=$s(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??qr(o);return i.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=$s(t);r(a=>{const i=new Map(a.sessions),c=i.get(o)??qr(o),d=a.nextChunkId,m={id:d,data:n},f=[...c.bufferChunks,m];let u=c.bufferLength+n.length;for(;u>Jg&&f.length>1;){const h=f.shift();if(!h)break;u-=h.data.length}const p=f.map(h=>h.data).join("");return i.set(o,{...c,buffer:p,bufferChunks:f,bufferLength:u,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=$s(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=$s(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=$s(t);r(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{r({sessions:new Map,nextChunkId:1})}})),dc=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Zg=[{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'}],Qg=[{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'}],uc=r=>Object.fromEntries(r.map(s=>[s.id,s])),Si=uc(Zg),zs=uc(Qg),ey="ibm-plex-sans",rn="ibm-plex-mono";function ty(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 mc=l.forwardRef(({sessionKey:r,chunks:s,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:c,enableTouchScroll:d},m)=>{const f=l.useRef(null),u=l.useRef(null),p=l.useRef(null),h=l.useRef(null),g=l.useRef(t),x=l.useRef(n),S=l.useRef([]),v=l.useRef(!1),k=l.useRef(0),b=l.useRef(null),w=l.useRef(null),[,j]=l.useReducer(D=>D+1,0);g.current=t,x.current=n;const y=l.useCallback(()=>{S.current=[],v.current=!1,k.current=0,b.current=null},[]),C=l.useCallback(()=>{const D=h.current,I=p.current,z=f.current;if(!D||!I||!z)return;const E=z.getBoundingClientRect();if(!(E.width<24||E.height<24))try{D.fit(),x.current(I.cols,I.rows)}catch{}},[]),M=l.useCallback(()=>{if(v.current)return;const D=()=>{const I=p.current;if(!I){y();return}const z=S.current.shift();if(z===void 0){v.current=!1;return}v.current=!0,I.write(z,()=>{v.current=!1,S.current.length>0&&(typeof window<"u"?window.setTimeout(D,0):D())})};D()},[y]),N=l.useCallback(D=>{D&&(S.current=[D],v.current=!1,M())},[M]),A=l.useCallback(()=>{if(w.current?.(),w.current=null,!d)return;const D=f.current,I=p.current;if(!D||!I)return;const z={lastY:null,remainder:0},$=I._core?.dimensions?.actualCellHeight??null,V=typeof $=="number"&&$>0?$:Math.max(i+6,i*1.6),Y=je=>{je.touches.length===1&&(z.lastY=je.touches[0].clientY,z.remainder=0)},L=je=>{if(je.touches.length!==1){z.lastY=null,z.remainder=0;return}if(z.lastY===null){z.lastY=je.touches[0].clientY;return}const Me=je.touches[0].clientY,$e=z.lastY-Me;z.lastY=Me;const he=z.remainder+$e/V,ie=he>0?Math.floor(he):he<0?Math.ceil(he):0;z.remainder=he-ie,ie!==0&&(je.preventDefault(),je.stopPropagation(),I.scrollLines(ie))},_=()=>{z.lastY=null,z.remainder=0},W={passive:!1};D.addEventListener("touchstart",Y,W),D.addEventListener("touchmove",L,W),D.addEventListener("touchend",_),D.addEventListener("touchcancel",_);const ae=D.style.touchAction;D.style.touchAction="none",w.current=()=>{D.removeEventListener("touchstart",Y),D.removeEventListener("touchmove",L),D.removeEventListener("touchend",_),D.removeEventListener("touchcancel",_),D.style.touchAction=ae}},[d,i]);return l.useEffect(()=>{const D=new Qd.Terminal(ji(a,i,o)),I=new eu.FitAddon;p.current=D,h.current=I,D.loadAddon(I);const z=f.current;if(z){D.open(z);const V=z.querySelector(".xterm-viewport");V&&(V.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),u.current=V,j()),C(),D.focus()}const E=[D.onData(V=>{g.current(V)})],$=new ResizeObserver(()=>{C()});return z&&$.observe(z),()=>{w.current?.(),w.current=null,E.forEach(V=>V.dispose()),$.disconnect(),D.dispose(),p.current=null,h.current=null,y()}},[C,a,i,o,y]),l.useEffect(()=>{const D=p.current;if(!D)return;const I=ji(a,i,o);Object.assign(D.options,I),C()},[C,a,i,o]),l.useEffect(()=>{const D=p.current;D&&(D.reset(),y(),C(),D.focus())},[r,C,y]),l.useEffect(()=>(A(),()=>{w.current?.(),w.current=null}),[A,r]),l.useEffect(()=>{const D=p.current;if(!D)return;if(s.length===0){k.current!==0&&(D.reset(),y(),C());return}const I=s[0].id;if(b.current===null&&(b.current=I),(b.current!==I||k.current>s.length)&&(D.reset(),y(),b.current=I),k.current<s.length){const E=s.slice(k.current);N(E.map($=>$.data).join("")),k.current=s.length}},[s,N,C,y]),l.useImperativeHandle(m,()=>({focus:()=>{p.current?.focus()},clear:()=>{const D=p.current;D&&(D.reset(),y(),C())},fit:()=>{C()}}),[C,y]),e.jsx("div",{ref:f,className:T("relative h-full w-full",c),children:u.current?e.jsx(Vo,{containerRef:u,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null})});mc.displayName="TerminalViewport";const sy=13,ry={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Kr={ctrl:"5",cmd:"3"},ny={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},oy=(r,s)=>{if(s)switch(r){case"arrow-up":return`\x1B[1;${Kr[s]}A`;case"arrow-down":return`\x1B[1;${Kr[s]}B`;case"arrow-right":return`\x1B[1;${Kr[s]}C`;case"arrow-left":return`\x1B[1;${Kr[s]}D`}return ry[r]??null},ay=()=>{const{terminal:r}=Gs(),{currentTheme:s}=ir(),{monoFont:t}=dc(),{isMobile:n}=Ct(),{currentSessionId:o,sessions:a,worktreeMetadata:i}=ye(),c=o?i.get(o)??void 0:void 0,d=l.useMemo(()=>{if(c?.path)return c.path;if(!o)return null;const F=a.find(P=>P.id===o),G=typeof F?.directory=="string"?F.directory:null;return G&&G.length>0?G:null},[o,a,c]),{currentDirectory:m,homeDirectory:f}=yt(),u=d||m||null,p=l.useMemo(()=>u?f?u===f?"~":u.startsWith(f+"/")?"~"+u.slice(f.length):u:u:"",[u,f]),h=vi(),g=h.sessions,x=h.setTerminalSession,S=h.setConnecting,v=h.appendToBuffer,k=h.clearTerminalSession,b=h.removeTerminalSession,w=h.clearBuffer,j=l.useMemo(()=>{if(u)return g.get(u)},[g,u]),y=j?.terminalSessionId??null,C=j?.bufferChunks??[],M=j?.bufferLength??0,N=j?.isConnecting??!1,A=y,[D,I]=l.useState(null),[z,E]=l.useState(!1),[$,V]=l.useState(null),[Y,L]=l.useState(!1),_=l.useRef(null),W=l.useRef(null),ae=l.useRef(A),je=l.useRef(u),Me=l.useRef(null),he=Re(F=>F.activeMainTab)==="terminal";l.useEffect(()=>{ae.current=A},[A]),l.useEffect(()=>{je.current=u},[u]),l.useEffect(()=>{!n&&$!==null&&V(null)},[n,$,V]),l.useEffect(()=>{!A&&$!==null&&V(null)},[A,$,V]);const ie=l.useCallback(()=>{_.current?.(),_.current=null,W.current=null},[]);l.useEffect(()=>()=>{ie(),ae.current=null},[ie]);const Ne=l.useCallback(F=>{if(W.current===F)return;ie();const G=r.connect(F,{onEvent:P=>{const de=je.current;if(de)switch(P.type){case"connected":{S(de,!1),I(null),E(!1),Me.current?.focus();break}case"reconnecting":{const be=P.attempt??0,Ie=P.maxAttempts??3;I(`Reconnecting (${be}/${Ie})...`),E(!1);break}case"data":{P.data&&v(de,P.data);break}case"exit":{const be=typeof P.exitCode=="number"?P.exitCode:null,Ie=typeof P.signal=="number"?P.signal:null;v(de,`\r
52
+ [Process exited${be!==null?` with code ${be}`:""}${Ie!==null?` (signal ${Ie})`:""}]\r
53
+ `),k(de),S(de,!1),I("Terminal session ended"),E(!1),ie();break}}},onError:(P,de)=>{const be=je.current;if(!be)return;const Ie=de?`Connection failed: ${P.message}`:P.message||"Terminal stream connection error";I(Ie),E(!!de),de&&(S(be,!1),ie(),b(be))}},ny);_.current=()=>{G.close(),W.current=null},W.current=F},[v,k,ie,b,S,r,I]);l.useEffect(()=>{let F=!1;if(!u){I(o?"No working directory available for terminal.":"Select a session to open the terminal."),ie();return}return(async()=>{const P=u;if(!je.current||je.current!==P)return;let be=vi.getState().getTerminalSession(P)?.terminalSessionId??null;if(!be){I(null),E(!1),S(P,!0);try{const Ie=await r.createSession({cwd:P});if(F){try{await r.close(Ie.sessionId)}catch{}return}x(P,Ie),be=Ie.sessionId}catch(Ie){F||(I(Ie instanceof Error?Ie.message:"Failed to start terminal session"),E(!0),S(P,!1));return}}!be||F||(ae.current=be,Ne(be))})(),()=>{F=!0,ae.current=null,ie()}},[o,u,A,b,S,x,Ne,ie,r]);const Q=l.useCallback(async()=>{if(!u||Y)return;L(!0),I(null),E(!1),ie();const F=ae.current;try{if(r.restartSession&&F){const G=await r.restartSession(F,{cwd:u});x(u,G),ae.current=G.sessionId,Ne(G.sessionId)}else{if(F)try{await r.close(F)}catch{}b(u)}}catch(G){I(G instanceof Error?G.message:"Failed to restart terminal"),E(!0)}finally{L(!1)}},[u,Y,ie,r,x,Ne,b]),We=l.useCallback(async()=>{if(u&&!Y){L(!0),I(null),E(!1),ie();try{r.forceKill&&await r.forceKill({cwd:u})}catch{}b(u),w(u),Me.current?.clear(),await new Promise(F=>setTimeout(F,100));try{S(u,!0);const F=await r.createSession({cwd:u});x(u,F),ae.current=F.sessionId,Ne(F.sessionId)}catch(F){I(F instanceof Error?F.message:"Failed to create terminal"),E(!0),S(u,!1)}finally{L(!1)}}},[u,Y,ie,r,b,w,S,x,Ne]),ne=l.useCallback(()=>{if(!u)return;w(u),Me.current?.clear(),Me.current?.focus();const F=ae.current;F&&r.sendInput(F,"\f").catch(G=>{I(G instanceof Error?G.message:"Failed to refresh prompt")})},[w,u,I,r]),B=l.useCallback(F=>{if(!F)return;let G=F,P=!1;if($&&F.length>0){const be=F[0];if(be.length===1&&/[a-zA-Z]/.test(be)){const Ie=be.toUpperCase();($==="ctrl"||$==="cmd")&&(G=String.fromCharCode(Ie.charCodeAt(0)&31),P=!0)}P||(P=!0)}const de=ae.current;de&&(r.sendInput(de,G).catch(be=>{I(be instanceof Error?be.message:"Failed to send input")}),P&&(V(null),Me.current?.focus()))},[$,V,r]),we=l.useCallback((F,G)=>{const P=ae.current;P&&r.resize({sessionId:P,cols:F,rows:G}).catch(()=>{})},[r]),oe=l.useCallback(F=>{V(G=>G===F?null:F),Me.current?.focus()},[V]),Z=l.useCallback(F=>{const G=oy(F,$);G&&(B(G),V(null),Me.current?.focus())},[$,B,V]);l.useEffect(()=>{if(!n||!$||!A)return;const F=G=>{if(G.repeat)return;const P=G.key;if(!P||P==="Control"||P==="Meta"||P==="Alt"||P==="Shift")return;const de=P.length===1?P.toLowerCase():P,be=G.code??"",Ie=be.startsWith("Key")&&be.length===4?be.slice(3).toUpperCase():null,Ye=P.length===1&&/[a-zA-Z]/.test(P)?P.toUpperCase():Ie,ct={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc",tab:"tab",enter:"enter",arrowup:"arrow-up",arrowdown:"arrow-down",arrowleft:"arrow-left",arrowright:"arrow-right",escape:"esc"};if(de in ct){G.preventDefault(),G.stopPropagation(),Z(ct[de]);return}if($==="ctrl"&&Ye&&Ye.length===1&&Ye>="A"&&Ye<="Z"){const ze=String.fromCharCode(Ye.charCodeAt(0)&31);G.preventDefault(),G.stopPropagation(),B(ze),V(null),Me.current?.focus()}};return window.addEventListener("keydown",F),()=>{window.removeEventListener("keydown",F)}},[$,Z,B,n,V,A]);const O=l.useMemo(()=>{const F=zs[rn].stack;if(typeof window>"u")return(zs[t]??zs[rn]).stack;const P=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return P&&P.trim().length>0?P.trim():(zs[t]??zs[rn]).stack??F},[t]),re=l.useMemo(()=>ty(s),[s]),ee=l.useMemo(()=>`${u??"no-dir"}::${A??"pending"}`,[u,A]);l.useEffect(()=>{if(!he)return;const F=Me.current;if(!F)return;const G=()=>{F.fit()};if(typeof window<"u"){const P=window.requestAnimationFrame(()=>{G(),F.focus()}),de=[220,400].map(be=>window.setTimeout(G,be));return()=>{window.cancelAnimationFrame(P),de.forEach(be=>window.clearTimeout(be))}}G()},[he,ee,A]);const le=D?.includes("Reconnecting"),Se=D?le?e.jsx(su,{size:20,className:"text-amber-400"}):e.jsx(os,{size:20,className:"text-destructive"}):A&&!N&&!Y?e.jsx(Xr,{size:20,className:"text-emerald-400"}):N||Y?e.jsx(la,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(la,{size:20,className:"text-muted-foreground"});if(!o)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(!u)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:Q,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const xe=!A||N||Y;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:p})}),e.jsxs("div",{className:"flex items-center gap-2",children:[Se,e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:ne,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(Ps,{size:16}),"Clear"]}),e.jsxs(De,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Q,disabled:Y,title:"Restart terminal session",type:"button",children:[e.jsx(rr,{size:16,className:T((N||Y)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(De,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>Z("esc"),disabled:xe,children:"Esc"}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Z("tab"),disabled:xe,children:[e.jsx(ia,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(De,{type:"button",size:"sm",variant:$==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>oe("ctrl"),disabled:xe,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:$==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>oe("cmd"),disabled:xe,children:[e.jsx(nr,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Z("arrow-up"),disabled:xe,children:[e.jsx(gr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Z("arrow-left"),disabled:xe,children:[e.jsx(Wi,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Z("arrow-down"),disabled:xe,children:[e.jsx(yr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Z("arrow-right"),disabled:xe,children:[e.jsx(ia,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(De,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Z("enter"),disabled:xe,children:[e.jsx(tu,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:re.background},children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:he?e.jsx(Je,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(mc,{ref:F=>{Me.current=F},sessionKey:ee,chunks:C,onInput:B,onResize:we,theme:re,fontFamily:O,fontSize:sy,enableTouchScroll:n},ee)}):null}),D&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:D}),z&&e.jsx(De,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:We,disabled:Y,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},iy=()=>{const{isSidebarOpen:r,activeMainTab:s,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i}=Re(),{isMobile:c}=Ct(),[d,m]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||m(typeof window.opencodeDesktop<"u")},[]),Lp({enabled:!0}),l.useEffect(()=>{Re.getState().isMobile!==c&&t(c)},[c,t]),l.useEffect(()=>{if(typeof window>"u")return;let p;const h=()=>{p!==void 0&&window.clearTimeout(p),p=window.setTimeout(()=>{Re.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",h),()=>{window.removeEventListener("resize",h),p!==void 0&&window.clearTimeout(p)}},[]);const f=l.useMemo(()=>{switch(s){case"git":return e.jsx(Ug,{});case"diff":return e.jsx(Hf,{});case"terminal":return e.jsx(ay,{});default:return null}},[s]),u=s==="chat";return e.jsx(Rp,{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(vp,{}),e.jsx(kp,{}),e.jsx(Ip,{}),e.jsx(bp,{isOpen:a,onClose:()=>i(!1)}),c?e.jsxs(e.Fragment,{children:[e.jsx($a,{}),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",!u&&"invisible"),children:e.jsx(Xt,{children:e.jsx(vo,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Xt,{children:f})})]})}),e.jsx(Wt,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(go,{mobileVariant:!0})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Yf,{isOpen:r,isMobile:c,children:e.jsx(go,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx($a,{}),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",!u&&"invisible"),children:e.jsx(Xt,{children:e.jsx(vo,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Xt,{children:f})})]})})]})]}),e.jsx(Uf,{})]})})},ly=()=>{const[r,s]=l.useState("sessions"),t=ye(E=>E.currentSessionId),n=ye(E=>E.sessions),o=ye(E=>E.createSession),a=ye(E=>E.setCurrentSession),[i,c]=l.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),[d,m]=l.useState(()=>typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.error:void 0),[f,u]=l.useState(()=>i==="connected"),[p,h]=l.useState(()=>i!=="connected"),g=l.useRef(null),x=xt(E=>E.isInitialized),S=xt(E=>E.initializeApp),v=ye(E=>E.loadSessions),k=ye(E=>E.loadMessages),b=ye(E=>E.messages),[w,j]=l.useState(()=>x),[y,C]=l.useState(!1),M=l.useRef(!1),N=l.useRef(!1);l.useEffect(()=>{t&&s("chat")},[t]),l.useEffect(()=>{!t&&r==="chat"&&s("sessions")},[t,r]);const A=l.useCallback(()=>{s("sessions")},[]),D=l.useCallback(async()=>{(await o())?.id&&s("chat")},[o]);l.useEffect(()=>{const E=$=>{const V=$.detail,Y=V?.status;(Y==="connected"||Y==="connecting"||Y==="error"||Y==="disconnected")&&(c(Y),m(V?.error),Y==="connected"&&u(!0))};return window.addEventListener("openchamber:connection-status",E),()=>window.removeEventListener("openchamber:connection-status",E)},[]);const I=l.useMemo(()=>w&&i==="connected"&&!y?!1:w?i==="error":i!=="connected"||y,[i,w,y]),z=f?800:250;return l.useEffect(()=>(g.current&&(window.clearTimeout(g.current),g.current=null),I?g.current=window.setTimeout(()=>h(!0),z):h(!1),()=>{g.current&&(window.clearTimeout(g.current),g.current=null)}),[z,I]),l.useEffect(()=>{(async()=>{if(!(y||w||i!=="connected")){C(!0);try{x||await S(),await v(),j(!0)}catch{}finally{C(!1)}}})()},[i,x,w,S,y,v]),l.useEffect(()=>{(async()=>{if(!w||i!=="connected"||r!=="chat")return;const $=t||n[0]?.id;if(!$)return;if(!(b.has($)&&(b.get($)?.length||0)>0)){t||a($);try{await k($)}catch{}}})()},[i,t,r,w,k,b,n,a]),l.useEffect(()=>{!w||M.current||!t&&n.length>0&&(a(n[0].id),M.current=!0)},[t,w,n,a]),l.useEffect(()=>{(async()=>{if(i!=="connected"||!w||N.current)return;const $=n.find(Y=>Y.id===t),V=$?.title?.toLowerCase()?.startsWith("new session");if($&&V)a($.id);else{const Y=n.find(L=>L.title?.toLowerCase()?.startsWith("new session"));if(Y)a(Y.id);else{const L=await o();L?.id&&a(L.id)}}N.current=!0})()},[i,o,t,w,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(ki,{title:"Sessions",onNewSession:D}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(go,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>s("chat"),hideDirectoryControls:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(ki,{title:n.find(E=>E.id===t)?.title||"Chat",showBack:!0,onBack:A,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Xt,{children:e.jsx(vo,{})})})]}),p&&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(Ft,{className:"h-7 w-7 animate-spin text-muted-foreground"}),e.jsx("div",{className:"text-sm font-medium",children:i==="connecting"?f?"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})]})]})},ki=({title:r,showBack:s,onBack:t,onNewSession:n,showContextUsage:o})=>{const{getCurrentModel:a}=xt(),i=ye(p=>p.getContextUsage),c=a(),d=c?.limit&&typeof c.limit=="object"?c.limit:null,m=typeof d?.context=="number"?d.context:0,f=typeof d?.output=="number"?d.output:0,u=i(m,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(Wi,{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(Zt,{className:"h-5 w-5"})}),o&&u&&u.totalTokens>0&&e.jsx(mo,{totalTokens:u.totalTokens,percentage:u.percentage,contextLimit:u.contextLimit,outputLimit:u.outputLimit??0,size:"compact"})]})},Ni=({...r})=>{const{theme:s="system"}=ru();return e.jsx(nu,{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})},cy=(r=5e3)=>{const[s,t]=fe.useState(null);return fe.useEffect(()=>{if(!Ht())return;let n=!1,o=null;const a=async()=>{const i=await Nu();n||(t(i),o=setTimeout(a,r))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[r]),s},dy=({onClose:r})=>{const{sessions:s,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=ye(),c=cy(4e3),d=l.useMemo(()=>{let u=0;return t.forEach(p=>{u+=p.length}),u},[t]),m=l.useMemo(()=>s.map(u=>{const p=t.get(u.id)?.length||0,h=n.get(u.id);return{id:u.id,title:u.title||"Untitled",messageCount:p,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:u.id===o}}).sort((u,p)=>p.lastAccessed-u.lastAccessed),[s,t,n,o]),f=t.size;return e.jsxs(Xo,{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(ou,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),r&&e.jsx(De,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:r,children:e.jsx(os,{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:[f," / ",Dt.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:[Dt.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:[Dt.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:[Dt.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(Je,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:m.map(u=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${u.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:u.title}),u.isStreaming&&e.jsx(au,{className:"h-3 w-3 text-primary animate-pulse"}),u.isZombie&&e.jsx("span",{className:"text-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${u.messageCount>Dt.VIEWPORT_MESSAGES?"text-warning":""}`,children:[u.messageCount," msgs"]}),u.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",u.backgroundCount]})]})]},u.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Ps,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]}),e.jsx(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"}),e.jsx(De,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{},children:"Log State"})]})]})]})},uy="openchamber-message-cursors",sr="cursors",my=1,fc="openchamber.messageCursors",Zo=()=>typeof window<"u",Qo=()=>Zo()&&typeof indexedDB<"u",pc=()=>Qo()?new Promise((r,s)=>{const t=indexedDB.open(uy,my);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(sr)||n.createObjectStore(sr)},t.onerror=()=>{s(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{r(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),hc=()=>{if(!Zo())return{};try{const r=window.localStorage.getItem(fc);if(!r)return{};const s=JSON.parse(r);return s&&typeof s=="object"?s:{}}catch{return{}}},fy=r=>{if(Zo())try{window.localStorage.setItem(fc,JSON.stringify(r))}catch{}},py=async(r,s,t)=>{if(!r||!s)return;if(Qo())try{const o=await pc();await new Promise((a,i)=>{const c=o.transaction(sr,"readwrite");c.objectStore(sr).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=hc();n[r]={messageId:s,completedAt:t},fy(n)},hy=async r=>{if(!r)return null;if(Qo())try{const t=await pc(),n=await new Promise((o,a)=>{const i=t.transaction(sr,"readonly"),d=i.objectStore(sr).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 hc()[r]??null},Vt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},gy=50,Ci=new WeakMap,Mi=r=>{if(!r||!Array.isArray(r))return 0;const s=Ci.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 Ci.set(r,t),t},So=new Map,Ai=(r,s)=>{const t=`${r}:${s}`,n=So.get(t);if(n&&n.sessionId===r)return n.message;const i=(ye.getState().messages.get(r)||[]).find(c=>c.info.id===s)||null;return So.set(t,{sessionId:r,message:i}),i},yy=()=>{const{addStreamingPart:r,completeStreamingMessage:s,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:m,loadSessions:f}=ye(),{checkConnection:u}=xt(),p=yt(ne=>ne.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 ne=c.find(B=>B.id===a);if(ne&&typeof ne.directory=="string"&&ne.directory.trim().length>0)return ne.directory.trim()},[a,d,c]),g=l.useMemo(()=>{if(h&&h.length>0)return h;if(typeof p=="string"&&p.trim().length>0)return p.trim()},[h,p]),x=Re(ne=>ne.setEventStreamStatus),S=l.useRef(null),v=l.useCallback((ne,B)=>{const we=B??null,oe=S.current;if(!(oe&&oe.status===ne&&oe.hint===we)){if(S.current={status:ne,hint:we},Vt()){const O={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[ne]??"[INFO]",re=we?`${O} SSE ${ne}: ${we}`:`${O} SSE ${ne}`;console.info(re)}x(ne,we)}},[x]),k=l.useCallback((ne,B,we)=>{Vt()&&console.debug(`[MessageTracker] ${ne}: ${B}`,we)},[]),b=l.useCallback(ne=>{Vt()&&console.debug(`[MessageTracker] ${ne}: reported`)},[]),w=l.useRef(null),j=l.useRef(null),y=l.useRef(0);l.useRef(new Set);const C=l.useRef(new Map),M=l.useRef(null),N=l.useRef(!1),A=l.useCallback(()=>{if(typeof document>"u")return"visible";const ne=document.visibilityState;return ne==="hidden"&&document.hasFocus()?"visible":ne},[]),D=l.useRef(A()),I=l.useRef(typeof navigator>"u"?!0:navigator.onLine),z=l.useRef(!1),E=l.useRef(null),$=l.useRef(null),V=l.useRef(Date.now()),Y=l.useRef(!1);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(Y.current=!0)},[]);const L=l.useRef(new Map),_=l.useRef(new Map),W=l.useCallback(ne=>{if(!ne)return;const B=Date.now(),we=C.current,oe=we.get(ne);oe&&B-oe<3e3||(we.set(ne,B),setTimeout(async()=>{try{const Z=await Ae.getSession(ne);if(Z){const O={};typeof Z.title=="string"&&Z.title.length>0&&(O.title=Z.title),Z.summary!==void 0&&(O.summary=Z.summary),Object.keys(O).length>0&&i(ne,O)}}catch(Z){console.warn("Failed to refresh session metadata:",Z)}},100))},[i]),ae=l.useCallback(()=>{M.current||(M.current=setTimeout(()=>{M.current=null;try{f()}catch(ne){console.warn("Failed to refresh sessions after stream completion:",ne)}},500))},[f]),je=l.useCallback((ne,B)=>{if(_.current.get(ne)===B)return;const oe=L.current.get(ne);if(oe&&(clearTimeout(oe),L.current.delete(ne)),_.current.set(ne,B),ye.setState({sessionActivityPhase:new Map(_.current)}),B==="cooldown"){const Z=setTimeout(()=>{L.current.delete(ne),_.current.get(ne)==="cooldown"&&(_.current.set(ne,"idle"),ye.setState({sessionActivityPhase:new Map(_.current)}))},2e3);L.current.set(ne,Z)}},[]),Me=l.useCallback(ne=>{if(V.current=Date.now(),Vt()&&console.debug("[useEventStream] Received event:",ne.type,ne.properties),!ne.properties)return;const B=ne.properties;if(!new Set(["session.abort","session.error"]).has(ne.type)){const oe=(typeof B.session=="object"&&B.session!==null?B.session:null)||(typeof B.sessionInfo=="object"&&B.sessionInfo!==null?B.sessionInfo:null);if(oe){const Z=oe,O=typeof Z.id=="string"&&Z.id.length>0?Z.id:typeof Z.sessionID=="string"&&Z.sessionID.length>0?Z.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof B.id=="string"&&B.id.length>0?B.id:void 0;if(O){const re=typeof Z.title=="string"?Z.title:typeof B.title=="string"?B.title:void 0,ee=typeof Z.summary=="object"&&Z.summary!==null?Z.summary:typeof B.summary=="object"&&B.summary!==null?B.summary:void 0;if(re!==void 0||ee!==void 0){const le={};re!==void 0&&(le.title=re),ee!==void 0&&(le.summary=ee),i(O,le)}}}}switch(ne.type){case"server.connected":u();break;case"openchamber:session-activity":{if(!Y.current)break;const oe=typeof B.sessionId=="string"?B.sessionId:null,Z=typeof B.phase=="string"?B.phase:null;oe&&(Z==="idle"||Z==="busy"||Z==="cooldown")&&(je(oe,Z),ae());break}case"session.status":if(Y.current)break;{const oe=typeof B.sessionID=="string"?B.sessionID:null,Z=typeof B.status=="object"&&B.status!==null?B.status:null,O=typeof Z?.type=="string"?Z.type:null;oe&&O&&(je(oe,O==="busy"||O==="retry"?"busy":"idle"),ae())}break;case"message.part.updated":{const oe=typeof B.part=="object"&&B.part!==null?B.part:null;if(!oe)break;const Z=oe,O=typeof B.info=="object"&&B.info!==null?B.info:B,re=typeof O.sessionID=="string"?O.sessionID:null,ee=typeof Z.sessionID=="string"&&Z.sessionID.length>0?Z.sessionID:typeof re=="string"&&re.length>0?re:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,le=typeof O.id=="string"?O.id:null,Se=typeof Z.messageID=="string"&&Z.messageID.length>0?Z.messageID:typeof le=="string"&&le.length>0?le:typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;if(!ee||!Se){Vt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:Z.sessionID??re??B.sessionID,messageID:Z.messageID??le??B.messageID});break}const xe=ee,F=Se;let G="assistant";if(O&&typeof O.role=="string")G=O.role;else{const de=Ai(xe,F);if(de){const be=de.info.role;typeof be=="string"&&(G=be)}}if(k(F,"part_received",{role:G}),G==="user"&&Z.synthetic===!0){k(F,"skipped_synthetic_user_part");break}const P={...oe,type:oe.type||"text"};k(F,"addStreamingPart_called"),r(xe,F,P,G);break}case"message.updated":{const oe=typeof B.info=="object"&&B.info!==null?B.info:B,Z=oe,O=typeof Z.sessionID=="string"&&Z.sessionID.length>0?Z.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,re=typeof Z.id=="string"&&Z.id.length>0?Z.id:typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;if(!O||!re){Vt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:Z.sessionID??B.sessionID,messageID:Z.id??B.messageID});break}const ee=O,le=re;if(Y.current&&Vt())try{const ze=B.parts||Z.parts||[],Qe=(Array.isArray(ze)?ze.filter(Ge=>Ge?.type==="text"):[]).map(Ge=>{const Le=Ge;return typeof Le?.text=="string"?Le.text:typeof Le?.content=="string"?Le.content:""}).join(`
54
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:le,role:Z.role,status:Z.status,textLen:Qe.length,textPreview:Qe.slice(0,120),partsCount:Array.isArray(ze)?ze.length:0})}catch{}if(k(le,"message_updated",{role:Z.role}),Z.role==="user"){const ze=B.parts||Z.parts,et=Array.isArray(ze)?ze:[],Qe={...oe,userMessageMarker:!0,clientRole:"user"};if(t(ee,le,Qe),et.length>0)for(let Ge=0;Ge<et.length;Ge++){const Le=et[Ge];if(Le.synthetic===!0)continue;const He={...Le,type:Le?.type||"text",sessionID:Le?.sessionID||ee,messageID:Le?.messageID||le};r(ee,le,He,"user")}k(le,"user_message_created_from_event",{partsCount:et.length});break}const Se=Ai(ee,le),xe=Mi(Se?.parts||[]),F=Se?.parts?.some(ze=>ze?.type==="step-finish"&&ze.reason==="stop")??!1,G=B.parts||Z.parts,P=Array.isArray(G)?G:[],de=P.length>0,Ie=typeof(Z.time||{})?.completed=="number";if(!de&&!Ie)break;if(Z.role==="assistant"&&de){const ze=Mi(P),et=xe>0&&ze+gy<xe,Qe=P.some(Ge=>Ge?.type==="step-finish"&&Ge.reason==="stop");if(et&&!Qe){k(le,"skipped_shrinking_update",{incomingLen:ze,existingLen:xe});break}if(Y.current){const Ge=xe>0&&ze<xe,Le=P.some(ot=>{if(!ot||ot.type!=="text")return!1;const dt=ot;return typeof dt.text=="string"&&dt.text.length>0});if(Ge&&!(Qe&&Le)){k(le,"desktop_shrinking_update_suppressed",{incomingLen:ze,existingLen:xe});break}}}if(t(ee,le,oe),de&&Z.role!=="user"){const Qe=(ye.getState().messages.get(ee)||[]).find(He=>He.info.id===le),Ge=!Qe||Qe.parts.length===0;k(le,Ge?"server_parts_injected":"server_parts_refreshed",{count:P.length});const Le=Y.current&&Z.role==="assistant"?P.filter(He=>He?.type!=="text"):P;for(let He=0;He<Le.length;He++){const ot=Le[He],dt={...ot,type:ot?.type||"text",sessionID:ot?.sessionID||ee,messageID:ot?.messageID||le};r(ee,le,dt,Z.role),k(le,`server_part_${He}`)}}const Ye=oe.time;if(oe.role==="assistant"&&Ye?.completed!==void 0&&oe.role==="assistant"){const et=ye.getState().messages.get(ee)||[];let Qe=null,Ge="";for(let R=0;R<et.length;R++){const te=et[R];te.info.role==="assistant"&&te.info.id>Ge&&(Ge=te.info.id,Qe=te.info.id)}if(le!==Qe)break;if(!(P.some(R=>R?.type==="step-finish"&&R.reason==="stop")||F)&&Y.current){k(le,"desktop_completion_without_stop");break}const He=Ye?.completed!==void 0?Ye?.completed:Date.now();if(Ye?.completed||t(ee,le,{...oe,time:{...Ye??{},completed:He}}),k(le,"completed",{timeCompleted:He}),b(le),py(ee,le,He),s(ee,le),!Y.current){const R=oe.sessionID,te=typeof R=="string"&&R.length>0?R:ee;_.current.get(te)==="busy"&&je(te,"cooldown")}const ot=oe.sessionID,dt=typeof ot=="string"&&ot.length>0?ot:ee;W(dt),oe.summary&&typeof dt=="string"&&n(dt,null)}break}case"session.updated":{const oe=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,Z=typeof oe.id=="string"&&oe.id.length>0?oe.id:typeof oe.sessionID=="string"&&oe.sessionID.length>0?oe.sessionID:typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:typeof B.id=="string"&&B.id.length>0?B.id:void 0;if(Z){const O=typeof oe.time=="object"&&oe.time!==null?oe.time:typeof B.time=="object"&&B.time!==null?B.time:null,re=O&&typeof O.compacting=="number"?O.compacting:null;n(Z,re)}break}case"session.abort":{const oe=typeof B.sessionID=="string"&&B.sessionID.length>0?B.sessionID:null,Z=typeof B.messageID=="string"&&B.messageID.length>0?B.messageID:null;oe&&Z&&s(oe,Z);break}case"permission.updated":a===B.sessionID&&o(B);break}},[a,r,s,t,o,u,W,ae,n,i,k,b,je]),$e=l.useCallback(()=>{const ne=A();return D.current=ne,ne==="visible"&&I.current},[A]),he=l.useCallback(()=>{Vt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:Y.current,hasUnsubscribe:!!w.current,currentSessionId:a,effectiveDirectory:g,onlineStatus:I.current,visibilityState:D.current,lastEventTimestamp:V.current,reconnectAttempts:y.current})},[a,g]),ie=l.useCallback(async()=>!0,[]),Ne=l.useCallback(()=>{if(N.current){Vt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(N.current=!0,j.current&&(clearTimeout(j.current),j.current=null),w.current){const ne=w.current;w.current=null;try{ne()}catch(B){console.warn("[useEventStream] Error during unsubscribe:",B)}}N.current=!1},[]),Q=l.useCallback(async ne=>{if(he(),!$e()){z.current=!0,I.current?v("paused","Paused while hidden"):v("offline","Waiting for network");return}Y.current&&(await ie()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),ne?.resetAttempts&&(y.current=0),Ne(),V.current=Date.now(),v("connecting",null),Vt()&&console.info("[useEventStream] Starting event stream...");const B=oe=>{console.warn("Event stream error:",oe)},we=()=>{const oe=z.current;y.current=0,z.current=!1,V.current=Date.now(),v("connected",null),u(),oe&&a&&setTimeout(()=>{m(a).then(()=>W(a)).catch(Z=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Z)})},0)};if(Vt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:g,isCleaningUp:N.current}),N.current){Vt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const oe=Ae.subscribeToEvents(Me,B,we,g),Z=()=>{try{oe()}catch(O){console.warn("[useEventStream] Error during unsubscribe:",O)}};N.current?Z():w.current=Z}catch(oe){console.error("[useEventStream] Error during subscription:",oe),B(oe)}},[$e,Ne,v,u,a,m,W,ae,s,Me,g,je,ie,he]),We=l.useCallback(ne=>{if(!$e()){z.current=!0,Ne(),I.current?v("paused","Paused while hidden"):v("offline","Waiting for network");return}const B=y.current+1;y.current=B;const we=ne??`Retrying (${B})`;v("reconnecting",we);const oe=B<=3?Math.min(1e3*Math.pow(2,B-1),8e3):Math.min(2e3*Math.pow(2,B-3),32e3),Z=Math.floor(Math.random()*250),O=oe+Z;j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{Q({resetAttempts:!1})},O)},[$e,Ne,v,Q]);l.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=k);let ne=null;Y.current&&typeof window<"u"&&(ne=le=>{const Se=typeof le.detail?.sessionId=="string"?le.detail.sessionId:null,xe=typeof le.detail?.phase=="string"?le.detail.phase:null;Se&&(xe==="idle"||xe==="busy"||xe==="cooldown")&&(je(Se,xe),ae())},window.addEventListener("openchamber:session-activity",ne));const B=()=>{E.current&&(clearTimeout(E.current),E.current=null)},we=()=>{E.current||(E.current=setTimeout(()=>{const le=A();D.current=le,le!=="visible"?(Ne(),z.current=!0,v("paused","Paused while hidden")):B()},5e3))},oe=()=>{D.current=A(),D.current==="visible"?(B(),(z.current||!w.current)&&(console.info("[useEventStream] Visibility restored, triggering soft refresh..."),Y.current||_.current.clear(),a&&(m(a).catch(()=>{}),W(a)),f(),v("connecting","Resuming stream"),Q({resetAttempts:!0}))):(v("paused","Paused while hidden"),we())},Z=()=>{D.current=A(),D.current==="visible"&&(B(),(z.current||!w.current)&&(console.info("[useEventStream] Window focused after pause, triggering soft refresh..."),Y.current||_.current.clear(),a&&(W(a),m(a).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(le=>console.warn("[useEventStream] Failed to refresh messages:",le))),f(),v("connecting","Resuming stream"),Q({resetAttempts:!0})))},O=()=>{I.current=!0,(z.current||!w.current)&&(v("connecting","Network restored"),Q({resetAttempts:!0}))},re=()=>{I.current=!1,z.current=!0,v("offline","Waiting for network"),Ne()};typeof document<"u"&&document.addEventListener("visibilitychange",oe),typeof window<"u"&&(window.addEventListener("online",O),window.addEventListener("offline",re),window.addEventListener("focus",Z));const ee=setTimeout(()=>{Q({resetAttempts:!0})},100);return $.current&&clearInterval($.current),$.current=setInterval(()=>{if(!$e())return;Date.now()-V.current>25e3&&Promise.resolve().then(async()=>{try{await Ae.checkHealth()?V.current=Date.now():We("Refreshing stalled stream")}catch(Se){console.warn("Health check after stale stream failed:",Se),We("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(ee),ne&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",ne),typeof document<"u"&&document.removeEventListener("visibilitychange",oe),typeof window<"u"&&(window.removeEventListener("online",O),window.removeEventListener("offline",re),window.removeEventListener("focus",Z)),B(),$.current&&(clearInterval($.current),$.current=null);const le=L.current,Se=_.current;le.forEach(xe=>clearTimeout(xe)),le.clear(),Se.clear(),So.clear(),z.current=!1,D.current=A(),I.current=typeof navigator>"u"?!0:navigator.onLine,Ne(),M.current&&(clearTimeout(M.current),M.current=null),v("idle",null)}},[a,g,k,A,Ne,v,Q,We,m,W,je,$e])},xy=()=>{const{createSession:r,abortCurrentOperation:s,initializeNewOpenChamberSession:t,armAbortPrompt:n,clearAbortPrompt:o,currentSessionId:a}=ye(),{toggleCommandPalette:i,toggleHelpDialog:c,toggleSidebar:d,setSessionSwitcherOpen:m,setSessionCreateDialogOpen:f,setActiveMainTab:u,setSettingsDialogOpen:p}=Re(),{agents:h}=xt(),{themeMode:g,setThemeMode:x}=ir(),{working:S}=Kl(),v=l.useRef(null),k=l.useRef(null),b=l.useRef(!1),w=l.useCallback(()=>{k.current&&(clearTimeout(k.current),k.current=null),v.current=null,o()},[o]);l.useEffect(()=>{const j=y=>{if(y.ctrlKey&&y.key==="x"&&(y.preventDefault(),i()),y.ctrlKey&&y.shiftKey&&y.key.toLowerCase()==="l"){const M=Zi()?.diagnostics;if(!M||(y.preventDefault(),b.current))return;b.current=!0,M.downloadLogs().then(({fileName:N,content:A})=>{const D=new Blob([A],{type:"text/plain;charset=utf-8"}),I=URL.createObjectURL(D),z=document.createElement("a");z.href=I,z.download=N||"desktop.log",document.body.appendChild(z),z.click(),document.body.removeChild(z),URL.revokeObjectURL(I)}).finally(()=>{b.current=!1});return}if(y.ctrlKey&&y.key==="h"&&(y.preventDefault(),c()),y.ctrlKey&&!y.metaKey&&y.key.toLowerCase()==="n"){if(y.preventDefault(),y.shiftKey){f(!0);return}r().then(C=>{C&&t(C.id,h)})}if((y.metaKey||y.ctrlKey)&&y.key==="/"){y.preventDefault();const C=["light","dark","system"],N=(C.indexOf(g)+1)%C.length;x(C[N])}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="g"){y.preventDefault();const{activeMainTab:C}=Re.getState();u(C==="git"?"chat":"git");return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="t"){y.preventDefault();const{activeMainTab:C}=Re.getState();u(C==="terminal"?"chat":"terminal");return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key===","){y.preventDefault();const{isSettingsDialogOpen:C}=Re.getState();p(!C);return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="l"){y.preventDefault();const{isMobile:C,isSessionSwitcherOpen:M}=Re.getState();C?m(!M):d();return}if(y.ctrlKey&&!y.metaKey&&!y.shiftKey&&y.key.toLowerCase()==="i"){y.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(y.key==="Escape"){const C=a;if(!(S.canAbort&&!!C)){w();return}const N=Date.now(),A=v.current;if(A&&N<A){y.preventDefault(),w(),s();return}y.preventDefault();const D=n(3e3)??N+3e3;v.current=D,k.current&&clearTimeout(k.current);const I=Math.max(D-N,0);k.current=setTimeout(()=>{v.current&&Date.now()>=v.current&&w()},I||0);return}};return window.addEventListener("keydown",j),()=>{window.removeEventListener("keydown",j)}},[r,s,i,c,d,m,f,u,p,x,g,t,h,S,n,w,a]),l.useEffect(()=>()=>{w()},[w])},by=r=>r.role==="assistant",Di=r=>{const s=r.info;if(!by(s))return;const t=s.time?.completed;return typeof t=="number"?t:void 0},nn=r=>{if(!r)return!1;if(r.role==="user")return!0;const s=r;return s.clientRole==="user"?!0:!!s.userMessageMarker},Ei=r=>(Array.isArray(r?.parts)?r.parts:[]).map(n=>wr(n)).join(" ").replace(/\s+/g," ").trim(),wy=(r,s)=>{if(!r||!nn(r.info))return-1;const t=Ei(r),n=typeof r.info?.time?.created=="number"?r.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return s.forEach((i,c)=>{if(!nn(i.info))return;const d=Ei(i),m=!!(t&&d&&d===t),f=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,u=typeof n=="number"&&typeof f=="number"?Math.abs(f-n):null;if(m){const p=typeof u=="number"?u:0;p<a&&(o=c,a=p);return}!t&&!d&&typeof u=="number"&&u<1500&&u<a&&(o=c,a=u)}),o!==-1?o:typeof n=="number"?s.findIndex(i=>{if(!nn(i.info))return!1;const c=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},vy=()=>{const{currentSessionId:r,messages:s,streamingMessageIds:t}=ye(),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)||[],m=await Ae.getSessionMessages(r),f=await hy(r);if(!m)return;const u=d[d.length-1];if(u){const p=m.findIndex(x=>x.info.id===u.info.id),g=p===-1?wy(u,m):p;if(g!==-1)if(g<m.length-1){const x=m.slice(g+1);console.log(`[SYNC] Found ${x.length} new messages to append`);const S=[...d,...x],{syncMessages:v}=ye.getState();v(r,S)}else{const x=m[g],S=d[d.length-1],v=Di(x),k=Di(S);if(v&&!k){console.log("[SYNC] Last message completed on server");const b=[...d.slice(0,-1),x],{syncMessages:w}=ye.getState();w(r,b)}}else if(nn(u.info)){const x=m.slice(-Dt.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:S}=ye.getState();S(r,x)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(f){const p=m.findIndex(h=>h.info.id===f.messageId);if(p!==-1){if(p<m.length-1){const g=m.slice(p+1).slice(-Dt.VIEWPORT_MESSAGES);if(g.length>0){console.log(`[SYNC] Restoring ${g.length} messages after cursor`);const{syncMessages:x}=ye.getState();x(r,g)}}}else if(m.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=m.slice(-Dt.VIEWPORT_MESSAGES),{syncMessages:g}=ye.getState();g(r,h)}}else if(m.length>0){const p=m.slice(-Dt.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:h}=ye.getState();h(r,p)}}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])},Sy=()=>{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&&ye.setState({sessionActivityPhase:n})}catch{}})(),()=>{r=!0}},[])};function jy(){const{git:r}=Gs(),s=yt(i=>i.currentDirectory),{setActiveDirectory:t,startPolling:n,stopPolling:o,fetchAll:a}=jt();l.useEffect(()=>{if(!s||!r){o();return}return t(s),a(s,r),n(r),()=>{o()}},[s,r,t,n,o,a])}function ky({children:r}){return jy(),e.jsx(e.Fragment,{children:r})}const Ny=()=>{const[{isUpdating:r,message:s},t]=l.useState(()=>ym());return l.useEffect(()=>gm(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(rr,{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 Ti({apis:r,children:s}){return e.jsx(zo.Provider,{value:r,children:s})}const Cy="curl -fsSL https://opencode.ai/install | bash",My=3e3;function Ay({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(ks,{className:"h-4 w-4"})})]})}const Dy=3e4;function Ey({onCliAvailable:r}){const[s,t]=l.useState(!1),[n,o]=l.useState(!1),[a,i]=l.useState(!1);l.useEffect(()=>{const f=setTimeout(()=>o(!0),Dy);return()=>clearTimeout(f)},[]),l.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const c=l.useCallback(async f=>{if(!f.target.closest("button, a, input, select, textarea, code")&&f.button===0&&a)try{const{getCurrentWindow:u}=await jr(async()=>{const{getCurrentWindow:h}=await import("./vendor-.pnpm-BKK22KLz.js").then(g=>g.bS);return{getCurrentWindow:h}},__vite__mapDeps([0,1]));await u().startDragging()}catch(u){console.error("Failed to start window dragging:",u)}},[a]),d=l.useCallback(async()=>{try{const f=await fetch("/health");return f.ok?(await f.json()).cliAvailable===!0:!1}catch{return!1}},[]),m=l.useCallback(async()=>{try{await navigator.clipboard.writeText(Cy),t(!0),setTimeout(()=>t(!1),2e3)}catch(f){console.error("Failed to copy:",f)}},[]);return l.useEffect(()=>{const f=async()=>{await d()&&r?.()},u=setInterval(f,My);return f(),()=>clearInterval(u)},[d,r]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(no,{className:"h-4 w-4"})]})," ","is required to continue."]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"bg-background/60 backdrop-blur-sm border border-border rounded-lg px-5 py-3 font-mono text-sm w-fit",children:s?e.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[e.jsx(Nt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(Ay,{onCopy:m})})}),e.jsxs("a",{href:"https://opencode.ai/docs",target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1 justify-center",children:["View documentation",e.jsx(no,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."})]}),n&&e.jsxs("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["Already installed? Make sure ",e.jsx("code",{className:"text-foreground/70",children:"opencode"})," is in your PATH"]}),e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["or set ",e.jsx("code",{className:"text-foreground/70",children:"OPENCODE_BINARY"})," environment variable."]})]})]})}function Ty({apis:r}){const{initializeApp:s,loadProviders:t,isInitialized:n}=xt(),{error:o,clearError:a,loadSessions:i}=ye(),c=yt(w=>w.currentDirectory),d=yt(w=>w.isSwitchingDirectory),[m,f]=l.useState(!1),{uiFont:u,monoFont:p}=dc(),[h,g]=l.useState(()=>r.runtime.isDesktop),[x,S]=l.useState(()=>r.runtime.isVSCode),[v,k]=l.useState(()=>r.runtime.isDesktop?Cu():!0);l.useEffect(()=>{g(r.runtime.isDesktop),S(r.runtime.isVSCode)},[r.runtime.isDesktop,r.runtime.isVSCode]),l.useEffect(()=>(pa(r),()=>pa(null)),[r]),l.useEffect(()=>{if(typeof document>"u")return;const w=document.documentElement,j=Si[u]?.stack??Si[ey].stack,y=zs[p]?.stack??zs[rn].stack;w.style.setProperty("--font-sans",j),w.style.setProperty("--font-heading",j),w.style.setProperty("--font-family-sans",j),w.style.setProperty("--font-mono",y),w.style.setProperty("--font-family-mono",y),w.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=j)},[u,p]),l.useEffect(()=>{if(n){const j=setTimeout(()=>{const y=document.getElementById("initial-loading");y&&(y.classList.add("fade-out"),setTimeout(()=>{y.remove()},300))},150);return()=>clearTimeout(j)}},[n]),l.useEffect(()=>{const w=setTimeout(()=>{const j=document.getElementById("initial-loading");j&&!n&&(j.classList.add("fade-out"),setTimeout(()=>{j.remove()},300))},5e3);return()=>clearTimeout(w)},[n]),l.useEffect(()=>{(async()=>{await s(),await t()})()},[s,t]),l.useEffect(()=>{if(d)return;(async()=>{Ae.setDirectory(c),await i()})()},[c,d,i]),yy(),xy(),vy(),Sy(),l.useEffect(()=>{const w=j=>{(j.metaKey||j.ctrlKey)&&j.shiftKey&&j.key==="M"&&(j.preventDefault(),f(y=>!y))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]),l.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const b=l.useCallback(()=>{k(!0),window.location.reload()},[]);return h&&!v?e.jsx(Xt,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(Ey,{onCliAvailable:b})})}):x?e.jsx(Xt,{children:e.jsx(Ti,{apis:r,children:e.jsx(bi,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(ly,{}),e.jsx(Ni,{})]})})})}):e.jsx(Xt,{children:e.jsx(Ti,{apis:r,children:e.jsx(ky,{children:e.jsx(bi,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(iy,{}),e.jsx(Ni,{}),e.jsx(Ny,{}),m&&e.jsx(dy,{onClose:()=>f(!1)})]})})})})})}const gc=({className:r="",width:s=70,height:t=70})=>e.jsxs("svg",{width:s,height:t,viewBox:"0 0 70 70",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:r,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M0 13H35V58H0V13ZM26.25 22.1957H8.75V48.701H26.25V22.1957Z",fill:"currentColor"}),e.jsx("path",{d:"M43.75 13H70V22.1957H52.5V48.701H70V57.8967H43.75V13Z",fill:"currentColor"})]}),yc=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=yt.getState();r&&t.homeDirectory!==r&&t.synchronizeHomeDirectory(r),s&&t.setDirectory(s,{showOverlay:!1})},xc="/auth/session",Iy=async()=>fetch(xc,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Fy=async r=>fetch(xc,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:r})}),ea=({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})]}),Py=({message:r="Preparing workspace…"})=>e.jsx(ea,{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})})}),Ry=({onRetry:r})=>e.jsx(ea,{children:e.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-destructive/30 bg-card/90 p-6 shadow-none backdrop-blur",children:e.jsxs("div",{className:"space-y-3 text-center",children:[e.jsx("div",{className:"flex justify-center",children:e.jsx(gc,{width:28,height:28,className:"text-destructive"})}),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",children:"We couldn't verify the UI session. Check that the service is running and try again."}),e.jsx(De,{type:"button",onClick:r,className:"w-full",children:"Retry"})]})})}),Ly=({children:r})=>{const s=l.useMemo(()=>Ht(),[]),t=l.useMemo(()=>rs(),[]),n=s||t,[o,a]=l.useState(()=>n?"authenticated":"pending"),[i,c]=l.useState(""),[d,m]=l.useState(!1),[f,u]=l.useState(""),p=l.useRef(null),h=l.useRef(n),g=l.useCallback(async()=>{if(n){a("authenticated");return}a(S=>S==="authenticated"?S:"pending");try{const S=await Iy();if(S.ok){a("authenticated"),u("");return}if(S.status===401){a("locked");return}a("error")}catch(S){console.warn("Failed to check session status:",S),a("error")}},[n]);l.useEffect(()=>{n||g()},[g,n]),l.useEffect(()=>{!n&&o==="locked"&&(h.current=!1)},[n,o]),l.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),l.useEffect(()=>{n||o==="authenticated"&&!h.current&&(h.current=!0,(async()=>(await tl(),await sl(),await yc()))())},[n,o]);const x=async S=>{if(S.preventDefault(),!(!i||d)){m(!0),u("");try{const v=await Fy(i);if(v.ok){c(""),a("authenticated");return}if(v.status===401){u("Incorrect password. Try again."),a("locked");return}u("Unexpected response from server."),a("error")}catch(v){console.warn("Failed to submit UI password:",v),u("Network error. Check connection and retry."),a("error")}finally{m(!1)}}};return o==="pending"?e.jsx(Py,{}):o==="error"?e.jsx(Ry,{onRetry:()=>void g()}):o==="locked"?e.jsx(ea,{children:e.jsxs("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/95 p-8 shadow-none backdrop-blur",children:[e.jsxs("div",{className:"flex flex-col items-center gap-3 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/15 text-primary",children:e.jsx(gc,{width:24,height:24,className:"opacity-80"})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-foreground",children:"Unlock OpenChamber"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter the password configured for this web session."})]})]}),e.jsxs("form",{onSubmit:x,className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{htmlFor:"openchamber-ui-password",className:"typography-ui-label text-left font-medium text-foreground",children:"Password"}),e.jsx(kt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:S=>{c(S.target.value),f&&u("")},"aria-invalid":!!f||void 0,"aria-describedby":f?"oc-ui-auth-error":void 0,disabled:d}),f&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:f})]}),e.jsx(De,{type:"submit",className:"w-full",disabled:!i||d,children:d?"Unlocking…":"Unlock"})]})]})}):e.jsx(e.Fragment,{children:r})},to=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 _y{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(`
55
+ `)}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=to(s.colors.surface.muted),o=to(s.colors.surface.subtle),a=to(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 m=s.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(m,c)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(m,d)} !important;`)}return s.colors.charts?.series&&Array.isArray(s.colors.charts.series)&&s.colors.charts.series.forEach((m,f)=>{t.push(` --chart-${f+1}: ${m};`)}),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 {
56
+ ${t}
57
+ }
58
+
59
+ .dark {
60
+ ${t}
61
+ }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
62
+ ${t}
63
+ }
64
+
65
+ :root:not(.dark) {
66
+ ${t}
67
+ }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",s.metadata.variant)}generatePrimaryColors(s){const t=[];return t.push(` --primary-base: ${s.base};`),t.push(` --primary-hover: ${s.hover||this.darken(s.base,10)};`),t.push(` --primary-active: ${s.active||this.darken(s.base,20)};`),t.push(` --primary-foreground: ${s.foreground||"#ffffff"};`),t.push(` --primary-muted: ${s.muted||this.opacity(s.base,.5)};`),t.push(` --primary-emphasis: ${s.emphasis||this.lighten(s.base,10)};`),t}generateSurfaceColors(s){const t=[];return t.push(` --surface-background: ${s.background};`),t.push(` --surface-foreground: ${s.foreground};`),t.push(` --surface-muted: ${s.muted};`),t.push(` --surface-muted-foreground: ${s.mutedForeground};`),t.push(` --surface-elevated: ${s.elevated};`),t.push(` --surface-elevated-foreground: ${s.elevatedForeground};`),t.push(` --surface-overlay: ${s.overlay};`),t.push(` --surface-subtle: ${s.subtle};`),t}generateInteractiveColors(s){const t=[];return t.push(` --interactive-border: ${s.border};`),t.push(` --interactive-border-hover: ${s.borderHover};`),t.push(` --interactive-border-focus: ${s.borderFocus};`),t.push(` --interactive-selection: ${s.selection};`),t.push(` --interactive-selection-foreground: ${s.selectionForeground};`),t.push(` --interactive-focus: ${s.focus};`),t.push(` --interactive-focus-ring: ${s.focusRing};`),t.push(` --interactive-cursor: ${s.cursor};`),t.push(` --interactive-hover: ${s.hover};`),t.push(` --interactive-active: ${s.active};`),t}generateStatusColors(s){const t=[];return t.push(` --status-error: ${s.error};`),t.push(` --status-error-foreground: ${s.errorForeground};`),t.push(` --status-error-background: ${s.errorBackground};`),t.push(` --status-error-border: ${s.errorBorder};`),t.push(` --status-warning: ${s.warning};`),t.push(` --status-warning-foreground: ${s.warningForeground};`),t.push(` --status-warning-background: ${s.warningBackground};`),t.push(` --status-warning-border: ${s.warningBorder};`),t.push(` --status-success: ${s.success};`),t.push(` --status-success-foreground: ${s.successForeground};`),t.push(` --status-success-background: ${s.successBackground};`),t.push(` --status-success-border: ${s.successBorder};`),t.push(` --status-info: ${s.info};`),t.push(` --status-info-foreground: ${s.infoForeground};`),t.push(` --status-info-background: ${s.infoBackground};`),t.push(` --status-info-border: ${s.infoBorder};`),t}generateSyntaxColors(s){const t=[];t.push(` --syntax-background: ${s.base.background};`),t.push(` --syntax-foreground: ${s.base.foreground};`),t.push(` --syntax-comment: ${s.base.comment};`),t.push(` --syntax-keyword: ${s.base.keyword};`),t.push(` --syntax-string: ${s.base.string};`),t.push(` --syntax-number: ${s.base.number};`),t.push(` --syntax-function: ${s.base.function};`),t.push(` --syntax-variable: ${s.base.variable};`),t.push(` --syntax-type: ${s.base.type};`),t.push(` --syntax-operator: ${s.base.operator};`);const n=this.generateSyntaxTokens(s);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(s){const t=s.base,n=s.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(s,t){const n=[];return s.markdown?n.push(...this.generateMarkdownColors(s.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),s.chat?n.push(...this.generateChatColors(s.chat,t)):n.push(...this.generateDefaultChatColors(t)),s.tools?n.push(...this.generateToolColors(s.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(s,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${s.heading1||o};`),n.push(` --markdown-heading2: ${s.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${s.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${s.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${s.link||o};`),n.push(` --markdown-link-hover: ${s.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${s.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${s.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${s.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${s.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${s.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${s.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${s.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${s.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${s.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(s){const t=[],n=s.colors.primary.base,o=s.colors.chat?.background||s.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${s.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${s.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${s.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${s.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${s.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${s.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(s.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${s.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${s.colors.interactive.border};`),t}generateChatColors(s,t){const n=[],o=s.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${s.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${s.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${s.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${s.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${s.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${s.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${s.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(s){const t=[];return t.push(` --chat-background: ${s.colors.surface.background};`),t.push(` --chat-user-message: ${s.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${s.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${s.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${s.colors.surface.muted};`),t.push(` --chat-timestamp: ${s.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${s.colors.interactive.border};`),t.push(` --chat-typing: ${s.colors.surface.mutedForeground};`),t}generateToolColors(s,t){const n=[];return n.push(` --tools-background: ${s?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${s?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${s?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${s?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${s?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${s?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),s?.edit?(n.push(` --tools-edit-added: ${s.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${s.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${s.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${s.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${s.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${s.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${s.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(s){const t=[];return t.push(` --tools-background: ${this.opacity(s.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(s.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(s.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${s.colors.surface.mutedForeground};`),t.push(` --tools-title: ${s.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${s.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${s.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${s.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(s.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(s.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(s){const t=[];return s&&(s.fonts&&(s.fonts.sans&&(t.push(` --font-sans: ${s.fonts.sans};`),t.push(` --font-family-sans: ${s.fonts.sans};`)),s.fonts.mono&&(t.push(` --font-mono: ${s.fonts.mono};`),t.push(` --font-family-mono: ${s.fonts.mono};`)),s.fonts.heading&&t.push(` --font-heading: ${s.fonts.heading};`)),s.radius&&(s.radius.none&&t.push(` --radius-none: ${s.radius.none};`),s.radius.sm&&t.push(` --radius-sm: ${s.radius.sm};`),s.radius.md&&t.push(` --radius-md: ${s.radius.md};`),s.radius.lg&&t.push(` --radius-lg: ${s.radius.lg};`),s.radius.xl&&t.push(` --radius-xl: ${s.radius.xl};`),s.radius.full&&t.push(` --radius-full: ${s.radius.full};`)),s.transitions&&(s.transitions.fast&&t.push(` --transition-fast: ${s.transitions.fast};`),s.transitions.normal&&t.push(` --transition-normal: ${s.transitions.normal};`),s.transitions.slow&&t.push(` --transition-slow: ${s.transitions.slow};`))),t}generateTypographyVariables(){const s=[],t=rs()?Th:sc;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 ta={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"}}},sa={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"}}},Tr=[ta,sa];function wn(r){return Tr.find(s=>s.metadata.id===r)}const bc=ta.metadata.id,wc=sa.metadata.id,By=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,vc=r=>r==="dark"?sa:ta,Oy=r=>(Tr.find(t=>t.metadata.variant===r)??vc(r)).metadata.id,Yr=(r,s)=>{const t=wn(r);return t&&t.metadata.variant===s?t:Tr.find(o=>o.metadata.variant===s)??vc(s)},$y=typeof window<"u"?l.useLayoutEffect:l.useEffect,vn=(r,s)=>{if(!r)return s==="light"?bc:wc;const t=wn(r);return t&&t.metadata.variant===s?t.metadata.id:Oy(s)},zy=r=>{let s=bc,t=wc,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"),m=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 u=wn(d);u&&(n=u.metadata.variant==="dark"?"dark":"light",u.metadata.variant==="dark"?t=u.metadata.id:s=u.metadata.id)}}else(m==="light"||m==="dark")&&(n=m);s=vn(a,"light"),t=vn(i,"dark")}if(r){const o=wn(r);o&&(o.metadata.variant==="light"?s=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:s,darkThemeId:t}};function Hy({children:r,defaultThemeId:s}){const t=fe.useMemo(()=>new _y,[]),[n,o]=fe.useState(()=>zy(s)),[a,i]=fe.useState(()=>By()),[c,d]=fe.useState(()=>typeof window>"u"||!rs()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),m=fe.useMemo(()=>rs(),[]),f=fe.useMemo(()=>m&&c?c:n.themeMode==="light"?Yr(n.lightThemeId,"light"):n.themeMode==="dark"||a?Yr(n.darkThemeId,"dark"):Yr(n.lightThemeId,"light"),[m,n,a,c]),u=fe.useMemo(()=>m&&c?[c,...Tr]:Tr,[m,c]);fe.useEffect(()=>{if(!m)return;const w=C=>{d(C);const M=C.metadata.variant==="dark"?"dark":"light",N=Re.getState();N.theme!==M&&N.setTheme(M)},j=C=>{const M=C.detail;M?.theme&&w(M.theme)},y=window.__OPENCHAMBER_VSCODE_THEME__;return y&&w(y),window.addEventListener("openchamber:vscode-theme",j),()=>window.removeEventListener("openchamber:vscode-theme",j)},[m]);const p=fe.useCallback(w=>{if(typeof document>"u")return;const j=w.colors.surface.background;Ht()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=j;let y=document.querySelector('meta[name="theme-color"]');y||(y=document.createElement("meta"),y.setAttribute("name","theme-color"),document.head.appendChild(y)),y.setAttribute("content",j);const C=w.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let M=document.querySelector(`meta[name="theme-color"][media="${C}"]`);M||(M=document.createElement("meta"),M.setAttribute("name","theme-color"),M.setAttribute("media",C),document.head.appendChild(M)),M.setAttribute("content",j)},[]),h=fe.useCallback(w=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",w)},[]);$y(()=>{if(typeof window>"u")return;t.apply(f),h(m),p(f);const w=document.documentElement;w.classList.remove("light","dark"),w.classList.add(f.metadata.variant)},[h,t,f,m,p]),fe.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const w=window.matchMedia("(prefers-color-scheme: dark)"),j=y=>{i(y.matches)};return i(w.matches),w.addEventListener("change",j),()=>w.removeEventListener("change",j)},[n.themeMode]),fe.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",f.metadata.id),localStorage.setItem("selectedThemeVariant",f.metadata.variant==="light"?"light":"dark"))},[n,f]),fe.useEffect(()=>{fs({themeId:f.metadata.id,themeVariant:f.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[f.metadata.id,f.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),fe.useEffect(()=>{if(typeof window>"u")return;const w=j=>{const y=j.detail;y&&o(C=>{let M=C.themeMode;y.useSystemTheme===!0?M="system":y.useSystemTheme===!1&&(y.themeVariant==="dark"||y.themeVariant==="light")&&(M=y.themeVariant);let N=C.lightThemeId;typeof y.lightThemeId=="string"&&y.lightThemeId.length>0&&(N=vn(y.lightThemeId,"light"));let A=C.darkThemeId;return typeof y.darkThemeId=="string"&&y.darkThemeId.length>0&&(A=vn(y.darkThemeId,"dark")),M===C.themeMode&&N===C.lightThemeId&&A===C.darkThemeId?C:{themeMode:M,lightThemeId:N,darkThemeId:A}})};return window.addEventListener("openchamber:settings-synced",w),()=>window.removeEventListener("openchamber:settings-synced",w)},[]);const g=fe.useCallback(w=>{const j=u.find(y=>y.metadata.id===w);j&&o(y=>j.metadata.variant==="dark"?y.darkThemeId===j.metadata.id&&y.themeMode==="dark"?y:{...y,darkThemeId:j.metadata.id,themeMode:"dark"}:y.lightThemeId===j.metadata.id&&y.themeMode==="light"?y:{...y,lightThemeId:j.metadata.id,themeMode:"light"})},[u]),x=fe.useCallback(w=>{o(j=>j.themeMode===w?j:{...j,themeMode:w})},[]),S=fe.useCallback(w=>{if(w){o(y=>y.themeMode==="system"?y:{...y,themeMode:"system"});return}const j=f.metadata.variant==="dark"?"dark":"light";o(y=>y.themeMode===j?y:{...y,themeMode:j})},[f.metadata.variant]),v=fe.useCallback(w=>{const j=u.find(y=>y.metadata.id===w&&y.metadata.variant==="light");j&&o(y=>y.lightThemeId===j.metadata.id?y:{...y,lightThemeId:j.metadata.id})},[u]),k=fe.useCallback(w=>{const j=u.find(y=>y.metadata.id===w&&y.metadata.variant==="dark");j&&o(y=>y.darkThemeId===j.metadata.id?y:{...y,darkThemeId:j.metadata.id})},[u]),b={currentTheme:f,availableThemes:u,setTheme:g,isSystemPreference:n.themeMode==="system",setSystemPreference:S,themeMode:n.themeMode,setThemeMode:x,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:v,setDarkThemePreference:k};return e.jsx(Wo.Provider,{value:b,children:r})}const Wy=({children:r})=>{const{theme:s,applyTheme:t}=Re();return l.useEffect(()=>{t()},[s,t]),l.useEffect(()=>{const n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>{s==="system"&&t()};return n.addEventListener("change",o),()=>{n.removeEventListener("change",o)}},[s,t]),e.jsx(e.Fragment,{children:r})},Uy={getLastAssistantMessage(){const r=ye.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(p=>{const h={id:p.id,type:p.type};return p.type==="text"?(h.text=p.text,h.textLength=p.text?.length||0):p.type==="tool"?(h.tool=p.tool,h.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(h.isStepMarker=!0),h}),i=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),c=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),m=a.length===0,f=!i&&!c&&(!m||d),u={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:m,isEmptyResponse:f,raw:o};return console.log("[INSPECT] Last Assistant Message:",u),console.log("[SUMMARY] Summary:",{messageId:u.messageId,partsCount:u.partsCount,isEmpty:u.isEmpty,isEmptyResponse:u.isEmptyResponse,hasText:i,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!c}),u.isEmpty&&console.warn("[WARNING] Message has NO parts!"),u.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"))),u}}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=ye.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=ye.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=ye.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:
68
+ `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
69
+ `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
70
+ `),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)
71
+ `),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=ye.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(p=>p.info.role==="assistant"),d={totalMessages:i.length,analyzedMessages:c.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},m=p=>typeof p=="number"&&Number.isFinite(p)?p:null,f=p=>{const h=p.filter(g=>typeof g=="number");return h.length>0?Math.max(...h):null},u=c.map((p,h)=>{const g=p.info??{},x=Array.isArray(p.parts)?p.parts:[],S=g.time??{},v=m(S.completed),k=v!==null,b=x.filter(I=>I.type==="tool"),w=x.filter(I=>I.type==="reasoning"),j=f(b.map(I=>m(I.state?.time?.end??I.state?.time?.start))),y=f(w.map(I=>m(I.time?.end??I.time?.start))),C=f([j,y].filter(I=>I!==null)),M=b.some(I=>["pending","running","started"].includes(I.state?.status)),N=w.some(I=>typeof I.time?.end!="number");b.length>0&&(d.withTools+=1),w.length>0&&(d.withReasoning+=1),k||(d.completedMissing+=1);const A=!!(k&&typeof j=="number"&&v<j);A&&(d.completedBeforeTool+=1);const D=!!(k&&typeof y=="number"&&v<y);return D&&(d.completedBeforeReasoning+=1),k&&M&&(d.runningToolsWhenCompleted+=1),k&&N&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:v,latestToolTimestamp:j,latestReasoningTimestamp:y,latestPartTimestamp:C,completed_missing:!k,completed_before_tool:A,completed_before_reasoning:D,running_tools_when_completed:!!(k&&M),reasoning_open_when_completed:!!(k&&N),has_tools:b.length>0,has_reasoning:w.length>0}});return t&&(console.table(u.slice(0,n)),u.length>n&&console.log(`Displayed first ${n} rows out of ${u.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:u}},checkCompletionStatus(){const r=ye.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const n=(r.messages.get(s)||[]).filter(S=>S.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(S=>S.type==="step-finish"),i=o.parts.some(S=>S.type==="step-finish"&&S.reason==="stop"),d=o.info.time?.completed,m=o.info.status,f=typeof d=="number"&&d>0||m==="completed",u=!!(f&&i),p=r.messageStreamStates,h=o.info.sessionID?r.streamingMessageIds.get(o.info.sessionID)??null:null,g=p.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:",m),console.log("hasCompletedFlag:",f),console.log("hasStopReason:",i),console.log("messageIsComplete:",u),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:m,hasCompletedFlag:f,hasStopReason:i,messageIsComplete:u,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Uy,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 Ii=!1;const Vy=()=>{if(Ii||typeof window>"u")return;Ii=!0;let r={showReasoningTraces:Re.getState().showReasoningTraces},s=null,t=null;const n=()=>{const a=s;s=null,t=null,a&&Object.keys(a).length>0&&fs(a)},o=a=>{s={...s??{},...a},!t&&(t=setTimeout(n,150))};Re.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 Fi=!1;const Pi="openchamber-typography-base",Gy=()=>{if(typeof document>"u")return;const s=`:root {
72
+ ${Object.entries(sc).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
73
+ `)}
74
+ }
75
+ `,t=document.getElementById(Pi);if(t){t.textContent=s;return}const n=document.createElement("style");n.id=Pi,n.textContent=s,document.head.appendChild(n)},qy=()=>{Fi||typeof window>"u"||(Fi=!0,Gy())},Ky=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await tl();await sl();Vy();qy();await yc();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(),m=d?.limit?.context||0,f=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;m>0&&s.getContextUsage(m,f)}});const Sc=document.getElementById("root");if(!Sc)throw new Error("Root element not found");iu.createRoot(Sc).render(e.jsx(fe.StrictMode,{children:e.jsx(Hy,{children:e.jsx(Wy,{children:e.jsx(Ly,{children:e.jsx(Ty,{apis:Ky})})})})}));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 Jy=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ws as D,vs as a,Sf as b,T as c,Ph as d,Rh as e,fi as f,Mn as g,Lh as h,Bh as i,Jy as m,Oh as p,_h as r,sn as t};