@openchamber/web 1.0.3 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{MonacoDiffViewer-BsVn1wGg.js → MonacoDiffViewer-DjQ3gWyc.js} +1 -1
- package/dist/assets/{ToolOutputDialog-BLz2cnk4.js → ToolOutputDialog-uun3dDkb.js} +1 -1
- package/dist/assets/{index-BNR6aFOq.js → index-CMbNRGFL.js} +2 -2
- package/dist/assets/main-DvzQhmuw.js +59 -0
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/main-Di3gaYl_.js +0 -59
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MonacoDiffViewer-BsVn1wGg.js","assets/vendor-.pnpm-B1ce5n1Z.js","assets/vendor--B3aGWKBE.css","assets/index-BNR6aFOq.js","assets/index-D5a0YHM0.css","assets/ToolOutputDialog-BLz2cnk4.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{t as zl,c as Bl,j as e,R as Hl,T as Wl,P as Ul,C as Vl,A as Gl,a as ql,S as si,b as ri,d as Mt,e as Et,p as es,f as ts,g as Kl,I as Yl,h as l,i as Jl,k as Xl,l as Zl,m as Ql,n as ec,o as tc,q as sc,s as ht,r as rc,u as nc,v as oc,w as ac,x as ds,y as ic,z as lc,B as cc,_ as Ws,D as ft,U as At,E as he,K as qn,F as ge,L as dc,Y as vs,Q as Ss,W as Ct,O as gr,V as lo,G as Kn,J as qs,H as ni,M as uc,N as mc,X as fc,Z as Zt,$ as pc,a0 as hc,a1 as gc,a2 as xc,a3 as yc,a4 as Yn,a5 as un,a6 as bc,a7 as Kr,a8 as co,a9 as mn,aa as Ks,ab as wc,ac as Qt,ad as Yr,ae as fn,af as Gt,ag as Ns,ah as oi,ai,aj as xr,ak as vc,al as as,am as zt,an as Fo,ao as uo,ap as ii,aq as mo,ar as fo,as as po,at as pn,au as Lo,av as Fs,aw as li,ax as lr,ay as yr,az as jc,aA as Sc,aB as ci,aC as di,aD as cr,aE as Nc,aF as kc,aG as wn,aH as Cc,aI as Ut,aJ as Mc,aK as Ac,aL as vn,aM as Dc,aN as ho,aO as go,aP as Ec,aQ as Tc,aR as Us,aS as Is,aT as hn,aU as gn,aV as xo,aW as Ic,aX as Pc,aY as Rc,aZ as Fc,a_ as Lc,a$ as _c,b0 as Oc,b1 as Jn,b2 as $r,b3 as yo,b4 as $c,b5 as zc,b6 as Qs,b7 as Bc,b8 as Hc,b9 as Vs,ba as Wc,bb as Uc,bc as Vc,bd as Gc,be as Xn,bf as qc,bg as ns,bh as Kc,bi as Yc,bj as dr,bk as Jc,bl as Xc,bm as Zc,bn as Qc,bo as ed,bp as td,bq as sd,br as rd,bs as nd,bt as od,bu as ad,bv as id,bw as ld,bx as cd,by as dd,bz as ud,bA as _o,bB as md,bC as fd,bD as pd,bE as Oo,bF as hd,bG as gd,bH as xd,bI as yd,bJ as bd}from"./vendor-.pnpm-B1ce5n1Z.js";import{c as wd,l as vd,g as jd,r as Sd,d as Nd,a as kd,b as Cd,u as Md,e as Ad,f as Dd,h as Ed,i as Td,j as Id,k as Pd}from"./index-BNR6aFOq.js";function A(...r){return zl(Bl(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 u=c?`${c}/${d}`:d;if(u.length>i)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},Jr=r=>r?r==="/"?"/":r.replace(/\/+$/,""):"";function Dt(r,s){if(!r)return"";const t=Jr(r);if(t==="/")return"/";const n=s?Jr(s):void 0;if(n&&n!=="/"){if(t===n)return"~";if(t.startsWith(`${n}/`)){const o=t.slice(n.length+1);return o?`~/${o}`:"~"}}return t}function jn(r,s){if(!r)return"/";const t=Jr(r);if(!t||t==="/")return"/";const n=s?Jr(s):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Rd({delayDuration:r=0,...s}){return e.jsx(ql,{"data-slot":"tooltip-provider",delayDuration:r,...s})}function at({delayDuration:r=0,...s}){return e.jsx(Rd,{delayDuration:r,children:e.jsx(Hl,{"data-slot":"tooltip",...s})})}function it({...r}){return e.jsx(Wl,{"data-slot":"tooltip-trigger",...r})}function rt({className:r,sideOffset:s=0,children:t,...n}){return e.jsx(Ul,{children:e.jsxs(Vl,{"data-slot":"tooltip-content",sideOffset:s,className:A("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(Gl,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}const Fd=ri("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 Ne({className:r,variant:s,size:t,asChild:n=!1,...o}){const a=n?si:"button";return e.jsx(a,{"data-slot":"button",className:A(Fd({variant:s,size:t,className:r})),...o})}let Sn=null;const $o=()=>{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}}},Ld=()=>{if(typeof window>"u"||!window.localStorage)return $o();const r=window.localStorage,s=$o();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const f=r.getItem(u);if(f!==null)return f}catch{n()}return s.getItem(u)},setItem:(u,f)=>{if(t)try{r.setItem(u,f),s.removeItem(u);return}catch{n()}s.setItem(u,f)},removeItem:u=>{if(t)try{r.removeItem(u)}catch{n()}s.removeItem(u)},clear:()=>{if(t)try{r.clear()}catch{n()}s.clear()},key:u=>{if(t)try{return r.key(u)}catch{n()}return s.key(u)},get length(){if(t)try{return r.length+s.length}catch{n()}return s.length}}},Ot=()=>(Sn||(Sn=Ld()),Sn),Fe=Mt()(Et(es((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:{},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}}))},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:ts(()=>Ot()),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})}),{name:"ui-store"})),Rt=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",ks=()=>Rt()?window.opencodeDesktop??null:null,mi=()=>{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},fi=async()=>{const r=ks();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},_d=async()=>{const r=ks();if(!r)return null;try{return await r.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},Od=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,pi=async()=>{const r=mi();if(!r)return null;try{return await r.getSettings()}catch(s){return console.warn("Failed to read desktop settings",s),null}},$d=async r=>{const s=mi();if(!s)return null;try{return await s.updateSettings(r)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},zd=async r=>{const s=ks();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)}}},Bd=async r=>{const s=ks();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)}}},Hd=async r=>{const s=ks();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)}}},Wd=async()=>{const r=ks();if(!r||!r.checkForUpdates)return null;try{return await r.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},Ud=async r=>{const s=ks();if(!s||!s.downloadUpdate)return!1;try{return await s.downloadUpdate(r),!0}catch(t){return console.warn("Failed to download update",t),!1}},Vd=async()=>{const r=ks();if(!r||!r.restartToUpdate)return!1;try{return await r.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}},Gd="/api",qd=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Kd=r=>{const s=typeof r=="string"&&r.trim().length>0?r.trim():"/api";if(qd.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}},Yd=()=>{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},jr=r=>r.replace(/\\/g,"/"),Nn=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_RUNTIME_APIS__;return r&&r.runtime?.isDesktop&&r.files?r.files:null};class Jd{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=Gd){const n=Yd()||s;this.baseUrl=Kd(n),this.client=Kl({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.text&&s.text.trim()){const a={type:"text",text:s.text};o.push(a)}if(s.files&&s.files.length>0&&s.files.forEach(a=>{const i={type:"file",mime:a.mime,filename:a.filename,url:a.url};o.push(i)}),s.agentMentions&&s.agentMentions.length>0){const[a]=s.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({path:{id:s.id},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{model:{providerID:s.providerID,modelID:s.modelID},agent:s.agent,parts:o}}),n}async abortSession(s){return!!(await this.client.session.abort({path:{id:s},throwOnError:!0})).data}async getSessionStatus(){try{const s=this.baseUrl.replace(/\/$/,""),t=new URL(`${s}/session/status`);this.currentDirectory&&this.currentDirectory.length>0&&t.searchParams.set("directory",this.currentDirectory);const n=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return{};const o=await n.json().catch(()=>null);return!o||typeof o!="object"?{}:o}catch{return{}}}async respondToPermission(s,t,n){return(await this.client.postSessionIdPermissionsPermissionId({path:{id:s,permissionID:t},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{response:n}})).data||!1}async getConfig(){const s=await this.client.config.get();if(!s.data)throw new Error("Failed to get config");return s.data}async updateConfig(s){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(s){const t=await this.getConfig(),n=s(t);return await this.updateConfig(n)}async getProviders(){const s=await this.client.config.providers({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!s.data)throw new Error("Failed to get providers");return s.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}catch{return[]}}subscribeToEvents(s,t,n,o){this.sseAbortController&&this.sseAbortController.abort();const a=new AbortController;return this.sseAbortController=a,console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const i=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",i);const c=async d=>{try{const u=await this.client.event.subscribe({query:i?{directory:i}:void 0,signal:a.signal,sseMaxRetryAttempts:2,sseDefaultRetryDelay:500,sseMaxRetryDelay:8e3,onSseError: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 m=f.data;m&&typeof m=="object"&&s(m)}}});n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const f of u.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(u){if(u?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",u),t&&t(u);const f=Math.min(500*Math.pow(2,d),8e3);await new Promise(m=>setTimeout(m,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=Nn();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=Nn();if(t)try{const n=await t.listDirectory(s||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:jr(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=Nn(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?jr(o):null;if(n)try{const f=await n.search({directory:o||"",query:s,maxResults:t?.limit});return Array.isArray(f)?f.map(m=>{const p=jr(m.path),h=p.split("/").filter(Boolean).pop()||p,g=m.preview&&m.preview.length>0&&typeof m.preview[0]=="string"?jr(m.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(()=>({})),m=typeof f.error=="string"?f.error:"Failed to search files";throw new Error(m)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const s=await fi();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 Se=new Jd,Zn=new Set;function bo(r){return Zn.add(r),()=>{Zn.delete(r)}}function cs(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 Zn)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 Xr(r,s){return r.scopes.includes("all")||r.scopes.includes(s)}const Xd="https://models.dev/api.json",Zd="/api/openchamber/models-metadata",Qd=r=>r?.toLowerCase?.()??"",eu=r=>r==="primary"||r==="all"||r===void 0||r===null,br=r=>typeof r=="object"&&r!==null,Zr=r=>Array.isArray(r)&&r.every(s=>typeof s=="string"),tu=r=>{if(!br(r))return!1;const s=r;if(s.modalities){const{input:t,output:n}=s.modalities;if(t&&!Zr(t)||n&&!Zr(n))return!1}return!0},su=r=>{if(!br(r))return!1;const s=r;return s.models===void 0||br(s.models)},hi=(r,s)=>{const t=Qd(r);return!t||!s?"":`${t}/${s}`},ru=r=>{const s=new Map;if(!br(r))return s;for(const[t,n]of Object.entries(r)){if(!su(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!br(a)))for(const[i,c]of Object.entries(a)){if(!tu(c))continue;const d=typeof i=="string"&&i.length>0?i:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:Zr(c.modalities.input)?c.modalities.input:void 0,output:Zr(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=hi(o,d);f&&s.set(f,u)}}return s},nu=async()=>{if(typeof fetch!="function")return new Map;const r=[Zd,Xd];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 ru(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},ou=r=>new Promise(s=>setTimeout(s,r)),yt=Mt()(Et(es((r,s)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,loadProviders:async()=>{try{const t=nu(),n=await Se.getProviders(),o=Array.isArray(n?.providers)?n.providers:[],a=n?.default||{},i=o.map(m=>{const p=m.models??{},h=Object.keys(p).map(g=>p[g]);return{...m,models:h}}),c=a.provider||i[0]?.id||"",d=i.find(m=>m.id===c),u=a.model||d?.models?.[0]?.id||"";r({providers:i,defaultProviders:a,currentProviderId:c,currentModelId:u});const 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 Se.listAgents(),i=Array.isArray(a)?a:[];r({agents:i});const{providers:c}=s();if(i.length===0)return r({currentAgentName:void 0}),!0;const d=i.filter(m=>eu(m.mode)),f=d.find(m=>m.name==="build")||d[0]||i[0];if(r({currentAgentName:f.name}),f?.model?.providerID&&f?.model?.modelID){const m=c.find(p=>p.id===f.model.providerID);m&&m.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:u,getAgentModelForSession:f}=i;c&&a.setState(m=>{const p=new Map(m.currentAgentContext);return p.set(c,t),{currentAgentContext:p}}),c&&d(c)&&(f(c,t)||u(c,n))}}if(t&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const{currentSessionId:c,getAgentModelForSession:d}=a.getState();if(c&&d(c,t))return}const i=n.find(c=>c.name===t);if(i?.model?.providerID&&i?.model?.modelID){const c=o.find(d=>d.id===i.model.providerID);c&&c.models.find(u=>u.id===i.model.modelID)&&r({currentProviderId:i.model.providerID,currentModelId:i.model.modelID})}}},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Se.checkHealth();return r({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await ou(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 Se.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=hi(t,n);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)}}),{name:"config-store",storage:ts(()=>Ot()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=yt);let zo=null;zo||(zo=bo(async r=>{const s=[];if(Xr(r,"agents")){const{loadAgents:t}=yt.getState();s.push(t().then(()=>{}))}if(Xr(r,"providers")){const{loadProviders:t}=yt.getState();s.push(t())}s.length>0&&await Promise.all(s)}));const St={MAX_SESSIONS:2,VIEWPORT_MESSAGES:60,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:100,ZOMBIE_TIMEOUT:600*1e3},au=120,Tt=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function wo(r){const s=Tt();return s?s.checkIsGitRepository(r):wd(r)}async function iu(r){const s=Tt();return s?s.getGitStatus(r):jd(r)}async function lu(r,s){const t=Tt();return t?t.deleteGitBranch(r,s):Nd(r,s)}async function cu(r,s){const t=Tt();return t?t.deleteRemoteBranch(r,s):kd(r,s)}async function du(r){const s=Tt();return s?s.listGitWorktrees(r):vd(r)}async function uu(r,s){const t=Tt();return t?t.addGitWorktree(r,s):Pd(r,s)}async function gi(r,s){const t=Tt();return t?t.removeGitWorktree(r,s):Sd(r,s)}async function mu(r){const s=Tt();return s?s.ensureOpenChamberIgnored(r):Td(r)}async function fu(r,s={}){const t=Tt();return t?t.gitPush(r,s):Id(r,s)}async function pu(){const r=Tt();return r?r.getGitIdentities():Ed()}async function hu(r){const s=Tt();return s?s.createGitIdentity(r):Ad(r)}async function gu(r,s){const t=Tt();return t?t.updateGitIdentity(r,s):Md(r,s)}async function xu(r){const s=Tt();return s?s.deleteGitIdentity(r):Cd(r)}async function yu(r){const s=Tt();return s?s.getCurrentGitIdentity(r):Dd(r)}const bu=".openchamber",us=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Bo=(r,s)=>{const t=us(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:"",wu=async r=>{try{await Se.createDirectory(r)}catch(s){if(s instanceof Error&&/exist/i.test(s.message))return;throw s}};async function vu(r,s){const t=us(r),n=Bo(t,bu);return await wu(n),Bo(n,s)}async function ju(r){const{projectDirectory:s,worktreeSlug:t,branch:n,createBranch:o}=r,a=us(s),i=await vu(a,t);return await uu(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 Ho(r){const{projectDirectory:s,path:t,force:n}=r,o=us(s);await gi(o,{path:t,force:n})}async function Su(r){const{projectDirectory:s,path:t,branch:n,force:o,deleteRemote:a,remote:i}=r,c=us(s),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await gi(c,{path:t,force:o}),d&&(await lu(c,{branch:d,force:!0}),a))try{await cu(c,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Qr(r){const s=us(r);return du(s)}async function zr(r){const s=us(r),t=await iu(s);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function en(r,s){const t=us(r),n=us(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 Wo=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},Nu=r=>!r||typeof r!="object"?null:{showReasoningTraces:r.showReasoningTraces},ku=r=>{const s=Fe.getState();typeof r.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(r.showReasoningTraces)},Cu=async()=>{if(typeof window>"u")return null;if(Rt()){const s=window.opencodeAppearance;if(!s||typeof s.load!="function")return null;try{const t=await s.load();return Wo(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=Nu(s);return Wo(t)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let yi=null;const Uo=r=>{yi=r},bi=()=>yi,Br=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"))},wi=()=>{const r=Fe.persist;if(r&&typeof r=="object")return r},vi=()=>bi()?.settings??null,Hr=r=>{const s=Fe.getState();typeof r.showReasoningTraces=="boolean"&&r.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(r.showReasoningTraces)},Vo=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},Mu=async()=>{const r=vi();if(r)try{const s=await r.load();return Vo(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 Vo(t)}catch(s){return console.warn("Failed to load shared settings from server:",s),null}},ji=async()=>{if(typeof window>"u")return;const r=wi(),s=t=>{Br(t);const n=()=>Hr(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=Rt()?await pi():await Mu();t&&s(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},os=async r=>{if(typeof window>"u")return;if(Rt()){try{const t=await $d(r);t&&(Br(t),Hr(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const s=vi();if(s)try{const t=await s.save(r);t&&(Br(t),Hr(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&&(Br(n),Hr(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Si=async()=>{if(typeof window>"u")return;const r=wi();try{const s=await Cu();if(!s)return;const t=()=>ku(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)}},vo="Updating OpenCode configuration...";let Xt=0,js=vo;const Qn=new Set;function tn(){const r={isUpdating:Xt>0,message:js};Qn.forEach(s=>s(r))}function ws(r){Xt+=1,Xt===1?(js=r||vo,tn()):r&&(js=r,tn())}function Ht(){Xt!==0&&(Xt-=1,Xt===0&&(js=vo,tn()))}function Vt(r){js===r&&Xt>0||(js=r,Xt>0&&tn())}function Au(r){return Qn.add(r),r({isUpdating:Xt>0,message:js}),()=>{Qn.delete(r)}}function Du(){return{isUpdating:Xt>0,message:js}}const ur="useAgentsStore",sn=r=>new Promise(s=>setTimeout(s,r)),Eu=2e4,Go=300,qo=4,Tu=800,Iu=200,Pu=2e3,Ys=Mt()(Et(es((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 Se.listAgents();return r({agents:a,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),r({agents:t,isLoading:!1}),!1},createAgent:async t=>{ws("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.tools&&Object.keys(t.tools).length>0&&(o.tools=t.tools),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),console.log("[AgentsStore] Agent config to save:",o);const a=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const u=i?.error||"Failed to create agent";throw new Error(u)}if(console.log("[AgentsStore] Agent created successfully"),i?.requiresReload??!0)return n=!0,await Hs({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadAgents();return d&&cs("agents",{source:ur}),d}catch(o){return console.error("[AgentsStore] Failed to create agent:",o),!1}finally{n||Ht()}},updateAgent:async(t,n)=>{ws("Updating agent configuration…");let o=!1;try{console.log("[AgentsStore] Updating agent:",t),console.log("[AgentsStore] Config received:",n);const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.tools!==void 0&&(a.tools=n.tools),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable),console.log("[AgentsStore] Agent config to update:",a);const i=await fetch(`/api/config/agents/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),c=await i.json().catch(()=>null);if(!i.ok){const 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 Hs({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadAgents();return u&&cs("agents",{source:ur}),u}catch(a){return console.error("[AgentsStore] Failed to update agent:",a),!1}finally{o||Ht()}},deleteAgent:async t=>{ws("Deleting agent configuration…");let n=!1;try{const o=await fetch(`/api/config/agents/${encodeURIComponent(t)}`,{method:"DELETE"}),a=await o.json().catch(()=>null);if(!o.ok){const d=a?.error||"Failed to delete agent";throw new Error(d)}if(console.log("[AgentsStore] Agent deleted successfully"),a?.requiresReload??!0)return n=!0,await Hs({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadAgents();return c&&cs("agents",{source:ur}),s().selectedAgentName===t&&r({selectedAgentName:null}),c}catch(o){return console.error("Failed to delete agent:",o),!1}finally{n||Ht()}},getAgentByName:t=>{const{agents:n}=s();return n.find(o=>o.name===t)}}),{name:"agents-store",storage:ts(()=>Ot()),partialize:r=>({selectedAgentName:r.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Ys);async function Ru(r){const s=typeof r=="number"&&r>0?Math.min(r,Go):0;s>0&&await sn(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Eu;){n+=1,Vt(`Waiting for OpenCode… (attempt ${n})`);try{if(await Se.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=qo&&a<1200?Go:Math.min(Tu+Math.max(0,n-qo)*Iu,Pu);await sn(i)}throw o||new Error("OpenCode did not become ready in time")}async function Hs(r={}){const{message:s,delayMs:t}=r;try{Vt(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 Ru(t),Vt("Refreshing providers and agents…");const n=yt.getState(),o=Ys.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),cs("agents",{source:ur})}catch(n){console.error("[AgentsStore] Failed to refresh configuration after OpenCode restart:",n),Vt("OpenCode reload failed. Please retry refreshing configuration manually."),await sn(1500)}finally{Ht()}}async function Fu(r){await Hs(r)}async function Lu(r){ws("Reloading OpenCode configuration…");try{const s=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await s.json().catch(()=>null);if(!s.ok){const n=t?.error||"Failed to reload configuration";throw new Error(n)}t?.requiresReload?await Hs({message:t.message,delayMs:t.reloadDelayMs}):await Hs(r)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),Vt("Failed to reload configuration. Please try again."),await sn(2e3),Ht(),s}}let Ko=null;Ko||(Ko=bo(r=>{if(r.source!==ur&&Xr(r,"agents")){const{loadAgents:s}=Ys.getState();s()}}));const mr="useCommandsStore",eo=r=>new Promise(s=>setTimeout(s,r)),_u=2e4,Yo=300,Jo=4,Ou=800,$u=200,zu=2e3,Js=Mt()(Et(es((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 Se.listCommandsWithDetails();return r({commands:a,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load commands:",n),r({commands:t,isLoading:!1}),!1},createCommand:async t=>{ws("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),console.log("[CommandsStore] Command config to save:",o);const a=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const u=i?.error||"Failed to create command";throw new Error(u)}if(console.log("[CommandsStore] Command created successfully"),i?.requiresReload??!0)return n=!0,await kn({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadCommands();return d&&cs("commands",{source:mr}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Ht()}},updateCommand:async(t,n)=>{ws("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=await fetch(`/api/config/commands/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),c=await i.json().catch(()=>null);if(!i.ok){const 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 kn({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await s().loadCommands();return u&&cs("commands",{source:mr}),u}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Ht()}},deleteCommand:async t=>{ws("Deleting command configuration…");let n=!1;try{const o=await fetch(`/api/config/commands/${encodeURIComponent(t)}`,{method:"DELETE"}),a=await o.json().catch(()=>null);if(!o.ok){const d=a?.error||"Failed to delete command";throw new Error(d)}if(console.log("[CommandsStore] Command deleted successfully"),a?.requiresReload??!0)return n=!0,await kn({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadCommands();return c&&cs("commands",{source:mr}),s().selectedCommandName===t&&r({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Ht()}},getCommandByName:t=>{const{commands:n}=s();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:ts(()=>Ot()),partialize:r=>({selectedCommandName:r.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Js);async function Bu(r){const s=typeof r=="number"&&r>0?Math.min(r,Yo):0;s>0&&await eo(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<_u;){n+=1,Vt(`Waiting for OpenCode… (attempt ${n})`);try{if(await Se.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=Jo&&a<1200?Yo:Math.min(Ou+Math.max(0,n-Jo)*$u,zu);await eo(i)}throw o||new Error("OpenCode did not become ready in time")}async function kn(r={}){const{message:s,delayMs:t}=r;try{Vt(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 Bu(t),Vt("Refreshing providers and commands…");const n=yt.getState(),o=Js.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),cs("commands",{source:mr})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Vt("OpenCode reload failed. Please retry refreshing configuration manually."),await eo(1500)}finally{Ht()}}let Xo=null;Xo||(Xo=bo(r=>{if(r.source!==mr&&Xr(r,"commands")){const{loadCommands:s}=Js.getState();s()}}));const Hu=3e4,Wu=40,Uu=60,Vu=(r,s,t)=>{const n=r.trim(),o=s.trim().toLowerCase();return`${n}::${o}::${t}`},jo=Mt()(Et((r,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=Uu){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=Vu(a,i,o),d=Date.now(),u=s().cache[c];if(u&&d-u.timestamp<Hu)return u.files;const f=s().inFlight[c];if(f)return f;const m=Se.searchFiles(i,{directory:a,limit:o}).then(p=>(r(h=>{const g={...h.cache,[c]:{files:p,timestamp:Date.now()}},y=h.cacheKeys.filter(b=>b!==c);for(y.push(c);y.length>Wu;){const b=y.shift();b&&delete g[b]}return{cache:g,cacheKeys:y}}),p)).finally(()=>{r(p=>{const h={...p.inFlight};return delete h[c],{inFlight:h}})});return r(p=>({inFlight:{...p.inFlight,[c]:m}})),m},invalidateDirectory(t){if(!t||t.trim().length===0){r({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;r(a=>{const i={...a.cache},c=a.cacheKeys.filter(f=>f.startsWith(o)?(delete i[f],!1):!0),d=Object.entries(a.inFlight).filter(([f])=>!f.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"}));var Gu={};let is=null;const Yt=Ot(),Zo=Yt.getItem("lastDirectory"),qu=typeof Zo=="string"&&Zo.length>0,Sr=(r,s)=>((s?.showOverlay??!0)&&ws("Switching project directory…"),Se.setOpenCodeWorkingDirectory(r).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),Nr=(r,s,t)=>{const{showOverlay:n}=s,o=()=>{try{we.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&&(Vt("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),Ht()),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 Fu({message:"Refreshing OpenCode configuration…"});try{await Js.getState().loadCommands();try{cs("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&&Ht()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(Vt("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),Ht())}finally{t?.(a),o()}})()},kr=r=>{try{jo.getState().invalidateDirectory(r)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},rn=()=>{if(typeof window<"u"){const s=Yt.getItem("lastDirectory");if(s)return s;if(is)return is;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 is=t,Yt.setItem("homeDirectory",t),t;const n=Yt.getItem("homeDirectory");if(n)return is=n,n}const r=typeof process<"u"&&Gu?.HOME;return r||process?.cwd?.()||"/"},Ku=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},Yu=r=>(is=r,typeof window<"u"&&Yt.setItem("homeDirectory",r),os({homeDirectory:r}),r),Ni=async()=>{const r=n=>{const o=Ku(n);return o?Yu(o):null};try{const n=await Se.getFilesystemHome(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Se.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 fi(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const s=rn(),t=r(s);return t||s},Ps=rn();Ps&&Se.setDirectory(Ps);const Ju=!!(Ps&&Ps!=="/"),dt=Mt()(Et((r,s)=>({currentDirectory:Ps,directoryHistory:[Ps],historyIndex:0,homeDirectory:Ps,hasPersistedDirectory:qu,isHomeReady:Ju,isSwitchingDirectory:!1,setDirectory:(t,n)=>{console.log("[DirectoryStore] setDirectory called with path:",t);const o=n?.showOverlay??!0;Se.setDirectory(t),kr();const a=Sr(t,{showOverlay:o});console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),r(i=>{const c=[...i.directoryHistory.slice(0,i.historyIndex+1),t];return Yt.setItem("lastDirectory",t),os({lastDirectory:t}),{currentDirectory:t,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),Nr(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];Se.setDirectory(o),kr();const a=Sr(o);Yt.setItem("lastDirectory",o),os({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Nr(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];Se.setDirectory(o),kr();const a=Sr(o);Yt.setItem("lastDirectory",o),os({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Nr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=s(),o=is||s().homeDirectory||rn();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=is||rn();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=is||s().homeDirectory||await Ni();s().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=s(),o=t;is=o;const a=n.homeDirectory!==o,i=Yt.getItem("lastDirectory"),c=typeof i=="string"&&i.length>0,d=!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||r({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",f={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d&&(f.currentDirectory=o,f.directoryHistory=[o],f.historyIndex=0,f.isSwitchingDirectory=!0),r(()=>f),d&&u){Se.setDirectory(o),kr(),Yt.setItem("lastDirectory",o),os({lastDirectory:o});const m=Sr(o,{showOverlay:!1});Nr(m,{showOverlay:!1},()=>{r(p=>p.currentDirectory!==o?{}:p.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}os({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Ni().then(r=>{dt.getState().synchronizeHomeDirectory(r)});const ki=Ot(),Ci="oc.sessionSelectionByDirectory",Qo=".openchamber",Xu=()=>{try{const r=ki.getItem(Ci);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 Wr=null;const So=()=>(Wr||(Wr=Xu()),Wr),Mi=r=>{Wr=r;try{ki.setItem(Ci,JSON.stringify(r))}catch{}},Ai=r=>{if(!r)return null;const t=So()[r];return typeof t=="string"?t:null},Cs=(r,s)=>{if(!r)return;const t={...So()};s?t[r]=s:delete t[r],Mi(t)},Zu=(r,s)=>{if(!r)return;const t=Ai(r);if(!t)return;if(!new Set(s).has(t)){const o={...So()};delete o[r],Mi(o)}},ea=async(r,s)=>{const t=r.status??await zr(r.path).catch(()=>{});await Su({projectDirectory:r.projectDirectory,path:r.path,branch:r.branch,force:!!t?.isDirty,deleteRemote:!!s?.deleteRemoteBranch,remote:s?.remoteName})},vt=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},_s=(r,s)=>{const t=r.find(n=>n.id===s);return t?vt(t.directory??null):null},Qu=async(r,s,t)=>{const n=vt(s);if(!n||r.length===0)return null;const o=r.map(u=>({id:u.id,directory:vt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Qr(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const f=new Map(t);return o.forEach(({id:m})=>{f.delete(m)&&(u=!0)}),u?f:null}const i=new Map;a.forEach(u=>{const f=en(n,u),m=vt(f.path)??f.path;m!==n&&i.set(m,f)});let c=!1;const d=new Map(t);return o.forEach(({id:u,directory:f})=>{const m=i.get(f);if(!m){d.delete(u)&&(c=!0);return}const p=d.get(u);(!p||p.path!==m.path||p.branch!==m.branch||p.label!==m.label)&&(d.set(u,m),c=!0)}),c?d:null},We=Mt()(Et(es((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=dt.getState().currentDirectory??Se.getDirectory()??null,o=Se.getApiClient(),a=async D=>{const k=await o.session.list({query:D?{directory:D}:void 0});return Array.isArray(k.data)?k.data:[]},i=vt(n),c=i?await wo(i).catch(()=>!1):!1,d=await a(i||null),u=[];let f=[];if(n&&c&&i){const D=`${i}/${Qo}`;try{const k=new Set;D&&(await Se.listLocalDirectory(D)).filter(I=>I.isDirectory).forEach(I=>{const F=/^([A-Za-z]:)?\//.test(I.path)?I.path:`${D}/${I.name}`;k.add(vt(F)??F)});const M=await Qr(i);Array.isArray(M)&&(f=M.map(E=>en(i,E)).filter(E=>E.path.includes(`/${Qo}/`)),f.forEach(E=>k.add(E.path))),k.size>0&&(await Promise.allSettled(Array.from(k).map(I=>a(I)))).forEach(I=>{I.status==="fulfilled"&&Array.isArray(I.value)&&u.push(...I.value)})}catch{f=[]}}const m=new Set;i&&m.add(i),f.forEach(D=>{const k=vt(D.path);k&&m.add(k)});const p=[...d,...u].filter(D=>{const k=D.directory??i??null,M=vt(k);return M?m.has(M):!1}),h=s(),g=h.lastLoadedDirectory??null,y=n!==g;let b=[...p],w=h.currentSessionId;const j=D=>{b=[D,...b.filter(k=>k.id!==D.id)]};if(y)w=b.length>0?b[0].id:null;else if(w){if(!b.some(k=>k.id===w)){const k=h.sessions.find(M=>M.id===w);if(k)j(k);else try{const M=await Se.getSession(w);j(M)}catch{w=b.length>0?b[0].id:null}}}else w=b.length>0?b[0].id:null;const x=b.reduce((D,k)=>(D.some(M=>M.id===k.id)||D.push(k),D),[]);w&&!x.some(D=>D.id===w)&&(w=x.length>0?x[0].id:null);const v=new Set(x.map(D=>D.id));if(n){Zu(n,v);const D=Ai(n);D&&v.has(D)&&(w=D)}let N=null;try{N=await Qu(x,n,h.worktreeMetadata)}catch(D){console.debug("Failed to refresh worktree metadata during session load:",D)}const S=(()=>{const D=N??h.worktreeMetadata;if(!y||!i)return D;const k=new Map;return D.forEach((M,E)=>{vt(M.projectDirectory)===i&&k.set(E,M)}),k})(),C=(()=>{if(!w)return i??null;const D=S.get(w)?.path;if(D)return vt(D)??D;const k=_s(x,w);return k||(i??null)})();try{Se.setDirectory(C??void 0)}catch(D){console.warn("Failed to sync OpenCode directory after session load:",D)}r({sessions:x,currentSessionId:w,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:S,availableWorktrees:f}),Cs(C??n,w)}catch(t){r({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,n)=>{r({error:null});const o=dt.getState(),a=vt(o.currentDirectory),i=vt(n??Se.getDirectory()??a),c=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,d=s(),u=new Set(d.sessions.map(h=>h.id)),f={id:c,title:t||"New session",parentID:void 0,directory:i??null,projectID:d.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(r(h=>({sessions:[f,...h.sessions],currentSessionId:c,webUICreatedSessions:new Set([...h.webUICreatedSessions,c]),isLoading:!1})),i)try{Se.setDirectory(i)}catch(h){console.warn("Failed to sync OpenCode directory after session creation:",h)}const m=h=>{r(g=>({sessions:g.sessions.map(b=>b.id===c?h:b),currentSessionId:h.id,webUICreatedSessions:new Set([...Array.from(g.webUICreatedSessions).filter(b=>b!==c),h.id])})),Cs(i??null,h.id)},p=async()=>{const h=Se.getApiClient(),g=20;for(let y=0;y<g;y+=1){try{const b=await h.session.list({query:i?{directory:i}:void 0}),j=(Array.isArray(b.data)?b.data:[]).find(x=>!(u.has(x.id)||t&&x.title&&x.title!==t));if(j)return j}catch(b){console.debug("Session poll attempt failed:",b)}await new Promise(b=>setTimeout(b,2e3))}return null};try{const h=()=>Se.createSession({title:t});let g=null;try{g=i?await Se.withDirectory(i,h):await h()}catch(y){console.warn("Direct session create failed or timed out, falling back to polling:",y)}return g||(g=await p()),g?(m(g),g):(r(y=>({sessions:y.sessions.filter(b=>b.id!==c),currentSessionId:d.currentSessionId,webUICreatedSessions:new Set(Array.from(y.webUICreatedSessions).filter(b=>b!==c)),isLoading:!1,error:"Failed to create session"})),null)}catch(h){return r(g=>({sessions:g.sessions.filter(y=>y.id!==c),currentSessionId:d.currentSessionId,webUICreatedSessions:new Set(Array.from(g.webUICreatedSessions).filter(y=>y!==c)),isLoading:!1,error:h instanceof Error?h.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{r({isLoading:!0,error:null});const o=s().worktreeMetadata.get(t),a=_s(s().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await ea(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Se.deleteSession(t);if(!(i?await Se.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(b=>b.id!==t);f=p.currentSessionId===t?null:p.currentSessionId;const g=new Map(p.worktreeMetadata);g.delete(t);const y=n?.archiveWorktree&&o?p.availableWorktrees.filter(b=>vt(b.path)!==vt(o.path)):p.availableWorktrees;return{sessions:h,currentSessionId:f,isLoading:!1,worktreeMetadata:g,availableWorktrees:y}});const m=i??Se.getDirectory()??null;return Cs(m,f),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return r(c?f=>{const m=new Map(f.worktreeMetadata);return m.delete(t),{worktreeMetadata:m,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(y=>typeof y=="string"&&y.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};r({isLoading:!0,error:null});const a=[],i=[],c=new Set,d=[],u=new Set;for(const y of o)try{const b=s().worktreeMetadata.get(y),w=_s(s().sessions,y),j=b?.path??w;b&&n?.archiveWorktree&&!u.has(b.path)&&(await ea(b,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c.add(y),d.push({path:b.path,projectDirectory:b.projectDirectory}),u.add(b.path));const x=()=>Se.deleteSession(y);(j?await Se.withDirectory(j,x):await x())?(a.push(y),b?.path&&!d.some(N=>N.path===b.path)&&d.push({path:b.path,projectDirectory:b.projectDirectory})):i.push(y)}catch{i.push(y)}const f=dt.getState();d.forEach(({path:y,projectDirectory:b})=>{f.currentDirectory===y&&f.setDirectory(b,{showOverlay:!1})});const m=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(y=>{const b=y.sessions.filter(v=>!m.has(v.id));y.currentSessionId&&m.has(y.currentSessionId)?h=b.length>0?b[0].id:null:h=y.currentSessionId;const w=new Map(y.worktreeMetadata);for(const v of m)w.delete(v);for(const v of c)w.delete(v);const j=new Set(d.map(v=>vt(v.path)).filter(v=>!!v)),x=j.size>0?y.availableWorktrees.filter(v=>!j.has(vt(v.path)??v.path)):y.availableWorktrees;return{sessions:b,currentSessionId:h,isLoading:!1,worktreeMetadata:w,availableWorktrees:x,error:p}});const g=Se.getDirectory()??null;return Cs(g,h),{deletedIds:a,failedIds:i}},updateSessionTitle:async(t,n)=>{try{const o=_s(s().sessions,t),a=s().worktreeMetadata.get(t),i=()=>Se.updateSession(t,n),c=a?.path??o,d=c?await Se.withDirectory(c,i):await i();r(u=>({sessions:u.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=_s(s().sessions,t),o=Se.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Se.getDirectory();return o.session.share({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Se.withDirectory(i,c):await c();return d.data?(r(u=>({sessions:u.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=_s(s().sessions,t),o=Se.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Se.getDirectory();return o.session.unshare({path:{id:t},query:u?{directory:u}:void 0})},d=i?await Se.withDirectory(i,c):await c();return d.data?(r(u=>({sessions:u.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=Se.getDirectory()??null;Cs(n,t)},clearError:()=>{r({error:null})},getSessionsByDirectory:()=>{const{sessions:t}=s();return t},applySessionMetadata:(t,n)=>{!t||!n||r(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const i=o.sessions[a],c=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,f={...i,...n,time:c,summary:d,share:u},m=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]=m?f:i,m?{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(u=>u.id===t);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(r(u=>{const f=[...u.sessions],m={...f[a]};return d!==void 0?m.directory=d:delete m.directory,f[a]=m,{sessions:f}}),c&&Cs(c,null),n&&Cs(n,t))},updateSession:t=>{r(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:ts(()=>Ot()),partialize:r=>({currentSessionId:r.currentSessionId,sessions:r.sessions,lastLoadedDirectory:r.lastLoadedDirectory,webUICreatedSessions:Array.from(r.webUICreatedSessions),worktreeMetadata:Array.from(r.worktreeMetadata.entries()),availableWorktrees:r.availableWorktrees}),merge:(r,s)=>{if(!(u=>typeof u=="object"&&u!==null)(r))return s;const n=Array.isArray(r.sessions)?r.sessions:s.sessions,o=typeof r.currentSessionId=="string"||r.currentSessionId===null?r.currentSessionId:s.currentSessionId,a=Array.isArray(r.webUICreatedSessions)?r.webUICreatedSessions:[],i=Array.isArray(r.worktreeMetadata)?r.worktreeMetadata:[],c=Array.isArray(r.availableWorktrees)?r.availableWorktrees:s.availableWorktrees,d=typeof r.lastLoadedDirectory=="string"?r.lastLoadedDirectory:s.lastLoadedDirectory??null;return{...s,...r,sessions:n,currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:c,lastLoadedDirectory:d}}}),{name:"session-store"})),Cn=(r,s)=>{const t=Date.now(),n=r.get(s),o=new Map(r);return o.set(s,{phase:"streaming",startedAt:n?.startedAt??t,lastUpdateAt:t}),o},er=(r,s)=>{const t=Array.from(s);if(!t.some(a=>r.has(a)))return r;const o=new Map(r);return t.forEach(a=>{o.delete(a)}),o},ta=new Map,Di=r=>{const s=ta.get(r);s&&(clearTimeout(s),ta.delete(r))},Ms=r=>{for(const s of r)Di(s)},wr=r=>{if(!r)return"";if(typeof r=="string")return r;if(Array.isArray(r))return r.map(s=>wr(s)).join("");if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(Array.isArray(r.content))return r.content.map(s=>wr(s)).join("")}return""},fr=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:fr(n)).join("");const t=wr(s.delta);return t||(typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||wr(o.delta)||""}return""}).join(""):"")},tr=(r,s)=>{const t={...r};if(t.type=t.type||"text",t.type==="text"){const n=s&&typeof s.text=="string"?s.text:"",o=typeof t.text=="string"?t.text:"",a=wr(r.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},sa=10*1024*1024,em=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"}},ys=Mt()(Et(es((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=sa;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=em(t);!i.some(g=>c.startsWith(g)||c===g||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,f=await new Promise((g,y)=>{u.onload=()=>g(u.result),u.onerror=y,u.readAsDataURL(t)}),m=f.startsWith("data:")?f.replace(/^data:[^;]*/,`data:${c}`):f,p=g=>{const y=g.replace(/\\/g,"/").split("/");return y[y.length-1]||g},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:m,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(y=>y.serverPath===t&&y.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o;if(!c)try{const y=Se.getApiClient(),b=t.lastIndexOf("/"),w=b>0?t.substring(0,b):"/",j=b>0?t.substring(b+1):t,x=await y.file.read({query:{path:j,directory:w}});x.data&&"content"in x.data?c=x.data.content:c=""}catch(y){console.error("Failed to read server file:",y),c=`[File: ${n}]`}const d=new Blob([c||""],{type:"text/plain"});if(d.size>sa)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const u=new File([d],n,{type:"text/plain"}),m=new TextEncoder().encode(c||""),h=`data:text/plain;base64,${btoa(String.fromCharCode(...m))}`,g={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:u,dataUrl:h,mimeType:"text/plain",filename:n,size:d.size,source:"server",serverPath:t};r(y=>({attachedFiles:[...y.attachedFiles,g]}))},removeAttachedFile:t=>{r(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{r({attachedFiles:[]})}}),{name:"file-store",storage:ts(()=>Ot()),partialize:r=>({attachedFiles:r.attachedFiles})}),{name:"file-store"}));let Mn=[],An=null;const tm=50,sm=3e4,As=new Map,Cr=new Map,Os=new Map,rm=10,nn=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<rm?null:n},ra=(r,s)=>{const t=nn(r),n=nn(s);return!t||!n||t.length!==n.length?!0:t>n},nm=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Mr=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),na=r=>Array.isArray(r)?r.some(s=>s?.type==="step-finish"&&s?.reason==="stop"):!1,oa=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??""}`}}},aa=new Set,ia=(r=[],s=[])=>{if(!s.length)return[...r];const t=[...r],n=new Set(r.map(oa).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=oa(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},om=(r,s)=>{let t=s,n=s?nn(s):null;for(const o of r){const a=o?.info?.id,i=nn(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},$s=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return o.set(s,t),o},Ar=(r,s)=>{const t=new Map(r);let n=!1;for(const o of s)t.delete(o)&&(n=!0);return n?t:r},am=(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},la=(r,s,t)=>r.streamingMessageIds.get(s)===t?!0:r.messageSessionIndex.get(t)===s&&r.messageStreamStates.has(t),im=async r=>{if(r)try{const s=We.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}},Dn=async(r,s)=>{const t=await im(r);return t?Se.withDirectory(t,s):s()},Xe=Mt()(Et(es((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=St.VIEWPORT_MESSAGES)=>{const o=await Dn(t,()=>Se.getSessionMessages(t)),a=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=(a?o.filter(d=>{const u=d?.info?.id;return u?ra(u,a):!0}):o).slice(-n);r(d=>{const u=new Map(d.messages),f=d.messages.get(t)||[],m=new Map(f.filter(C=>typeof C.info?.id=="string").map(C=>[C.info.id,C])),h=c.map(C=>{const D={...C.info,clientRole:C.info?.clientRole??C.info.role,userMessageMarker:C.info.role==="user"?!0:C.info?.userMessageMarker},k=Array.isArray(C.parts)?[...C.parts]:[],M=D?.id?m.get(D.id):void 0;if(M&&M.info.role==="assistant"){const E=Array.isArray(M.parts)?M.parts:[],I=Mr(E),L=Mr(k);if(na(E)&&I>L){const $=ia(E,k);return{...C,info:D,parts:$}}}return{...C,info:D,parts:k}}),g=new Set(f.map(C=>C.info.id)),y=new Set(h.map(C=>C.info.id)),b=[];g.forEach(C=>{y.has(C)||b.push(C)}),u.set(t,h);const w=new Map(d.sessionMemoryState),j=d.sessionMemoryState.get(t);w.set(t,{viewportAnchor:h.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>c.length,trimmedHeadMaxId:j?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const x={messages:u,sessionMemoryState:w};Ms(b);const v=er(d.messageStreamStates,b);if(v!==d.messageStreamStates&&(x.messageStreamStates=v),b.length>0){const C=d.streamingMessageIds.get(t);C&&b.includes(C)&&(x.streamingMessageIds=qt(x.streamingMessageIds??d.streamingMessageIds,t,null))}if(b.length>0){const C=Ar(x.messageSessionIndex??d.messageSessionIndex,b);C!==(x.messageSessionIndex??d.messageSessionIndex)&&(x.messageSessionIndex=C)}if(b.length>0){const C=new Map(d.pendingAssistantParts);let D=!1;b.forEach(k=>{C.delete(k)&&(D=!0)}),D&&(x.pendingAssistantParts=C)}const N=x.messageSessionIndex??d.messageSessionIndex;let S=N;return h.forEach(C=>{const D=C?.info?.id;typeof D=="string"&&D.length>0&&(S=$s(S,D,t))}),S!==N&&(x.messageSessionIndex=S),x})},sendMessage:async(t,n,o,a,i,c,d)=>{if(!i)throw new Error("No session selected");const u=i;s().sessionAbortFlags.has(u)&&r(f=>{const m=new Map(f.sessionAbortFlags);return m.delete(u),{sessionAbortFlags:m}}),await Dn(u,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(),y=Se.getApiClient(),b=Se.getDirectory();if(h==="init"){const w=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await y.session.init({path:{id:u},body:{messageID:w,providerID:n,modelID:o},query:b?{directory:b}:void 0});return}if(h==="summarize"){await y.session.summarize({path:{id:u},body:{providerID:n,modelID:o},query:b?{directory:b}:void 0});return}try{const w=await Se.getCommandDetails(h);w?.template?f=w.template.replace(/\$ARGUMENTS/g,g):f=t}catch(w){console.error("Command template resolution failed:",w),f=t}}r({lastUsedProvider:{providerID:n,modelID:o}}),r(p=>{const h=p.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=Os.get(u);g&&(clearTimeout(g),Os.delete(u));const y=new Map(p.sessionMemoryState);return y.set(u,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:y}});try{const p=new AbortController;r(g=>{const y=new Map(g.abortControllers);return y.set(u,p),{abortControllers:y}});const h=(c??[]).map(g=>({type:"file",mime:g.mimeType,filename:g.filename,url:g.dataUrl}));if(await Se.sendMessage({id:u,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{ys.getState().clearAttachedFiles()}catch(g){console.error("Failed to clear attached files after send",g)}r(g=>{const y=new Map(g.abortControllers);return y.delete(u),{abortControllers:y}})}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 y=new Map(g.abortControllers);return y.delete(u),{abortControllers:y}});return}else p.message&&(h=p.message);throw r(g=>{const y=new Map(g.abortControllers);return y.delete(u),{abortControllers:y}}),new Error(h)}}catch(f){let m="Network error while sending message. The message may still be processing.";throw f.name==="AbortError"?m="Request timed out. The message may still be processing.":f.response?.status===401?m="Session not found or unauthorized. Please refresh the page.":f.response?.status===502?m="OpenCode is restarting. Please wait a moment and try again.":f.message?.includes("504")||f.message?.includes("Gateway")?m="Gateway timeout - your message is being processed. Please wait for response.":f.message&&(m=f.message),r(p=>{const h=new Map(p.abortControllers);return h.delete(u),{abortControllers:h}}),new Error(m)}})},abortCurrentOperation:async t=>{if(!t)return;const n=s(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=am(n,t);if(c.size===0){const u=t?a.get(t)??[]:[];let f=null;for(let m=u.length-1;m>=0;m-=1){const p=u[m];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 u of c){const f=As.get(u);f&&(clearTimeout(f),As.delete(u),Cr.delete(u))}c.size>0&&Ms(c);const d=Date.now();r(u=>{const f=er(u.messageStreamStates,c),m=u.messages.get(t)??[];let p=!1,h=u.messages;if(m.length>0&&c.size>0){const w=m.map(j=>{if(!c.has(j.info.id)&&c.size>0)return j;const x=(j.parts??[]).map(v=>{if(v.type==="reasoning"){const N=v,S={...N.time??{}};return typeof S.end!="number"&&(S.end=d),{...N,time:S}}if(v.type==="tool"){const N=v,S={...N.state??{}};return(S.status==="running"||S.status==="pending")&&(S.status="aborted"),{...N,state:S}}return v.type==="step-start"?{...v,type:"step-finish",aborted:!0}:v});return p=!0,{...j,info:{...j.info,abortedAt:d,streaming:!1,status:"aborted"},parts:x}});p&&(h=new Map(u.messages),h.set(t,w))}const g=u.sessionMemoryState.get(t);let y=u.sessionMemoryState;if(g){const w=new Map(u.sessionMemoryState);w.set(t,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),y=w}const b=new Map(u.sessionAbortFlags);return b.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:f,sessionMemoryState:y,sessionAbortFlags:b,abortControllers:(()=>{const w=new Map(u.abortControllers);return w.delete(t),w})(),streamingMessageIds:qt(u.streamingMessageIds,t,null),...p?{messages:h}:{}}}),Se.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=s();if(aa.has(n))return;const d=c.messages.get(t)||[],u=d.find(h=>h.info.id===n),f=a==="user"||u?.info.role==="user"?"user":a||u?.info.role||"assistant",m=s().sessionMemoryState.get(t);if(m?.streamStartTime&&Date.now()-m.streamStartTime>St.ZOMBIE_TIMEOUT){m.isZombie||r(g=>{const y=new Map(g.sessionMemoryState);return y.set(t,{...m,isZombie:!0}),{sessionMemoryState:y}}),setTimeout(()=>{s().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}r(h=>{const y=[...h.messages.get(t)||[]],b={},w=$s(h.messageSessionIndex,n,t);w!==h.messageSessionIndex&&(b.messageSessionIndex=w);const j=k=>{if(!((f==="assistant"||f==="user")&&h.sessionAbortFlags.has(t)))return k;const E=new Map(h.sessionAbortFlags);return E.delete(t),{...k,sessionAbortFlags:E}},x=k=>{const M=k||"",E=Cr.get(n);if(M&&E===M){const F=s();if(la(F,t,n)){const $=As.get(n);$&&(clearTimeout($),As.delete(n)),setTimeout(()=>{const Y=s();typeof Y.forceCompleteMessage=="function"&&Y.forceCompleteMessage(t,n,"timeout"),Y.completeStreamingMessage(t,n)},100)}}Cr.set(n,M);const I=As.get(n);I&&clearTimeout(I);const L=setTimeout(()=>{const F=s();typeof F.forceCompleteMessage=="function"&&F.forceCompleteMessage(t,n,"timeout"),la(F,t,n)&&F.completeStreamingMessage(t,n),As.delete(n),Cr.delete(n)},8e3);As.set(n,L)},v=t!==i,N=h.sessionMemoryState.get(t);if(v&&N?.isStreaming){y.length>=St.BACKGROUND_STREAMING_BUFFER&&y.shift();const k=new Map(h.sessionMemoryState);k.set(t,{...N,backgroundMessageCount:(N.backgroundMessageCount||0)+1}),h.sessionMemoryState=k}if(f==="assistant"){const k=h.sessionMemoryState.get(t);if(k){const M=Date.now(),E=new Map(h.sessionMemoryState);E.set(t,{...k,isStreaming:!0,streamStartTime:k.streamStartTime??M,lastAccessedAt:M,isZombie:!1}),h.sessionMemoryState=E}}const S=fr(o);if(nm()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:S.length,snapshotParts:d.length})}catch{}const C=b.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const k=qt(C,t,n);k!==C&&(b.streamingMessageIds=k,window.__messageTracker?.(n,"streamingId_set_latest"))}const D=y.findIndex(k=>k.info.id===n);if(D!==-1&&f==="user"){const k=y[D],M=k.parts.findIndex($=>$.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const E=tr(o,M!==-1?k.parts[M]:void 0);window.__messageTracker?.(n,`user_part_type:${E.type||"unknown"}`);const I={...k};M!==-1?I.parts=I.parts.map(($,Y)=>Y===M?E:$):I.parts=[...I.parts,E];const L=[...y];L[D]=I;const F=new Map(h.messages);return F.set(t,L),j({messages:F})}if(f==="assistant"&&D!==-1){const k=y[D],M=k.parts.findIndex(Y=>Y.id===o.id),E=tr(o,M!==-1?k.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${E.type||"unknown"}`);const I={...k};M!==-1?I.parts=I.parts.map((Y,ie)=>ie===M?E:Y):I.parts=[...I.parts,E];const L=[...y];L[D]=I;const F=new Map(h.messages);F.set(t,L),b.messageStreamStates=Cn(h.messageStreamStates,n);const $=qt(b.streamingMessageIds??h.streamingMessageIds,t,n);return $!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=$,window.__messageTracker?.(n,"streamingId_set")),E.type==="text"?x(E.text||""):x(""),j({messages:F,...b})}if(D===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const P=tr(o);window.__messageTracker?.(n,`new_user_part_type:${P.type||"unknown"}`);const B={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,time:{created:Date.now()}},parts:[P]},te=[...y,B];te.sort((se,V)=>{const ve=se.info?.time?.created||0,Ae=V.info?.time?.created||0;return ve-Ae});const ye=new Map(h.messages);return ye.set(t,te),j({messages:ye})}if(o?.type==="text"){const P=fr(o).trim();if(P.length>0){const B=[...y].reverse().find(te=>te.info.role==="user");if(B){const te=B.parts.map(ye=>fr(ye)).join("").trim();if(te.length>0&&te===P)return aa.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const k=tr(o);window.__messageTracker?.(n,`part_type:${k.type||"unknown"}`),k.type==="text"?x(k.text||""):x("");const M=h.pendingAssistantParts.get(n),E=M?[...M.parts]:[],I=E.findIndex(P=>P.id===k.id);I!==-1?E[I]=k:E.push(k);const L=new Map(h.pendingAssistantParts);L.set(n,{sessionId:t,parts:E});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:E},Y=[...y,$],ie=new Map(h.messages);if(ie.set(t,Y),f==="assistant"){b.messageStreamStates=Cn(h.messageStreamStates,n);const P=qt(b.streamingMessageIds??h.streamingMessageIds,t,n);P!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set"))}return j({messages:ie,pendingAssistantParts:L,...b})}else{const k=y[D],M=k.parts.findIndex($=>$.id===o.id),E=tr(o,M!==-1?k.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${E.type||"unknown"}`);const I={...k};M!==-1?I.parts=I.parts.map(($,Y)=>Y===M?E:$):I.parts=[...I.parts,E];const L=[...y];L[D]=I;const F=new Map(h.messages);if(F.set(t,L),I.info.role==="assistant"){b.messageStreamStates=Cn(h.messageStreamStates,n);const $=qt(b.streamingMessageIds??h.streamingMessageIds,t,n);$!==(b.streamingMessageIds??h.streamingMessageIds)&&(b.streamingMessageIds=$,window.__messageTracker?.(n,"streamingId_set"))}return E.type==="text"?x(E.text||""):x(""),j({messages:F,...b})}}),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}Mn.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),An||(An=setTimeout(()=>{const c=[...Mn];Mn=[],An=null;const d=s();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},tm))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};r(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],u=d.findIndex(N=>N.info.id===n);if(u===-1)return i;const f=d[u];if(!f)return i;const m=Date.now(),p=f.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let g=!1;const y={...p};h||(y.time={...p.time??{},completed:m},g=!0),y.status!=="completed"&&(y.status="completed",g=!0),y.streaming&&(y.streaming=!1,g=!0);let b=!1;const w=f.parts.map(N=>{if(!N)return N;if(N.type==="tool"){const S=N.state;if(!S)return N;const C=S.status,D=C==="running"||C==="pending"||C==="started",k=!S.time||typeof S.time?.end!="number";if(D||k){const M={...S};return D&&(M.status="completed"),k&&(M.time={...S.time??{},end:m}),b=!0,{...N,state:M}}return N}if(N.type==="reasoning"){const S=N.time;return!S||typeof S.end!="number"?(b=!0,{...N,time:{...S??{},end:m}}):N}if(N.type==="text"){const S=N.time;return S&&typeof S.end!="number"?(b=!0,{...N,time:{...S,end:m}}):N}return N});if(!g&&!b)return i;window.__messageTracker?.(n,`force_complete:${o}`);const j={...f,info:y,parts:b?w:f.parts},x=[...d];x[u]=j;const v=new Map(i.messages);return v.set(c,x),{messages:v}})},markMessageStreamSettled:t=>{r(n=>{Di(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,u)=>{if(i)return;const f=d.findIndex(y=>y.info.id===t);if(f===-1)return;const m=d[f];if(m.info?.animationSettled)return;const p={...m,info:{...m.info,animationSettled:!0}},h=[...d];h[f]=p;const g=new Map(n.messages);g.set(u,h),a=g,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),Ms([t])},updateMessageInfo:(t,n,o)=>{r(a=>{const c=[...a.messages.get(t)??[]],d=c.findIndex(N=>N.info.id===n),u=a.pendingAssistantParts.get(n),f=(N=[],S=[])=>{if(!S.length)return N;const C=[...N];return S.forEach(D=>{const k=C.findIndex(M=>M.id===D.id);k===-1?C.push(D):C[k]=D}),C},m=N=>{if(!N)return N;const S=N.clientRole??N.role,C=S==="user"?!0:N.userMessageMarker;return{...N,clientRole:S,...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 L=c[0]?.info,F=typeof L?.time?.created=="number"?L.time.created:null,$=typeof L?.id=="string"?L.id:null,Y=o,ie=typeof Y?.time?.created=="number"?Y.time.created:null,P=typeof Y?.id=="string"?Y.id:n;let B=!1;if(ie!==null&&F!==null&&(B=ie<F),!B&&P&&$&&(B=P.localeCompare($)<0),B)return window.__messageTracker?.(n,"skipped_evicted_message_update"),a}const N=m(o);if(N&&N.role==="user"){const I=u?.parts??[],L={info:{...N,userMessageMarker:!0,clientRole:"user"},parts:I.length>0?[...I]:[]},F=new Map(a.messages),$=[...c,L];$.sort((P,B)=>{const te=P.info?.time?.created||0,ye=B.info?.time?.created||0;return te-ye}),F.set(t,$);const Y={messages:F},ie=$s(Y.messageSessionIndex??a.messageSessionIndex,n,t);if(ie!==(Y.messageSessionIndex??a.messageSessionIndex)&&(Y.messageSessionIndex=ie),u){const P=new Map(a.pendingAssistantParts);P.delete(n),Y.pendingAssistantParts=P}return Y}if(!N||N.role!=="assistant")return a;const S=u?.parts??[],C={info:{...N,animationSettled:N?.animationSettled??!1},parts:S.length>0?[...S]:[]},D=new Map(a.messages),k=[...c,C];D.set(t,k);const M={messages:D},E=$s(M.messageSessionIndex??a.messageSessionIndex,n,t);if(E!==(M.messageSessionIndex??a.messageSessionIndex)&&(M.messageSessionIndex=E),u){const I=new Map(a.pendingAssistantParts);I.delete(n),M.pendingAssistantParts=I}return M}const p=c[d],h=p.info;if(h.userMessageMarker===!0||h.clientRole==="user"||h.role==="user"){const N={...p.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:h.providerID||void 0,modelID:h.modelID||void 0},S={...p,info:N},C=new Map(a.messages),D=[...c];return D[d]=S,C.set(t,D),{messages:C}}const y={...p.info,...o};o.role&&o.role!==p.info.role&&(y.role=p.info.role),y.clientRole=y.clientRole??p.info.clientRole??p.info.role,y.clientRole==="user"&&(y.userMessageMarker=!0);const b=u?.parts?f(p.parts,u.parts):p.parts,w={...p,info:y,parts:b},j=new Map(a.messages),x=[...c];x[d]=w,j.set(t,x);const v={messages:j};if(u){const N=new Map(a.pendingAssistantParts);N.delete(n),v.pendingAssistantParts=N}return v})},completeStreamingMessage:(t,n)=>{const o=s();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(a&&(i.streamingMessageIds=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 u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),Ms([n]);let c=!1;if(r(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const f=new Map(d.sessionMemoryState),m=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:m,streamingCooldownUntil:m+2e3};return f.set(t,p),c=!0,{sessionMemoryState:f}}),c){const d=Os.get(t);d&&(clearTimeout(d),Os.delete(t));const u=setTimeout(()=>{r(f=>{const m=f.sessionMemoryState.get(t);if(!m||m.isStreaming)return f;const p=new Map(f.sessionMemoryState),{streamingCooldownUntil:h,...g}=m;return p.set(t,g),{sessionMemoryState:p}}),Os.delete(t)},2e3);Os.set(t,u)}},syncMessages:(t,n)=>{const o=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,a=o?n.filter(i=>{const c=i?.info?.id;return c?ra(c,o):!0}):n;r(i=>{const c=new Map(i.messages),d=i.messages.get(t)||[],u=new Map(d.filter(x=>typeof x.info?.id=="string").map(x=>[x.info.id,x])),m=a.map(x=>{const v={...x.info,clientRole:x.info?.clientRole??x.info.role,userMessageMarker:x.info.role==="user"?!0:x.info?.userMessageMarker,animationSettled:x.info.role==="assistant"?x.info?.animationSettled??!0:x.info?.animationSettled},N=Array.isArray(x.parts)?[...x.parts]:[],S=typeof v?.id=="string"?v.id:void 0,C=S?u.get(S):void 0;if(C&&C.info.role==="assistant"){const D=Array.isArray(C.parts)?C.parts:[],k=Mr(D),M=Mr(N);if(na(D)&&k>M){const I=ia(D,N);return{...x,info:v,parts:I}}}return{...x,info:v,parts:N}}),p=new Set(d.map(x=>x.info.id)),h=new Set(m.map(x=>x.info.id)),g=[];p.forEach(x=>{h.has(x)||g.push(x)}),c.set(t,m);const y={messages:c,isSyncing:!0};Ms(g);const b=er(i.messageStreamStates,g);if(b!==i.messageStreamStates&&(y.messageStreamStates=b),g.length>0){const x=i.streamingMessageIds.get(t);x&&g.includes(x)&&(y.streamingMessageIds=qt(y.streamingMessageIds??i.streamingMessageIds,t,null))}if(g.length>0){const x=Ar(y.messageSessionIndex??i.messageSessionIndex,g);x!==(y.messageSessionIndex??i.messageSessionIndex)&&(y.messageSessionIndex=x)}if(g.length>0){const x=new Map(i.pendingAssistantParts);let v=!1;g.forEach(N=>{x.delete(N)&&(v=!0)}),v&&(y.pendingAssistantParts=x)}const w=y.messageSessionIndex??i.messageSessionIndex;let j=w;return m.forEach(x=>{const v=x?.info?.id;typeof v=="string"&&v.length>0&&(j=$s(j,v,t))}),j!==w&&(y.messageSessionIndex=j),y}),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+sm;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=St.VIEWPORT_MESSAGES,o)=>{const a=s(),i=a.messages.get(t);if(!i||i.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const f=Math.min(i.length,u+n);f===i.length&&f-u<n&&(u=Math.max(0,f-n));const m=i.slice(u,f),p=i.slice(0,u),h=new Set(m.map(y=>y.info.id)),g=i.filter(y=>!h.has(y.info.id)).map(y=>y.info.id);r(y=>{const b=new Map(y.messages);b.set(t,m);const w=new Map(y.sessionMemoryState),j={...c,viewportAnchor:d-u,trimmedHeadMaxId:om(p,c.trimmedHeadMaxId)};w.set(t,j);const x={messages:b,sessionMemoryState:w};Ms(g);const v=er(y.messageStreamStates,g);if(v!==y.messageStreamStates&&(x.messageStreamStates=v),g.length>0){const C=y.streamingMessageIds.get(t);C&&g.includes(C)&&(x.streamingMessageIds=qt(x.streamingMessageIds??y.streamingMessageIds,t,null))}if(g.length>0){const C=Ar(x.messageSessionIndex??y.messageSessionIndex,g);C!==(x.messageSessionIndex??y.messageSessionIndex)&&(x.messageSessionIndex=C)}const N=x.messageSessionIndex??y.messageSessionIndex;let S=N;return m.forEach(C=>{const D=C?.info?.id;typeof D=="string"&&D.length>0&&(S=$s(S,D,t))}),S!==N&&(x.messageSessionIndex=S),x})},evictLeastRecentlyUsed:t=>{const n=s();if(n.messages.size<=St.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const f=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,f])});const i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=i[0][0];r(d=>{const f=(d.messages.get(c)||[]).map(v=>v.info.id),m=new Map(d.messages),p=new Map(d.sessionMemoryState);m.delete(c),p.delete(c);const h={messages:m,sessionMemoryState:p},g=new Map(d.pendingAssistantParts);let y=!1;g.forEach((v,N)=>{v.sessionId===c&&(g.delete(N),y=!0)}),y&&(h.pendingAssistantParts=g);const b=new Map(d.sessionCompactionUntil);b.delete(c)&&(h.sessionCompactionUntil=b),Ms(f);const w=er(d.messageStreamStates,f);w!==d.messageStreamStates&&(h.messageStreamStates=w);const j=Ar(h.messageSessionIndex??d.messageSessionIndex,f);j!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=j);const x=qt(d.streamingMessageIds,c,null);if(x!==d.streamingMessageIds&&(h.streamingMessageIds=x),d.abortControllers.has(c)){const v=new Map(d.abortControllers);v.delete(c),h.abortControllers=v}return h})},loadMoreMessages:async(t,n="up")=>{const o=s(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const c=await Dn(t,()=>Se.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=c.findIndex(f=>f.info.id===d.info.id);if(u>0){const f=Math.min(St.VIEWPORT_MESSAGES,u),m=c.slice(u-f,u);r(p=>{const h=[...m,...a],g=new Map(p.messages);g.set(t,h);const y=new Map(p.sessionMemoryState);return y.set(t,{...i,viewportAnchor:i.viewportAnchor+m.length,hasMoreAbove:u-f>0,totalAvailableMessages:c.length}),{messages:g,sessionMemoryState:y}})}else u===0&&r(f=>{const m=new Map(f.sessionMemoryState);return m.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:m}})}},getLastMessageModel:t=>{const{messages:n}=s(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:ts(()=>Ot()),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"})),lm=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),cm=r=>r?lm.has(r.toLowerCase()):!1,dm=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},um=r=>{if(r)try{const s=dm();if(s?.getState)return s.getState().agents?.find?.(n=>n.name===r)}catch{}},Ur=r=>{const s=um(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"},ca=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},En=r=>{const s=r.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return ca(s);const t=r.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:ca(t.tokens)},Tn=(r,s,t)=>{const n=Number.isFinite(s)?Math.max(s,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),c=Math.min(i,n),d=n>0?Math.max(n-c,1):0,u=d>0?r/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},sr=["ask","allow","full"],ot=Mt()(Et(es((r,s)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{r(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=s();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{r(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=s();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{r(i=>{const c=new Map(i.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=s(),a=o.get(t);return a&&a.get(n)||null},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a}=s(),i=new Map,c=(m,p)=>{if("mode"in m&&m.mode&&typeof m.mode=="string"&&n.find(b=>b.name===m.mode))return m.mode;if(m.providerID&&m.modelID){const y=n.find(b=>b.model?.providerID===m.providerID&&b.model?.modelID===m.modelID);if(y)return y.name}const{currentAgentContext:h}=s(),g=h.get(t);if(g&&n.find(y=>y.name===g))return g;if(p>0&&m.providerID&&m.modelID){const b=(o.get(t)||[]).filter(w=>w.info.role==="assistant").sort((w,j)=>w.info.time.created-j.info.time.created);for(let w=p-1;w>=0;w--){const x=b[w].info;if(x.providerID===m.providerID&&x.modelID===m.modelID){if(x.mode&&typeof x.mode=="string"&&n.find(S=>S.name===x.mode))return x.mode;const v=n.find(N=>N.model?.providerID===x.providerID&&N.model?.modelID===x.modelID);if(v)return v.name}}}return m.providerID&&m.modelID&&n.find(b=>b.name==="build")?"build":null},d=o.get(t)||[],u=d.filter(m=>m.info.role==="assistant"||m.info.role==="user").sort((m,p)=>m.info.time.created-p.info.time.created),f=d.filter(m=>m.info.role==="assistant").sort((m,p)=>m.info.time.created-p.info.time.created);for(let m=0;m<u.length;m++){const p=u[m],{info:h}=p,g=h;if(g.providerID&&g.modelID){const y=c(g,f.indexOf(p));if(y&&n.find(b=>b.name===y)){const b={providerId:g.providerID,modelId:g.modelID,timestamp:h.time.created},w=i.get(y);(!w||b.timestamp>w.timestamp)&&i.set(y,b)}}}for(const[m,p]of i)a(t,m,p.providerId,p.modelId);return i},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=Tn(0,n,o),c=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(c===0||u===0)return null;const m=(a.get(t)||[]).filter(x=>x.info.role==="assistant");if(m.length===0)return null;const p=m[m.length-1],h=p.info.id,g=x=>{const v=()=>{r(N=>{const S=N.sessionContextUsage.get(t);if(S&&S.totalTokens===x.totalTokens&&S.percentage===x.percentage&&S.contextLimit===x.contextLimit&&(S.outputLimit??0)===(x.outputLimit??0)&&(S.normalizedOutput??0)===(x.normalizedOutput??0)&&S.thresholdLimit===x.thresholdLimit&&S.lastMessageId===x.lastMessageId)return N;const C=new Map(N.sessionContextUsage);return C.set(t,x),{sessionContextUsage:C}})};typeof queueMicrotask=="function"?queueMicrotask(v):typeof window<"u"?window.setTimeout(v,0):setTimeout(v,0)},y=s().sessionContextUsage.get(t);if(y&&y.lastMessageId===h){const x=y.normalizedOutput??y.outputLimit??0,v=y.contextLimit!==c||x!==d||y.thresholdLimit!==u;if(v&&y.totalTokens>0){const N=y.totalTokens/u*100,S={totalTokens:y.totalTokens,percentage:Math.min(N,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:h};return g(S),S}if(!v&&y.totalTokens>0)return y}const b=En(p);if(b===0)return y||null;const w=Tn(b,n,o),j={totalTokens:b,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.outputLimit,normalizedOutput:w.normalizedOutput,thresholdLimit:w.thresholdLimit,lastMessageId:h};return g(j),j},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(m=>m.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=En(d);if(u===0)return;const f=Tn(u,n,o);r(m=>{const p=new Map(m.sessionContextUsage);return p.set(t,{totalTokens:u,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 u=(o.get(t)||[]).find(f=>f.info.id===n);if(u&&u.info.role==="assistant"&&En(u)>0){s().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=s();return n.get(t)},getSessionAgentEditMode:(t,n,o=Ur(n))=>!t||!n?o:s().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Ur(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||sr.includes(o)&&r(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Ur(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=s().getSessionAgentEditMode(t,n,a),c=sr.indexOf(i),d=sr.indexOf(a),f=((c>=0?c:d>=0?d:0)+1)%sr.length,m=sr[f];s().setSessionAgentEditMode(t,n,m,a)}}),{name:"context-store",storage:ts(()=>Ot()),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"})),mm=r=>typeof r=="object"&&r!==null,fm=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},pm=async(r,s)=>{try{const t=We.getState(),n=t.getWorktreeMetadata(r);if(n?.path)return Se.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 Se.withDirectory(a,s)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return s()},on=Mt()(Et(es((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=Ur(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&cm(a)){s().respondToPermission(o,t.id,"once").catch(()=>{});return}r(f=>{const m=f.permissions.get(o)||[],p=new Map(f.permissions);return p.set(o,[...m,t]),{permissions:p}})},respondToPermission:async(t,n,o)=>{await pm(t,()=>Se.respondToPermission(t,n,o)),o==="reject"&&await Xe.getState().abortCurrentOperation(t),r(a=>{const c=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:ts(()=>Ot()),partialize:r=>({permissions:Array.from(r.permissions.entries())}),merge:(r,s)=>{if(!mm(r))return s;const t=fm(r.permissions);return{...s,permissions:new Map(t)}}}),{name:"permission-store"})),da=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},hm=(r,s,t)=>{if(!s)return null;const n=t(s)?.path;if(typeof n=="string"&&n.trim().length>0)return da(n);const o=r.find(a=>a.id===s);return o?da(o.directory??null):null},we=Mt()(Et((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)=>ot.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>ot.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>ot.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>We.getState().loadSessions(),createSession:async(t,n)=>{const o=await We.getState().createSession(t,n);return o?.id&&await s().setCurrentSession(o.id),o},deleteSession:(t,n)=>We.getState().deleteSession(t,n),deleteSessions:(t,n)=>We.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>We.getState().updateSessionTitle(t,n),shareSession:t=>We.getState().shareSession(t),unshareSession:t=>We.getState().unshareSession(t),setCurrentSession:async t=>{const n=s().currentSessionId,o=hm(We.getState().sessions,t,We.getState().getWorktreeMetadata),a=Se.getDirectory()??dt.getState().currentDirectory??null,i=o??a;try{Se.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,St.VIEWPORT_MESSAGES)}We.getState().setCurrentSession(t),t&&(s().messages.get(t)||await s().loadMessages(t),s().trimToViewportWindow(t,au)),s().evictLeastRecentlyUsed()},loadMessages:t=>Xe.getState().loadMessages(t),sendMessage:(t,n,o,a,i,c)=>{const d=We.getState().currentSessionId;return Xe.getState().sendMessage(t,n,o,a,d||void 0,i,c)},abortCurrentOperation:()=>{const t=We.getState().currentSessionId;return Xe.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=We.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&&Xe.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=We.getState().currentSessionId||t;return Xe.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>Xe.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>Xe.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>Xe.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>Xe.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:ot.getState().currentAgentContext,sessionAgentSelections:ot.getState().sessionAgentSelections,getSessionAgentEditMode:ot.getState().getSessionAgentEditMode};return on.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>on.getState().respondToPermission(t,n,o),clearError:()=>We.getState().clearError(),getSessionsByDirectory:t=>We.getState().getSessionsByDirectory(t),getLastMessageModel:t=>Xe.getState().getLastMessageModel(t),getCurrentAgent:t=>ot.getState().getCurrentAgent(t),syncMessages:(t,n)=>Xe.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>We.getState().applySessionMetadata(t,n),addAttachedFile:t=>ys.getState().addAttachedFile(t),addServerFile:(t,n,o)=>ys.getState().addServerFile(t,n,o),removeAttachedFile:t=>ys.getState().removeAttachedFile(t),clearAttachedFiles:()=>ys.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>Xe.getState().updateViewportAnchor(t,n),trimToViewportWindow:(t,n)=>{const o=We.getState().currentSessionId;return Xe.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=We.getState().currentSessionId;return Xe.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>Xe.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>ot.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>ot.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>ot.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>ot.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>ot.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>ot.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=Xe.getState().messages;return ot.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>We.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>We.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>We.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>We.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>We.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>We.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{const o=We.getState().currentSessionId;if(!o)return null;const a=Xe.getState().messages;return ot.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=Xe.getState().messages;return ot.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=Xe.getState().messages;return ot.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=Xe.getState().messages.get(t)||[],o=We.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=Xe.getState().messages;return ot.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>We.getState().updateSession(t)}),{name:"composed-session-store"}));We.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||we.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})});Xe.subscribe((r,s)=>{if(r.messages===s.messages&&r.sessionMemoryState===s.sessionMemoryState&&r.messageStreamStates===s.messageStreamStates&&r.sessionCompactionUntil===s.sessionCompactionUntil&&r.sessionAbortFlags===s.sessionAbortFlags&&r.streamingMessageIds===s.streamingMessageIds&&r.abortControllers===s.abortControllers&&r.lastUsedProvider===s.lastUsedProvider&&r.isSyncing===s.isSyncing)return;const t=new Map;r.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const c=i.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const f=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:u,createdAt:f});break}}}}}),we.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})});ys.subscribe((r,s)=>{r.attachedFiles!==s.attachedFiles&&we.setState({attachedFiles:r.attachedFiles})});ot.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||we.setState({sessionModelSelections:r.sessionModelSelections,sessionAgentSelections:r.sessionAgentSelections,sessionAgentModelSelections:r.sessionAgentModelSelections,currentAgentContext:r.currentAgentContext,sessionContextUsage:r.sessionContextUsage,sessionAgentEditModes:r.sessionAgentEditModes})});on.subscribe((r,s)=>{r.permissions!==s.permissions&&we.setState({permissions:r.permissions})});we.setState({sessions:We.getState().sessions,currentSessionId:We.getState().currentSessionId,lastLoadedDirectory:We.getState().lastLoadedDirectory,isLoading:We.getState().isLoading,error:We.getState().error,webUICreatedSessions:We.getState().webUICreatedSessions,worktreeMetadata:We.getState().worktreeMetadata,availableWorktrees:We.getState().availableWorktrees,messages:Xe.getState().messages,sessionMemoryState:Xe.getState().sessionMemoryState,messageStreamStates:Xe.getState().messageStreamStates,sessionCompactionUntil:Xe.getState().sessionCompactionUntil,sessionAbortFlags:Xe.getState().sessionAbortFlags,streamingMessageIds:Xe.getState().streamingMessageIds,abortControllers:Xe.getState().abortControllers,lastUsedProvider:Xe.getState().lastUsedProvider,isSyncing:Xe.getState().isSyncing,permissions:on.getState().permissions,attachedFiles:ys.getState().attachedFiles,sessionModelSelections:ot.getState().sessionModelSelections,sessionAgentSelections:ot.getState().sessionAgentSelections,sessionAgentModelSelections:ot.getState().sessionAgentModelSelections,currentAgentContext:ot.getState().currentAgentContext,sessionContextUsage:ot.getState().sessionContextUsage,sessionAgentEditModes:ot.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=we);const ua=({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)}`],u=e.jsxs("div",{className:A("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(Yl,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:A(i(s),"font-medium"),children:[Math.min(s,999).toFixed(1),"%"]})]});return e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:u}),e.jsx(rt,{children:e.jsx("div",{className:"space-y-0.5",children:d.map(f=>e.jsx("p",{className:"typography-micro leading-tight",children:f},f))})})]})},rr={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Ei=(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 In(){const r=window.innerWidth,s=typeof window.matchMedia=="function",t=s?window.matchMedia("(pointer: coarse)"):null,n=s?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=r>rr.md&&r<=rr.lg,f=r<=rr.md;let m=d&&f,p=d&&!m&&u,h=!d||r>rr.lg,g="desktop";c?(m=!1,p=!1,h=!0,g="desktop"):m?g="mobile":p?g="tablet":(h=!0,g="desktop"),Ei(c,g,d);let y="xs";for(const[b,w]of Object.entries(rr))r>=w&&(y=b);return{isMobile:m,isTablet:p,isDesktop:h,deviceType:g,screenWidth:r,breakpoint:y,hasTouchInput:d}}function wt(){const[r,s]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:In());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{s(In())};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(In())},a=[],i=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return i(t),i(n),()=>{a.forEach(c=>c())}},[]),l.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||c||d>0;Ei(t,r.deviceType,u)},[r.deviceType,r.hasTouchInput]),r}const gm=3e3,xm=3e4,Kt=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),ym=(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)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!1},xt=Mt()(Et((r,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=s();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,Kt()),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=Kt()),a||r({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const m=new Map(i);return m.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),r({directories:m,isLoadingStatus:!1}),!1}const f=await n.getGitStatus(t);if(ym(c.status,f)){d=!0;const m=new Map(s().directories),p=m.get(t)??Kt();m.set(t,{...p,isGitRepo:!0,status:f,diffCache:new Map,lastStatusFetch:Date.now(),lastStatusChange:Date.now()}),r({directories:m})}else{const m=new Map(s().directories),p=m.get(t)??Kt();m.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),r({directories:m})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||r({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{r({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(s().directories),i=a.get(t)??Kt();a.set(t,{...i,branches:o}),r({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{r({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=s(),i=a.get(t),c=o??i?.logMaxCount??25;r({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),u=new Map(s().directories),f=u.get(t)??Kt();u.set(t,{...f,log:d,lastLogFetch:Date.now(),logMaxCount:c}),r({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{r({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{r({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(s().directories),i=a.get(t)??Kt();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=Kt();const m=new Map(a);m.set(t,i),r({directories:m})}const{force:c=!1}=o,d=Date.now();await s().fetchStatus(t,n);const u=s().directories.get(t);if(!u?.isGitRepo)return;await s().fetchBranches(t,n);const f=d-(u.lastLogFetch||0);(c||f>xm||!u.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)??Kt(),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)??Kt();o.set(t,{...a,logMaxCount:n}),r({directories:o})},startPolling:t=>{const{pollIntervalId:n}=s();if(n)return;const o=setInterval(async()=>{const{activeDirectory:a}=s();if(!a)return;await s().fetchStatus(a,t,{silent:!0})&&await s().fetchLog(a,t)},gm);r({pollIntervalId:o})},stopPolling:()=>{const{pollIntervalId:t}=s();t&&(clearInterval(t),r({pollIntervalId:null}))},refresh:async(t,n={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,t,n)}}),{name:"git-store"})),Ti=r=>xt(s=>r?s.directories.get(r)?.status??null:null),bm=r=>xt(s=>r?s.directories.get(r)?.branches??null:null),wm=r=>xt(s=>r?s.directories.get(r)?.log??null:null),vm=r=>xt(s=>r?s.directories.get(r)?.identity??null:null),Ii=r=>xt(s=>r?s.directories.get(r)?.isGitRepo??null:null),jm=r=>xt(s=>r?s.directories.get(r)?.status?.files?.length??0:0);function Ft({...r}){return e.jsx(Jl,{"data-slot":"dropdown-menu",...r})}function Lt({...r}){return e.jsx(Xl,{"data-slot":"dropdown-menu-trigger",...r})}function _t({className:r,sideOffset:s=4,...t}){return e.jsx(Zl,{children:e.jsx(Ql,{"data-slot":"dropdown-menu-content",sideOffset:s,className:A("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 mt({className:r,inset:s,variant:t="default",...n}){return e.jsx(rc,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":t,className:A("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 Sm({...r}){return e.jsx(ec,{"data-slot":"dropdown-menu-radio-group",...r})}function Nm({className:r,children:s,...t}){return e.jsxs(tc,{"data-slot":"dropdown-menu-radio-item",className:A("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(sc,{children:e.jsx(ht,{className:"size-3"})})}),s]})}function No({className:r,...s}){return e.jsx(nc,{"data-slot":"dropdown-menu-separator",className:A("bg-border -mx-1 my-0.5 h-px",r),...s})}function Pi({...r}){return e.jsx(oc,{"data-slot":"dropdown-menu-sub",...r})}function Ri({className:r,inset:s,children:t,...n}){return e.jsxs(ac,{"data-slot":"dropdown-menu-sub-trigger","data-inset":s,className:A("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(ds,{className:"ml-auto size-3.5"})]})}function Fi({className:r,...s}){return e.jsx(ic,{"data-slot":"dropdown-menu-sub-content",className:A("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 km={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 Li(r){return km[r]||{displayName:r.charAt(0).toUpperCase()+r.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Cm(r,s,t){const n=Li(r);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=xn(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 xn(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 Mm(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(`
|
|
4
|
-
`):String(r)}const _i=l.createContext(null),Xs=()=>{const r=l.useContext(_i);if(!r)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return r},Am=({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(Ne,{size:"sm",variant:"ghost",className:A("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(lc,{className:"h-3 w-3"}):e.jsx(cc,{className:"h-3 w-3"})})},Dm=l.lazy(()=>Ws(()=>import("./MonacoDiffViewer-BsVn1wGg.js"),__vite__mapDeps([0,1,2,3,4])).then(r=>({default:r.MonacoDiffViewer}))),Em=r=>{const{index:s,working_dir:t}=r;return s==="A"||t==="A"||s==="?"||t==="?"},ma=(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]})},Tm=l.memo(({changedFiles:r,selectedFile:s,selectedFileEntry:t,onSelectFile:n})=>r.length===0?null:e.jsxs(Ft,{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}),ma(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(ft,{className:"size-4 opacity-50"})]})}),e.jsx(_t,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Sm,{value:s??"",onValueChange:n,children:r.map(o=>e.jsx(Nm,{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}),ma(o.insertions,o.deletions)]})},o.path))})})]})),Im=l.memo(({fileDiff:r,activeFilePath:s,isDiffLoading:t,diffError:n,onRetry:o,renderSideBySide:a,allowResponsive:i})=>{const c=l.useMemo(()=>s&&xn(s)||"text",[s]);return t?e.jsxs("div",{className:"flex h-full items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(At,{size:16,className:"animate-spin"}),"Loading diff…"]}):n?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 text-center",children:[e.jsx("p",{className:"text-sm text-destructive",children:n}),e.jsx(Ne,{size:"sm",onClick:o,children:"Retry"})]}):!r||!r.original&&!r.modified?e.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"No changes detected for this file"}):e.jsx("div",{className:"flex h-full w-full",children:e.jsx(l.Suspense,{fallback:e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(At,{size:16,className:"animate-spin"}),"Loading diff viewer…"]}),children:e.jsx(Dm,{original:r.original,modified:r.modified,language:c,renderSideBySide:a,allowResponsive:i})})})}),Pm=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=we(),{currentDirectory:n}=dt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},Rm=()=>{const{git:r}=Xs(),s=Pm(),t=Ii(s??null),n=Ti(s??null),o=xt($=>$.isLoadingStatus),{setActiveDirectory:a,fetchStatus:i,setDiff:c}=xt(),[d,u]=l.useState(null),f=l.useRef(null),[m,p]=l.useState(!1),[h,g]=l.useState(null),[y,b]=l.useState(null),w=Fe($=>$.pendingDiffFile),j=Fe($=>$.setPendingDiffFile),x=Fe($=>$.diffLayoutPreference),v=Fe($=>$.diffFileLayout),N=Fe($=>$.setDiffFileLayout),S=xt(l.useCallback($=>s?$.directories.get(s)?.lastStatusChange??0:0,[s])),C=l.useCallback(($,Y)=>{if(!$)return null;const ie=xt.getState().directories.get($);if(!ie)return null;const P=ie.diffCache.get(Y);return!P||P.fetchedAt<(ie.lastStatusChange||0)?null:P},[]),D=l.useCallback($=>{f.current=$,u($),g(null);const Y=C(s,$);Y?(b({original:Y.original,modified:Y.modified}),p(!1)):(b(null),p(!0))},[s,C]);l.useEffect(()=>{s&&(a(s),xt.getState().directories.get(s)?.status||i(s,r))},[s,a,i,r]),l.useEffect(()=>{w&&(D(w),j(null))},[w,D,j]),l.useEffect(()=>{f.current=d},[d]);const k=l.useMemo(()=>{if(!n?.files)return[];const $=n.diffStats??{};return n.files.map(Y=>({...Y,insertions:$[Y.path]?.insertions??0,deletions:$[Y.path]?.deletions??0,isNew:Em(Y)})).sort((Y,ie)=>Y.path.localeCompare(ie.path))},[n]),M=l.useMemo(()=>d?k.find($=>$.path===d)??null:null,[k,d]),E=l.useMemo(()=>{if(!M)return null;const $=v[M.path];return $||(x==="inline"||x==="side-by-side"?x:M.isNew?"inline":"side-by-side")},[M,v,x]);l.useEffect(()=>{if(!d&&!w&&k.length>0){const $=k[0].path;D($)}},[k,d,w,D]),l.useEffect(()=>{d&&k.length>0&&(k.some(Y=>Y.path===d)||(u(null),f.current=null,b(null),g(null)))},[k,d]);const I=l.useCallback(async()=>{if(!s||!M){b(null),g(null),p(!1);return}const $=M.path,Y=C(s,$);if(Y){b({original:Y.original,modified:Y.modified}),g(null),p(!1);return}p(!0),g(null);try{const ie=await r.getGitFileDiff(s,{path:M.path}),P={original:ie.original??"",modified:ie.modified??""};c(s,$,P),b(P)}catch(ie){const P=ie instanceof Error?ie.message:"Failed to load diff";g(P),he.error(P)}finally{p(!1)}},[s,r,M,C,c,S]);l.useEffect(()=>{I()},[I]);const L=M?.path??"",F=()=>{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(o&&!n)return e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(At,{size:16,className:"animate-spin"}),"Loading repository status…"]});if(t===!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(k.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"});if(!M)return e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a file to inspect its diff"});const Y=(E??"side-by-side")==="side-by-side",ie=!!v[M.path],P=x==="dynamic"&&!ie;return e.jsx("div",{className:"flex flex-1 min-h-0 px-3 py-3",children:e.jsx(Im,{fileDiff:y,activeFilePath:L,isDiffLoading:m,diffError:h,onRetry:I,renderSideBySide:Y,allowResponsive:P})})};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(qn,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:o&&!n?"Loading changes…":`${k.length} ${k.length===1?"file":"files"} changed`})]}),e.jsx(Tm,{changedFiles:k,selectedFile:d,selectedFileEntry:M,onSelectFile:D}),e.jsx("div",{className:"flex-1"}),M&&E&&e.jsx(Am,{mode:E==="side-by-side"?"side-by-side":"unified",onModeChange:$=>{if(!M)return;const Y=$==="side-by-side"?"side-by-side":"inline";N(M.path,Y)}})]}),F()]})},Fm=()=>{const{git:r}=Xs(),{currentSessionId:s,sessions:t,worktreeMetadata:n}=we(),{currentDirectory:o}=dt(),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:u,fetchStatus:f}=xt(),m=jm(d??null);return l.useEffect(()=>{d&&(u(d),xt.getState().directories.get(d)?.status||f(d,r))},[d,u,f,r]),m},Lm=()=>{const r=Fe(d=>d.setSessionSwitcherOpen),s=Fe(d=>d.toggleSidebar),{isMobile:t}=wt(),[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(gr,{className:"h-5 w-5"})})})},fa=()=>{const r=Fe(P=>P.setSessionSwitcherOpen),s=Fe(P=>P.toggleSidebar),t=Fe(P=>P.isSidebarOpen),n=Fe(P=>P.sidebarWidth),o=Fe(P=>P.activeMainTab),a=Fe(P=>P.setActiveMainTab),{getCurrentModel:i}=yt(),c=we(P=>P.getContextUsage),{isMobile:d}=wt(),u=Fm(),f=l.useRef(null),[m,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||""),[]);ge.useEffect(()=>{if(typeof window>"u")return;const P=typeof window.opencodeDesktop<"u";p(P)},[]);const g=i(),y=g&&typeof g.limit=="object"&&g.limit!==null?g.limit:null,b=y&&typeof y.context=="number"?y.context:0,w=y&&typeof y.output=="number"?y.output:0,j=c(b,w),[x,v]=l.useState(!1),N=Fe(P=>P.isSessionSwitcherOpen),S=l.useCallback(()=>{if(d){r(!N);return}s()},[d,N,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",D=l.useMemo(()=>m&&h?t?"pl-0":"pl-[8.0rem]":"pl-3",[m,h,t]),k=l.useCallback(()=>{if(typeof document>"u")return;const P=f.current?.getBoundingClientRect().height;P&&document.documentElement.style.setProperty("--oc-header-height",`${P}px`)},[]);ge.useEffect(()=>{if(typeof window>"u")return;k();const P=f.current;if(!P||typeof ResizeObserver>"u")return()=>{};const B=new ResizeObserver(()=>{k()});return B.observe(P),window.addEventListener("resize",k),window.addEventListener("orientationchange",k),()=>{B.disconnect(),window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k)}},[k]),ge.useEffect(()=>{k()},[k,d,x]);const M=l.useCallback(P=>P>=1e6?`${(P/1e6).toFixed(1)}M`:P>=1e3?`${(P/1e3).toFixed(1)}K`:P.toFixed(1).replace(/\.0$/,""),[]),E=l.useCallback(async P=>{if(!P.target.closest("button, a, input, select, textarea")&&P.button===0&&m)try{const{getCurrentWindow:B}=await Ws(async()=>{const{getCurrentWindow:ye}=await import("./vendor-.pnpm-B1ce5n1Z.js").then(se=>se.bL);return{getCurrentWindow:ye}},__vite__mapDeps([1,2]));await B().startDragging()}catch(B){console.error("Failed to start window dragging:",B)}},[m]),I=l.useCallback(async P=>{if(P.button===0&&m)try{const{getCurrentWindow:B}=await Ws(async()=>{const{getCurrentWindow:ye}=await import("./vendor-.pnpm-B1ce5n1Z.js").then(se=>se.bL);return{getCurrentWindow:ye}},__vite__mapDeps([1,2]));await B().startDragging()}catch(B){console.error("Failed to start window dragging:",B)}},[m]),L=l.useMemo(()=>[{id:"chat",label:"Chat",icon:dc},{id:"diff",label:"Diff",icon:vs,badge:u>0?u:void 0},{id:"terminal",label:"Terminal",icon:Ss},{id:"git",label:"Git",icon:Ct}],[u]);ge.useEffect(()=>{const P=B=>{if((B.metaKey||B.ctrlKey)&&!B.shiftKey&&!B.altKey){const te=parseInt(B.key,10);te>=1&&te<=L.length&&(B.preventDefault(),a(L[te-1].id))}};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[L,a]);const F=(P,B)=>{const te=o===P.id,ye=P.icon,se=P.id==="chat",V=P.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>a(P.id),onMouseDown:te?I:void 0,className:A("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",te?"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",te?"text-foreground":"text-muted-foreground",te&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",te&&se&&t&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",se&&!(m&&h&&t)&&"border-l",V&&"border-r",se&&!d&&"min-w-[165px]"),style:{...te&&se&&t?{"--sidebar-w":m&&h?`${n}px`:"64px"}:{},...se&&!(m&&h&&t)||V?{borderColor:"var(--interactive-border)"}:{}},"aria-selected":te,role:"tab",children:[d?e.jsx(ye,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ye,{size:16}),e.jsx("span",{children:P.label})]}),se&&!d&&j&&j.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(ua,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit??0,size:"compact"})}),P.badge!==void 0&&P.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:P.badge})]}),!B&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},P.id)},$=()=>e.jsxs("div",{onMouseDown:E,className:A("app-region-drag relative flex h-12 select-none items-center",D),role:"tablist","aria-label":"Main navigation",children:[!(m&&h)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:S,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(gr,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:L.map((P,B)=>F(P,B===L.length-1))}),e.jsx("div",{className:"flex-1"})]}),Y=()=>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:S,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(gr,{className:"h-5 w-5"})}),j&&j.totalTokens>0&&o==="chat"&&e.jsx(ua,{totalTokens:j.totalTokens,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.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:L.map(P=>{const B=o===P.id,te=P.icon;return e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>a(P.id),"aria-label":P.label,"aria-selected":B,role:"tab",className:A(C,B&&"text-foreground"),children:[e.jsx(te,{className:"h-5 w-5"}),P.badge!==void 0&&P.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:P.badge})]})}),e.jsx(rt,{children:e.jsx("p",{children:P.label})})]},P.id)})}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon","aria-expanded":x,"aria-controls":"mobile-header-details",onClick:()=>v(P=>!P),className:"app-region-no-drag h-8 w-8",children:x?e.jsx(lo,{className:"h-4 w-4"}):e.jsx(ft,{className:"h-4 w-4"})})]})]}),x&&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:j&&j.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:M(j.totalTokens)})]}),e.jsxs("p",{className:"typography-meta",children:["Context limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:M(j.contextLimit)})]}),e.jsxs("p",{className:"typography-meta",children:["Output limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:M(j.outputLimit??0)})]})]})]})})})]}),ie=A("header-safe-area border-b relative z-10",m?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:f,className:ie,style:{borderColor:"var(--interactive-border)"},children:d?Y():$()})};function ko({className:r,...s}){return e.jsx("div",{"data-slot":"card",className:A("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",r),...s})}function Oi({className:r,...s}){return e.jsx("div",{"data-slot":"card-header",className:A("@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 $i({className:r,...s}){return e.jsx("div",{"data-slot":"card-title",className:A("leading-none font-semibold",r),...s})}function zi({className:r,...s}){return e.jsx("div",{"data-slot":"card-content",className:A("px-6",r),...s})}class ls extends l.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,t){this.setState({error:s,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(ko,{className:"w-full max-w-md",children:[e.jsx(Oi,{className:"text-center",children:e.jsxs($i,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Kn,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(zi,{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(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(qs,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}const Dr={checking:!1,available:!0,downloading:!1,downloaded:!1,info:{available:!0,version:"99.0.0-test",currentVersion:"0.0.0",body:"Test update for UI development"},progress:null,error:null},pa=()=>typeof window>"u"?!1:window.__OPENCHAMBER_MOCK_UPDATE__===!0,_m=(r=!0)=>{const[s,t]=ge.useState({checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null}),[n,o]=ge.useState(pa),[a,i]=ge.useState(Dr);ge.useEffect(()=>{const p=setInterval(()=>{const h=pa();h!==n&&(o(h),h&&i(Dr))},500);return()=>clearInterval(p)},[n]);const c=ge.useCallback(async()=>{if(n){i(Dr);return}if(Rt()){t(p=>({...p,checking:!0,error:null}));try{const p=await Wd();t(h=>({...h,checking:!1,available:p?.available??!1,info:p}))}catch(p){t(h=>({...h,checking:!1,error:p instanceof Error?p.message:"Failed to check for updates"}))}}},[n]),d=ge.useCallback(async()=>{if(n){i(g=>({...g,downloading:!0}));let p=0;const h=setInterval(()=>{p+=20,i(g=>({...g,progress:{downloaded:p*1e3,total:1e5}})),p>=100&&(clearInterval(h),i(g=>({...g,downloading:!1,downloaded:!0,progress:null})))},500);return}if(!(!Rt()||!s.available)){t(p=>({...p,downloading:!0,error:null,progress:null}));try{await Ud(p=>{t(h=>({...h,progress:p}))}),t(p=>({...p,downloading:!1,downloaded:!0}))}catch(p){t(h=>({...h,downloading:!1,error:p instanceof Error?p.message:"Failed to download update"}))}}},[n,s.available]),u=ge.useCallback(async()=>{if(!n&&!(!Rt()||!s.downloaded))try{await Vd()}catch(p){t(h=>({...h,error:p instanceof Error?p.message:"Failed to restart"}))}},[n,s.downloaded]),f=ge.useCallback(()=>{if(n){i(Dr);return}t(p=>({...p,available:!1,downloaded:!1,info:null}))},[n]);return ge.useEffect(()=>{if(r&&(Rt()||n)){const p=setTimeout(()=>{c()},3e3);return()=>clearTimeout(p)}},[r,c,n]),{...n?a:s,checkForUpdates:c,downloadUpdate:d,restartToUpdate:u,dismiss:f}};let Er=0;function ms({...r}){return e.jsx(uc,{"data-slot":"dialog",...r})}function Bi({...r}){return e.jsx(xc,{"data-slot":"dialog-trigger",...r})}function Om({...r}){return e.jsx(pc,{"data-slot":"dialog-portal",...r})}const Hi=ge.forwardRef(({className:r,...s},t)=>(ge.useEffect(()=>(Er+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Er=Math.max(0,Er-1),Er===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(ni,{ref:t,"data-slot":"dialog-overlay",className:A("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",r),...s})));Hi.displayName=ni.displayName;function fs({className:r,children:s,showCloseButton:t=!0,...n}){return e.jsxs(Om,{"data-slot":"dialog-portal",children:[e.jsx(Hi,{className:"rounded-none"}),e.jsxs(mc,{"data-slot":"dialog-content",className:A("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(fc,{"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(Zt,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ps({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:A("flex flex-col gap-2 text-center sm:text-left",r),...s})}function vr({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-footer",className:A("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",r),...s})}function hs({className:r,...s}){return e.jsx(hc,{"data-slot":"dialog-title",className:A("typography-markdown leading-none font-semibold text-foreground",r),...s})}function Ls({className:r,...s}){return e.jsx(gc,{"data-slot":"dialog-description",className:A("text-muted-foreground typography-ui-label",r),...s})}const ha="https://github.com/btriapitsyn/openchamber/releases",$m=({open:r,onOpenChange:s,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d})=>{const u=t?.version?`${ha}/tag/v${t.version}`:ha,f=a?.total?Math.round(a.downloaded/a.total*100):0;return e.jsx(ms,{open:r,onOpenChange:s,children:e.jsxs(fs,{className:"max-w-md",children:[e.jsx(ps,{children:e.jsxs(hs,{className:"flex items-center gap-2",children:[e.jsx(yc,{className:"h-5 w-5 text-primary"}),"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t?.currentVersion&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Current version"}),e.jsx("span",{className:"font-mono",children:t.currentVersion})]}),t?.version&&e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"New version"}),e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),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:u,target:"_blank",rel:"noopener noreferrer",className:A("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","border border-border","hover:bg-accent hover:text-accent-foreground","transition-colors"),children:[e.jsx(Yn,{className:"h-4 w-4"}),"View Release Notes"]}),!o&&!n&&e.jsxs("button",{onClick:c,className:A("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(un,{className:"h-4 w-4"}),"Download Update"]}),n&&e.jsxs("button",{disabled:!0,className:A("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(bc,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),o&&e.jsxs("button",{onClick:d,className:A("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(qs,{className:"h-4 w-4"}),"Restart to Update"]})]})]})]})})},an=264,ga=200,xa=500,zm=40,Bm=({isOpen:r,isMobile:s,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a}=Fe(),[i,c]=l.useState(!1),d=l.useRef(0),u=l.useRef(n||an),[f,m]=l.useState(!1),p=_m(),[h,g]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const v=typeof window.opencodeDesktop<"u";g(v)},[]),l.useEffect(()=>{if(s||!i)return;const v=S=>{const C=S.clientX-d.current,D=Math.min(xa,Math.max(ga,u.current+C));o(D)},N=()=>{c(!1)};return window.addEventListener("pointermove",v),window.addEventListener("pointerup",N,{once:!0}),()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",N)}},[s,i,o]),l.useEffect(()=>{s&&i&&c(!1)},[s,i]);const b=l.useCallback(async v=>{if(v.button===0&&h)try{const{getCurrentWindow:N}=await Ws(async()=>{const{getCurrentWindow:C}=await import("./vendor-.pnpm-B1ce5n1Z.js").then(D=>D.bL);return{getCurrentWindow:C}},__vite__mapDeps([1,2]));await N().startDragging()}catch(N){console.error("Failed to start window dragging from sidebar:",N)}},[h]);if(s)return null;const w=r?Math.min(xa,Math.max(ga,n||an)):0,j=h&&y,x=v=>{r&&(c(!0),d.current=v.clientX,u.current=w,v.preventDefault())};return e.jsxs("aside",{className:A("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:`${w}px`,minWidth:`${w}px`,maxWidth:`${w}px`,pointerEvents:r?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!r||w===0,children:[r&&e.jsx("div",{className:A("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:x,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:A("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!r&&"pointer-events-none select-none opacity-0"),style:{width:`${w}px`,overflowX:"hidden"},"aria-hidden":!r,children:[j&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${zm}px`},onMouseDown:b,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:t})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:A("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(Kr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),(p.available||p.downloaded)&&e.jsxs("button",{onClick:()=>m(!0),className:A("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(un,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]})]})}),e.jsx($m,{open:f,onOpenChange:m,info:p.info,downloading:p.downloading,downloaded:p.downloaded,progress:p.progress,error:p.error,onDownload:p.downloadUpdate,onRestart:p.restartToUpdate})]})]})},Wi=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:co},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:mn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:Ks},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ct},{id:"settings",label:"Appearance",description:"Fine-tune themes, fonts, and typography across the interface.",icon:wc}],Hm={},Ui={},Vi={};Wi.forEach(r=>{Hm[r.id]=r.label,Ui[r.id]=r.description,Vi[r.id]=r});const ya=Ui,Wm=Vi;function gs({className:r,variant:s,...t}){return e.jsx(Ne,{variant:s,size:"sm",className:A("h-7 px-2 py-0",r),...t})}function bt({className:r,type:s,...t}){return e.jsx("input",{type:s,"data-slot":"input",className:A("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 Co=({containerRef:r,minThumbSize:s=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=l.useState(!1),[c,d]=l.useState({length:0,offset:0}),[u,f]=l.useState({length:0,offset:0}),m=l.useRef(null),p=l.useRef(null),h=l.useRef(!1),g=l.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),y=l.useRef(null),b=l.useCallback(()=>{const k=r.current;if(!k)return;const{scrollHeight:M,clientHeight:E,scrollTop:I,scrollWidth:L,clientWidth:F,scrollLeft:$}=k,Y=8;if(M>E){const ie=Math.max(E-Y*2,0),P=E/M*ie,B=Math.max(s,Math.min(ie,P)),te=Math.max(ie-B,0),ye=Math.max(M-E,1),se=I/ye*te;d({length:B,offset:se})}else d({length:0,offset:0});if(!o&&L>F){const ie=Math.max(F-Y*2,0),P=F/L*ie,B=Math.max(s,Math.min(ie,P)),te=Math.max(ie-B,0),ye=Math.max(L-F,1),se=$/ye*te;f({length:B,offset:se})}else f({length:0,offset:0})},[r,s,o]),w=l.useCallback(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(()=>i(!1),t)},[t]),j=l.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{b(),i(!0),w()})},[w,b]);l.useEffect(()=>{const k=r.current;if(!k)return;b(),i(!0),w(),k.addEventListener("scroll",j,{passive:!0});const M=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null;M?.observe(k);const E=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return E?.observe(k,{childList:!0,subtree:!0,characterData:!0}),()=>{k.removeEventListener("scroll",j),M?.disconnect(),E?.disconnect(),m.current&&clearTimeout(m.current),p.current&&cancelAnimationFrame(p.current)}},[r,j,w,b]);const x=(k,M)=>{const E=r.current;E&&(h.current=!0,g.current={pointerX:k.clientX,pointerY:k.clientY,scrollTop:E.scrollTop,scrollLeft:E.scrollLeft},y.current=M,i(!0),m.current&&clearTimeout(m.current),k.currentTarget.setPointerCapture(k.pointerId))},v=k=>{if(!h.current)return;const M=r.current;if(!M)return;const E=y.current;if(E==="vertical"){const{pointerY:I,scrollTop:L}=g.current,F=k.clientY-I,$=M.clientHeight,Y=Math.max($-c.length,1),ie=Math.max(M.scrollHeight-M.clientHeight,1),P=F/Y*ie;M.scrollTop=L+P}else if(E==="horizontal"){const{pointerX:I,scrollLeft:L}=g.current,F=k.clientX-I,$=M.clientWidth,Y=Math.max($-u.length,1),ie=Math.max(M.scrollWidth-M.clientWidth,1),P=F/Y*ie;M.scrollLeft=L+P}},N=k=>{h.current&&(h.current=!1,k.currentTarget.releasePointerCapture(k.pointerId),w())},S=c.length>0,C=u.length>0;if(!S&&!C)return null;const D=8;return e.jsxs("div",{className:A("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[S&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${D+c.offset}px`,right:`${D/2}px`},onPointerDown:k=>x(k,"vertical"),onPointerMove:v,onPointerUp:N,onPointerCancel:N}),C&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${D+u.offset}px`,bottom:`${D/2}px`},onPointerDown:k=>x(k,"horizontal"),onPointerMove:v,onPointerUp:N,onPointerCancel:N})]})},Ge=l.forwardRef(({className:r,outerClassName:s,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,...f},m)=>{const p=l.useRef(null);return l.useImperativeHandle(m,()=>p.current,[]),e.jsxs("div",{className:A("relative flex flex-col min-h-0 w-full overflow-hidden",s),children:[e.jsx(i,{ref:p,className:A("overlay-scrollbar-target overlay-scrollbar-container",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",r),style:n,...f,children:t}),e.jsx(Co,{containerRef:p,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});Ge.displayName="ScrollableOverlay";const Um=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedAgentName:o,agents:a,setSelectedAgent:i,deleteAgent:c,loadAgents:d}=Ys(),{setSidebarOpen:u}=Fe(),{isMobile:f}=wt();l.useEffect(()=>{d()},[d]);const m=()=>{if(!r.trim()){he.error("Agent name is required");return}if(a.some(w=>w.name===r)){he.error("An agent with this name already exists");return}i(r),s(""),n(!1),f&&u(!1)},p=async w=>{if(w.builtIn){he.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${w.name}"?`)&&(await c(w.name)?he.success(`Agent "${w.name}" deleted successfully`):he.error("Failed to delete agent"))},h=w=>{const j=w.name;let x=1,v=`${j} Copy`;for(;a.some(N=>N.name===v);)x++,v=`${j} Copy ${x}`;i(v),n(!1),f&&u(!1)},g=w=>{switch(w){case"primary":return e.jsx(xr,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(ai,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(oi,{className:"h-3 w-3 text-primary"});default:return null}},y=a.filter(w=>w.builtIn),b=a.filter(w=>!w.builtIn);return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(ms,{open:t,onOpenChange:n,children:[e.jsx("div",{className:A("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(Bi,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(Qt,{className:"size-4"})})})]})]})}),e.jsx(Ge,{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(Yr,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[y.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),y.map(w=>e.jsx(ba,{agent:w,isSelected:o===w.name,onSelect:()=>{i(w.name),f&&u(!1)},onDuplicate:()=>h(w),getAgentModeIcon:g},w.name))]}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Agents"}),b.map(w=>e.jsx(ba,{agent:w,isSelected:o===w.name,onSelect:()=>{i(w.name),f&&u(!1)},onDelete:()=>p(w),onDuplicate:()=>h(w),getAgentModeIcon:g},w.name))]})]})}),e.jsxs(fs,{children:[e.jsxs(ps,{children:[e.jsx(hs,{children:"Create New Agent"}),e.jsx(Ls,{children:"Enter a unique name for your new agent"})]}),e.jsx(bt,{value:r,onChange:w=>s(w.target.value),placeholder:"Agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:w=>{w.key==="Enter"&&m()}}),e.jsxs(vr,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(gs,{onClick:m,children:"Create"})]})]})]})})},ba=({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:A("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(Ft,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(Ne,{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(fn,{className:"h-3.5 w-3.5"})})}),e.jsxs(_t,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(mt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(Gt,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),!r.builtIn&&n&&e.jsxs(mt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ns,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})});function pr({className:r,variant:s,...t}){return e.jsx(Ne,{variant:s,size:"sm",className:A("h-6 px-2 text-xs",r),...t})}const Rs=ge.forwardRef(({className:r,...s},t)=>e.jsx(Ge,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:A("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}));Rs.displayName="Textarea";const wa="mobile-overlay-root",Vm=()=>{if(typeof document>"u")return null;let r=document.getElementById(wa);return r||(r=document.createElement("div"),r.id=wa,document.body.appendChild(r)),r},Bt=({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=Vm()),l.useEffect(()=>{if(!r)return;const u=document.body.style.overflow;document.body.style.overflow="hidden";const f=m=>{m.key==="Escape"&&t()};return document.addEventListener("keydown",f),()=>{document.body.style.overflow=u,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:A("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:u=>u.stopPropagation(),children:[(()=>{const u=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(Zt,{className:"h-4 w-4"})});return i?i(u):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}),u]})})(),e.jsx(Ge,{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 vc.createPortal(d,c.current)},Gm="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",qm="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",Km=Object.assign({"../assets/provider-logos/gocode.svg":Gm,"../assets/provider-logos/kimi-for-coding.svg":qm}),to=new Map;for(const[r,s]of Object.entries(Km)){const t=r.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&s&&to.set(t[1].toLowerCase(),s)}function Gi(r){const s=r?.toLowerCase()??null,t=s?to.has(s):!1,n=s?to.get(s)??null:null,[o,a]=ge.useState(t?"local":"remote");ge.useEffect(()=>{a(t?"local":"remote")},[t,s]);const i=ge.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 Jt=({providerId:r,alt:s,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=Gi(r),c=l.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:s||`${r} logo`,className:A("dark:invert",t),onError:c})},qi=({providerId:r,modelId:s,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=yt(),i=Fe(x=>x.isMobile),{isMobile:c}=wt(),d=i||c,[u,f]=l.useState(!1),[m,p]=l.useState(new Set),h=()=>f(!1),g=x=>{p(v=>{const N=new Set(v);return N.has(x)?N.delete(x):N.add(x),N})},y=x=>{const v=x?.name||x?.id||"",N=String(v);return N.length>40?N.substring(0,37)+"...":N},b=(x,v)=>{const N=`${x}/${v}`;return a.get(N)},w=(x,v)=>{t(x,v)},j=()=>d?e.jsx(Bt,{open:u,onClose:h,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[o.map(x=>{const v=Array.isArray(x.models)?x.models:[];if(v.length===0)return null;const N=x.id===r,S=m.has(x.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(x.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{providerId:x.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:x.name}),N&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),S?e.jsx(ft,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"})]}),S&&e.jsx("div",{className:"border-t border-border/20",children:v.map(C=>{const D=x.id===r&&C.id===s,k=b(x.id,C.id);return e.jsxs("button",{type:"button",className:A("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",D?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{w(x.id,C.id),h()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:y(C)}),typeof k?.description=="string"&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:k.description})]}),D&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},C.id)})})]},x.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{w("",""),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:A("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(Jt,{providerId:r,className:"h-3.5 w-3.5"}):e.jsx(as,{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(ft,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Ft,{children:[e.jsx(Lt,{asChild:!0,children:e.jsxs("div",{className:A("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(Jt,{providerId:r,className:"h-3 w-3 flex-shrink-0"}),e.jsx(as,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(as,{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(ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(_t,{className:"max-w-[300px]",children:[o.map(x=>{const v=Array.isArray(x.models)?x.models:[];return v.length===0?e.jsxs(mt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Jt,{providerId:x.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),x.name," (No models)"]},x.id):e.jsxs(Pi,{children:[e.jsxs(Ri,{className:"typography-meta",children:[e.jsx(Jt,{providerId:x.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),x.name]}),e.jsx(Fi,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ge,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:v.map(N=>{const S=b(x.id,N.id);return e.jsx(mt,{className:"typography-meta",onSelect:()=>{w(x.id,N.id)},children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:y(N)}),typeof S?.description=="string"&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:S.description})]})},N.id)})})})]},x.id)}),e.jsx(mt,{className:"typography-meta",onSelect:()=>w("",""),children:e.jsx("span",{className:"text-muted-foreground",children:"No model (optional)"})})]})]}),j()]})},Ym=()=>{const{tools:r}=Xs(),[s,t]=l.useState([]),[n,o]=l.useState(!0),[a,i]=l.useState(null);return l.useEffect(()=>{let c=!1;return(async()=>{o(!0),i(null);try{const u=await r.getAvailableTools();if(c)return;t(u)}catch(u){if(c)return;const f=u instanceof Error?u.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}},Jm=()=>{const{selectedAgentName:r,getAgentByName:s,createAgent:t,updateAgent:n,agents:o}=Ys();yt();const{tools:a}=Ym(),i=r?s(r):null,c=r&&!i,[d,u]=l.useState(""),[f,m]=l.useState(""),[p,h]=l.useState("subagent"),[g,y]=l.useState(""),[b,w]=l.useState(void 0),[j,x]=l.useState(void 0),[v,N]=l.useState(""),[S,C]=l.useState({}),[D,k]=l.useState("allow"),[M,E]=l.useState("allow"),[I,L]=l.useState("ask"),[F,$]=l.useState(!1);l.useEffect(()=>{if(c)u(r||""),m(""),h("subagent"),y(""),w(void 0),x(void 0),N(""),C({}),k("allow"),E("allow"),L("ask");else if(i&&(u(i.name),m(i.description||""),h(i.mode||"subagent"),i.model?.providerID&&i.model?.modelID?y(`${i.model.providerID}/${i.model.modelID}`):y(""),w(i.temperature),x(i.topP),N(i.prompt||""),C(i.tools||{}),i.permission)){const B=i.permission.edit;(B==="allow"||B==="ask"||B==="deny"||B==="full")&&k(B),i.permission.webfetch&&E(i.permission.webfetch),typeof i.permission.bash=="string"&&L(i.permission.bash)}},[i,c,r,o]);const Y=async()=>{if(!d.trim()){he.error("Agent name is required");return}$(!0);try{const B=g.trim(),te={name:d.trim(),description:f.trim()||void 0,mode:p,model:B===""?null:B,temperature:b,top_p:j,prompt:v.trim()||void 0,tools:Object.keys(S).length>0?S:void 0,permission:{edit:D,webfetch:M,bash:I}};let ye;c?ye=await t(te):ye=await n(d,te),ye?he.success(c?"Agent created successfully":"Agent updated successfully"):he.error(c?"Failed to create agent":"Failed to update agent")}catch(B){console.error("Error saving agent:",B),he.error("An error occurred while saving")}finally{$(!1)}},ie=B=>{C(te=>({...te,[B]:!te[B]}))},P=B=>{const te={};a.forEach(ye=>{te[ye]=B}),C(te)};return r?e.jsxs(Ge,{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(bt,{value:d,onChange:B=>u(B.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(Rs,{value:f,onChange:B=>m(B.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(pr,{variant:p==="primary"?"default":"outline",onClick:()=>h("primary"),className:A("gap-2",p==="primary"?void 0:"text-foreground"),children:[e.jsx(xr,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(pr,{variant:p==="subagent"?"default":"outline",onClick:()=>h("subagent"),className:A("gap-2",p==="subagent"?void 0:"text-foreground"),children:[e.jsx(oi,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(pr,{variant:p==="all"?"default":"outline",onClick:()=>h("all"),className:A("gap-2",p==="all"?void 0:"text-foreground"),children:[e.jsx(ai,{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(qi,{providerId:g?g.split("/")[0]:"",modelId:g?g.split("/")[1]:"",onChange:(B,te)=>{y(B&&te?`${B}/${te}`:"")}})]}),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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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 te=Math.max(0,(b!==void 0?b:.7)-.1);w(parseFloat(te.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(Fo,{className:"h-3.5 w-3.5"})}),e.jsx(bt,{type:"text",inputMode:"decimal",value:b!==void 0?b:"",onChange:B=>{const te=B.target.value;if(te===""){w(void 0);return}const ye=parseFloat(te);!isNaN(ye)&&ye>=0&&ye<=2&&w(ye)},onBlur:B=>{const te=B.target.value;if(te!==""){const ye=parseFloat(te);if(!isNaN(ye)){const se=Math.max(0,Math.min(2,ye));w(parseFloat(se.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 te=Math.min(2,(b!==void 0?b:.7)+.1);w(parseFloat(te.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(Qt,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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 te=Math.max(0,(j!==void 0?j:.9)-.1);x(parseFloat(te.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(Fo,{className:"h-3.5 w-3.5"})}),e.jsx(bt,{type:"text",inputMode:"decimal",value:j!==void 0?j:"",onChange:B=>{const te=B.target.value;if(te===""){x(void 0);return}const ye=parseFloat(te);!isNaN(ye)&&ye>=0&&ye<=1&&x(ye)},onBlur:B=>{const te=B.target.value;if(te!==""){const ye=parseFloat(te);if(!isNaN(ye)){const se=Math.max(0,Math.min(1,ye));x(parseFloat(se.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 te=Math.min(1,(j!==void 0?j:.9)+.1);x(parseFloat(te.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(Qt,{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(Rs,{value:v,onChange:B=>N(B.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(Ne,{variant:"outline",size:"sm",onClick:()=>P(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>P(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(B=>e.jsx("button",{type:"button",onClick:()=>ie(B),className:A("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",S[B]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:B},B))})]}),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(Ne,{size:"sm",variant:D==="full"?"default":"outline",onClick:()=>k("full"),className:"h-6 px-2 text-xs",children:"Full"}),e.jsx(Ne,{size:"sm",variant:D==="allow"?"default":"outline",onClick:()=>k("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:D==="ask"?"default":"outline",onClick:()=>k("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:D==="deny"?"default":"outline",onClick:()=>k("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Controls file editing permissions."}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{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(Ne,{size:"sm",variant:I==="allow"?"default":"outline",onClick:()=>L("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:I==="ask"?"default":"outline",onClick:()=>L("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:I==="deny"?"default":"outline",onClick:()=>L("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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{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(Ne,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>E("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>E("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:M==="deny"?"default":"outline",onClick:()=>E("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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(rt,{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(Ne,{size:"sm",variant:"default",onClick:Y,disabled:F,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(uo,{className:"h-3 w-3"}),F?"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(Yr,{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"})]})})},Xm=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedCommandName:o,commands:a,setSelectedCommand:i,deleteCommand:c,loadCommands:d}=Js(),{setSidebarOpen:u}=Fe(),{isMobile:f}=wt();l.useEffect(()=>{d()},[d]);const m=()=>{if(!r.trim()){he.error("Command name is required");return}const g=r.trim().replace(/\s+/g,"-");if(a.some(y=>y.name===g)){he.error("A command with this name already exists");return}i(g),s(""),n(!1),f&&u(!1)},p=async g=>{window.confirm(`Are you sure you want to delete command "${g.name}"?`)&&(await c(g.name)?he.success(`Command "${g.name}" deleted successfully`):he.error("Failed to delete command"))},h=g=>{const y=g.name;let b=1,w=`${y}-copy`;for(;a.some(j=>j.name===w);)b++,w=`${y}-copy-${b}`;i(w),n(!1),f&&u(!1)};return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(ms,{open:t,onOpenChange:n,children:[e.jsx("div",{className:A("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(Bi,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(Qt,{className:"size-4"})})})]})]})}),e.jsx(Ge,{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(Ss,{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,y)=>g.name.localeCompare(y.name)).map(g=>e.jsx(Zm,{command:g,isSelected:o===g.name,onSelect:()=>{i(g.name),f&&u(!1)},onDelete:()=>p(g),onDuplicate:()=>h(g)},g.name))})}),e.jsxs(fs,{children:[e.jsxs(ps,{children:[e.jsx(hs,{children:"Create New Command"}),e.jsx(Ls,{children:"Enter a unique name for your new slash command"})]}),e.jsx(bt,{value:r,onChange:g=>s(g.target.value),placeholder:"Command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:g=>{g.key==="Enter"&&m()}}),e.jsxs(vr,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(gs,{onClick:m,children:"Create"})]})]})]})})},Zm=({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:A("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(Ft,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(Ne,{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(fn,{className:"h-3.5 w-3.5"})})}),e.jsxs(_t,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(mt,{onClick:a=>{a.stopPropagation(),o()},children:[e.jsx(Gt,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(mt,{onClick:a=>{a.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ns,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})}),Qm=({agentName:r,onChange:s,className:t})=>{const{agents:n,loadAgents:o}=Ys(),a=Fe(h=>h.isMobile),{isMobile:i}=wt(),c=a||i,[d,u]=l.useState(!1);l.useEffect(()=>{o()},[o]);const f=()=>u(!1),m=h=>{s(h)},p=()=>c?e.jsx(Bt,{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:A("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:()=>{m(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:()=>{m(""),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:()=>u(!0),className:A("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(Yr,{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(ft,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Ft,{children:[e.jsx(Lt,{asChild:!0,children:e.jsxs("div",{className:A("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(Yr,{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(ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(_t,{className:"max-w-[300px]",children:[n.map(h=>e.jsx(mt,{className:"typography-meta",onSelect:()=>m(h.name),children:e.jsx("span",{className:"font-medium",children:h.name})},h.name)),e.jsx(mt,{className:"typography-meta",onSelect:()=>m(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),p()]})},ef=()=>{const{selectedCommandName:r,getCommandByName:s,createCommand:t,updateCommand:n,commands:o}=Js(),a=r?s(r):null,i=r&&!a,[c,d]=l.useState(""),[u,f]=l.useState(""),[m,p]=l.useState(""),[h,g]=l.useState(""),[y,b]=l.useState(""),[w,j]=l.useState(!1),[x,v]=l.useState(!1);l.useEffect(()=>{i?(d(r||""),f(""),p(""),g(""),b(""),j(!1)):a&&(d(a.name),f(a.description||""),p(a.agent||""),g(a.model||""),b(a.template||""),j(a.subtask||!1))},[a,i,r,o]);const N=async()=>{if(!c.trim()){he.error("Command name is required");return}if(!y.trim()){he.error("Command template is required");return}v(!0);try{const S=m.trim(),C=h.trim(),D=y.trim(),k={name:c.trim(),description:u.trim()||void 0,agent:S===""?null:S,model:C===""?null:C,template:D,subtask:w};let M;i?M=await t(k):M=await n(c,k),M?he.success(i?"Command created successfully":"Command updated successfully"):he.error(i?"Failed to create command":"Failed to update command")}catch(S){console.error("Error saving command:",S),he.error("An error occurred while saving")}finally{v(!1)}};return r?e.jsxs(Ge,{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(bt,{value:c,onChange:S=>d(S.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(Rs,{value:u,onChange:S=>f(S.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(Qm,{agentName:m,onChange:S=>p(S)}),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(qi,{providerId:h?h.split("/")[0]:"",modelId:h?h.split("/")[1]:"",onChange:(S,C)=>{g(S&&C?`${S}/${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:w,onChange:S=>j(S.target.checked),className:"sr-only"}),e.jsx("div",{className:A("w-5 h-5 rounded border-2 flex items-center justify-center",w?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:w&&e.jsx(ht,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(Rs,{value:y,onChange:S=>b(S.target.value),placeholder:`Your command template here...
|
|
5
|
-
|
|
6
|
-
Use $ARGUMENTS to reference user input.
|
|
7
|
-
Use !\`shell command\` to inject shell output.
|
|
8
|
-
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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(Ne,{size:"sm",variant:"default",onClick:N,disabled:x,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(uo,{className:"h-3 w-3"}),x?"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(Ss,{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"})]})})},Ki=({sectionId:r,variant:s})=>{const t=Wm[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:ya[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:ya[r]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60",children:"Coming soon..."})]})},tf=()=>e.jsx(Ge,{outerClassName:"h-full",className:"px-3 py-2",children:e.jsx(Ki,{sectionId:"providers",variant:"sidebar"})}),sf=()=>e.jsx(Ge,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:e.jsx(Ki,{sectionId:"providers",variant:"page"})}),yn=Mt()(Et(es((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 pu();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 yu("");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 hu(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 gu(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 xu(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:ts(()=>Ot()),partialize:r=>({selectedProfileId:r.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=yn);const rf={branch:Ct,briefcase:po,house:fo,graduation:mo,code:vs,heart:ii},nf={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},of=()=>{const{selectedProfileId:r,profiles:s,globalIdentity:t,setSelectedProfile:n,deleteProfile:o,loadProfiles:a,loadGlobalIdentity:i}=yn(),{setSidebarOpen:c}=Fe(),{isMobile:d}=wt();l.useEffect(()=>{a(),i()},[a,i]);const u=()=>{n("new"),d&&c(!1)},f=async m=>{window.confirm(`Are you sure you want to delete profile "${m.name}"?`)&&(await o(m.id)?he.success(`Profile "${m.name}" deleted successfully`):he.error("Failed to delete profile"))};return e.jsxs("div",{className:"flex h-full flex-col bg-sidebar",children:[e.jsx("div",{className:A("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(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",onClick:u,children:e.jsx(Qt,{className:"size-4"})})]})]})}),e.jsxs(Ge,{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(va,{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(Ct,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:s.map(m=>e.jsx(va,{profile:m,isSelected:r===m.id,onSelect:()=>{n(m.id),d&&c(!1)},onDelete:()=>f(m)},m.id))})]})]})},va=({profile:r,isSelected:s,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=rf[r.icon||"branch"]||Ct,i=nf[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:A("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(Ft,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx(Ne,{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(fn,{className:"h-3.5 w-3.5"})})}),e.jsx(_t,{align:"end",className:"w-fit min-w-20",children:e.jsxs(mt,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ns,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})})},ja=[{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)"}],af=[{key:"branch",Icon:Ct,label:"Branch"},{key:"briefcase",Icon:po,label:"Work"},{key:"house",Icon:fo,label:"Personal"},{key:"graduation",Icon:mo,label:"School"},{key:"code",Icon:vs,label:"Code"}],lf=()=>{const{selectedProfileId:r,getProfileById:s,createProfile:t,updateProfile:n,deleteProfile:o}=yn(),a=l.useMemo(()=>r&&r!=="new"?s(r):null,[r,s]),i=r==="new",c=r==="global",[d,u]=l.useState(""),[f,m]=l.useState(""),[p,h]=l.useState(""),[g,y]=l.useState(""),[b,w]=l.useState("keyword"),[j,x]=l.useState("branch"),[v,N]=l.useState(!1);l.useEffect(()=>{i?(u(""),m(""),h(""),y(""),w("keyword"),x("branch")):a&&(u(a.name),m(a.userName),h(a.userEmail),y(a.sshKey||""),w(a.color||"keyword"),x(a.icon||"branch"))},[a,i,r]);const S=async()=>{if(!f.trim()||!p.trim()){he.error("User name and email are required");return}N(!0);try{const k={name:d.trim()||f.trim(),userName:f.trim(),userEmail:p.trim(),sshKey:g.trim()||null,color:b,icon:j};let M;if(i)M=await t(k);else if(r)M=await n(r,k);else return;M?he.success(i?"Profile created successfully":"Profile updated successfully"):he.error(i?"Failed to create profile":"Failed to update profile")}catch(k){console.error("Error saving profile:",k),he.error("An error occurred while saving")}finally{N(!1)}},C=async()=>{if(!(!r||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(r)?he.success("Profile deleted successfully"):he.error("Failed to delete profile")}catch(k){console.error("Error deleting profile:",k),he.error("An error occurred while deleting")}},D=l.useMemo(()=>ja.find(M=>M.key===b)?.cssVar||"var(--syntax-keyword)",[b]);return r?e.jsxs(Ge,{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(bt,{value:d,onChange:k=>u(k.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:ja.map(k=>e.jsx("button",{onClick:()=>w(k.key),className:A("w-8 h-8 rounded-lg border-2 transition-all",b===k.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:k.cssVar},title:k.label},k.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:af.map(k=>{const M=k.Icon;return e.jsx("button",{onClick:()=>x(k.key),className:A("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",j===k.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:k.label,children:e.jsx(M,{className:"w-4 h-4",style:{color:D}})},k.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(bt,{value:f,onChange:k=>m(k.target.value),placeholder:"John Doe",required:!c,readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!c&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(bt,{type:"email",value:p,onChange:k=>h(k.target.value),placeholder:"john@example.com",required:!c,readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["SSH Key Path",e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(zt,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(rt,{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(bt,{value:g,onChange:k=>y(k.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:c,disabled:c}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!c&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(Ne,{size:"sm",variant:"destructive",onClick:C,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Ns,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:A("flex gap-2",i&&"ml-auto"),children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:S,disabled:v,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(uo,{className:"h-3 w-3"}),v?"Saving...":"Save Profile"]})})]})]})]}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(pn,{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"})]})})},Mo=ge.createContext(void 0);function Zs(){const r=ge.useContext(Mo);if(!r)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return r}function cf(){return ge.useContext(Mo)}const df=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Sa=[{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."}],uf=()=>{const r=Fe(i=>i.showReasoningTraces),s=Fe(i=>i.setShowReasoningTraces),t=Fe(i=>i.diffLayoutPreference),n=Fe(i=>i.setDiffLayoutPreference),{themeMode:o,setThemeMode:a}=Zs();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:df.map(i=>e.jsx(pr,{variant:o===i.value?"default":"outline",className:A(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:Sa.map(i=>e.jsx(pr,{variant:t===i.id?"default":"outline",className:A(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:Sa.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"})]})]})},mf=()=>e.jsx(Ge,{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(uf,{})}),Na=(()=>{const r=Wi.filter(n=>n.id!=="sessions"),s=r.find(n=>n.id==="settings"),t=r.filter(n=>n.id!=="settings");return s?[s,...t]:r})(),ff=({isOpen:r,onClose:s})=>{const[t,n]=l.useState("settings"),[o,a]=l.useState(!1),{isMobile:i}=wt();l.useEffect(()=>{r&&(n("settings"),a(!1))},[r]);const c=l.useCallback(b=>{n(b),i&&a(!1)},[i]),d=l.useCallback(()=>{i&&a(!0)},[i]),u=()=>{if(t==="settings")return null;const b=(()=>{switch(t){case"agents":return e.jsx(Um,{});case"commands":return e.jsx(Xm,{});case"providers":return e.jsx(tf,{});case"git-identities":return e.jsx(of,{});default:return null}})();return i?e.jsx("div",{onClick:d,children:b}):b},f=()=>{switch(t){case"agents":return e.jsx(Jm,{});case"commands":return e.jsx(ef,{});case"providers":return e.jsx(sf,{});case"git-identities":return e.jsx(lf,{});case"settings":return e.jsx(mf,{});default:return null}},m=Na.find(b=>b.id===t),p=i,h=e.jsxs(ps,{className:"border-b border-border/40 px-6 pb-4 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)]",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[i&&o&&e.jsxs(Ne,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(Lo,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx(hs,{className:"typography-ui-header",children:"Settings"})]}),m&&e.jsx(Ls,{className:"typography-meta text-muted-foreground hidden sm:block",children:m.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:Na.map(({id:b,label:w,icon:j})=>{const x=t===b,v=j;return e.jsxs("button",{onClick:()=>c(b),className:A("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",x?"text-primary":"text-muted-foreground hover:text-foreground"),"aria-pressed":x,"aria-label":w,children:[e.jsx(v,{className:A("h-5 w-5 sm:h-4 sm:w-4"),weight:"regular"}),e.jsx("span",{className:"hidden sm:inline",children:w})]},b)})}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[t!=="settings"&&(!i||!o)&&e.jsx("div",{className:A("overflow-hidden border-r bg-sidebar",i&&"w-full border-r-0"),style:i?void 0:{width:`${an}px`,minWidth:`${an}px`},children:e.jsx(ls,{children:u()})}),(t==="settings"||!i||o)&&e.jsx("div",{className:A("flex-1 overflow-hidden bg-background",i&&"w-full"),children:e.jsx(ls,{children:f()})})]})]}),y=e.jsxs("div",{className:"flex h-full flex-col overflow-hidden",children:[!p&&h,g]});return p?e.jsx(Bt,{open:r,onClose:s,title:"Settings",className:"max-w-full",renderHeader:b=>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(Ne,{variant:"ghost",size:"icon",onClick:()=>a(!1),className:"absolute left-0 h-6 w-6 flex-shrink-0",children:[e.jsx(Lo,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Back to sidebar"})]}),e.jsx("span",{className:"typography-ui-header",children:"Settings"})]}),b]}),children:g}):e.jsx(ms,{open:r,onOpenChange:b=>!b&&s(),children:e.jsx(fs,{className:A("flex flex-col gap-0 p-0","h-[88vh] w-[65vw] max-w-[900px]"),children:y})})};function Yi({className:r,...s}){return e.jsx(Fs,{"data-slot":"command",className:A("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",r),...s})}function pf({title:r="Command Palette",description:s="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(ms,{...a,children:[e.jsxs(ps,{className:"sr-only",children:[e.jsx(hs,{children:r}),e.jsx(Ls,{children:s})]}),e.jsx(fs,{className:A("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(Yi,{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 Ji({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(li,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Fs.Input,{"data-slot":"command-input",className:A("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 Xi({className:r,children:s,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(Ge,{as:Fs.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:A("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 Zi({...r}){return e.jsx(Fs.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...r})}function hr({className:r,...s}){return e.jsx(Fs.Group,{"data-slot":"command-group",className:A("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 so({className:r,...s}){return e.jsx(Fs.Separator,{"data-slot":"command-separator",className:A("bg-border -mx-1 h-px",r),...s})}function jt({className:r,...s}){return e.jsx(Fs.Item,{"data-slot":"command-item",className:A("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 Ds({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(Ks,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(lr,{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:A("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",r),...s,children:o.length>0?o.map((a,i)=>e.jsxs(ge.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):s.children})}const hf=()=>{const{isCommandPaletteOpen:r,setCommandPaletteOpen:s,setHelpDialogOpen:t,setSessionCreateDialogOpen:n,setActiveMainTab:o,setSettingsDialogOpen:a,setSessionSwitcherOpen:i,toggleSidebar:c}=Fe(),{createSession:d,setCurrentSession:u,getSessionsByDirectory:f,initializeNewOpenChamberSession:m}=we(),{currentDirectory:p}=dt(),{agents:h}=yt(),{themeMode:g,setThemeMode:y}=Zs(),b=()=>{s(!1)},w=async()=>{const F=await d();F&&m(F.id,h),b()},j=F=>{u(F),b()},x=F=>{y(F),b()},v=()=>{t(!0),b()},N=()=>{n(!0),b()},{isMobile:S}=wt(),C=()=>{if(S){const{isSessionSwitcherOpen:F}=Fe.getState();i(!F)}else c();b()},D=()=>{o("git"),b()},k=()=>{o("terminal"),b()},M=()=>{a(!0),b()},E=()=>{Lu(),b()},I=f(p??""),L=l.useMemo(()=>I.slice(0,5),[I]);return e.jsxs(pf,{open:r,onOpenChange:s,children:[e.jsx(Ji,{placeholder:"Type a command or search..."}),e.jsxs(Xi,{children:[e.jsx(Zi,{children:"No results found."}),e.jsxs(hr,{heading:"Actions",children:[e.jsxs(jt,{onSelect:C,children:[e.jsx(gr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsx(Ds,{children:"Ctrl + L"})]}),e.jsxs(jt,{onSelect:w,children:[e.jsx(Qt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(Ds,{children:"Ctrl + N"})]}),e.jsxs(jt,{onSelect:N,children:[e.jsx(Ct,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(Ds,{children:"Shift + Ctrl + N"})]}),e.jsxs(jt,{onSelect:v,children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsx(Ds,{children:"Ctrl + H"})]}),e.jsxs(jt,{onSelect:D,children:[e.jsx(Ct,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsx(Ds,{children:"Ctrl + G"})]}),e.jsxs(jt,{onSelect:k,children:[e.jsx(Ss,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsx(Ds,{children:"Ctrl + T"})]}),e.jsxs(jt,{onSelect:M,children:[e.jsx(Kr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsx(Ds,{children:"Ctrl + ,"})]}),e.jsxs(jt,{onSelect:E,children:[e.jsx(qs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(so,{}),e.jsxs(hr,{heading:"Theme",children:[e.jsxs(jt,{onSelect:()=>x("light"),children:[e.jsx(jc,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),g==="light"&&e.jsx(ht,{className:"ml-auto h-4 w-4"})]}),e.jsxs(jt,{onSelect:()=>x("dark"),children:[e.jsx(Sc,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),g==="dark"&&e.jsx(ht,{className:"ml-auto h-4 w-4"})]}),e.jsxs(jt,{onSelect:()=>x("system"),children:[e.jsx(ci,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),g==="system"&&e.jsx(ht,{className:"ml-auto h-4 w-4"})]})]}),L.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(so,{}),e.jsx(hr,{heading:"Recent Sessions",children:L.map(F=>e.jsxs(jt,{onSelect:()=>j(F.id),children:[e.jsx(co,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:F.title||"Untitled Session"})]},F.id))})]})]})]})},gf=(r,s)=>{const t=r.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(lo,{className:"h-3.5 w-3.5"},`ctrl-${s}`):t==="shift"||t==="⇧"?e.jsx(kc,{className:"h-3.5 w-3.5"},`shift-${s}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(Ks,{className:"h-3.5 w-3.5"},`cmd-${s}`):e.jsx("span",{className:"text-xs font-medium",children:r.trim()},`key-${s}`)},xf=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:"+"}),gf(t,n)]},`${t}-${n}`))},yf=()=>{const{isHelpDialogOpen:r,setHelpDialogOpen:s}=Fe(),t=[{category:"Navigation & Commands",items:[{keys:["Ctrl + X"],description:"Open Command Palette",icon:Ks},{keys:["Ctrl + H"],description:"Show Keyboard Shortcuts (this dialog)",icon:yr},{keys:["Ctrl + L"],description:"Toggle Session Sidebar",icon:gr}]},{category:"Session Management",items:[{keys:["Ctrl + N"],description:"Create New Session",icon:Qt},{keys:["Shift + Ctrl + N"],description:"Open Session Creator (worktree support)",icon:Ct},{keys:["Ctrl + I"],description:"Focus Chat Input",icon:di},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:cr}]},{category:"Interface",items:[{keys:["⌘ + /","Ctrl + /"],description:"Cycle Theme (Light → Dark → System)",icon:Nc},{keys:["Ctrl + G"],description:"Open Git Panel",icon:Ct},{keys:["Ctrl + T"],description:"Open Terminal",icon:Ss},{keys:["Ctrl + ,"],description:"Open Settings",icon:Kr}]}];return e.jsx(ms,{open:r,onOpenChange:s,children:e.jsxs(fs,{className:"max-w-2xl",children:[e.jsxs(ps,{children:[e.jsxs(hs,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ls,{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:xf(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(yr,{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"})]})]})]})})]})})},Pn=new Set,Rn=new Set,Fn=new Set,Bs={onDeleteRequest(r){return Pn.add(r),()=>{Pn.delete(r)}},requestDelete(r){r.sessions.length&&Pn.forEach(s=>s(r))},onCreateRequest(r){return Rn.add(r),()=>{Rn.delete(r)}},requestCreate(r){const s=r??{};Rn.forEach(t=>t(s))},onDirectoryRequest(r){return Fn.add(r),()=>{Fn.delete(r)}},requestDirectoryDialog(){Fn.forEach(r=>r())}},bf=".openchamber",ka="oc.sessions.groupCollapse",Ca="oc.sessions.expandedParents",Ma=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(",","")},rs=r=>{if(!r)return null;const s=r.replace(/\\/g,"/").replace(/\/+$/,"");return s.length===0?"/":s},wf=(r,s)=>{const t=rs(r),n=Array.from(s.values())[0];if(n?.projectDirectory)return rs(n.projectDirectory);if(!t)return null;const o=`/${bf}`,a=t.indexOf(o);return a>0?t.slice(0,a):t},Aa=({mobileVariant:r=!1})=>{const[s,t]=l.useState(null),[n,o]=l.useState(""),[a,i]=l.useState(null),c=l.useRef(null),[d,u]=l.useState(new Set),[f,m]=l.useState(()=>new Map),p=l.useRef(new Set),h=l.useMemo(()=>Ot(),[]),[g,y]=l.useState(!1),[b,w]=l.useState(new Set),[j,x]=l.useState(null),[v,N]=l.useState(new Set),[S,C]=l.useState(null),D=dt(O=>O.currentDirectory),k=dt(O=>O.homeDirectory),M=dt(O=>O.setDirectory),E=yt(O=>O.agents),I=we(O=>O.getSessionsByDirectory),L=we(O=>O.currentSessionId),F=we(O=>O.setCurrentSession),$=we(O=>O.updateSessionTitle),Y=we(O=>O.shareSession),ie=we(O=>O.unshareSession),P=we(O=>O.sessionMemoryState),B=we(O=>O.sessionActivityPhase),te=we(O=>O.worktreeMetadata),ye=we(O=>O.availableWorktrees),se=we(O=>O.createSession),V=we(O=>O.initializeNewOpenChamberSession),ve=we(O=>O.setSessionDirectory),[Ae,Pe]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{try{const O=h.getItem(ka);if(O){const J=JSON.parse(O);Array.isArray(J)&&w(new Set(J.filter(z=>typeof z=="string")))}const de=h.getItem(Ca);if(de){const J=JSON.parse(de);Array.isArray(J)&&u(new Set(J.filter(z=>typeof z=="string")))}}catch{}},[h]),l.useEffect(()=>{typeof window>"u"||Pe(typeof window.opencodeDesktop<"u")},[]);const je=I(D),De=l.useMemo(()=>[...je].sort((O,de)=>(de.time?.created||0)-(O.time?.created||0)),[je]);l.useEffect(()=>{if(!D){x(null);return}let O=!1;return wo(D).then(de=>{O||x(de)}).catch(()=>{O||x(null)}),()=>{O=!0}},[D]);const ue=l.useMemo(()=>new Map(De.map(O=>[O.id,O])),[De]),X=l.useMemo(()=>{const O=new Map;return De.forEach(de=>{const J=de.parentID;J&&O.set(de.id,J)}),O},[De]),R=l.useMemo(()=>{const O=new Map;return De.forEach(de=>{const J=de.parentID;if(!J)return;const z=O.get(J)??[];z.push(de),O.set(J,z)}),O.forEach(de=>de.sort((J,z)=>(z.time?.created||0)-(J.time?.created||0))),O},[De]);l.useEffect(()=>{L&&u(O=>{const de=new Set(O);let J=X.get(L)||null,z=!1;for(;J;)de.has(J)||(de.add(J),z=!0),J=X.get(J)||null;return z?de:O})},[L,X]);const ne=l.useMemo(()=>wf(D,te),[D,te]);l.useEffect(()=>{const O=new Set;De.forEach(de=>{const J=rs(de.directory??null);J&&O.add(J)}),ne&&O.add(ne),O.forEach(de=>{const J=f.get(de);J&&J!=="unknown"||p.current.has(de)||(p.current.add(de),Se.listLocalDirectory(de).then(()=>{m(z=>{const me=new Map(z);return me.get(de)==="exists"?z:(me.set(de,"exists"),me)})}).catch(()=>{m(z=>{const me=new Map(z);return me.get(de)==="missing"?z:(me.set(de,"missing"),me)})}).finally(()=>{p.current.delete(de)}))})},[De,ne,f]),l.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]);const Z=l.useMemo(()=>jn(D,k),[D,k]),q=l.useMemo(()=>Dt(D,k),[D,k]),_=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."})]}),Q=l.useCallback((O,de)=>{de||F(O)},[F]),U=l.useCallback(async()=>{s&&n.trim()&&(await $(s,n.trim()),t(null),o(""))},[s,n,$]),K=l.useCallback(()=>{t(null),o("")},[]),ee=l.useCallback(async O=>{const de=await Y(O.id);de&&de.share?.url?he.success("Session shared",{description:"You can copy the link from the menu."}):he.error("Unable to share session")},[Y]),re=l.useCallback((O,de)=>{navigator.clipboard.writeText(O).then(()=>{i(de),c.current&&clearTimeout(c.current),c.current=window.setTimeout(()=>{i(null),c.current=null},2e3)}).catch(()=>{he.error("Failed to copy URL")})},[]),ce=l.useCallback(async O=>{await ie(O)?he.success("Session unshared"):he.error("Unable to unshare session")},[ie]),be=l.useCallback(O=>{const de=[],J=z=>{(R.get(z)??[]).forEach(oe=>{de.push(oe),J(oe.id)})};return J(O),de},[R]),ae=we(O=>O.deleteSession),Be=we(O=>O.deleteSessions),qe=l.useCallback(async O=>{const de=be(O.id);if(de.length===0)await ae(O.id)?he.success("Session deleted"):he.error("Failed to delete session");else{const J=[O.id,...de.map(oe=>oe.id)],{deletedIds:z,failedIds:me}=await Be(J);z.length>0&&he.success(`Deleted ${z.length} session${z.length===1?"":"s"}`),me.length>0&&he.error(`Failed to delete ${me.length} session${me.length===1?"":"s"}`)}},[be,ae,Be]),nt=l.useCallback(async O=>{if(!O){he.error("No directory available for session creation");return}if(!g)try{y(!0);const de=await se(void 0,O);if(!de){he.error("Failed to create session");return}V(de.id,E),ve(de.id,O)}catch(de){const J=de instanceof Error?de.message:"Failed to create session";he.error(J)}finally{y(!1)}},[se,V,ve,E,g]),et=l.useCallback(()=>{Bs.requestCreate({worktreeMode:"create"})},[]),st=l.useCallback(()=>{Ae&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(O=>{O.success&&O.path?M(O.path,{showOverlay:!0}):O.error&&O.error!=="Directory selection cancelled"&&he.error("Failed to select directory",{description:O.error})}).catch(O=>{console.error("Desktop: Error selecting directory:",O),he.error("Failed to select directory")}):Bs.requestDirectoryDialog()},[Ae,M]),Ke=l.useCallback(O=>{u(de=>{const J=new Set(de);J.has(O)?J.delete(O):J.add(O);try{h.setItem(Ca,JSON.stringify(Array.from(J)))}catch{}return J})},[h]),He=l.useCallback(O=>{const de=R.get(O.id)??[];return{session:O,children:de.map(J=>He(J))}},[R]),Ee=l.useMemo(()=>{const O=new Map,de=rs(ne??null),J=new Map,z=new Set;ye.forEach(fe=>{if(fe.path){const ke=rs(fe.path)??fe.path;z.add(ke),J.set(ke,fe)}});const me=fe=>{const ke=rs(fe.directory??null),_e=te.get(fe.id),Je=((_e?.path?z.has(rs(_e.path)??_e.path):!1)?_e:null)??(ke?J.get(ke)??null:null),$e=!Je&&(ke&&de?ke===de:!ke&&!!de),Ze=$e?"main":Je?.path??ke??fe.id,Qe=Je?.path??ke??de??null;if(!O.has(Ze)){const ct=$e?"Main workspace":Je?.label||Je?.branch||jn(Qe||"",k)||"Worktree",Nt=Je?.relativePath?Dt(Je.relativePath,k):Qe?Dt(Qe,k):null;O.set(Ze,{id:Ze,label:ct,description:Nt,isMain:$e,worktree:Je,directory:Qe,sessions:[]})}return O.get(Ze)};return De.filter(fe=>{const ke=fe.parentID;return ke?!ue.has(ke):!0}).forEach(fe=>{const ke=me(fe),_e=He(fe);ke.sessions.push(_e)}),O.has("main")||O.set("main",{id:"main",label:"Main workspace",description:de?Dt(de,k):null,isMain:!0,worktree:null,directory:de,sessions:[]}),J.forEach((fe,ke)=>{const _e=fe.path;O.has(_e)||O.set(_e,{id:_e,label:fe.label||fe.branch||jn(ke,k)||"Worktree",description:fe.relativePath?Dt(fe.relativePath,k):Dt(ke,k),isMain:!1,worktree:fe,directory:ke,sessions:[]})}),O.forEach(fe=>{fe.sessions.sort((ke,_e)=>(_e.session.time?.created||0)-(ke.session.time?.created||0))}),Array.from(O.values()).sort((fe,ke)=>fe.isMain!==ke.isMain?fe.isMain?-1:1:(fe.label||"").localeCompare(ke.label||""))},[De,te,ye,ne,k,He,ue]),Ue=l.useCallback(O=>{w(de=>{const J=new Set(de);J.has(O)?J.delete(O):J.add(O);try{h.setItem(ka,JSON.stringify(Array.from(J)))}catch{}return J})},[h]),Le=l.useCallback(O=>{N(de=>{const J=new Set(de);return J.has(O)?J.delete(O):J.add(O),J})},[]),ze=l.useCallback((O,de=0,J)=>{const z=O.session,me=rs(z.directory??null)??rs(J??null),fe=(me?f.get(me):null)==="missing",ke=P.get(z.id),_e=L===z.id,Ye=z.title||"Untitled Session",Je=O.children.length>0,$e=d.has(z.id),Ze=z.summary?.additions,Qe=z.summary?.deletions,ct=typeof Ze=="number"||typeof Qe=="number";if(s===z.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:H=>{H.preventDefault(),U()},children:[e.jsx(bt,{value:n,onChange:H=>o(H.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:H=>{H.key==="Escape"&&K()}}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6 p-0",type:"submit",children:e.jsx(ht,{className:"h-4 w-4"})}),e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6 p-0",type:"button",onClick:K,children:e.jsx(Zt,{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:Ma(z.time?.created||Date.now())}),z.share&&e.jsx(wn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"})]})]},z.id);const Nt=B?.get(z.id)??"idle",gt=Nt==="busy"||Nt==="cooldown",kt=ke&&ke.isZombie?e.jsx(Kn,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(l.Fragment,{children:[e.jsx("div",{className:A("group relative flex items-center rounded-md px-1.5 py-1",_e?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",fe?"opacity-75":"",de>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:fe,onClick:()=>Q(z.id,fe),className:A("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",children:e.jsx("span",{className:A("truncate typography-ui-label font-normal text-foreground",gt&&"animate-pulse [animation-duration:1.8s]"),children:Ye})}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Je?e.jsx("span",{role:"button",tabIndex:0,onClick:H=>{H.stopPropagation(),Ke(z.id)},onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),H.stopPropagation(),Ke(z.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":$e?"Collapse subsessions":"Expand subsessions",children:$e?e.jsx(ft,{className:"h-3 w-3"}):e.jsx(ds,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Ma(z.time?.created||Date.now())}),z.share?e.jsx(wn,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,ct&&((Ze??0)!==0||(Qe??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,Ze??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,Qe??0)]})]}):null,Je?e.jsxs("span",{className:"truncate",children:[O.children.length," ",O.children.length===1?"task":"tasks"]}):null,fe?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Kn,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[kt,e.jsxs(Ft,{children:[e.jsx(Lt,{asChild:!0,children:e.jsx("button",{type:"button",className:A("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:H=>H.stopPropagation(),onKeyDown:H=>H.stopPropagation(),children:e.jsx(fn,{className:r?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(_t,{align:"end",className:"min-w-[180px]",children:[e.jsxs(mt,{onClick:()=>{t(z.id),o(Ye)},className:"[&>svg]:mr-1",children:[e.jsx(as,{className:"mr-1 h-4 w-4"}),"Rename"]}),z.share?e.jsxs(e.Fragment,{children:[e.jsx(mt,{onClick:()=>{z.share?.url&&re(z.share.url,z.id)},className:"[&>svg]:mr-1",children:a===z.id?e.jsxs(e.Fragment,{children:[e.jsx(ht,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Gt,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(mt,{onClick:()=>ce(z.id),className:"[&>svg]:mr-1",children:[e.jsx(Cc,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(mt,{onClick:()=>ee(z),className:"[&>svg]:mr-1",children:[e.jsx(wn,{className:"mr-1 h-4 w-4"}),"Share"]}),e.jsxs(mt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>qe(z),children:[e.jsx(Ns,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Je&&$e?O.children.map(H=>ze(H,de+1,me??J)):null]},z.id)},[f,P,B,L,d,s,n,U,K,Ke,Q,ee,re,ce,qe,a,r]);return e.jsxs("div",{className:A("flex h-full flex-col text-foreground overflow-x-hidden",r?"":Ae?"bg-transparent":"bg-sidebar"),children:[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:st,className:A("group flex min-w-0 flex-1 items-center gap-2 rounded-md px-0 py-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!Ae&&"hover:bg-sidebar/20"),"aria-label":"Change project directory",title:q||"/",children:[e.jsx("span",{className:A("flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground group-hover:text-foreground",!Ae&&"bg-sidebar/60"),children:e.jsx(Ut,{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:Z||"/"})})]}),j?e.jsx("button",{type:"button",onClick:et,className:A("inline-flex h-10 w-7 flex-shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!Ae&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Manage worktrees",children:e.jsx(Mc,{className:"h-[1.125rem] w-[1.125rem] translate-y-px"})}):null]})}),e.jsx(Ge,{outerClassName:"flex-1 min-h-0",className:A("space-y-1 pb-1 pl-2.5 pr-1",""),children:Ee.length===0?_:Ee.map(O=>e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button",onClick:()=>Ue(O.id),className:A("sticky top-0 z-10 pt-1.5 pb-1 w-full text-left cursor-pointer group/header border-b",!Ae&&"bg-sidebar"),style:{borderColor:S===O.id?"var(--color-border)":b.has(O.id)?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>C(O.id),onMouseLeave:()=>C(null),"aria-label":b.has(O.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:O.label}),e.jsx("span",{role:"button",tabIndex:0,"aria-disabled":g,className:A("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",g&&"opacity-40 cursor-default"),"aria-label":"Create session in this group",onClick:de=>{g||(de.stopPropagation(),nt(O.directory))},onKeyDown:de=>{g||(de.key==="Enter"||de.key===" ")&&(de.stopPropagation(),nt(O.directory))},children:e.jsx(Qt,{className:"h-4.5 w-4.5"})})]})}),b.has(O.id)?null:e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const de=v.has(O.id),J=7,z=O.sessions.length,me=de?O.sessions:O.sessions.slice(0,J),oe=z-me.length;return e.jsxs(e.Fragment,{children:[me.map(fe=>ze(fe,0,O.directory)),z===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this worktree yet."}):null,oe>0&&!de?e.jsxs("button",{type:"button",onClick:()=>Le(O.id),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",oe," more ",oe===1?"session":"sessions"]}):null,de&&z>J?e.jsx("button",{type:"button",onClick:()=>Le(O.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]})})()})]},O.id))})]})},vf=ri("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 jf({className:r,variant:s,size:t,...n}){return e.jsx(Ac,{"data-slot":"toggle",className:A(vf({variant:s,size:t,className:r})),...n})}const Qi=()=>{const[r,s]=ge.useState(!1);ge.useEffect(()=>{s(Rt())},[]);const t=ge.useCallback(async a=>r?await zd(a):{success:!0,path:a},[r]),n=ge.useCallback(async a=>r?await Bd(a):{success:!0},[r]),o=ge.useCallback(async a=>r?await Hd(a):{success:!0},[r]);return{isDesktop:r,requestAccess:t,startAccessing:n,stopAccessing:o}},Sf=({currentPath:r,onSelectPath:s,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:c=!1,rootDirectory:d=null,isRootReady:u})=>{const f=l.useMemo(()=>Rt(),[]),[m,p]=l.useState([]),[h,g]=l.useState(new Set),[y,b]=l.useState(!0),[w,j]=l.useState(!1),[x,v]=l.useState(""),[N,S]=l.useState(new Set),[C,D]=l.useState(null),[k,M]=l.useState(""),E=l.useRef(null),{requestAccess:I,startAccessing:L,isDesktop:F}=Qi(),$=l.useRef(c),Y=l.useCallback(_=>{if(!_)return _;if(_==="/"||_.length===0)return"/";let Q=_;for(;Q.length>1&&Q.endsWith("/");)Q=Q.slice(0,-1);return Q.length===0?"/":Q},[]),ie=l.useMemo(()=>{if(!x)return null;const _=x.replace(/\\/g,"/");return Y(_)},[x,Y]),P=l.useMemo(()=>{if(typeof d=="string"&&d.length>0){const _=d.replace(/\\/g,"/"),Q=Y(_);if(Q&&Q!=="/")return Q}return ie&&ie!=="/"?ie:null},[d,ie,Y]),B=l.useMemo(()=>typeof u=="boolean"?!!(u&&P):!!P,[u,P]);l.useEffect(()=>{B||(b(!0),p([]))},[B]);const te=l.useCallback(_=>{if(!_||!B||!P)return!1;const Q=_.replace(/\\/g,"/"),U=Y(Q)??Q;if(U===P)return!0;const K=`${P}/`;return U.startsWith(K)},[B,P,Y]),ye=async _=>{if(B){if(a==="deferred"){s(_);return}if(F){const Q=await I(_);Q.success&&Q.path?(await L(Q.path),s(Q.path)):(console.error("Failed to get directory access:",Q.error),s(_))}else s(_)}};l.useEffect(()=>{let _=!1;const Q=ee=>{if(!ee)return!1;const re=Y(ee.replace(/\\/g,"/"));return!re||re==="/"?!1:(v(typeof re=="string"?re:ee.replace(/\\/g,"/")),!0)};return(d?Q(d):!1)||(async()=>{try{const ee=await Se.getFilesystemHome();if(!_&&Q(ee))return}catch(ee){console.warn("Failed to resolve filesystem home directory:",ee)}try{const ee=await Se.getSystemInfo();if(!_&&Q(ee?.homeDirectory))return}catch(ee){console.warn("Failed to resolve home directory from system info:",ee)}})(),()=>{_=!0}},[d,Y]),l.useEffect(()=>{let _=!1;const Q=re=>{if(_)return;const ce=re.filter(be=>typeof be=="string"&&be.length>0).map(be=>{const ae=be.replace(/\\/g,"/");return Y(ae)??ae});S(new Set(ce))},U=()=>{try{const re=localStorage.getItem("pinnedDirectories");if(!re)return;const ce=JSON.parse(re);Array.isArray(ce)&&Q(ce)}catch(re){console.warn("Failed to load pinned directories from local storage:",re)}},K=async()=>{try{let re=[];if(f){const ce=await pi();re=Array.isArray(ce?.pinnedDirectories)?ce.pinnedDirectories:[]}else{const ce=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(ce.ok){const be=await ce.json();re=Array.isArray(be?.pinnedDirectories)?be.pinnedDirectories:[]}}if(_)return;Q(re)}catch(re){console.warn("Failed to load pinned directories:",re)}};U();const ee=re=>{const ce=re.detail;ce&&Array.isArray(ce.pinnedDirectories)&&Q(ce.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",ee),K(),()=>{_=!0,window.removeEventListener("openchamber:settings-synced",ee)}},[f,Y]);const se=l.useRef(!0);l.useEffect(()=>{if(se.current){se.current=!1;return}const _={pinnedDirectories:Array.from(N)};os(_)},[N]),l.useEffect(()=>{P&&S(_=>{const Q=Array.from(_).map(U=>Y(U.replace(/\\/g,"/"))??U).filter(U=>te(U));return new Set(Q)})},[P,te,Y]),l.useEffect(()=>{$.current!==c&&($.current=c,g(new Set))},[c]);const V=_=>{S(Q=>{if(!te(_))return Q;const U=Y(_.replace(/\\/g,"/"))??_.replace(/\\/g,"/"),K=new Set(Q);return K.has(U)?K.delete(U):K.add(U),K})},ve=l.useMemo(()=>Array.from(N).map(_=>Y(_.replace(/\\/g,"/"))??_).filter(_=>te(_)).map(_=>({path:_,name:_.split("/").pop()||_})).sort((_,Q)=>_.name.localeCompare(Q.name)),[N,te,Y]),Ae=l.useCallback(async _=>{const Q=ce=>c||!ce.startsWith("."),U=P;if(!B||!U)return[];const K=_&&_.length>0?_:U,ee=K?K.replace(/\\/g,"/"):null,re=ee?Y(ee)??ee:null;if(re){const ce=`${U}/`;if(!(re===U||re.startsWith(ce)))return[]}try{return(await Se.listLocalDirectory(_)).filter(be=>{if(!be.isDirectory||!Q(be.name))return!1;const ae=be.path.replace(/\\/g,"/"),Be=Y(ae)??ae,qe=Be===U?U:`${U}/`;return Be===U||Be.startsWith(qe)}).map(be=>({name:be.name,path:be.path.replace(/\\/g,"/"),isDirectory:!0})).sort((be,ae)=>be.name.localeCompare(ae.name))}catch{try{const be=await Se.getApiClient().file.list({query:{path:".",directory:_}});return be.data?be.data.filter(ae=>{if(ae.type!=="directory"||!ae.name||!Q(ae.name))return!1;const Be=String(ae.absolute||ae.path||ae.name).replace(/\\/g,"/"),qe=Y(Be)??Be,nt=qe===U?U:`${U}/`;return qe===U||qe.startsWith(nt)}).map(ae=>({name:ae.name||"",path:String(ae.absolute||ae.path||ae.name).replace(/\\/g,"/"),isDirectory:!0})).filter(ae=>ae.name!=="").sort((ae,Be)=>ae.name.localeCompare(Be.name)):[]}catch{return[]}}},[c,P,Y,B]),Pe=l.useCallback(async()=>{if(!B||!P){b(!0),p([]);return}b(!0);try{const _=await Ae(P);p(_)}catch{}finally{b(!1)}},[B,P,Ae]);l.useEffect(()=>{B&&(n==="inline"||w)&&Pe()},[n,w,B,Pe]);const je=async _=>{if(!B)return;const Q=h.has(_.path),U=new Set(h);if(Q){U.delete(_.path),g(U);return}U.add(_.path),g(U);const K=await Ae(_.path),ee=re=>re.map(ce=>ce.path===_.path?{...ce,children:K}:ce.children?{...ce,children:ee(ce.children)}:ce);p(re=>ee(re))};l.useEffect(()=>{C&&E.current&&(E.current.focus(),E.current.select())},[C]);const De=(_,Q=[])=>{const U="new_directory",K=Q.map(be=>be.name);if(!K.includes(U))return U;let ee=1;const re=new RegExp(`^${U}(\\d+)$`);for(const be of K){const ae=be.match(re);if(ae){const Be=parseInt(ae[1],10);Be>ee&&(ee=Be)}}let ce=2;for(;K.includes(`${U}${ce}`);)ce++;return`${U}${Math.max(ce,ee+1)}`},ue=async _=>{if(B){if(h.has(_.path)){const Q=De(_.path,_.children);M(Q)}else{const Q=new Set(h);if(Q.add(_.path),g(Q),_.children){const U=De(_.path,_.children);M(U)}else{const U=await Ae(_.path),K=re=>re.map(ce=>ce.path===_.path?{...ce,children:U}:ce.children?{...ce,children:K(ce.children)}:ce);p(re=>K(re));const ee=De(_.path,U);M(ee)}}D(_.path)}},X=async()=>{if(!C||!B)return;const _=k.trim()||"new_directory",Q=`${C}/${_}`;try{await Se.createDirectory(Q);const U=await Ae(C),K=ee=>ee.map(re=>re.path===C?{...re,children:U}:re.children?{...re,children:K(re.children)}:re);p(ee=>K(ee)),D(null),M("")}catch(U){console.error("Failed to create directory:",U)}},R=()=>{D(null),M("")},ne=(_,Q=0)=>{const U=h.has(_.path),K=_.isDirectory,ee=N.has(_.path),re=r===_.path,ce=n==="inline",be=e.jsxs(e.Fragment,{children:[K&&e.jsx("button",{onClick:ae=>{ae.stopPropagation(),je(_)},className:"p-0.5 hover:bg-accent rounded",children:U?e.jsx(ft,{className:"h-3 w-3"}):e.jsx(ds,{className:"h-3 w-3"})}),!K&&e.jsx("div",{className:"w-4"}),e.jsxs("button",{onClick:ae=>{ae.stopPropagation(),ye(_.path),n==="dropdown"&&a==="immediate"&&j(!1)},onDoubleClick:ae=>{ae.stopPropagation(),i&&i(_.path)},className:A("flex items-center gap-1.5 flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",ce&&re?"text-primary":"text-foreground"),children:[U?e.jsx(Ut,{className:A("h-3.5 w-3.5 text-muted-foreground",ce&&re&&"text-primary")}):e.jsx(Ut,{className:A("h-3.5 w-3.5 text-muted-foreground",ce&&re&&"text-primary")}),e.jsx("span",{className:A("typography-ui-label font-medium truncate",ce&&re?"text-primary":"text-foreground"),children:_.name})]}),e.jsx("button",{onClick:ae=>{ae.stopPropagation(),ue(_)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Create new directory",children:e.jsx(Qt,{className:"h-3 w-3 text-muted-foreground"})}),e.jsx("button",{onClick:ae=>{ae.stopPropagation(),V(_.path)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:ee?"Unpin directory":"Pin directory",children:ee?e.jsx(vn,{className:"h-3 w-3 text-primary"}):e.jsx(Dc,{className:"h-3 w-3 text-muted-foreground"})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:A("group flex items-center gap-1 rounded px-2 py-1.5 text-left hover:bg-accent/40",re?"text-primary":"text-foreground"),style:{paddingLeft:`${Q*12+8}px`},children:be}),U&&e.jsxs(e.Fragment,{children:[C===_.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(Q+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Ut,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{ref:E,value:k,onChange:ae=>M(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"?(ae.preventDefault(),ae.stopPropagation(),X()):ae.key==="Escape"&&(ae.preventDefault(),ae.stopPropagation(),R())},onBlur:X,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),X()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(ht,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),R()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Zt,{className:"h-3 w-3 text-muted-foreground"})})]}),_.children&&_.children.map(ae=>ne(ae,Q+1))]})]},_.path):e.jsxs("div",{children:[e.jsxs(mt,{className:A("flex items-center gap-1 cursor-pointer group",r===_.path&&"bg-accent"),style:{paddingLeft:`${Q*12+8}px`},onSelect:ae=>{ae.preventDefault()},children:[K&&e.jsx("button",{onClick:ae=>{ae.stopPropagation(),je(_)},className:"p-0.5 hover:bg-accent rounded",children:U?e.jsx(ft,{className:"h-3 w-3"}):e.jsx(ds,{className:"h-3 w-3"})}),!K&&e.jsx("div",{className:"w-4"}),be]}),U&&e.jsxs("div",{children:[C===_.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(Q+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Ut,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{ref:E,value:k,onChange:ae=>M(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"?(ae.preventDefault(),ae.stopPropagation(),X()):ae.key==="Escape"&&(ae.preventDefault(),ae.stopPropagation(),R())},onBlur:X,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),X()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(ht,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ae=>{ae.preventDefault(),ae.stopPropagation(),R()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Zt,{className:"h-3 w-3 text-muted-foreground"})})]}),_.children&&_.children.map(ae=>ne(ae,Q+1))]})]},_.path)},Z=(_,Q)=>{if(n==="inline"){const U=r===Q;return e.jsxs("div",{className:A("group flex items-center gap-2 px-2 py-1.5 hover:bg-accent/40"),children:[e.jsxs("button",{onClick:()=>ye(Q),onDoubleClick:K=>{K.stopPropagation(),i&&i(Q)},className:A("flex flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded",U?"text-primary":"text-foreground"),children:[e.jsx(Ut,{className:A("h-3.5 w-3.5 text-muted-foreground",U&&"text-primary")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:A("typography-ui-label font-medium truncate",U?"text-primary":"text-foreground"),children:_}),e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:Dt(Q,x)})]})]}),e.jsx("button",{onClick:()=>V(Q),className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(vn,{className:"h-3 w-3 text-primary"})})]},Q)}return e.jsxs(mt,{onSelect:U=>{U.preventDefault(),ye(Q),a==="immediate"&&j(!1)},className:A("flex items-start gap-2 cursor-pointer group py-2",r===Q&&"bg-accent"),children:[e.jsx(Ut,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium",children:_}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Dt(Q,x)})]}),e.jsx("button",{onClick:U=>{U.stopPropagation(),U.preventDefault(),V(Q)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(vn,{className:"h-3 w-3 text-primary"})})]},Q)},q=e.jsx(e.Fragment,{children:B?e.jsxs(e.Fragment,{children:[ve.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"}),ve.map(({name:_,path:Q})=>Z(_,Q)),n==="dropdown"&&e.jsx(No,{})]}),e.jsx("div",{className:"px-2 py-1.5 typography-meta font-semibold text-muted-foreground",children:"Browse"}),y?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):m.map(_=>ne(_)),!y&&m.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:A("overflow-hidden rounded-xl border border-border/40 bg-sidebar/70",o),children:e.jsx(Ge,{outerClassName:"max-h-full",className:"w-full",children:q})}):e.jsxs(Ft,{open:w,onOpenChange:j,children:[e.jsx(Lt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",className:A("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(Ut,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:r,children:Dt(r,x)})]}),e.jsx(ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(_t,{align:"start",className:"w-[350px]",children:e.jsx(Ge,{outerClassName:"h-full",className:"w-full",children:q})})]})},Da="directoryTreeShowHidden",Nf=({open:r,onOpenChange:s})=>{const{currentDirectory:t,homeDirectory:n,setDirectory:o,isHomeReady:a}=dt(),[i,c]=l.useState(null),[d,u]=l.useState(!1),[f,m]=l.useState(!1),[p,h]=l.useState(()=>{if(typeof window>"u")return!1;try{const E=window.localStorage.getItem(Da);if(E==="true")return!0;if(E==="false")return!1}catch{}return!1}),{isDesktop:g,requestAccess:y,startAccessing:b}=Qi(),{isMobile:w}=wt();l.useEffect(()=>{r&&(c(null),u(!1),m(!1))},[r]),l.useEffect(()=>{r&&!d&&!i&&n&&a&&(c(n),u(!0))},[r,d,i,n,a]),l.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Da,p?"true":"false")}catch{}},[p]);const j=l.useMemo(()=>i?Dt(i,n):"Select a directory",[i,n]),x=l.useCallback(()=>{s(!1)},[s]),v=l.useCallback(async E=>{if(!(!E||f)){if(E===t){x();return}m(!0);try{let I=E;if(g){const L=await y(E);if(!L.success){he.error("Unable to access directory",{description:L.error||"Desktop denied directory access."});return}I=L.path??E;const F=await b(I);if(!F.success){he.error("Failed to open directory",{description:F.error||"Desktop could not grant file access."});return}}o(I),x()}catch(I){he.error("Failed to select directory",{description:I instanceof Error?I.message:"Unknown error occurred."})}finally{m(!1)}}},[t,x,g,y,o,b,f]),N=l.useCallback(async()=>{i&&await v(i)},[v,i]),S=l.useCallback(E=>{c(E),u(!0)},[]),C=l.useCallback(async E=>{c(E),u(!0),await v(E)},[v]),D=e.jsxs(ps,{className:"flex-shrink-0 px-4 pb-3 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-4 sm:pt-[calc(var(--oc-safe-area-top,0px)+0px)]",children:[e.jsx(hs,{children:"Select project directory"}),e.jsx(Ls,{className:"hidden sm:block",children:"Choose the working directory used for sessions, commands, and OpenCode operations."})]}),k=e.jsxs(Ge,{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:Dt(t,n),children:Dt(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(Sf,{variant:"inline",currentPath:i??t,onSelectPath:S,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?j:void 0,children:j})]}),e.jsxs(jf,{pressed:p,onPressedChange:E=>h(!!E),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(ho,{className:"h-4 w-4"}):e.jsx(go,{className:"h-4 w-4"}),"Show hidden directories"]}),e.jsx("div",{className:"hidden rounded-xl border border-dashed border-border/40 bg-sidebar/40 px-3 py-2 sm:block sm:px-4 sm:py-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Use the tree to browse, pin frequently used locations, or create a new directory. Select a folder, then confirm to update the working directory for OpenChamber."})})]})]})]}),M=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",onClick:x,disabled:f,className:"w-full sm:w-auto",children:"Cancel"}),e.jsx(Ne,{onClick:N,disabled:f||!d||!i,className:"w-full sm:w-auto",children:f?"Applying...":"Use Selected Directory"})]});return w?e.jsx(Bt,{open:r,onClose:()=>s(!1),title:"Select project directory",className:"max-w-full",footer:e.jsx("div",{className:"flex flex-col gap-2",children:M()}),children:k}):e.jsx(ms,{open:r,onOpenChange:s,children:e.jsxs(fs,{className:A("flex w-full max-w-[min(640px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-4xl sm:p-6"),children:[D,k,e.jsx(vr,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-col gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:flex-row sm:justify-end sm:gap-2 sm:border-0 sm:bg-transparent sm:px-0 sm:py-0",children:M()})]})})},ln=".openchamber",Tr=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,kf=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),el=r=>r.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),tl=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Ir=(r,s)=>{const t=tl(r),n=el(s),o=!t||t==="/"?`/${ln}`:`${t}/${ln}`;return n?`${o}/${n}`:o},Cf=()=>{const[r,s]=l.useState(!1),[t,n]=l.useState(!1),[o,a]=l.useState(""),[i,c]=l.useState([]),[d,u]=l.useState(!1),[f,m]=l.useState(null),[p,h]=l.useState(!1),[g,y]=l.useState(null),[b,w]=l.useState(!1),j=l.useRef(new Set),[x,v]=l.useState(null),[N,S]=l.useState([]),[C,D]=l.useState(!1),[k,M]=l.useState(!1),{sessions:E,createSession:I,deleteSession:L,deleteSessions:F,loadSessions:$,initializeNewOpenChamberSession:Y,setWorktreeMetadata:ie,setSessionDirectory:P,getWorktreeMetadata:B,isLoading:te}=we(),{currentDirectory:ye,homeDirectory:se,hasPersistedDirectory:V,isHomeReady:ve}=dt(),{agents:Ae}=yt(),{isSessionCreateDialogOpen:Pe,setSessionCreateDialogOpen:je}=Fe(),{isMobile:De,isTablet:ue,hasTouchInput:X}=wt(),R=De||ue||X,ne=l.useMemo(()=>tl(ye),[ye]),Z=l.useMemo(()=>kf(o),[o]),q=l.useMemo(()=>el(Z),[Z]),_=l.useMemo(()=>!ne||!q?"":Ir(ne,q),[ne,q]),Q=g===!0,U=l.useMemo(()=>(x?.worktree?.status?.isDirty??!1)||N.some(J=>J.metadata.status?.isDirty),[x?.worktree?.status?.isDirty,N]),K=l.useMemo(()=>{const J=x?.worktree;return J&&typeof J.branch=="string"&&J.branch.trim().length>0?!0:N.length>0&&N.every(({metadata:z})=>typeof z.branch=="string"&&z.branch.trim().length>0)},[x?.worktree,N]),ee=x?.mode==="worktree",re=ee,ce=k||!ee||!K;l.useEffect(()=>{ne&&(j.current.has(ne)||mu(ne).then(()=>j.current.add(ne)).catch(J=>{console.warn("Failed to ensure .openchamber directory is ignored:",J),j.current.delete(ne)}))},[ne]),l.useEffect(()=>{$()},[$,ye]),l.useEffect(()=>{!t&&ve&&!V&&(s(!0),n(!0))},[V,t,ve]),l.useEffect(()=>{if(!Pe){a(""),c([]),m(null),u(!1),h(!1),y(null),w(!1);return}if(!ne){c([]),y(null),h(!1);return}let J=!1;return u(!0),h(!0),m(null),(async()=>{try{const z=await wo(ne);if(J)return;if(y(z),!z)c([]),m(null);else{const me=await Qr(ne);if(J)return;const oe=me.map(Ye=>en(ne,Ye)),ke=`${Ir(ne,"")}/`,_e=oe.filter(Ye=>Ye.path.startsWith(ke));c(_e)}}catch(z){if(J)return;const me=z instanceof Error?z.message:"Failed to load worktrees";m(me)}finally{J||(u(!1),h(!1))}})(),()=>{J=!0}},[Pe,ne]);const be=l.useCallback(J=>{v({sessions:J.sessions,dateLabel:J.dateLabel,mode:J.mode??"session",worktree:J.worktree??null})},[]),ae=l.useCallback(()=>{v(null),S([]),D(!1),M(!1)},[]);l.useEffect(()=>Bs.onDeleteRequest(J=>{be(J)}),[be]),l.useEffect(()=>Bs.onDirectoryRequest(()=>{s(!0)}),[]),l.useEffect(()=>Bs.onCreateRequest(()=>{a(""),je(!0)}),[je]),l.useEffect(()=>{if(!x){S([]),D(!1);return}const J=x.sessions.map(me=>{const oe=B(me.id);return oe?{session:me,metadata:oe}:null}).filter(me=>!!me);if(S(J),D(!1),J.length===0)return;let z=!1;return(async()=>{const me=await Promise.all(J.map(async({metadata:oe})=>{if(oe.status&&typeof oe.status.isDirty=="boolean")return oe.status;try{return await zr(oe.path)}catch{return oe.status}})).catch(oe=>(console.warn("Failed to inspect worktree status before deletion:",oe),J.map(({metadata:fe})=>fe.status)));z||!Array.isArray(me)||S(oe=>oe.map((fe,ke)=>({session:fe.session,metadata:{...fe.metadata,status:me[ke]??fe.metadata.status}})))})(),()=>{z=!0}},[x,B]),l.useEffect(()=>{K||D(!1)},[K]);const Be=l.useCallback(J=>{a(J),m(null)},[]),qe=l.useCallback(async()=>{if(!(!ne||!g))try{const z=(await Qr(ne)).map(ke=>en(ne,ke)),oe=`${Ir(ne,"")}/`,fe=z.filter(ke=>ke.path.startsWith(oe));c(fe)}catch{}},[ne,g]),nt=l.useRef(null);l.useEffect(()=>{nt.current?.mode==="worktree"&&!x&&qe(),nt.current=x},[x,qe]);const et=l.useCallback(()=>{if(!ne){const oe="Select a project directory first.";return m(oe),he.error(oe),!1}const J=Z,z=q;if(!J){const oe="Provide a branch name for the new worktree.";return m(oe),he.error(oe),!1}if(!z){const oe="Provide a branch name that can be used as a folder.";return m(oe),he.error(oe),!1}const me=Ir(ne,z);if(i.some(oe=>oe.path===me)){const oe="A worktree with this folder already exists.";return m(oe),he.error(oe),!1}return m(null),!0},[ne,Z,q,i]),st=async()=>{if(b||te||!et())return;w(!0),m(null);let J=null;try{const z=Z,oe=await ju({projectDirectory:ne,worktreeSlug:q,branch:z,createBranch:!0});J=oe;let fe=await zr(oe.path).catch(()=>{});try{await fu(oe.path,{remote:"origin",branch:z,options:["--set-upstream"]}),fe=await zr(oe.path).catch(()=>fe),he.success(`Configured upstream for ${z}`)}catch(Ye){const Je=Ye instanceof Error?Ye.message:"Unable to push new worktree branch.";he.warning("Worktree created locally",{description:Tr(`Upstream setup failed: ${Je}`)})}const ke=fe?{...oe,status:fe}:oe,_e=await I(void 0,oe.path);if(!_e){await Ho({projectDirectory:ne,path:oe.path,force:!0}).catch(()=>{});const Ye="Failed to create session for worktree";m(Ye),he.error(Ye);return}Y(_e.id,Ae),P(_e.id,oe.path),ie(_e.id,ke),await qe(),a(""),he.success("Worktree created")}catch(z){J&&await Ho({projectDirectory:ne,path:J.path,force:!0}).catch(()=>{});const me=z instanceof Error?z.message:"Failed to create worktree";m(me),he.error(me)}finally{w(!1)}},Ke=l.useCallback(J=>{const z=E.filter(me=>B(me.id)?.path===J.path);Bs.requestDelete({sessions:z,mode:"worktree",worktree:J})},[E,B]),He=l.useCallback(async()=>{if(x){M(!0);try{const J=re,z=J&&C;if(x.sessions.length===1){const me=x.sessions[0];if(!await L(me.id,{archiveWorktree:J,deleteRemoteBranch:z})){he.error("Failed to delete session"),M(!1);return}const fe=J?z?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;he.success("Session deleted",{description:Tr(fe)})}else{const me=x.sessions.map(ke=>ke.id),{deletedIds:oe,failedIds:fe}=await F(me,{archiveWorktree:J,deleteRemoteBranch:z});if(oe.length>0){const ke=J?z?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,Ye=[fe.length>0?`${fe.length} session${fe.length===1?"":"s"} could not be deleted.`:x.dateLabel?`Removed all sessions from ${x.dateLabel}.`:void 0,ke].filter(Boolean).join(" ");he.success(`Deleted ${oe.length} session${oe.length===1?"":"s"}`,{description:Tr(Ye||void 0)})}if(fe.length>0&&(he.error(`Failed to delete ${fe.length} session${fe.length===1?"":"s"}`,{description:Tr("Please try again in a moment.")}),oe.length===0)){M(!1);return}}ae()}finally{M(!1)}}},[x,C,L,F,ae,re]),Ee=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:ln}),"."]})]}),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(bt,{id:"worktree-branch-input",value:o,onChange:J=>Be(J.target.value),placeholder:"feature/new-branch",className:"h-8 flex-1 typography-meta text-foreground placeholder:text-muted-foreground/70",disabled:!Q||p,onKeyDown:J=>{J.key==="Enter"&&!b&&st()}}),e.jsx(Ne,{onClick:st,disabled:b||te||!Q||!Z,className:"h-8",children:b?"Creating…":"Create"})]}),Z&&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:Z})," ","at"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground break-all",children:Dt(_,se)})]})]}),f&&e.jsx("p",{className:"typography-meta text-destructive",children:f}),!Q&&!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:ln}),"."]}):e.jsx("div",{className:"space-y-1.5 min-w-0",children:i.map(J=>{const z=J.relativePath||(J.path.startsWith(ne+"/")?J.path.slice(ne.length+1):J.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:J.label||J.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70 break-all",children:z})]}),e.jsx("button",{type:"button",onClick:()=>Ke(J),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 ${J.branch||J.label}`,children:e.jsx(Ns,{className:"h-4 w-4"})})]},J.path)})})]})]}),Ue=e.jsx(Ne,{variant:"ghost",onClick:()=>je(!1),disabled:b,children:"Close"}),Le=x?.worktree??N[0]?.metadata??null,ze=x?x.mode==="worktree"?`This removes the selected worktree and ${x.sessions.length===1?"1 linked session":`${x.sessions.length} linked sessions`}.`:`This action permanently removes ${x.sessions.length===1?"1 session":`${x.sessions.length} sessions`}${x.dateLabel?` from ${x.dateLabel}`:""}.`:"",O=x?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:[x.sessions.slice(0,3).map(J=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:J.title||"Untitled Session"},J.id)),x.sessions.length>3&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",x.sessions.length-3," more"]})]})}),ee?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?Dt(Le.path,se):"Worktree path unavailable."}),U&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),K?e.jsxs("button",{type:"button",onClick:()=>{ce||D(J=>!J)},disabled:ce,className:A("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",ce?"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(ho,{className:"size-4 text-primary"}):e.jsx(go,{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,de=e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",onClick:ae,disabled:k,children:"Cancel"}),e.jsx(Ne,{variant:"destructive",onClick:He,disabled:k,children:k?"Deleting…":ee?"Delete worktree":x?.sessions.length===1?"Delete session":"Delete sessions"})]});return e.jsxs(e.Fragment,{children:[R?e.jsx(Bt,{open:Pe,onClose:()=>je(!1),title:"Worktree Manager",footer:e.jsx("div",{className:"flex justify-end gap-2",children:Ue}),children:e.jsx("div",{className:"space-y-2 pb-2",children:Ee})}):e.jsx(ms,{open:Pe,onOpenChange:je,children:e.jsxs(fs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2 overflow-hidden",children:[e.jsx(ps,{children:e.jsx(hs,{children:"Worktree Manager"})}),Ee,e.jsx(vr,{className:"mt-2 gap-2 pt-1 pb-1",children:Ue})]})}),R?e.jsx(Bt,{open:!!x,onClose:()=>{k||ae()},title:x?.sessions.length===1?"Delete session":"Delete sessions",footer:e.jsx("div",{className:"flex justify-end gap-2",children:de}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[ze&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:ze}),O]})}):e.jsx(ms,{open:!!x,onOpenChange:J=>{if(!J){if(k)return;ae()}},children:e.jsxs(fs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(ps,{children:[e.jsx(hs,{children:x?.sessions.length===1?"Delete session":"Delete sessions"}),ze&&e.jsx(Ls,{children:ze})]}),O,e.jsx(vr,{className:"mt-2 gap-2 pt-1 pb-1",children:de})]})}),e.jsx(Nf,{open:r,onOpenChange:s})]})},Mf=(r={})=>{const{edgeThreshold:s=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=r,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:c}=Fe(),d=ge.useRef(null),u=ge.useRef(null);return ge.useEffect(()=>{if(!o||!a)return;const f=g=>{const y=g.touches[0];if(!y){d.current=null;return}y.clientX<=s?d.current={x:y.clientX,y:y.clientY,time:Date.now()}:d.current=null},m=g=>{if(!d.current)return;const y=g.touches[0];if(!y)return;y.clientX-d.current.x>10&&g.preventDefault()},p=g=>{if(!d.current)return;const y=g.changedTouches[0];if(!y){d.current=null,u.current=null;return}u.current={x:y.clientX,y:y.clientY,time:Date.now()};const{x:b,y:w,time:j}=d.current,{x,y:v,time:N}=u.current,S=x-b,C=v-w,D=N-j,k=Math.abs(C)<Math.abs(S),M=D<=n,E=Math.abs(C)<t;S>=t&&k&&M&&E&&!c&&i(!0),d.current=null,u.current=null},h=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",f,{passive:!0,capture:!0}),document.addEventListener("touchmove",m,{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",m,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",h,{capture:!0})}},[o,a,s,t,n,i,c]),null},ar=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,Ea=ge.memo(()=>{const r=ge.useRef(null),{addAttachedFile:s}=we(),{isMobile:t}=Fe(),n=t?"h-9 w-9":"h-7 w-7",o=t?"h-5 w-5":"h-[18px] w-[18px]",a=async i=>{const c=i.target.files;if(!c)return;let d=0;for(let u=0;u<c.length;u++){const f=we.getState().attachedFiles.length;try{await s(c[u]),we.getState().attachedFiles.length>f&&d++}catch(m){console.error("File attach failed",m),he.error(m instanceof Error?m.message:"Failed to attach file")}}d>0&&he.success(`Attached ${d} file${d>1?"s":""}`),r.current&&(r.current.value="")};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:r,type:"file",multiple:!0,className:"hidden",onChange:a,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>r.current?.click(),className:A(n,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),title:"Attach files",children:e.jsx(Ec,{className:A(o,"text-current")})})]})}),Af=ge.memo(({file:r,onRemove:s})=>{const t=()=>r.mimeType.startsWith("image/")?e.jsx(Us,{className:"h-3.5 w-3.5"}):r.mimeType.includes("text")||r.mimeType.includes("code")?e.jsx(Is,{className:"h-3.5 w-3.5"}):r.mimeType.includes("json")||r.mimeType.includes("xml")?e.jsx(hn,{className:"h-3.5 w-3.5"}):e.jsx(Is,{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(Tc,{className:"h-3 w-3 text-primary"}):e.jsx(ci,{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(Zt,{className:"h-3 w-3"})})]})}),Df=ge.memo(()=>{const{attachedFiles:r,removeAttachedFile:s}=we();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(Af,{file:t,onRemove:()=>s(t.id)},t.id))]})})}),sl=ge.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(Us,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(Is,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(hn,{className:"h-3.5 w-3.5"}):e.jsx(Is,{className:"h-3.5 w-3.5"}):e.jsx(Is,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),c=l.useCallback(d=>{if(!s||!d?.url)return;const u=n(d.filename)||"Image",f={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};s(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,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const f=n(d.filename)||"Image";return e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{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:m=>{const p=m.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(Us,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:f})]})}),e.jsx(rt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:f})]},`img-${u}`)})})})]})}),rl=(r,s=200)=>{const[t,n]=ge.useState(r);return ge.useEffect(()=>{const o=window.setTimeout(()=>{n(r)},s);return()=>{window.clearTimeout(o)}},[r,s]),t},Ef=l.forwardRef(({searchQuery:r,onFileSelect:s,onClose:t},n)=>{const{currentDirectory:o}=dt(),{addServerFile:a}=we(),i=jo(v=>v.searchFiles),c=rl(r,180),[d,u]=l.useState([]),[f,m]=l.useState(!1),[p,h]=l.useState(0),[g,y]=l.useState(null),b=l.useRef([]),w=l.useRef(null);l.useEffect(()=>{const v=N=>{const S=N.target;!S||!w.current||w.current.contains(S)||t()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[t]),l.useEffect(()=>{if(!o){u([]);return}let v=!1;return m(!0),i(o,c??"",40).then(N=>{v||u(N.slice(0,15))}).catch(()=>{v||u([])}).finally(()=>{v||m(!1)}),()=>{v=!0}},[o,c,i]),l.useEffect(()=>{h(0),y(null)},[d]),l.useEffect(()=>{b.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]);const j=l.useCallback(async v=>{await a(v.path,v.name),s(v)},[a,s]);l.useImperativeHandle(n,()=>({handleKeyDown:v=>{if(v==="Escape"){t();return}const N=d.length;if(N!==0){if(v==="ArrowDown"){h(S=>(S+1)%N);return}if(v==="ArrowUp"){h(S=>(S-1+N)%N);return}if(v==="Enter"||v==="Tab"){const S=(p%N+N)%N,C=d[S];C&&j(C)}}}}),[d,p,t,j]);const x=v=>{switch(v.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(vs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(vs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Is,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Us,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(hn,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:w,className:"absolute z-[100] min-w-[240px] max-w-[520px] max-h-64 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 w-max flex flex-col",children:[e.jsx(Ge,{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(gn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((v,N)=>{const S=v.relativePath||v.name,C=ui(S,{maxLength:45}),D=p===N,M=D||g===N,E=e.jsxs("div",{ref:I=>{b.current[N]=I},className:A("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",D&&"bg-accent"),onClick:()=>j(v),onMouseEnter:()=>h(N),children:[x(v),e.jsx("span",{className:"flex-1 truncate max-w-[360px]","aria-label":S,children:C})]});return e.jsxs(at,{open:M,delayDuration:M?0:120,onOpenChange:I=>{y(L=>!I&&L===N?null:I?N:L)},children:[e.jsx(it,{asChild:!0,children:E}),e.jsx(rt,{side:"right",align:"center",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:S})})]},v.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"})]})}),nl=l.forwardRef(({searchQuery:r,onCommandSelect:s,onClose:t},n)=>{const{hasMessagesInCurrentSession:o}=we(xo(g=>{const y=g.currentSessionId;return{hasMessagesInCurrentSession:(y?g.messages.get(y)?.length??0:0)>0}})),[a,i]=l.useState([]),[c,d]=l.useState(!1),[u,f]=l.useState(0),m=l.useRef([]),p=l.useRef(null);l.useEffect(()=>{const g=y=>{const b=y.target;!b||!p.current||p.current.contains(b)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),l.useEffect(()=>{(async()=>{d(!0);try{const b=(await Se.listCommands()).map(S=>({name:S.name,description:S.description,agent:S.agent,model:S.model,isBuiltIn:!1})),w=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],j=new Map;w.forEach(S=>j.set(S.name,S)),b.forEach(S=>j.set(S.name,S));const x=Array.from(j.values()),v=!o,N=(r?x.filter(S=>S.name.toLowerCase().includes(r.toLowerCase())||S.description&&S.description.toLowerCase().includes(r.toLowerCase())):x).filter(S=>v||S.name!=="init");N.sort((S,C)=>{const D=S.name.toLowerCase().startsWith(r.toLowerCase()),k=C.name.toLowerCase().startsWith(r.toLowerCase());return D&&!k?-1:!D&&k?1:S.name.localeCompare(C.name)}),i(N)}catch{const y=!o,b=[...o?[]:[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}],{name:"summarize",description:"Generate a summary of the current session",isBuiltIn:!0}],w=(r?b.filter(j=>j.name.toLowerCase().includes(r.toLowerCase())||j.description&&j.description.toLowerCase().includes(r.toLowerCase())):b).filter(j=>y||j.name!=="init");i(w)}finally{d(!1)}})()},[r,o]),l.useEffect(()=>{f(0)},[a]),l.useEffect(()=>{m.current[u]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[u]),l.useImperativeHandle(n,()=>({handleKeyDown:g=>{const y=a.length;if(g==="Escape"){t();return}if(y!==0){if(g==="ArrowDown"){f(b=>(b+1)%y);return}if(g==="ArrowUp"){f(b=>(b-1+y)%y);return}if(g==="Enter"||g==="Tab"){const b=(u%y+y)%y,w=a[b];w&&s(w)}}}}),[a,u,t,s]);const h=g=>{switch(g.name){case"init":return e.jsx(Is,{className:"h-3.5 w-3.5 text-green-500"});case"summarize":return e.jsx(Pc,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Ss,{className:"h-3.5 w-3.5 text-cyan-500"});default:return g.isBuiltIn?e.jsx(Ic,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(Ks,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:p,className:"absolute z-[100] min-w-[250px] max-w-[450px] max-h-64 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 w-max flex flex-col",children:[e.jsx(Ge,{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(gn,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[a.map((g,y)=>e.jsxs("div",{ref:b=>{m.current[y]=b},className:A("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",y===u&&"bg-accent"),onClick:()=>s(g),onMouseEnter:()=>f(y),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"})]})});nl.displayName="CommandAutocomplete";const Tf=r=>r?r!=="primary":!1,ol=l.forwardRef(({searchQuery:r,onAgentSelect:s,onClose:t},n)=>{const o=l.useRef(null),[a,i]=l.useState(0),[c,d]=l.useState([]),{agents:u}=yt();l.useEffect(()=>{const m=u.filter(g=>Tf(g.mode)).map(g=>({name:g.name,description:g.description,mode:g.mode??void 0})),p=r.trim().toLowerCase(),h=p.length?m.filter(g=>g.name.toLowerCase().includes(p)):m;h.sort((g,y)=>g.name.localeCompare(y.name)),d(h),i(0)},[u,r]),l.useEffect(()=>{const m=p=>{const h=p.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",m,!0),()=>{document.removeEventListener("pointerdown",m,!0)}},[t]),l.useImperativeHandle(n,()=>({handleKeyDown:m=>{if(m==="Escape"){t();return}if(c.length){if(m==="ArrowDown"){i(p=>(p+1)%c.length);return}if(m==="ArrowUp"){i(p=>(p-1+c.length)%c.length);return}if(m==="Enter"||m==="Tab"){const p=c[(a+c.length)%c.length];p&&s(p.name)}}}}),[c,s,t,a]);const f=(m,p)=>e.jsx("div",{className:A("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",p===a&&"bg-accent"),onClick:()=>s(m.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:["#",m.name]})}),m.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",children:m.description})]})},m.name);return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-[240px] max-w-[360px] max-h-60 bg-popover border border-border rounded-xl shadow-none bottom-full mb-2 left-0 w-max flex flex-col",children:[e.jsx(Ge,{outerClassName:"flex-1 min-h-0",className:"px-0",children:c.length?e.jsx("div",{children:c.map((m,p)=>f(m,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"})]})});ol.displayName="AgentMentionAutocomplete";function If({className:r,children:s,...t}){return e.jsxs(Rc,{"data-slot":"scroll-area",className:A("relative",r),...t,children:[e.jsx(Fc,{"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(Pf,{}),e.jsx(Lc,{})]})}function Pf({className:r,orientation:s="vertical",...t}){return e.jsx(_c,{"data-slot":"scroll-area-scrollbar",orientation:s,className:A("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(Oc,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Rf=({onFilesSelected:r,multiSelect:s=!1,children:t})=>{const{isMobile:n}=wt(),{currentDirectory:o}=dt(),a=jo(ue=>ue.searchFiles),[i,c]=l.useState(!1),[d,u]=l.useState(!1),[f,m]=l.useState(""),p=rl(f,200),[h,g]=l.useState(new Set),[y,b]=l.useState(new Set),[w,j]=l.useState([]),[x,v]=l.useState([]),[N,S]=l.useState(!1),[C,D]=l.useState(!1),[k,M]=l.useState(!1),[E,I]=l.useState(null),L=l.useCallback(async ue=>{D(!0),I(null);try{const R=await Se.getApiClient().file.list({query:{path:".",directory:ue}});if(!R.data){j([]);return}const ne=R.data.filter(Z=>!Z.name.startsWith(".")).map(Z=>{const q=Z.type==="file"?Z.name.split(".").pop()?.toLowerCase():void 0;return{name:Z.name,path:Z.absolute||`${ue}/${Z.name}`,type:Z.type,size:Z.size||0,extension:q}}).sort((Z,q)=>Z.type!==q.type?Z.type==="directory"?-1:1:Z.name.localeCompare(q.name));j(ne)}catch{I("Failed to load directory contents"),j([])}finally{D(!1)}},[]);l.useEffect(()=>{(i||d)&&o&&L(o)},[i,d,o,L]),l.useEffect(()=>{if(!(i||d)||!o){v([]),S(!1);return}const ue=p.trim();if(!ue){v([]),S(!1);return}let X=!1;return S(!0),a(o,ue,150).then(R=>{if(X)return;const ne=R.map(Z=>({name:Z.name,path:Z.path,type:"file",extension:Z.extension,relativePath:Z.relativePath,size:0}));v(ne)}).catch(()=>{X||v([])}).finally(()=>{X||S(!1)}),()=>{X=!0}},[i,d,o,p,a]),l.useEffect(()=>{!i&&!d&&(g(new Set),m(""),v([]),S(!1))},[i,d]);const F=ue=>{if(ue.type==="directory")return y.has(ue.path)?e.jsx(Ut,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(Ut,{className:"h-3.5 w-3.5 text-primary/60"});switch(ue.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(vs,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(vs,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(Jn,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(Us,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Jn,{className:"h-3.5 w-3.5 text-muted-foreground"})}},$=async ue=>{if(y.has(ue))b(R=>{const ne=new Set(R);return ne.delete(ue),ne});else{b(R=>{const ne=new Set(R);return ne.add(ue),ne});try{const ne=await Se.getApiClient().file.list({query:{path:".",directory:ue}});if(ne.data){const Z=ne.data.filter(q=>!q.name.startsWith(".")).map(q=>{const _=q.type==="file"?q.name.split(".").pop()?.toLowerCase():void 0;return{name:q.name,path:q.absolute||`${ue}/${q.name}`,type:q.type,size:0,extension:_}});j(q=>[...q.filter(Q=>!Q.path.startsWith(ue+"/")),...Z].sort((Q,U)=>{const K=Q.path.split("/").length,ee=U.path.split("/").length;return K!==ee?K-ee:Q.type!==U.type?Q.type==="directory"?-1:1:Q.name.localeCompare(U.name)}))}}catch{}}},Y=ue=>{g(s?X=>{const R=new Set(X);return R.has(ue)?R.delete(ue):R.add(ue),R}:new Set([ue]))},ie=async()=>{const ue=new Map(w.filter(ne=>ne.type==="file").map(ne=>[ne.path,ne])),X=new Map(x.map(ne=>[ne.path,ne])),R=Array.from(h).map(ne=>ue.get(ne)??X.get(ne)).filter(ne=>!!ne);M(!0);try{await r(R),g(new Set),c(!1),u(!1)}finally{M(!1)}},P=l.useMemo(()=>o?w.filter(ue=>ue.path.substring(0,ue.path.lastIndexOf("/"))===o):[],[w,o]),B=f.trim().length>0,te=ue=>w.filter(X=>X.path.substring(0,X.path.lastIndexOf("/"))===ue),ye=ue=>{if(o&&ue.startsWith(o)){const X=ue.substring(o.length);return X.startsWith("/")?X.substring(1):X}return ue.split("/").pop()||ue},se=(ue,X)=>{const R=B?ue.relativePath||ye(ue.path):ue.name,ne=B&&R.includes("/")&&R.length>45,Z=ne?ui(R,{maxLength:n?42:48}):R,q=e.jsxs("div",{className:A("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",ue.type==="file"&&h.has(ue.path)&&"bg-primary/10"),style:{paddingLeft:`${X*12}px`},onClick:_=>{_.preventDefault(),_.stopPropagation(),ue.type==="file"&&Y(ue.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:F(ue)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":R,children:Z})]}),ue.type==="file"&&h.has(ue.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return ne?e.jsxs(at,{delayDuration:120,children:[e.jsx(it,{asChild:!0,children:q}),e.jsx(rt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:R})})]},ue.path):l.cloneElement(q,{key:ue.path})},V=(ue,X)=>{const R=ue.type==="directory",ne=R?te(ue.path):[],Z=y.has(ue.path);return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:A("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!R&&h.has(ue.path)&&"bg-primary/10"),style:{paddingLeft:`${X*12}px`},onClick:q=>{q.preventDefault(),q.stopPropagation(),R?$(ue.path):Y(ue.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:F(ue)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:ue.name}),!R&&h.has(ue.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),R&&Z&&ne.length>0&&e.jsx("div",{children:ne.map(q=>V(q,X+1))})]},ue.path)},ve=h.size>0?`${h.size} file${h.size!==1?"s":""} selected`:"No files selected",Ae=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:ve}),e.jsx(Ne,{size:"sm",onClick:ie,disabled:h.size===0||k,className:"h-6 typography-meta",children:k?"Attaching...":"Attach Files"})]}),Pe=n?"flex-1 min-h-[240px]":"h-[300px]",je=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(li,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(bt,{value:f,onChange:ue=>m(ue.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:ue=>ue.stopPropagation()}),f&&e.jsx("button",{onClick:ue=>{ue.stopPropagation(),m("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-accent rounded",children:e.jsx(Zt,{className:"h-3 w-3"})})]})}),e.jsxs(If,{className:Pe,children:[C&&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..."})}),E&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:E})}),!C&&!E&&e.jsxs("div",{className:"py-1 px-2",children:[B?N?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):x.map(ue=>se(ue,0)):P.map(ue=>V(ue,0)),!B&&P.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&&!N&&x.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),De=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),u(!0)},children:t});return n?e.jsxs(e.Fragment,{children:[De,e.jsx(Bt,{open:d,onClose:()=>u(!1),title:"Select Project Files",footer:Ae,children:e.jsx("div",{className:"flex flex-col gap-0",children:je})})]}):e.jsxs(Ft,{open:i,onOpenChange:c,children:[e.jsx(Lt,{asChild:!0,children:t}),e.jsxs(_t,{className:"w-[520px] p-0 overflow-hidden flex flex-col ml-16",align:"center",sideOffset:5,children:[je,e.jsx(No,{}),Ae]})]})},Pr=[{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 xs(r){if(!r||r==="build")return Pr[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)%(Pr.length-1);return Pr[t]}const Ff=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),al=r=>Ff(r),Lf=r=>r?typeof r=="string"?r==="ask":al(r)?Object.values(r).some(s=>s==="ask"):!1:!1,_f=r=>r?typeof r=="string"?r==="deny":al(r)?Object.values(r).some(s=>s==="deny"):!1:!1,il=({agentDefaultEditMode:r,webfetchPermission:s,bashPermission:t})=>{const n=Lf(t),o=_f(t),a=!n&&!o,i=s==="allow",c=s!=="deny",d=r==="allow"||r==="full",u=r==="ask";let f=r;d&&i&&a?f="full":d&&n?f="allow":u&&(f="ask");const m={ask:u,allow:u||d&&n,full:r!=="deny"&&c&&n,deny:!1},p=m.allow||m.full;return{cascadeDefaultMode:f,modeAvailability:m,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:c}},Rr=r=>r==="primary"||r==="all"||r===void 0||r===null,Of=[{key:"tool_call",icon:yo,label:"Tool calling",isActive:r=>r?.tool_call===!0},{key:"reasoning",icon:mn,label:"Reasoning",isActive:r=>r?.reasoning===!0}],$f={text:{icon:di,label:"Text"},image:{icon:Us,label:"Image"},video:{icon:zc,label:"Video"},audio:{icon:$c,label:"Audio"},pdf:{icon:hn,label:"PDF"}},zf=r=>r.trim().toLowerCase(),nr=(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=>zf(o)))).map(o=>{const a=$f[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Bf=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Hf=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),zs=r=>{if(typeof r!="number"||Number.isNaN(r))return"—";if(r===0)return"0";const s=Bf.format(r);return s.endsWith(".0")?s.slice(0,-2):s},Fr=r=>typeof r!="number"||!Number.isFinite(r)?"—":Hf.format(r),Ln=r=>Of.filter(s=>s.isActive(r)).map(s=>({key:s.key,icon:s.icon,label:s.label})),Ta=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},Ia=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)},Pa=({className:r})=>{const{providers:s,agents:t,currentProviderId:n,currentModelId:o,currentAgentName:a,setProvider:i,setModel:c,setAgent:d,getCurrentProvider:u,getModelMetadata:f,getCurrentAgent:m}=yt(),{currentSessionId:p,messages:h,saveSessionAgentSelection:g,getSessionAgentSelection:y,saveAgentModelForSession:b,getAgentModelForSession:w,analyzeAndSaveExternalSessionChoices:j,getSessionAgentEditMode:x,setSessionAgentEditMode:v}=we(),N=ot(W=>W.hasHydrated),{isMobile:S}=wt(),[C,D]=l.useState(null),[k,M]=l.useState(null),E=l.useCallback(()=>D(null),[]),I=l.useCallback(()=>M(null),[]),L=l.useRef(void 0),[F,$]=l.useState(()=>{const W=new Set;return n&&W.add(n),W}),[Y,ie]=l.useState(!1),[P,B]=l.useState(!1),[te,ye]=l.useState(!1),se=l.useId();l.useEffect(()=>{C==="model"&&$(()=>{const W=new Set;return n&&W.add(n),W})},[C,n]),l.useEffect(()=>{C!=="agent"&&ie(!1)},[C]),l.useEffect(()=>{P||ye(!1)},[P]);const V=m?.(),ve=V?.permission?.edit;let Ae="ask";(ve==="allow"||ve==="ask"||ve==="deny"||ve==="full")&&(Ae=ve);const Pe=V?V.tools?.edit!==!1:!1;(!V||!Pe)&&(Ae="deny");const je=V?.permission?.webfetch,De=V?.permission?.bash,ue=l.useMemo(()=>il({agentDefaultEditMode:Ae,webfetchPermission:je,bashPermission:De}),[Ae,je,De]),{cascadeDefaultMode:X,modeAvailability:R,autoApproveAvailable:ne}=ue,Z=!!(p&&a),q=Z&&p&&a?x(p,a,X):X,_={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Q=l.useCallback(W=>!R[W],[R]),U=l.useMemo(()=>!Z||Q(q)&&q!==X?X:q,[X,Q,Z,q]),K=[{mode:"ask",label:_.ask,disabled:Q("ask")},{mode:"allow",label:_.allow,disabled:Q("allow")},{mode:"full",label:_.full,disabled:Q("full")}],ee=l.useMemo(()=>ar(U),[U]),re=!Z||!ne;l.useEffect(()=>{re&&(ie(!1),ye(!1))},[re]);const ce=S?"h-9":"h-8",be=S?"h-5 w-5":"h-4 w-4",ae=S?"h-5 w-5":"h-4 w-4",Be=S?"typography-micro":"typography-meta",qe=S?"gap-x-2":"gap-x-3",nt=_[U],et=l.useCallback((W,le=be)=>{const xe=A(le,"flex-shrink-0"),Te=ar(W),lt={color:Te?Te.text:"var(--foreground)"};return W==="full"?e.jsx(as,{className:xe,style:lt}):W==="allow"?e.jsx($r,{className:xe,style:lt}):W==="deny"?e.jsx(cr,{className:xe,style:lt}):e.jsx(yr,{className:xe,style:lt})},[be]),st=l.useCallback(W=>{re||!p||!a||Q(W)||(v(p,a,W,X),B(!1),ie(!1),ye(!1))},[X,re,p,a,v,B,ye,Q]),Ke=u(),He=Array.isArray(Ke?.models)?Ke.models:[],Ee=n&&o?f(n,o):void 0,Ue=Ln(Ee),Le=nr(Ee,"input"),ze=nr(Ee,"output"),O=[{label:"Input",value:Fr(Ee?.cost?.input)},{label:"Output",value:Fr(Ee?.cost?.output)},{label:"Cache read",value:Fr(Ee?.cost?.cache_read)},{label:"Cache write",value:Fr(Ee?.cost?.cache_write)}],de=[{label:"Context",value:zs(Ee?.limit?.context)},{label:"Output",value:zs(Ee?.limit?.output)}],J=l.useRef(void 0),z=p?h.get(p)?.length??-1:-1,me=l.useRef(null),oe=l.useCallback((W,le,xe)=>{if(!W||!le)return"model-missing";const Te=s.find(Ce=>Ce.id===W);return Te?(Array.isArray(Te.models)?Te.models:[]).find(Ce=>Ce.id===le)?(i(W),c(le),p&&xe&&b(p,xe,W,le),"applied"):"model-missing":"provider-missing"},[s,i,c,p,b]);l.useEffect(()=>{if(!p){me.current=null;return}if(!N||s.length===0||t.length===0)return;(!me.current||me.current.sessionId!==p)&&(me.current={sessionId:p,resolved:!1,inFlight:!1});const W=me.current;if(!W||W.resolved||W.inFlight)return;let le=!1;const xe=()=>{if(le)return;const Ce=me.current;Ce&&Ce.sessionId===p&&(Ce.resolved=!0,Ce.inFlight=!1)},Te=()=>{const Ce=y(p);if(Ce){a!==Ce&&d(Ce);const Ve=w(p,Ce);if(Ve){const ut=oe(Ve.providerId,Ve.modelId,Ce);if(ut==="applied")return"resolved";if(ut==="provider-missing")return"waiting"}else return"resolved"}for(const Ve of t){const ut=w(p,Ve.name);if(!ut)continue;a!==Ve.name&&d(Ve.name),g(p,Ve.name);const Wt=oe(ut.providerId,ut.modelId,Ve.name);if(Wt==="applied")return"resolved";if(Wt==="provider-missing")return"waiting"}return"continue"},tt=()=>{if(t.length===0)return;const Ce=t.filter(ut=>Rr(ut.mode)),Ve=t.find(ut=>ut.name==="build")||Ce[0]||t[0];Ve&&(g(p,Ve.name),a!==Ve.name&&d(Ve.name),Ve.model?.providerID&&Ve.model?.modelID&&oe(Ve.model.providerID,Ve.model.modelID,Ve.name))};return(async()=>{try{const Ce=Te();if(Ce==="resolved"){xe();return}if(Ce==="waiting"||z===-1)return;if(z>0){W.inFlight=!0;try{const Ve=await j(p,t);if(le)return;if(Ve.size>0){let ut=null,Wt=-1/0;for(const[pt,It]of Ve)It.timestamp>Wt&&(Wt=It.timestamp,ut=pt);if(ut){g(p,ut),a!==ut&&d(ut);const pt=Ve.get(ut);if(pt){const It=oe(pt.providerId,pt.modelId,ut);if(It==="applied"){xe();return}if(It==="provider-missing")return}else{xe();return}}}}catch(Ve){le||console.error("[ModelControls] Error resolving session from messages:",Ve)}finally{const Ve=me.current;!le&&Ve&&Ve.sessionId===p&&(Ve.inFlight=!1)}}tt(),xe()}catch(Ce){le||console.error("[ModelControls] Error in session switch:",Ce)}})(),()=>{le=!0}},[p,z,t,a,y,w,d,oe,j,g,N,s]),l.useEffect(()=>{if(!N||!p||s.length===0||t.length===0)return;const le=y(p)||a;if(!le)return;const xe=w(p,le);if(!xe)return;const Te=s.find(Ve=>Ve.id===xe.providerId);if(!Te||!(Array.isArray(Te.models)?Te.models.some(Ve=>Ve.id===xe.modelId):!1))return;const lt=n===xe.providerId,Ce=o===xe.modelId;lt&&Ce||(le!==a&&d(le),oe(xe.providerId,xe.modelId,le))},[N,p,a,n,o,s,t,y,w,oe,d]),l.useEffect(()=>{if(!N)return;(async()=>{try{if(a!==J.current&&(J.current=a,a&&p)){await new Promise(Te=>setTimeout(Te,50));const le=w(p,a);if(le){const Te=oe(le.providerId,le.modelId,a);if(Te==="applied"||Te==="provider-missing")return}const xe=t.find(Te=>Te.name===a);if(xe?.model?.providerID&&xe?.model?.modelID&&oe(xe.model.providerID,xe.model.modelID,a)==="provider-missing")return}}catch(le){console.error("[ModelControls] Agent change error:",le)}})()},[a,p,w,oe,t,N]);const fe=W=>{try{d(W),B(!1),p&&g(p,W),S&&E()}catch(le){console.error("[ModelControls] Handle agent change error:",le)}},ke=(W,le)=>{try{const xe=oe(W,le,a||void 0);if(xe!=="applied"){xe==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",W):xe==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:W,modelId:le});return}S&&E()}catch(xe){console.error("[ModelControls] Handle model change error:",xe)}},_e=W=>{const le=typeof W?.name=="string"?W.name:typeof W?.id=="string"?W.id:"";return le.length>40?le.substring(0,37)+"...":le},Ye=()=>s.find(le=>le.id===n)?.name||n,Je=()=>{if(!n||!o||He.length===0)return"Not selected";const W=He.find(le=>le.id===o);return _e(W)},$e=()=>{if(!a){const le=t.filter(tt=>Rr(tt.mode)),Te=le.find(tt=>tt.name==="build")||le[0];return Te?Ze(Te.name):"Select Agent"}const W=t.find(le=>le.name===a);return Ze(W?W.name:a)},Ze=W=>W.charAt(0).toUpperCase()+W.slice(1),Qe=(W,le,xe)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:le,"aria-label":le,role:"img",children:e.jsx(W,{className:"h-3.5 w-3.5"})},xe),ct=l.useCallback(W=>{$(le=>{const xe=new Set(le);return xe.has(W)?xe.delete(W):xe.add(W),xe})},[]),Nt=l.useCallback(W=>{L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{M(W)},500)},[]),gt=l.useCallback(()=>{L.current&&clearTimeout(L.current)},[]);l.useEffect(()=>()=>{L.current&&clearTimeout(L.current)},[]);const kt=()=>!S||k!=="model"?null:e.jsx(Bt,{open:!0,onClose:I,title:Ee?.name||Je(),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:Ye()})]}),Ue.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:Ue.map(({key:W,icon:le,label:xe})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[Qe(le,xe,`cap-${W}`),e.jsx("span",{className:"typography-meta text-foreground",children:xe})]},W))})]}),(Le.length>0||ze.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:[Le.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:Le.map(({key:W,icon:le,label:xe})=>Qe(le,`${xe} input`,`input-${W}`))})]}),ze.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:ze.map(({key:W,icon:le,label:xe})=>Qe(le,`${xe} output`,`output-${W}`))})]})]})]}),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:zs(Ee?.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:zs(Ee?.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:Ta(Ee?.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:Ia(Ee?.release_date)})]})]})]})]})}),H=()=>{if(!S||k!=="agent"||!V)return null;const W=Object.entries(V.tools||{}).filter(([,Ce])=>Ce).map(([Ce])=>Ce).sort(),le=!!(V.prompt&&V.prompt.trim().length>0),xe=V.model?.providerID&&V.model?.modelID,Te=V.temperature!==void 0||V.topP!==void 0,tt=Ce=>et(Ce==="full"||Ce==="allow"||Ce==="deny"?Ce:"ask","h-3.5 w-3.5"),lt=Ce=>Ce==="full"?"Full":Ce==="allow"?"Allow":Ce==="deny"?"Deny":"Ask";return e.jsx(Bt,{open:!0,onClose:I,title:Ze(V.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[V.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:V.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:V.mode==="primary"?"Primary":V.mode==="subagent"?"Subagent":V.mode==="all"?"All":"—"})]}),(xe||Te)&&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"}),xe&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[V.model.providerID," / ",V.model.modelID]}),Te&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[V.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:V.temperature})]}),V.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:V.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"}),W.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:W.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(V.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:lt(V.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 V.permission?.bash=="string"?V.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:lt(typeof V.permission?.bash=="string"?V.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(V.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:lt(V.permission?.webfetch)})]})]})]})]}),le&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx($r,{className:"h-4 w-4 text-foreground"})]})})]})})},T=()=>S?e.jsx(Bt,{open:C==="model",onClose:E,title:"Select model",children:e.jsx("div",{className:"space-y-2",children:s.map(W=>{const le=Array.isArray(W.models)?W.models:[];if(le.length===0)return null;const xe=W.id===n,Te=F.has(W.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",onClick:()=>ct(W.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Te,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{providerId:W.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:W.name}),xe&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Te?e.jsx(ft,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"})]}),Te&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:le.map(tt=>{const lt=xe&&tt.id===o,Ce=f(W.id,tt.id),Ve=Ln(Ce).slice(0,3),ut=nr(Ce,"input");return e.jsx("button",{type:"button",onClick:()=>ke(W.id,tt.id),className:A("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",lt?"bg-primary/15 text-primary":"hover:bg-accent/40"),children:e.jsxs("div",{className:"flex min-w-0 flex-col",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:_e(tt)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 pt-0.5",children:[Ve.map(({key:Wt,icon:pt,label:It})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:It,"aria-label":It,children:e.jsx(pt,{className:"h-3 w-3"})},`cap-${W.id}-${tt.id}-${Wt}`)),ut.map(({key:Wt,icon:pt,label:It})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:`${It} input`,"aria-label":`${It} input`,children:e.jsx(pt,{className:"h-3 w-3"})},`input-${W.id}-${tt.id}-${Wt}`))]})]})},tt.id)})})]},W.id)})})}):null,G=()=>{if(!S)return null;const W=t.filter(le=>Rr(le.mode));return e.jsx(Bt,{open:C==="agent",onClose:E,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[W.map(le=>{const xe=le.name===a,Te=xs(le.name);return e.jsxs("button",{type:"button",className:A("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",Te.class,xe?"active":"border-border/40"),onClick:()=>fe(le.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:A("h-2 w-2 rounded-full",Te.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:xe?{color:`var(${Te.var})`}:void 0,children:Ze(le.name)})]}),le.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:le.description})]},le.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:re,onClick:()=>{re||ie(le=>!le)},className:A("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",re?"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:ee?ee.text:"var(--foreground)",mixBlendMode:"normal"},children:nt})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:A("flex items-center justify-center p-1",!ee&&"text-muted-foreground"),style:ee?{color:ee.text}:void 0,children:et(U,be)}),e.jsx(ft,{className:A("h-4 w-4 text-muted-foreground transition-transform",Y?"rotate-180":"")})]})]}),Y&&!re&&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:K.map(le=>{const xe=le.mode===U,Te=ar(le.mode);return e.jsxs("button",{type:"button",disabled:le.disabled,onClick:()=>st(le.mode),className:A("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",le.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",xe?"bg-primary/10":void 0),style:xe&&Te?{backgroundColor:Te.background??void 0}:void 0,children:[et(le.mode,be),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:Te?Te.text:"var(--foreground)"},children:le.label})})]},le.mode)})})})]})]})})},pe=()=>e.jsx(rt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ee?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:Ee.name||Je()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:Ye()})]}),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:Ue.length>0?Ue.map(({key:W,icon:le,label:xe})=>Qe(le,xe,`cap-${W}`)):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:Le.length>0?Le.map(({key:W,icon:le,label:xe})=>Qe(le,`${xe} input`,`input-${W}`)):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:ze.length>0?ze.map(({key:W,icon:le,label:xe})=>Qe(le,`${xe} output`,`output-${W}`)):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)"}),O.map(W=>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:W.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:W.value})]},W.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"}),de.map(W=>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:W.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:W.value})]},W.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:Ta(Ee.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:Ia(Ee.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),Me=()=>e.jsxs(at,{delayDuration:1e3,children:[S?e.jsxs("button",{type:"button",onClick:()=>D("model"),onTouchStart:()=>Nt("model"),onTouchEnd:gt,onTouchCancel:gt,className:A("flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70 max-w-full justify-end",ce),children:[n?e.jsx(Jt,{providerId:n,className:A(ae,"flex-shrink-0")}):e.jsx(as,{className:A(ae,"text-muted-foreground")}),e.jsx("span",{className:"typography-micro font-medium truncate min-w-0 max-w-[36vw] text-right",children:Je()})]}):e.jsxs(Ft,{open:P,onOpenChange:B,children:[e.jsx(it,{asChild:!0,children:e.jsx(Lt,{asChild:!0,children:e.jsxs("div",{className:A("flex items-center gap-1.5 cursor-pointer hover:opacity-70 w-fit",ce),children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{providerId:n,className:A(ae,"flex-shrink-0")}),e.jsx(as,{className:A(ae,"text-primary/60 hidden")})]}):e.jsx(as,{className:A(ae,"text-muted-foreground")}),e.jsx("span",{className:A(Be,"font-medium whitespace-nowrap text-foreground","max-w-[32vw]","md:max-w-[20vw]","truncate"),children:Je()},`${n}-${o}`)]})})}),e.jsx(_t,{className:"max-w-[300px]",children:s.map(W=>{const le=Array.isArray(W.models)?W.models:[];return le.length===0?e.jsxs(mt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(Jt,{providerId:W.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),W.name," (No models)"]},W.id):e.jsxs(Pi,{children:[e.jsxs(Ri,{className:"typography-meta",children:[e.jsx(Jt,{providerId:W.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),W.name]}),e.jsx(Fi,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Ge,{outerClassName:"max-h-[320px] min-w-[200px]",children:le.map(xe=>{const Te=f(W.id,xe.id),tt=Ln(Te).map(pt=>({...pt,id:`cap-${pt.key}`})),lt=[...nr(Te,"input"),...nr(Te,"output")],Ce=Array.from(new Map(lt.map(pt=>[pt.key,pt])).values()).map(pt=>({...pt,id:`mod-${pt.key}`})),Ve=[...tt,...Ce],ut=zs(Te?.limit?.context),Wt=zs(Te?.limit?.output);return e.jsx(mt,{className:"typography-meta",onSelect:()=>{ke(W.id,xe.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:_e(xe)}),Te?.limit?.context||Te?.limit?.output?e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[Te?.limit?.context?`${ut} ctx`:"",Te?.limit?.context&&Te?.limit?.output?" • ":"",Te?.limit?.output?`${Wt} out`:""]}):null]}),e.jsx("div",{className:"ml-auto flex items-center gap-1",children:Ve.map(({id:pt,icon:It,label:Ro})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground","aria-label":Ro,role:"img",title:Ro,children:e.jsx(It,{className:"h-3 w-3"})},pt))})]})},xe.id)})})})]},W.id)})})]}),pe()]}),Re=()=>{if(!V)return e.jsx(rt,{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 W=Object.entries(V.tools||{}).filter(([,Ce])=>Ce).map(([Ce])=>Ce).sort(),le=!!(V.prompt&&V.prompt.trim().length>0),xe=V.model?.providerID&&V.model?.modelID,Te=V.temperature!==void 0||V.topP!==void 0,tt=Ce=>et(Ce==="full"||Ce==="allow"||Ce==="deny"?Ce:"ask","h-3.5 w-3.5"),lt=Ce=>Ce==="full"?"Full":Ce==="allow"?"Allow":Ce==="deny"?"Deny":"Ask";return e.jsx(rt,{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:Ze(V.name)}),V.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:V.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:V.mode==="primary"?"Primary":V.mode==="subagent"?"Subagent":V.mode==="all"?"All":"—"})]}),(xe||Te)&&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"}),xe?e.jsxs("span",{className:"typography-meta text-foreground",children:[V.model.providerID," / ",V.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),Te&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[V.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:V.temperature})]}),V.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:V.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"}),W.length>0?e.jsx("div",{className:"flex flex-wrap gap-1 leading-tight",children:W.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(V.permission?.edit),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:lt(V.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 V.permission?.bash=="string"?V.permission.bash:void 0),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:lt(typeof V.permission?.bash=="string"?V.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(V.permission?.webfetch),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:lt(V.permission?.webfetch)})]})]})]}),le&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx($r,{className:"h-4 w-4 text-foreground"})]})]})})},Ie=()=>S?e.jsxs("button",{type:"button",onClick:()=>D("agent"),onTouchStart:()=>Nt("agent"),onTouchEnd:gt,onTouchCancel:gt,className:A("flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",ce,"cursor-pointer hover:opacity-70",S&&"ml-1"),children:[e.jsx(xr,{className:A(ae,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${xs(a).var})`}:void 0}),e.jsx("span",{className:A(Be,"font-medium truncate","max-w-[36vw]","md:max-w-[20vw]"),style:a?{color:`var(${xs(a).var})`}:void 0,children:$e()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(at,{delayDuration:1e3,children:[e.jsxs(Ft,{children:[e.jsx(it,{asChild:!0,children:e.jsx(Lt,{asChild:!0,children:e.jsxs("div",{className:A("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70",ce),children:[e.jsx(xr,{className:A(ae,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${xs(a).var})`}:void 0}),e.jsx("span",{className:A(Be,"font-medium min-w-0 truncate"),style:a?{color:`var(${xs(a).var})`}:void 0,children:$e()})]})})}),e.jsxs(_t,{align:"end",children:[t.filter(W=>Rr(W.mode)).map(W=>e.jsx(mt,{className:"typography-meta",onSelect:()=>fe(W.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:A("h-1 w-1 rounded-full agent-dot",xs(W.name).class)}),e.jsx("span",{className:"font-medium",children:Ze(W.name)})]}),W.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:W.description})]})},W.name)),e.jsx(No,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:re,onClick:()=>{re||ye(W=>!W)},className:A("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",re?"cursor-not-allowed opacity-60":void 0),"aria-expanded":te,"aria-controls":se,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:ee?ee.text:"var(--foreground)"},children:nt})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:A("flex items-center justify-center p-1",!ee&&"text-muted-foreground"),style:ee?{color:ee.text}:void 0,children:et(U)}),e.jsx(ft,{className:A("h-3.5 w-3.5 transition-transform text-muted-foreground",te?"rotate-180":"")})]})]}),te&&!re&&e.jsx("div",{id:se,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:K.map(W=>{const le=W.mode===U,xe=ar(W.mode);return e.jsxs("button",{type:"button",disabled:W.disabled,onClick:()=>st(W.mode),className:A("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",W.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",le?"bg-primary/10":void 0),style:le&&xe?{backgroundColor:xe.background??void 0}:void 0,children:[et(W.mode,be),e.jsx("span",{className:"typography-meta font-medium",style:{color:xe?xe.text:"var(--foreground)"},children:W.label})]},W.mode)})})]})]})]}),Re()]})}),Oe=A("flex items-center min-w-0",qe,r);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Oe,children:[e.jsx("div",{className:A("flex items-center min-w-0",S?"flex-1 min-w-0":void 0),children:Me()}),e.jsx("div",{className:A("flex items-center min-w-0",qe),children:Ie()})]}),T(),G(),kt(),H()]})},Wf=r=>r?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(r):!0,Uf=(r,s)=>{if(typeof r!="string"||r.length===0)return{sanitizedText:r,mention:null};const t=s.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!r.includes("#"))return{sanitizedText:r,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(r))!==null;){const c=i.index,d=c+i[0].length,u=c>0?r[c-1]:null;if(!Wf(u))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}},Ra=[{variant:"shine",component:({children:r,className:s,...t})=>e.jsx(Qs.span,{...t,className:A("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)=>ge.createElement(Qs.span,{...t,key:n+String(o),className:A("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:A("invisible",s),children:r}),e.jsx("span",{...t,className:A("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:A("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(Qs.span,{...t,className:A("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(Qs.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:A("absolute inset-0"),children:a.map((i,c)=>e.jsx(Qs.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:A("text-primary-muted hover:animate-text-shake",s),children:r})},{variant:"hover-decoration",component:({children:r,className:s,...t})=>e.jsx("div",{className:A("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:A("text-primary-muted",s),children:r})})}];function _n({variant:r="shine",className:s,...t}){const a=Ra.find(i=>i.variant===r)?.component||Ra[0].component;return e.jsx(si,{children:e.jsx(a,{...t,className:s})})}const Vf=2e3,Gf=1500;function qf({statusText:r,isWaitingForPermission:s,wasAborted:t,completionId:n,isComplete:o}){const[a,i]=ge.useState(null),[c,d]=ge.useState(!1),[u,f]=ge.useState(!1),[m,p]=ge.useState(!1),[h,g]=ge.useState(null),[y,b]=ge.useState(!1),w=ge.useRef(0),j=ge.useRef([]),x=ge.useRef(!1),v=ge.useRef(null),N=ge.useRef(null),S=ge.useRef(null),C=ge.useRef(null),D=ge.useRef(!1),k=ge.useRef(!1),M=ge.useRef(!1),E=ge.useRef(!0),I=ge.useRef(null),L=ge.useRef(null),F=(P,B)=>{if(v.current&&(clearTimeout(v.current),v.current=null),N.current&&(clearTimeout(N.current),N.current=null),S.current&&(clearTimeout(S.current),S.current=null),P==="aborted"){i(null),d(!1),p(!1),g("aborted"),b(!1),C.current="aborted",D.current=!0,k.current=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>f(!0)):f(!0);return}g(null),p(!1),C.current=P,D.current=!0,a!==null&&a!==P&&(b(!0),S.current=setTimeout(()=>{b(!1),S.current=null},150)),i(P),d(B),u||(typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>{f(!0)}):f(!0))};if(ge.useEffect(()=>{const P=Date.now();r?(x.current=!1,a?(r!==a||!!s!==c)&&j.current.push({status:r,permission:!!s}):(F(r,!!s),w.current=P,j.current=[])):x.current=!0},[r,s,a,c,t]),ge.useEffect(()=>{t&&(k.current=!0)},[t]),ge.useEffect(()=>{M.current=!!o},[o]),ge.useEffect(()=>{o&&(x.current=!0)},[o]),ge.useEffect(()=>{const P=te=>{if(m)return;const ye=C.current!==null||D.current;te&&ye?(p(!1),f(!0),i(null),d(!1),g(te),C.current=null,b(!1),te==="success"&&n&&(I.current=n),L.current=Date.now(),N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{f(!1),g(null),D.current=!1,N.current=null},Gf)):(p(!0),f(!1),g(null),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{i(null),d(!1),p(!1),D.current=!1,C.current=null,v.current=null},180)),k.current=!1},B=setInterval(()=>{const te=Date.now(),ye=te-w.current,se=x.current&&M.current;if(!(!se&&j.current.length>0&&ye<Vf)){if(x.current&&k.current)x.current=!1,j.current=[],P("aborted");else if(!se&&j.current.length>0){const ve=j.current[j.current.length-1];F(ve.status,ve.permission),w.current=te,j.current=[]}else if(x.current){x.current=!1,j.current.length>0&&(D.current=!0),j.current=[];let ve=null;if(k.current?ve="aborted":M.current&&(ve="success",D.current=!0),ve==="success"&&n&&I.current===n){i(null),d(!1),p(!1),f(!1),g(null),j.current=[],D.current=!1,C.current=null,x.current=!1,k.current=!1;return}P(ve)}}},50);return()=>clearInterval(B)},[m]),ge.useEffect(()=>()=>{v.current&&clearTimeout(v.current),N.current&&clearTimeout(N.current),S.current&&clearTimeout(S.current)},[]),ge.useEffect(()=>{if(typeof window>"u")return;E.current=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0;const P=()=>{E.current=!0},B=()=>{E.current=!1};return window.addEventListener("focus",P),window.addEventListener("blur",B),()=>{window.removeEventListener("focus",P),window.removeEventListener("blur",B)}},[]),ge.useEffect(()=>{const P=()=>{if(typeof document>"u"||typeof Date>"u"||document.visibilityState!=="visible")return;const B=L.current;(h!==null||a!==null)&&B&&Date.now()-B>500&&(i(null),d(!1),p(!1),f(!1),g(null),j.current=[],D.current=!1,C.current=null,x.current=!1,k.current=!1)};return document.addEventListener("visibilitychange",P),window.addEventListener("focus",P),()=>{document.removeEventListener("visibilitychange",P),window.removeEventListener("focus",P)}},[a,h]),!a&&h===null)return null;let $;h==="success"?$="Done":h==="aborted"?$="Aborted":a?$=a.charAt(0).toUpperCase()+a.slice(1):$="Working";const Y=c?"assertive":"polite",ie=h===null?`${$}...`:$;return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${u&&!m?"opacity-100":"opacity-0"}`,role:"status","aria-live":Y,"aria-label":$,"data-waiting":c?"true":void 0,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[h===null&&e.jsx(_n,{variant:"shine",className:"typography-ui-header transition-opacity duration-150",style:{opacity:y?.6:1},children:ie}),h==="success"&&e.jsx(_n,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150",style:{opacity:y?.6:1},children:"Done"}),h==="aborted"&&e.jsx(_n,{variant:"hover-enter",className:"typography-ui-header transition-opacity duration-150 text-status-error",style:{opacity:y?.6:1},children:"Aborted"})]})})}const Kf=r=>!r||typeof r!="object"?!1:!!r.synthetic,ro=r=>!Array.isArray(r)||r.length===0?!1:r.every(s=>Kf(s)),Yf={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Jf(r){const s=we(t=>!r||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(r)??"idle");return l.useMemo(()=>{if(s==="idle")return Yf;const t=s==="busy",n=s==="cooldown";return{phase:s,isWorking:t||n,isBusy:t,isCooldown:n}},[s])}function ll(){const r=we(s=>s.currentSessionId);return Jf(r)}const Xf={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},Fa=r=>r.role==="assistant",Zf=r=>r.type==="reasoning",cl=r=>r.type==="text",La=r=>{if(cl(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},_a=r=>(cl(r)||Zf(r),r.time),Qf=r=>{if(r.tool)return r.tool;const s=r;return typeof s.name=="string"?s.name:"tool"};function dl(){const{currentSessionId:r,messages:s,permissions:t,sessionAbortFlags:n}=we(xo(h=>({currentSessionId:h.currentSessionId,messages:h.messages,permissions:h.permissions,sessionAbortFlags:h.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=ll(),c=l.useMemo(()=>r?s.get(r)??[]:[],[r,s]),d=l.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const h=c.filter(v=>Fa(v.info)&&!ro(v.parts));if(h.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working"};const g=[...h].sort((v,N)=>{const S=typeof v.info.time?.created=="number"?v.info.time.created:null,C=typeof N.info.time?.created=="number"?N.info.time.created:null;return S!==null&&C!==null&&S!==C?S-C:v.info.id.localeCompare(N.info.id)}),y=g[g.length-1];let b,w;const j=new Set(["edit","write"]);for(let v=(y.parts??[]).length-1;v>=0;v-=1){const N=y.parts?.[v];if(N)switch(N.type){case"reasoning":{const S=N.time??_a(N);(!S||typeof S.end>"u")&&!b&&(b="reasoning");break}case"tool":{const S=N.state?.status;if((S==="running"||S==="pending")&&!b){const C=Qf(N);j.has(C)?b="editing":(b="tool",w=C)}break}case"text":{const S=La(N)??"";if(typeof S=="string"&&S.trim().length>0){const C=_a(N);(!C||typeof C.end>"u")&&!b&&(b="text")}break}}}const x=b==="editing"?"editing":b==="tool"&&w?`using ${w}`:b==="reasoning"?"thinking":b==="text"?"composing":"working";return{activePartType:b,activeToolName:w,statusText:x}},[c]),u=l.useMemo(()=>{const h=r,g=h?n?.get(h)??null:null,y=!!(g&&!g.acknowledged);return{wasAborted:y,abortActive:y}},[r,n]),f=l.useMemo(()=>{if(u.wasAborted)return{...Xf,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const h=a,g=o==="busy",y=i;let b="idle";return h&&(d.activePartType==="tool"||d.activePartType==="editing"?b="tooling":b=y?"cooldown":"streaming"),{activity:b,hasWorkingContext:h,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:h,isStreaming:g,isCooldown:y,lifecyclePhase:g?"streaming":y?"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:y}},[o,a,i,d,u]),m=l.useMemo(()=>{const h=a&&d.activePartType==="text";if(!h||c.length===0)return{isActive:h,characterCount:0};const g=c.filter(w=>Fa(w.info)&&!ro(w.parts));if(g.length===0)return{isActive:h,characterCount:0};const y=g[g.length-1];let b=0;return(y.parts??[]).forEach(w=>{if(w.type!=="text")return;const j=La(w)??"";typeof j=="string"&&j.trim().length>0&&(b+=j.length)}),{isActive:h,characterCount:b}},[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:m,working:p}}const ep=8,tp=r=>r==="primary"||r==="all"||r===void 0||r===null,On=({onOpenSettings:r,scrollToBottom:s})=>{const[t,n]=l.useState(""),[o,a]=l.useState(!1),[i,c]=l.useState(!1),[d,u]=l.useState(""),[f,m]=l.useState(!1),[p,h]=l.useState(""),[g,y]=l.useState(!1),[b,w]=l.useState(""),[j,x]=l.useState(null),v=l.useRef(null),N=l.useRef(null),S=l.useRef(null),C=l.useRef(null),D=l.useRef(null),k=we(T=>T.sendMessage),M=we(T=>T.currentSessionId),E=we(T=>T.abortCurrentOperation),I=we(T=>T.acknowledgeSessionAbort),L=we(T=>T.abortPromptSessionId),F=we(T=>T.abortPromptExpiresAt),$=we(T=>T.clearAbortPrompt),Y=we(T=>T.attachedFiles),ie=we(T=>T.addAttachedFile),P=we(T=>T.addServerFile),B=we(T=>T.clearAttachedFiles),te=we(T=>T.saveSessionAgentSelection),{currentProviderId:ye,currentModelId:se,currentAgentName:V,agents:ve,setAgent:Ae}=yt(),{isMobile:Pe}=Fe(),{working:je}=dl(),[De,ue]=l.useState(!1),X=l.useRef(null),R=l.useRef(!1),ne=l.useMemo(()=>{if(V)return ve.find(T=>T.name===V)},[ve,V]),Z=l.useMemo(()=>{const T=ne?.permission?.edit;let G="ask";(T==="allow"||T==="ask"||T==="deny"||T==="full")&&(G=T);const pe=ne?ne.tools?.edit!==!1:!1;return(!ne||!pe)&&(G="deny"),G},[ne]),q=we(l.useCallback(T=>!M||!V?void 0:T.sessionAgentEditModes.get(M)?.get(V),[M,V])),_=ne?.permission?.webfetch,Q=ne?.permission?.bash,U=l.useMemo(()=>il({agentDefaultEditMode:Z,webfetchPermission:_,bashPermission:Q}),[Z,_,Q]),K=!!(M&&V),ee=l.useMemo(()=>K&&q&&U.modeAvailability[q]?q:U.cascadeDefaultMode,[U,K,q]),re=l.useMemo(()=>ar(ee),[ee]),ce=l.useMemo(()=>{if(re)return{borderColor:re.border??re.text,borderWidth:re.borderWidth??1}},[re]),be=t.trim()||Y.length>0,ae=je.isWorking,Be=l.useMemo(()=>M?L===M&&!!F:!1,[L,F,M]),qe=ae&&(Pe||Be),nt=async T=>{if(T?.preventDefault(),!be||!M)return;const G=t.replace(/^\n+|\n+$/g,"");s?.({instant:!0});const pe=G.trimStart();if(pe.startsWith("/")&&pe.slice(1).trim().split(/\s+/)[0]?.toLowerCase()==="summarize"&&s?.({instant:!0}),!ye||!se){console.warn("Cannot send message: provider or model not selected");return}const{sanitizedText:Me,mention:Re}=Uf(G,ve),Ie=Re?.name,Oe=Y.map(W=>({...W}));Oe.length>0&&B(),n(""),await k(Me,ye,se,V,Oe,Ie).catch(W=>{const le=W instanceof Error?W.message:typeof W=="string"?W:String(W??""),xe=le.toLowerCase();console.error("Message send failed:",le||W),!(xe.includes("timeout")||xe.includes("timed out")||xe.includes("may still be processing")||xe.includes("being processed")||xe.includes("failed to fetch")||xe.includes("networkerror")||xe.includes("network error")||xe.includes("gateway timeout")||xe==="failed to send message")&&(Oe.length>0&&ys.setState({attachedFiles:Oe}),he.error(le||"Message failed to send. Attachments restored."))}),v.current?.focus()},et=T=>{if(f&&C.current&&(T.key==="Enter"||T.key==="ArrowUp"||T.key==="ArrowDown"||T.key==="Escape"||T.key==="Tab")){T.preventDefault(),C.current.handleKeyDown(T.key);return}if(g&&D.current&&(T.key==="Enter"||T.key==="ArrowUp"||T.key==="ArrowDown"||T.key==="Escape"||T.key==="Tab")){T.preventDefault(),D.current.handleKeyDown(T.key);return}if(i&&S.current&&(T.key==="Enter"||T.key==="ArrowUp"||T.key==="ArrowDown"||T.key==="Escape"||T.key==="Tab")){T.preventDefault(),S.current.handleKeyDown(T.key);return}if(T.key==="Tab"&&!f&&!i){T.preventDefault(),He();return}T.key==="Enter"&&!T.shiftKey&&!Pe&&(T.preventDefault(),nt())},st=l.useCallback(()=>{X.current&&(clearTimeout(X.current),X.current=null),ue(!0),X.current=setTimeout(()=>{ue(!1),X.current=null},1800)},[]),Ke=l.useCallback(()=>{$(),st(),E()},[E,$,st]),He=()=>{const T=ve.filter(Re=>tp(Re.mode));if(T.length<=1)return;const pe=(T.findIndex(Re=>Re.name===V)+1)%T.length,Me=T[pe];Ae(Me.name),M&&te(M,Me.name)},Ee=l.useCallback(()=>{const T=v.current;if(!T)return;T.style.height="auto";const G=T.ownerDocument?.defaultView,pe=G?G.getComputedStyle(T):null,Me=pe?parseFloat(pe.lineHeight):NaN,Re=pe?parseFloat(pe.paddingTop):NaN,Ie=pe?parseFloat(pe.paddingBottom):NaN,Oe=22,le=Number.isNaN(Re)||Number.isNaN(Ie)?16:Re+Ie,Te=(Number.isNaN(Me)?Oe:Me)*ep+le,tt=T.scrollHeight||T.offsetHeight,lt=Math.min(tt,Te);T.style.height=`${lt}px`,T.style.maxHeight=`${Te}px`,x(Ce=>Ce&&Ce.height===lt&&Ce.maxHeight===Te?Ce:{height:lt,maxHeight:Te})},[]);l.useLayoutEffect(()=>{Ee()},[Ee,t,Pe]);const Ue=l.useCallback((T,G)=>{if(T.startsWith("/")){const Ie=T.indexOf(" "),Oe=T.indexOf(`
|
|
9
|
-
`),W=Math.min(Ie===-1?T.length:Ie,Oe===-1?T.length:Oe);if(G<=W&&Ie===-1){const le=T.substring(1,W);h(le),m(!0),c(!1),y(!1)}else m(!1);return}m(!1);const pe=T.substring(0,G),Me=pe.lastIndexOf("#");if(Me!==-1){const Ie=Me>0?pe[Me-1]:null,Oe=pe.substring(Me+1),W=Oe.includes(" ")||Oe.includes(`
|
|
10
|
-
`);if((!Ie||/\s/.test(Ie))&&!W){w(Oe),y(!0),c(!1);return}}y(!1),w("");const Re=pe.lastIndexOf("@");if(Re!==-1){const Ie=pe.substring(Re+1);!Ie.includes(" ")&&!Ie.includes(`
|
|
11
|
-
`)?(u(Ie),c(!0)):c(!1)}else c(!1)},[w,h,u,y,m,c]),Le=l.useCallback(T=>{if(!T)return;const G=v.current;if(!G){const Oe=t+T;n(Oe),Ue(Oe,Oe.length),requestAnimationFrame(()=>Ee());return}const pe=G.selectionStart??t.length,Me=G.selectionEnd??t.length,Re=`${t.substring(0,pe)}${T}${t.substring(Me)}`;n(Re);const Ie=pe+T.length;requestAnimationFrame(()=>{const Oe=v.current;Oe&&(Oe.selectionStart=Ie,Oe.selectionEnd=Ie),Ee()}),Ue(Re,Ie)},[Ee,t,Ue]),ze=T=>{const G=T.target.value,pe=T.target.selectionStart??G.length;n(G),Ee(),Ue(G,pe)},O=l.useCallback(async T=>{const G=new Map;Array.from(T.clipboardData.files||[]).forEach(Ie=>{Ie.type.startsWith("image/")&&G.set(`${Ie.name}-${Ie.size}`,Ie)}),Array.from(T.clipboardData.items||[]).forEach(Ie=>{if(Ie.kind==="file"&&Ie.type.startsWith("image/")){const Oe=Ie.getAsFile();Oe&&G.set(`${Oe.name}-${Oe.size}`,Oe)}});const pe=Array.from(G.values());if(pe.length===0||!M)return;T.preventDefault();const Me=T.clipboardData.getData("text");Me&&Le(Me);let Re=0;for(const Ie of pe){const Oe=we.getState().attachedFiles.length;try{await ie(Ie),we.getState().attachedFiles.length>Oe&&(Re+=1)}catch(W){console.error("Clipboard image attach failed",W),he.error(W instanceof Error?W.message:"Failed to attach image from clipboard")}}Re>0&&he.success(`Attached ${Re} image${Re>1?"s":""} from clipboard`)},[ie,M,Le]),de=T=>{const G=v.current?.selectionStart||0,Me=t.substring(0,G).lastIndexOf("@");if(Me!==-1){const Re=t.substring(0,Me)+T.name+t.substring(G);n(Re)}c(!1),u(""),v.current?.focus()},J=T=>{const pe=v.current?.selectionStart??t.length,Re=t.substring(0,pe).lastIndexOf("#");if(Re!==-1){const Ie=t.substring(0,Re)+`#${T} `+t.substring(pe);n(Ie);const Oe=Re+T.length+2;requestAnimationFrame(()=>{v.current&&(v.current.selectionStart=Oe,v.current.selectionEnd=Oe),Ee(),Ue(Ie,Oe)})}y(!1),w(""),v.current?.focus()},z=T=>{n(`/${T.name} `);const G=v.current;G&&(G._commandMetadata=T),m(!1),h(""),setTimeout(()=>{v.current&&(v.current.focus(),v.current.setSelectionRange(v.current.value.length,v.current.value.length))},0)};l.useEffect(()=>{M&&v.current&&!Pe&&v.current.focus()},[M,Pe]),l.useEffect(()=>{L&&L!==M&&$()},[L,M,$]);const me=T=>{T.preventDefault(),T.stopPropagation(),M&&!o&&a(!0)},oe=T=>{T.preventDefault(),T.stopPropagation(),T.currentTarget===T.target&&a(!1)},fe=async T=>{if(T.preventDefault(),T.stopPropagation(),a(!1),!M)return;const G=Array.from(T.dataTransfer.files);let pe=0;for(const Me of G){const Re=we.getState().attachedFiles.length;try{await ie(Me),we.getState().attachedFiles.length>Re&&(pe+=1)}catch(Ie){console.error("File attach failed",Ie),he.error(Ie instanceof Error?Ie.message:"Failed to attach file")}}pe>0&&he.success(`Attached ${pe} file${pe>1?"s":""}`)},ke=l.useCallback(async T=>{let G=0;for(const pe of T){const Me=we.getState().attachedFiles.length;try{await P(pe.path,pe.name),we.getState().attachedFiles.length>Me&&(G+=1)}catch(Re){console.error("Server file attach failed",Re),he.error(Re instanceof Error?Re.message:"Failed to attach file")}}G>0&&he.success(`Attached ${G} file${G>1?"s":""}`)},[P]),_e="gap-x-1.5 gap-y-0",Ye=Pe?"px-1.5 py-1.5":"px-2.5 py-1.5",Je=Pe?"h-9 w-9":"h-7 w-7",$e=Pe?"h-5 w-5":"h-[18px] w-[18px]",Ze=A(Je,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),Qe=e.jsx("button",{type:"submit",disabled:!be||!M,className:A(Ze,be&&M?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Bc,{className:A($e)})}),ct=e.jsx(Rf,{onFilesSelected:ke,multiSelect:!0,children:e.jsx("button",{type:"button",className:Ze,title:"Attach files from project","aria-label":"Attach files from project",children:e.jsx(Hc,{className:A($e,"text-current")})})}),Nt=r?e.jsx("button",{type:"button",onClick:r,className:Ze,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(xr,{className:A($e,"text-current")})}):null,gt=e.jsxs(e.Fragment,{children:[e.jsx(Ea,{}),ct,Nt]}),kt=je.statusText;l.useEffect(()=>{const T=!!je.wasAborted;!R.current&&T&&!De&&(st(),M&&I(M)),R.current=T},[I,M,De,st,je.wasAborted]),l.useEffect(()=>()=>{X.current&&(clearTimeout(X.current),X.current=null)},[]);const H=!De&&(je.wasAborted||!je.abortActive);return e.jsxs("form",{onSubmit:nt,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:De?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(cr,{size:18,"aria-hidden":"true"}),"Aborted"]})}):H?e.jsx(qf,{statusText:kt,isWaitingForPermission:je.isWaitingForPermission,wasAborted:je.wasAborted,completionId:je.lastCompletionId,isComplete:je.isComplete},M??"no-session"):null}),qe?e.jsx("div",{className:"flex-shrink-0 pr-[2ch]",children:Pe?e.jsx("button",{type:"button",onClick:Ke,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(cr,{size:18,"aria-hidden":"true"})}):e.jsxs("button",{type:"button",onClick:Ke,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(cr,{size:11,className:"text-white","aria-hidden":"true"}),"Abort"]})}):null]}),e.jsxs("div",{ref:N,className:A("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:me,onDragLeave:oe,onDrop:fe,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(Ea,{}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Df,{}),e.jsxs("div",{className:A("rounded-xl border border-border/20 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:ce,children:[f&&e.jsx(nl,{ref:C,searchQuery:p,onCommandSelect:z,onClose:()=>m(!1)}),g&&e.jsx(ol,{ref:D,searchQuery:b,onAgentSelect:J,onClose:()=>y(!1)}),i&&e.jsx(Ef,{ref:S,searchQuery:d,onFileSelect:de,onClose:()=>c(!1)}),e.jsx(Rs,{ref:v,"data-chat-input":"true",value:t,onChange:ze,onKeyDown:et,onPaste:O,placeholder:M?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!M,className:A("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",Pe?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:j?`${j.height}px`:void 0,maxHeight:j?`${j.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:A("rounded-b-xl bg-transparent",Ye,Pe?"flex items-center gap-x-1.5":A("flex items-center justify-between",_e)),"data-chat-input-footer":"true",children:Pe?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:gt}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-x-1 min-w-0",children:[e.jsx(Pa,{className:A("flex items-center justify-end min-w-0")}),Qe]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:A("flex items-center flex-shrink-0",_e),children:gt}),e.jsxs("div",{className:A("flex items-center flex-1 justify-end",_e,"md:gap-x-3"),children:[e.jsx(Pa,{className:A("flex-1 min-w-0 justify-end")}),Qe]})]})})]})]})]})};function $n({className:r,...s}){return e.jsx("div",{"data-slot":"skeleton",className:A("bg-accent animate-pulse rounded-xl",r),...s})}const Oa=({className:r="",width:s=70,height:t=70,isAnimated:n=!1})=>{const o=cf();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})]})},sp={'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"}},rp={'code[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0",overflow:"auto"},comment:{color:"#7a756a",fontStyle:"italic"},prolog:{color:"#7a756a"},doctype:{color:"#7a756a"},cdata:{color:"#7a756a"},punctuation:{color:"#6b6963"},property:{color:"#c07845"},tag:{color:"#b96f55"},boolean:{color:"#b97659"},number:{color:"#b97659"},constant:{color:"#4791ba"},symbol:{color:"#4791ba"},deleted:{color:"#c15748"},selector:{color:"#6a9354"},"attr-name":{color:"#9f7d3e"},string:{color:"#6a9354"},char:{color:"#6a9354"},builtin:{color:"#4791ba"},inserted:{color:"#6a9354"},operator:{color:"#c07845"},entity:{color:"#d09930",cursor:"help"},url:{color:"#4791ba"},".language-css .token.string":{color:"#6a9354"},".style .token.string":{color:"#6a9354"},variable:{color:"#c07845"},atrule:{color:"#9f7d3e"},"attr-value":{color:"#6a9354"},function:{color:"#4791ba"},"class-name":{color:"#9f7d3e"},keyword:{color:"#b96f55"},regex:{color:"#6a9354"},important:{color:"#b96f55",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{opacity:.7},title:{color:"#d09930",fontWeight:"bold"},"code-block":{color:"#6a9354"},"code-snippet":{color:"#6a9354"},list:{color:"#c07845"},hr:{color:"#6b6963"},table:{color:"#4791ba"},blockquote:{color:"#7a756a",fontStyle:"italic"},strike:{textDecoration:"line-through"}};class bs{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}recordSessionStart(s){this.sessionStartTimes.set(s,Date.now())}getSessionStartTime(s){return this.sessionStartTimes.get(s)}shouldAnimateMessage(s,t){if(s.role!=="assistant"||this.seenMessageIds.has(s.id))return!1;const n=this.sessionStartTimes.get(t);if(!n)return this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created),!1;const o=s.time.created>n-5e3;return o||(this.seenMessageIds.add(s.id),this.messageCreationTimes.set(s.id,s.time.created)),o}clearSession(s){this.sessionStartTimes.delete(s)}hasSessionTiming(s){return this.sessionStartTimes.has(s)}hasBeenAnimated(s){return this.seenMessageIds.has(s)}markMessageAsAnimated(s,t){this.seenMessageIds.add(s),this.messageCreationTimes.set(s,t)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function ul(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 Pt=({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:A("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",s),children:r})},np=({isUser:r,providerID:s,agentName:t,modelName:n,isDarkTheme:o})=>{const{src:a,onError:i,hasLogo:c}=Gi(s);return e.jsx(Pt,{children:e.jsx("div",{className:A("pl-3","mb-2"),children:e.jsx("div",{className:A("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(pn,{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(mn,{className:"h-4 w-4",style:{color:`var(${xs(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:A("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:A("flex items-center gap-1 px-1.5 py-0 rounded","agent-badge typography-meta",xs(t).class),children:e.jsx("span",{className:"font-medium",children:t})})]})]})})})})},op=l.memo(np),ml=["vitesse-light","vitesse-dark"],fl=r=>{const s=[],t=[],n=r.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>s.push(i.innerText.trim()));const o=r.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const c=i.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:s,rows:t}},pl=({headers:r,rows:s})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
12
|
-
`)?`"${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(`
|
|
13
|
-
`)},ap=({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(`
|
|
14
|
-
`)},ip=({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(`
|
|
15
|
-
`)},lp=(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)},cp=({tableRef:r})=>{const[s,t]=l.useState(!1),[n,o]=l.useState(!1),a=l.useRef(null);l.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const i=async c=>{const d=r.current?.querySelector("table");if(d)try{const u=fl(d),f=c==="csv"?pl(u):ap(u);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(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:s?e.jsx(ht,{className:"size-3.5"}):e.jsx(Gt,{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"})]})]})},dp=({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=fl(i),d=a==="csv"?pl(c):ip(c);lp(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(un,{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"})]})]})},up=({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(cp,{tableRef:t}),e.jsx(dp,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:A("w-full border-collapse border border-border",s),"data-streamdown":"table",children:r})})]})},mp=({children:r,className:s})=>{const[t,n]=l.useState(!1),o=l.useRef(null),a=()=>o.current&&o.current.querySelector("code")?.innerText||"",i=async()=>{const c=a();if(c)try{await navigator.clipboard.writeText(c),n(!0),setTimeout(()=>n(!1),2e3)}catch(d){console.error("Failed to copy:",d)}};return e.jsxs("div",{className:A("group relative",s),ref:o,children:[r,e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:i,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:t?e.jsx(ht,{className:"size-3.5"}):e.jsx(Gt,{className:"size-3.5"})})})]})},hl={pre:mp,table:up},fp=({content:r,part:s,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1})=>{const i=l.useMemo(()=>`markdown-${s?.id?`part-${s.id}`:`message-${t}`}`,[t,s?.id]),c=e.jsx("div",{className:A("break-words",o),children:e.jsx(Vs,{mode:a?"streaming":"static",shikiTheme:ml,className:"streamdown-content",controls:{code:!1,table:!1},components:hl,children:r})});return n?e.jsx(Pt,{children:c},i):c},pp=({content:r,className:s})=>e.jsx("div",{className:A("break-words",s),children:e.jsx(Vs,{mode:"static",shikiTheme:ml,className:"streamdown-content",controls:{code:!1,table:!1},components:hl,children:r})}),hp={thinking:{label:"Thinking",Icon:mn},justification:{label:"Justification",Icon:co}},gl=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
|
|
16
|
-
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
17
|
-
`).trim(),gp=r=>{if(!r)return"";const s=r.trim(),t=s.indexOf(`
|
|
18
|
-
`),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},Ao=({text:r,variant:s,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>gp(r),[r]),{label:c,Icon:d}=hp[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:A("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(u=>!u),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:A("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:A("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(ft,{className:"h-3.5 w-3.5"}):e.jsx(ds,{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:A("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(Ge,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:r})})]})},xl=({part:r,onContentChange:s,messageId:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>gl(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Ao,{text:a,variant:"thinking",onContentChange:s,blockId:r.id||`${t}-reasoning`}):null},xp=r=>gl(r),yp=({part:r,messageId:s,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=r,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",u=l.useMemo(()=>a?xp(d):d,[d,a]),f=t==="streaming",m=t==="cooldown",p=l.useRef(f);if(f||m)return p.current=!0,null;const h=i.time;return!(h&&typeof h.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(Ao,{text:u,variant:"justification",onContentChange:o,blockId:r.id||`${s}-reasoning-text`},r.id||`${s}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(fp,{content:u,part:r,messageId:s,isAnimated:n,isStreaming:!1})},r.id||`${s}-text`)},bp=["vitesse-light","vitesse-dark"],wp=({children:r,className:s})=>{const[t,n]=l.useState(!1),o=l.useRef(null),a=async()=>{if(!o.current)return;const c=o.current.querySelector("code")?.innerText||"";if(c)try{await navigator.clipboard.writeText(c),n(!0),setTimeout(()=>n(!1),2e3)}catch(d){console.error("Failed to copy:",d)}};return e.jsxs("div",{className:A("group relative",s),ref:o,children:[r,e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:a,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:t?e.jsx(ht,{className:"size-3.5"}):e.jsx(Gt,{className:"size-3.5"})})})]})},yl=r=>{const s=[],t=[],n=r.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>s.push(i.innerText.trim()));const o=r.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const c=i.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:s,rows:t}},bl=({headers:r,rows:s})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
|
|
19
|
-
`)?`"${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(`
|
|
20
|
-
`)},vp=({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(`
|
|
21
|
-
`)},jp=({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(`
|
|
22
|
-
`)},Sp=(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)},Np=({tableRef:r})=>{const[s,t]=l.useState(!1),[n,o]=l.useState(!1),a=l.useRef(null);l.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const i=async c=>{const d=r.current?.querySelector("table");if(d)try{const u=yl(d),f=c==="csv"?bl(u):vp(u);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(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:s?e.jsx(ht,{className:"size-3.5"}):e.jsx(Gt,{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"})]})]})},kp=({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=yl(i),d=a==="csv"?bl(c):jp(c);Sp(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(un,{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"})]})]})},Cp=({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(Np,{tableRef:t}),e.jsx(kp,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:A("w-full border-collapse border border-border",s),"data-streamdown":"table",children:r})})]})},Mp={pre:wp,table:Cp},Ap=(r,s)=>{const t=encodeURIComponent(s);return`[${r}](https://opencode.ai/docs/agents/#${t})`},Dp=({part:r,messageId:s,isMobile:t,agentMention:n})=>{const o=r,a=o.text,i=typeof a=="string"?a:o.content||o.value||"",[c,d]=l.useState(!1),[u,f]=l.useState(!1),m=l.useRef(null),p=l.useMemo(()=>{if(!n)return i;const g=n.token;if(!g||g.length===0||!i.includes(g))return i;const y=Ap(g,n.name);return i.replace(g,y)},[n,i]);l.useEffect(()=>{const g=m.current;g&&!c&&f(g.scrollHeight>g.clientHeight)},[p,c]);const h=l.useCallback(()=>{(u||c)&&d(g=>!g)},[u,c]);return!p||p.trim().length===0?null:e.jsx("div",{className:A("break-words",!c&&"line-clamp-3",(u||c)&&"cursor-pointer"),ref:m,onClick:h,children:e.jsx(Vs,{mode:"static",shikiTheme:bp,className:A("streamdown-content streamdown-user",t&&"streamdown-mobile"),controls:{code:!1,table:!1},components:Mp,children:p})},r.id||`${s}-user-text`)},Ep=l.memo(Dp),Es={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},ir={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)"}}},Vr={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...ir.tool.collapsed,background:"transparent !important",margin:0,padding:Vr.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...ir.tool.popup,background:"transparent !important",margin:0,padding:Vr.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...ir.tool.popup,background:"transparent !important",margin:0,padding:Vr.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...ir.tool.inline})},Tp=r=>{let s=r.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},wl=r=>r?r.includes("<file_diagnostics>")||r.includes("This file has errors")||r.includes("please fix"):!1,Ip=r=>r?r.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",$a=(r,s)=>!r||typeof r!="object"?String(r):Mm(r,s||""),zn=(r,s,t)=>{let n=Tp(r);if((s==="edit"||s==="multiedit")&&wl(n)&&(n=Ip(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Pp=(r,s)=>{try{const t=r.trim().split(`
|
|
23
|
-
`).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,c]=a,d=Math.floor(i.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:A("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:ir.micro,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}},Rp=(r,s,t)=>{try{const n=r.trim().split(`
|
|
24
|
-
`).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,c,d,u]=i,f=u!==void 0?d:"",m=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:f,content:m})}}),e.jsxs("div",{className:A("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),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:A("font-medium text-muted-foreground",s?"typography-micro":"typography-meta"),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:A("flex items-start gap-2 min-w-0",s?"typography-micro":"typography-meta"),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}},Fp=(r,s,t)=>{try{const n=r.trim().split(`
|
|
25
|
-
`).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",u=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:A("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),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:A("font-medium text-muted-foreground",s?"typography-micro":"typography-meta"),children:[i,"/"]}),e.jsx("div",{className:A("pl-4 grid gap-1",s?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:A("flex items-center gap-2 min-w-0",s?"typography-micro":"typography-meta"),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}},Lp=(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:A("space-y-3 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),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-meta 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-meta 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(ht,{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(ht,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-meta 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-meta text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||i))})]})]})}catch{return null}},_p=(r,s,t)=>{try{return e.jsx("div",{className:A("typography-meta max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),children:e.jsx(Vs,{mode:"static",className:"streamdown-content streamdown-tool",children:r})})}catch{return null}},Op=r=>{const s=r.split(`
|
|
26
|
-
`);let t="";const n=[];let o=0;for(;o<s.length;){const a=s[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let f=d,m=o+1;for(;m<s.length&&!s[m].startsWith("@@")&&!s[m].startsWith("Index:");){const p=s[m];p.startsWith("+")?(u.push({type:"added",lineNumber:f,content:p.substring(1)}),f++):p.startsWith("-")?u.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(u.push({type:"context",lineNumber:f,content:p.substring(1)}),f++),m++}n.push({file:t,oldStart:c,newStart:d,lines:u}),o=m;continue}o++}return n},no=(r,s,t)=>Cm(s,r,t),$p=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(Wc,{className:s}):t==="write"||t==="create"||t==="file_write"?e.jsx(Uc,{className:s}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(Jn,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Ss,{className:s}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(Ut,{className:s}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(Vc,{className:s}):t==="glob"?e.jsx(Gc,{className:s}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(Xn,{className:s}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(Xn,{className:s}):t==="todowrite"||t==="todoread"?e.jsx(qc,{className:s}):t.startsWith("git")?e.jsx(Ct,{className:s}):e.jsx(yo,{className:s})},zp=(r,s)=>{const n=(s?s-r:Date.now()-r)/1e3;return`${(n<.05&&s!==void 0?.1:n).toFixed(1)}s`},Bp=r=>{if(!r?.diff||typeof r.diff!="string")return null;const s=r.diff.split(`
|
|
27
|
-
`);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}},oo=(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},Hp=(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 oo(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 oo(d,n,t)}if(r.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
|
|
28
|
-
`)[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:""},Wp=({children:r,maxHeightClass:s="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(Ge,{outerClassName:A("w-full min-w-0 flex-none overflow-hidden",s,n),className:A("p-2 rounded-xl w-full min-w-0 border border-border/20 bg-muted/30",t),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:r})}),Up=({diff:r,syntaxTheme:s,input:t})=>e.jsx("div",{className:"typography-meta px-1 pb-1 pt-0 space-y-0",children:Op(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:A("typography-meta 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(ns,{style:s,language:xn(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 !important",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent !important"}},children:a.content})})]},i))})]},o))}),Vp=({content:r,syntaxTheme:s,filePath:t,displayPath:n})=>{const o=r.split(`
|
|
29
|
-
`),a=xn(t??"")||no(r,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),c=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-meta font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ns,{style:s,language:a||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent !important",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent !important"}},children:d||" "})})]},u))})]})},Gp=({part:r,state:s,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const c=s,d=c.metadata,u=c.input,f=c.output,m=typeof f=="string"&&f.length>0,p=typeof f=="string"?f:"",h=typeof d?.diff=="string"?d.diff:null,g=r.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,y=r.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,b=r.tool==="write"&&!!y,w=b?g?oo(g,o,n):"New file":null,j=l.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&r.tool==="bash"?$a(u,r.tool):typeof u.content=="string"?u.content??"":$a(u,r.tool),[u,r.tool]),x=j.trim().length>0,v=(S,C)=>e.jsx(Wp,{maxHeightClass:C?.maxHeightClass,className:C?.className,disableHorizontal:C?.disableHorizontal,outerClassName:C?.outerClassName,children:S}),N=()=>{if(r.tool==="todowrite"||r.tool==="todoread"){if(s.status==="completed"&&m){const S=Lp(p,{unstyled:!0});return v(S??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return s.status==="error"&&"error"in s?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:s.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(r.tool==="list"&&m){const S=Pp(p,{unstyled:!0});return v(S??e.jsx("pre",{className:"typography-meta font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="grep"&&m){const S=Rp(p,n,{unstyled:!0});return v(S??e.jsx("pre",{className:"typography-meta font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="glob"&&m){const S=Fp(p,n,{unstyled:!0});return v(S??e.jsx("pre",{className:"typography-meta font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="task"&&m)return v(e.jsx("div",{className:"w-full min-w-0",style:{fontSize:"var(--text-code)"},children:e.jsx(Vs,{mode:"static",className:"streamdown-content streamdown-tool",children:p})}));if((r.tool==="web-search"||r.tool==="websearch"||r.tool==="search_web")&&m){const S=_p(p,t,{unstyled:!0});return v(S??e.jsx("pre",{className:"typography-meta font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="codesearch"&&m)return v(e.jsx("div",{className:"w-full min-w-0",style:{fontSize:"var(--text-code)"},children:e.jsx(Vs,{mode:"static",className:"streamdown-content streamdown-tool",children:p})}));if((r.tool==="edit"||r.tool==="multiedit")&&(!m&&h||p.trim().length===0||wl(p))&&h)return v(e.jsx(Up,{diff:h,syntaxTheme:t,input:u}),{className:"p-1"});if(m&&p.trim()){if(r.tool==="read"){const S=zn(p,r.tool,d),C=S.split(`
|
|
30
|
-
`),D=typeof u?.offset=="number"?u.offset:0,k=typeof u?.limit=="number"?u.limit:void 0,M=E=>E.trim().startsWith("(");return v(e.jsx("div",{className:"typography-meta w-full min-w-0 space-y-1",children:C.map((E,I)=>{const L=M(E),F=D+I+1,$=!L&&(k===void 0||I<k);return e.jsxs("div",{className:A("typography-meta font-mono flex w-full min-w-0",L&&"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:$?F:""}),e.jsx("div",{className:"flex-1 min-w-0",children:L?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(ns,{style:t,language:no(S,r.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent !important",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent !important"}},children:E})})]},I)})}),{className:"p-1"})}return v(e.jsx(ns,{style:t,language:no(zn(p,r.tool,d),r.tool,u),PreTag:"div",customStyle:{...Vr.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent !important"}},wrapLongLines:!0,children:zn(p,r.tool,d)}),{className:"p-1"})}return v(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:A("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"?N():e.jsxs(e.Fragment,{children:[b?e.jsx("div",{className:"my-1",children:v(e.jsx(Vp,{content:y,syntaxTheme:t,filePath:g,displayPath:w??"New file"}))}):x?e.jsx("div",{className:"my-1",children:v(e.jsx("blockquote",{className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:j}),{maxHeightClass:"max-h-60"})}):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:"}),N()]}),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})]})]})})},ao=({part:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=r.state,u=dt(N=>N.currentDirectory),f=d.status==="completed"||d.status==="error",m=d.status==="running",p=d.status==="error",[h,g]=l.useState(Date.now());l.useEffect(()=>{if(m){const N=setInterval(()=>{g(Date.now())},100);return()=>clearInterval(N)}},[m]);const y=l.useRef(s);l.useEffect(()=>{f&&y.current!==s&&(y.current=s,typeof s=="boolean"&&a?.("structural"))},[s,f,a]);const w=d.metadata,j=r.tool==="edit"||r.tool==="multiedit"?Bp(w):null,x=Hp(r,d,o,u),v=Li(r.tool).displayName;return f?e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:A("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>t(r.id),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:A("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:p?{color:"var(--status-error)"}:{},children:$p(r.tool)}),e.jsx("div",{className:A("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(ft,{className:"h-3.5 w-3.5"}):e.jsx(ds,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:p?{color:"var(--status-error)"}:{},children:v})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[x&&e.jsx("span",{className:A("truncate",o&&"max-w-[120px]"),children:x}),j&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",j.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",j.removed]})]}),"time"in d&&d.time&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:zp(d.time.start,f&&"end"in d.time?d.time.end:h)})]})]}),s&&e.jsx(Gp,{part:r,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:c})]}):null},qp=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
|
|
31
|
-
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
32
|
-
`).trim(),Kp=({part:r,messageId:s,onContentChange:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>qp(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Ao,{text:a,variant:"justification",onContentChange:t,blockId:r.id||`${s}-justification`}):null},Yp=l.memo(Kp),Jp=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(", ")},Bn=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}),Xp=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},Zp=({parts:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:f})=>{const m=l.useRef(s);l.useEffect(()=>{m.current!==s&&(m.current=s,c?.("structural"))},[s,c]);const p=l.useMemo(()=>Bn(!d||s?r:r.filter(y=>y.part.id&&u.has(y.id))),[r,d,s,u]),h=Jp(p),g=Xp(p);return p.length===0?null:e.jsx(Pt,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:A("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:A("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(Kc,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:A("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(ft,{className:"h-3.5 w-3.5"}):e.jsx(ds,{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:A("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((y,b)=>{const w=y.part.id||`group-part-${b}`,j=g[w];switch(y.kind){case"tool":return e.jsx(Pt,{children:e.jsx(ao,{part:y.part,isExpanded:a.has(w),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:j?.hasPrev??!1,hasNextTool:j?.hasNext??!1})},w);case"reasoning":return e.jsx(Pt,{children:e.jsx(xl,{part:y.part,messageId:y.messageId,onContentChange:c})},w);case"justification":return e.jsx(Pt,{children:e.jsx(Yp,{part:y.part,messageId:y.messageId,onContentChange:c})},w);default:return null}})})]})})},Qp=l.memo(Zp),eh=({isMigrating:r,children:s,className:t})=>e.jsx("div",{className:A("w-full overflow-hidden",r&&"pointer-events-none",t),style:r?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:s}),Hn=l.memo(eh),vl=r=>{const s=r,t=s.text;return typeof t=="string"?t:s.content||s.value||""},jl=r=>{if(r.type!=="text")return!1;const s=vl(r);return!s||s.trim().length===0},th=(r,s={})=>{const{includeReasoning:t=!0}=s;return r.filter(n=>!!n.synthetic||!t&&n.type==="reasoning"?!1:!(n.type==="patch"))},sh=(r,s)=>{const t=l.useRef(null),n=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(r);i.current=r;const c=l.useRef(s);c.current=s;const d=l.useRef(!1),u=s.size>0;return l.useEffect(()=>{r&&r.isWorking&&(r.isGroupExpanded||u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const f=i.current;if(!f)return;const m=Array.from(c.current);m.length>0&&f.markPartsPreviewed(m)},300)},1e3))))},[u,r]),l.useEffect(()=>{r&&(!r.isWorking||r.isGroupExpanded||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[u,r]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},rh=({messageId:r,parts:s,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d})=>{const[u,f]=l.useState(!1),m=l.useRef(null),p=l.useMemo(()=>s.filter(S=>S.type!=="text"?!1:!jl(S)),[s]),h=d?.token;let g=!1;const y=!!a,b=!!i,w=!!(n??t),j=!!o,x=l.useCallback(()=>{m.current!==null&&typeof window<"u"&&(window.clearTimeout(m.current),m.current=null)},[]),v=l.useCallback(()=>{!w||!y||!j||typeof window>"u"||(x(),f(!0),m.current=window.setTimeout(()=>{f(!1),m.current=null},1800))},[y,x,j,w]);l.useEffect(()=>{j||(f(!1),x())},[x,j]);const N=l.useCallback(S=>{!a||!j||(S.stopPropagation(),S.preventDefault(),a(),w&&v())},[j,w,a,v]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:w&&y&&j?v:void 0,children:[y&&e.jsx(Ne,{type:"button",variant:"ghost",size:"icon","data-visible":u||b?"true":void 0,className:A("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",j&&"group-hover/message:opacity-60 group-hover/message:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",(u||b)&&"opacity-100 pointer-events-auto"),style:{insetInlineEnd:"0.32rem",insetBlockStart:"-0.28rem"},disabled:!j,"aria-label":"Copy message text","aria-hidden":!j,onPointerDown:S=>S.stopPropagation(),onClick:N,onFocus:()=>{j&&f(!0)},onBlur:()=>{b||f(!1)},children:b?e.jsx(ht,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gt,{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((S,C)=>{let D;return d&&h&&!g&&vl(S).includes(h)&&(D=d,g=!0),e.jsx(Pt,{children:e.jsx(Ep,{part:S,messageId:r,isMobile:t,agentMention:D})},`user-text-${C}`)})}),e.jsx(sl,{files:s,onShowPopup:c})]})]})},nh=({messageId:r,parts:s,isMessageCompleted:t,syntaxTheme:n,isMobile:o,hasTouchInput:a,copiedCode:i,onCopyCode:c,expandedTools:d,onToggleTool:u,onShowPopup:f,streamPhase:m,allowAnimation:p,onContentChange:h,shouldShowHeader:g=!0,hasTextContent:y=!1,onCopyMessage:b,copiedMessage:w=!1,onAuxiliaryContentComplete:j,showReasoningTraces:x=!1,turnGroupingContext:v})=>{const[N,S]=l.useState(!1),C=l.useRef(null),D=!!b,k=!!w,M=!!(a??o),E=!t,I=l.useMemo(()=>s.filter(z=>!jl(z)).filter(z=>z.type!=="compaction"),[s]),L=l.useMemo(()=>I.filter(z=>z.type==="tool"),[I]),F=l.useMemo(()=>I.filter(z=>z.type==="text"),[I]),$=L.length>0,Y=l.useMemo(()=>L.some(z=>{const oe=(z.state??{})?.status;return oe==="pending"||oe==="running"||oe==="started"}),[L]),ie=l.useCallback(z=>{const me=z.state??{},oe=me?.status;if(oe==="pending"||oe==="running"||oe==="started")return!1;const fe=me?.time??{},ke=typeof fe?.end=="number"?fe.end:void 0,_e=typeof fe?.start=="number"?fe.start:void 0;return!(typeof ke!="number"||typeof _e=="number"&&ke<_e)},[]),P=l.useMemo(()=>L.length===0?!0:Y?!1:L.every(z=>ie(z)),[L,Y,ie]),B=l.useMemo(()=>F.length===0?!0:F.every(z=>typeof z.time?.end=="number"),[F]),te=l.useMemo(()=>I.filter(z=>z.type==="reasoning"),[I]),ye=l.useMemo(()=>te.length===0?!0:te.every(z=>typeof z.time?.end=="number"),[te]),V=l.useMemo(()=>{let z=0,me=0;return I.forEach(oe=>{oe.type==="step-start"?z+=1:oe.type==="step-finish"&&(me+=1)}),{stepStarts:z,stepFinishes:me,hasOpenStep:z>me}},[I]).hasOpenStep,ve=te.length>0&&$&&(Y||V||!P),Ae=l.useMemo(()=>$?F.length===0?V||Y||!P:!0:F.length>0?ve:!1,[F.length,V,Y,$,ve,P]),Pe=E||Ae&&(!B||!P||Y||V)||ve,je=E||$&&(Y||V||!P),De=E||ve,ue=$||te.length>0,X=F.length===0,R=ue&&X&&!je&&!De&&P&&ye,ne=l.useRef(!1),Z=l.useRef(!1);l.useEffect(()=>{Z.current=!1},[r]),l.useEffect(()=>{if(!R){ne.current=!1;return}ne.current||(ne.current=!0,j?.())},[R,j]),l.useEffect(()=>{if(E){Z.current=!1;return}if($){Z.current=!1;return}te.length!==0&&(De||!ye||Z.current||(Z.current=!0,h?.("structural")))},[E,$,h,ye,te.length,De]);const q=!!y&&!E,_=l.useCallback(()=>{C.current!==null&&typeof window<"u"&&(window.clearTimeout(C.current),C.current=null)},[]),Q=l.useCallback(()=>{!M||!D||!q||typeof window>"u"||(_(),S(!0),C.current=window.setTimeout(()=>{S(!1),C.current=null},1800))},[D,_,q,M]);l.useEffect(()=>{q||(S(!1),_())},[_,q]);const U=l.useCallback(z=>{!b||!q||(z.stopPropagation(),z.preventDefault(),b(),M&&Q())},[q,M,b,Q]);l.useEffect(()=>()=>{_()},[_]);const K=l.useMemo(()=>{const z={},me=L.filter(oe=>je?!1:ie(oe));return me.forEach((oe,fe)=>{z[oe.id]={hasPrev:fe>0,hasNext:fe<me.length-1}}),z},[L,je,ie]),ee=l.useMemo(()=>v?.activityParts??[],[v]),re=l.useMemo(()=>v?ee.filter(z=>z.messageId===r):[],[ee,r,v]),ce=l.useMemo(()=>{const z=new Map;return re.forEach(me=>{z.set(me.part,me)}),z},[re]),be=l.useMemo(()=>v?x?ee:ee.filter(z=>z.kind==="tool"):[],[ee,x,v]),[ae,Be]=l.useState(!1);l.useEffect(()=>{v&&be.length>1&&Be(!0)},[v,be.length]);const qe=!!(v&&ae),nt=l.useMemo(()=>{if(!v)return[];if(!qe)return[];if(!v.isWorking||v.isGroupExpanded)return[];const z=[];return re.forEach(me=>{if(v.previewedPartIds.has(me.id)||!x&&me.kind!=="tool")return;const oe=me.part;if(me.kind==="tool"){const fe=oe;if(je||!ie(fe))return}else if(me.kind==="reasoning"){if(!x||De||typeof oe.time?.end!="number")return}else if(me.kind==="justification"&&(!x||Pe||typeof oe.time?.end!="number"))return;z.push(me)}),z},[re,ie,Pe,De,je,x,qe,v]),et=l.useMemo(()=>{const z=new Set;return nt.forEach(me=>{z.add(me.id)}),z},[nt]),{isAnimating:st}=sh(v,et),Ke=l.useMemo(()=>{const z=[];v&&v.isFirstAssistantInTurn&&qe&&be.length>0&&z.push(e.jsx(Qp,{parts:be,isExpanded:v.isGroupExpanded,onToggle:v.toggleGroup,syntaxTheme:n,isMobile:o,expandedTools:d,onToggleTool:u,onShowPopup:f,onContentChange:h,isWorking:v.isWorking,previewedPartIds:v.previewedPartIds,diffStats:v.diffStats},"progressive-group"));const me=[];return I.forEach((oe,fe)=>{const ke=ce.get(oe);if(!ke||!v)return;let _e=null,Ye=null;if(!qe){if(ke.kind==="tool"){const $e=oe,Qe=$e.state?.time,ct=ie($e);if(!(!je&&ct))return;const gt=K[$e.id];Ye=e.jsx(Pt,{children:e.jsx(ao,{part:$e,isExpanded:d.has($e.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:gt?.hasPrev??!1,hasNextTool:gt?.hasNext??!1})},`tool-${$e.id}`),_e=ct&&typeof Qe?.end=="number"?Qe.end:null}Ye&&me.push({part:oe,index:fe,endTime:_e,element:Ye});return}if(!v.isWorking||v.isGroupExpanded||v.previewedPartIds.has(ke.id)||!x&&ke.kind!=="tool")return;const Je=et.has(ke.id);switch(ke.kind){case"tool":{const $e=oe,Qe=$e.state?.time,ct=ie($e);if(!(!je&&ct))break;const gt=K[$e.id],kt=e.jsx(Pt,{children:e.jsx(ao,{part:$e,isExpanded:d.has($e.id),onToggle:u,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:gt?.hasPrev??!1,hasNextTool:gt?.hasNext??!1})},`tool-${$e.id}`);Ye=Je?e.jsx(Hn,{isMigrating:st,children:kt},`migrating-tool-${$e.id}`):kt,_e=ct&&typeof Qe?.end=="number"?Qe.end:null;break}case"reasoning":{if(!x)break;const $e=oe.time,Ze=typeof $e?.end=="number";if(!(Ze&&!De))break;const ct=e.jsx(Pt,{children:e.jsx(xl,{part:oe,messageId:r,onContentChange:h})},`reasoning-${fe}`);Ye=Je?e.jsx(Hn,{isMigrating:st,children:ct},`migrating-reasoning-${fe}`):ct,_e=Ze?$e?.end??null:null;break}case"justification":{if(!x)break;const $e=oe.time,Ze=typeof $e?.end=="number";if(!(Ze&&!Pe))break;const ct=e.jsx(Pt,{children:e.jsx(yp,{part:oe,messageId:r,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${fe}`);Ye=Je?e.jsx(Hn,{isMigrating:st,children:ct},`migrating-text-${fe}`):ct,_e=Ze?$e?.end??null:null;break}}Ye&&me.push({part:oe,index:fe,endTime:_e,element:Ye})}),me.sort((oe,fe)=>oe.endTime===null&&fe.endTime===null?oe.index-fe.index:oe.endTime===null?1:fe.endTime===null?-1:oe.endTime-fe.endTime),me.forEach(({element:oe})=>{z.push(oe)}),z},[ce,i,w,d,y,st,o,ie,r,h,c,b,f,u,et,Pe,De,je,qe,g,x,n,K,v,be,I]),He=v?.turnId,Ee=We(z=>z.currentSessionId),Ue=Xe(z=>{if(!He||!Ee)return;const me=z.messages.get(Ee);if(!me)return;const oe=me.find(_e=>_e.info?.id===He);if(!oe)return;const ke=oe.info.summary?.body;return typeof ke=="string"&&ke.trim().length>0?ke:void 0}),Le=typeof v?.summaryBody=="string"&&v.summaryBody.trim().length>0?v.summaryBody:Ue,ze=l.useRef(void 0);Le&&Le.trim().length>0&&(ze.current=Le);const O=l.useRef(He);O.current!==He&&(O.current=He,ze.current=void 0);const de=ze.current,J=v?.isFirstAssistantInTurn&&de&&de.trim().length>0;return e.jsx("div",{className:A("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:M&&D&&q?Q: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:[Ke,J&&e.jsx(Pt,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onTouchStart:M&&D&&q?Q:void 0,children:[D&&e.jsx(Ne,{type:"button",variant:"ghost",size:"icon","data-visible":N||k?"true":void 0,className:A("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",q&&"group-hover/message:opacity-60 group-hover/message:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",(N||k)&&"opacity-100 pointer-events-auto"),style:{insetInlineEnd:"0.32rem",insetBlockStart:"-0.4rem"},disabled:!q,"aria-label":"Copy message text","aria-hidden":!q,onPointerDown:z=>z.stopPropagation(),onClick:U,onFocus:()=>{q&&S(!0)},onBlur:()=>{k||S(!1)},children:k?e.jsx(ht,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gt,{className:"h-3.5 w-3.5 text-foreground hover:text-primary focus-visible:text-primary"})}),e.jsx(pp,{content:de})]})},"summary-body")]}),e.jsx(sl,{files:s,onShowPopup:f})]})})},oh=({isUser:r,...s})=>r?e.jsx(rh,{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(nh,{...s}),za=l.memo(oh),Wn=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}},ah=l.lazy(()=>Ws(()=>import("./ToolOutputDialog-BLz2cnk4.js"),__vite__mapDeps([5,1,2,3,4])));function Un(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 ss=(r,s)=>{if(typeof r=="object"&&r!==null)return r[s]},ih=({message:r,previousMessage:s,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=wt(),{currentTheme:u}=Zs(),f=l.useRef(null),m=we(xo(G=>({lifecyclePhase:G.messageStreamStates.get(r.info.id)?.phase??null,isStreamingMessage:(()=>{const pe=r.info.sessionID??G.currentSessionId??null;return pe?(G.streamingMessageIds.get(pe)??null)===r.info.id:!1})(),currentSessionId:G.currentSessionId,getCurrentAgent:G.getCurrentAgent,getSessionAgentSelection:G.getSessionAgentSelection,getAgentModelForSession:G.getAgentModelForSession,getSessionModelSelection:G.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:g,getCurrentAgent:y,getSessionAgentSelection:b,getAgentModelForSession:w,getSessionModelSelection:j}=m,x=yt(G=>G.providers),v=Fe(G=>G.showReasoningTraces);l.useEffect(()=>{g&&bs.getInstance().recordSessionStart(g)},[g]);const[N,S]=l.useState(null),[C,D]=l.useState(!1),[k,M]=l.useState(new Set),[E,I]=l.useState({open:!1,title:"",content:""}),F=l.useMemo(()=>Wn(r.info),[r.info]).isUser,$=l.useMemo(()=>F?r.parts.map(G=>G.type==="compaction"?{type:"text",text:"/summarize"}:G):r.parts,[F,r.parts]),Y=l.useMemo(()=>{if(F||!s)return null;const G=ss(s.info,"clientRole"),pe=ss(s.info,"role");if((typeof G=="string"?G:typeof pe=="string"?pe:void 0)!=="user")return null;const Re=ss(s.info,"mode"),Ie=ss(s.info,"providerID"),Oe=ss(s.info,"modelID"),W=typeof Re=="string"&&Re.trim().length>0?Re:void 0,le=typeof Ie=="string"&&Ie.trim().length>0?Ie:void 0,xe=typeof Oe=="string"&&Oe.trim().length>0?Oe:void 0;return!W&&!le&&!xe?null:{agentName:W,providerId:le,modelId:xe}},[F,s]),ie=l.useMemo(()=>{if(F)return;const G=ss(r.info,"mode");if(typeof G=="string"&&G.trim().length>0)return G;if(Y?.agentName)return Y.agentName;const pe=r.info.sessionID;if(!pe)return;const Me=y(pe);return Me||(b(pe)??void 0)},[F,r.info,Y,y,b]),P=r.info.sessionID,B=F?null:ss(r.info,"providerID"),te=F?null:ss(r.info,"modelID"),ye=l.useMemo(()=>{if(F||!P)return null;if(Y?.providerId&&Y?.modelId)return{providerId:Y.providerId,modelId:Y.modelId};if(ie){const pe=w(P,ie);if(pe?.providerId&&pe?.modelId)return pe}const G=j(P);return G?.providerId&&G?.modelId?G:null},[F,P,ie,Y,w,j]),se=l.useMemo(()=>F?null:typeof B=="string"&&B.trim().length>0?B:ye?.providerId??null,[F,B,ye]),V=l.useMemo(()=>F?null:typeof te=="string"&&te.trim().length>0?te:ye?.modelId??null,[F,te,ye]),ve=l.useMemo(()=>{if(!F&&se&&V&&x.length>0){const G=x.find(pe=>pe.id===se);if(G?.models&&Array.isArray(G.models)){const Re=G.models.find(Ie=>Ie.id===V)?.name;return typeof Re=="string"?Re:void 0}}},[F,se,V,x]),Ae=Un(ie),Pe=Un(se??void 0),je=Un(ve),De=Ae??void 0,ue=Pe??null,X=je??void 0,R=l.useMemo(()=>{const G=r.info.time;return typeof G?.completed=="number"?G.completed:null},[r.info.time]),ne=l.useMemo(()=>F?!0:!!(R&&R>0),[F,R]),Z=l.useMemo(()=>th($,{includeReasoning:v}),[$,v]),q=l.useMemo(()=>F||ne?Z:[],[F,ne,Z]),_=l.useMemo(()=>F?[]:Z.filter(G=>G.type==="text"),[F,Z]),Q=l.useMemo(()=>F?[]:Z.filter(G=>G.type==="tool"),[F,Z]),U=l.useMemo(()=>{if(!F)return;const G=r.parts.find(Ie=>Ie.type==="agent");if(!G)return;const pe=G,Me=typeof pe.name=="string"?pe.name:void 0;if(!Me)return;const Re=pe.source&&typeof pe.source.value=="string"&&pe.source.value.trim().length>0?pe.source.value:`#${Me}`;return{name:Me,token:Re}},[F,r.parts]),ee=l.useMemo(()=>{let G=0,pe=0;return Z.forEach(Me=>{Me.type==="step-start"?G+=1:Me.type==="step-finish"&&(pe+=1)}),{hasOpenStep:G>pe}},[Z]).hasOpenStep,re=l.useMemo(()=>F?!1:_.length===0||Q.length===0?ee:!0,[_.length,Q.length,ee,F]),ce=u?.metadata.variant,be=l.useMemo(()=>ce?ce==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ce]),ae=l.useMemo(()=>u?ul(u):be?sp:rp,[u,be]),Be=l.useMemo(()=>F?!1:bs.getInstance().shouldAnimateMessage(r.info,g||r.info.sessionID),[r.info,g,F]),qe=l.useMemo(()=>s?Wn(s.info):null,[s]),nt=l.useMemo(()=>t?Wn(t.info):null,[t]),et=l.useMemo(()=>F||!qe?!0:qe.isUser,[F,qe]),st=l.useMemo(()=>F||!nt?!1:!nt.isUser&&nt.role==="assistant",[F,nt]),Ke=l.useMemo(()=>ne?"completed":p||(h?"streaming":"completed"),[ne,p,h]),He=l.useCallback(G=>{navigator.clipboard.writeText(G),S(G),setTimeout(()=>S(null),2e3)},[]),Ee=i?.turnId,Ue=Xe(G=>{if(!Ee)return;const pe=r.info.sessionID;if(!pe)return;const Me=G.messages.get(pe);if(!Me)return;const Re=Me.find(W=>W.info?.id===Ee);if(!Re)return;const Oe=Re.info.summary?.body;return typeof Oe=="string"&&Oe.trim().length>0?Oe:void 0}),Le=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:Ue,ze=l.useRef(void 0);Le&&Le.trim().length>0&&(ze.current=Le);const O=l.useRef(Ee);O.current!==Ee&&(O.current=Ee,ze.current=void 0);const de=ze.current,J=l.useMemo(()=>F?q.filter(Ie=>Ie.type==="text").map(Ie=>(Ie.text||Ie.content||"").trim()).filter(Ie=>Ie.length>0).join(`
|
|
33
|
-
`).replace(/\n\s*\n+/g,`
|
|
34
|
-
`):de&&de.trim().length>0?de:q.filter(Me=>Me.type==="text").map(Me=>(Me.text||Me.content||"").trim()).filter(Me=>Me.length>0).join(`
|
|
35
|
-
`).replace(/\n\s*\n+/g,`
|
|
36
|
-
`),[de,q,F]),z=J.length>0,me=l.useCallback(()=>{navigator.clipboard.writeText(J),D(!0),setTimeout(()=>D(!1),2e3)},[J]),oe=l.useCallback(G=>{M(pe=>{const Me=new Set(pe);return Me.has(G)?Me.delete(G):Me.add(G),Me})},[]),fe=o??null,ke=l.useRef(!1),_e=l.useRef(!1),Ye=l.useRef(!1),Je=l.useRef(!1),$e=l.useRef(!1);l.useEffect(()=>{_e.current=!1,Ye.current=!1,Je.current=!1,$e.current=!1,ke.current=!1},[r.info.id]);const Ze=l.useCallback(()=>{F||ke.current||(ke.current=!0,n?.("structural"))},[F,n]),Qe=l.useCallback(G=>{G.image&&I(G)},[]),ct=l.useCallback(G=>{I(pe=>({...pe,open:G}))},[]),Nt=!!ss(r.info,"animationSettled"),gt=Ke==="streaming",kt=l.useMemo(()=>F?!1:Z.some(G=>G.type==="reasoning"),[F,Z]),H=Be&&!Nt&&!gt,T=!F&&Be&&_.length>0&&!re;return l.useEffect(()=>{if(fe?.onStreamingCandidate){if(!T){Ye.current&&(kt&&fe?.onReasoningBlock?fe.onReasoningBlock():fe?.onReservationCancelled&&fe.onReservationCancelled(),Ye.current=!1);return}$e.current||($e.current=!0,fe.onStreamingCandidate(),Ye.current=!0)}},[fe,T,kt]),l.useEffect(()=>{fe?.onAnimationStart&&H&&(Je.current||(fe.onAnimationStart(),Je.current=!0))},[fe,H]),l.useEffect(()=>{if(F)return;const G=fe?.onAnimatedHeightChange;if(!G||!(H||T))return;const Me=f.current;if(!Me)return;if(typeof window>"u"||typeof ResizeObserver>"u"){G(Me.getBoundingClientRect().height);return}let Re=null;const Ie=W=>{if(typeof window>"u"){G(W);return}Re!==null&&window.cancelAnimationFrame(Re),Re=window.requestAnimationFrame(()=>{G(W)})},Oe=new ResizeObserver(W=>{const le=W[0];le&&Ie(le.contentRect.height)});return Oe.observe(Me),Ie(Me.getBoundingClientRect().height),()=>{Re!==null&&(window.cancelAnimationFrame(Re),Re=null),Oe.disconnect()}},[H,F,fe,T]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:A("group w-full",et?"pt-2":"pt-0",F?"pb-2":st?"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:F?e.jsx(Pt,{children:e.jsx("div",{className:A("rounded-xl border bg-input/10 dark:bg-input/30 pt-[0.7rem] pb-[0.45rem] relative"),style:{borderColor:"color-mix(in srgb, var(--primary-muted, var(--primary)) 40%, var(--interactive-border, transparent))"},children:e.jsx(za,{messageId:r.info.id,parts:Z,isUser:F,isMessageCompleted:ne,syntaxTheme:ae,isMobile:c,hasTouchInput:d,copiedCode:N,onCopyCode:He,expandedTools:k,onToggleTool:oe,onShowPopup:Qe,streamPhase:Ke,allowAnimation:H,onContentChange:n,shouldShowHeader:!1,hasTextContent:z,onCopyMessage:me,copiedMessage:C,showReasoningTraces:v,onAuxiliaryContentComplete:Ze,agentMention:U})})}):e.jsxs("div",{children:[et&&e.jsx(op,{isUser:F,providerID:ue,agentName:De,modelName:X,isDarkTheme:be}),e.jsx(za,{messageId:r.info.id,parts:Z,isUser:F,isMessageCompleted:ne,syntaxTheme:ae,isMobile:c,hasTouchInput:d,copiedCode:N,onCopyCode:He,expandedTools:k,onToggleTool:oe,onShowPopup:Qe,streamPhase:Ke,allowAnimation:H,onContentChange:n,shouldShowHeader:et,hasTextContent:z,onCopyMessage:me,copiedMessage:C,onAuxiliaryContentComplete:Ze,showReasoningTraces:v,agentMention:U,turnGroupingContext:i})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(ah,{popup:E,onOpenChange:ct,syntaxTheme:ae,isMobile:c})})]})},lh=l.memo(ih),ch=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(as,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Ss,{className:s}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(Xn,{className:s}):e.jsx(yo,{className:s})},dh=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},uh=({permission:r,onResponse:s})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=we(),{currentTheme:c}=Zs(),d=l.useMemo(()=>ul(c),[c]),u=async w=>{n(!0);try{await i(r.sessionID,r.id,w),a(!0),s?.(w)}catch{}finally{n(!1)}};if(o)return null;const f=r.type||"Unknown Tool",m=f.toLowerCase(),p=(w,j="")=>{const x=r.metadata[w];return typeof x=="string"?x:typeof x=="number"?String(x):j},h=w=>{const j=r.metadata[w];return typeof j=="number"?j:void 0},g=w=>!!r.metadata[w],y=dh(f),b=()=>{if(m==="bash"||m==="shell"||m==="shell_command"){const x=p("command")||p("cmd")||p("script"),v=p("description"),N=p("cwd")||p("working_directory")||p("directory")||p("path"),S=h("timeout"),C=r.title===x;return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),N&&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:N})]}),S&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",S,"ms"]}),x&&!C&&e.jsx("div",{children:e.jsx(ns,{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:x})})]})}if(m==="edit"||m==="multiedit"||m==="str_replace"||m==="str_replace_based_edit_tool"){const x=p("path")||p("file_path")||p("filename")||p("filePath"),v=p("old_str")||p("oldString")||p("old_content")||p("before"),N=p("new_str")||p("newString")||p("new_content")||p("after"),S=p("changes")||p("diff"),C=g("replace_all")||g("replaceAll");return e.jsxs(e.Fragment,{children:[x&&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:x})]}),C&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),S?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Changes:"}),e.jsx(Ge,{outerClassName:"max-h-64",className:"overflow-x-auto p-0",children:e.jsx(ns,{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:S})})]}):e.jsxs(e.Fragment,{children:[v&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Remove:"}),e.jsx(Ge,{outerClassName:"max-h-32 border border-red-500/20 rounded bg-red-500/5 p-2",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono text-red-600 dark:text-red-400 whitespace-pre-wrap break-all",children:v.length>500?v.substring(0,500)+"...":v})})]}),N&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Replace with:"}),e.jsx(Ge,{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:N.length>500?N.substring(0,500)+"...":N})})]})]})]})}if(m==="webfetch"||m==="fetch"||m==="curl"||m==="wget"){const x=p("url")||p("uri")||p("endpoint"),v=p("method")||"GET",N=r.metadata.headers&&typeof r.metadata.headers=="object"?r.metadata.headers:void 0,S=p("body")||p("data")||p("payload"),C=h("timeout"),D=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[x&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:v}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:x})]})]}),N&&Object.keys(N).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(Ge,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(ns,{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(N,null,2)})})]}),S&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(Ge,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(ns,{language:typeof S=="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 S=="object"?JSON.stringify(S,null,2):String(S)})})]}),(C||D)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[C&&e.jsxs("span",{children:["Timeout: ",C,"ms"]}),C&&D&&e.jsx("span",{children:" • "}),D&&e.jsxs("span",{children:["Response format: ",D]})]})]})}const w=p("command")||p("content")||p("action")||p("operation"),j=p("description");return e.jsxs(e.Fragment,{children:[j&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:j}),w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(Ge,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(w)})})]}),Object.keys(r.metadata).length>0&&!w&&!j&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(Ge,{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(yr,{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:[ch(f),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:y})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[(()=>{let w="",j="text",x=!1;m==="bash"||m==="shell"||m==="shell_command"?(w=p("command")||p("cmd")||p("script"),j="bash",x=!0):m==="edit"||m==="multiedit"||m==="str_replace"||m==="str_replace_based_edit_tool"?(w=p("path")||p("file_path")||p("filename")||p("filePath"),x=!1):(m==="webfetch"||m==="fetch")&&(w=p("url")||p("uri")||p("endpoint"),x=!1);const v=r.title===w;return v&&w&&x?e.jsx("div",{className:"mb-3",children:e.jsx(ns,{language:j,style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:w})}):v&&w&&!x?e.jsx("div",{className:"mb-3",children:e.jsx("code",{className:"typography-ui-label px-2 py-1 bg-muted/30 rounded block break-all",children:w})}):r.title?e.jsx("div",{className:A("typography-ui-label text-foreground mb-3",(x||w)&&"font-mono"),children:r.title}):null})(),b()]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:t,className:A("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(ht,{className:"h-3 w-3"}),"Allow Once"]}),e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:A("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(Yc,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:A("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:w=>{w.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(Zt,{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"})})]})]})})})},mh=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},fh=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}}}},ph=r=>{const s=fh(r);let t;const o=r.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let u=0,f=0,m=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)&&(m+=1),u+=h,f+=g}),m>0&&(t={additions:u,deletions:f,files:m})}let a=!1,i=!1;r.assistantMessages.forEach(u=>{u.parts.forEach(f=>{f.type==="tool"?a=!0:f.type==="reasoning"&&(i=!0)})});const c=[];let d=0;return r.assistantMessages.forEach(u=>{const f=u.info.id;u.parts.forEach(m=>{const p=typeof m.id=="string"&&m.id.trim().length>0?m.id:`${f}-activity-${d++}`;if(m.type==="tool"){const g=m.state?.time,y=typeof g?.end=="number"?g.end:void 0;c.push({id:p,turnId:r.turnId,messageId:f,kind:"tool",part:m,endedAt:y});return}if(m.type==="reasoning"){const h=m.text??m.content;if(typeof h!="string"||h.trim().length===0)return;const g=m.time,y=typeof g?.end=="number"?g.end:void 0;c.push({id:p,turnId:r.turnId,messageId:f,kind:"reasoning",part:m,endedAt:y});return}})}),{activityParts:c,hasTools:a,hasReasoning:i,summaryBody:s,diffStats:t}},hh=r=>{const{isWorking:s}=ll(),t=l.useMemo(()=>mh(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(y=>{h.set(y.info.id,g)})}),h},[t]),a=l.useMemo(()=>{const h=new Map;return t.forEach(g=>{h.set(g.turnId,ph(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]),u=l.useCallback(h=>{c(g=>{const y=new Map(g),b=y.get(h)??{isExpanded:!1,previewedPartIds:new Set};return y.set(h,{...b,isExpanded:!b.isExpanded}),y})},[]),f=l.useCallback((h,g)=>{g.length!==0&&c(y=>{const b=new Map(y),w=b.get(h)??{isExpanded:!1,previewedPartIds:new Set},j=new Set(w.previewedPartIds);return g.forEach(x=>{x&&x.trim().length>0&&j.add(x)}),b.set(h,{...w,previewedPartIds:j}),b})},[]),m=l.useCallback(h=>o.get(h),[o]),p=l.useCallback(h=>{const g=o.get(h);if(!g||!g.assistantMessages.some(M=>M.info.id===h))return;const b=a.get(g.turnId),w=b?.activityParts??[],j=!!b?.hasTools,x=!!b?.hasReasoning,v=b?.summaryBody,N=b?.diffStats,S=g.assistantMessages[0]?.info.id,C=h===S,D=d(g.turnId),k=s&&n===g.turnId;return{turnId:g.turnId,isFirstAssistantInTurn:C,summaryBody:v,activityParts:w,hasTools:j,hasReasoning:x,diffStats:N,isWorking:k,isGroupExpanded:D.isExpanded,previewedPartIds:D.previewedPartIds,toggleGroup:()=>u(g.turnId),markPartsPreviewed:M=>f(g.turnId,M)}},[d,n,s,f,o,u,a]);return{turns:t,getTurnForMessage:m,getContextForMessage:p}},gh=({messages:r,permissions:s,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:c,pendingAnchorId:d})=>{l.useEffect(()=>{s.length!==0&&t("permission")},[s,t]);const u=l.useMemo(()=>r.filter(m=>!ro(m.parts)),[r]),{getContextForMessage:f}=hh(u);return e.jsxs("div",{children:[o&&e.jsx("div",{className:"flex justify-center py-3",children:a?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:i,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((m,p)=>e.jsx(lh,{message:m,previousMessage:p>0?u[p-1]:void 0,nextMessage:p<u.length-1?u[p+1]:void 0,onContentChange:t,animationHandlers:n(m.info.id),scrollToBottom:c,isPendingAnchor:d===m.info.id,turnGroupingContext:f(m.info.id)},m.info.id))}),s.length>0&&e.jsx("div",{children:s.map(m=>e.jsx(uh,{permission:m},m.id))})]})},xh=l.memo(gh);function yh(...r){return s=>{r.forEach(t=>{typeof t=="function"?t(s):t&&typeof t=="object"&&(t.current=s)})}}const Sl=l.forwardRef(({orientation:r="vertical",offset:s=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:c,children:d,...u},f)=>{const m=l.useRef(null),p=l.useRef("none"),h=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const g=l.useMemo(()=>{const j={...i};return j["--scroll-shadow-size"]=`${t}px`,j},[t,i]),y=l.useCallback((j,x,v,N,S)=>{const C=`${N}${S.charAt(0).toUpperCase()}${S.slice(1)}Scroll`;x&&v?(j.dataset[C]="true",j.removeAttribute(`data-${N}-scroll`),j.removeAttribute(`data-${S}-scroll`)):(j.dataset[`${N}Scroll`]=String(x),j.dataset[`${S}Scroll`]=String(v),j.removeAttribute(`data-${N}-${S}-scroll`))},[]),b=l.useCallback(j=>{["top","bottom","top-bottom","left","right","left-right"].forEach(x=>{j.removeAttribute(`data-${x}-scroll`)})},[]),w=l.useCallback(()=>{const j=m.current;if(!j)return;if(!n){b(j);return}const x=r==="vertical"?j.scrollTop>s:j.scrollLeft>s;let v=r==="vertical"?j.scrollTop+j.clientHeight+s<j.scrollHeight:j.scrollLeft+j.clientWidth+s<j.scrollWidth;o&&r==="vertical"&&(v=!1),y(j,x,v,r==="vertical"?"top":"left",r==="vertical"?"bottom":"right");const N=x&&v?"both":x?r==="vertical"?"top":"left":v?r==="vertical"?"bottom":"right":"none";N!==p.current&&(p.current=N,a?.(N))},[b,o,n,s,a,r,y]);return l.useEffect(()=>{const j=m.current;if(!j)return;const x=()=>w(),v=typeof ResizeObserver<"u"?new ResizeObserver(()=>w()):null,N=typeof MutationObserver<"u"?new MutationObserver(()=>w()):null;return w(),j.addEventListener("scroll",x,{passive:!0}),v?.observe(j),N?.observe(j,{childList:!0,subtree:!0,characterData:!0}),()=>{j.removeEventListener("scroll",x),v?.disconnect(),N?.disconnect()}},[w]),e.jsx("div",{...u,ref:yh(m,f),className:c,"data-orientation":r,"data-scroll-shadow":h??!0,style:g,children:d})});Sl.displayName="ScrollShadow";const bh=160,wh=({containerRef:r})=>{const[s,t]=l.useState(!0),n=l.useRef(!0),o=l.useRef(!1),a=l.useRef(null),i=l.useRef(null),c=l.useRef(0),d=l.useRef(0),u=l.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),f=l.useCallback(x=>{const v=r.current;if(!v){u();return}i.current===null&&(i.current=x);const N=Math.min(1,(x-i.current)/bh),S=1-Math.pow(1-N,3),C=c.current,D=d.current,k=C+(D-C)*S;if(v.scrollTop=k,N<1){a.current=window.requestAnimationFrame(f);return}v.scrollTop=D,u(),n.current&&(n.current=!1,t(!1))},[u,r,t]),m=l.useCallback((x,v)=>{const N=r.current;if(!N)return;const S=Math.max(0,x),C=v?.instant??!1;if(o.current=!1,typeof window>"u"||C){u(),N.scrollTop=S;const k=S<=1;n.current!==k&&(n.current=k,t(k));return}if(u(),Math.abs(S-N.scrollTop)<=.5){N.scrollTop=S;const k=S<=1;n.current!==k&&(n.current=k,t(k));return}c.current=N.scrollTop,d.current=S,i.current=null,a.current=window.requestAnimationFrame(f)},[u,r,f,t]),p=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),g=l.useCallback(()=>o.current,[]),y=l.useCallback(()=>r.current?.scrollTop??0,[r]),b=l.useCallback(()=>r.current?.scrollHeight??0,[r]),w=l.useCallback(()=>r.current?.clientHeight??0,[r]),j=l.useCallback(()=>{const x=r.current;if(!x)return;o.current&&a.current!==null&&u();const v=x.scrollTop<=1;n.current!==v&&(n.current=v,t(v))},[u,r]);return l.useEffect(()=>{const x=r.current;if(x)return x.addEventListener("wheel",h,{passive:!0}),x.addEventListener("touchstart",h,{passive:!0}),()=>{x.removeEventListener("wheel",h),x.removeEventListener("touchstart",h)}},[r,h]),l.useEffect(()=>()=>{u()},[u]),l.useMemo(()=>({handleScroll:j,scrollToPosition:m,forceManualMode:p,isAtTop:s,isManualOverrideActive:g,getScrollTop:y,getScrollHeight:b,getClientHeight:w}),[j,m,p,s,g,y,b,w])},Ba=typeof window<"u"?l.useLayoutEffect:l.useEffect,Ha=50,vh=40,jh=.2,Sh=.1,Nh=150,Vn=r=>{const s=r.info;return typeof s?.id=="string"?s.id:null},kh=r=>{const s=r.info;if(s?.userMessageMarker===!0)return!0;const t=s?.clientRole,n=s?.role;return t==="user"||n==="user"},Ch=({currentSessionId:r,sessionMessages:s,updateViewportAnchor:t,isSyncing:n,isMobile:o,sessionActivityPhase:a})=>{const i=l.useRef(null),c=wh({containerRef:i}),[d,u]=l.useState(null),[f,m]=l.useState(0),[p,h]=l.useState(!1),[g,y]=l.useState(null),b=l.useRef(null),w=l.useRef(null),j=l.useRef(s.length),x=l.useRef(0),v=l.useRef(0),N=l.useRef(void 0),S=l.useRef(null),C=l.useRef(!1),D=r?a?.get(r)??"idle":"idle",k=l.useCallback(se=>{const V=Math.max(0,se);x.current!==V&&(x.current=V,m(V))},[]),M=l.useCallback(()=>{const se=i.current;se&&(v.current=se.clientHeight)},[]),E=l.useCallback(()=>{if(!d)return null;const se=i.current;return se?se.querySelector(`[data-message-id="${d}"]`):null},[d]),I=l.useCallback(()=>{const se=i.current,V=x.current;if(!se||V<=0)return!0;const ve=se.scrollHeight-V;return se.scrollTop+se.clientHeight<ve},[]),L=l.useCallback((se,V)=>{const ve=se.offsetHeight,Ae=se.offsetTop;if(ve>V*jh){const je=V*Sh;return Ae+ve-je}else return Ae-Ha},[]),F=l.useCallback(()=>{const se=i.current;if(!se||!S.current)return;const V=E();if(!V)return;const ve=se.clientHeight,Ae=se.scrollHeight,je=L(V,ve)+ve,De=x.current,ue=Ae-De;if(!C.current&&ue<je){const X=je-ue;X>De&&k(X)}},[L,E,k]),$=l.useCallback(()=>{const se=i.current;if(!se){h(!1);return}if(g){h(!1);return}if(!(se.scrollHeight>se.clientHeight)){h(!1);return}const ve=se.scrollHeight-se.scrollTop-se.clientHeight,Ae=x.current;if(Ae>0){const Pe=se.scrollHeight-Ae,je=se.scrollTop+se.clientHeight;h(je<Pe)}else h(ve>vh)},[g]),Y=l.useCallback(se=>{const V=i.current;if(!V)return;const ve=V.scrollHeight-V.clientHeight;c.scrollToPosition(Math.max(0,ve),se)},[c]),ie=l.useCallback(se=>{if(b.current===se)return;b.current=se,y(se);const V=i.current;if(!V){y(null);return}const ve=V.scrollHeight,Ae=x.current,Pe=ve-Ae,je=v.current>0?v.current:V.clientHeight,ue=Pe-Ha,X=ue+je;let R=0;Pe<X&&(R=X-Pe),R!==Ae&&k(R),C.current=!0,window.requestAnimationFrame(()=>{c.scrollToPosition(ue,{instant:!0}),window.requestAnimationFrame(()=>{y(null)})})},[c,k]),P=l.useCallback(()=>{const se=i.current;if(!se||!r)return;c.handleScroll(),$(),D==="idle"&&x.current>0&&I()&&(k(0),S.current=null,u(null));const{scrollTop:V,scrollHeight:ve,clientHeight:Ae}=se,Pe=(V+Ae/2)/Math.max(ve,1),je=Math.floor(Pe*s.length);t(r,je)},[r,D,I,c,s.length,$,k,t]);l.useEffect(()=>{const se=i.current;if(se)return se.addEventListener("scroll",P,{passive:!0}),()=>{se.removeEventListener("scroll",P)}},[P]),Ba(()=>{if(typeof window>"u")return;M();const se=()=>{N.current!==void 0&&window.clearTimeout(N.current),N.current=window.setTimeout(()=>{M()},Nh)};return window.addEventListener("resize",se),()=>{window.removeEventListener("resize",se),N.current!==void 0&&window.clearTimeout(N.current)}},[M]),l.useEffect(()=>{r&&r!==w.current&&(w.current=r,bs.getInstance().recordSessionStart(r),j.current=s.length,b.current=null,S.current=null,C.current=!1,u(null),x.current=0,m(0))},[r,s.length]),Ba(()=>{if(n){j.current=s.length;return}if(w.current!==r)return;const se=j.current,V=s.length;if(V>se&&se>0){const ve=Vn(s[se-1]);if(ve!==null&&Vn(s[Math.min(se-1,V-1)])===ve){const je=s.slice(se,V).find(kh);if(je){const De=Vn(je);De&&(S.current=De,u(De),ie(De))}else F()}else F()}j.current=V},[r,n,F,ie,s]),l.useEffect(()=>{const se=i.current;if(!se||typeof ResizeObserver>"u")return;const V=new ResizeObserver(()=>{F(),$()});return V.observe(se),()=>{V.disconnect()}},[F,$]),l.useEffect(()=>{d&&(F(),$())},[d,F,$]),l.useEffect(()=>{D==="idle"&&x.current>0&&I()&&(k(0),S.current=null,C.current=!1,u(null))},[D,I,k]),l.useEffect(()=>{$()},[f,$]);const B=l.useRef(new Map),te=l.useCallback(()=>{F(),$()},[F,$]),ye=l.useCallback(se=>{const V=B.current.get(se);if(V)return V;const ve={onChunk:()=>{F()},onComplete:()=>{F()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{F()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return B.current.set(se,ve),ve},[F]);return{scrollRef:i,handleMessageContentChange:te,getAnimationHandlers:ye,showScrollButton:p,scrollToBottom:Y,spacerHeight:f,pendingAnchorId:g,hasActiveAnchor:d!==null}},Mh=()=>{const{currentSessionId:r,messages:s,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,sessionMemoryState:d,isSyncing:u,messageStreamStates:f,trimToViewportWindow:m,sessionActivityPhase:p}=we(),h=l.useMemo(()=>r?n.get(r)??null:null,[r,n]),{isMobile:g}=wt(),y=l.useMemo(()=>r?s.get(r)||[]:[],[r,s]),b=l.useMemo(()=>r?t.get(r)||[]:[],[r,t]),{scrollRef:w,handleMessageContentChange:j,getAnimationHandlers:x,showScrollButton:v,scrollToBottom:N,spacerHeight:S,pendingAnchorId:C,hasActiveAnchor:D}=Ch({currentSessionId:r,sessionMessages:y,updateViewportAnchor:c,isSyncing:u,isMobile:g,sessionActivityPhase:p}),M=!!l.useMemo(()=>r?d.get(r)??null:null,[r,d])?.hasMoreAbove,[E,I]=l.useState(!1);l.useEffect(()=>{I(!1)},[r]);const L=l.useRef(null);l.useLayoutEffect(()=>{if(!r||r===L.current)return;L.current=r;const $=w.current;$&&($.scrollTop=$.scrollHeight-$.clientHeight)},[r,w]);const F=l.useCallback(async()=>{if(!r||E)return;const $=w.current,Y=$?.scrollHeight??null,ie=$?.scrollTop??null;I(!0);try{if(await i(r,"up"),$&&Y!==null&&ie!==null){const P=$.scrollHeight-Y;$.scrollTop=ie+P}}finally{I(!1)}},[r,E,i,w]);return l.useEffect(()=>{if(!r||(s.has(r)?s.get(r)??[]:[]).length>0)return;(async()=>{try{await a(r)}finally{typeof window>"u"?N():window.requestAnimationFrame(()=>{N()})}})()},[r,a,s,N]),r?o&&y.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(Y=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx($n,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx($n,{className:"h-4 w-24"}),e.jsx($n,{className:"h-20 w-full"})]})]},Y))})}),e.jsx(On,{scrollToBottom:N})]}):y.length===0&&!h?e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Oa,{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(On,{scrollToBottom:N})})]}):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(Sl,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:w,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!C,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(xh,{messages:y,permissions:b,onMessageContentChange:j,getAnimationHandlers:x,hasMoreAbove:M,isLoadingOlder:E,onLoadOlder:F,scrollToBottom:N,pendingAnchorId:C}),S>0&&D&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:S},"aria-hidden":"true"})]})}),e.jsx(Co,{containerRef:w})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[v&&y.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>N(),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(dr,{className:"h-4 w-4"})})}),e.jsx(On,{scrollToBottom:N})]})]}):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(Oa,{width:140,height:140,className:"opacity-20",isAnimated:!0})})})};class Ah 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(ko,{className:"w-full max-w-md",children:[e.jsx(Oi,{className:"text-center",children:e.jsxs($i,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Jc,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(zi,{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(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(qs,{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 Wa=()=>{const r=we(s=>s.currentSessionId);return e.jsx(Ah,{sessionId:r||void 0,children:e.jsx(Mh,{})})},Ua=12,Dh=[{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"}],Eh=({isActive:r,burstKey:s=0,className:t,durationMs:n=900,bursts:o=Dh,onComplete:a})=>{const i=ge.useRef(!1);ge.useEffect(()=>{!r&&i.current&&a?.(),r&&(i.current=!0)},[r,a]);const c=ge.useMemo(()=>Array.from({length:Ua},(d,u)=>{const f=Math.PI*2*u/Ua;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return r?e.jsx("div",{className:A("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:c.map((f,m)=>{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}-${m}-${s}`)})},`${d.id}-${s}`)})}):null},Th=({durationMs:r=3400}={})=>{const[s,t]=ge.useState({isActive:!1,cycle:0}),n=ge.useRef(null),o=ge.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=ge.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=ge.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 ge.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:i,dismissFireworks:a}},Nl=l.createContext(void 0),Ih=({children:r})=>{const{isActive:s,burstKey:t,triggerFireworks:n,dismissFireworks:o}=Th(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Nl.Provider,{value:a,children:[r,e.jsx(Eh,{isActive:s,burstKey:t})]})},Ph=()=>{const r=l.useContext(Nl);if(!r)throw new Error("useFireworksCelebration must be used within FireworksProvider");return r};function Rh({...r}){return e.jsx(Xc,{"data-slot":"select",...r})}function Fh({...r}){return e.jsx(ed,{"data-slot":"select-value",...r})}function Lh({className:r,size:s="default",children:t,...n}){return e.jsxs(Zc,{"data-slot":"select-trigger","data-size":s,className:A("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(Qc,{asChild:!0,children:e.jsx(ft,{className:"size-4 opacity-50"})})]})}function _h({className:r,children:s,position:t="popper",...n}){return e.jsx(td,{children:e.jsxs(sd,{"data-slot":"select-content",className:A("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($h,{}),e.jsx(Ge,{as:rd,outerClassName:"max-h-[var(--radix-select-content-available-height)] w-full",className:A("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(zh,{})]})})}function Oh({className:r,children:s,...t}){return e.jsxs(nd,{"data-slot":"select-item",className:A("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(od,{children:e.jsx(ht,{className:"size-4"})})}),e.jsx(ad,{children:s})]})}function $h({className:r,...s}){return e.jsx(id,{"data-slot":"select-scroll-up-button",className:A("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(lo,{className:"size-4"})})}function zh({className:r,...s}){return e.jsx(ld,{"data-slot":"select-scroll-down-button",className:A("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(ft,{className:"size-4"})})}const Bh=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Hh=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,Wh=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}];let or=null;const Uh=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=we(),{currentDirectory:n}=dt(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},Vh=()=>{const{git:r}=Xs(),s=Uh(),{currentSessionId:t,worktreeMetadata:n}=we(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=yn(),u=Ii(s??null),f=Ti(s??null),m=bm(s??null),p=wm(s??null),h=vm(s??null),g=xt(H=>H.isLoadingStatus),y=xt(H=>H.isLoadingLog),{setActiveDirectory:b,fetchAll:w,fetchStatus:j,fetchBranches:x,fetchLog:v,fetchIdentity:N,setLogMaxCount:S}=xt(),C=l.useMemo(()=>!or||or.directory!==s?null:or,[s]),[D,k]=l.useState(C?.commitMessage??""),[M,E]=l.useState(""),I=l.useMemo(()=>Bh(M),[M]),[L,F]=l.useState(null),[$,Y]=l.useState(null),[ie,P]=l.useState(!1),[B,te]=l.useState(null),[ye,se]=l.useState(25),[V,ve]=l.useState(!1),[Ae,Pe]=l.useState(!1),[je,De]=l.useState(""),[ue]=l.useState(null),{triggerFireworks:X}=Ph(),[R,ne]=l.useState(()=>new Set(C?.selectedPaths??[])),[Z,q]=l.useState(!1),[_,Q]=l.useState(new Set),[U,K]=l.useState(!1),[ee,re]=l.useState([]),ce=l.useCallback(()=>{re([])},[]),[be,ae]=l.useState(null),[Be,qe]=l.useState([]),[nt,et]=l.useState(!1),st=l.useMemo(()=>!be||!p?null:p.all.find(H=>H.hash===be)??null,[be,p]),Ke=l.useCallback(H=>{navigator.clipboard.writeText(H).then(()=>{he.success("Commit hash copied")}).catch(()=>{he.error("Failed to copy")})},[]);l.useEffect(()=>{if(!be||!s||!r){qe([]);return}let H=!1;return et(!0),r.getCommitFiles(s,be).then(T=>{H||qe(T.files)}).catch(T=>{console.error("Failed to fetch commit files:",T),H||qe([])}).finally(()=>{H||et(!1)}),()=>{H=!0}},[be,s,r]),l.useEffect(()=>()=>{if(!s){or=null;return}or={directory:s,selectedPaths:Array.from(R),commitMessage:D}},[D,s,R]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{s&&(b(s),xt.getState().directories.get(s)?.status||w(s,r,{force:!0}))},[s,b,w,r]);const He=l.useCallback(async(H=!0)=>{if(s)try{await Promise.all([j(s,r),x(s,r)])}catch(T){if(H){const G=T instanceof Error?T.message:"Failed to refresh repository state";he.error(G)}}},[s,r,j,x]),Ee=l.useCallback(async()=>{s&&await v(s,r,ye)},[s,r,v,ye]),Ue=l.useCallback(async()=>{s&&await N(s,r)},[s,r,N]),Le=l.useMemo(()=>{if(!f)return[];const H=f.files??[],T=new Map;return H.forEach(G=>{T.set(G.path,G)}),Array.from(T.values()).sort((G,pe)=>G.path.localeCompare(pe.path))},[f]);l.useEffect(()=>{if(!f||Le.length===0){ne(new Set),q(!1);return}ne(H=>{const T=new Set,G=H??new Set;return Le.forEach(pe=>{G.has(pe.path)?T.add(pe.path):Z||T.add(pe.path)}),T})},[f,Le,Z]);const ze=async H=>{if(s){F(H);try{if(H==="fetch")await r.gitFetch(s),he.success("Fetched latest updates");else if(H==="pull"){const T=await r.gitPull(s);he.success(`Pulled ${T.files.length} file${T.files.length===1?"":"s"}`)}else H==="push"&&(await r.gitPush(s),he.success("Pushed to remote"));te(`${H.toUpperCase()} completed at ${new Date().toLocaleTimeString()}`),await He(!1),await Ee()}catch(T){const G=T instanceof Error?T.message:`Failed to ${H==="pull"?"pull":H}`;he.error(G)}finally{F(null)}}},O=async(H={})=>{if(!s)return;if(!D.trim()){he.error("Please enter a commit message");return}const T=Array.from(R).sort();if(T.length===0){he.error("Select at least one file to commit");return}const G=H.pushAfter?"commitAndPush":"commit";Y(G);try{await r.createGitCommit(s,D.trim(),{files:T}),he.success("Commit created successfully"),k(""),ne(new Set),q(!1),await He(),H.pushAfter?(await r.gitPush(s),he.success("Pushed to remote"),X(),await He(!1)):await He(!1),await Ee()}catch(pe){const Me=pe instanceof Error?pe.message:"Failed to create commit";he.error(Me)}finally{Y(null)}},de=l.useCallback(async()=>{if(s){if(R.size===0){he.error("Select at least one file to describe");return}K(!0);try{const{message:H}=await r.generateCommitMessage(s,Array.from(R)),T=H.subject?.trim()??"",G=Array.isArray(H.highlights)?H.highlights:[];T&&k(T),re(G),he.success("Commit message generated")}catch(H){const T=H instanceof Error?H.message:"Failed to generate commit message";he.error(T)}finally{K(!1)}}},[s,R,r]),J=async()=>{if(!s||!f)return;const H=I;if(!H){he.error('Provide a branch name using letters, numbers, ".", "_", "-" or "/".');return}const T=f.current??null;P(!0);try{await r.createBranch(s,H,T??"HEAD"),he.success(`Created branch ${H}`);let G=!1;try{await r.checkoutBranch(s,H),await r.gitPush(s,{remote:"origin",branch:H,options:["--set-upstream"]}),G=!0}catch(pe){const Me=pe instanceof Error?pe.message:"Unable to push new branch to origin.";he.warning("Branch created locally",{description:Hh(`Upstream setup failed: ${Me}`)})}finally{if(T)try{await r.checkoutBranch(s,T)}catch(pe){console.warn("Failed to restore original branch after creation:",pe)}}E(""),await He(),await Ee(),G&&he.success(`Upstream set for ${H}`)}catch(G){const pe=G instanceof Error?G.message:"Failed to create branch";he.error(pe)}finally{P(!1)}},z=async H=>{if(!s)return;const T=H.replace(/^remotes\//,"");if(f?.current===T){Pe(!1);return}try{await r.checkoutBranch(s,T),he.success(`Checked out ${T}`),Pe(!1),De(""),await He();const G=f?.current;G&&(await r.checkoutBranch(s,G),he.success(`Checked out ${G}`)),await Ee()}catch(G){const pe=G instanceof Error?G.message:`Failed to checkout ${T}`;he.error(pe)}},me=async H=>{if(s){ve(!0);try{await r.setGitIdentity(s,H.id),he.success(`Applied "${H.name}" to repository`),await Ue()}catch(T){const G=T instanceof Error?T.message:"Failed to apply git identity";he.error(G)}finally{ve(!1)}}},oe=l.useMemo(()=>m?.all?m.all.filter(H=>!H.startsWith("remotes/")).sort():[],[m]),fe=l.useMemo(()=>m?.all?m.all.filter(H=>H.startsWith("remotes/")).map(H=>H.replace(/^remotes\//,"")).sort():[],[m]),ke=l.useMemo(()=>{const H=je.trim().toLowerCase();return H?{locals:oe.filter(T=>T.toLowerCase().includes(H)),remotes:fe.filter(T=>T.toLowerCase().includes(H))}:{locals:oe,remotes:fe}},[je,oe,fe]);l.useEffect(()=>{Ae||De("")},[Ae]);const _e=l.useMemo(()=>{const H=new Map;i&&H.set(i.id,i);for(const T of a)H.set(T.id,T);return Array.from(H.values())},[a,i]),Ye=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const H=a.find(T=>T.userName===h.userName&&T.userEmail===h.userEmail);return H||(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]),Je=Le.length,$e=R.size,Ze=g||L!==null||$!==null,Qe=H=>{ne(T=>{const G=new Set(T);return G.has(H)?G.delete(H):G.add(H),G}),q(!0)},ct=()=>{const H=new Set(Le.map(T=>T.path));ne(H),q(!0)},Nt=()=>{ne(new Set),q(!0)},gt=l.useCallback(async H=>{if(s){Q(T=>{const G=new Set(T);return G.add(H),G});try{await r.revertGitFile(s,H),he.success(`Reverted ${H}`),await He(!1)}catch(T){const G=T instanceof Error?T.message:"Failed to revert changes";he.error(G)}finally{Q(T=>{const G=new Set(T);return G.delete(H),G})}}},[s,He,r]);if(!s)return e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view repository details."})});if(g&&u===null)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(At,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository…"})]})});if(u===!1)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Ct,{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 kt=Je>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(Ct,{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(lr,{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(dr,{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(Kh,{activeProfile:Ye,identities:_e,onSelect:me,isApplying:V})]}),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(gs,{variant:"default",onClick:()=>ze("fetch"),disabled:L!==null||!f,children:[L==="fetch"?e.jsx(At,{size:16,className:"animate-spin"}):e.jsx(gn,{size:16}),"Fetch"]}),e.jsxs(gs,{variant:"default",onClick:()=>ze("pull"),disabled:L!==null||!f,children:[L==="pull"?e.jsx(At,{size:16,className:"animate-spin"}):e.jsx(dr,{size:16}),"Pull"]}),e.jsxs(gs,{variant:"default",onClick:()=>ze("push"),disabled:L!==null||!f,children:[L==="push"?e.jsx(At,{size:16,className:"animate-spin"}):e.jsx(lr,{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(Ft,{open:Ae,onOpenChange:Pe,children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Lt,{asChild:!0,children:e.jsxs(Ne,{variant:"outline",size:"sm",className:"gap-1.5 px-2 py-1 h-8",children:[e.jsx(Ct,{className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:f?.current||"Branch"}),e.jsx(ft,{className:"size-4 opacity-60"})]})})}),e.jsxs(rt,{sideOffset:8,children:["Switch branch (",oe.length," local · ",fe.length," remote)"]})]}),e.jsx(_t,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(Yi,{className:"h-full min-h-0",children:[e.jsx(Ji,{placeholder:"Search branches…",value:je,onValueChange:De}),e.jsxs(Xi,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Zi,{children:"No branches found."}),e.jsxs(hr,{heading:"Local branches",children:[ke.locals.map(H=>e.jsxs(jt,{onSelect:()=>z(H),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:H}),m?.branches?.[H]?.ahead||m?.branches?.[H]?.behind?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[m.branches[H].ahead||0," ahead ·"," ",m.branches[H].behind||0," behind"]}):null]}),f?.current===H&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${H}`)),ke.locals.length===0&&e.jsx(jt,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(so,{}),e.jsxs(hr,{heading:"Remote branches",children:[ke.remotes.map(H=>e.jsx(jt,{onSelect:()=>z(H),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:H})},`remote-${H}`)),ke.remotes.length===0&&e.jsx(jt,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]}),e.jsx(bt,{placeholder:"New branch",value:M,onChange:H=>E(H.target.value),className:"h-8 w-32 sm:w-40 rounded-lg bg-background/80 text-sm"}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ne,{variant:"default",size:"sm",className:"h-8 px-2",onClick:J,disabled:ie||!I,children:ie?e.jsx(At,{className:"size-4 animate-spin"}):e.jsx(Qt,{className:"size-4"})})}),e.jsx(rt,{sideOffset:8,children:I?`Create branch "${I}"`:"Enter branch name"})]})]}),e.jsx("div",{className:"flex-1"}),B&&e.jsx("span",{className:"typography-micro text-muted-foreground hidden lg:inline",children:B})]}),ue&&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:ue}),e.jsx("p",{className:"typography-meta text-destructive/80",children:"Try refreshing or confirm the repository is accessible."})]}),e.jsx(Ge,{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:[$e,"/",Je]}),Je>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:ct,children:"All"}),e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:Nt,disabled:$e===0,children:"None"})]})]})]}),e.jsx(Ge,{outerClassName:"flex-1 min-h-0",className:"w-full",children:f?.isClean||Je===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(qn,{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(H=>e.jsx(Gh,{file:H,checked:R.has(H.path),stats:f?.diffStats?.[H.path],onToggle:()=>Qe(H.path),onViewDiff:()=>Fe.getState().navigateToDiff(H.path),onRevert:()=>gt(H.path),isReverting:_.has(H.path)},H.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:[ee.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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"icon",className:"size-6",onClick:()=>{if(ee.length===0)return;const H=ee.map(T=>T.trim()).filter(Boolean);if(H.length===0){ce();return}k(T=>{const G=T.trim(),pe=G.length>0?`
|
|
37
|
-
|
|
38
|
-
`:"";return`${G}${pe}${H.join(`
|
|
39
|
-
`)}`.trim()}),ce()},"aria-label":"Insert highlights into commit message",children:e.jsx(dr,{className:"size-4"})})}),e.jsx(rt,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:ee.map((H,T)=>e.jsx("li",{className:"typography-meta text-foreground",children:H},T))})]}),e.jsx(Rs,{value:D,onChange:H=>k(H.target.value),placeholder:kt?"Commit message":"No changes to commit",rows:ee.length>0?4:8,disabled:$!==null||!kt,className:A("flex-1 rounded-lg bg-background/80 resize-none",ee.length>0?"min-h-[80px]":"min-h-[180px]")}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(gs,{variant:"ghost",onClick:de,disabled:U||$!==null||$e===0||Ze,className:"px-3","aria-label":"Generate commit message",children:U?e.jsx(At,{className:"size-4 animate-spin"}):e.jsx(cd,{className:"size-4 text-primary"})})}),e.jsx(rt,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(gs,{variant:"outline",onClick:()=>{ce(),O({pushAfter:!1})},disabled:$!==null||!D.trim()||$e===0||U,children:$==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"size-4 animate-spin"}),"Committing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(qn,{className:"size-4"}),"Commit"]})}),e.jsx(gs,{variant:"default",onClick:()=>{ce(),O({pushAfter:!0})},disabled:$!==null||!D.trim()||$e===0||U,children:$==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"size-4 animate-spin"}),"Pushing…"]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{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(Rh,{value:String(ye),onValueChange:H=>{const T=Number(H);se(T),s&&(S(s,T),v(s,r,T))},disabled:y,children:[e.jsx(Lh,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:y,children:e.jsx(Fh,{placeholder:"Commits"})}),e.jsx(_h,{children:Wh.map(H=>e.jsx(Oh,{value:String(H.value),children:H.label},H.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(Ge,{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(H=>e.jsx(qh,{entry:H,isSelected:be===H.hash,onSelect:()=>ae(H.hash)},H.hash))})}),e.jsx("div",{className:"flex flex-col min-h-[120px] lg:min-h-0 overflow-hidden",children:st?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:st.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:st.author_name}),e.jsx("span",{children:Cl(st.date)}),e.jsx("code",{className:"font-mono",children:st.hash.slice(0,8)}),e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-5 px-1.5 -ml-1",onClick:()=>Ke(st.hash),children:e.jsx(Gt,{className:"size-3"})})}),e.jsx(rt,{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:nt?"Loading...":`${Be.length} file${Be.length===1?"":"s"}`})}),e.jsx(Ge,{outerClassName:"flex-1 min-h-0 max-h-32",className:"w-full",children:nt?e.jsx("div",{className:"flex items-center justify-center p-3",children:e.jsx(At,{className:"size-4 animate-spin text-muted-foreground"})}):Be.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:Be.map(H=>e.jsxs("li",{className:"flex items-center gap-2 px-3 py-1.5",children:[e.jsx("span",{className:A("typography-micro font-semibold w-4 shrink-0 text-center",H.changeType==="A"&&"text-emerald-500",H.changeType==="D"&&"text-red-500",H.changeType==="M"&&"text-amber-500",H.changeType==="R"&&"text-blue-500"),children:H.changeType}),e.jsx("span",{className:"typography-micro text-foreground truncate flex-1",title:H.path,children:H.path}),!H.isBinary&&e.jsxs("span",{className:"typography-micro shrink-0",children:[e.jsxs("span",{className:"font-semibold",style:{color:"var(--status-success)"},children:["+",H.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{className:"font-semibold",style:{color:"var(--status-error)"},children:["-",H.deletions]})]}),H.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},H.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"})})})]})]})]})})]})},Gh=({file:r,checked:s,onToggle:t,onViewDiff:n,onRevert:o,isReverting:a,stats:i})=>{const c=l.useMemo(()=>Yh(r),[r]),d=c.description??c.code,u=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:m=>{m.key===" "?(m.preventDefault(),t()):m.key==="Enter"&&(m.preventDefault(),n())},children:[e.jsx("button",{type:"button",onClick:m=>{m.preventDefault(),m.stopPropagation(),t()},"aria-pressed":s,"aria-label":`Select ${r.path}`,className:"flex size-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(ho,{className:"size-4 text-primary"}):e.jsx(go,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold uppercase tracking-wide",style:{color:c.color},title:d,"aria-label":d,children:c.code}),e.jsx("span",{className:"flex-1 min-w-0 break-words typography-ui-label text-foreground",title:r.path,children:r.path}),e.jsxs("span",{className:"shrink-0 typography-micro font-semibold",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",u]}),e.jsx("span",{className:"mx-0.5 text-muted-foreground",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",f]})]}),e.jsxs(at,{delayDuration:200,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{type:"button",onClick:m=>{m.preventDefault(),m.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(At,{className:"size-4 animate-spin"}):e.jsx(gn,{className:"size-4"})})}),e.jsx(rt,{sideOffset:8,children:"Revert changes"})]})]})})},qh=({entry:r,isSelected:s,onSelect:t})=>e.jsxs("li",{className:A("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," · ",Cl(r.date)]}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:r.hash.slice(0,8)})]})]}),Kh=({activeProfile:r,identities:s,onSelect:t,isApplying:n})=>{const o=n||s.length===0;return e.jsxs(Ft,{children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Lt,{asChild:!0,children:e.jsxs(Ne,{variant:"outline",size:"sm",className:"gap-2 px-3 py-1 typography-ui-label",style:{color:kl(r?.color)},disabled:o,children:[n?e.jsx(At,{className:"size-4 animate-spin"}):e.jsx(Va,{icon:r?.icon,colorToken:r?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[180px] truncate",children:r?.name||"No identity"}),e.jsx(ft,{className:"size-4 opacity-60"})]})})}),e.jsxs(rt,{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(mt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Va,{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 Yh(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 Jh={branch:Ct,briefcase:po,house:fo,graduation:mo,code:vs,heart:ii,user:pn},Xh={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 kl(r){return r&&Xh[r]||"var(--primary)"}const Va=({icon:r,className:s,colorToken:t})=>{const n=Jh[r??"branch"]??pn;return e.jsx(n,{className:s,style:{color:kl(t)}})};function Cl(r){const s=new Date(r);return Number.isNaN(s.getTime())?r:s.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}const Zh=6e4,Lr=r=>({sessionId:r,terminalSessionId:null,directory:"",isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Ga=Mt((r,s)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>s().sessions.get(t),setTerminalSession:(t,n,o)=>{r(a=>{const i=new Map(a.sessions),c=i.get(t),u=!c||c.terminalSessionId!==n.sessionId||c.directory!==o?Lr(t):c??Lr(t);return i.set(t,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{r(o=>{const a=new Map(o.sessions),i=a.get(t)??Lr(t);return a.set(t,{...i,isConnecting:n,updatedAt:Date.now()}),{sessions:a}})},appendToBuffer:(t,n)=>{n&&r(o=>{const a=new Map(o.sessions),i=a.get(t)??Lr(t),c=o.nextChunkId,d={id:c,data:n},u=[...i.bufferChunks,d];let f=i.bufferLength+n.length;for(;f>Zh&&u.length>1;){const p=u.shift();if(!p)break;f-=p.data.length}const m=u.map(p=>p.data).join("");return a.set(t,{...i,buffer:m,bufferChunks:u,bufferLength:f,updatedAt:Date.now()}),{sessions:a,nextChunkId:c+1}})},clearTerminalSession:t=>{r(n=>{const o=new Map(n.sessions),a=o.get(t);return a&&o.set(t,{...a,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:o}})},clearBuffer:t=>{r(n=>{const o=new Map(n.sessions),a=o.get(t);return a?(o.set(t,{...a,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:o}):n})},removeTerminalSession:t=>{r(n=>{const o=new Map(n.sessions);return o.delete(t),{sessions:o}})},clearAllTerminalSessions:()=>{r({sessions:new Map,nextChunkId:1})}})),Ml=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),Qh=[{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'}],eg=[{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'}],Al=r=>Object.fromEntries(r.map(s=>[s.id,s])),qa=Al(Qh),Ts=Al(eg),tg="ibm-plex-sans",Gr="ibm-plex-mono";function sg(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 Ka(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 Dl=l.forwardRef(({sessionKey:r,chunks:s,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:c,enableTouchScroll:d},u)=>{const f=l.useRef(null),m=l.useRef(null),p=l.useRef(null),h=l.useRef(null),g=l.useRef(t),y=l.useRef(n),b=l.useRef([]),w=l.useRef(!1),j=l.useRef(0),x=l.useRef(null),v=l.useRef(null),[,N]=l.useReducer(E=>E+1,0);g.current=t,y.current=n;const S=l.useCallback(()=>{b.current=[],w.current=!1,j.current=0,x.current=null},[]),C=l.useCallback(()=>{const E=h.current,I=p.current,L=f.current;if(!E||!I||!L)return;const F=L.getBoundingClientRect();if(!(F.width<24||F.height<24))try{E.fit(),y.current(I.cols,I.rows)}catch{}},[]),D=l.useCallback(()=>{if(w.current)return;const E=()=>{const I=p.current;if(!I){S();return}const L=b.current.shift();if(L===void 0){w.current=!1;return}w.current=!0,I.write(L,()=>{w.current=!1,b.current.length>0&&(typeof window<"u"?window.setTimeout(E,0):E())})};E()},[S]),k=l.useCallback(E=>{E&&(b.current=[E],w.current=!1,D())},[D]),M=l.useCallback(()=>{if(v.current?.(),v.current=null,!d)return;const E=f.current,I=p.current;if(!E||!I)return;const L={lastY:null,remainder:0},$=I._core?.dimensions?.actualCellHeight??null,Y=typeof $=="number"&&$>0?$:Math.max(i+6,i*1.6),ie=se=>{se.touches.length===1&&(L.lastY=se.touches[0].clientY,L.remainder=0)},P=se=>{if(se.touches.length!==1){L.lastY=null,L.remainder=0;return}if(L.lastY===null){L.lastY=se.touches[0].clientY;return}const V=se.touches[0].clientY,ve=L.lastY-V;L.lastY=V;const Ae=L.remainder+ve/Y,Pe=Ae>0?Math.floor(Ae):Ae<0?Math.ceil(Ae):0;L.remainder=Ae-Pe,Pe!==0&&(se.preventDefault(),se.stopPropagation(),I.scrollLines(Pe))},B=()=>{L.lastY=null,L.remainder=0},te={passive:!1};E.addEventListener("touchstart",ie,te),E.addEventListener("touchmove",P,te),E.addEventListener("touchend",B),E.addEventListener("touchcancel",B);const ye=E.style.touchAction;E.style.touchAction="none",v.current=()=>{E.removeEventListener("touchstart",ie),E.removeEventListener("touchmove",P),E.removeEventListener("touchend",B),E.removeEventListener("touchcancel",B),E.style.touchAction=ye}},[d,i]);return l.useEffect(()=>{const E=new dd.Terminal(Ka(a,i,o)),I=new ud.FitAddon;p.current=E,h.current=I,E.loadAddon(I);const L=f.current;if(L){E.open(L);const Y=L.querySelector(".xterm-viewport");Y&&(Y.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),m.current=Y,N()),C(),E.focus()}const F=[E.onData(Y=>{g.current(Y)})],$=new ResizeObserver(()=>{C()});return L&&$.observe(L),()=>{v.current?.(),v.current=null,F.forEach(Y=>Y.dispose()),$.disconnect(),E.dispose(),p.current=null,h.current=null,S()}},[C,a,i,o,S]),l.useEffect(()=>{const E=p.current;if(!E)return;const I=Ka(a,i,o);Object.assign(E.options,I),C()},[C,a,i,o]),l.useEffect(()=>{const E=p.current;E&&(E.reset(),S(),C(),E.focus())},[r,C,S]),l.useEffect(()=>(M(),()=>{v.current?.(),v.current=null}),[M,r]),l.useEffect(()=>{const E=p.current;if(!E)return;if(s.length===0){j.current!==0&&(E.reset(),S(),C());return}const I=s[0].id;if(x.current===null&&(x.current=I),(x.current!==I||j.current>s.length)&&(E.reset(),S(),x.current=I),j.current<s.length){const F=s.slice(j.current);k(F.map($=>$.data).join("")),j.current=s.length}},[s,k,C,S]),l.useImperativeHandle(u,()=>({focus:()=>{p.current?.focus()},clear:()=>{const E=p.current;E&&(E.reset(),S(),C())},fit:()=>{C()}}),[C,S]),e.jsx("div",{ref:f,className:A("relative h-full w-full",c),children:m.current?e.jsx(Co,{containerRef:m,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null})});Dl.displayName="TerminalViewport";const rg=13,ng={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},_r={ctrl:"5",cmd:"3"},og={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},ag=(r,s)=>{if(s)switch(r){case"arrow-up":return`\x1B[1;${_r[s]}A`;case"arrow-down":return`\x1B[1;${_r[s]}B`;case"arrow-right":return`\x1B[1;${_r[s]}C`;case"arrow-left":return`\x1B[1;${_r[s]}D`}return ng[r]??null},ig=()=>{const{terminal:r}=Xs(),{currentTheme:s}=Zs(),{monoFont:t}=Ml(),{isMobile:n}=wt(),{currentSessionId:o,sessions:a,worktreeMetadata:i}=we(),c=o?i.get(o)??void 0:void 0,d=l.useMemo(()=>{if(c?.path)return c.path;if(!o)return null;const U=a.find(ee=>ee.id===o),K=typeof U?.directory=="string"?U.directory:null;return K&&K.length>0?K:null},[o,a,c]),{currentDirectory:u,homeDirectory:f}=dt(),m=d||u||null,p=l.useMemo(()=>m?f?m===f?"~":m.startsWith(f+"/")?"~"+m.slice(f.length):m:m:"",[m,f]),h=Ga(),g=h.sessions,y=h.setTerminalSession,b=h.setConnecting,w=h.appendToBuffer,j=h.clearTerminalSession,x=h.removeTerminalSession,v=h.clearBuffer,N=l.useMemo(()=>{if(o)return g.get(o)},[g,o]),S=N?.terminalSessionId??null,C=N?.bufferChunks??[],D=N?.bufferLength??0,k=N?.isConnecting??!1,M=S,[E,I]=l.useState(null),[L,F]=l.useState(null),$=l.useRef(null),Y=l.useRef(null),ie=l.useRef(o??null),P=l.useRef(M),B=l.useRef(m),te=l.useRef(null),se=Fe(U=>U.activeMainTab)==="terminal";l.useEffect(()=>{ie.current=o??null},[o]),l.useEffect(()=>{P.current=M},[M]),l.useEffect(()=>{B.current=m},[m]),l.useEffect(()=>{!n&&L!==null&&F(null)},[n,L,F]),l.useEffect(()=>{!M&&L!==null&&F(null)},[M,L,F]);const V=l.useCallback(()=>{$.current?.(),$.current=null,Y.current=null},[]);l.useEffect(()=>()=>{V(),P.current=null},[V]);const ve=l.useCallback(U=>{if(Y.current===U)return;V();const K=r.connect(U,{onEvent:ee=>{const re=ie.current;if(re)switch(ee.type){case"connected":{b(re,!1),I(null),te.current?.focus();break}case"reconnecting":{const ce=ee.attempt??0,be=ee.maxAttempts??3;I(`Reconnecting (${ce}/${be})...`);break}case"data":{ee.data&&w(re,ee.data);break}case"exit":{const ce=typeof ee.exitCode=="number"?ee.exitCode:null,be=typeof ee.signal=="number"?ee.signal:null;w(re,`\r
|
|
40
|
-
[Process exited${ce!==null?` with code ${ce}`:""}${be!==null?` (signal ${be})`:""}]\r
|
|
41
|
-
`),j(re),b(re,!1),I("Terminal session ended"),V();break}}},onError:(ee,re)=>{const ce=ie.current;if(!ce)return;const be=re?`Connection failed: ${ee.message}`:ee.message||"Terminal stream connection error";I(be),re&&(b(ce,!1),V(),x(ce))}},og);$.current=()=>{K.close(),Y.current=null},Y.current=U},[w,j,V,x,b,r,I]);l.useEffect(()=>{let U=!1;const K=o;if(!K||!m){I(K?"No working directory available for terminal.":"Select a session to open the terminal."),V();return}return(async()=>{if(!ie.current||ie.current!==K)return;const re=Ga.getState().sessions.get(K);if(re?.terminalSessionId&&re.directory&&re.directory!==m){V();try{re.terminalSessionId&&await r.close(re.terminalSessionId)}catch{}x(K);return}let ce=re?.terminalSessionId??null;if(!ce){I(null),b(K,!0);try{const be=await r.createSession({cwd:m});if(U){try{await r.close(be.sessionId)}catch{}return}y(K,be,m),ce=be.sessionId}catch(be){U||(I(be instanceof Error?be.message:"Failed to start terminal session"),b(K,!1));return}}!ce||U||(P.current=ce,ve(ce))})(),()=>{U=!0,P.current=null,V()}},[o,m,M,x,b,y,ve,V,r]);const Ae=l.useCallback(async()=>{if(!o)return;I(null),V();const U=M;if(U)try{await r.close(U)}catch{}x(o)},[o,V,x,r,M]),Pe=l.useCallback(()=>{if(!o)return;v(o),te.current?.clear(),te.current?.focus();const U=P.current;U&&r.sendInput(U,"\f").catch(K=>{I(K instanceof Error?K.message:"Failed to refresh prompt")})},[v,o,I,r]),je=l.useCallback(U=>{if(!U)return;let K=U,ee=!1;if(L&&U.length>0){const ce=U[0];if(ce.length===1&&/[a-zA-Z]/.test(ce)){const be=ce.toUpperCase();(L==="ctrl"||L==="cmd")&&(K=String.fromCharCode(be.charCodeAt(0)&31),ee=!0)}ee||(ee=!0)}const re=P.current;re&&(r.sendInput(re,K).catch(ce=>{I(ce instanceof Error?ce.message:"Failed to send input")}),ee&&(F(null),te.current?.focus()))},[L,F,r]),De=l.useCallback((U,K)=>{const ee=P.current;ee&&r.resize({sessionId:ee,cols:U,rows:K}).catch(()=>{})},[r]),ue=l.useCallback(U=>{F(K=>K===U?null:U),te.current?.focus()},[F]),X=l.useCallback(U=>{const K=ag(U,L);K&&(je(K),F(null),te.current?.focus())},[L,je,F]);l.useEffect(()=>{if(!n||!L||!M)return;const U=K=>{if(K.repeat)return;const ee=K.key;if(!ee||ee==="Control"||ee==="Meta"||ee==="Alt"||ee==="Shift")return;const re=ee.length===1?ee.toLowerCase():ee,ce=K.code??"",be=ce.startsWith("Key")&&ce.length===4?ce.slice(3).toUpperCase():null,ae=ee.length===1&&/[a-zA-Z]/.test(ee)?ee.toUpperCase():be,Be={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(re in Be){K.preventDefault(),K.stopPropagation(),X(Be[re]);return}if(L==="ctrl"&&ae&&ae.length===1&&ae>="A"&&ae<="Z"){const qe=String.fromCharCode(ae.charCodeAt(0)&31);K.preventDefault(),K.stopPropagation(),je(qe),F(null),te.current?.focus()}};return window.addEventListener("keydown",U),()=>{window.removeEventListener("keydown",U)}},[L,X,je,n,F,M]);const R=l.useMemo(()=>{const U=Ts[Gr].stack;if(typeof window>"u")return(Ts[t]??Ts[Gr]).stack;const ee=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ee&&ee.trim().length>0?ee.trim():(Ts[t]??Ts[Gr]).stack??U},[t]),ne=l.useMemo(()=>sg(s),[s]),Z=l.useMemo(()=>`${o??"none"}::${m??"no-dir"}::${M??"pending"}`,[o,m,M]);l.useEffect(()=>{if(!se)return;const U=te.current;if(!U)return;const K=()=>{U.fit()};if(typeof window<"u"){const ee=window.requestAnimationFrame(()=>{K(),U.focus()}),re=[220,400].map(ce=>window.setTimeout(K,ce));return()=>{window.cancelAnimationFrame(ee),re.forEach(ce=>window.clearTimeout(ce))}}K()},[se,Z,o,M]);const q=E?.includes("Reconnecting"),_=E?q?e.jsx(pd,{size:20,className:"text-amber-400"}):e.jsx(Zt,{size:20,className:"text-destructive"}):M&&!k?e.jsx($r,{size:20,className:"text-emerald-400"}):k?e.jsx(Oo,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Oo,{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(!m)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[e.jsx("p",{children:"No working directory available for this session."}),e.jsx("button",{onClick:Ae,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Q=!M||k;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:[_,e.jsxs(Ne,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Pe,disabled:!D,title:"Clear output",type:"button",children:[e.jsx(Ns,{size:16}),"Clear"]}),e.jsxs(Ne,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:Ae,title:"Restart terminal session",type:"button",children:[e.jsx(qs,{size:16,className:A(k&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>X("esc"),disabled:Q,children:"Esc"}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>X("tab"),disabled:Q,children:[e.jsx(_o,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:L==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ue("ctrl"),disabled:Q,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:L==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ue("cmd"),disabled:Q,children:[e.jsx(Ks,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>X("arrow-up"),disabled:Q,children:[e.jsx(lr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>X("arrow-left"),disabled:Q,children:[e.jsx(md,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>X("arrow-down"),disabled:Q,children:[e.jsx(dr,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>X("arrow-right"),disabled:Q,children:[e.jsx(_o,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>X("enter"),disabled:Q,children:[e.jsx(fd,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:ne.background},children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:se?e.jsx(Ge,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Dl,{ref:U=>{te.current=U},sessionKey:Z,chunks:C,onInput:je,onResize:De,theme:ne,fontFamily:R,fontSize:rg,enableTouchScroll:n},Z)}):null}),E&&e.jsx("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground",children:E})]})]})},lg=()=>{const{isSidebarOpen:r,activeMainTab:s,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i}=Fe(),{isMobile:c}=wt(),[d,u]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");l.useEffect(()=>{typeof window>"u"||u(typeof window.opencodeDesktop<"u")},[]),Mf({enabled:!0}),l.useEffect(()=>{Fe.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(()=>{Fe.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(Vh,{});case"diff":return e.jsx(Rm,{});case"terminal":return e.jsx(ig,{});default:return null}},[s]),m=s==="chat";return e.jsxs("div",{className:A("main-content-safe-area h-[100dvh]",c?"flex flex-col":"flex",d?"bg-transparent":"bg-background"),children:[e.jsx(hf,{}),e.jsx(yf,{}),e.jsx(Cf,{}),e.jsx(ff,{isOpen:a,onClose:()=>i(!1)}),c?e.jsxs(e.Fragment,{children:[e.jsx(fa,{}),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:A("absolute inset-0",!m&&"invisible"),children:e.jsx(ls,{children:e.jsx(Wa,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:f})})]})}),e.jsx(Bt,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Aa,{mobileVariant:!0})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Bm,{isOpen:r,isMobile:c,children:e.jsx(Aa,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden",children:[e.jsx(fa,{}),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:A("absolute inset-0",!m&&"invisible"),children:e.jsx(ls,{children:e.jsx(Wa,{})})}),f&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:f})})]})})]})]}),e.jsx(Lm,{})]})},cg=({...r})=>{const{theme:s="system"}=hd();return e.jsx(gd,{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})},dg=(r=5e3)=>{const[s,t]=ge.useState(null);return ge.useEffect(()=>{if(!Rt())return;let n=!1,o=null;const a=async()=>{const i=await _d();n||(t(i),o=setTimeout(a,r))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[r]),s},ug=({onClose:r})=>{const{sessions:s,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=we(),c=dg(4e3),d=l.useMemo(()=>{let m=0;return t.forEach(p=>{m+=p.length}),m},[t]),u=l.useMemo(()=>s.map(m=>{const p=t.get(m.id)?.length||0,h=n.get(m.id);return{id:m.id,title:m.title||"Untitled",messageCount:p,isStreaming:h?.isStreaming||!1,isZombie:h?.isZombie||!1,backgroundCount:h?.backgroundMessageCount||0,lastAccessed:h?.lastAccessedAt||0,isCurrent:m.id===o}}).sort((m,p)=>p.lastAccessed-m.lastAccessed),[s,t,n,o]),f=t.size;return e.jsxs(ko,{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(xd,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),r&&e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:r,children:e.jsx(Zt,{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," / ",St.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:[St.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:[St.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:[St.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(Ge,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(m=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${m.isCurrent?"bg-primary/10":"bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"truncate",children:m.title}),m.isStreaming&&e.jsx(yd,{className:"h-3 w-3 text-primary animate-pulse"}),m.isZombie&&e.jsx("span",{className:"text-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${m.messageCount>St.VIEWPORT_MESSAGES?"text-warning":""}`,children:[m.messageCount," msgs"]}),m.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",m.backgroundCount]})]})]},m.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Ns,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]}),e.jsx(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"}),e.jsx(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{},children:"Log State"})]})]})]})},mg="openchamber-message-cursors",Gs="cursors",fg=1,El="openchamber.messageCursors",Do=()=>typeof window<"u",Eo=()=>Do()&&typeof indexedDB<"u",Tl=()=>Eo()?new Promise((r,s)=>{const t=indexedDB.open(mg,fg);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Gs)||n.createObjectStore(Gs)},t.onerror=()=>{s(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{r(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),Il=()=>{if(!Do())return{};try{const r=window.localStorage.getItem(El);if(!r)return{};const s=JSON.parse(r);return s&&typeof s=="object"?s:{}}catch{return{}}},pg=r=>{if(Do())try{window.localStorage.setItem(El,JSON.stringify(r))}catch{}},hg=async(r,s,t)=>{if(!r||!s)return;if(Eo())try{const o=await Tl();await new Promise((a,i)=>{const c=o.transaction(Gs,"readwrite");c.objectStore(Gs).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=Il();n[r]={messageId:s,completedAt:t},pg(n)},gg=async r=>{if(!r)return null;if(Eo())try{const t=await Tl(),n=await new Promise((o,a)=>{const i=t.transaction(Gs,"readonly"),d=i.objectStore(Gs).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 Il()[r]??null},$t=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},xg=50,Ya=new WeakMap,Ja=r=>{if(!r||!Array.isArray(r))return 0;const s=Ya.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 Ya.set(r,t),t},io=new Map,Xa=(r,s)=>{const t=`${r}:${s}`,n=io.get(t);if(n&&n.sessionId===r)return n.message;const i=(we.getState().messages.get(r)||[]).find(c=>c.info.id===s)||null;return io.set(t,{sessionId:r,message:i}),i},yg=()=>{const{addStreamingPart:r,completeStreamingMessage:s,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:c,getWorktreeMetadata:d,loadMessages:u,loadSessions:f}=we(),{checkConnection:m}=yt(),p=dt(X=>X.currentDirectory),h=l.useMemo(()=>{if(!a)return;try{const R=d?.(a);if(R?.path)return R.path}catch(R){console.warn("Failed to inspect worktree metadata for session directory:",R)}const X=c.find(R=>R.id===a);if(X&&typeof X.directory=="string"&&X.directory.trim().length>0)return X.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]),y=Fe(X=>X.setEventStreamStatus),b=l.useRef(null),w=l.useCallback((X,R)=>{const ne=R??null,Z=b.current;if(!(Z&&Z.status===X&&Z.hint===ne)){if(b.current={status:X,hint:ne},$t()){const _={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[X]??"[INFO]",Q=ne?`${_} SSE ${X}: ${ne}`:`${_} SSE ${X}`;console.info(Q)}y(X,ne)}},[y]),j=l.useCallback((X,R,ne)=>{$t()&&console.debug(`[MessageTracker] ${X}: ${R}`,ne)},[]),x=l.useCallback(X=>{$t()&&console.debug(`[MessageTracker] ${X}: reported`)},[]),v=l.useRef(null),N=l.useRef(null),S=l.useRef(0);l.useRef(new Set);const C=l.useRef(new Map),D=l.useRef(null),k=l.useRef(!1),M=l.useCallback(()=>{if(typeof document>"u")return"visible";const X=document.visibilityState;return X==="hidden"&&document.hasFocus()?"visible":X},[]),E=l.useRef(M()),I=l.useRef(typeof navigator>"u"?!0:navigator.onLine),L=l.useRef(!1),F=l.useRef(null),$=l.useRef(null),Y=l.useRef(Date.now()),ie=l.useRef(!1);l.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(ie.current=!0)},[]);const P=l.useRef(new Map),B=l.useRef(new Map),te=l.useCallback(X=>{if(!X)return;const R=Date.now(),ne=C.current,Z=ne.get(X);Z&&R-Z<3e3||(ne.set(X,R),setTimeout(async()=>{try{const q=await Se.getSession(X);if(q){const _={};typeof q.title=="string"&&q.title.length>0&&(_.title=q.title),q.summary!==void 0&&(_.summary=q.summary),Object.keys(_).length>0&&i(X,_)}}catch(q){console.warn("Failed to refresh session metadata:",q)}},100))},[i]),ye=l.useCallback(()=>{D.current||(D.current=setTimeout(()=>{D.current=null;try{f()}catch(X){console.warn("Failed to refresh sessions after stream completion:",X)}},500))},[f]),se=l.useCallback((X,R)=>{if(B.current.get(X)===R)return;const Z=P.current.get(X);if(Z&&(clearTimeout(Z),P.current.delete(X)),B.current.set(X,R),we.setState({sessionActivityPhase:new Map(B.current)}),R==="cooldown"){const q=setTimeout(()=>{P.current.delete(X),B.current.get(X)==="cooldown"&&(B.current.set(X,"idle"),we.setState({sessionActivityPhase:new Map(B.current)}))},2e3);P.current.set(X,q)}},[]),V=l.useCallback(X=>{if(Y.current=Date.now(),$t()&&console.debug("[useEventStream] Received event:",X.type,X.properties),!X.properties)return;const R=X.properties;if(!new Set(["session.abort","session.error"]).has(X.type)){const Z=(typeof R.session=="object"&&R.session!==null?R.session:null)||(typeof R.sessionInfo=="object"&&R.sessionInfo!==null?R.sessionInfo:null);if(Z){const q=Z,_=typeof q.id=="string"&&q.id.length>0?q.id:typeof q.sessionID=="string"&&q.sessionID.length>0?q.sessionID:typeof R.sessionID=="string"&&R.sessionID.length>0?R.sessionID:typeof R.id=="string"&&R.id.length>0?R.id:void 0;if(_){const Q=typeof q.title=="string"?q.title:typeof R.title=="string"?R.title:void 0,U=typeof q.summary=="object"&&q.summary!==null?q.summary:typeof R.summary=="object"&&R.summary!==null?R.summary:void 0;if(Q!==void 0||U!==void 0){const K={};Q!==void 0&&(K.title=Q),U!==void 0&&(K.summary=U),i(_,K)}}}}switch(X.type){case"server.connected":m();break;case"openchamber:session-activity":{if(!ie.current)break;const Z=typeof R.sessionId=="string"?R.sessionId:null,q=typeof R.phase=="string"?R.phase:null;Z&&(q==="idle"||q==="busy"||q==="cooldown")&&(se(Z,q),ye());break}case"session.status":if(ie.current)break;{const Z=typeof R.sessionID=="string"?R.sessionID:null,q=typeof R.status=="object"&&R.status!==null?R.status:null,_=typeof q?.type=="string"?q.type:null;Z&&_&&(se(Z,_==="busy"||_==="retry"?"busy":"idle"),ye())}break;case"message.part.updated":{const Z=typeof R.part=="object"&&R.part!==null?R.part:null;if(!Z)break;const q=Z,_=typeof R.info=="object"&&R.info!==null?R.info:R,Q=typeof _.sessionID=="string"?_.sessionID:null,U=typeof q.sessionID=="string"&&q.sessionID.length>0?q.sessionID:typeof Q=="string"&&Q.length>0?Q:typeof R.sessionID=="string"&&R.sessionID.length>0?R.sessionID:null,K=typeof _.id=="string"?_.id:null,ee=typeof q.messageID=="string"&&q.messageID.length>0?q.messageID:typeof K=="string"&&K.length>0?K:typeof R.messageID=="string"&&R.messageID.length>0?R.messageID:null;if(!U||!ee){$t()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:q.sessionID??Q??R.sessionID,messageID:q.messageID??K??R.messageID});break}const re=U,ce=ee;let be="assistant";if(_&&typeof _.role=="string")be=_.role;else{const Be=Xa(re,ce);if(Be){const qe=Be.info.role;typeof qe=="string"&&(be=qe)}}if(j(ce,"part_received",{role:be}),be==="user"&&q.synthetic===!0){j(ce,"skipped_synthetic_user_part");break}const ae={...Z,type:Z.type||"text"};j(ce,"addStreamingPart_called"),r(re,ce,ae,be);break}case"message.updated":{const Z=typeof R.info=="object"&&R.info!==null?R.info:R,q=Z,_=typeof q.sessionID=="string"&&q.sessionID.length>0?q.sessionID:typeof R.sessionID=="string"&&R.sessionID.length>0?R.sessionID:null,Q=typeof q.id=="string"&&q.id.length>0?q.id:typeof R.messageID=="string"&&R.messageID.length>0?R.messageID:null;if(!_||!Q){$t()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:q.sessionID??R.sessionID,messageID:q.id??R.messageID});break}const U=_,K=Q;if(ie.current&&$t())try{const Ke=R.parts||q.parts||[],Ee=(Array.isArray(Ke)?Ke.filter(Ue=>Ue?.type==="text"):[]).map(Ue=>{const Le=Ue;return typeof Le?.text=="string"?Le.text:typeof Le?.content=="string"?Le.content:""}).join(`
|
|
42
|
-
`);console.info("[STREAM-TRACE] message.updated",{messageId:K,role:q.role,status:q.status,textLen:Ee.length,textPreview:Ee.slice(0,120),partsCount:Array.isArray(Ke)?Ke.length:0})}catch{}if(j(K,"message_updated",{role:q.role}),q.role==="user"){const Ke=R.parts||q.parts,He=Array.isArray(Ke)?Ke:[],Ee={...Z,userMessageMarker:!0,clientRole:"user"};if(t(U,K,Ee),He.length>0)for(let Ue=0;Ue<He.length;Ue++){const Le=He[Ue];if(Le.synthetic===!0)continue;const ze={...Le,type:Le?.type||"text",sessionID:Le?.sessionID||U,messageID:Le?.messageID||K};r(U,K,ze,"user")}j(K,"user_message_created_from_event",{partsCount:He.length});break}const ee=Xa(U,K),re=Ja(ee?.parts||[]),ce=ee?.parts?.some(Ke=>Ke?.type==="step-finish"&&Ke.reason==="stop")??!1,be=R.parts||q.parts,ae=Array.isArray(be)?be:[],Be=ae.length>0,nt=typeof(q.time||{})?.completed=="number";if(!Be&&!nt)break;if(q.role==="assistant"&&Be){const Ke=Ja(ae),He=re>0&&Ke+xg<re,Ee=ae.some(Ue=>Ue?.type==="step-finish"&&Ue.reason==="stop");if(He&&!Ee){j(K,"skipped_shrinking_update",{incomingLen:Ke,existingLen:re});break}if(ie.current){const Ue=re>0&&Ke<re,Le=ae.some(O=>{if(!O||O.type!=="text")return!1;const de=O;return typeof de.text=="string"&&de.text.length>0});if(Ue&&!(Ee&&Le)){j(K,"desktop_shrinking_update_suppressed",{incomingLen:Ke,existingLen:re});break}}}if(t(U,K,Z),Be&&q.role!=="user"){const Ee=(we.getState().messages.get(U)||[]).find(ze=>ze.info.id===K),Ue=!Ee||Ee.parts.length===0;j(K,Ue?"server_parts_injected":"server_parts_refreshed",{count:ae.length});const Le=ie.current&&q.role==="assistant"?ae.filter(ze=>ze?.type!=="text"):ae;for(let ze=0;ze<Le.length;ze++){const O=Le[ze],de={...O,type:O?.type||"text",sessionID:O?.sessionID||U,messageID:O?.messageID||K};r(U,K,de,q.role),j(K,`server_part_${ze}`)}}const et=Z.time;if(Z.role==="assistant"&&et?.completed!==void 0&&Z.role==="assistant"){const He=we.getState().messages.get(U)||[];let Ee=null,Ue="";for(let z=0;z<He.length;z++){const me=He[z];me.info.role==="assistant"&&me.info.id>Ue&&(Ue=me.info.id,Ee=me.info.id)}if(K!==Ee)break;if(!(ae.some(z=>z?.type==="step-finish"&&z.reason==="stop")||ce)&&ie.current){j(K,"desktop_completion_without_stop");break}const ze=et?.completed!==void 0?et?.completed:Date.now();if(et?.completed||t(U,K,{...Z,time:{...et??{},completed:ze}}),j(K,"completed",{timeCompleted:ze}),x(K),hg(U,K,ze),s(U,K),!ie.current){const z=Z.sessionID,me=typeof z=="string"&&z.length>0?z:U;B.current.get(me)==="busy"&&se(me,"cooldown")}const O=Z.sessionID,de=typeof O=="string"&&O.length>0?O:U;te(de),Z.summary&&typeof de=="string"&&n(de,null)}break}case"session.updated":{const Z=typeof R.info=="object"&&R.info!==null?R.info:typeof R.sessionInfo=="object"&&R.sessionInfo!==null?R.sessionInfo:typeof R.session=="object"&&R.session!==null?R.session:R,q=typeof Z.id=="string"&&Z.id.length>0?Z.id:typeof Z.sessionID=="string"&&Z.sessionID.length>0?Z.sessionID:typeof R.sessionID=="string"&&R.sessionID.length>0?R.sessionID:typeof R.id=="string"&&R.id.length>0?R.id:void 0;if(q){const _=typeof Z.time=="object"&&Z.time!==null?Z.time:typeof R.time=="object"&&R.time!==null?R.time:null,Q=_&&typeof _.compacting=="number"?_.compacting:null;n(q,Q)}break}case"session.abort":{const Z=typeof R.sessionID=="string"&&R.sessionID.length>0?R.sessionID:null,q=typeof R.messageID=="string"&&R.messageID.length>0?R.messageID:null;Z&&q&&s(Z,q);break}case"permission.updated":a===R.sessionID&&o(R);break}},[a,r,s,t,o,m,te,ye,n,i,j,x,se]),ve=l.useCallback(()=>{const X=M();return E.current=X,X==="visible"&&I.current},[M]),Ae=l.useCallback(()=>{$t()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:ie.current,hasUnsubscribe:!!v.current,currentSessionId:a,effectiveDirectory:g,onlineStatus:I.current,visibilityState:E.current,lastEventTimestamp:Y.current,reconnectAttempts:S.current})},[a,g]),Pe=l.useCallback(async()=>!0,[]),je=l.useCallback(()=>{if(k.current){$t()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(k.current=!0,N.current&&(clearTimeout(N.current),N.current=null),v.current){const X=v.current;v.current=null;try{X()}catch(R){console.warn("[useEventStream] Error during unsubscribe:",R)}}k.current=!1},[]),De=l.useCallback(async X=>{if(Ae(),!ve()){L.current=!0,I.current?w("paused","Paused while hidden"):w("offline","Waiting for network");return}ie.current&&(await Pe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),X?.resetAttempts&&(S.current=0),je(),Y.current=Date.now(),w("connecting",null),$t()&&console.info("[useEventStream] Starting event stream...");const R=Z=>{console.warn("Event stream error:",Z)},ne=()=>{const Z=L.current;S.current=0,L.current=!1,Y.current=Date.now(),w("connected",null),m(),Z&&a&&setTimeout(()=>{u(a).then(()=>te(a)).catch(q=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",q)})},0)};if($t()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:g,isCleaningUp:k.current}),k.current){$t()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const Z=Se.subscribeToEvents(V,R,ne,g),q=()=>{try{Z()}catch(_){console.warn("[useEventStream] Error during unsubscribe:",_)}};k.current?q():v.current=q}catch(Z){console.error("[useEventStream] Error during subscription:",Z),R(Z)}},[ve,je,w,m,a,u,te,ye,s,V,g,se,Pe,Ae]),ue=l.useCallback(X=>{if(!ve()){L.current=!0,je(),I.current?w("paused","Paused while hidden"):w("offline","Waiting for network");return}const R=S.current+1;S.current=R;const ne=X??`Retrying (${R})`;w("reconnecting",ne);const Z=R<=3?Math.min(1e3*Math.pow(2,R-1),8e3):Math.min(2e3*Math.pow(2,R-3),32e3),q=Math.floor(Math.random()*250),_=Z+q;N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{De({resetAttempts:!1})},_)},[ve,je,w,De]);l.useEffect(()=>{typeof window<"u"&&(window.__messageTracker=j);let X=null;ie.current&&typeof window<"u"&&(X=K=>{const ee=typeof K.detail?.sessionId=="string"?K.detail.sessionId:null,re=typeof K.detail?.phase=="string"?K.detail.phase:null;ee&&(re==="idle"||re==="busy"||re==="cooldown")&&(se(ee,re),ye())},window.addEventListener("openchamber:session-activity",X));const R=()=>{F.current&&(clearTimeout(F.current),F.current=null)},ne=()=>{F.current||(F.current=setTimeout(()=>{const K=M();E.current=K,K!=="visible"?(je(),L.current=!0,w("paused","Paused while hidden")):R()},5e3))},Z=()=>{E.current=M(),E.current==="visible"?(R(),(L.current||!v.current)&&(console.info("[useEventStream] Visibility restored, triggering soft refresh..."),ie.current||B.current.clear(),a&&(u(a).catch(()=>{}),te(a)),f(),w("connecting","Resuming stream"),De({resetAttempts:!0}))):(w("paused","Paused while hidden"),ne())},q=()=>{E.current=M(),E.current==="visible"&&(R(),(L.current||!v.current)&&(console.info("[useEventStream] Window focused after pause, triggering soft refresh..."),ie.current||B.current.clear(),a&&(te(a),u(a).then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(K=>console.warn("[useEventStream] Failed to refresh messages:",K))),f(),w("connecting","Resuming stream"),De({resetAttempts:!0})))},_=()=>{I.current=!0,(L.current||!v.current)&&(w("connecting","Network restored"),De({resetAttempts:!0}))},Q=()=>{I.current=!1,L.current=!0,w("offline","Waiting for network"),je()};typeof document<"u"&&document.addEventListener("visibilitychange",Z),typeof window<"u"&&(window.addEventListener("online",_),window.addEventListener("offline",Q),window.addEventListener("focus",q));const U=setTimeout(()=>{De({resetAttempts:!0})},100);return $.current&&clearInterval($.current),$.current=setInterval(()=>{if(!ve())return;Date.now()-Y.current>25e3&&Promise.resolve().then(async()=>{try{await Se.checkHealth()?Y.current=Date.now():ue("Refreshing stalled stream")}catch(ee){console.warn("Health check after stale stream failed:",ee),ue("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(U),X&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",X),typeof document<"u"&&document.removeEventListener("visibilitychange",Z),typeof window<"u"&&(window.removeEventListener("online",_),window.removeEventListener("offline",Q),window.removeEventListener("focus",q)),R(),$.current&&(clearInterval($.current),$.current=null);const K=P.current,ee=B.current;K.forEach(re=>clearTimeout(re)),K.clear(),ee.clear(),io.clear(),L.current=!1,E.current=M(),I.current=typeof navigator>"u"?!0:navigator.onLine,je(),D.current&&(clearTimeout(D.current),D.current=null),w("idle",null)}},[a,g,j,M,je,w,De,ue,u,te,se,ve])},bg=()=>{const{createSession:r,abortCurrentOperation:s,initializeNewOpenChamberSession:t,armAbortPrompt:n,clearAbortPrompt:o,currentSessionId:a}=we(),{toggleCommandPalette:i,toggleHelpDialog:c,toggleSidebar:d,setSessionSwitcherOpen:u,setSessionCreateDialogOpen:f,setActiveMainTab:m,setSettingsDialogOpen:p}=Fe(),{agents:h}=yt(),{themeMode:g,setThemeMode:y}=Zs(),{working:b}=dl(),w=l.useRef(null),j=l.useRef(null),x=l.useRef(!1),v=l.useCallback(()=>{j.current&&(clearTimeout(j.current),j.current=null),w.current=null,o()},[o]);l.useEffect(()=>{const N=S=>{if(S.ctrlKey&&S.key==="x"&&(S.preventDefault(),i()),S.ctrlKey&&S.shiftKey&&S.key.toLowerCase()==="l"){const D=bi()?.diagnostics;if(!D||(S.preventDefault(),x.current))return;x.current=!0,D.downloadLogs().then(({fileName:k,content:M})=>{const E=new Blob([M],{type:"text/plain;charset=utf-8"}),I=URL.createObjectURL(E),L=document.createElement("a");L.href=I,L.download=k||"desktop.log",document.body.appendChild(L),L.click(),document.body.removeChild(L),URL.revokeObjectURL(I)}).finally(()=>{x.current=!1});return}if(S.ctrlKey&&S.key==="h"&&(S.preventDefault(),c()),S.ctrlKey&&!S.metaKey&&S.key.toLowerCase()==="n"){if(S.preventDefault(),S.shiftKey){f(!0);return}r().then(C=>{C&&t(C.id,h)})}if((S.metaKey||S.ctrlKey)&&S.key==="/"){S.preventDefault();const C=["light","dark","system"],k=(C.indexOf(g)+1)%C.length;y(C[k])}if(S.ctrlKey&&!S.metaKey&&!S.shiftKey&&S.key.toLowerCase()==="g"){S.preventDefault();const{activeMainTab:C}=Fe.getState();m(C==="git"?"chat":"git");return}if(S.ctrlKey&&!S.metaKey&&!S.shiftKey&&S.key.toLowerCase()==="t"){S.preventDefault();const{activeMainTab:C}=Fe.getState();m(C==="terminal"?"chat":"terminal");return}if(S.ctrlKey&&!S.metaKey&&!S.shiftKey&&S.key===","){S.preventDefault();const{isSettingsDialogOpen:C}=Fe.getState();p(!C);return}if(S.ctrlKey&&!S.metaKey&&!S.shiftKey&&S.key.toLowerCase()==="l"){S.preventDefault();const{isMobile:C,isSessionSwitcherOpen:D}=Fe.getState();C?u(!D):d();return}if(S.ctrlKey&&!S.metaKey&&!S.shiftKey&&S.key.toLowerCase()==="i"){S.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(S.key==="Escape"){const C=a;if(!(b.canAbort&&!!C)){v();return}const k=Date.now(),M=w.current;if(M&&k<M){S.preventDefault(),v(),s();return}S.preventDefault();const E=n(3e3)??k+3e3;w.current=E,j.current&&clearTimeout(j.current);const I=Math.max(E-k,0);j.current=setTimeout(()=>{w.current&&Date.now()>=w.current&&v()},I||0);return}};return window.addEventListener("keydown",N),()=>{window.removeEventListener("keydown",N)}},[r,s,i,c,d,u,f,m,p,y,g,t,h,b,n,v,a]),l.useEffect(()=>()=>{v()},[v])},wg=r=>r.role==="assistant",Za=r=>{const s=r.info;if(!wg(s))return;const t=s.time?.completed;return typeof t=="number"?t:void 0},qr=r=>{if(!r)return!1;if(r.role==="user")return!0;const s=r;return s.clientRole==="user"?!0:!!s.userMessageMarker},Qa=r=>(Array.isArray(r?.parts)?r.parts:[]).map(n=>fr(n)).join(" ").replace(/\s+/g," ").trim(),vg=(r,s)=>{if(!r||!qr(r.info))return-1;const t=Qa(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(!qr(i.info))return;const d=Qa(i),u=!!(t&&d&&d===t),f=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,m=typeof n=="number"&&typeof f=="number"?Math.abs(f-n):null;if(u){const p=typeof m=="number"?m:0;p<a&&(o=c,a=p);return}!t&&!d&&typeof m=="number"&&m<1500&&m<a&&(o=c,a=m)}),o!==-1?o:typeof n=="number"?s.findIndex(i=>{if(!qr(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},jg=()=>{const{currentSessionId:r,messages:s,streamingMessageIds:t}=we(),n=l.useMemo(()=>r?t.get(r)??null:null,[r,t]),o=l.useRef(void 0),a=l.useRef(0),i=l.useCallback(async()=>{if(!r||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=s.get(r)||[],u=await Se.getSessionMessages(r),f=await gg(r);if(!u)return;const m=d[d.length-1];if(m){const p=u.findIndex(y=>y.info.id===m.info.id),g=p===-1?vg(m,u):p;if(g!==-1)if(g<u.length-1){const y=u.slice(g+1);console.log(`[SYNC] Found ${y.length} new messages to append`);const b=[...d,...y],{syncMessages:w}=we.getState();w(r,b)}else{const y=u[g],b=d[d.length-1],w=Za(y),j=Za(b);if(w&&!j){console.log("[SYNC] Last message completed on server");const x=[...d.slice(0,-1),y],{syncMessages:v}=we.getState();v(r,x)}}else if(qr(m.info)){const y=u.slice(-St.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:b}=we.getState();b(r,y)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(f){const p=u.findIndex(h=>h.info.id===f.messageId);if(p!==-1){if(p<u.length-1){const g=u.slice(p+1).slice(-St.VIEWPORT_MESSAGES);if(g.length>0){console.log(`[SYNC] Restoring ${g.length} messages after cursor`);const{syncMessages:y}=we.getState();y(r,g)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const h=u.slice(-St.VIEWPORT_MESSAGES),{syncMessages:g}=we.getState();g(r,h)}}else if(u.length>0){const p=u.slice(-St.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:h}=we.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])},Sg=()=>{l.useEffect(()=>{let r=!1;return(async()=>{try{const t=await Se.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&&we.setState({sessionActivityPhase:n})}catch{}})(),()=>{r=!0}},[])};function Ng(){const{git:r}=Xs(),s=dt(i=>i.currentDirectory),{setActiveDirectory:t,startPolling:n,stopPolling:o,fetchAll:a}=xt();l.useEffect(()=>{if(!s||!r){o();return}return t(s),a(s,r),n(r),()=>{o()}},[s,r,t,n,o,a])}function kg({children:r}){return Ng(),e.jsx(e.Fragment,{children:r})}const Cg=()=>{const[{isUpdating:r,message:s},t]=l.useState(()=>Du());return l.useEffect(()=>Au(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(qs,{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 Mg({apis:r,children:s}){return e.jsx(_i.Provider,{value:r,children:s})}const Ag="curl -fsSL https://opencode.ai/install | bash",Dg=3e3;function Eg({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(Gt,{className:"h-4 w-4"})})]})}const Tg=3e4;function Ig({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),Tg);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:m}=await Ws(async()=>{const{getCurrentWindow:h}=await import("./vendor-.pnpm-B1ce5n1Z.js").then(g=>g.bL);return{getCurrentWindow:h}},__vite__mapDeps([1,2]));await m().startDragging()}catch(m){console.error("Failed to start window dragging:",m)}},[a]),d=l.useCallback(async()=>{try{const f=await fetch("/health");return f.ok?(await f.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=l.useCallback(async()=>{try{await navigator.clipboard.writeText(Ag),t(!0),setTimeout(()=>t(!1),2e3)}catch(f){console.error("Failed to copy:",f)}},[]);return l.useEffect(()=>{const f=async()=>{await d()&&r?.()},m=setInterval(f,Dg);return f(),()=>clearInterval(m)},[d,r]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:c,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(Yn,{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(ht,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(Eg,{onCopy:u})})}),e.jsxs("a",{href:"https://opencode.ai/docs",target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1 justify-center",children:["View documentation",e.jsx(Yn,{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 Pg({apis:r}){const{initializeApp:s,loadProviders:t,isInitialized:n}=yt(),{error:o,clearError:a,loadSessions:i}=we(),c=dt(j=>j.currentDirectory),d=dt(j=>j.isSwitchingDirectory),[u,f]=l.useState(!1),{uiFont:m,monoFont:p}=Ml(),[h,g]=l.useState(()=>r.runtime.isDesktop),[y,b]=l.useState(()=>r.runtime.isDesktop?Od():!0);l.useEffect(()=>{g(r.runtime.isDesktop)},[r.runtime.isDesktop]),l.useEffect(()=>(Uo(r),()=>Uo(null)),[r]),l.useEffect(()=>{if(typeof document>"u")return;const j=document.documentElement,x=qa[m]?.stack??qa[tg].stack,v=Ts[p]?.stack??Ts[Gr].stack;j.style.setProperty("--font-sans",x),j.style.setProperty("--font-heading",x),j.style.setProperty("--font-family-sans",x),j.style.setProperty("--font-mono",v),j.style.setProperty("--font-family-mono",v),j.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=x)},[m,p]),l.useEffect(()=>{if(n){const x=setTimeout(()=>{const v=document.getElementById("initial-loading");v&&(v.classList.add("fade-out"),setTimeout(()=>{v.remove()},300))},150);return()=>clearTimeout(x)}},[n]),l.useEffect(()=>{const j=setTimeout(()=>{const x=document.getElementById("initial-loading");x&&!n&&(x.classList.add("fade-out"),setTimeout(()=>{x.remove()},300))},5e3);return()=>clearTimeout(j)},[n]),l.useEffect(()=>{(async()=>{await s(),await t()})()},[s,t]),l.useEffect(()=>{if(d)return;(async()=>{Se.setDirectory(c),await i()})()},[c,d,i]),yg(),bg(),jg(),Sg(),l.useEffect(()=>{const j=x=>{(x.metaKey||x.ctrlKey)&&x.shiftKey&&x.key==="M"&&(x.preventDefault(),f(v=>!v))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[]),l.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const w=l.useCallback(()=>{b(!0),window.location.reload()},[]);return h&&!y?e.jsx(ls,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(Ig,{onCliAvailable:w})})}):e.jsx(ls,{children:e.jsx(Mg,{apis:r,children:e.jsx(kg,{children:e.jsx(Ih,{children:e.jsxs("div",{className:`h-full text-foreground ${h?"bg-transparent":"bg-background"}`,children:[e.jsx(lg,{}),e.jsx(cg,{}),e.jsx(Cg,{}),u&&e.jsx(ug,{onClose:()=>f(!1)})]})})})})})}const Pl=({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"})]}),Rl=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=dt.getState();r&&t.homeDirectory!==r&&t.synchronizeHomeDirectory(r),s&&t.setDirectory(s,{showOverlay:!1})},Fl="/auth/session",Rg=async()=>fetch(Fl,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),Fg=async r=>fetch(Fl,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:r})}),To=({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})]}),Lg=({message:r="Preparing workspace…"})=>e.jsx(To,{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})})}),_g=({onRetry:r})=>e.jsx(To,{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(Pl,{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(Ne,{type:"button",onClick:r,className:"w-full",children:"Retry"})]})})}),Og=({children:r})=>{const s=l.useMemo(()=>Rt(),[]),[t,n]=l.useState(()=>s?"authenticated":"pending"),[o,a]=l.useState(""),[i,c]=l.useState(!1),[d,u]=l.useState(""),f=l.useRef(null),m=l.useRef(s),p=l.useCallback(async()=>{if(s){n("authenticated");return}n(g=>g==="authenticated"?g:"pending");try{const g=await Rg();if(g.ok){n("authenticated"),u("");return}if(g.status===401){n("locked");return}n("error")}catch(g){console.warn("Failed to check session status:",g),n("error")}},[s]);l.useEffect(()=>{s||p()},[p,s]),l.useEffect(()=>{!s&&t==="locked"&&(m.current=!1)},[s,t]),l.useEffect(()=>{t==="locked"&&f.current&&(f.current.focus(),f.current.select())},[t]),l.useEffect(()=>{s||t==="authenticated"&&!m.current&&(m.current=!0,(async()=>(await ji(),await Si(),await Rl()))())},[s,t]);const h=async g=>{if(g.preventDefault(),!(!o||i)){c(!0),u("");try{const y=await Fg(o);if(y.ok){a(""),n("authenticated");return}if(y.status===401){u("Incorrect password. Try again."),n("locked");return}u("Unexpected response from server."),n("error")}catch(y){console.warn("Failed to submit UI password:",y),u("Network error. Check connection and retry."),n("error")}finally{c(!1)}}};return t==="pending"?e.jsx(Lg,{}):t==="error"?e.jsx(_g,{onRetry:()=>void p()}):t==="locked"?e.jsx(To,{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(Pl,{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:h,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(bt,{id:"openchamber-ui-password",ref:f,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:o,onChange:g=>{a(g.target.value),d&&u("")},"aria-invalid":!!d||void 0,"aria-describedby":d?"oc-ui-auth-error":void 0,disabled:i}),d&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:d})]}),e.jsx(Ne,{type:"submit",className:"w-full",disabled:!o||i,children:i?"Unlocking…":"Unlock"})]})]})}):e.jsx(e.Fragment,{children:r})},Gn=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 $g{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(`
|
|
43
|
-
`)}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=Gn(s.colors.surface.muted),o=Gn(s.colors.surface.subtle),a=Gn(s.colors.interactive.border);t.push(` --sidebar-base: ${s.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${s.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${s.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${s.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${s.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${s.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${s.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${s.colors.interactive.focusRing} !important;`);const i=s.metadata.variant==="dark",c=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=s.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,c)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return s.colors.charts?.series&&Array.isArray(s.colors.charts.series)&&s.colors.charts.series.forEach((u,f)=>{t.push(` --chart-${f+1}: ${u};`)}),s.colors.loading?(t.push(` --loading-spinner: ${s.colors.loading.spinner||s.colors.primary.base};`),t.push(` --loading-spinner-track: ${s.colors.loading.spinnerTrack||s.colors.surface.muted};`)):(t.push(` --loading-spinner: ${s.colors.primary.base};`),t.push(` --loading-spinner-track: ${s.colors.surface.muted};`)),t}apply(s){const t=this.generate(s),n=document.createElement("style");n.id="opencode-theme-variables";let o="";s.metadata.variant==="dark"?(o=`:root {
|
|
44
|
-
${t}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
.dark {
|
|
48
|
-
${t}
|
|
49
|
-
}`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
|
|
50
|
-
${t}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
:root:not(.dark) {
|
|
54
|
-
${t}
|
|
55
|
-
}`,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=[];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: ${Es.markdown};`),s.push(" /* Code content - all code elements use same size */"),s.push(` --text-code: ${Es.code};`),s.push(" /* UI headers - dialog titles, panel headers */"),s.push(` --text-ui-header: ${Es.uiHeader};`),s.push(" /* UI labels - buttons, menus, navigation */"),s.push(` --text-ui-label: ${Es.uiLabel};`),s.push(" /* Metadata - timestamps, status, helper text */"),s.push(` --text-meta: ${Es.meta};`),s.push(" /* Micro text - badges, shortcuts, indicators */"),s.push(` --text-micro: ${Es.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 Io={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"}}},Po={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"}}},bn=[Io,Po];function cn(r){return bn.find(s=>s.metadata.id===r)}const Ll=Io.metadata.id,_l=Po.metadata.id,zg=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Ol=r=>r==="dark"?Po:Io,Bg=r=>(bn.find(t=>t.metadata.variant===r)??Ol(r)).metadata.id,Or=(r,s)=>{const t=cn(r);return t&&t.metadata.variant===s?t:bn.find(o=>o.metadata.variant===s)??Ol(s)},dn=(r,s)=>{if(!r)return s==="light"?Ll:_l;const t=cn(r);return t&&t.metadata.variant===s?t.metadata.id:Bg(s)},Hg=r=>{let s=Ll,t=_l,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const m=cn(d);m&&(n=m.metadata.variant==="dark"?"dark":"light",m.metadata.variant==="dark"?t=m.metadata.id:s=m.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);s=dn(a,"light"),t=dn(i,"dark")}if(r){const o=cn(r);o&&(o.metadata.variant==="light"?s=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:s,darkThemeId:t}};function Wg({children:r,defaultThemeId:s}){const t=ge.useMemo(()=>new $g,[]),[n,o]=ge.useState(()=>Hg(s)),[a,i]=ge.useState(()=>zg()),c=ge.useMemo(()=>n.themeMode==="light"?Or(n.lightThemeId,"light"):n.themeMode==="dark"||a?Or(n.darkThemeId,"dark"):Or(n.lightThemeId,"light"),[n,a]),d=bn,u=ge.useCallback(b=>{if(typeof document>"u")return;const w=b.colors.surface.background;Rt()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=w;let j=document.querySelector('meta[name="theme-color"]');j||(j=document.createElement("meta"),j.setAttribute("name","theme-color"),document.head.appendChild(j)),j.setAttribute("content",w);const x=b.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let v=document.querySelector(`meta[name="theme-color"][media="${x}"]`);v||(v=document.createElement("meta"),v.setAttribute("name","theme-color"),v.setAttribute("media",x),document.head.appendChild(v)),v.setAttribute("content",w)},[]);ge.useEffect(()=>{if(typeof window>"u")return;t.apply(c),u(c);const b=document.documentElement;b.classList.remove("light","dark"),b.classList.add(c.metadata.variant)},[t,c,u]),ge.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const b=window.matchMedia("(prefers-color-scheme: dark)"),w=j=>{i(j.matches)};return i(b.matches),b.addEventListener("change",w),()=>b.removeEventListener("change",w)},[n.themeMode]),ge.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",c.metadata.id),localStorage.setItem("selectedThemeVariant",c.metadata.variant==="light"?"light":"dark"))},[n,c]),ge.useEffect(()=>{os({themeId:c.metadata.id,themeVariant:c.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[c.metadata.id,c.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),ge.useEffect(()=>{if(typeof window>"u")return;const b=w=>{const j=w.detail;j&&o(x=>{let v=x.themeMode;j.useSystemTheme===!0?v="system":j.useSystemTheme===!1&&(j.themeVariant==="dark"||j.themeVariant==="light")&&(v=j.themeVariant);let N=x.lightThemeId;typeof j.lightThemeId=="string"&&j.lightThemeId.length>0&&(N=dn(j.lightThemeId,"light"));let S=x.darkThemeId;return typeof j.darkThemeId=="string"&&j.darkThemeId.length>0&&(S=dn(j.darkThemeId,"dark")),v===x.themeMode&&N===x.lightThemeId&&S===x.darkThemeId?x:{themeMode:v,lightThemeId:N,darkThemeId:S}})};return window.addEventListener("openchamber:settings-synced",b),()=>window.removeEventListener("openchamber:settings-synced",b)},[]);const f=ge.useCallback(b=>{const w=d.find(j=>j.metadata.id===b);w&&o(j=>w.metadata.variant==="dark"?j.darkThemeId===w.metadata.id&&j.themeMode==="dark"?j:{...j,darkThemeId:w.metadata.id,themeMode:"dark"}:j.lightThemeId===w.metadata.id&&j.themeMode==="light"?j:{...j,lightThemeId:w.metadata.id,themeMode:"light"})},[d]),m=ge.useCallback(b=>{o(w=>w.themeMode===b?w:{...w,themeMode:b})},[]),p=ge.useCallback(b=>{if(b){o(j=>j.themeMode==="system"?j:{...j,themeMode:"system"});return}const w=c.metadata.variant==="dark"?"dark":"light";o(j=>j.themeMode===w?j:{...j,themeMode:w})},[c.metadata.variant]),h=ge.useCallback(b=>{const w=d.find(j=>j.metadata.id===b&&j.metadata.variant==="light");w&&o(j=>j.lightThemeId===w.metadata.id?j:{...j,lightThemeId:w.metadata.id})},[d]),g=ge.useCallback(b=>{const w=d.find(j=>j.metadata.id===b&&j.metadata.variant==="dark");w&&o(j=>j.darkThemeId===w.metadata.id?j:{...j,darkThemeId:w.metadata.id})},[d]),y={currentTheme:c,availableThemes:d,setTheme:f,isSystemPreference:n.themeMode==="system",setSystemPreference:p,themeMode:n.themeMode,setThemeMode:m,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:h,setDarkThemePreference:g};return e.jsx(Mo.Provider,{value:y,children:r})}const Ug=({children:r})=>{const{theme:s,applyTheme:t}=Fe();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})},Vg={getLastAssistantMessage(){const r=we.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"),u=a.length===0,f=!i&&!c&&(!u||d),m={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:f,raw:o};return console.log("[INSPECT] Last Assistant Message:",m),console.log("[SUMMARY] Summary:",{messageId:m.messageId,partsCount:m.partsCount,isEmpty:m.isEmpty,isEmptyResponse:m.isEmptyResponse,hasText:i,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!c}),m.isEmpty&&console.warn("[WARNING] Message has NO parts!"),m.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!c&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),m}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(r,s=80){return!r||typeof r!="string"||r.length<=s?r:r.substring(0,s)+"…"},truncateMessages(r){return r.map(s=>({...s,parts:(s.parts||[]).map(t=>{const n={...t};return"text"in t&&(n.text=this.truncateString(t.text)),"textPreview"in t&&(n.textPreview=this.truncateString(t.textPreview)),t.state&&(n.state={...t.state},"output"in t.state&&(n.state.output=this.truncateString(t.state.output)),"error"in t.state&&(n.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(n.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),n})}))},getAllMessages(r=!1){const s=we.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=we.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=we.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:
|
|
56
|
-
`),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
|
|
57
|
-
`),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
|
|
58
|
-
`),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)
|
|
59
|
-
`),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=we.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},u=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},m=c.map((p,h)=>{const g=p.info??{},y=Array.isArray(p.parts)?p.parts:[],b=g.time??{},w=u(b.completed),j=w!==null,x=y.filter(I=>I.type==="tool"),v=y.filter(I=>I.type==="reasoning"),N=f(x.map(I=>u(I.state?.time?.end??I.state?.time?.start))),S=f(v.map(I=>u(I.time?.end??I.time?.start))),C=f([N,S].filter(I=>I!==null)),D=x.some(I=>["pending","running","started"].includes(I.state?.status)),k=v.some(I=>typeof I.time?.end!="number");x.length>0&&(d.withTools+=1),v.length>0&&(d.withReasoning+=1),j||(d.completedMissing+=1);const M=!!(j&&typeof N=="number"&&w<N);M&&(d.completedBeforeTool+=1);const E=!!(j&&typeof S=="number"&&w<S);return E&&(d.completedBeforeReasoning+=1),j&&D&&(d.runningToolsWhenCompleted+=1),j&&k&&(d.reasoningOpenWhenCompleted+=1),{index:h,messageId:g.id,role:g.role,completedAt:w,latestToolTimestamp:N,latestReasoningTimestamp:S,latestPartTimestamp:C,completed_missing:!j,completed_before_tool:M,completed_before_reasoning:E,running_tools_when_completed:!!(j&&D),reasoning_open_when_completed:!!(j&&k),has_tools:x.length>0,has_reasoning:v.length>0}});return t&&(console.table(m.slice(0,n)),m.length>n&&console.log(`Displayed first ${n} rows out of ${m.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:m}},checkCompletionStatus(){const r=we.getState(),s=r.currentSessionId;if(!s)return console.log("[ERROR] No active session"),null;const n=(r.messages.get(s)||[]).filter(b=>b.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(b=>b.type==="step-finish"),i=o.parts.some(b=>b.type==="step-finish"&&b.reason==="stop"),d=o.info.time?.completed,u=o.info.status,f=typeof d=="number"&&d>0||u==="completed",m=!!(f&&i),p=r.messageStreamStates,h=o.info.sessionID?r.streamingMessageIds.get(o.info.sessionID)??null:null,g=p.get(o.info.id),y=o.info.id===h;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",f),console.log("hasStopReason:",i),console.log("messageIsComplete:",m),console.log("lifecycle phase:",g?.phase),console.log("isStreamingCandidate:",y),console.log("streamingMessageId:",h),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:f,hasStopReason:i,messageIsComplete:m,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=Vg,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 ei=!1;const Gg=()=>{if(ei||typeof window>"u")return;ei=!0;let r={showReasoningTraces:Fe.getState().showReasoningTraces},s=null,t=null;const n=()=>{const a=s;s=null,t=null,a&&Object.keys(a).length>0&&os(a)},o=a=>{s={...s??{},...a},!t&&(t=setTimeout(n,150))};Fe.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces},c={};i.showReasoningTraces!==r.showReasoningTraces&&(c.showReasoningTraces=i.showReasoningTraces),r=i,Object.keys(c).length>0&&o(c)})};let ti=!1;const qg=()=>{if(typeof document>"u")return;const r=document.documentElement;Object.entries(Es).forEach(([s,t])=>{const n=`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`;r.style.setProperty(n,t)})},Kg=()=>{ti||typeof window>"u"||(ti=!0,qg())},Yg=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await ji();await Si();Gg();Kg();await Rl();typeof window<"u"&&(window.debugContextTokens=()=>{const r=window.__zustand_session_store__;if(!r)return;const s=r.getState(),t=s.currentSessionId;if(!t)return;const o=(s.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const i=o[o.length-1].info.tokens;i&&typeof i=="object"&&console.debug("Token breakdown:",{base:(i.input||0)+(i.output||0)+(i.reasoning||0),cache:i.cache?(i.cache.read||0)+(i.cache.write||0):0}),s.sessionContextUsage.get(t);const c=window.__zustand_config_store__;if(c){const d=c.getState().getCurrentModel(),u=d?.limit?.context||0,f=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&s.getContextUsage(u,f)}});const $l=document.getElementById("root");if(!$l)throw new Error("Root element not found");bd.createRoot($l).render(e.jsx(ge.StrictMode,{children:e.jsx(Wg,{children:e.jsx(Ug,{children:e.jsx(Og,{children:e.jsx(Pg,{apis:Yg})})})})}));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 Zg=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ms as D,fs as a,Am as b,A as c,Pp as d,Rp as e,$a as f,xn as g,Fp as h,_p as i,Zg as m,Op as p,Lp as r,Vr as t,Zs as u};
|