@openchamber/web 1.1.1 → 1.1.2
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-DQgBqdB9.js → MonacoDiffViewer-Bfe8kvMD.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DGK97u29.js → ToolOutputDialog-JB7cKw3B.js} +1 -1
- package/dist/assets/index-CfuUZcD_.css +1 -0
- package/dist/assets/{index-DGdbqmi8.js → index-CwlOducd.js} +2 -2
- package/dist/assets/{main-Cc1ax0UC.js → main-D_z8j30p.js} +5 -5
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/index-l6a40qve.css +0 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MonacoDiffViewer-
|
|
2
|
-
import{t as ic,c as lc,j as e,R as cc,T as dc,P as uc,C as mc,A as fc,a as pc,S as ji,b as Si,d as Tt,e as Pt,p as rs,f as ns,g as hc,I as gc,h as l,i as xc,k as yc,l as bc,m as wc,n as vc,o as jc,q as Sc,s as jt,r as Nc,u as kc,v as Cc,w as Mc,x as ps,y as Ac,z as Dc,B as Ec,_ as Js,D as yt,U as Dt,E as he,K as eo,F as fe,Z as Tc,Y as Ms,Q as Ds,W as Et,O as wr,V as wo,G as to,J as er,H as Ni,L as Ic,M as Pc,N as Rc,X as ss,$ as Fc,a0 as _c,a1 as Lc,a2 as Oc,a3 as $c,a4 as so,a5 as vo,a6 as zc,a7 as tn,a8 as jo,a9 as bn,aa as tr,ab as Bc,ac as Yt,ad as sn,ae as wn,af as ws,ag as Es,ah as ki,ai as Ci,aj as vr,ak as Hc,al as ds,am as Ht,an as Xo,ao as So,ap as Mi,aq as No,ar as ko,as as Co,at as vn,au as Jo,av as Hs,aw as Mo,ax as fr,ay as jr,az as Wc,aA as Uc,aB as Ai,aC as Di,aD as Ys,aE as Vc,aF as Gc,aG as Mn,aH as qc,aI as Gt,aJ as Kc,aK as Yc,aL as An,aM as Xc,aN as Ao,aO as Do,aP as Jc,aQ as Zc,aR as Zs,aS as $s,aT as jn,aU as Sn,aV as Eo,aW as Qc,aX as ed,aY as td,aZ as sd,a_ as rd,a$ as nd,b0 as od,b1 as ro,b2 as Gr,b3 as To,b4 as ad,b5 as id,b6 as or,b7 as ld,b8 as cd,b9 as Sr,ba as dd,bb as ud,bc as md,bd as fd,be as no,bf as pd,bg as ls,bh as hd,bi as gd,bj as xd,bk as pr,bl as yd,bm as bd,bn as wd,bo as vd,bp as jd,bq as Sd,br as Nd,bs as kd,bt as Cd,bu as Md,bv as Ad,bw as Dd,bx as Ed,by as Td,bz as Id,bA as Pd,bB as Zo,bC as Ei,bD as Rd,bE as Fd,bF as Qo,bG as _d,bH as Ld,bI as Od,bJ as $d,bK as zd}from"./vendor-.pnpm-BGm12ky3.js";import{c as Bd,l as Hd,g as Wd,r as Ud,d as Vd,a as Gd,b as qd,u as Kd,e as Yd,f as Xd,h as Jd,i as Zd,j as Qd,k as eu}from"./index-DGdbqmi8.js";function T(...r){return ic(lc(r))}const Ti=(r,s)=>{const t=r??"",n=Math.max(16,s?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const m=c?`${c}/${d}`:d;if(m.length>i)break;c=m}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},rn=r=>r?r==="/"?"/":r.replace(/\/+$/,""):"";function It(r,s){if(!r)return"";const t=rn(r);if(t==="/")return"/";const n=s?rn(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 Dn(r,s){if(!r)return"/";const t=rn(r);if(!t||t==="/")return"/";const n=s?rn(s):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function tu({delayDuration:r=0,...s}){return e.jsx(pc,{"data-slot":"tooltip-provider",delayDuration:r,...s})}function dt({delayDuration:r=0,...s}){return e.jsx(tu,{delayDuration:r,children:e.jsx(cc,{"data-slot":"tooltip",...s})})}function ut({...r}){return e.jsx(dc,{"data-slot":"tooltip-trigger",...r})}function lt({className:r,sideOffset:s=0,children:t,...n}){return e.jsx(uc,{children:e.jsxs(mc,{"data-slot":"tooltip-content",sideOffset:s,className:T("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",r),...n,children:[t,e.jsx(fc,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}const su=Si("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 Ce({className:r,variant:s,size:t,asChild:n=!1,...o}){const a=n?ji:"button";return e.jsx(a,{"data-slot":"button",className:T(su({variant:s,size:t,className:r})),...o})}let En=null;const ea=()=>{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}}},ru=()=>{if(typeof window>"u"||!window.localStorage)return ea();const r=window.localStorage,s=ea();let t=!0;const n=()=>{t=!1};return{getItem:m=>{if(t)try{const f=r.getItem(m);if(f!==null)return f}catch{n()}return s.getItem(m)},setItem:(m,f)=>{if(t)try{r.setItem(m,f),s.removeItem(m);return}catch{n()}s.setItem(m,f)},removeItem:m=>{if(t)try{r.removeItem(m)}catch{n()}s.removeItem(m)},clear:()=>{if(t)try{r.clear()}catch{n()}s.clear()},key:m=>{if(t)try{return r.key(m)}catch{n()}return s.key(m)},get length(){if(t)try{return r.length+s.length}catch{n()}return s.length}}},zt=()=>(En||(En=ru()),En),Le=Tt()(Pt(rs((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:ns(()=>zt()),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"})),_t=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",nn=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Ts=()=>_t()?window.opencodeDesktop??null:null,Ii=()=>{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},Pi=async()=>{const r=Ts();if(typeof window<"u"){const s=window.__OPENCHAMBER_HOME__;if(s&&s.length>0)return s}if(!r)return null;if(typeof r.homeDirectory=="string"&&r.homeDirectory.length>0)return r.homeDirectory;try{if(!r.getHomeDirectory)return null;const s=await r.getHomeDirectory();if(s?.success&&typeof s.path=="string"&&s.path.length>0)return s.path}catch(s){console.warn("Failed to obtain desktop home directory:",s)}return null},nu=async()=>{const r=Ts();if(!r)return null;try{return await r.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},ou=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Ri=async()=>{const r=Ii();if(!r)return null;try{return await r.getSettings()}catch(s){return console.warn("Failed to read desktop settings",s),null}},au=async r=>{const s=Ii();if(!s)return null;try{return await s.updateSettings(r)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},iu=async r=>{const s=Ts();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)}}},lu=async r=>{const s=Ts();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)}}},cu=async r=>{const s=Ts();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)}}},du=async()=>{const r=Ts();if(!r||!r.checkForUpdates)return null;try{return await r.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},uu=async r=>{const s=Ts();if(!s||!s.downloadUpdate)return!1;try{return await s.downloadUpdate(r),!0}catch(t){return console.warn("Failed to download update",t),!1}},mu=async()=>{const r=Ts();if(!r||!r.restartToUpdate)return!1;try{return await r.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}},fu="/api",pu=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,hu=r=>{const s=typeof r=="string"&&r.trim().length>0?r.trim():"/api";if(pu.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}},gu=()=>{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},Dr=r=>r.replace(/\\/g,"/"),Tn=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_RUNTIME_APIS__;return r&&r.runtime?.isDesktop&&r.files?r.files:null};class xu{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=fu){const n=gu()||s;this.baseUrl=hu(n),this.client=hc({baseUrl:this.baseUrl})}normalizeCandidatePath(s){if(typeof s!="string")return null;const t=s.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(s){const t=s.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],c=s.slice(a.length+(s.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=s.startsWith("/"),o=s.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(s){this.currentDirectory=s}getDirectory(){return this.currentDirectory}async withDirectory(s,t){if(s==null)return t();const n=this.currentDirectory;this.currentDirectory=s;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const s=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&s.add(a)};try{const a=(await this.client.path.get({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!s.size)try{const o=await this.client.project.current({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!s.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!s.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!s.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(s);return this.deriveHomeDirectory(n)}async listSessions(){const s=await this.client.session.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});return Array.isArray(s.data)?s.data:[]}async createSession(s){const t=await this.client.session.create({query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{parentID:s?.parentID,title:s?.title}});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(s){const t=await this.client.session.get({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(s){return(await this.client.session.delete({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||!1}async updateSession(s,t){const n=await this.client.session.update({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{title:t}});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(s){return(await this.client.session.messages({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}async sendMessage(s){const t=Date.now(),n=s.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(s.prefaceText&&s.prefaceText.trim()&&o.push({type:"text",text:s.prefaceText}),s.text&&s.text.trim()){const a={type:"text",text:s.text};o.push(a)}if(s.files&&s.files.length>0&&s.files.forEach(a=>{const i={type:"file",mime:a.mime,filename:a.filename,url:a.url};o.push(i)}),s.agentMentions&&s.agentMentions.length>0){const[a]=s.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({path:{id:s.id},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{model:{providerID:s.providerID,modelID:s.modelID},agent:s.agent,parts:o}}),n}async abortSession(s){return!!(await this.client.session.abort({path:{id:s},throwOnError:!0})).data}async getSessionStatus(){try{const s=this.baseUrl.replace(/\/$/,""),t=new URL(`${s}/session/status`);this.currentDirectory&&this.currentDirectory.length>0&&t.searchParams.set("directory",this.currentDirectory);const n=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return{};const o=await n.json().catch(()=>null);return!o||typeof o!="object"?{}:o}catch{return{}}}async respondToPermission(s,t,n){return(await this.client.postSessionIdPermissionsPermissionId({path:{id:s,permissionID:t},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{response:n}})).data||!1}async getConfig(){const s=await this.client.config.get();if(!s.data)throw new Error("Failed to get config");return s.data}async updateConfig(s){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(s){const t=await this.getConfig(),n=s(t);return await this.updateConfig(n)}async getProviders(){const s=await this.client.config.providers({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!s.data)throw new Error("Failed to get providers");return s.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}catch{return[]}}subscribeToEvents(s,t,n,o){this.sseAbortController&&this.sseAbortController.abort();const a=new AbortController;return this.sseAbortController=a,console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const i=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",i);const c=async d=>{try{const m=await this.client.event.subscribe({query:i?{directory:i}:void 0,signal:a.signal,sseMaxRetryAttempts:2,sseDefaultRetryDelay:500,sseMaxRetryDelay:8e3,onSseError:f=>{f instanceof Error&&f.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",f),t&&!a.signal.aborted&&t(f))},onSseEvent:f=>{if(!a.signal.aborted){const u=f.data;u&&typeof u=="object"&&s(u)}}});n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const f of m.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(m){if(m?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",m),t&&t(m);const f=Math.min(500*Math.pow(2,d),8e3);await new Promise(u=>setTimeout(u,f)),a.signal.aborted||await c(d+1)}};try{await c(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortController===a&&(this.sseAbortController=null)}})(),()=>{this.sseAbortController===a&&(this.sseAbortController=null),a.abort()}}async readFile(s){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${s}
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/MonacoDiffViewer-Bfe8kvMD.js","assets/vendor-.pnpm-BGm12ky3.js","assets/vendor--B3aGWKBE.css","assets/index-CwlOducd.js","assets/index-CfuUZcD_.css","assets/ToolOutputDialog-JB7cKw3B.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as ic,c as lc,j as e,R as cc,T as dc,P as uc,C as mc,A as fc,a as pc,S as ji,b as Si,d as Tt,e as Pt,p as rs,f as ns,g as hc,I as gc,h as l,i as xc,k as yc,l as bc,m as wc,n as vc,o as jc,q as Sc,s as jt,r as Nc,u as kc,v as Cc,w as Mc,x as ps,y as Ac,z as Dc,B as Ec,_ as Js,D as yt,U as Dt,E as he,K as eo,F as fe,Z as Tc,Y as Ms,Q as Ds,W as Et,O as wr,V as wo,G as to,J as er,H as Ni,L as Ic,M as Pc,N as Rc,X as ss,$ as Fc,a0 as _c,a1 as Lc,a2 as Oc,a3 as $c,a4 as so,a5 as vo,a6 as zc,a7 as tn,a8 as jo,a9 as bn,aa as tr,ab as Bc,ac as Yt,ad as sn,ae as wn,af as ws,ag as Es,ah as ki,ai as Ci,aj as vr,ak as Hc,al as ds,am as Ht,an as Xo,ao as So,ap as Mi,aq as No,ar as ko,as as Co,at as vn,au as Jo,av as Hs,aw as Mo,ax as fr,ay as jr,az as Wc,aA as Uc,aB as Ai,aC as Di,aD as Ys,aE as Vc,aF as Gc,aG as Mn,aH as qc,aI as Gt,aJ as Kc,aK as Yc,aL as An,aM as Xc,aN as Ao,aO as Do,aP as Jc,aQ as Zc,aR as Zs,aS as $s,aT as jn,aU as Sn,aV as Eo,aW as Qc,aX as ed,aY as td,aZ as sd,a_ as rd,a$ as nd,b0 as od,b1 as ro,b2 as Gr,b3 as To,b4 as ad,b5 as id,b6 as or,b7 as ld,b8 as cd,b9 as Sr,ba as dd,bb as ud,bc as md,bd as fd,be as no,bf as pd,bg as ls,bh as hd,bi as gd,bj as xd,bk as pr,bl as yd,bm as bd,bn as wd,bo as vd,bp as jd,bq as Sd,br as Nd,bs as kd,bt as Cd,bu as Md,bv as Ad,bw as Dd,bx as Ed,by as Td,bz as Id,bA as Pd,bB as Zo,bC as Ei,bD as Rd,bE as Fd,bF as Qo,bG as _d,bH as Ld,bI as Od,bJ as $d,bK as zd}from"./vendor-.pnpm-BGm12ky3.js";import{c as Bd,l as Hd,g as Wd,r as Ud,d as Vd,a as Gd,b as qd,u as Kd,e as Yd,f as Xd,h as Jd,i as Zd,j as Qd,k as eu}from"./index-CwlOducd.js";function T(...r){return ic(lc(r))}const Ti=(r,s)=>{const t=r??"",n=Math.max(16,s?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const m=c?`${c}/${d}`:d;if(m.length>i)break;c=m}if(!c){const d=o[0]??"";c=d?d.slice(0,i):""}return c?`${c}…/${a}`:`…/${a}`},rn=r=>r?r==="/"?"/":r.replace(/\/+$/,""):"";function It(r,s){if(!r)return"";const t=rn(r);if(t==="/")return"/";const n=s?rn(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 Dn(r,s){if(!r)return"/";const t=rn(r);if(!t||t==="/")return"/";const n=s?rn(s):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function tu({delayDuration:r=0,...s}){return e.jsx(pc,{"data-slot":"tooltip-provider",delayDuration:r,...s})}function dt({delayDuration:r=0,...s}){return e.jsx(tu,{delayDuration:r,children:e.jsx(cc,{"data-slot":"tooltip",...s})})}function ut({...r}){return e.jsx(dc,{"data-slot":"tooltip-trigger",...r})}function lt({className:r,sideOffset:s=0,children:t,...n}){return e.jsx(uc,{children:e.jsxs(mc,{"data-slot":"tooltip-content",sideOffset:s,className:T("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",r),...n,children:[t,e.jsx(fc,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}const su=Si("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 Ce({className:r,variant:s,size:t,asChild:n=!1,...o}){const a=n?ji:"button";return e.jsx(a,{"data-slot":"button",className:T(su({variant:s,size:t,className:r})),...o})}let En=null;const ea=()=>{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}}},ru=()=>{if(typeof window>"u"||!window.localStorage)return ea();const r=window.localStorage,s=ea();let t=!0;const n=()=>{t=!1};return{getItem:m=>{if(t)try{const f=r.getItem(m);if(f!==null)return f}catch{n()}return s.getItem(m)},setItem:(m,f)=>{if(t)try{r.setItem(m,f),s.removeItem(m);return}catch{n()}s.setItem(m,f)},removeItem:m=>{if(t)try{r.removeItem(m)}catch{n()}s.removeItem(m)},clear:()=>{if(t)try{r.clear()}catch{n()}s.clear()},key:m=>{if(t)try{return r.key(m)}catch{n()}return s.key(m)},get length(){if(t)try{return r.length+s.length}catch{n()}return s.length}}},zt=()=>(En||(En=ru()),En),Le=Tt()(Pt(rs((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:ns(()=>zt()),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"})),_t=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",nn=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,Ts=()=>_t()?window.opencodeDesktop??null:null,Ii=()=>{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},Pi=async()=>{const r=Ts();if(typeof window<"u"){const s=window.__OPENCHAMBER_HOME__;if(s&&s.length>0)return s}if(!r)return null;if(typeof r.homeDirectory=="string"&&r.homeDirectory.length>0)return r.homeDirectory;try{if(!r.getHomeDirectory)return null;const s=await r.getHomeDirectory();if(s?.success&&typeof s.path=="string"&&s.path.length>0)return s.path}catch(s){console.warn("Failed to obtain desktop home directory:",s)}return null},nu=async()=>{const r=Ts();if(!r)return null;try{return await r.getServerInfo()}catch(s){return console.warn("Failed to read desktop server info",s),null}},ou=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Ri=async()=>{const r=Ii();if(!r)return null;try{return await r.getSettings()}catch(s){return console.warn("Failed to read desktop settings",s),null}},au=async r=>{const s=Ii();if(!s)return null;try{return await s.updateSettings(r)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},iu=async r=>{const s=Ts();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)}}},lu=async r=>{const s=Ts();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)}}},cu=async r=>{const s=Ts();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)}}},du=async()=>{const r=Ts();if(!r||!r.checkForUpdates)return null;try{return await r.checkForUpdates()}catch(s){return console.warn("Failed to check for updates",s),null}},uu=async r=>{const s=Ts();if(!s||!s.downloadUpdate)return!1;try{return await s.downloadUpdate(r),!0}catch(t){return console.warn("Failed to download update",t),!1}},mu=async()=>{const r=Ts();if(!r||!r.restartToUpdate)return!1;try{return await r.restartToUpdate(),!0}catch(s){return console.warn("Failed to restart for update",s),!1}},fu="/api",pu=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,hu=r=>{const s=typeof r=="string"&&r.trim().length>0?r.trim():"/api";if(pu.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}},gu=()=>{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},Dr=r=>r.replace(/\\/g,"/"),Tn=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_RUNTIME_APIS__;return r&&r.runtime?.isDesktop&&r.files?r.files:null};class xu{client;baseUrl;sseAbortController=null;currentDirectory=void 0;constructor(s=fu){const n=gu()||s;this.baseUrl=hu(n),this.client=hc({baseUrl:this.baseUrl})}normalizeCandidatePath(s){if(typeof s!="string")return null;const t=s.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(s){const t=s.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],c=s.slice(a.length+(s.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[0]}:{homeDirectory:a,username:void 0}}const n=s.startsWith("/"),o=s.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(s){this.currentDirectory=s}getDirectory(){return this.currentDirectory}async withDirectory(s,t){if(s==null)return t();const n=this.currentDirectory;this.currentDirectory=s;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const s=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&s.add(a)};try{const a=(await this.client.path.get({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!s.size)try{const o=await this.client.project.current({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!s.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!s.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!s.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(s);return this.deriveHomeDirectory(n)}async listSessions(){const s=await this.client.session.list({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});return Array.isArray(s.data)?s.data:[]}async createSession(s){const t=await this.client.session.create({query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{parentID:s?.parentID,title:s?.title}});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(s){const t=await this.client.session.get({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(s){return(await this.client.session.delete({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||!1}async updateSession(s,t){const n=await this.client.session.update({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{title:t}});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(s){return(await this.client.session.messages({path:{id:s},query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}async sendMessage(s){const t=Date.now(),n=s.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(s.prefaceText&&s.prefaceText.trim()&&o.push({type:"text",text:s.prefaceText}),s.text&&s.text.trim()){const a={type:"text",text:s.text};o.push(a)}if(s.files&&s.files.length>0&&s.files.forEach(a=>{const i={type:"file",mime:a.mime,filename:a.filename,url:a.url};o.push(i)}),s.agentMentions&&s.agentMentions.length>0){const[a]=s.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({path:{id:s.id},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{model:{providerID:s.providerID,modelID:s.modelID},agent:s.agent,parts:o}}),n}async abortSession(s){return!!(await this.client.session.abort({path:{id:s},throwOnError:!0})).data}async getSessionStatus(){try{const s=this.baseUrl.replace(/\/$/,""),t=new URL(`${s}/session/status`);this.currentDirectory&&this.currentDirectory.length>0&&t.searchParams.set("directory",this.currentDirectory);const n=await fetch(t.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!n.ok)return{};const o=await n.json().catch(()=>null);return!o||typeof o!="object"?{}:o}catch{return{}}}async respondToPermission(s,t,n){return(await this.client.postSessionIdPermissionsPermissionId({path:{id:s,permissionID:t},query:this.currentDirectory?{directory:this.currentDirectory}:void 0,body:{response:n}})).data||!1}async getConfig(){const s=await this.client.config.get();if(!s.data)throw new Error("Failed to get config");return s.data}async updateConfig(s){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(s){const t=await this.getConfig(),n=s(t);return await this.updateConfig(n)}async getProviders(){const s=await this.client.config.providers({query:this.currentDirectory?{directory:this.currentDirectory}:void 0});if(!s.data)throw new Error("Failed to get providers");return s.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents({query:this.currentDirectory?{directory:this.currentDirectory}:void 0})).data||[]}catch{return[]}}subscribeToEvents(s,t,n,o){this.sseAbortController&&this.sseAbortController.abort();const a=new AbortController;return this.sseAbortController=a,console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const i=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",i);const c=async d=>{try{const m=await this.client.event.subscribe({query:i?{directory:i}:void 0,signal:a.signal,sseMaxRetryAttempts:2,sseDefaultRetryDelay:500,sseMaxRetryDelay:8e3,onSseError:f=>{f instanceof Error&&f.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",f),t&&!a.signal.aborted&&t(f))},onSseEvent:f=>{if(!a.signal.aborted){const u=f.data;u&&typeof u=="object"&&s(u)}}});n&&!a.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const f of m.stream)if(a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(m){if(m?.name==="AbortError"||a.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",m),t&&t(m);const f=Math.min(500*Math.pow(2,d),8e3);await new Promise(u=>setTimeout(u,f)),a.signal.aborted||await c(d+1)}};try{await c(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortController===a&&(this.sseAbortController=null)}})(),()=>{this.sseAbortController===a&&(this.sseAbortController=null),a.abort()}}async readFile(s){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:s,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${s}
|
|
3
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=Tn();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=Tn();if(t)try{const n=await t.listDirectory(s||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:Dr(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=Tn(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?Dr(o):null;if(n)try{const f=await n.search({directory:o||"",query:s,maxResults:t?.limit});return Array.isArray(f)?f.map(u=>{const p=Dr(u.path),h=p.split("/").filter(Boolean).pop()||p,g=u.preview&&u.preview.length>0&&typeof u.preview[0]=="string"?Dr(u.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||h;return{name:h,path:p,relativePath:g,extension:h.includes(".")?h.split(".").pop()?.toLowerCase():void 0}}):[]}catch(f){throw console.error("Failed to search files:",f),f}const i=new URLSearchParams;o&&o.length>0&&i.set("directory",o),typeof s=="string"&&i.set("q",s),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&i.set("limit",String(t.limit));const c=`${this.baseUrl}/fs/search${i.toString()?`?${i.toString()}`:""}`,d=await fetch(c,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const f=await d.json().catch(()=>({})),u=typeof f.error=="string"?f.error:"Failed to search files";throw new Error(u)}const m=await d.json();return!m||!Array.isArray(m.files)?[]:m.files}async getFilesystemHome(){const s=await Pi();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 Ne=new xu,oo=new Set;function Io(r){return oo.add(r),()=>{oo.delete(r)}}function fs(r,s){const t=Array.isArray(r)?r:[r],n=Array.from(new Set(t));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:s?.source,timestamp:Date.now()};for(const a of oo)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 on(r,s){return r.scopes.includes("all")||r.scopes.includes(s)}const yu="https://models.dev/api.json",bu="/api/openchamber/models-metadata",wu=r=>r?.toLowerCase?.()??"",vu=r=>r==="primary"||r==="all"||r===void 0||r===null,Nr=r=>typeof r=="object"&&r!==null,an=r=>Array.isArray(r)&&r.every(s=>typeof s=="string"),ju=r=>{if(!Nr(r))return!1;const s=r;if(s.modalities){const{input:t,output:n}=s.modalities;if(t&&!an(t)||n&&!an(n))return!1}return!0},Su=r=>{if(!Nr(r))return!1;const s=r;return s.models===void 0||Nr(s.models)},Fi=(r,s)=>{const t=wu(r);return!t||!s?"":`${t}/${s}`},Nu=r=>{const s=new Map;if(!Nr(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||!Nr(a)))for(const[i,c]of Object.entries(a)){if(!ju(c))continue;const d=typeof i=="string"&&i.length>0?i:c.id;if(!d||typeof d!="string"||d.length===0)continue;const m={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:an(c.modalities.input)?c.modalities.input:void 0,output:an(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=Fi(o,d);f&&s.set(f,m)}}return s},ku=async()=>{if(typeof fetch!="function")return new Map;const r=[bu,yu];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 Nu(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},Cu=r=>new Promise(s=>setTimeout(s,r)),gt=Tt()(Pt(rs((r,s)=>({providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,loadProviders:async()=>{try{const t=ku(),n=await Ne.getProviders(),o=Array.isArray(n?.providers)?n.providers:[],a=n?.default||{},i=o.map(u=>{const p=u.models??{},h=Object.keys(p).map(g=>p[g]);return{...u,models:h}}),c=a.provider||i[0]?.id||"",d=i.find(u=>u.id===c),m=a.model||d?.models?.[0]?.id||"";r({providers:i,defaultProviders:a,currentProviderId:c,currentModelId:m});const f=await t;f.size>0&&r({modelsMetadata:f})}catch(t){console.error("Failed to load providers:",t),r({providers:[],defaultProviders:{},currentProviderId:"",currentModelId:""})}},setProvider:t=>{const{providers:n}=s(),o=n.find(a=>a.id===t);if(o){const i=o.models[0]?.id||"";r({currentProviderId:t,currentModelId:i})}},setModel:t=>{r({currentModelId:t})},saveAgentModelSelection:(t,n,o)=>{r(a=>({agentModelSelections:{...a.agentModelSelections,[t]:{providerId:n,modelId:o}}}))},getAgentModelSelection:t=>{const{agentModelSelections:n}=s();return n[t]||null},loadAgents:async()=>{const t=s().agents;let n=null;for(let o=0;o<3;o++)try{const a=await Ne.listAgents(),i=Array.isArray(a)?a:[];r({agents:i});const{providers:c}=s();if(i.length===0)return r({currentAgentName:void 0}),!0;const d=i.filter(u=>vu(u.mode)),f=d.find(u=>u.name==="build")||d[0]||i[0];if(r({currentAgentName:f.name}),f?.model?.providerID&&f?.model?.modelID){const u=c.find(p=>p.id===f.model.providerID);u&&u.models.find(h=>h.id===f.model.modelID)&&r({currentProviderId:f.model.providerID,currentModelId:f.model.modelID})}return!0}catch(a){n=a;const i=200*(o+1);await new Promise(c=>setTimeout(c,i))}return console.error("Failed to load agents:",n),r({agents:t}),!1},setAgent:t=>{const{agents:n,providers:o}=s();if(r({currentAgentName:t}),t&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const i=a.getState(),{currentSessionId:c,isOpenChamberCreatedSession:d,initializeNewOpenChamberSession:m,getAgentModelForSession:f}=i;c&&a.setState(u=>{const p=new Map(u.currentAgentContext);return p.set(c,t),{currentAgentContext:p}}),c&&d(c)&&(f(c,t)||m(c,n))}}if(t&&typeof window<"u"){const a=window.__zustand_session_store__;if(a){const{currentSessionId:c,getAgentModelForSession:d}=a.getState();if(c&&d(c,t))return}const i=n.find(c=>c.name===t);if(i?.model?.providerID&&i?.model?.modelID){const c=o.find(d=>d.id===i.model.providerID);c&&c.models.find(m=>m.id===i.model.modelID)&&r({currentProviderId:i.model.providerID,currentModelId:i.model.modelID})}}},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Ne.checkHealth();return r({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await Cu(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 Ne.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=Fi(t,n);if(!o)return;const{modelsMetadata:a}=s();return a.get(o)}}),{name:"config-store",storage:ns(()=>zt()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=gt);let ta=null;ta||(ta=Io(async r=>{const s=[];if(on(r,"agents")){const{loadAgents:t}=gt.getState();s.push(t().then(()=>{}))}if(on(r,"providers")){const{loadProviders:t}=gt.getState();s.push(t())}s.length>0&&await Promise.all(s)}));const Mt={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Mu=180,Rt=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function Po(r){const s=Rt();return s?s.checkIsGitRepository(r):Bd(r)}async function Au(r){const s=Rt();return s?s.getGitStatus(r):Wd(r)}async function Du(r,s){const t=Rt();return t?t.deleteGitBranch(r,s):Vd(r,s)}async function Eu(r,s){const t=Rt();return t?t.deleteRemoteBranch(r,s):Gd(r,s)}async function Tu(r){const s=Rt();return s?s.listGitWorktrees(r):Hd(r)}async function Iu(r,s){const t=Rt();return t?t.addGitWorktree(r,s):eu(r,s)}async function _i(r,s){const t=Rt();return t?t.removeGitWorktree(r,s):Ud(r,s)}async function Pu(r){const s=Rt();return s?s.ensureOpenChamberIgnored(r):Zd(r)}async function Ru(r,s={}){const t=Rt();return t?t.gitPush(r,s):Qd(r,s)}async function Fu(){const r=Rt();return r?r.getGitIdentities():Jd()}async function _u(r){const s=Rt();return s?s.createGitIdentity(r):Yd(r)}async function Lu(r,s){const t=Rt();return t?t.updateGitIdentity(r,s):Kd(r,s)}async function Ou(r){const s=Rt();return s?s.deleteGitIdentity(r):qd(r)}async function $u(r){const s=Rt();return s?s.getCurrentGitIdentity(r):Xd(r)}const zu=".openchamber",hs=r=>{if(!r)return"";const s=r.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},sa=(r,s)=>{const t=hs(r),n=s.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Li=r=>r?r.startsWith("refs/heads/")?r.substring(11):r.startsWith("heads/")?r.substring(6):r.startsWith("refs/")?r.substring(5):r:"",Bu=async r=>{try{await Ne.createDirectory(r)}catch(s){if(s instanceof Error&&/exist/i.test(s.message))return;throw s}};async function Hu(r,s){const t=hs(r),n=sa(t,zu);return await Bu(n),sa(n,s)}async function Wu(r){const{projectDirectory:s,worktreeSlug:t,branch:n,createBranch:o}=r,a=hs(s),i=await Hu(a,t);return await Iu(a,{path:i,branch:n,createBranch:!!o}),{path:i,branch:n,label:Li(n),projectDirectory:a,relativePath:i.startsWith(`${a}/`)?i.slice(a.length+1):i}}async function ra(r){const{projectDirectory:s,path:t,force:n}=r,o=hs(s);await _i(o,{path:t,force:n})}async function Uu(r){const{projectDirectory:s,path:t,branch:n,force:o,deleteRemote:a,remote:i}=r,c=hs(s),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await _i(c,{path:t,force:o}),d&&(await Du(c,{branch:d,force:!0}),a))try{await Eu(c,{branch:d,remote:i})}catch(m){console.warn("Failed to delete remote branch during worktree archive:",m)}}async function ln(r){const s=hs(r);return Tu(s)}async function qr(r){const s=hs(r),t=await Au(s);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function cn(r,s){const t=hs(r),n=hs(s.worktree);return{path:n,branch:s.branch??"",label:Li(s.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}const na=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},Vu=r=>!r||typeof r!="object"?null:{showReasoningTraces:r.showReasoningTraces},Gu=r=>{const s=Le.getState();typeof r.showReasoningTraces=="boolean"&&s.setShowReasoningTraces(r.showReasoningTraces)},qu=async()=>{if(typeof window>"u")return null;if(_t()){const s=window.opencodeAppearance;if(!s||typeof s.load!="function")return null;try{const t=await s.load();return na(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=Vu(s);return na(t)}catch(s){return console.warn("Failed to parse stored appearance preferences:",s),null}};let Oi=null;const oa=r=>{Oi=r},$i=()=>Oi,Kr=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"))},zi=()=>{const r=Le.persist;if(r&&typeof r=="object")return r},Bi=()=>$i()?.settings??null,Yr=r=>{const s=Le.getState();typeof r.showReasoningTraces=="boolean"&&r.showReasoningTraces!==s.showReasoningTraces&&s.setShowReasoningTraces(r.showReasoningTraces)},aa=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},Ku=async()=>{const r=Bi();if(r)try{const s=await r.load();return aa(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 aa(t)}catch(s){return console.warn("Failed to load shared settings from server:",s),null}},Hi=async()=>{if(typeof window>"u")return;const r=zi(),s=t=>{Kr(t);const n=()=>Yr(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=_t()?await Ri():await Ku();t&&s(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},cs=async r=>{if(typeof window>"u")return;if(_t()){try{const t=await au(r);t&&(Kr(t),Yr(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const s=Bi();if(s)try{const t=await s.save(r);t&&(Kr(t),Yr(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&&(Kr(n),Yr(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Wi=async()=>{if(typeof window>"u")return;const r=zi();try{const s=await qu();if(!s)return;const t=()=>Gu(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)}},Ro="Updating OpenCode configuration...";let ts=0,As=Ro;const ao=new Set;function dn(){const r={isUpdating:ts>0,message:As};ao.forEach(s=>s(r))}function Cs(r){ts+=1,ts===1?(As=r||Ro,dn()):r&&(As=r,dn())}function Ut(){ts!==0&&(ts-=1,ts===0&&(As=Ro,dn()))}function Kt(r){As===r&&ts>0||(As=r,ts>0&&dn())}function Yu(r){return ao.add(r),r({isUpdating:ts>0,message:As}),()=>{ao.delete(r)}}function Xu(){return{isUpdating:ts>0,message:As}}const hr="useAgentsStore",un=r=>new Promise(s=>setTimeout(s,r)),Ju=2e4,ia=300,la=4,Zu=800,Qu=200,em=2e3,sr=Tt()(Pt(rs((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 Ne.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=>{Cs("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.tools&&Object.keys(t.tools).length>0&&(o.tools=t.tools),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),console.log("[AgentsStore] Agent config to save:",o);const a=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const m=i?.error||"Failed to create agent";throw new Error(m)}if(console.log("[AgentsStore] Agent created successfully"),i?.requiresReload??!0)return n=!0,await Xs({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadAgents();return d&&fs("agents",{source:hr}),d}catch(o){return console.error("[AgentsStore] Failed to create agent:",o),!1}finally{n||Ut()}},updateAgent:async(t,n)=>{Cs("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 Xs({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const m=await s().loadAgents();return m&&fs("agents",{source:hr}),m}catch(a){return console.error("[AgentsStore] Failed to update agent:",a),!1}finally{o||Ut()}},deleteAgent:async t=>{Cs("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 Xs({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadAgents();return c&&fs("agents",{source:hr}),s().selectedAgentName===t&&r({selectedAgentName:null}),c}catch(o){return console.error("Failed to delete agent:",o),!1}finally{n||Ut()}},getAgentByName:t=>{const{agents:n}=s();return n.find(o=>o.name===t)}}),{name:"agents-store",storage:ns(()=>zt()),partialize:r=>({selectedAgentName:r.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=sr);async function tm(r){const s=typeof r=="number"&&r>0?Math.min(r,ia):0;s>0&&await un(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Ju;){n+=1,Kt(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ne.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=la&&a<1200?ia:Math.min(Zu+Math.max(0,n-la)*Qu,em);await un(i)}throw o||new Error("OpenCode did not become ready in time")}async function Xs(r={}){const{message:s,delayMs:t}=r;try{Kt(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 tm(t),Kt("Refreshing providers and agents…");const n=gt.getState(),o=sr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadAgents().then(()=>{})]),fs("agents",{source:hr})}catch(n){console.error("[AgentsStore] Failed to refresh configuration after OpenCode restart:",n),Kt("OpenCode reload failed. Please retry refreshing configuration manually."),await un(1500)}finally{Ut()}}async function sm(r){await Xs(r)}async function rm(r){Cs("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 Xs({message:t.message,delayMs:t.reloadDelayMs}):await Xs(r)}catch(s){throw console.error("[reloadOpenCodeConfiguration] Failed:",s),Kt("Failed to reload configuration. Please try again."),await un(2e3),Ut(),s}}let ca=null;ca||(ca=Io(r=>{if(r.source!==hr&&on(r,"agents")){const{loadAgents:s}=sr.getState();s()}}));const gr="useCommandsStore",io=r=>new Promise(s=>setTimeout(s,r)),nm=2e4,da=300,ua=4,om=800,am=200,im=2e3,rr=Tt()(Pt(rs((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 Ne.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=>{Cs("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),console.log("[CommandsStore] Command config to save:",o);const a=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),i=await a.json().catch(()=>null);if(!a.ok){const m=i?.error||"Failed to create command";throw new Error(m)}if(console.log("[CommandsStore] Command created successfully"),i?.requiresReload??!0)return n=!0,await In({message:i?.message,delayMs:i?.reloadDelayMs}),!0;const d=await s().loadCommands();return d&&fs("commands",{source:gr}),d}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Ut()}},updateCommand:async(t,n)=>{Cs("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 In({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const m=await s().loadCommands();return m&&fs("commands",{source:gr}),m}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Ut()}},deleteCommand:async t=>{Cs("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 In({message:a?.message,delayMs:a?.reloadDelayMs}),!0;const c=await s().loadCommands();return c&&fs("commands",{source:gr}),s().selectedCommandName===t&&r({selectedCommandName:null}),c}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Ut()}},getCommandByName:t=>{const{commands:n}=s();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:ns(()=>zt()),partialize:r=>({selectedCommandName:r.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=rr);async function lm(r){const s=typeof r=="number"&&r>0?Math.min(r,da):0;s>0&&await io(s);const t=Date.now();let n=0,o=null;for(;Date.now()-t<nm;){n+=1,Kt(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ne.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,i=n<=ua&&a<1200?da:Math.min(om+Math.max(0,n-ua)*am,im);await io(i)}throw o||new Error("OpenCode did not become ready in time")}async function In(r={}){const{message:s,delayMs:t}=r;try{Kt(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 lm(t),Kt("Refreshing providers and commands…");const n=gt.getState(),o=rr.getState();await Promise.all([n.loadProviders().then(()=>{}),o.loadCommands().then(()=>{})]),fs("commands",{source:gr})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),Kt("OpenCode reload failed. Please retry refreshing configuration manually."),await io(1500)}finally{Ut()}}let ma=null;ma||(ma=Io(r=>{if(r.source!==gr&&on(r,"commands")){const{loadCommands:s}=rr.getState();s()}}));const cm=3e4,dm=40,um=60,mm=(r,s,t)=>{const n=r.trim(),o=s.trim().toLowerCase();return`${n}::${o}::${t}`},Fo=Tt()(Pt((r,s)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=um){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",c=mm(a,i,o),d=Date.now(),m=s().cache[c];if(m&&d-m.timestamp<cm)return m.files;const f=s().inFlight[c];if(f)return f;const u=Ne.searchFiles(i,{directory:a,limit:o}).then(p=>(r(h=>{const g={...h.cache,[c]:{files:p,timestamp:Date.now()}},x=h.cacheKeys.filter(v=>v!==c);for(x.push(c);x.length>dm;){const v=x.shift();v&&delete g[v]}return{cache:g,cacheKeys:x}}),p)).finally(()=>{r(p=>{const h={...p.inFlight};return delete h[c],{inFlight:h}})});return r(p=>({inFlight:{...p.inFlight,[c]:u}})),u},invalidateDirectory(t){if(!t||t.trim().length===0){r({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;r(a=>{const i={...a.cache},c=a.cacheKeys.filter(f=>f.startsWith(o)?(delete i[f],!1):!0),d=Object.entries(a.inFlight).filter(([f])=>!f.startsWith(o)),m=Object.fromEntries(d);return{cache:i,cacheKeys:c,inFlight:m}})}}),{name:"file-search-store"}));var fm={};let us=null;const Qt=zt(),fa=Qt.getItem("lastDirectory"),pm=typeof fa=="string"&&fa.length>0,Er=(r,s)=>((s?.showOverlay??!0)&&Cs("Switching project directory…"),Ne.setOpenCodeWorkingDirectory(r).catch(n=>{throw console.warn("Failed to synchronize OpenCode working directory:",n),n})),Tr=(r,s,t)=>{const{showOverlay:n}=s,o=()=>{try{pe.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&&(Kt("Failed to switch directory. Please try again."),await new Promise(c=>setTimeout(c,1500)),Ut()),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 sm({message:"Refreshing OpenCode configuration…"});try{await rr.getState().loadCommands();try{fs("commands",{source:"useCommandsStore"})}catch(i){console.warn("Failed to emit command configuration change:",i)}}catch(i){console.warn("Failed to reload commands after directory change:",i)}}else n&&Ut()}catch(i){console.error("Failed to refresh configuration after directory change:",i),n&&(Kt("Failed to refresh configuration. Please reload manually."),await new Promise(c=>setTimeout(c,1500)),Ut())}finally{t?.(a),o()}})()},Ir=r=>{try{Fo.getState().invalidateDirectory(r)}catch(s){console.warn("Failed to invalidate file search cache:",s)}},mn=()=>{if(typeof window<"u"){const s=Qt.getItem("lastDirectory");if(s)return s;if(us)return us;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 us=t,Qt.setItem("homeDirectory",t),t;const n=Qt.getItem("homeDirectory");if(n)return us=n,n}const r=typeof process<"u"&&fm?.HOME;return r||process?.cwd?.()||"/"},hm=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},gm=r=>(us=r,typeof window<"u"&&Qt.setItem("homeDirectory",r),cs({homeDirectory:r}),r),Ui=async()=>{const r=n=>{const o=hm(n);return o?gm(o):null};try{const n=await Ne.getFilesystemHome(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Ne.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 Pi(),o=r(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const s=mn(),t=r(s);return t||s},zs=mn();zs&&Ne.setDirectory(zs);const xm=!!(zs&&zs!=="/"),ht=Tt()(Pt((r,s)=>({currentDirectory:zs,directoryHistory:[zs],historyIndex:0,homeDirectory:zs,hasPersistedDirectory:pm,isHomeReady:xm,isSwitchingDirectory:!1,setDirectory:(t,n)=>{console.log("[DirectoryStore] setDirectory called with path:",t);const o=n?.showOverlay??!0;Ne.setDirectory(t),Ir();const a=Er(t,{showOverlay:o});console.log("[DirectoryStore] notifyOpenCodeWorkingDirectory initiated"),r(i=>{const c=[...i.directoryHistory.slice(0,i.historyIndex+1),t];return Qt.setItem("lastDirectory",t),cs({lastDirectory:t}),{currentDirectory:t,directoryHistory:c,historyIndex:c.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}}),Tr(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];Ne.setDirectory(o),Ir();const a=Er(o);Qt.setItem("lastDirectory",o),cs({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Tr(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];Ne.setDirectory(o),Ir();const a=Er(o);Qt.setItem("lastDirectory",o),cs({lastDirectory:o}),r({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!0}),Tr(a,{showOverlay:!0},()=>{r(i=>i.currentDirectory!==o?{}:i.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=s(),o=us||s().homeDirectory||mn();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const c=us||mn();n(c)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=us||s().homeDirectory||await Ui();s().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=s(),o=t;us=o;const a=n.homeDirectory!==o,i=Qt.getItem("lastDirectory"),c=typeof i=="string"&&i.length>0,d=!c&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||r({isHomeReady:!0});return}const m=typeof o=="string"&&o!==""&&o!=="/",f={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:m};if(d&&(f.currentDirectory=o,f.directoryHistory=[o],f.historyIndex=0,f.isSwitchingDirectory=!0),r(()=>f),d&&m){Ne.setDirectory(o),Ir(),Qt.setItem("lastDirectory",o),cs({lastDirectory:o});const u=Er(o,{showOverlay:!1});Tr(u,{showOverlay:!1},()=>{r(p=>p.currentDirectory!==o?{}:p.isSwitchingDirectory?{isSwitchingDirectory:!1}:{})})}cs({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Ui().then(r=>{ht.getState().synchronizeHomeDirectory(r)});const Vi=zt(),Gi="oc.sessionSelectionByDirectory",pa=".openchamber",ym=()=>{try{const r=Vi.getItem(Gi);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 Xr=null;const _o=()=>(Xr||(Xr=ym()),Xr),qi=r=>{Xr=r;try{Vi.setItem(Gi,JSON.stringify(r))}catch{}},Ki=r=>{if(!r)return null;const t=_o()[r];return typeof t=="string"?t:null},Ps=(r,s)=>{if(!r)return;const t={..._o()};s?t[r]=s:delete t[r],qi(t)},bm=(r,s)=>{if(!r)return;const t=Ki(r);if(!t)return;if(!new Set(s).has(t)){const o={..._o()};delete o[r],qi(o)}},ha=async(r,s)=>{const t=r.status??await qr(r.path).catch(()=>{});await Uu({projectDirectory:r.projectDirectory,path:r.path,branch:r.branch,force:!!t?.isDirty,deleteRemote:!!s?.deleteRemoteBranch,remote:s?.remoteName})},kt=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},Vs=(r,s)=>{const t=r.find(n=>n.id===s);return t?kt(t.directory??null):null},wm=async(r,s,t)=>{const n=kt(s);if(!n||r.length===0)return null;const o=r.map(m=>({id:m.id,directory:kt(m.directory)})).filter(m=>!!m.directory);if(o.length===0)return null;let a;try{a=await ln(n)}catch(m){return console.debug("Failed to hydrate worktree metadata from git worktree list:",m),null}if(!Array.isArray(a)||a.length===0){let m=!1;const f=new Map(t);return o.forEach(({id:u})=>{f.delete(u)&&(m=!0)}),m?f:null}const i=new Map;a.forEach(m=>{const f=cn(n,m),u=kt(f.path)??f.path;u!==n&&i.set(u,f)});let c=!1;const d=new Map(t);return o.forEach(({id:m,directory:f})=>{const u=i.get(f);if(!u){d.delete(m)&&(c=!0);return}const p=d.get(m);(!p||p.path!==u.path||p.branch!==u.branch||p.label!==u.label)&&(d.set(m,u),c=!0)}),c?d:null},Xe=Tt()(Pt(rs((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=ht.getState().currentDirectory??Ne.getDirectory()??null,o=Ne.getApiClient(),a=async D=>{const k=await o.session.list({query:D?{directory:D}:void 0});return Array.isArray(k.data)?k.data:[]},i=kt(n),c=i?await Po(i).catch(()=>!1):!1,d=await a(i||null),m=[];let f=[];if(n&&c&&i){const D=`${i}/${pa}`;try{const k=new Set;D&&(await Ne.listLocalDirectory(D)).filter(P=>P.isDirectory).forEach(P=>{const F=/^([A-Za-z]:)?\//.test(P.path)?P.path:`${D}/${P.name}`;k.add(kt(F)??F)});const M=await ln(i);Array.isArray(M)&&(f=M.map(E=>cn(i,E)).filter(E=>E.path.includes(`/${pa}/`)),f.forEach(E=>k.add(E.path))),k.size>0&&(await Promise.allSettled(Array.from(k).map(P=>a(P)))).forEach(P=>{P.status==="fulfilled"&&Array.isArray(P.value)&&m.push(...P.value)})}catch{f=[]}}const u=new Set;i&&u.add(i),f.forEach(D=>{const k=kt(D.path);k&&u.add(k)});const p=[...d,...m].filter(D=>{const k=D.directory??i??null,M=kt(k);return M?u.has(M):!1}),h=s(),g=h.lastLoadedDirectory??null,x=n!==g;let v=[...p],j=h.currentSessionId;const N=D=>{v=[D,...v.filter(k=>k.id!==D.id)]};if(x)j=v.length>0?v[0].id:null;else if(j){if(!v.some(k=>k.id===j)){const k=h.sessions.find(M=>M.id===j);if(k)N(k);else try{const M=await Ne.getSession(j);N(M)}catch{j=v.length>0?v[0].id:null}}}else j=v.length>0?v[0].id:null;const w=v.reduce((D,k)=>(D.some(M=>M.id===k.id)||D.push(k),D),[]);j&&!w.some(D=>D.id===j)&&(j=w.length>0?w[0].id:null);const y=new Set(w.map(D=>D.id));if(n){bm(n,y);const D=Ki(n);D&&y.has(D)&&(j=D)}let S=null;try{S=await wm(w,n,h.worktreeMetadata)}catch(D){console.debug("Failed to refresh worktree metadata during session load:",D)}const b=(()=>{const D=S??h.worktreeMetadata;if(!x||!i)return D;const k=new Map;return D.forEach((M,E)=>{kt(M.projectDirectory)===i&&k.set(E,M)}),k})(),C=(()=>{if(!j)return i??null;const D=b.get(j)?.path;if(D)return kt(D)??D;const k=Vs(w,j);return k||(i??null)})();try{Ne.setDirectory(C??void 0)}catch(D){console.warn("Failed to sync OpenCode directory after session load:",D)}r({sessions:w,currentSessionId:j,lastLoadedDirectory:n,isLoading:!1,worktreeMetadata:b,availableWorktrees:f}),Ps(C??n,j)}catch(t){r({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,n,o)=>{r({error:null});const a=ht.getState(),i=kt(a.currentDirectory),c=kt(n??Ne.getDirectory()??i),d=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=s(),f=new Set(m.sessions.map(g=>g.id)),u={id:d,title:t||"New session",parentID:o??void 0,directory:c??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(r(g=>({sessions:[u,...g.sessions],currentSessionId:d,webUICreatedSessions:new Set([...g.webUICreatedSessions,d]),isLoading:!1})),c)try{Ne.setDirectory(c)}catch(g){console.warn("Failed to sync OpenCode directory after session creation:",g)}const p=g=>{r(x=>({sessions:x.sessions.map(j=>j.id===d?g:j),currentSessionId:g.id,webUICreatedSessions:new Set([...Array.from(x.webUICreatedSessions).filter(j=>j!==d),g.id])})),Ps(c??null,g.id)},h=async()=>{const g=Ne.getApiClient(),x=20;for(let v=0;v<x;v+=1){try{const j=await g.session.list({query:c?{directory:c}:void 0}),w=(Array.isArray(j.data)?j.data:[]).find(y=>!(f.has(y.id)||t&&y.title&&y.title!==t));if(w)return w}catch(j){console.debug("Session poll attempt failed:",j)}await new Promise(j=>setTimeout(j,2e3))}return null};try{const g=()=>Ne.createSession({title:t,parentID:o??void 0});let x=null;try{x=c?await Ne.withDirectory(c,g):await g()}catch(v){console.warn("Direct session create failed or timed out, falling back to polling:",v)}return x||(x=await h()),x?(p(x),x):(r(v=>({sessions:v.sessions.filter(j=>j.id!==d),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(v.webUICreatedSessions).filter(j=>j!==d)),isLoading:!1,error:"Failed to create session"})),null)}catch(g){return r(x=>({sessions:x.sessions.filter(v=>v.id!==d),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(x.webUICreatedSessions).filter(v=>v!==d)),isLoading:!1,error:g instanceof Error?g.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{r({isLoading:!0,error:null});const o=s().worktreeMetadata.get(t),a=Vs(s().sessions,t),i=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await ha(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Ne.deleteSession(t);if(!(i?await Ne.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(v=>v.id!==t);f=p.currentSessionId===t?null:p.currentSessionId;const g=new Map(p.worktreeMetadata);g.delete(t);const x=n?.archiveWorktree&&o?p.availableWorktrees.filter(v=>kt(v.path)!==kt(o.path)):p.availableWorktrees;return{sessions:h,currentSessionId:f,isLoading:!1,worktreeMetadata:g,availableWorktrees:x}});const u=i??Ne.getDirectory()??null;return Ps(u,f),!0}catch(d){const m=d instanceof Error?d.message:"Failed to delete session";return r(c?f=>{const u=new Map(f.worktreeMetadata);return u.delete(t),{worktreeMetadata:u,error:m,isLoading:!1}}:{error:m,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(x=>typeof x=="string"&&x.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};r({isLoading:!0,error:null});const a=[],i=[],c=new Set,d=[],m=new Set;for(const x of o)try{const v=s().worktreeMetadata.get(x),j=Vs(s().sessions,x),N=v?.path??j;v&&n?.archiveWorktree&&!m.has(v.path)&&(await ha(v,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c.add(x),d.push({path:v.path,projectDirectory:v.projectDirectory}),m.add(v.path));const w=()=>Ne.deleteSession(x);(N?await Ne.withDirectory(N,w):await w())?(a.push(x),v?.path&&!d.some(S=>S.path===v.path)&&d.push({path:v.path,projectDirectory:v.projectDirectory})):i.push(x)}catch{i.push(x)}const f=ht.getState();d.forEach(({path:x,projectDirectory:v})=>{f.currentDirectory===x&&f.setDirectory(v,{showOverlay:!1})});const u=new Set(a),p=i.length>0?i.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let h=null;r(x=>{const v=x.sessions.filter(y=>!u.has(y.id));x.currentSessionId&&u.has(x.currentSessionId)?h=v.length>0?v[0].id:null:h=x.currentSessionId;const j=new Map(x.worktreeMetadata);for(const y of u)j.delete(y);for(const y of c)j.delete(y);const N=new Set(d.map(y=>kt(y.path)).filter(y=>!!y)),w=N.size>0?x.availableWorktrees.filter(y=>!N.has(kt(y.path)??y.path)):x.availableWorktrees;return{sessions:v,currentSessionId:h,isLoading:!1,worktreeMetadata:j,availableWorktrees:w,error:p}});const g=Ne.getDirectory()??null;return Ps(g,h),{deletedIds:a,failedIds:i}},updateSessionTitle:async(t,n)=>{try{const o=Vs(s().sessions,t),a=s().worktreeMetadata.get(t),i=()=>Ne.updateSession(t,n),c=a?.path??o,d=c?await Ne.withDirectory(c,i):await i();r(m=>({sessions:m.sessions.map(f=>f.id===t?d:f)}))}catch(o){r({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=Vs(s().sessions,t),o=Ne.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const m=n??Ne.getDirectory();return o.session.share({path:{id:t},query:m?{directory:m}:void 0})},d=i?await Ne.withDirectory(i,c):await c();return d.data?(r(m=>({sessions:m.sessions.map(f=>f.id===t?d.data:f)})),d.data):null}catch(n){return r({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=Vs(s().sessions,t),o=Ne.getApiClient(),i=s().worktreeMetadata.get(t)?.path??n,c=async()=>{const m=n??Ne.getDirectory();return o.session.unshare({path:{id:t},query:m?{directory:m}:void 0})},d=i?await Ne.withDirectory(i,c):await c();return d.data?(r(m=>({sessions:m.sessions.map(f=>f.id===t?d.data:f)})),d.data):null}catch(n){return r({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{r({currentSessionId:t,error:null});const n=Ne.getDirectory()??null;Ps(n,t)},clearError:()=>{r({error:null})},getSessionsByDirectory:()=>{const{sessions:t}=s();return t},applySessionMetadata:(t,n)=>{!t||!n||r(o=>{const a=o.sessions.findIndex(h=>h.id===t);if(a===-1)return o;const i=o.sessions[a],c=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,m=n.share===void 0?i.share:n.share||void 0,f={...i,...n,time:c,summary:d,share:m},u=f.title!==i.title||f.parentID!==i.parentID||f.directory!==i.directory||f.version!==i.version||f.projectID!==i.projectID||JSON.stringify(f.time)!==JSON.stringify(i.time)||JSON.stringify(f.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(f.share??null)!==JSON.stringify(i.share??null),p=[...o.sessions];return p[a]=u?f:i,u?{sessions:p}:o})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=s();return n.has(t)},markSessionAsOpenChamberCreated:t=>{r(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=s();n(t)},setWorktreeMetadata:(t,n)=>{t&&r(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return s().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=s().sessions,a=o.findIndex(m=>m.id===t);if(a===-1)return;const c=o[a].directory??null,d=n??void 0;c!==(d??null)&&(r(m=>{const f=[...m.sessions],u={...f[a]};return d!==void 0?u.directory=d:delete u.directory,f[a]=u,{sessions:f}}),c&&Ps(c,null),n&&Ps(n,t))},updateSession:t=>{r(n=>({sessions:n.sessions.map(o=>o.id===t.id?t:o)}))}}),{name:"session-store",storage:ns(()=>zt()),partialize:r=>({currentSessionId:r.currentSessionId,sessions:r.sessions,lastLoadedDirectory:r.lastLoadedDirectory,webUICreatedSessions:Array.from(r.webUICreatedSessions),worktreeMetadata:Array.from(r.worktreeMetadata.entries()),availableWorktrees:r.availableWorktrees}),merge:(r,s)=>{if(!(m=>typeof m=="object"&&m!==null)(r))return s;const n=Array.isArray(r.sessions)?r.sessions:s.sessions,o=typeof r.currentSessionId=="string"||r.currentSessionId===null?r.currentSessionId:s.currentSessionId,a=Array.isArray(r.webUICreatedSessions)?r.webUICreatedSessions:[],i=Array.isArray(r.worktreeMetadata)?r.worktreeMetadata:[],c=Array.isArray(r.availableWorktrees)?r.availableWorktrees:s.availableWorktrees,d=typeof r.lastLoadedDirectory=="string"?r.lastLoadedDirectory:s.lastLoadedDirectory??null;return{...s,...r,sessions:n,currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:c,lastLoadedDirectory:d}}}),{name:"session-store"})),Yi="This message comes from an AI assistant in another session. The user wants you to respond according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed. Always clearly state what you understand your task to be, and wait for the user's approval of your conclusions before taking any further actions.",Pn=r=>typeof r=="string"&&r.trim()===Yi.trim(),Rn=(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},ar=(r,s)=>{const t=Array.from(s);if(!t.some(a=>r.has(a)))return r;const o=new Map(r);return t.forEach(a=>{o.delete(a)}),o},ga=new Map,Xi=r=>{const s=ga.get(r);s&&(clearTimeout(s),ga.delete(r))},Rs=r=>{for(const s of r)Xi(s)},kr=r=>{if(!r)return"";if(typeof r=="string")return r;if(Array.isArray(r))return r.map(s=>kr(s)).join("");if(typeof r=="object"){if(typeof r.text=="string")return r.text;if(Array.isArray(r.content))return r.content.map(s=>kr(s)).join("")}return""},xr=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:xr(n)).join("");const t=kr(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||kr(o.delta)||""}return""}).join(""):"")},ir=(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=kr(r.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},xa=10*1024*1024,vm=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"}},Ns=Tt()(Pt(rs((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=xa;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=vm(t);!i.some(g=>c.startsWith(g)||c===g||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const m=new FileReader,f=await new Promise((g,x)=>{m.onload=()=>g(m.result),m.onerror=x,m.readAsDataURL(t)}),u=f.startsWith("data:")?f.replace(/^data:[^;]*/,`data:${c}`):f,p=g=>{const x=g.replace(/\\/g,"/").split("/");return x[x.length-1]||g},h={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:u,mimeType:c,filename:p(t.name),size:t.size,source:"local"};r(g=>({attachedFiles:[...g.attachedFiles,h]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=s();if(a.some(x=>x.serverPath===t&&x.source==="server")){console.log(`Server file "${n}" is already attached`);return}let c=o;if(!c)try{const x=Ne.getApiClient(),v=t.lastIndexOf("/"),j=v>0?t.substring(0,v):"/",N=v>0?t.substring(v+1):t,w=await x.file.read({query:{path:N,directory:j}});w.data&&"content"in w.data?c=w.data.content:c=""}catch(x){console.error("Failed to read server file:",x),c=`[File: ${n}]`}const d=new Blob([c||""],{type:"text/plain"});if(d.size>xa)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const m=new File([d],n,{type:"text/plain"}),u=new TextEncoder().encode(c||""),h=`data:text/plain;base64,${btoa(String.fromCharCode(...u))}`,g={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:m,dataUrl:h,mimeType:"text/plain",filename:n,size:d.size,source:"server",serverPath:t};r(x=>({attachedFiles:[...x.attachedFiles,g]}))},removeAttachedFile:t=>{r(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{r({attachedFiles:[]})}}),{name:"file-store",storage:ns(()=>zt()),partialize:r=>({attachedFiles:r.attachedFiles})}),{name:"file-store"}));let Fn=[],_n=null;const jm=50,Sm=3e4,Fs=new Map,Pr=new Map,Gs=new Map,Nm=10,fn=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<Nm?null:n},ya=(r,s)=>{const t=fn(r),n=fn(s);return!t||!n||t.length!==n.length?!0:t>n},km=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},Rr=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),ba=r=>Array.isArray(r)?r.some(s=>s?.type==="step-finish"&&s?.reason==="stop"):!1,wa=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??""}`}}},va=new Set,ja=(r=[],s=[])=>{if(!s.length)return[...r];const t=[...r],n=new Set(r.map(wa).filter(o=>!!o));return s.forEach(o=>{if(!o)return;const a=wa(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},Cm=(r,s)=>{let t=s,n=s?fn(s):null;for(const o of r){const a=o?.info?.id,i=fn(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Jt=(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},qs=(r,s,t)=>{if(r.get(s)===t)return r;const o=new Map(r);return o.set(s,t),o},Fr=(r,s)=>{const t=new Map(r);let n=!1;for(const o of s)t.delete(o)&&(n=!0);return n?t:r},Mm=(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},Sa=(r,s,t)=>r.streamingMessageIds.get(s)===t?!0:r.messageSessionIndex.get(t)===s&&r.messageStreamStates.has(t),Am=async r=>{if(r)try{const s=Xe.getState(),t=s.getWorktreeMetadata(r);if(t?.path)return t.path;const n=s.sessions.find(a=>a.id===r);return typeof n?.directory=="string"&&n.directory.length>0?n.directory:void 0}catch(s){console.warn("Failed to resolve session directory override:",s);return}},Ln=async(r,s)=>{const t=await Am(r);return t?Ne.withDirectory(t,s):s()},Qe=Tt()(Pt(rs((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=Mt.VIEWPORT_MESSAGES)=>{const o=await Ln(t,()=>Ne.getSessionMessages(t)),a=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=(a?o.filter(d=>{const m=d?.info?.id;return m?ya(m,a):!0}):o).slice(-n);r(d=>{const m=new Map(d.messages),f=d.messages.get(t)||[],u=new Map(f.filter(C=>typeof C.info?.id=="string").map(C=>[C.info.id,C])),h=c.map(C=>{const 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:[]).map(E=>{if(E?.type==="text"){const P=E.text??E.content??"";if(Pn(P))return{...E,synthetic:!0}}return E}),M=D?.id?u.get(D.id):void 0;if(M&&M.info.role==="assistant"){const E=Array.isArray(M.parts)?M.parts:[],P=Rr(E),W=Rr(k);if(ba(E)&&P>W){const O=ja(E,k);return{...C,info:D,parts:O}}}return{...C,info:D,parts:k}}),g=new Set(f.map(C=>C.info.id)),x=new Set(h.map(C=>C.info.id)),v=[];g.forEach(C=>{x.has(C)||v.push(C)}),m.set(t,h);const j=new Map(d.sessionMemoryState),N=d.sessionMemoryState.get(t);j.set(t,{viewportAnchor:h.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>c.length,trimmedHeadMaxId:N?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const w={messages:m,sessionMemoryState:j};Rs(v);const y=ar(d.messageStreamStates,v);if(y!==d.messageStreamStates&&(w.messageStreamStates=y),v.length>0){const C=d.streamingMessageIds.get(t);C&&v.includes(C)&&(w.streamingMessageIds=Jt(w.streamingMessageIds??d.streamingMessageIds,t,null))}if(v.length>0){const C=Fr(w.messageSessionIndex??d.messageSessionIndex,v);C!==(w.messageSessionIndex??d.messageSessionIndex)&&(w.messageSessionIndex=C)}if(v.length>0){const C=new Map(d.pendingAssistantParts);let D=!1;v.forEach(k=>{C.delete(k)&&(D=!0)}),D&&(w.pendingAssistantParts=C)}const S=w.messageSessionIndex??d.messageSessionIndex;let b=S;return h.forEach(C=>{const D=C?.info?.id;typeof D=="string"&&D.length>0&&(b=qs(b,D,t))}),b!==S&&(w.messageSessionIndex=b),w})},sendMessage:async(t,n,o,a,i,c,d)=>{if(!i)throw new Error("No session selected");const m=i;s().sessionAbortFlags.has(m)&&r(f=>{const u=new Map(f.sessionAbortFlags);return u.delete(m),{sessionAbortFlags:u}}),await Ln(m,async()=>{try{let f=t;if(t.startsWith("/")){const p=t.indexOf(" "),h=p===-1?t.substring(1):t.substring(1,p),g=p===-1?"":t.substring(p+1).trim(),x=Ne.getApiClient(),v=Ne.getDirectory();if(h==="init"){const j=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await x.session.init({path:{id:m},body:{messageID:j,providerID:n,modelID:o},query:v?{directory:v}:void 0});return}if(h==="summarize"){await x.session.summarize({path:{id:m},body:{providerID:n,modelID:o},query:v?{directory:v}:void 0});return}try{const j=await Ne.getCommandDetails(h);j?.template?f=j.template.replace(/\$ARGUMENTS/g,g):f=t}catch(j){console.error("Command template resolution failed:",j),f=t}}r({lastUsedProvider:{providerID:n,modelID:o}}),r(p=>{const h=p.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},g=Gs.get(m);g&&(clearTimeout(g),Gs.delete(m));const x=new Map(p.sessionMemoryState);return x.set(m,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:x}});try{const p=new AbortController;r(g=>{const x=new Map(g.abortControllers);return x.set(m,p),{abortControllers:x}});const h=(c??[]).map(g=>({type:"file",mime:g.mimeType,filename:g.filename,url:g.dataUrl}));if(await Ne.sendMessage({id:m,providerID:n,modelID:o,text:f,agent:a,files:h.length>0?h:void 0,agentMentions:d?[{name:d}]:void 0}),h.length>0)try{Ns.getState().clearAttachedFiles()}catch(g){console.error("Failed to clear attached files after send",g)}r(g=>{const x=new Map(g.abortControllers);return x.delete(m),{abortControllers:x}})}catch(p){let h="Network error while sending message. The message may still be processing.";if(p.name==="AbortError")h="Request timed out. The message may still be processing.";else if(p.message?.includes("504")||p.message?.includes("Gateway")){h="Gateway timeout - your message is being processed. Please wait for response.",r(g=>{const x=new Map(g.abortControllers);return x.delete(m),{abortControllers:x}});return}else p.message&&(h=p.message);throw r(g=>{const x=new Map(g.abortControllers);return x.delete(m),{abortControllers:x}}),new Error(h)}}catch(f){let u="Network error while sending message. The message may still be processing.";throw f.name==="AbortError"?u="Request timed out. The message may still be processing.":f.response?.status===401?u="Session not found or unauthorized. Please refresh the page.":f.response?.status===502?u="OpenCode is restarting. Please wait a moment and try again.":f.message?.includes("504")||f.message?.includes("Gateway")?u="Gateway timeout - your message is being processed. Please wait for response.":f.message&&(u=f.message),r(p=>{const h=new Map(p.abortControllers);return h.delete(m),{abortControllers:h}}),new Error(u)}})},abortCurrentOperation:async t=>{if(!t)return;const n=s(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const c=Mm(n,t);if(c.size===0){const m=t?a.get(t)??[]:[];let f=null;for(let u=m.length-1;u>=0;u-=1){const p=m[u];if(!p||p.info.role!=="assistant")continue;if(f||(f=p.info.id),(p.parts??[]).some(g=>g.type==="reasoning"||g.type==="tool"||g.type==="step-start")){c.add(p.info.id);break}}c.size===0&&f&&c.add(f)}for(const m of c){const f=Fs.get(m);f&&(clearTimeout(f),Fs.delete(m),Pr.delete(m))}c.size>0&&Rs(c);const d=Date.now();r(m=>{const f=ar(m.messageStreamStates,c),u=m.messages.get(t)??[];let p=!1,h=m.messages;if(u.length>0&&c.size>0){const j=u.map(N=>{if(!c.has(N.info.id)&&c.size>0)return N;const w=(N.parts??[]).map(y=>{if(y.type==="reasoning"){const S=y,b={...S.time??{}};return typeof b.end!="number"&&(b.end=d),{...S,time:b}}if(y.type==="tool"){const S=y,b={...S.state??{}};return(b.status==="running"||b.status==="pending")&&(b.status="aborted"),{...S,state:b}}return y.type==="step-start"?{...y,type:"step-finish",aborted:!0}:y});return p=!0,{...N,info:{...N.info,abortedAt:d,streaming:!1,status:"aborted"},parts:w}});p&&(h=new Map(m.messages),h.set(t,j))}const g=m.sessionMemoryState.get(t);let x=m.sessionMemoryState;if(g){const j=new Map(m.sessionMemoryState);j.set(t,{...g,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),x=j}const v=new Map(m.sessionAbortFlags);return v.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:f,sessionMemoryState:x,sessionAbortFlags:v,abortControllers:(()=>{const j=new Map(m.abortControllers);return j.delete(t),j})(),streamingMessageIds:Jt(m.streamingMessageIds,t,null),...p?{messages:h}:{}}}),Ne.abortSession(t).catch(m=>{console.warn("Abort request failed:",m)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const c=s();if(va.has(n))return;const d=c.messages.get(t)||[],m=d.find(h=>h.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",u=s().sessionMemoryState.get(t);if(u?.streamStartTime&&Date.now()-u.streamStartTime>Mt.ZOMBIE_TIMEOUT){u.isZombie||r(g=>{const x=new Map(g.sessionMemoryState);return x.set(t,{...u,isZombie:!0}),{sessionMemoryState:x}}),setTimeout(()=>{s().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}r(h=>{const x=[...h.messages.get(t)||[]],v={},j=qs(h.messageSessionIndex,n,t);j!==h.messageSessionIndex&&(v.messageSessionIndex=j);const N=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}},w=k=>{const M=k||"",E=Pr.get(n);if(M&&E===M){const F=s();if(Sa(F,t,n)){const O=Fs.get(n);O&&(clearTimeout(O),Fs.delete(n)),setTimeout(()=>{const z=s();typeof z.forceCompleteMessage=="function"&&z.forceCompleteMessage(t,n,"timeout"),z.completeStreamingMessage(t,n)},100)}}Pr.set(n,M);const P=Fs.get(n);P&&clearTimeout(P);const W=setTimeout(()=>{const F=s();typeof F.forceCompleteMessage=="function"&&F.forceCompleteMessage(t,n,"timeout"),Sa(F,t,n)&&F.completeStreamingMessage(t,n),Fs.delete(n),Pr.delete(n)},8e3);Fs.set(n,W)},y=t!==i,S=h.sessionMemoryState.get(t);if(y&&S?.isStreaming){x.length>=Mt.BACKGROUND_STREAMING_BUFFER&&x.shift();const k=new Map(h.sessionMemoryState);k.set(t,{...S,backgroundMessageCount:(S.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 b=xr(o);if(Pn(b)&&(o.synthetic=!0),km()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:b.length,snapshotParts:d.length})}catch{}const C=v.streamingMessageIds??h.streamingMessageIds;if(f==="assistant"){const k=Jt(C,t,n);k!==C&&(v.streamingMessageIds=k,window.__messageTracker?.(n,"streamingId_set_latest"))}const D=x.findIndex(k=>k.info.id===n);if(D!==-1&&f==="user"){const k=x[D],M=k.parts.findIndex(O=>O.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),h;const E=ir(o,M!==-1?k.parts[M]:void 0);window.__messageTracker?.(n,`user_part_type:${E.type||"unknown"}`);const P={...k};M!==-1?P.parts=P.parts.map((O,z)=>z===M?E:O):P.parts=[...P.parts,E];const W=[...x];W[D]=P;const F=new Map(h.messages);return F.set(t,W),N({messages:F})}if(f==="assistant"&&D!==-1){const k=x[D],M=k.parts.findIndex(z=>z.id===o.id),E=ir(o,M!==-1?k.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${E.type||"unknown"}`);const P={...k};M!==-1?P.parts=P.parts.map((z,X)=>X===M?E:z):P.parts=[...P.parts,E];const W=[...x];W[D]=P;const F=new Map(h.messages);F.set(t,W),v.messageStreamStates=Rn(h.messageStreamStates,n);const O=Jt(v.streamingMessageIds??h.streamingMessageIds,t,n);return O!==(v.streamingMessageIds??h.streamingMessageIds)&&(v.streamingMessageIds=O,window.__messageTracker?.(n,"streamingId_set")),E.type==="text"?w(E.text||""):w(""),N({messages:F,...v})}if(D===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),h;const L=ir(o);window.__messageTracker?.(n,`new_user_part_type:${L.type||"unknown"}`);const V={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,time:{created:Date.now()}},parts:[L]},Y=[...x,V];Y.sort((we,ke)=>{const ze=we.info?.time?.created||0,de=ke.info?.time?.created||0;return ze-de});const ie=new Map(h.messages);return ie.set(t,Y),N({messages:ie})}if(o?.type==="text"){const L=xr(o).trim();if(L.length>0){const V=[...x].reverse().find(Y=>Y.info.role==="user");if(V){const Y=V.parts.map(ie=>xr(ie)).join("").trim();if(Y.length>0&&Y===L)return va.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),h}}}const k=ir(o);window.__messageTracker?.(n,`part_type:${k.type||"unknown"}`),k.type==="text"?w(k.text||""):w("");const M=h.pendingAssistantParts.get(n),E=M?[...M.parts]:[],P=E.findIndex(L=>L.id===k.id);P!==-1?E[P]=k:E.push(k);const W=new Map(h.pendingAssistantParts);W.set(n,{sessionId:t,parts:E});const O={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},z=[...x,O],X=new Map(h.messages);if(X.set(t,z),f==="assistant"){v.messageStreamStates=Rn(h.messageStreamStates,n);const L=Jt(v.streamingMessageIds??h.streamingMessageIds,t,n);L!==(v.streamingMessageIds??h.streamingMessageIds)&&(v.streamingMessageIds=L,window.__messageTracker?.(n,"streamingId_set"))}return N({messages:X,pendingAssistantParts:W,...v})}else{const k=x[D],M=k.parts.findIndex(O=>O.id===o.id),E=ir(o,M!==-1?k.parts[M]:void 0);window.__messageTracker?.(n,`part_type:${E.type||"unknown"}`);const P={...k};M!==-1?P.parts=P.parts.map((O,z)=>z===M?E:O):P.parts=[...P.parts,E];const W=[...x];W[D]=P;const F=new Map(h.messages);if(F.set(t,W),P.info.role==="assistant"){v.messageStreamStates=Rn(h.messageStreamStates,n);const O=Jt(v.streamingMessageIds??h.streamingMessageIds,t,n);O!==(v.streamingMessageIds??h.streamingMessageIds)&&(v.streamingMessageIds=O,window.__messageTracker?.(n,"streamingId_set"))}return E.type==="text"?w(E.text||""):w(""),N({messages:F,...v})}}),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}Fn.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),_n||(_n=setTimeout(()=>{const c=[...Fn];Fn=[],_n=null;const d=s();for(const m of c)d._addStreamingPartImmediate(m.sessionId,m.messageId,m.part,m.role,m.currentSessionId)},jm))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[c,d]of i.messages.entries())if(d.some(m=>m.info.id===n))return c;return null};r(i=>{const c=a(i);if(!c)return i;const d=i.messages.get(c)??[],m=d.findIndex(S=>S.info.id===n);if(m===-1)return i;const f=d[m];if(!f)return i;const u=Date.now(),p=f.info,h=typeof p?.time?.completed=="number"&&p.time.completed>0;let g=!1;const x={...p};h||(x.time={...p.time??{},completed:u},g=!0),x.status!=="completed"&&(x.status="completed",g=!0),x.streaming&&(x.streaming=!1,g=!0);let v=!1;const j=f.parts.map(S=>{if(!S)return S;if(S.type==="tool"){const b=S.state;if(!b)return S;const C=b.status,D=C==="running"||C==="pending"||C==="started",k=!b.time||typeof b.time?.end!="number";if(D||k){const M={...b};return D&&(M.status="completed"),k&&(M.time={...b.time??{},end:u}),v=!0,{...S,state:M}}return S}if(S.type==="reasoning"){const b=S.time;return!b||typeof b.end!="number"?(v=!0,{...S,time:{...b??{},end:u}}):S}if(S.type==="text"){const b=S.time;return b&&typeof b.end!="number"?(v=!0,{...S,time:{...b,end:u}}):S}return S});if(!g&&!v)return i;window.__messageTracker?.(n,`force_complete:${o}`);const N={...f,info:x,parts:v?j:f.parts},w=[...d];w[m]=N;const y=new Map(i.messages);return y.set(c,w),{messages:y}})},markMessageStreamSettled:t=>{r(n=>{Xi(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,m)=>{if(i)return;const f=d.findIndex(x=>x.info.id===t);if(f===-1)return;const u=d[f];if(u.info?.animationSettled)return;const p={...u,info:{...u.info,animationSettled:!0}},h=[...d];h[f]=p;const g=new Map(n.messages);g.set(m,h),a=g,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),Rs([t])},updateMessageInfo:(t,n,o)=>{r(a=>{const c=[...a.messages.get(t)??[]],d=c.findIndex(S=>S.info.id===n),m=a.pendingAssistantParts.get(n),f=(S=[],b=[])=>{if(!b.length)return S;const C=[...S];return b.forEach(D=>{const k=C.findIndex(M=>M.id===D.id);k===-1?C.push(D):C[k]=D}),C},u=S=>{if(!S)return S;const b=S.clientRole??S.role,C=b==="user"?!0:S.userMessageMarker;return{...S,clientRole:b,...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 W=c[0]?.info,F=typeof W?.time?.created=="number"?W.time.created:null,O=typeof W?.id=="string"?W.id:null,z=o,X=typeof z?.time?.created=="number"?z.time.created:null,L=typeof z?.id=="string"?z.id:n;let V=!1;if(X!==null&&F!==null&&(V=X<F),!V&&L&&O&&(V=L.localeCompare(O)<0),V)return window.__messageTracker?.(n,"skipped_evicted_message_update"),a}const S=u(o);if(S&&S.role==="user"){const P=m?.parts??[],W={info:{...S,userMessageMarker:!0,clientRole:"user"},parts:P.length>0?[...P]:[]},F=new Map(a.messages),O=[...c,W];O.sort((L,V)=>{const Y=L.info?.time?.created||0,ie=V.info?.time?.created||0;return Y-ie}),F.set(t,O);const z={messages:F},X=qs(z.messageSessionIndex??a.messageSessionIndex,n,t);if(X!==(z.messageSessionIndex??a.messageSessionIndex)&&(z.messageSessionIndex=X),m){const L=new Map(a.pendingAssistantParts);L.delete(n),z.pendingAssistantParts=L}return z}if(!S||S.role!=="assistant")return a;const b=m?.parts??[],C={info:{...S,animationSettled:S?.animationSettled??!1},parts:b.length>0?[...b]:[]},D=new Map(a.messages),k=[...c,C];D.set(t,k);const M={messages:D},E=qs(M.messageSessionIndex??a.messageSessionIndex,n,t);if(E!==(M.messageSessionIndex??a.messageSessionIndex)&&(M.messageSessionIndex=E),m){const P=new Map(a.pendingAssistantParts);P.delete(n),M.pendingAssistantParts=P}return M}const p=c[d],h=p.info;if(h.userMessageMarker===!0||h.clientRole==="user"||h.role==="user"){const S={...p.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:h.providerID||void 0,modelID:h.modelID||void 0},b={...p,info:S},C=new Map(a.messages),D=[...c];return D[d]=b,C.set(t,D),{messages:C}}const x={...p.info,...o};o.role&&o.role!==p.info.role&&(x.role=p.info.role),x.clientRole=x.clientRole??p.info.clientRole??p.info.role,x.clientRole==="user"&&(x.userMessageMarker=!0);const v=m?.parts?f(p.parts,m.parts):p.parts,j={...p,info:x,parts:v},N=new Map(a.messages),w=[...c];w[d]=j,N.set(t,w);const y={messages:N};if(m){const S=new Map(a.pendingAssistantParts);S.delete(n),y.pendingAssistantParts=S}return y})},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=Jt(o.streamingMessageIds,t,null),i.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),i.messageStreamStates=d}Object.keys(i).length>0&&r(i),o.pendingAssistantParts.has(n)&&r(d=>{if(!d.pendingAssistantParts.has(n))return d;const m=new Map(d.pendingAssistantParts);return m.delete(n),{pendingAssistantParts:m}}),Rs([n]);let c=!1;if(r(d=>{const m=d.sessionMemoryState.get(t);if(!m||!m.isStreaming)return d;const f=new Map(d.sessionMemoryState),u=Date.now(),p={...m,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:u,streamingCooldownUntil:u+2e3};return f.set(t,p),c=!0,{sessionMemoryState:f}}),c){const d=Gs.get(t);d&&(clearTimeout(d),Gs.delete(t));const m=setTimeout(()=>{r(f=>{const u=f.sessionMemoryState.get(t);if(!u||u.isStreaming)return f;const p=new Map(f.sessionMemoryState),{streamingCooldownUntil:h,...g}=u;return p.set(t,g),{sessionMemoryState:p}}),Gs.delete(t)},2e3);Gs.set(t,m)}},syncMessages:(t,n)=>{const o=s().sessionMemoryState.get(t)?.trimmedHeadMaxId,a=o?n.filter(i=>{const c=i?.info?.id;return c?ya(c,o):!0}):n;r(i=>{const c=new Map(i.messages),d=i.messages.get(t)||[],m=new Map(d.filter(w=>typeof w.info?.id=="string").map(w=>[w.info.id,w])),u=a.map(w=>{const y={...w.info,clientRole:w.info?.clientRole??w.info.role,userMessageMarker:w.info.role==="user"?!0:w.info?.userMessageMarker,animationSettled:w.info.role==="assistant"?w.info?.animationSettled??!0:w.info?.animationSettled},S=(Array.isArray(w.parts)?w.parts:[]).map(D=>{if(D?.type==="text"){const k=D.text??D.content??"";if(Pn(k))return{...D,synthetic:!0}}return D}),b=typeof y?.id=="string"?y.id:void 0,C=b?m.get(b):void 0;if(C&&C.info.role==="assistant"){const D=Array.isArray(C.parts)?C.parts:[],k=Rr(D),M=Rr(S);if(ba(D)&&k>M){const P=ja(D,S);return{...w,info:y,parts:P}}}return{...w,info:y,parts:S}}),p=new Set(d.map(w=>w.info.id)),h=new Set(u.map(w=>w.info.id)),g=[];p.forEach(w=>{h.has(w)||g.push(w)}),c.set(t,u);const x={messages:c,isSyncing:!0};Rs(g);const v=ar(i.messageStreamStates,g);if(v!==i.messageStreamStates&&(x.messageStreamStates=v),g.length>0){const w=i.streamingMessageIds.get(t);w&&g.includes(w)&&(x.streamingMessageIds=Jt(x.streamingMessageIds??i.streamingMessageIds,t,null))}if(g.length>0){const w=Fr(x.messageSessionIndex??i.messageSessionIndex,g);w!==(x.messageSessionIndex??i.messageSessionIndex)&&(x.messageSessionIndex=w)}if(g.length>0){const w=new Map(i.pendingAssistantParts);let y=!1;g.forEach(S=>{w.delete(S)&&(y=!0)}),y&&(x.pendingAssistantParts=w)}const j=x.messageSessionIndex??i.messageSessionIndex;let N=j;return u.forEach(w=>{const y=w?.info?.id;typeof y=="string"&&y.length>0&&(N=qs(N,y,t))}),N!==j&&(x.messageSessionIndex=N),x}),setTimeout(()=>{r({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{r(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=n+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=Mt.VIEWPORT_MESSAGES,o)=>{const a=s(),i=a.messages.get(t);if(!i||i.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.viewportAnchor||i.length-1;let m=Math.max(0,d-Math.floor(n/2));const f=Math.min(i.length,m+n);f===i.length&&f-m<n&&(m=Math.max(0,f-n));const u=i.slice(m,f),p=i.slice(0,m),h=new Set(u.map(x=>x.info.id)),g=i.filter(x=>!h.has(x.info.id)).map(x=>x.info.id);r(x=>{const v=new Map(x.messages);v.set(t,u);const j=new Map(x.sessionMemoryState),N={...c,viewportAnchor:d-m,trimmedHeadMaxId:Cm(p,c.trimmedHeadMaxId)};j.set(t,N);const w={messages:v,sessionMemoryState:j};Rs(g);const y=ar(x.messageStreamStates,g);if(y!==x.messageStreamStates&&(w.messageStreamStates=y),g.length>0){const C=x.streamingMessageIds.get(t);C&&g.includes(C)&&(w.streamingMessageIds=Jt(w.streamingMessageIds??x.streamingMessageIds,t,null))}if(g.length>0){const C=Fr(w.messageSessionIndex??x.messageSessionIndex,g);C!==(w.messageSessionIndex??x.messageSessionIndex)&&(w.messageSessionIndex=C)}const S=w.messageSessionIndex??x.messageSessionIndex;let b=S;return u.forEach(C=>{const D=C?.info?.id;typeof D=="string"&&D.length>0&&(b=qs(b,D,t))}),b!==S&&(w.messageSessionIndex=b),w})},evictLeastRecentlyUsed:t=>{const n=s();if(n.messages.size<=Mt.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,m)=>{const f=n.sessionMemoryState.get(m)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([m,f])});const i=a.filter(([d,m])=>d!==t&&!m.isStreaming);if(i.length===0)return;i.sort((d,m)=>d[1].lastAccessedAt-m[1].lastAccessedAt);const c=i[0][0];r(d=>{const f=(d.messages.get(c)||[]).map(y=>y.info.id),u=new Map(d.messages),p=new Map(d.sessionMemoryState);u.delete(c),p.delete(c);const h={messages:u,sessionMemoryState:p},g=new Map(d.pendingAssistantParts);let x=!1;g.forEach((y,S)=>{y.sessionId===c&&(g.delete(S),x=!0)}),x&&(h.pendingAssistantParts=g);const v=new Map(d.sessionCompactionUntil);v.delete(c)&&(h.sessionCompactionUntil=v),Rs(f);const j=ar(d.messageStreamStates,f);j!==d.messageStreamStates&&(h.messageStreamStates=j);const N=Fr(h.messageSessionIndex??d.messageSessionIndex,f);N!==(h.messageSessionIndex??d.messageSessionIndex)&&(h.messageSessionIndex=N);const w=Jt(d.streamingMessageIds,c,null);if(w!==d.streamingMessageIds&&(h.streamingMessageIds=w),d.abortControllers.has(c)){const y=new Map(d.abortControllers);y.delete(c),h.abortControllers=y}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 Ln(t,()=>Ne.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],m=c.findIndex(f=>f.info.id===d.info.id);if(m>0){const f=Math.min(Mt.VIEWPORT_MESSAGES,m),u=c.slice(m-f,m);r(p=>{const h=[...u,...a],g=new Map(p.messages);g.set(t,h);const x=new Map(p.sessionMemoryState);return x.set(t,{...i,viewportAnchor:i.viewportAnchor+u.length,hasMoreAbove:m-f>0,totalAvailableMessages:c.length}),{messages:g,sessionMemoryState:x}})}else m===0&&r(f=>{const u=new Map(f.sessionMemoryState);return u.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:u}})}},getLastMessageModel:t=>{const{messages:n}=s(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:ns(()=>zt()),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"})),Dm=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Em=r=>r?Dm.has(r.toLowerCase()):!1,Tm=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Im=r=>{if(r)try{const s=Tm();if(s?.getState)return s.getState().agents?.find?.(n=>n.name===r)}catch{}},Jr=r=>{const s=Im(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"},Na=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},On=r=>{const s=r.info.tokens;if(typeof s=="number")return s;if(s&&typeof s=="object")return Na(s);const t=r.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:Na(t.tokens)},$n=(r,s,t)=>{const n=Number.isFinite(s)?Math.max(s,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),c=Math.min(i,n),d=n>0?Math.max(n-c,1):0,m=d>0?r/d*100:0;return{percentage:Math.min(m,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},lr=["ask","allow","full"],mt=Tt()(Pt(rs((r,s)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{r(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=s();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{r(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=s();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{r(i=>{const c=new Map(i.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=s(),a=o.get(t);return a&&a.get(n)||null},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a}=s(),i=new Map,c=(u,p)=>{if("mode"in u&&u.mode&&typeof u.mode=="string"&&n.find(v=>v.name===u.mode))return u.mode;if(u.providerID&&u.modelID){const x=n.find(v=>v.model?.providerID===u.providerID&&v.model?.modelID===u.modelID);if(x)return x.name}const{currentAgentContext:h}=s(),g=h.get(t);if(g&&n.find(x=>x.name===g))return g;if(p>0&&u.providerID&&u.modelID){const v=(o.get(t)||[]).filter(j=>j.info.role==="assistant").sort((j,N)=>j.info.time.created-N.info.time.created);for(let j=p-1;j>=0;j--){const w=v[j].info;if(w.providerID===u.providerID&&w.modelID===u.modelID){if(w.mode&&typeof w.mode=="string"&&n.find(b=>b.name===w.mode))return w.mode;const y=n.find(S=>S.model?.providerID===w.providerID&&S.model?.modelID===w.modelID);if(y)return y.name}}}return u.providerID&&u.modelID&&n.find(v=>v.name==="build")?"build":null},d=o.get(t)||[],m=d.filter(u=>u.info.role==="assistant"||u.info.role==="user").sort((u,p)=>u.info.time.created-p.info.time.created),f=d.filter(u=>u.info.role==="assistant").sort((u,p)=>u.info.time.created-p.info.time.created);for(let u=0;u<m.length;u++){const p=m[u],{info:h}=p,g=h;if(g.providerID&&g.modelID){const x=c(g,f.indexOf(p));if(x&&n.find(v=>v.name===x)){const v={providerId:g.providerID,modelId:g.modelID,timestamp:h.time.created},j=i.get(x);(!j||v.timestamp>j.timestamp)&&i.set(x,v)}}}for(const[u,p]of i)a(t,u,p.providerId,p.modelId);return i},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=$n(0,n,o),c=i.contextLimit,d=i.normalizedOutput??0,m=i.thresholdLimit;if(c===0||m===0)return null;const u=(a.get(t)||[]).filter(w=>w.info.role==="assistant");if(u.length===0)return null;const p=u[u.length-1],h=p.info.id,g=w=>{const y=()=>{r(S=>{const b=S.sessionContextUsage.get(t);if(b&&b.totalTokens===w.totalTokens&&b.percentage===w.percentage&&b.contextLimit===w.contextLimit&&(b.outputLimit??0)===(w.outputLimit??0)&&(b.normalizedOutput??0)===(w.normalizedOutput??0)&&b.thresholdLimit===w.thresholdLimit&&b.lastMessageId===w.lastMessageId)return S;const C=new Map(S.sessionContextUsage);return C.set(t,w),{sessionContextUsage:C}})};typeof queueMicrotask=="function"?queueMicrotask(y):typeof window<"u"?window.setTimeout(y,0):setTimeout(y,0)},x=s().sessionContextUsage.get(t);if(x&&x.lastMessageId===h){const w=x.normalizedOutput??x.outputLimit??0,y=x.contextLimit!==c||w!==d||x.thresholdLimit!==m;if(y&&x.totalTokens>0){const S=x.totalTokens/m*100,b={totalTokens:x.totalTokens,percentage:Math.min(S,100),contextLimit:c,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:m,lastMessageId:h};return g(b),b}if(!y&&x.totalTokens>0)return x}const v=On(p);if(v===0)return x||null;const j=$n(v,n,o),N={totalTokens:v,percentage:j.percentage,contextLimit:j.contextLimit,outputLimit:j.outputLimit,normalizedOutput:j.normalizedOutput,thresholdLimit:j.thresholdLimit,lastMessageId:h};return g(N),N},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(u=>u.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],m=On(d);if(m===0)return;const f=$n(m,n,o);r(u=>{const p=new Map(u.sessionContextUsage);return p.set(t,{totalTokens:m,percentage:f.percentage,contextLimit:f.contextLimit,outputLimit:f.outputLimit,normalizedOutput:f.normalizedOutput,thresholdLimit:f.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(t,n,o,a)=>{const c=s().sessionContextUsage.get(t);(!c||c.totalTokens===0)&&s().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const c=()=>{i++;const m=(o.get(t)||[]).find(f=>f.info.id===n);if(m&&m.info.role==="assistant"&&On(m)>0){s().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=s();return n.get(t)},getSessionAgentEditMode:(t,n,o=Jr(n))=>!t||!n?o:s().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Jr(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||lr.includes(o)&&r(c=>{const d=new Map(c.sessionAgentEditModes),m=new Map(d.get(t)??new Map);return o===i?(m.delete(n),m.size===0?d.delete(t):d.set(t,m)):(m.set(n,o),d.set(t,m)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Jr(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=s().getSessionAgentEditMode(t,n,a),c=lr.indexOf(i),d=lr.indexOf(a),f=((c>=0?c:d>=0?d:0)+1)%lr.length,u=lr[f];s().setSessionAgentEditMode(t,n,u,a)}}),{name:"context-store",storage:ns(()=>zt()),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"})),Pm=r=>typeof r=="object"&&r!==null,Rm=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},Fm=async(r,s)=>{try{const t=Xe.getState(),n=t.getWorktreeMetadata(r);if(n?.path)return Ne.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 Ne.withDirectory(a,s)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return s()},pn=Tt()(Pt(rs((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=Jr(i),d=n?.getSessionAgentEditMode?.(o,i)??c;if(d==="full"||d==="allow"&&Em(a)){s().respondToPermission(o,t.id,"once").catch(()=>{});return}r(f=>{const u=f.permissions.get(o)||[],p=new Map(f.permissions);return p.set(o,[...u,t]),{permissions:p}})},respondToPermission:async(t,n,o)=>{await Fm(t,()=>Ne.respondToPermission(t,n,o)),o==="reject"&&await Qe.getState().abortCurrentOperation(t),r(a=>{const c=(a.permissions.get(t)||[]).filter(m=>m.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:ns(()=>zt()),partialize:r=>({permissions:Array.from(r.permissions.entries())}),merge:(r,s)=>{if(!Pm(r))return s;const t=Rm(r.permissions);return{...s,permissions:new Map(t)}}}),{name:"permission-store"})),Ji=r=>r.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
|
|
4
4
|
`).replace(/\n\s*\n+/g,`
|
|
5
5
|
`),ka=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},Ca=(r,s,t)=>{if(!s)return null;const n=t(s)?.path;if(typeof n=="string"&&n.trim().length>0)return ka(n);const o=r.find(a=>a.id===s);return o?ka(o.directory??null):null},pe=Tt()(Pt((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)=>mt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>mt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>mt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>Xe.getState().loadSessions(),createSession:async(t,n,o)=>{const a=await Xe.getState().createSession(t,n,o);return a?.id&&await s().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=Qe.getState(),{messages:o,lastUsedProvider:a}=n;let i,c;if(o.forEach((j,N)=>{const w=j.find(y=>y.info?.id===t);w&&!i&&(i=w,c=N)}),!i||i.info.role!=="assistant")return;const d=Ji(i.parts);if(!d.trim())return;const m=Xe.getState(),f=Ca(m.sessions,c??null,m.getWorktreeMetadata),u=await s().createSession(void 0,f??null,null);if(!u)return;const{currentProviderId:p,currentModelId:h,currentAgentName:g}=gt.getState(),x=p||a?.providerID,v=h||a?.modelID;!x||!v||await Ne.sendMessage({id:u.id,providerID:x,modelID:v,text:d,prefaceText:Yi,agent:g??void 0})},deleteSession:(t,n)=>Xe.getState().deleteSession(t,n),deleteSessions:(t,n)=>Xe.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>Xe.getState().updateSessionTitle(t,n),shareSession:t=>Xe.getState().shareSession(t),unshareSession:t=>Xe.getState().unshareSession(t),setCurrentSession:async t=>{const n=s().currentSessionId,o=Ca(Xe.getState().sessions,t,Xe.getState().getWorktreeMetadata),a=Ne.getDirectory()??ht.getState().currentDirectory??null,i=o??a;try{Ne.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,Mt.VIEWPORT_MESSAGES)}Xe.getState().setCurrentSession(t),t&&(s().messages.get(t)||await s().loadMessages(t),s().trimToViewportWindow(t,Mu)),s().evictLeastRecentlyUsed()},loadMessages:t=>Qe.getState().loadMessages(t),sendMessage:(t,n,o,a,i,c)=>{const d=Xe.getState().currentSessionId;return Qe.getState().sendMessage(t,n,o,a,d||void 0,i,c)},abortCurrentOperation:()=>{const t=Xe.getState().currentSessionId;return Qe.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=Xe.getState().currentSessionId;if(!n)return null;const o=Date.now()+t;return r({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{r({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&&Qe.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=Xe.getState().currentSessionId||t;return Qe.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>Qe.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>Qe.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>Qe.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>Qe.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:mt.getState().currentAgentContext,sessionAgentSelections:mt.getState().sessionAgentSelections,getSessionAgentEditMode:mt.getState().getSessionAgentEditMode};return pn.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>pn.getState().respondToPermission(t,n,o),clearError:()=>Xe.getState().clearError(),getSessionsByDirectory:t=>Xe.getState().getSessionsByDirectory(t),getLastMessageModel:t=>Qe.getState().getLastMessageModel(t),getCurrentAgent:t=>mt.getState().getCurrentAgent(t),syncMessages:(t,n)=>Qe.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>Xe.getState().applySessionMetadata(t,n),addAttachedFile:t=>Ns.getState().addAttachedFile(t),addServerFile:(t,n,o)=>Ns.getState().addServerFile(t,n,o),removeAttachedFile:t=>Ns.getState().removeAttachedFile(t),clearAttachedFiles:()=>Ns.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>Qe.getState().updateViewportAnchor(t,n),trimToViewportWindow:(t,n)=>{const o=Xe.getState().currentSessionId;return Qe.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=Xe.getState().currentSessionId;return Qe.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>Qe.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>mt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>mt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>mt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>mt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>mt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>mt.getState().getAgentModelForSession(t,n),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=Qe.getState().messages;return mt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>Xe.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>Xe.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>Xe.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>Xe.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>Xe.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>Xe.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{const o=Xe.getState().currentSessionId;if(!o)return null;const a=Qe.getState().messages;return mt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=Qe.getState().messages;return mt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=Qe.getState().messages;return mt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=Qe.getState().messages.get(t)||[],o=Xe.getState().sessions.find(a=>a.id===t);console.log(`Debug session ${t}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(t,n,o)=>{const a=Qe.getState().messages;return mt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>Xe.getState().updateSession(t)}),{name:"composed-session-store"}));Xe.subscribe((r,s)=>{r.sessions===s.sessions&&r.currentSessionId===s.currentSessionId&&r.lastLoadedDirectory===s.lastLoadedDirectory&&r.isLoading===s.isLoading&&r.error===s.error&&r.webUICreatedSessions===s.webUICreatedSessions&&r.worktreeMetadata===s.worktreeMetadata&&r.availableWorktrees===s.availableWorktrees||pe.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})});Qe.subscribe((r,s)=>{if(r.messages===s.messages&&r.sessionMemoryState===s.sessionMemoryState&&r.messageStreamStates===s.messageStreamStates&&r.sessionCompactionUntil===s.sessionCompactionUntil&&r.sessionAbortFlags===s.sessionAbortFlags&&r.streamingMessageIds===s.streamingMessageIds&&r.abortControllers===s.abortControllers&&r.lastUsedProvider===s.lastUsedProvider&&r.isSyncing===s.isSyncing)return;const t=new Map;r.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const c=i.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const m=d.trim();if(m.length>0){const f=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:m,createdAt:f});break}}}}}),pe.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})});Ns.subscribe((r,s)=>{r.attachedFiles!==s.attachedFiles&&pe.setState({attachedFiles:r.attachedFiles})});mt.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||pe.setState({sessionModelSelections:r.sessionModelSelections,sessionAgentSelections:r.sessionAgentSelections,sessionAgentModelSelections:r.sessionAgentModelSelections,currentAgentContext:r.currentAgentContext,sessionContextUsage:r.sessionContextUsage,sessionAgentEditModes:r.sessionAgentEditModes})});pn.subscribe((r,s)=>{r.permissions!==s.permissions&&pe.setState({permissions:r.permissions})});pe.setState({sessions:Xe.getState().sessions,currentSessionId:Xe.getState().currentSessionId,lastLoadedDirectory:Xe.getState().lastLoadedDirectory,isLoading:Xe.getState().isLoading,error:Xe.getState().error,webUICreatedSessions:Xe.getState().webUICreatedSessions,worktreeMetadata:Xe.getState().worktreeMetadata,availableWorktrees:Xe.getState().availableWorktrees,messages:Qe.getState().messages,sessionMemoryState:Qe.getState().sessionMemoryState,messageStreamStates:Qe.getState().messageStreamStates,sessionCompactionUntil:Qe.getState().sessionCompactionUntil,sessionAbortFlags:Qe.getState().sessionAbortFlags,streamingMessageIds:Qe.getState().streamingMessageIds,abortControllers:Qe.getState().abortControllers,lastUsedProvider:Qe.getState().lastUsedProvider,isSyncing:Qe.getState().isSyncing,permissions:pn.getState().permissions,attachedFiles:Ns.getState().attachedFiles,sessionModelSelections:mt.getState().sessionModelSelections,sessionAgentSelections:mt.getState().sessionAgentSelections,sessionAgentModelSelections:mt.getState().sessionAgentModelSelections,currentAgentContext:mt.getState().currentAgentContext,sessionContextUsage:mt.getState().sessionContextUsage,sessionAgentEditModes:mt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=pe);const lo=({totalTokens:r,percentage:s,contextLimit:t,outputLimit:n,size:o="default"})=>{const a=f=>f>=1e6?`${(f/1e6).toFixed(1)}M`:f>=1e3?`${(f/1e3).toFixed(1)}K`:f.toFixed(1).replace(/\.0$/,""),i=f=>f>=90?"text-status-error":f>=75?"text-status-warning":"text-status-success",c=typeof n=="number"?Math.max(n,0):0,d=[`Used tokens: ${a(r)}`,`Context limit: ${a(t)}`,`Output limit: ${a(c)}`],m=e.jsxs("div",{className:T("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",children:[e.jsx(gc,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:T(i(s),"font-medium"),children:[Math.min(s,999).toFixed(1),"%"]})]});return e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:m}),e.jsx(lt,{children:e.jsx("div",{className:"space-y-0.5",children:d.map(f=>e.jsx("p",{className:"typography-micro leading-tight",children:f},f))})})]})},cr={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Zi=(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 zn(){const r=window.innerWidth,s=typeof window.matchMedia=="function",t=s?window.matchMedia("(pointer: coarse)"):null,n=s?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,m=r>cr.md&&r<=cr.lg,f=r<=cr.md;let u=d&&f,p=d&&!u&&m,h=!d||r>cr.lg,g="desktop";c?(u=!1,p=!1,h=!0,g="desktop"):u?g="mobile":p?g="tablet":(h=!0,g="desktop"),Zi(c,g,d);let x="xs";for(const[v,j]of Object.entries(cr))r>=j&&(x=v);return{isMobile:u,isTablet:p,isDesktop:h,deviceType:g,screenWidth:r,breakpoint:x,hasTouchInput:d}}function St(){const[r,s]=l.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:zn());return l.useEffect(()=>{if(typeof window>"u")return;const t=()=>{s(zn())};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(zn())},a=[],i=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return i(t),i(n),()=>{a.forEach(c=>c())}},[]),l.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,m=i||c||d>0;Zi(t,r.deviceType,m)},[r.deviceType,r.hasTouchInput]),r}const _r=1e4,_m=2e4,Lm=5e3,Om=3e4,Zt=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),$m=(r,s)=>{if(!r&&!s)return!1;if(!r||!s)return!0;const t=new Set([...Object.keys(r),...Object.keys(s)]);for(const n of t){const o=r[n],a=s[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},zm=(r,s)=>{if(!r&&!s)return!1;if(!r||!s)return!0;const t=r.files??[],n=s.files??[];if(t.length!==n.length||r.ahead!==s.ahead||r.behind!==s.behind||r.current!==s.current||r.tracking!==s.tracking||r.isClean!==s.isClean)return!0;const o=new Set(t.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of n)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!$m(r.diffStats,s.diffStats)},wt=Tt()(Pt((r,s)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:_r,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=s();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,Zt()),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=Zt()),a||r({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const u=new Map(i);return u.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),r({directories:u,isLoadingStatus:!1}),!1}const f=await n.getGitStatus(t);if(zm(c.status,f)){d=!0;const u=new Map(s().directories),p=u.get(t)??Zt();u.set(t,{...p,isGitRepo:!0,status:f,diffCache:new Map,lastStatusFetch:Date.now(),lastStatusChange:Date.now()}),r({directories:u})}else{const u=new Map(s().directories),p=u.get(t)??Zt();u.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),r({directories:u})}}catch(m){console.error("Failed to fetch git status:",m)}finally{a||r({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{r({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(s().directories),i=a.get(t)??Zt();a.set(t,{...i,branches:o}),r({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{r({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=s(),i=a.get(t),c=o??i?.logMaxCount??25;r({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),m=new Map(s().directories),f=m.get(t)??Zt();m.set(t,{...f,log:d,lastLogFetch:Date.now(),logMaxCount:c}),r({directories:m})}catch(d){console.error("Failed to fetch git log:",d)}finally{r({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{r({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(s().directories),i=a.get(t)??Zt();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=Zt();const u=new Map(a);u.set(t,i),r({directories:u})}const{force:c=!1}=o,d=Date.now();await s().fetchStatus(t,n);const m=s().directories.get(t);if(!m?.isGitRepo)return;await s().fetchBranches(t,n);const f=d-(m.lastLogFetch||0);(c||f>Om||!m.log)&&await s().fetchLog(t,n),await s().fetchIdentity(t,n)},getDiff:(t,n)=>s().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(s().directories),i=a.get(t)??Zt(),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)??Zt();o.set(t,{...a,logMaxCount:n}),r({directories:o})},startPolling:t=>{const{pollIntervalId:n}=s();if(n)return;const o=()=>{const{currentPollInterval:a}=s();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){r({pollIntervalId:o()});return}const{activeDirectory:c}=s();if(!c){r({pollIntervalId:o()});return}if(await s().fetchStatus(c,t,{silent:!0}))await s().fetchLog(c,t),r({currentPollInterval:_r});else{const f=Math.min(a+Lm,_m);r({currentPollInterval:f})}const{pollIntervalId:m}=s();m!==null&&r({pollIntervalId:o()})},a)};r({pollIntervalId:o(),currentPollInterval:_r})},stopPolling:()=>{const{pollIntervalId:t}=s();t&&(clearTimeout(t),r({pollIntervalId:null,currentPollInterval:_r}))},refresh:async(t,n={})=>{const{activeDirectory:o}=s();o&&await s().fetchAll(o,t,n)}}),{name:"git-store"})),Qi=r=>wt(s=>r?s.directories.get(r)?.status??null:null),Bm=r=>wt(s=>r?s.directories.get(r)?.branches??null:null),Hm=r=>wt(s=>r?s.directories.get(r)?.log??null:null),Wm=r=>wt(s=>r?s.directories.get(r)?.identity??null:null),el=r=>wt(s=>r?s.directories.get(r)?.isGitRepo??null:null),Um=r=>wt(s=>r?s.directories.get(r)?.status?.files?.length??0:0);function Lt({...r}){return e.jsx(xc,{"data-slot":"dropdown-menu",...r})}function Ot({...r}){return e.jsx(yc,{"data-slot":"dropdown-menu-trigger",...r})}function $t({className:r,sideOffset:s=4,...t}){return e.jsx(bc,{children:e.jsx(wc,{"data-slot":"dropdown-menu-content",sideOffset:s,className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...t})})}function xt({className:r,inset:s,variant:t="default",...n}){return e.jsx(Nc,{"data-slot":"dropdown-menu-item","data-inset":s,"data-variant":t,className:T("hover:bg-accent hover:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),...n})}function Vm({...r}){return e.jsx(vc,{"data-slot":"dropdown-menu-radio-group",...r})}function Gm({className:r,children:s,...t}){return e.jsxs(jc,{"data-slot":"dropdown-menu-radio-item",className:T("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-accent hover:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",r),...t,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(Sc,{children:e.jsx(jt,{className:"size-3"})})}),s]})}function Lo({className:r,...s}){return e.jsx(kc,{"data-slot":"dropdown-menu-separator",className:T("bg-border -mx-1 my-0.5 h-px",r),...s})}function tl({...r}){return e.jsx(Cc,{"data-slot":"dropdown-menu-sub",...r})}function sl({className:r,inset:s,children:t,...n}){return e.jsxs(Mc,{"data-slot":"dropdown-menu-sub-trigger","data-inset":s,className:T("hover:bg-accent hover:text-accent-foreground flex cursor-default items-center rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8",r),...n,children:[t,e.jsx(ps,{className:"ml-auto size-3.5"})]})}function rl({className:r,...s}){return e.jsx(Ac,{"data-slot":"dropdown-menu-sub-content",className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",r),...s})}const qm={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 nl(r){return qm[r]||{displayName:r.charAt(0).toUpperCase()+r.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Km(r,s,t){const n=nl(r);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=Nn(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 Nn(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 Ym(r,s){if(!r)return"";const t=n=>{const o=r[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(s==="bash"){const n=t("command");if(n)return n}if(s==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((s==="edit"||s==="multiedit")&&typeof r=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(s==="write"&&typeof r=="object"){const n=t("content");if(n)return n}return typeof r=="object"?Object.entries(r).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${i}: ${c}`}).join(`
|
|
6
|
-
`):String(r)}const Oo=l.createContext(null),Ws=()=>{const r=l.useContext(Oo);if(!r)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return r},ol=r=>{const s=Ws();return r(s)},Xm=()=>ol(r=>r.runtime.isDesktop),$o=()=>ol(r=>r.runtime.isVSCode),Jm=({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(Ce,{size:"sm",variant:"ghost",className:T("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:n,title:r==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:r==="side-by-side"?e.jsx(Dc,{className:"h-3 w-3"}):e.jsx(Ec,{className:"h-3 w-3"})})},Zm=l.lazy(()=>Js(()=>import("./MonacoDiffViewer-DQgBqdB9.js"),__vite__mapDeps([0,1,2,3,4])).then(r=>({default:r.MonacoDiffViewer}))),Qm=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]})},ef=l.memo(({changedFiles:r,selectedFile:s,selectedFileEntry:t,onSelectFile:n})=>r.length===0?null:e.jsxs(Lt,{children:[e.jsx(Ot,{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(yt,{className:"size-4 opacity-50"})]})}),e.jsx($t,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Vm,{value:s??"",onValueChange:n,children:r.map(o=>e.jsx(Gm,{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))})})]})),tf=l.memo(({fileDiff:r,activeFilePath:s,isDiffLoading:t,diffError:n,onRetry:o,renderSideBySide:a,allowResponsive:i})=>{const c=l.useMemo(()=>s&&Nn(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(Dt,{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(Ce,{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(Dt,{size:16,className:"animate-spin"}),"Loading diff viewer…"]}),children:e.jsx(Zm,{original:r.original,modified:r.modified,language:c,renderSideBySide:a,allowResponsive:i})})})}),sf=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=pe(),{currentDirectory:n}=ht(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},rf=()=>{const{git:r}=Ws(),s=sf(),t=el(s??null),n=Qi(s??null),o=wt(O=>O.isLoadingStatus),{setActiveDirectory:a,fetchStatus:i,setDiff:c}=wt(),[d,m]=l.useState(null),f=l.useRef(null),[u,p]=l.useState(!1),[h,g]=l.useState(null),[x,v]=l.useState(null),j=Le(O=>O.pendingDiffFile),N=Le(O=>O.setPendingDiffFile),w=Le(O=>O.diffLayoutPreference),y=Le(O=>O.diffFileLayout),S=Le(O=>O.setDiffFileLayout),b=wt(l.useCallback(O=>s?O.directories.get(s)?.lastStatusChange??0:0,[s])),C=l.useCallback((O,z)=>{if(!O)return null;const X=wt.getState().directories.get(O);if(!X)return null;const L=X.diffCache.get(z);return!L||L.fetchedAt<(X.lastStatusChange||0)?null:L},[]),D=l.useCallback(O=>{f.current=O,m(O),g(null);const z=C(s,O);z?(v({original:z.original,modified:z.modified}),p(!1)):(v(null),p(!0))},[s,C]);l.useEffect(()=>{s&&(a(s),wt.getState().directories.get(s)?.status||i(s,r))},[s,a,i,r]),l.useEffect(()=>{j&&(D(j),N(null))},[j,D,N]),l.useEffect(()=>{f.current=d},[d]);const k=l.useMemo(()=>{if(!n?.files)return[];const O=n.diffStats??{};return n.files.map(z=>({...z,insertions:O[z.path]?.insertions??0,deletions:O[z.path]?.deletions??0,isNew:Qm(z)})).sort((z,X)=>z.path.localeCompare(X.path))},[n]),M=l.useMemo(()=>d?k.find(O=>O.path===d)??null:null,[k,d]),E=l.useMemo(()=>{if(!M)return null;const O=y[M.path];return O||(w==="inline"||w==="side-by-side"?w:M.isNew?"inline":"side-by-side")},[M,y,w]);l.useEffect(()=>{if(!d&&!j&&k.length>0){const O=k[0].path;D(O)}},[k,d,j,D]),l.useEffect(()=>{d&&k.length>0&&(k.some(z=>z.path===d)||(m(null),f.current=null,v(null),g(null)))},[k,d]);const P=l.useCallback(async()=>{if(!s||!M){v(null),g(null),p(!1);return}const O=M.path,z=C(s,O);if(z){v({original:z.original,modified:z.modified}),g(null),p(!1);return}p(!0),g(null);try{const X=await r.getGitFileDiff(s,{path:M.path}),L={original:X.original??"",modified:X.modified??""};c(s,O,L),v(L)}catch(X){const L=X instanceof Error?X.message:"Failed to load diff";g(L),he.error(L)}finally{p(!1)}},[s,r,M,C,c,b]);l.useEffect(()=>{P()},[P]);const W=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(Dt,{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 z=(E??"side-by-side")==="side-by-side",X=!!y[M.path],L=w==="dynamic"&&!X;return e.jsx("div",{className:"flex flex-1 min-h-0 px-3 py-3",children:e.jsx(tf,{fileDiff:x,activeFilePath:W,isDiffLoading:u,diffError:h,onRetry:P,renderSideBySide:z,allowResponsive:L})})};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(eo,{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(ef,{changedFiles:k,selectedFile:d,selectedFileEntry:M,onSelectFile:D}),e.jsx("div",{className:"flex-1"}),M&&E&&e.jsx(Jm,{mode:E==="side-by-side"?"side-by-side":"unified",onModeChange:O=>{if(!M)return;const z=O==="side-by-side"?"side-by-side":"inline";S(M.path,z)}})]}),F()]})},nf=()=>{const{git:r}=Ws(),{currentSessionId:s,sessions:t,worktreeMetadata:n}=pe(),{currentDirectory:o}=ht(),a=s?n.get(s)??void 0:void 0,c=t.find(p=>p.id===s)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:m,fetchStatus:f}=wt(),u=Um(d??null);return l.useEffect(()=>{d&&(m(d),wt.getState().directories.get(d)?.status||f(d,r))},[d,m,f,r]),u},of=()=>{const r=Le(d=>d.setSessionSwitcherOpen),s=Le(d=>d.toggleSidebar),{isMobile:t}=St(),[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(wr,{className:"h-5 w-5"})})})},Aa=()=>{const r=Le(L=>L.setSessionSwitcherOpen),s=Le(L=>L.toggleSidebar),t=Le(L=>L.isSidebarOpen),n=Le(L=>L.sidebarWidth),o=Le(L=>L.activeMainTab),a=Le(L=>L.setActiveMainTab),{getCurrentModel:i}=gt(),c=pe(L=>L.getContextUsage),{isMobile:d}=St(),m=nf(),f=l.useRef(null),[u,p]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),h=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);fe.useEffect(()=>{if(typeof window>"u")return;const L=typeof window.opencodeDesktop<"u";p(L)},[]);const g=i(),x=g&&typeof g.limit=="object"&&g.limit!==null?g.limit:null,v=x&&typeof x.context=="number"?x.context:0,j=x&&typeof x.output=="number"?x.output:0,N=c(v,j),[w,y]=l.useState(!1),S=Le(L=>L.isSessionSwitcherOpen),b=l.useCallback(()=>{if(d){r(!S);return}s()},[d,S,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(()=>u&&h?t?"pl-0":"pl-[8.0rem]":"pl-3",[u,h,t]),k=l.useCallback(()=>{if(typeof document>"u")return;const L=f.current?.getBoundingClientRect().height;L&&document.documentElement.style.setProperty("--oc-header-height",`${L}px`)},[]);fe.useEffect(()=>{if(typeof window>"u")return;k();const L=f.current;if(!L||typeof ResizeObserver>"u")return()=>{};const V=new ResizeObserver(()=>{k()});return V.observe(L),window.addEventListener("resize",k),window.addEventListener("orientationchange",k),()=>{V.disconnect(),window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k)}},[k]),fe.useEffect(()=>{k()},[k,d,w]);const M=l.useCallback(L=>L>=1e6?`${(L/1e6).toFixed(1)}M`:L>=1e3?`${(L/1e3).toFixed(1)}K`:L.toFixed(1).replace(/\.0$/,""),[]),E=l.useCallback(async L=>{if(!L.target.closest("button, a, input, select, textarea")&&L.button===0&&u)try{const{getCurrentWindow:V}=await Js(async()=>{const{getCurrentWindow:ie}=await import("./vendor-.pnpm-BGm12ky3.js").then(we=>we.bM);return{getCurrentWindow:ie}},__vite__mapDeps([1,2]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[u]),P=l.useCallback(async L=>{if(L.button===0&&u)try{const{getCurrentWindow:V}=await Js(async()=>{const{getCurrentWindow:ie}=await import("./vendor-.pnpm-BGm12ky3.js").then(we=>we.bM);return{getCurrentWindow:ie}},__vite__mapDeps([1,2]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[u]),W=l.useMemo(()=>[{id:"chat",label:"Chat",icon:Tc},{id:"diff",label:"Diff",icon:Ms,badge:m>0?m:void 0},{id:"terminal",label:"Terminal",icon:Ds},{id:"git",label:"Git",icon:Et}],[m]);fe.useEffect(()=>{const L=V=>{if((V.metaKey||V.ctrlKey)&&!V.shiftKey&&!V.altKey){const Y=parseInt(V.key,10);Y>=1&&Y<=W.length&&(V.preventDefault(),a(W[Y-1].id))}};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[W,a]);const F=(L,V)=>{const Y=o===L.id,ie=L.icon,we=L.id==="chat",ke=L.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>a(L.id),onMouseDown:Y?P:void 0,className:T("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",Y?"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",Y?"text-foreground":"text-muted-foreground",Y&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",Y&&we&&t&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",we&&!(u&&h&&t)&&"border-l",ke&&"border-r",we&&!d&&"min-w-[165px]"),style:{...Y&&we&&t?{"--sidebar-w":u&&h?`${n}px`:"64px"}:{},...we&&!(u&&h&&t)||ke?{borderColor:"var(--interactive-border)"}:{}},"aria-selected":Y,role:"tab",children:[d?e.jsx(ie,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ie,{size:16}),e.jsx("span",{children:L.label})]}),we&&!d&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(lo,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact"})}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:L.badge})]}),!V&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},L.id)},O=()=>e.jsxs("div",{onMouseDown:E,className:T("app-region-drag relative flex h-12 select-none items-center",D),role:"tablist","aria-label":"Main navigation",children:[!(u&&h)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:b,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(wr,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:W.map((L,V)=>F(L,V===W.length-1))}),e.jsx("div",{className:"flex-1"})]}),z=()=>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:b,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(wr,{className:"h-5 w-5"})}),N&&N.totalTokens>0&&o==="chat"&&e.jsx(lo,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.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:W.map(L=>{const V=o===L.id,Y=L.icon;return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>a(L.id),"aria-label":L.label,"aria-selected":V,role:"tab",className:T(C,V&&"text-foreground"),children:[e.jsx(Y,{className:"h-5 w-5"}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:L.badge})]})}),e.jsx(lt,{children:e.jsx("p",{children:L.label})})]},L.id)})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","aria-expanded":w,"aria-controls":"mobile-header-details",onClick:()=>y(L=>!L),className:"app-region-no-drag h-8 w-8",children:w?e.jsx(wo,{className:"h-4 w-4"}):e.jsx(yt,{className:"h-4 w-4"})})]})]}),w&&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:N&&N.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(N.totalTokens)})]}),e.jsxs("p",{className:"typography-meta",children:["Context limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:M(N.contextLimit)})]}),e.jsxs("p",{className:"typography-meta",children:["Output limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:M(N.outputLimit??0)})]})]})]})})})]}),X=T("header-safe-area border-b relative z-10",u?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:f,className:X,style:{borderColor:"var(--interactive-border)"},children:d?z():O()})};function zo({className:r,...s}){return e.jsx("div",{"data-slot":"card",className:T("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",r),...s})}function al({className:r,...s}){return e.jsx("div",{"data-slot":"card-header",className:T("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",r),...s})}function il({className:r,...s}){return e.jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",r),...s})}function ll({className:r,...s}){return e.jsx("div",{"data-slot":"card-content",className:T("px-6",r),...s})}class qt 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(zo,{className:"w-full max-w-md",children:[e.jsx(al,{className:"text-center",children:e.jsxs(il,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(to,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(ll,{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(Ce,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}const co=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_MOCK_UPDATE__;return r?r===!0?{currentVersion:"1.0.3",newVersion:"1.0.8"}:r:null},Da=r=>({checking:!1,available:!0,downloading:!1,downloaded:!1,info:{available:!0,version:r.newVersion??"99.0.0-test",currentVersion:r.currentVersion??"0.0.0",body:void 0},progress:null,error:null}),Ea=()=>co()!==null,af=(r=!0)=>{const[s,t]=fe.useState({checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null}),[n]=fe.useState(Ea),[o,a]=fe.useState(()=>{if(Ea()){const u=co();return u?Da(u):null}return null}),i=fe.useCallback(async()=>{if(n){const u=co();if(u){const p=Da(u);p.info={...p.info,body:`## [${u.newVersion}] - 2025-01-01
|
|
6
|
+
`):String(r)}const Oo=l.createContext(null),Ws=()=>{const r=l.useContext(Oo);if(!r)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return r},ol=r=>{const s=Ws();return r(s)},Xm=()=>ol(r=>r.runtime.isDesktop),$o=()=>ol(r=>r.runtime.isVSCode),Jm=({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(Ce,{size:"sm",variant:"ghost",className:T("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:n,title:r==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:r==="side-by-side"?e.jsx(Dc,{className:"h-3 w-3"}):e.jsx(Ec,{className:"h-3 w-3"})})},Zm=l.lazy(()=>Js(()=>import("./MonacoDiffViewer-Bfe8kvMD.js"),__vite__mapDeps([0,1,2,3,4])).then(r=>({default:r.MonacoDiffViewer}))),Qm=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]})},ef=l.memo(({changedFiles:r,selectedFile:s,selectedFileEntry:t,onSelectFile:n})=>r.length===0?null:e.jsxs(Lt,{children:[e.jsx(Ot,{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(yt,{className:"size-4 opacity-50"})]})}),e.jsx($t,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Vm,{value:s??"",onValueChange:n,children:r.map(o=>e.jsx(Gm,{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))})})]})),tf=l.memo(({fileDiff:r,activeFilePath:s,isDiffLoading:t,diffError:n,onRetry:o,renderSideBySide:a,allowResponsive:i})=>{const c=l.useMemo(()=>s&&Nn(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(Dt,{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(Ce,{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(Dt,{size:16,className:"animate-spin"}),"Loading diff viewer…"]}),children:e.jsx(Zm,{original:r.original,modified:r.modified,language:c,renderSideBySide:a,allowResponsive:i})})})}),sf=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=pe(),{currentDirectory:n}=ht(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},rf=()=>{const{git:r}=Ws(),s=sf(),t=el(s??null),n=Qi(s??null),o=wt(O=>O.isLoadingStatus),{setActiveDirectory:a,fetchStatus:i,setDiff:c}=wt(),[d,m]=l.useState(null),f=l.useRef(null),[u,p]=l.useState(!1),[h,g]=l.useState(null),[x,v]=l.useState(null),j=Le(O=>O.pendingDiffFile),N=Le(O=>O.setPendingDiffFile),w=Le(O=>O.diffLayoutPreference),y=Le(O=>O.diffFileLayout),S=Le(O=>O.setDiffFileLayout),b=wt(l.useCallback(O=>s?O.directories.get(s)?.lastStatusChange??0:0,[s])),C=l.useCallback((O,z)=>{if(!O)return null;const X=wt.getState().directories.get(O);if(!X)return null;const L=X.diffCache.get(z);return!L||L.fetchedAt<(X.lastStatusChange||0)?null:L},[]),D=l.useCallback(O=>{f.current=O,m(O),g(null);const z=C(s,O);z?(v({original:z.original,modified:z.modified}),p(!1)):(v(null),p(!0))},[s,C]);l.useEffect(()=>{s&&(a(s),wt.getState().directories.get(s)?.status||i(s,r))},[s,a,i,r]),l.useEffect(()=>{j&&(D(j),N(null))},[j,D,N]),l.useEffect(()=>{f.current=d},[d]);const k=l.useMemo(()=>{if(!n?.files)return[];const O=n.diffStats??{};return n.files.map(z=>({...z,insertions:O[z.path]?.insertions??0,deletions:O[z.path]?.deletions??0,isNew:Qm(z)})).sort((z,X)=>z.path.localeCompare(X.path))},[n]),M=l.useMemo(()=>d?k.find(O=>O.path===d)??null:null,[k,d]),E=l.useMemo(()=>{if(!M)return null;const O=y[M.path];return O||(w==="inline"||w==="side-by-side"?w:M.isNew?"inline":"side-by-side")},[M,y,w]);l.useEffect(()=>{if(!d&&!j&&k.length>0){const O=k[0].path;D(O)}},[k,d,j,D]),l.useEffect(()=>{d&&k.length>0&&(k.some(z=>z.path===d)||(m(null),f.current=null,v(null),g(null)))},[k,d]);const P=l.useCallback(async()=>{if(!s||!M){v(null),g(null),p(!1);return}const O=M.path,z=C(s,O);if(z){v({original:z.original,modified:z.modified}),g(null),p(!1);return}p(!0),g(null);try{const X=await r.getGitFileDiff(s,{path:M.path}),L={original:X.original??"",modified:X.modified??""};c(s,O,L),v(L)}catch(X){const L=X instanceof Error?X.message:"Failed to load diff";g(L),he.error(L)}finally{p(!1)}},[s,r,M,C,c,b]);l.useEffect(()=>{P()},[P]);const W=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(Dt,{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 z=(E??"side-by-side")==="side-by-side",X=!!y[M.path],L=w==="dynamic"&&!X;return e.jsx("div",{className:"flex flex-1 min-h-0 px-3 py-3",children:e.jsx(tf,{fileDiff:x,activeFilePath:W,isDiffLoading:u,diffError:h,onRetry:P,renderSideBySide:z,allowResponsive:L})})};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(eo,{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(ef,{changedFiles:k,selectedFile:d,selectedFileEntry:M,onSelectFile:D}),e.jsx("div",{className:"flex-1"}),M&&E&&e.jsx(Jm,{mode:E==="side-by-side"?"side-by-side":"unified",onModeChange:O=>{if(!M)return;const z=O==="side-by-side"?"side-by-side":"inline";S(M.path,z)}})]}),F()]})},nf=()=>{const{git:r}=Ws(),{currentSessionId:s,sessions:t,worktreeMetadata:n}=pe(),{currentDirectory:o}=ht(),a=s?n.get(s)??void 0:void 0,c=t.find(p=>p.id===s)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:m,fetchStatus:f}=wt(),u=Um(d??null);return l.useEffect(()=>{d&&(m(d),wt.getState().directories.get(d)?.status||f(d,r))},[d,m,f,r]),u},of=()=>{const r=Le(d=>d.setSessionSwitcherOpen),s=Le(d=>d.toggleSidebar),{isMobile:t}=St(),[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(wr,{className:"h-5 w-5"})})})},Aa=()=>{const r=Le(L=>L.setSessionSwitcherOpen),s=Le(L=>L.toggleSidebar),t=Le(L=>L.isSidebarOpen),n=Le(L=>L.sidebarWidth),o=Le(L=>L.activeMainTab),a=Le(L=>L.setActiveMainTab),{getCurrentModel:i}=gt(),c=pe(L=>L.getContextUsage),{isMobile:d}=St(),m=nf(),f=l.useRef(null),[u,p]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),h=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);fe.useEffect(()=>{if(typeof window>"u")return;const L=typeof window.opencodeDesktop<"u";p(L)},[]);const g=i(),x=g&&typeof g.limit=="object"&&g.limit!==null?g.limit:null,v=x&&typeof x.context=="number"?x.context:0,j=x&&typeof x.output=="number"?x.output:0,N=c(v,j),[w,y]=l.useState(!1),S=Le(L=>L.isSessionSwitcherOpen),b=l.useCallback(()=>{if(d){r(!S);return}s()},[d,S,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(()=>u&&h?t?"pl-0":"pl-[8.0rem]":"pl-3",[u,h,t]),k=l.useCallback(()=>{if(typeof document>"u")return;const L=f.current?.getBoundingClientRect().height;L&&document.documentElement.style.setProperty("--oc-header-height",`${L}px`)},[]);fe.useEffect(()=>{if(typeof window>"u")return;k();const L=f.current;if(!L||typeof ResizeObserver>"u")return()=>{};const V=new ResizeObserver(()=>{k()});return V.observe(L),window.addEventListener("resize",k),window.addEventListener("orientationchange",k),()=>{V.disconnect(),window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k)}},[k]),fe.useEffect(()=>{k()},[k,d,w]);const M=l.useCallback(L=>L>=1e6?`${(L/1e6).toFixed(1)}M`:L>=1e3?`${(L/1e3).toFixed(1)}K`:L.toFixed(1).replace(/\.0$/,""),[]),E=l.useCallback(async L=>{if(!L.target.closest("button, a, input, select, textarea")&&L.button===0&&u)try{const{getCurrentWindow:V}=await Js(async()=>{const{getCurrentWindow:ie}=await import("./vendor-.pnpm-BGm12ky3.js").then(we=>we.bM);return{getCurrentWindow:ie}},__vite__mapDeps([1,2]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[u]),P=l.useCallback(async L=>{if(L.button===0&&u)try{const{getCurrentWindow:V}=await Js(async()=>{const{getCurrentWindow:ie}=await import("./vendor-.pnpm-BGm12ky3.js").then(we=>we.bM);return{getCurrentWindow:ie}},__vite__mapDeps([1,2]));await V().startDragging()}catch(V){console.error("Failed to start window dragging:",V)}},[u]),W=l.useMemo(()=>[{id:"chat",label:"Chat",icon:Tc},{id:"diff",label:"Diff",icon:Ms,badge:m>0?m:void 0},{id:"terminal",label:"Terminal",icon:Ds},{id:"git",label:"Git",icon:Et}],[m]);fe.useEffect(()=>{const L=V=>{if((V.metaKey||V.ctrlKey)&&!V.shiftKey&&!V.altKey){const Y=parseInt(V.key,10);Y>=1&&Y<=W.length&&(V.preventDefault(),a(W[Y-1].id))}};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[W,a]);const F=(L,V)=>{const Y=o===L.id,ie=L.icon,we=L.id==="chat",ke=L.id==="git";return e.jsxs(l.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>a(L.id),onMouseDown:Y?P:void 0,className:T("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",Y?"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",Y?"text-foreground":"text-muted-foreground",Y&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",Y&&we&&t&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",we&&!(u&&h&&t)&&"border-l",ke&&"border-r",we&&!d&&"min-w-[165px]"),style:{...Y&&we&&t?{"--sidebar-w":u&&h?`${n}px`:"64px"}:{},...we&&!(u&&h&&t)||ke?{borderColor:"var(--interactive-border)"}:{}},"aria-selected":Y,role:"tab",children:[d?e.jsx(ie,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ie,{size:16}),e.jsx("span",{children:L.label})]}),we&&!d&&N&&N.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(lo,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.outputLimit??0,size:"compact"})}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:L.badge})]}),!V&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},L.id)},O=()=>e.jsxs("div",{onMouseDown:E,className:T("app-region-drag relative flex h-12 select-none items-center",D),role:"tablist","aria-label":"Main navigation",children:[!(u&&h)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:b,"aria-label":"Open sessions",className:`${C} mr-2.5`,children:e.jsx(wr,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:W.map((L,V)=>F(L,V===W.length-1))}),e.jsx("div",{className:"flex-1"})]}),z=()=>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:b,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(wr,{className:"h-5 w-5"})}),N&&N.totalTokens>0&&o==="chat"&&e.jsx(lo,{totalTokens:N.totalTokens,percentage:N.percentage,contextLimit:N.contextLimit,outputLimit:N.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:W.map(L=>{const V=o===L.id,Y=L.icon;return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>a(L.id),"aria-label":L.label,"aria-selected":V,role:"tab",className:T(C,V&&"text-foreground"),children:[e.jsx(Y,{className:"h-5 w-5"}),L.badge!==void 0&&L.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:L.badge})]})}),e.jsx(lt,{children:e.jsx("p",{children:L.label})})]},L.id)})}),e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","aria-expanded":w,"aria-controls":"mobile-header-details",onClick:()=>y(L=>!L),className:"app-region-no-drag h-8 w-8",children:w?e.jsx(wo,{className:"h-4 w-4"}):e.jsx(yt,{className:"h-4 w-4"})})]})]}),w&&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:N&&N.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(N.totalTokens)})]}),e.jsxs("p",{className:"typography-meta",children:["Context limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:M(N.contextLimit)})]}),e.jsxs("p",{className:"typography-meta",children:["Output limit: ",e.jsx("span",{className:"font-semibold text-foreground",children:M(N.outputLimit??0)})]})]})]})})})]}),X=T("header-safe-area border-b relative z-10",u?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:f,className:X,style:{borderColor:"var(--interactive-border)"},children:d?z():O()})};function zo({className:r,...s}){return e.jsx("div",{"data-slot":"card",className:T("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",r),...s})}function al({className:r,...s}){return e.jsx("div",{"data-slot":"card-header",className:T("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",r),...s})}function il({className:r,...s}){return e.jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",r),...s})}function ll({className:r,...s}){return e.jsx("div",{"data-slot":"card-content",className:T("px-6",r),...s})}class qt 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(zo,{className:"w-full max-w-md",children:[e.jsx(al,{className:"text-center",children:e.jsxs(il,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(to,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(ll,{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(Ce,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(er,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}const co=()=>{if(typeof window>"u")return null;const r=window.__OPENCHAMBER_MOCK_UPDATE__;return r?r===!0?{currentVersion:"1.0.3",newVersion:"1.0.8"}:r:null},Da=r=>({checking:!1,available:!0,downloading:!1,downloaded:!1,info:{available:!0,version:r.newVersion??"99.0.0-test",currentVersion:r.currentVersion??"0.0.0",body:void 0},progress:null,error:null}),Ea=()=>co()!==null,af=(r=!0)=>{const[s,t]=fe.useState({checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null}),[n]=fe.useState(Ea),[o,a]=fe.useState(()=>{if(Ea()){const u=co();return u?Da(u):null}return null}),i=fe.useCallback(async()=>{if(n){const u=co();if(u){const p=Da(u);p.info={...p.info,body:`## [${u.newVersion}] - 2025-01-01
|
|
7
7
|
- Mock update for UI testing`},a(p)}return}if(_t()){t(u=>({...u,checking:!0,error:null}));try{const u=await du();t(p=>({...p,checking:!1,available:u?.available??!1,info:u}))}catch(u){t(p=>({...p,checking:!1,error:u instanceof Error?u.message:"Failed to check for updates"}))}}},[n]),c=fe.useCallback(async()=>{if(n){a(h=>h&&{...h,downloading:!0});let u=0;const p=setInterval(()=>{u+=20,a(h=>h&&{...h,progress:{downloaded:u*1e3,total:1e5}}),u>=100&&(clearInterval(p),a(h=>h&&{...h,downloading:!1,downloaded:!0,progress:null}))},500);return}if(!(!_t()||!s.available)){t(u=>({...u,downloading:!0,error:null,progress:null}));try{await uu(u=>{t(p=>({...p,progress:u}))}),t(u=>({...u,downloading:!1,downloaded:!0}))}catch(u){t(p=>({...p,downloading:!1,error:u instanceof Error?u.message:"Failed to download update"}))}}},[n,s.available]),d=fe.useCallback(async()=>{if(!n&&!(!_t()||!s.downloaded))try{await mu()}catch(u){t(p=>({...p,error:u instanceof Error?u.message:"Failed to restart"}))}},[n,s.downloaded]),m=fe.useCallback(()=>{if(n){a(null);return}t(u=>({...u,available:!1,downloaded:!1,info:null}))},[n]);return fe.useEffect(()=>{if(r&&(_t()||n)){const u=setTimeout(()=>{i()},3e3);return()=>clearTimeout(u)}},[r,i,n]),{...n&&o?o:s,checkForUpdates:i,downloadUpdate:c,restartToUpdate:d,dismiss:m}};let Lr=0;function gs({...r}){return e.jsx(Ic,{"data-slot":"dialog",...r})}function cl({...r}){return e.jsx(Oc,{"data-slot":"dialog-trigger",...r})}function lf({...r}){return e.jsx(Fc,{"data-slot":"dialog-portal",...r})}const dl=fe.forwardRef(({className:r,...s},t)=>(fe.useEffect(()=>(Lr+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Lr=Math.max(0,Lr-1),Lr===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Ni,{ref:t,"data-slot":"dialog-overlay",className:T("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",r),...s})));dl.displayName=Ni.displayName;function xs({className:r,children:s,showCloseButton:t=!0,...n}){return e.jsxs(lf,{"data-slot":"dialog-portal",children:[e.jsx(dl,{className:"rounded-none"}),e.jsxs(Pc,{"data-slot":"dialog-content",className:T("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",r),...n,children:[s,t&&e.jsxs(Rc,{"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(ss,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function ys({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-header",className:T("flex flex-col gap-2 text-center sm:text-left",r),...s})}function Cr({className:r,...s}){return e.jsx("div",{"data-slot":"dialog-footer",className:T("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",r),...s})}function bs({className:r,...s}){return e.jsx(_c,{"data-slot":"dialog-title",className:T("typography-markdown leading-none font-semibold text-foreground",r),...s})}function Us({className:r,...s}){return e.jsx(Lc,{"data-slot":"dialog-description",className:T("text-muted-foreground typography-ui-label",r),...s})}const Bo=({containerRef:r,minThumbSize:s=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=l.useState(!1),[c,d]=l.useState({length:0,offset:0}),[m,f]=l.useState({length:0,offset:0}),u=l.useRef(null),p=l.useRef(null),h=l.useRef(!1),g=l.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),x=l.useRef(null),v=l.useCallback(()=>{const k=r.current;if(!k)return;const{scrollHeight:M,clientHeight:E,scrollTop:P,scrollWidth:W,clientWidth:F,scrollLeft:O}=k,z=8;if(M>E){const X=Math.max(E-z*2,0),L=E/M*X,V=Math.max(s,Math.min(X,L)),Y=Math.max(X-V,0),ie=Math.max(M-E,1),we=P/ie*Y;d({length:V,offset:we})}else d({length:0,offset:0});if(!o&&W>F){const X=Math.max(F-z*2,0),L=F/W*X,V=Math.max(s,Math.min(X,L)),Y=Math.max(X-V,0),ie=Math.max(W-F,1),we=O/ie*Y;f({length:V,offset:we})}else f({length:0,offset:0})},[r,s,o]),j=l.useCallback(()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>i(!1),t)},[t]),N=l.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{v(),i(!0),j()})},[j,v]);l.useEffect(()=>{const k=r.current;if(!k)return;v(),i(!0),j(),k.addEventListener("scroll",N,{passive:!0});const M=typeof ResizeObserver<"u"?new ResizeObserver(()=>v()):null;M?.observe(k);const E=typeof MutationObserver<"u"?new MutationObserver(()=>v()):null;return E?.observe(k,{childList:!0,subtree:!0,characterData:!0}),()=>{k.removeEventListener("scroll",N),M?.disconnect(),E?.disconnect(),u.current&&clearTimeout(u.current),p.current&&cancelAnimationFrame(p.current)}},[r,N,j,v]);const w=(k,M)=>{const E=r.current;E&&(h.current=!0,g.current={pointerX:k.clientX,pointerY:k.clientY,scrollTop:E.scrollTop,scrollLeft:E.scrollLeft},x.current=M,i(!0),u.current&&clearTimeout(u.current),k.currentTarget.setPointerCapture(k.pointerId))},y=k=>{if(!h.current)return;const M=r.current;if(!M)return;const E=x.current;if(E==="vertical"){const{pointerY:P,scrollTop:W}=g.current,F=k.clientY-P,O=M.clientHeight,z=Math.max(O-c.length,1),X=Math.max(M.scrollHeight-M.clientHeight,1),L=F/z*X;M.scrollTop=W+L}else if(E==="horizontal"){const{pointerX:P,scrollLeft:W}=g.current,F=k.clientX-P,O=M.clientWidth,z=Math.max(O-m.length,1),X=Math.max(M.scrollWidth-M.clientWidth,1),L=F/z*X;M.scrollLeft=W+L}},S=k=>{h.current&&(h.current=!1,k.currentTarget.releasePointerCapture(k.pointerId),j())},b=c.length>0,C=m.length>0;if(!b&&!C)return null;const D=8;return e.jsxs("div",{className:T("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[b&&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=>w(k,"vertical"),onPointerMove:y,onPointerUp:S,onPointerCancel:S}),C&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${m.length}px`,left:`${D+m.offset}px`,bottom:`${D/2}px`},onPointerDown:k=>w(k,"horizontal"),onPointerMove:y,onPointerUp:S,onPointerCancel:S})]})},Je=l.forwardRef(({className:r,outerClassName:s,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:m=!0,...f},u)=>{const p=l.useRef(null);return l.useImperativeHandle(u,()=>p.current,[]),e.jsxs("div",{className:T("relative flex flex-col min-h-0 w-full overflow-hidden",s),children:[e.jsx(i,{ref:p,className:T("overlay-scrollbar-target overlay-scrollbar-container",m?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",r),style:n,...f,children:t}),e.jsx(Bo,{containerRef:p,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});Je.displayName="ScrollableOverlay";const Ta="https://github.com/btriapitsyn/openchamber/releases",cf=({open:r,onOpenChange:s,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:c,onRestart:d})=>{const m=t?.version?`${Ta}/tag/v${t.version}`:Ta,f=a?.total?Math.round(a.downloaded/a.total*100):0;return e.jsx(gs,{open:r,onOpenChange:s,children:e.jsxs(xs,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx($c,{className:"h-5 w-5 text-primary"}),"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(t?.currentVersion||t?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t?.currentVersion&&e.jsx("span",{className:"font-mono",children:t.currentVersion}),t?.currentVersion&&t?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),t?.version&&e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),t?.body&&e.jsx(Je,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.replace(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm,`— v$1 —
|
|
8
8
|
`).replace(/^- /gm,"• ").trim()})}),n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[f,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${f}%`}})})]}),i&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:i})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:m,target:"_blank",rel:"noopener noreferrer",className:T("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(so,{className:"h-4 w-4"}),"GitHub"]}),!o&&!n&&e.jsxs("button",{onClick:c,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(vo,{className:"h-4 w-4"}),"Download Update"]}),n&&e.jsxs("button",{disabled:!0,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(zc,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),o&&e.jsxs("button",{onClick:d,className:T("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(er,{className:"h-4 w-4"}),"Restart to Update"]})]})]})]})})},hn=264,Ia=200,Pa=500,df=40,uf=({isOpen:r,isMobile:s,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a}=Le(),[i,c]=l.useState(!1),d=l.useRef(0),m=l.useRef(n||hn),[f,u]=l.useState(!1),p=af(),[h,g]=l.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);l.useEffect(()=>{if(typeof window>"u")return;const y=typeof window.opencodeDesktop<"u";g(y)},[]),l.useEffect(()=>{if(s||!i)return;const y=b=>{const C=b.clientX-d.current,D=Math.min(Pa,Math.max(Ia,m.current+C));o(D)},S=()=>{c(!1)};return window.addEventListener("pointermove",y),window.addEventListener("pointerup",S,{once:!0}),()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",S)}},[s,i,o]),l.useEffect(()=>{s&&i&&c(!1)},[s,i]);const v=l.useCallback(async y=>{if(y.button===0&&h)try{const{getCurrentWindow:S}=await Js(async()=>{const{getCurrentWindow:C}=await import("./vendor-.pnpm-BGm12ky3.js").then(D=>D.bM);return{getCurrentWindow:C}},__vite__mapDeps([1,2]));await S().startDragging()}catch(S){console.error("Failed to start window dragging from sidebar:",S)}},[h]);if(s)return null;const j=r?Math.min(Pa,Math.max(Ia,n||hn)):0,N=h&&x,w=y=>{r&&(c(!0),d.current=y.clientX,m.current=j,y.preventDefault())};return e.jsxs("aside",{className:T("relative flex h-full overflow-hidden border-r",h?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",i?"transition-none":"",!r&&"border-r-0"),style:{width:`${j}px`,minWidth:`${j}px`,maxWidth:`${j}px`,pointerEvents:r?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!r||j===0,children:[r&&e.jsx("div",{className:T("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",i?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:w,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:T("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!r&&"pointer-events-none select-none opacity-0"),style:{width:`${j}px`,overflowX:"hidden"},"aria-hidden":!r,children:[N&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${df}px`},onMouseDown:v,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(qt,{children:t})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:T("flex items-center gap-2 rounded-md px-3 py-2","text-sm font-semibold text-muted-foreground","hover:text-foreground","transition-colors"),children:[e.jsx(tn,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),(p.available||p.downloaded)&&e.jsxs("button",{onClick:()=>u(!0),className:T("flex items-center gap-1.5 rounded-md px-2.5 py-1.5","text-xs font-medium","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(vo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]})]})}),e.jsx(cf,{open:f,onOpenChange:u,info:p.info,downloading:p.downloading,downloaded:p.downloaded,progress:p.progress,error:p.error,onDownload:p.downloadUpdate,onRestart:p.restartToUpdate})]})]})},ul=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:jo},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:bn},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:tr},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Et},{id:"settings",label:"Appearance",description:"Fine-tune themes, fonts, and typography across the interface.",icon:Bc}],mf={},ml={},fl={};ul.forEach(r=>{mf[r.id]=r.label,ml[r.id]=r.description,fl[r.id]=r});const Ra=ml,ff=fl;function js({className:r,variant:s,...t}){return e.jsx(Ce,{variant:s,size:"sm",className:T("h-7 px-2 py-0",r),...t})}function vt({className:r,type:s,...t}){return e.jsx("input",{type:s,"data-slot":"input",className:T("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",r),...t})}const pf=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedAgentName:o,agents:a,setSelectedAgent:i,deleteAgent:c,loadAgents:d}=sr(),{setSidebarOpen:m}=Le(),{isMobile:f}=St();l.useEffect(()=>{d()},[d]);const u=()=>{if(!r.trim()){he.error("Agent name is required");return}if(a.some(j=>j.name===r)){he.error("An agent with this name already exists");return}i(r),s(""),n(!1),f&&m(!1)},p=async j=>{if(j.builtIn){he.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${j.name}"?`)&&(await c(j.name)?he.success(`Agent "${j.name}" deleted successfully`):he.error("Failed to delete agent"))},h=j=>{const N=j.name;let w=1,y=`${N} Copy`;for(;a.some(S=>S.name===y);)w++,y=`${N} Copy ${w}`;i(y),n(!1),f&&m(!1)},g=j=>{switch(j){case"primary":return e.jsx(vr,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Ci,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(ki,{className:"h-3 w-3 text-primary"});default:return null}},x=a.filter(j=>j.builtIn),v=a.filter(j=>!j.builtIn);return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(gs,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",f?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Agents"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.length}),e.jsx(cl,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(Yt,{className:"size-4"})})})]})]})}),e.jsx(Je,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:a.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(sn,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[x.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),x.map(j=>e.jsx(Fa,{agent:j,isSelected:o===j.name,onSelect:()=>{i(j.name),f&&m(!1)},onDuplicate:()=>h(j),getAgentModeIcon:g},j.name))]}),v.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"}),v.map(j=>e.jsx(Fa,{agent:j,isSelected:o===j.name,onSelect:()=>{i(j.name),f&&m(!1)},onDelete:()=>p(j),onDuplicate:()=>h(j),getAgentModeIcon:g},j.name))]})]})}),e.jsxs(xs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Create New Agent"}),e.jsx(Us,{children:"Enter a unique name for your new agent"})]}),e.jsx(vt,{value:r,onChange:j=>s(j.target.value),placeholder:"Agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:j=>{j.key==="Enter"&&u()}}),e.jsxs(Cr,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(js,{onClick:u,children:"Create"})]})]})]})})},Fa=({agent:r,isSelected:s,onSelect:t,onDelete:n,onDuplicate:o,getAgentModeIcon:a})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:T("typography-ui-label font-medium truncate",s?"text-primary":"text-foreground hover:text-primary/80"),children:r.name}),a(r.mode)]}),r.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.description})]}),e.jsxs(Lt,{children:[e.jsx(Ot,{asChild:!0,children:e.jsx(Ce,{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(wn,{className:"h-3.5 w-3.5"})})}),e.jsxs($t,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(xt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(ws,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),!r.builtIn&&n&&e.jsxs(xt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})});function yr({className:r,variant:s,...t}){return e.jsx(Ce,{variant:s,size:"sm",className:T("h-6 px-2 text-xs",r),...t})}const Bs=fe.forwardRef(({className:r,...s},t)=>e.jsx(Je,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:T("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",r),...s}));Bs.displayName="Textarea";const _a="mobile-overlay-root",hf=()=>{if(typeof document>"u")return null;let r=document.getElementById(_a);return r||(r=document.createElement("div"),r.id=_a,document.body.appendChild(r)),r},Wt=({open:r,title:s,onClose:t,children:n,footer:o,className:a,renderHeader:i})=>{const c=l.useRef(null);if(typeof document<"u"&&!c.current&&(c.current=hf()),l.useEffect(()=>{if(!r)return;const m=document.body.style.overflow;document.body.style.overflow="hidden";const f=u=>{u.key==="Escape"&&t()};return document.addEventListener("keydown",f),()=>{document.body.style.overflow=m,document.removeEventListener("keydown",f)}},[r,t]),!r||!c.current)return null;const d=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:T("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),onClick:m=>m.stopPropagation(),children:[(()=>{const m=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(ss,{className:"h-4 w-4"})});return i?i(m):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:s}),m]})})(),e.jsx(Je,{outerClassName:"max-h-[min(70vh,520px)]",className:"px-2 py-2 pwa-overlay-scroll",children:n}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return Hc.createPortal(d,c.current)},gf="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",xf="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",yf=Object.assign({"../assets/provider-logos/gocode.svg":gf,"../assets/provider-logos/kimi-for-coding.svg":xf}),uo=new Map;for(const[r,s]of Object.entries(yf)){const t=r.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&s&&uo.set(t[1].toLowerCase(),s)}function pl(r){const s=r?.toLowerCase()??null,t=s?uo.has(s):!1,n=s?uo.get(s)??null:null,[o,a]=fe.useState(t?"local":"remote");fe.useEffect(()=>{a(t?"local":"remote")},[t,s]);const i=fe.useCallback(()=>{a(c=>c==="local"&&t?"remote":"none")},[t]);return s?o==="local"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${s}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const es=({providerId:r,alt:s,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=pl(r),c=l.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:s||`${r} logo`,className:T("dark:invert",t),onError:c})},hl=({providerId:r,modelId:s,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=gt(),i=Le(w=>w.isMobile),{isMobile:c}=St(),d=i||c,[m,f]=l.useState(!1),[u,p]=l.useState(new Set),h=()=>f(!1),g=w=>{p(y=>{const S=new Set(y);return S.has(w)?S.delete(w):S.add(w),S})},x=w=>{const y=w?.name||w?.id||"",S=String(y);return S.length>40?S.substring(0,37)+"...":S},v=(w,y)=>{const S=`${w}/${y}`;return a.get(S)},j=(w,y)=>{t(w,y)},N=()=>d?e.jsx(Wt,{open:m,onClose:h,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[o.map(w=>{const y=Array.isArray(w.models)?w.models:[];if(y.length===0)return null;const S=w.id===r,b=u.has(w.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(w.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(es,{providerId:w.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:w.name}),S&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),b?e.jsx(yt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(ps,{className:"h-3 w-3 text-muted-foreground"})]}),b&&e.jsx("div",{className:"border-t border-border/20",children:y.map(C=>{const D=w.id===r&&C.id===s,k=v(w.id,C.id);return e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",D?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{j(w.id,C.id),h()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:x(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)})})]},w.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{j("",""),h()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[d?e.jsxs("button",{type:"button",onClick:()=>f(!0),className:T("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(es,{providerId:r,className:"h-3.5 w-3.5"}):e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:r&&s?`${r}/${s}`:"Select model..."})]}),e.jsx(yt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Lt,{children:[e.jsx(Ot,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",n),children:[r?e.jsxs(e.Fragment,{children:[e.jsx(es,{providerId:r,className:"h-3 w-3 flex-shrink-0"}),e.jsx(ds,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(ds,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:r&&s?`${r}/${s}`:"Not selected"}),e.jsx(yt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs($t,{className:"max-w-[300px]",children:[o.map(w=>{const y=Array.isArray(w.models)?w.models:[];return y.length===0?e.jsxs(xt,{disabled:!0,className:"typography-meta text-muted-foreground",children:[e.jsx(es,{providerId:w.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),w.name," (No models)"]},w.id):e.jsxs(tl,{children:[e.jsxs(sl,{className:"typography-meta",children:[e.jsx(es,{providerId:w.id,className:"h-3 w-3 flex-shrink-0 mr-2"}),w.name]}),e.jsx(rl,{className:"max-h-[320px] min-w-[200px]",sideOffset:2,collisionPadding:8,avoidCollisions:!0,children:e.jsx(Je,{outerClassName:"max-h-[320px] min-w-[200px]",className:"space-y-1 p-1",children:y.map(S=>{const b=v(w.id,S.id);return e.jsx(xt,{className:"typography-meta",onSelect:()=>{j(w.id,S.id)},children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium",children:x(S)}),typeof b?.description=="string"&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:b.description})]})},S.id)})})})]},w.id)}),e.jsx(xt,{className:"typography-meta",onSelect:()=>j("",""),children:e.jsx("span",{className:"text-muted-foreground",children:"No model (optional)"})})]})]}),N()]})},bf=()=>{const{tools:r}=Ws(),[s,t]=l.useState([]),[n,o]=l.useState(!0),[a,i]=l.useState(null);return l.useEffect(()=>{let c=!1;return(async()=>{o(!0),i(null);try{const m=await r.getAvailableTools();if(c)return;t(m)}catch(m){if(c)return;const f=m instanceof Error?m.message:"Failed to fetch tools";console.error("Failed to fetch available tools:",f),i(f),t([])}finally{c||o(!1)}})(),()=>{c=!0}},[r]),{tools:s,isLoading:n,error:a}},wf=()=>{const{selectedAgentName:r,getAgentByName:s,createAgent:t,updateAgent:n,agents:o}=sr();gt();const{tools:a}=bf(),i=r?s(r):null,c=r&&!i,[d,m]=l.useState(""),[f,u]=l.useState(""),[p,h]=l.useState("subagent"),[g,x]=l.useState(""),[v,j]=l.useState(void 0),[N,w]=l.useState(void 0),[y,S]=l.useState(""),[b,C]=l.useState({}),[D,k]=l.useState("allow"),[M,E]=l.useState("allow"),[P,W]=l.useState("ask"),[F,O]=l.useState(!1);l.useEffect(()=>{if(c)m(r||""),u(""),h("subagent"),x(""),j(void 0),w(void 0),S(""),C({}),k("allow"),E("allow"),W("ask");else if(i&&(m(i.name),u(i.description||""),h(i.mode||"subagent"),i.model?.providerID&&i.model?.modelID?x(`${i.model.providerID}/${i.model.modelID}`):x(""),j(i.temperature),w(i.topP),S(i.prompt||""),C(i.tools||{}),i.permission)){const V=i.permission.edit;(V==="allow"||V==="ask"||V==="deny"||V==="full")&&k(V),i.permission.webfetch&&E(i.permission.webfetch),typeof i.permission.bash=="string"&&W(i.permission.bash)}},[i,c,r,o]);const z=async()=>{if(!d.trim()){he.error("Agent name is required");return}O(!0);try{const V=g.trim(),Y={name:d.trim(),description:f.trim()||void 0,mode:p,model:V===""?null:V,temperature:v,top_p:N,prompt:y.trim()||void 0,tools:Object.keys(b).length>0?b:void 0,permission:{edit:D,webfetch:M,bash:P}};let ie;c?ie=await t(Y):ie=await n(d,Y),ie?he.success(c?"Agent created successfully":"Agent updated successfully"):he.error(c?"Failed to create agent":"Failed to update agent")}catch(V){console.error("Error saving agent:",V),he.error("An error occurred while saving")}finally{O(!1)}},X=V=>{C(Y=>({...Y,[V]:!Y[V]}))},L=V=>{const Y={};a.forEach(ie=>{Y[ie]=V}),C(Y)};return r?e.jsxs(Je,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:c?"New Agent":d})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name"}),e.jsx(vt,{value:d,onChange:V=>m(V.target.value),placeholder:"my-agent",disabled:!c})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Bs,{value:f,onChange:V=>u(V.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(yr,{variant:p==="primary"?"default":"outline",onClick:()=>h("primary"),className:T("gap-2",p==="primary"?void 0:"text-foreground"),children:[e.jsx(vr,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(yr,{variant:p==="subagent"?"default":"outline",onClick:()=>h("subagent"),className:T("gap-2",p==="subagent"?void 0:"text-foreground"),children:[e.jsx(ki,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(yr,{variant:p==="all"?"default":"outline",onClick:()=>h("all"),className:T("gap-2",p==="all"?void 0:"text-foreground"),children:[e.jsx(Ci,{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(hl,{providerId:g?g.split("/")[0]:"",modelId:g?g.split("/")[1]:"",onChange:(V,Y)=>{x(V&&Y?`${V}/${Y}`:"")}})]}),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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ht,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Controls randomness in responses.",e.jsx("br",{}),"Higher values make output more creative and unpredictable,",e.jsx("br",{}),"lower values make it more focused and deterministic."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const Y=Math.max(0,(v!==void 0?v:.7)-.1);j(parseFloat(Y.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(Xo,{className:"h-3.5 w-3.5"})}),e.jsx(vt,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:V=>{const Y=V.target.value;if(Y===""){j(void 0);return}const ie=parseFloat(Y);!isNaN(ie)&&ie>=0&&ie<=2&&j(ie)},onBlur:V=>{const Y=V.target.value;if(Y!==""){const ie=parseFloat(Y);if(!isNaN(ie)){const we=Math.max(0,Math.min(2,ie));j(parseFloat(we.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 Y=Math.min(2,(v!==void 0?v:.7)+.1);j(parseFloat(Y.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(Yt,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ht,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["Controls diversity via nucleus sampling.",e.jsx("br",{}),"Lower values focus on most likely tokens,",e.jsx("br",{}),"higher values consider more possibilities."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const Y=Math.max(0,(N!==void 0?N:.9)-.1);w(parseFloat(Y.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(Xo,{className:"h-3.5 w-3.5"})}),e.jsx(vt,{type:"text",inputMode:"decimal",value:N!==void 0?N:"",onChange:V=>{const Y=V.target.value;if(Y===""){w(void 0);return}const ie=parseFloat(Y);!isNaN(ie)&&ie>=0&&ie<=1&&w(ie)},onBlur:V=>{const Y=V.target.value;if(Y!==""){const ie=parseFloat(Y);if(!isNaN(ie)){const we=Math.max(0,Math.min(1,ie));w(parseFloat(we.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 Y=Math.min(1,(N!==void 0?N:.9)+.1);w(parseFloat(Y.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(Yt,{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(Bs,{value:y,onChange:V=>S(V.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Available Tools"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select tools this agent can access"})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ce,{variant:"outline",size:"sm",onClick:()=>L(!0),className:"h-6 px-2 text-xs",children:"Enable All"}),e.jsx(Ce,{variant:"outline",size:"sm",onClick:()=>L(!1),className:"h-6 px-2 text-xs",children:"Disable All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(V=>e.jsx("button",{type:"button",onClick:()=>X(V),className:T("h-6 px-2 rounded-lg border text-[13px] cursor-pointer transition-colors",b[V]?"bg-primary border-primary text-primary-foreground":"border-border/40 bg-sidebar/30 text-foreground hover:bg-sidebar/50"),children:V},V))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure permission levels for different operations"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Edit Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ce,{size:"sm",variant:D==="full"?"default":"outline",onClick:()=>k("full"),className:"h-6 px-2 text-xs",children:"Full"}),e.jsx(Ce,{size:"sm",variant:D==="allow"?"default":"outline",onClick:()=>k("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ce,{size:"sm",variant:D==="ask"?"default":"outline",onClick:()=>k("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ce,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ht,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Full:"})," Auto-approves all tool requests"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Allows file editing with standard checks"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompts for confirmation before editing"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Blocks all file editing operations"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Bash Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ce,{size:"sm",variant:P==="allow"?"default":"outline",onClick:()=>W("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ce,{size:"sm",variant:P==="ask"?"default":"outline",onClick:()=>W("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ce,{size:"sm",variant:P==="deny"?"default":"outline",onClick:()=>W("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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ht,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run bash commands without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before execution"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all bash command execution"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"WebFetch Permission"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ce,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>E("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ce,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>E("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ce,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ht,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Fetch web content without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation before fetching"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block all web content access"]})]})})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ce,{size:"sm",variant:"default",onClick:z,disabled:F,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(So,{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(sn,{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"})]})})},vf=()=>{const[r,s]=l.useState(""),[t,n]=l.useState(!1),{selectedCommandName:o,commands:a,setSelectedCommand:i,deleteCommand:c,loadCommands:d}=rr(),{setSidebarOpen:m}=Le(),{isMobile:f}=St();l.useEffect(()=>{d()},[d]);const u=()=>{if(!r.trim()){he.error("Command name is required");return}const g=r.trim().replace(/\s+/g,"-");if(a.some(x=>x.name===g)){he.error("A command with this name already exists");return}i(g),s(""),n(!1),f&&m(!1)},p=async g=>{window.confirm(`Are you sure you want to delete command "${g.name}"?`)&&(await c(g.name)?he.success(`Command "${g.name}" deleted successfully`):he.error("Failed to delete command"))},h=g=>{const x=g.name;let v=1,j=`${x}-copy`;for(;a.some(N=>N.name===j);)v++,j=`${x}-copy-${v}`;i(j),n(!1),f&&m(!1)};return e.jsx("div",{className:"flex h-full flex-col bg-sidebar",children:e.jsxs(gs,{open:t,onOpenChange:n,children:[e.jsx("div",{className:T("border-b border-border/40 px-3 dark:border-white/10",f?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"Commands"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.length}),e.jsx(cl,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground",children:e.jsx(Yt,{className:"size-4"})})})]})]})}),e.jsx(Je,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:a.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ds,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No commands configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:[...a].sort((g,x)=>g.name.localeCompare(x.name)).map(g=>e.jsx(jf,{command:g,isSelected:o===g.name,onSelect:()=>{i(g.name),f&&m(!1)},onDelete:()=>p(g),onDuplicate:()=>h(g)},g.name))})}),e.jsxs(xs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Create New Command"}),e.jsx(Us,{children:"Enter a unique name for your new slash command"})]}),e.jsx(vt,{value:r,onChange:g=>s(g.target.value),placeholder:"Command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:g=>{g.key==="Enter"&&u()}}),e.jsxs(Cr,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>n(!1),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(js,{onClick:u,children:"Create"})]})]})]})})},jf=({command:r,isSelected:s,onSelect:t,onDelete:n,onDuplicate:o})=>e.jsx("div",{className:"group transition-all duration-200",children:e.jsx("div",{className:"relative",children:e.jsxs("div",{className:"w-full flex items-center justify-between py-1.5 px-2 pr-1",children:[e.jsxs("button",{onClick:t,className:"flex-1 text-left overflow-hidden",inputMode:"none",tabIndex:0,children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:T("typography-ui-label font-medium truncate flex-1",s?"text-primary":"text-foreground hover:text-primary/80"),children:["/",r.name]})}),r.description&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate mt-0.5",children:r.description})]}),e.jsxs(Lt,{children:[e.jsx(Ot,{asChild:!0,children:e.jsx(Ce,{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(wn,{className:"h-3.5 w-3.5"})})}),e.jsxs($t,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(xt,{onClick:a=>{a.stopPropagation(),o()},children:[e.jsx(ws,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(xt,{onClick:a=>{a.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})}),Sf=({agentName:r,onChange:s,className:t})=>{const{agents:n,loadAgents:o}=sr(),a=Le(h=>h.isMobile),{isMobile:i}=St(),c=a||i,[d,m]=l.useState(!1);l.useEffect(()=>{o()},[o]);const f=()=>m(!1),u=h=>{s(h)},p=()=>c?e.jsx(Wt,{open:d,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[n.map(h=>{const g=h.name===r;return e.jsxs("button",{type:"button",className:T("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",g?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{u(h.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:h.name}),h.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:h.description})]}),g&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},h.name)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{u(""),f()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No agent (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[c?e.jsxs("button",{type:"button",onClick:()=>m(!0),className:T("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:r||"Select agent..."})]}),e.jsx(yt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Lt,{children:[e.jsx(Ot,{asChild:!0,children:e.jsxs("div",{className:T("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",t),children:[e.jsx(sn,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:r||"Not selected"}),e.jsx(yt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs($t,{className:"max-w-[300px]",children:[n.map(h=>e.jsx(xt,{className:"typography-meta",onSelect:()=>u(h.name),children:e.jsx("span",{className:"font-medium",children:h.name})},h.name)),e.jsx(xt,{className:"typography-meta",onSelect:()=>u(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),p()]})},Nf=()=>{const{selectedCommandName:r,getCommandByName:s,createCommand:t,updateCommand:n,commands:o}=rr(),a=r?s(r):null,i=r&&!a,[c,d]=l.useState(""),[m,f]=l.useState(""),[u,p]=l.useState(""),[h,g]=l.useState(""),[x,v]=l.useState(""),[j,N]=l.useState(!1),[w,y]=l.useState(!1);l.useEffect(()=>{i?(d(r||""),f(""),p(""),g(""),v(""),N(!1)):a&&(d(a.name),f(a.description||""),p(a.agent||""),g(a.model||""),v(a.template||""),N(a.subtask||!1))},[a,i,r,o]);const S=async()=>{if(!c.trim()){he.error("Command name is required");return}if(!x.trim()){he.error("Command template is required");return}y(!0);try{const b=u.trim(),C=h.trim(),D=x.trim(),k={name:c.trim(),description:m.trim()||void 0,agent:b===""?null:b,model:C===""?null:C,template:D,subtask:j};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(b){console.error("Error saving command:",b),he.error("An error occurred while saving")}finally{y(!1)}};return r?e.jsxs(Je,{outerClassName:"h-full",className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:i?"New Command":c})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name"}),e.jsx(vt,{value:c,onChange:b=>d(b.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(Bs,{value:m,onChange:b=>f(b.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(Sf,{agentName:u,onChange:b=>p(b)}),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(hl,{providerId:h?h.split("/")[0]:"",modelId:h?h.split("/")[1]:"",onChange:(b,C)=>{g(b&&C?`${b}/${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:j,onChange:b=>N(b.target.checked),className:"sr-only"}),e.jsx("div",{className:T("w-5 h-5 rounded border-2 flex items-center justify-center",j?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:j&&e.jsx(jt,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ht,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["When enabled, this command will always execute in a subagent context,",e.jsx("br",{}),"even if triggered from main agent.",e.jsx("br",{}),"Useful for isolating command logic and maintaining clean separation of concerns."]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Command Template"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Define the prompt template for this command. Use $ARGUMENTS for user input."})]}),e.jsx(Bs,{value:x,onChange:b=>v(b.target.value),placeholder:`Your command template here...
|
|
9
9
|
|
|
@@ -21,7 +21,7 @@ ${g}`)}const h=u.map(g=>{if(!g?.dataUrl)return null;try{const[x,v]=g.dataUrl.spl
|
|
|
21
21
|
`)},Tp=(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)},Ip=({tableRef:r})=>{const[s,t]=l.useState(!1),[n,o]=l.useState(!1),a=l.useRef(null);l.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const i=async c=>{const d=r.current?.querySelector("table");if(d)try{const m=Fl(d),f=c==="csv"?_l(m):Dp(m);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([f],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),t(!0),o(!1),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy table:",m)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:s?e.jsx(jt,{className:"size-3.5"}):e.jsx(ws,{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"})]})]})},Pp=({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"?_l(c):Ep(c);Tp(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(vo,{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"})]})]})},Rp=({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(Ip,{tableRef:t}),e.jsx(Pp,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:T("w-full border-collapse border border-border",s),"data-streamdown":"table",children:r})})]})},Fp=({children:r,className:s,style:t,...n})=>{const[o,a]=l.useState(!1),i=l.useRef(null),c=()=>i.current&&i.current.querySelector("code")?.innerText||"",d=async()=>{const m=c();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:T(s),style:{...t,background:"transparent",backgroundColor:"transparent"},children:r}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:d,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(jt,{className:"size-3.5"}):e.jsx(ws,{className:"size-3.5"})})})]})},Ll={pre:Fp,table:Rp},_p=({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:T("break-words",o),children:e.jsx(Sr,{mode:a?"streaming":"static",shikiTheme:Rl,className:"streamdown-content",controls:{code:!1,table:!1},components:Ll,children:r})});return n?e.jsx(Ft,{children:c},i):c},Lp=({content:r,className:s})=>e.jsx("div",{className:T("break-words",s),children:e.jsx(Sr,{mode:"static",shikiTheme:Rl,className:"streamdown-content",controls:{code:!1,table:!1},components:Ll,children:r})}),Op={thinking:{label:"Thinking",Icon:bn},justification:{label:"Justification",Icon:jo}},Ol=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
|
|
22
22
|
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
23
23
|
`).trim(),$p=r=>{if(!r)return"";const s=r.trim(),t=s.indexOf(`
|
|
24
|
-
`),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},Wo=({text:r,variant:s,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>$p(r),[r]),{label:c,Icon:d}=Op[s];return l.useEffect(()=>{r.trim().length!==0&&t?.("structural")},[t,o,r]),!r||r.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(m=>!m),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(yt,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className:T("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(Je,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:r})})]})},$l=({part:r,onContentChange:s,messageId:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>Ol(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Wo,{text:a,variant:"thinking",onContentChange:s,blockId:r.id||`${t}-reasoning`}):null},zp=r=>Ol(r),Bp=({part:r,messageId:s,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=r,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",m=l.useMemo(()=>a?zp(d):d,[d,a]),f=t==="streaming",u=t==="cooldown",p=l.useRef(f);if(f||u)return p.current=!0,null;const h=i.time;return!(h&&typeof h.end<"u")&&(!m||m.trim().length===0)||!m||m.trim().length===0?null:a?e.jsx(Wo,{text:m,variant:"justification",onContentChange:o,blockId:r.id||`${s}-reasoning-text`},r.id||`${s}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(_p,{content:m,part:r,messageId:s,isAnimated:n,isStreaming:!1})},r.id||`${s}-text`)},Hp=r=>`https://opencode.ai/docs/agents/#${encodeURIComponent(r)}`,Wp=({part:r,messageId:s,agentMention:t})=>{const n=r,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,c]=l.useState(!1),[d,m]=l.useState(!1),f=l.useRef(null);l.useEffect(()=>{const h=f.current;h&&!i&&m(h.scrollHeight>h.clientHeight)},[a,i]);const u=l.useCallback(()=>{(d||i)&&c(h=>!h)},[d,i]);if(!a||a.trim().length===0)return null;const p=()=>{if(!t?.token||!a.includes(t.token))return a;const h=a.indexOf(t.token),g=a.slice(0,h),x=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[g,e.jsx("a",{href:Hp(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:v=>v.stopPropagation(),children:t.token}),x]})};return e.jsx("div",{className:T("break-words whitespace-pre-wrap",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:f,onClick:u,children:p()},r.id||`${s}-user-text`)},Up=l.memo(Wp),zl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Vp={markdown:"0.9375rem",code:"0.9375rem",uiHeader:"1rem",uiLabel:"0.9375rem",meta:"0.9375rem",micro:"0.875rem"},ms={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)"}}},Zr={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...ms.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zr.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...ms.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zr.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...ms.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zr.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...ms.tool.inline})},Gp=r=>{let s=r.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},Bl=r=>r?r.includes("<file_diagnostics>")||r.includes("This file has errors")||r.includes("please fix"):!1,qp=r=>r?r.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",ei=(r,s)=>!r||typeof r!="object"?String(r):Ym(r,s||""),Kn=(r,s,t)=>{let n=Gp(r);if((s==="edit"||s==="multiedit")&&Bl(n)&&(n=qp(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Kp=(r,s)=>{try{const t=r.trim().split(`
|
|
24
|
+
`),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},Wo=({text:r,variant:s,onContentChange:t,blockId:n})=>{const[o,a]=l.useState(!1),i=l.useMemo(()=>$p(r),[r]),{label:c,Icon:d}=Op[s];return l.useEffect(()=>{r.trim().length!==0&&t?.("structural")},[t,o,r]),!r||r.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(m=>!m),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(yt,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className:T("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(Je,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:r})})]})},$l=({part:r,onContentChange:s,messageId:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>Ol(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Wo,{text:a,variant:"thinking",onContentChange:s,blockId:r.id||`${t}-reasoning`}):null},zp=r=>Ol(r),Bp=({part:r,messageId:s,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=r,c=i.text,d=typeof c=="string"?c:i.content||i.value||"",m=l.useMemo(()=>a?zp(d):d,[d,a]),f=t==="streaming",u=t==="cooldown",p=l.useRef(f);if(f||u)return p.current=!0,null;const h=i.time;return!(h&&typeof h.end<"u")&&(!m||m.trim().length===0)||!m||m.trim().length===0?null:a?e.jsx(Wo,{text:m,variant:"justification",onContentChange:o,blockId:r.id||`${s}-reasoning-text`},r.id||`${s}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(_p,{content:m,part:r,messageId:s,isAnimated:n,isStreaming:!1})},r.id||`${s}-text`)},Hp=r=>`https://opencode.ai/docs/agents/#${encodeURIComponent(r)}`,Wp=({part:r,messageId:s,agentMention:t})=>{const n=r,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,c]=l.useState(!1),[d,m]=l.useState(!1),f=l.useRef(null);l.useEffect(()=>{const h=f.current;h&&!i&&m(h.scrollHeight>h.clientHeight)},[a,i]);const u=l.useCallback(()=>{(d||i)&&c(h=>!h)},[d,i]);if(!a||a.trim().length===0)return null;const p=()=>{if(!t?.token||!a.includes(t.token))return a;const h=a.indexOf(t.token),g=a.slice(0,h),x=a.slice(h+t.token.length);return e.jsxs(e.Fragment,{children:[g,e.jsx("a",{href:Hp(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:v=>v.stopPropagation(),children:t.token}),x]})};return e.jsx("div",{className:T("break-words whitespace-pre-wrap font-sans typography-markdown",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:f,onClick:u,children:p()},r.id||`${s}-user-text`)},Up=l.memo(Wp),zl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Vp={markdown:"0.9375rem",code:"0.9375rem",uiHeader:"1rem",uiLabel:"0.9375rem",meta:"0.9375rem",micro:"0.875rem"},ms={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)"}}},Zr={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...ms.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zr.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...ms.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zr.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...ms.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Zr.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...ms.tool.inline})},Gp=r=>{let s=r.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return s=s.replace(/^\s*\d{5}\|\s?/gm,""),s.trim()},Bl=r=>r?r.includes("<file_diagnostics>")||r.includes("This file has errors")||r.includes("please fix"):!1,qp=r=>r?r.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",ei=(r,s)=>!r||typeof r!="object"?String(r):Ym(r,s||""),Kn=(r,s,t)=>{let n=Gp(r);if((s==="edit"||s==="multiedit")&&Bl(n)&&(n=qp(n)),(s==="edit"||s==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Kp=(r,s)=>{try{const t=r.trim().split(`
|
|
25
25
|
`).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,c]=a,d=Math.floor(i.length/2),m=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:m})}}),e.jsx("div",{className:T("w-full min-w-0 font-mono space-y-0.5",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ms.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},Yp=(r,s,t)=>{try{const n=r.trim().split(`
|
|
26
26
|
`).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,c,d,m]=i,f=m!==void 0?d:"",u=m!==void 0?m:d;o[c]||(o[c]=[]),o[c].push({lineNum:f,content:u})}}),e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ms.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:T("font-medium text-muted-foreground",s?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:T("flex items-start gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},Xp=(r,s,t)=>{try{const n=r.trim().split(`
|
|
27
27
|
`).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const c=i.lastIndexOf("/"),d=c>0?i.substring(0,c):"/",m=c>=0?i.substring(c+1):i;o[d]||(o[d]=[]),o[d].push(m)});const a=Object.keys(o).sort();return e.jsxs("div",{className:T("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ms.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:T("font-medium text-muted-foreground",s?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:T("pl-4 grid gap-1",s?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(c=>e.jsxs("div",{className:T("flex items-center gap-2 min-w-0",s?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:c})]},c))})]},i))]})}catch{return null}},Jp=(r,s)=>{try{const t=JSON.parse(r);if(!Array.isArray(t))return null;const n={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const i="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:i,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:i,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:T("space-y-3 w-full min-w-0",s?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:ms.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{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(jt,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||i))})]})]})}catch{return null}},Zp=(r,s,t)=>{try{return e.jsx("div",{className:T("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:ms.tool.popup,children:e.jsx(Sr,{mode:"static",className:"streamdown-content streamdown-tool",children:r})})}catch{return null}},Qp=r=>{const s=r.split(`
|
|
@@ -31,7 +31,7 @@ ${g}`)}const h=u.map(g=>{if(!g?.dataUrl)return null;try{const[x,v]=g.dataUrl.spl
|
|
|
31
31
|
`),a=Nn(t??"")||ho(r,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),c=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${c})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,m)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:m+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(ls,{style:s,language:a||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},m))})]})},ih=({part:r,state:s,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const c=s,d=c.metadata,m=c.input,f=c.output,u=typeof f=="string"&&f.length>0,p=typeof f=="string"?f:"",h=typeof d?.diff=="string"?d.diff:null,g=r.tool==="write"?typeof m?.filePath=="string"?m.filePath:typeof m?.file_path=="string"?m.file_path:typeof m?.path=="string"?m.path:void 0:void 0,x=r.tool==="write"?typeof m?.content=="string"?m.content:typeof m?.text=="string"?m.text:null:null,v=r.tool==="write"&&!!x,j=v?g?go(g,o,n):"New file":null,N=l.useMemo(()=>!m||typeof m!="object"||Object.keys(m).length===0?"":"command"in m&&typeof m.command=="string"&&r.tool==="bash"?ei(m,r.tool):typeof m.content=="string"?m.content??"":ei(m,r.tool),[m,r.tool]),w=N.trim().length>0,y=(b,C)=>e.jsx(nh,{maxHeightClass:C?.maxHeightClass,className:C?.className,disableHorizontal:C?.disableHorizontal,outerClassName:C?.outerClassName,children:b}),S=()=>{if(r.tool==="todowrite"||r.tool==="todoread"){if(s.status==="completed"&&u){const b=Jp(p,{unstyled:!0});return y(b??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return s.status==="error"&&"error"in s?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:s.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(r.tool==="list"&&u){const b=Kp(p,{unstyled:!0});return y(b??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="grep"&&u){const b=Yp(p,n,{unstyled:!0});return y(b??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="glob"&&u){const b=Xp(p,n,{unstyled:!0});return y(b??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="task"&&u)return y(e.jsx("div",{className:"w-full min-w-0",style:{fontSize:"var(--text-code)"},children:e.jsx(Sr,{mode:"static",className:"streamdown-content streamdown-tool",children:p})}));if((r.tool==="web-search"||r.tool==="websearch"||r.tool==="search_web")&&u){const b=Zp(p,t,{unstyled:!0});return y(b??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(r.tool==="codesearch"&&u)return y(e.jsx("div",{className:"w-full min-w-0",style:{fontSize:"var(--text-code)"},children:e.jsx(Sr,{mode:"static",className:"streamdown-content streamdown-tool",children:p})}));if((r.tool==="edit"||r.tool==="multiedit")&&(!u&&h||p.trim().length===0||Bl(p))&&h)return y(e.jsx(oh,{diff:h,syntaxTheme:t,input:m}),{className:"p-1"});if(u&&p.trim()){if(r.tool==="read"){const b=Kn(p,r.tool,d),C=b.split(`
|
|
32
32
|
`),D=typeof m?.offset=="number"?m.offset:0,k=typeof m?.limit=="number"?m.limit:void 0,M=E=>E.trim().startsWith("(");return y(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:C.map((E,P)=>{const W=M(E),F=D+P+1,O=!W&&(k===void 0||P<k);return e.jsxs("div",{className:T("typography-code font-mono flex w-full min-w-0",W&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:O?F:""}),e.jsx("div",{className:"flex-1 min-w-0",children:W?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(ls,{style:t,language:ho(b,r.tool,m),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:E})})]},P)})}),{className:"p-1"})}return y(e.jsx(ls,{style:t,language:ho(Kn(p,r.tool,d),r.tool,m),PreTag:"div",customStyle:{...Zr.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Kn(p,r.tool,d)}),{className:"p-1"})}return y(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:T("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:r.tool==="todowrite"||r.tool==="todoread"?S():e.jsxs(e.Fragment,{children:[v?e.jsx("div",{className:"my-1",children:y(e.jsx(ah,{content:x,syntaxTheme:t,filePath:g,displayPath:j??"New file"}))}):w?e.jsx("div",{className:"my-1",children:y(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:N}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,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:"}),S()]}),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})]})]})})},xo=({part:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:c=!1})=>{const d=r.state,m=ht(D=>D.currentDirectory),f=d.status==="completed"||d.status==="error",u=d.status==="running",p=d.status==="error",[h,g]=l.useState(Date.now());l.useEffect(()=>{if(u){const D=setInterval(()=>{g(Date.now())},100);return()=>clearInterval(D)}},[u]);const x=l.useRef(s);l.useEffect(()=>{f&&x.current!==s&&(x.current=s,typeof s=="boolean"&&a?.("structural"))},[s,f,a]);const v=d,j=v.metadata,N=v.input,w=r.tool==="edit"||r.tool==="multiedit"?sh(j):null,y=rh(r,d,o,m),S=nl(r.tool).displayName,b=l.useContext(Oo),C=D=>{if(!b?.editor){t(r.id);return}let k;if((r.tool==="edit"||r.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(r.tool))&&(k=N?.filePath||N?.file_path||N?.path||j?.filePath||j?.file_path||j?.path),typeof k=="string"){D.stopPropagation();let M=k;k.startsWith("/")||(M=m.endsWith("/")?m+k:m+"/"+k),b.editor.openFile(M)}else t(r.id)};return f?e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:C,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:D=>{D.stopPropagation(),t(r.id)},children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),style:p?{color:"var(--status-error)"}:{},children:eh(r.tool)}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(yt,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:p?{color:"var(--status-error)"}:{},children:S})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[y&&e.jsx("span",{className:T("truncate",o&&"max-w-[120px]"),children:y}),w&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",w.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",w.removed]})]}),"time"in d&&d.time&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:th(d.time.start,f&&"end"in d.time?d.time.end:h)})]})]}),s&&e.jsx(ih,{part:r,state:d,syntaxTheme:n,isMobile:o,currentDirectory:m,hasPrevTool:i,hasNextTool:c})]}):null},lh=r=>typeof r!="string"||r.trim().length===0?"":r.split(`
|
|
33
33
|
`).map(s=>s.replace(/^>\s?/,"").trimEnd()).filter(s=>s.trim().length>0).join(`
|
|
34
|
-
`).trim(),ch=({part:r,messageId:s,onContentChange:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>lh(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Wo,{text:a,variant:"justification",onContentChange:t,blockId:r.id||`${s}-justification`}):null},dh=l.memo(ch),uh=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(", ")},Yn=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}),mh=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},fh=({parts:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:m,diffStats:f})=>{const u=l.useRef(s);l.useEffect(()=>{u.current!==s&&(u.current=s,c?.("structural"))},[s,c]);const p=l.useMemo(()=>Yn(!d||s?r:r.filter(x=>x.part.id&&m.has(x.id))),[r,d,s,m]),h=uh(p),g=mh(p);return p.length===0?null:e.jsx(Ft,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl cursor-pointer"),onClick:t,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(hd,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(yt,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(h||f)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[h&&e.jsx("span",{className:"truncate block",children:h}),f&&(f.additions>0||f.deletions>0)&&e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,f.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,f.deletions)]})]})]})]}),s&&e.jsx("div",{className:T("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:p.map((x,v)=>{const j=x.part.id||`group-part-${v}`,N=g[j];switch(x.kind){case"tool":return e.jsx(Ft,{children:e.jsx(xo,{part:x.part,isExpanded:a.has(j),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},j);case"reasoning":return e.jsx(Ft,{children:e.jsx($l,{part:x.part,messageId:x.messageId,onContentChange:c})},j);case"justification":return e.jsx(Ft,{children:e.jsx(dh,{part:x.part,messageId:x.messageId,onContentChange:c})},j);default:return null}})})]})})},ph=l.memo(fh),hh=({isMigrating:r,children:s,className:t})=>e.jsx("div",{className:T("w-full overflow-hidden",r&&"pointer-events-none",t),style:r?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:s}),Xn=l.memo(hh),Hl=r=>{const s=r,t=s.text;return typeof t=="string"?t:s.content||s.value||""},Wl=r=>{if(r.type!=="text")return!1;const s=Hl(r);return!s||s.trim().length===0},gh=(r,s={})=>{const{includeReasoning:t=!0}=s;return r.filter(n=>!!n.synthetic||!t&&n.type==="reasoning"?!1:!(n.type==="patch"))},xh=(r,s)=>{const t=l.useRef(null),n=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(r);i.current=r;const c=l.useRef(s);c.current=s;const d=l.useRef(!1),m=s.size>0;return l.useEffect(()=>{r&&r.isWorking&&(r.isGroupExpanded||m&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const f=i.current;if(!f)return;const u=Array.from(c.current);u.length>0&&f.markPartsPreviewed(u)},300)},1e3))))},[m,r]),l.useEffect(()=>{r&&(!r.isWorking||r.isGroupExpanded||!m)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[m,r]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},yh=({messageId:r,parts:s,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d})=>{const[m,f]=l.useState(!1),u=l.useRef(null),p=l.useMemo(()=>s.filter(b=>b.type!=="text"?!1:!Wl(b)),[s]),h=d?.token;let g=!1;const x=!!a,v=!!i,j=!!(n??t),N=!!o,w=l.useCallback(()=>{u.current!==null&&typeof window<"u"&&(window.clearTimeout(u.current),u.current=null)},[]),y=l.useCallback(()=>{!j||!x||!N||typeof window>"u"||(w(),f(!0),u.current=window.setTimeout(()=>{f(!1),u.current=null},1800))},[x,w,N,j]);l.useEffect(()=>{N||(f(!1),w())},[w,N]);const S=l.useCallback(b=>{!a||!N||(b.stopPropagation(),b.preventDefault(),a(),j&&y())},[N,j,a,y]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:j&&x&&N?y:void 0,children:[x&&e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":m||v?"true":void 0,className:T("absolute z-10 flex h-7 w-7 items-center justify-center rounded-full border border-border/40 shadow-none bg-background/95 supports-[backdrop-filter]:bg-background/80 hover:bg-accent duration-150","opacity-0 pointer-events-none disabled:opacity-30 disabled:text-muted-foreground/40",N&&"group-hover/message:opacity-60 group-hover/message:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",(m||v)&&"opacity-100 pointer-events-auto"),style:{insetInlineEnd:"0.32rem",insetBlockStart:"-0.28rem"},disabled:!N,"aria-label":"Copy message text","aria-hidden":!N,onPointerDown:b=>b.stopPropagation(),onClick:S,onFocus:()=>{N&&f(!0)},onBlur:()=>{v||f(!1)},children:v?e.jsx(jt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(ws,{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((b,C)=>{let D;return d&&h&&!g&&Hl(b).includes(h)&&(D=d,g=!0),e.jsx(Ft,{children:e.jsx(Up,{part:b,messageId:r,isMobile:t,agentMention:D})},`user-text-${C}`)})}),e.jsx(Nl,{files:s,onShowPopup:c})]})]})},bh=({messageId:r,parts:s,isMessageCompleted:t,syntaxTheme:n,isMobile:o,hasTouchInput:a,copiedCode:i,onCopyCode:c,expandedTools:d,onToggleTool:m,onShowPopup:f,streamPhase:u,allowAnimation:p,onContentChange:h,shouldShowHeader:g=!0,hasTextContent:x=!1,onCopyMessage:v,copiedMessage:j=!1,onAuxiliaryContentComplete:N,showReasoningTraces:w=!1,turnGroupingContext:y})=>{const[S,b]=l.useState(!1),C=l.useRef(null),D=!!v,k=!!j,M=!!(a??o),E=!t,P=l.useMemo(()=>s.filter(ge=>!Wl(ge)).filter(ge=>ge.type!=="compaction"),[s]),W=l.useMemo(()=>P.filter(ge=>ge.type==="tool"),[P]),F=l.useMemo(()=>P.filter(ge=>ge.type==="text"),[P]),O=pe(ge=>ge.createSessionFromAssistantMessage),z=y?.isLastAssistantInTurn??!1,X=l.useMemo(()=>s.some(ge=>ge.type==="step-finish"&&ge.reason==="stop"),[s]),L=W.length>0,V=l.useMemo(()=>W.some(ge=>{const Ee=(ge.state??{})?.status;return Ee==="pending"||Ee==="running"||Ee==="started"}),[W]),Y=l.useCallback(ge=>{const _e=ge.state??{},Ee=_e?.status;if(Ee==="pending"||Ee==="running"||Ee==="started")return!1;const Ke=_e?.time??{},st=typeof Ke?.end=="number"?Ke.end:void 0,it=typeof Ke?.start=="number"?Ke.start:void 0;return!(typeof st!="number"||typeof it=="number"&&st<it)},[]),ie=l.useMemo(()=>W.length===0?!0:V?!1:W.every(ge=>Y(ge)),[W,V,Y]),we=l.useMemo(()=>F.length===0?!0:F.every(ge=>typeof ge.time?.end=="number"),[F]),ke=l.useMemo(()=>P.filter(ge=>ge.type==="reasoning"),[P]),ze=l.useMemo(()=>ke.length===0?!0:ke.every(ge=>typeof ge.time?.end=="number"),[ke]),le=l.useMemo(()=>{let ge=0,_e=0;return P.forEach(Ee=>{Ee.type==="step-start"?ge+=1:Ee.type==="step-finish"&&(_e+=1)}),{stepStarts:ge,stepFinishes:_e,hasOpenStep:ge>_e}},[P]).hasOpenStep,ve=ke.length>0&&L&&(V||le||!ie),ee=l.useMemo(()=>L?F.length===0?le||V||!ie:!0:F.length>0?ve:!1,[F.length,le,V,L,ve,ie]),Be=E||ee&&(!we||!ie||V||le)||ve,re=E||L&&(V||le||!ie),A=E||ve,ne=L||ke.length>0,G=F.length===0,B=ne&&G&&!re&&!A&&ie&&ze,_=l.useRef(!1),q=l.useRef(!1);l.useEffect(()=>{q.current=!1},[r]),l.useEffect(()=>{if(!B){_.current=!1;return}_.current||(_.current=!0,N?.())},[B,N]),l.useEffect(()=>{if(E){q.current=!1;return}if(L){q.current=!1;return}ke.length!==0&&(A||!ze||q.current||(q.current=!0,h?.("structural")))},[E,L,h,ze,ke.length,A]);const J=!!x&&!E,oe=l.useCallback(()=>{C.current!==null&&typeof window<"u"&&(window.clearTimeout(C.current),C.current=null)},[]),be=l.useCallback(()=>{!M||!D||!J||typeof window>"u"||(oe(),b(!0),C.current=window.setTimeout(()=>{b(!1),C.current=null},1800))},[D,oe,J,M]);l.useEffect(()=>{J||(b(!1),oe())},[oe,J]);const ue=l.useCallback(ge=>{!v||!J||(ge.stopPropagation(),ge.preventDefault(),v(),M&&be())},[J,M,v,be]),K=l.useCallback(ge=>{ge.stopPropagation(),ge.preventDefault(),O&&O(r)},[O,r]);l.useEffect(()=>()=>{oe()},[oe]);const ae=l.useMemo(()=>{const ge={},_e=W.filter(Ee=>re?!1:Y(Ee));return _e.forEach((Ee,Ke)=>{ge[Ee.id]={hasPrev:Ke>0,hasNext:Ke<_e.length-1}}),ge},[W,re,Y]),H=l.useMemo(()=>y?.activityParts??[],[y]),Me=l.useMemo(()=>y?H.filter(ge=>ge.messageId===r):[],[H,r,y]),Se=l.useMemo(()=>{const ge=new Map;return Me.forEach(_e=>{ge.set(_e.part,_e)}),ge},[Me]),Oe=l.useMemo(()=>y?w?H:H.filter(ge=>ge.kind==="tool"):[],[H,w,y]),[et,tt]=l.useState(!1);l.useEffect(()=>{y&&Oe.length>1&&tt(!0)},[y,Oe.length]);const qe=!!(y&&et),Ze=l.useMemo(()=>{if(!y)return[];if(!qe)return[];if(!y.isWorking||y.isGroupExpanded)return[];const ge=[];return Me.forEach(_e=>{if(y.previewedPartIds.has(_e.id)||!w&&_e.kind!=="tool")return;const Ee=_e.part;if(_e.kind==="tool"){const Ke=Ee;if(re||!Y(Ke))return}else if(_e.kind==="reasoning"){if(!w||A||typeof Ee.time?.end!="number")return}else if(_e.kind==="justification"&&(!w||Be||typeof Ee.time?.end!="number"))return;ge.push(_e)}),ge},[Me,Y,Be,A,re,w,qe,y]),Ue=l.useMemo(()=>{const ge=new Set;return Ze.forEach(_e=>{ge.add(_e.id)}),ge},[Ze]),{isAnimating:We}=xh(y,Ue),Ve=l.useMemo(()=>{const ge=[];y&&y.isFirstAssistantInTurn&&qe&&Oe.length>0&&ge.push(e.jsx(ph,{parts:Oe,isExpanded:y.isGroupExpanded,onToggle:y.toggleGroup,syntaxTheme:n,isMobile:o,expandedTools:d,onToggleTool:m,onShowPopup:f,onContentChange:h,isWorking:y.isWorking,previewedPartIds:y.previewedPartIds,diffStats:y.diffStats},"progressive-group"));const _e=[];return P.forEach((Ee,Ke)=>{const st=Se.get(Ee);if(!st||!y)return;let it=null,ct=null;if(!qe){if(st.kind==="tool"){const I=Ee,se=I.state?.time,je=Y(I);if(!(!re&&je))return;const Ie=ae[I.id];ct=e.jsx(Ft,{children:e.jsx(xo,{part:I,isExpanded:d.has(I.id),onToggle:m,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:Ie?.hasPrev??!1,hasNextTool:Ie?.hasNext??!1})},`tool-${I.id}`),it=je&&typeof se?.end=="number"?se.end:null}ct&&_e.push({part:Ee,index:Ke,endTime:it,element:ct});return}if(!y.isWorking||y.isGroupExpanded||y.previewedPartIds.has(st.id)||!w&&st.kind!=="tool")return;const U=Ue.has(st.id);switch(st.kind){case"tool":{const I=Ee,se=I.state?.time,je=Y(I);if(!(!re&&je))break;const Ie=ae[I.id],$e=e.jsx(Ft,{children:e.jsx(xo,{part:I,isExpanded:d.has(I.id),onToggle:m,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:Ie?.hasPrev??!1,hasNextTool:Ie?.hasNext??!1})},`tool-${I.id}`);ct=U?e.jsx(Xn,{isMigrating:We,children:$e},`migrating-tool-${I.id}`):$e,it=je&&typeof se?.end=="number"?se.end:null;break}case"reasoning":{if(!w)break;const I=Ee.time,$=typeof I?.end=="number";if(!($&&!A))break;const je=e.jsx(Ft,{children:e.jsx($l,{part:Ee,messageId:r,onContentChange:h})},`reasoning-${Ke}`);ct=U?e.jsx(Xn,{isMigrating:We,children:je},`migrating-reasoning-${Ke}`):je,it=$?I?.end??null:null;break}case"justification":{if(!w)break;const I=Ee.time,$=typeof I?.end=="number";if(!($&&!Be))break;const je=e.jsx(Ft,{children:e.jsx(Bp,{part:Ee,messageId:r,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${Ke}`);ct=U?e.jsx(Xn,{isMigrating:We,children:je},`migrating-text-${Ke}`):je,it=$?I?.end??null:null;break}}ct&&_e.push({part:Ee,index:Ke,endTime:it,element:ct})}),_e.sort((Ee,Ke)=>Ee.endTime===null&&Ke.endTime===null?Ee.index-Ke.index:Ee.endTime===null?1:Ke.endTime===null?-1:Ee.endTime-Ke.endTime),_e.forEach(({element:Ee})=>{ge.push(Ee)}),ge},[Se,i,j,d,x,We,o,Y,r,h,c,v,f,m,Ue,Be,A,re,qe,g,w,n,ae,y,Oe,P]),He=y?.turnId,at=pe(ge=>ge.currentSessionId),Ge=Qe(ge=>{if(!He||!at)return;const _e=ge.messages.get(at);if(!_e)return;const Ee=_e.find(it=>it.info?.id===He);if(!Ee)return;const st=Ee.info.summary?.body;return typeof st=="string"&&st.trim().length>0?st:void 0}),ye=typeof y?.summaryBody=="string"&&y.summaryBody.trim().length>0?y.summaryBody:Ge,R=l.useRef(void 0);ye&&ye.trim().length>0&&(R.current=ye);const Q=l.useRef(He);Q.current!==He&&(Q.current=He,R.current=void 0);const te=R.current,ce=y?.isLastAssistantInTurn&&te&&te.trim().length>0,Fe=x&&F.length>0&&X&&z,[nt,De]=l.useState(!1),Re=e.jsxs(e.Fragment,{children:[v&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":S||k?"true":void 0,className:T("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!J&&"opacity-50",(S||k)&&"text-primary"),disabled:!J,"aria-label":"Copy message text","aria-hidden":!J,onPointerDown:ge=>ge.stopPropagation(),onClick:ue,onFocus:()=>{J&&b(!0)},onBlur:()=>{k||b(!1)},children:k?e.jsx(jt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(ws,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ce,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:ge=>ge.stopPropagation(),onClick:K,children:e.jsx(gd,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new session from this answer"})]})]});return e.jsx("div",{className:T("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:M&&D&&J?be:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ve,ce&&e.jsx(Ft,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>De(!0),onMouseLeave:()=>De(!1),children:[e.jsx(Lp,{content:te}),Fe&&e.jsx("div",{className:T("mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",nt&&"opacity-100 pointer-events-auto"),children:Re})]})},"summary-body")]}),e.jsx(Nl,{files:s,onShowPopup:f}),!ce&&Fe&&e.jsx("div",{className:"mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",children:Re})]})})},wh=({isUser:r,...s})=>r?e.jsx(yh,{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(bh,{...s}),ti=l.memo(wh),Jn=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}},vh=l.lazy(()=>Js(()=>import("./ToolOutputDialog-DGK97u29.js"),__vite__mapDeps([5,1,2,3,4])));function Zn(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 as=(r,s)=>{if(typeof r=="object"&&r!==null)return r[s]},jh=({message:r,previousMessage:s,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=St(),{currentTheme:m}=nr(),f=l.useRef(null),u=pe(Eo($=>({lifecyclePhase:$.messageStreamStates.get(r.info.id)?.phase??null,isStreamingMessage:(()=>{const se=r.info.sessionID??$.currentSessionId??null;return se?($.streamingMessageIds.get(se)??null)===r.info.id:!1})(),currentSessionId:$.currentSessionId,getCurrentAgent:$.getCurrentAgent,getSessionAgentSelection:$.getSessionAgentSelection,getAgentModelForSession:$.getAgentModelForSession,getSessionModelSelection:$.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:g,getCurrentAgent:x,getSessionAgentSelection:v,getAgentModelForSession:j,getSessionModelSelection:N}=u,w=gt($=>$.providers),y=Le($=>$.showReasoningTraces);l.useEffect(()=>{g&&ks.getInstance().recordSessionStart(g)},[g]);const[S,b]=l.useState(null),[C,D]=l.useState(!1),[k,M]=l.useState(new Set),[E,P]=l.useState({open:!1,title:"",content:""}),F=l.useMemo(()=>Jn(r.info),[r.info]).isUser,O=l.useMemo(()=>F?r.parts.map($=>$.type==="compaction"?{type:"text",text:"/summarize"}:$):r.parts,[F,r.parts]),z=l.useMemo(()=>{if(F||!s)return null;const $=as(s.info,"clientRole"),se=as(s.info,"role");if((typeof $=="string"?$:typeof se=="string"?se:void 0)!=="user")return null;const Pe=as(s.info,"mode"),Ie=as(s.info,"providerID"),$e=as(s.info,"modelID"),ot=typeof Pe=="string"&&Pe.trim().length>0?Pe:void 0,Nt=typeof Ie=="string"&&Ie.trim().length>0?Ie:void 0,At=typeof $e=="string"&&$e.trim().length>0?$e:void 0;return!ot&&!Nt&&!At?null:{agentName:ot,providerId:Nt,modelId:At}},[F,s]),X=l.useMemo(()=>{if(F)return;const $=as(r.info,"mode");if(typeof $=="string"&&$.trim().length>0)return $;if(z?.agentName)return z.agentName;const se=r.info.sessionID;if(!se)return;const je=x(se);return je||(v(se)??void 0)},[F,r.info,z,x,v]),L=r.info.sessionID,V=F?null:as(r.info,"providerID"),Y=F?null:as(r.info,"modelID"),ie=l.useMemo(()=>{if(F||!L)return null;if(z?.providerId&&z?.modelId)return{providerId:z.providerId,modelId:z.modelId};if(X){const se=j(L,X);if(se?.providerId&&se?.modelId)return se}const $=N(L);return $?.providerId&&$?.modelId?$:null},[F,L,X,z,j,N]),we=l.useMemo(()=>F?null:typeof V=="string"&&V.trim().length>0?V:ie?.providerId??null,[F,V,ie]),ke=l.useMemo(()=>F?null:typeof Y=="string"&&Y.trim().length>0?Y:ie?.modelId??null,[F,Y,ie]),ze=l.useMemo(()=>{if(!F&&we&&ke&&w.length>0){const $=w.find(se=>se.id===we);if($?.models&&Array.isArray($.models)){const Pe=$.models.find(Ie=>Ie.id===ke)?.name;return typeof Pe=="string"?Pe:void 0}}},[F,we,ke,w]),de=Zn(X),le=Zn(we??void 0),ve=Zn(ze),ee=de??void 0,Be=le??null,re=ve??void 0,A=l.useMemo(()=>{const $=r.info.time;return typeof $?.completed=="number"?$.completed:null},[r.info.time]),ne=l.useMemo(()=>F?!0:!!(A&&A>0),[F,A]),G=l.useMemo(()=>gh(O,{includeReasoning:y}),[O,y]),B=l.useMemo(()=>F||ne?G:[],[F,ne,G]),_=l.useMemo(()=>F?[]:G.filter($=>$.type==="text"),[F,G]),q=l.useMemo(()=>F?[]:G.filter($=>$.type==="tool"),[F,G]),J=l.useMemo(()=>{if(!F)return;const $=r.parts.find(Ie=>Ie.type==="agent");if(!$)return;const se=$,je=typeof se.name=="string"?se.name:void 0;if(!je)return;const Pe=se.source&&typeof se.source.value=="string"&&se.source.value.trim().length>0?se.source.value:`#${je}`;return{name:je,token:Pe}},[F,r.parts]),be=l.useMemo(()=>{let $=0,se=0;return G.forEach(je=>{je.type==="step-start"?$+=1:je.type==="step-finish"&&(se+=1)}),{hasOpenStep:$>se}},[G]).hasOpenStep,ue=l.useMemo(()=>F?!1:_.length===0||q.length===0?be:!0,[_.length,q.length,be,F]),K=m?.metadata.variant,ae=l.useMemo(()=>K?K==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[K]),H=l.useMemo(()=>m?Pl(m):ae?kp:Cp,[m,ae]),Me=l.useMemo(()=>F?!1:ks.getInstance().shouldAnimateMessage(r.info,g||r.info.sessionID),[r.info,g,F]),Se=l.useMemo(()=>s?Jn(s.info):null,[s]),Oe=l.useMemo(()=>t?Jn(t.info):null,[t]),et=l.useMemo(()=>F||!Se?!0:Se.isUser,[F,Se]),tt=l.useMemo(()=>F||!Oe?!1:!Oe.isUser&&Oe.role==="assistant",[F,Oe]),qe=l.useMemo(()=>ne?"completed":p||(h?"streaming":"completed"),[ne,p,h]),Ze=l.useCallback($=>{navigator.clipboard.writeText($),b($),setTimeout(()=>b(null),2e3)},[]),Ue=i?.turnId,We=Qe($=>{if(!Ue)return;const se=r.info.sessionID;if(!se)return;const je=$.messages.get(se);if(!je)return;const Pe=je.find(ot=>ot.info?.id===Ue);if(!Pe)return;const $e=Pe.info.summary?.body;return typeof $e=="string"&&$e.trim().length>0?$e:void 0}),Ve=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:We,He=l.useRef(void 0);Ve&&Ve.trim().length>0&&(He.current=Ve);const at=l.useRef(Ue);at.current!==Ue&&(at.current=Ue,He.current=void 0);const Ge=He.current,ye=l.useMemo(()=>F?B.filter(je=>je.type==="text").map(je=>(je.text||je.content||"").trim()).filter(je=>je.length>0).join(`
|
|
34
|
+
`).trim(),ch=({part:r,messageId:s,onContentChange:t})=>{const n=r,o=n.text||n.content||"",a=l.useMemo(()=>lh(o),[o]);return("time"in r?r.time:null)?.end?e.jsx(Wo,{text:a,variant:"justification",onContentChange:t,blockId:r.id||`${s}-justification`}):null},dh=l.memo(ch),uh=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(", ")},Yn=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}),mh=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},fh=({parts:r,isExpanded:s,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:c,isWorking:d,previewedPartIds:m,diffStats:f})=>{const u=l.useRef(s);l.useEffect(()=>{u.current!==s&&(u.current=s,c?.("structural"))},[s,c]);const p=l.useMemo(()=>Yn(!d||s?r:r.filter(x=>x.part.id&&m.has(x.id))),[r,d,s,m]),h=uh(p),g=mh(p);return p.length===0?null:e.jsx(Ft,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:T("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl cursor-pointer"),onClick:t,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:T("absolute inset-0 transition-opacity",s&&"opacity-0",!s&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(hd,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:T("absolute inset-0 transition-opacity flex items-center justify-center",s&&"opacity-100",!s&&o&&"opacity-0",!s&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:s?e.jsx(yt,{className:"h-3.5 w-3.5"}):e.jsx(ps,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(h||f)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[h&&e.jsx("span",{className:"truncate block",children:h}),f&&(f.additions>0||f.deletions>0)&&e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,f.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,f.deletions)]})]})]})]}),s&&e.jsx("div",{className:T("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:p.map((x,v)=>{const j=x.part.id||`group-part-${v}`,N=g[j];switch(x.kind){case"tool":return e.jsx(Ft,{children:e.jsx(xo,{part:x.part,isExpanded:a.has(j),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},j);case"reasoning":return e.jsx(Ft,{children:e.jsx($l,{part:x.part,messageId:x.messageId,onContentChange:c})},j);case"justification":return e.jsx(Ft,{children:e.jsx(dh,{part:x.part,messageId:x.messageId,onContentChange:c})},j);default:return null}})})]})})},ph=l.memo(fh),hh=({isMigrating:r,children:s,className:t})=>e.jsx("div",{className:T("w-full overflow-hidden",r&&"pointer-events-none",t),style:r?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:s}),Xn=l.memo(hh),Hl=r=>{const s=r,t=s.text;return typeof t=="string"?t:s.content||s.value||""},Wl=r=>{if(r.type!=="text")return!1;const s=Hl(r);return!s||s.trim().length===0},gh=(r,s={})=>{const{includeReasoning:t=!0}=s;return r.filter(n=>!!n.synthetic||!t&&n.type==="reasoning"?!1:!(n.type==="patch"))},xh=(r,s)=>{const t=l.useRef(null),n=l.useRef(null),[o,a]=l.useState(!1),i=l.useRef(r);i.current=r;const c=l.useRef(s);c.current=s;const d=l.useRef(!1),m=s.size>0;return l.useEffect(()=>{r&&r.isWorking&&(r.isGroupExpanded||m&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const f=i.current;if(!f)return;const u=Array.from(c.current);u.length>0&&f.markPartsPreviewed(u)},300)},1e3))))},[m,r]),l.useEffect(()=>{r&&(!r.isWorking||r.isGroupExpanded||!m)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[m,r]),l.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},yh=({messageId:r,parts:s,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:c,agentMention:d})=>{const[m,f]=l.useState(!1),u=l.useRef(null),p=l.useMemo(()=>s.filter(b=>b.type!=="text"?!1:!Wl(b)),[s]),h=d?.token;let g=!1;const x=!!a,v=!!i,j=!!(n??t),N=!!o,w=l.useCallback(()=>{u.current!==null&&typeof window<"u"&&(window.clearTimeout(u.current),u.current=null)},[]),y=l.useCallback(()=>{!j||!x||!N||typeof window>"u"||(w(),f(!0),u.current=window.setTimeout(()=>{f(!1),u.current=null},1800))},[x,w,N,j]);l.useEffect(()=>{N||(f(!1),w())},[w,N]);const S=l.useCallback(b=>{!a||!N||(b.stopPropagation(),b.preventDefault(),a(),j&&y())},[N,j,a,y]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:j&&x&&N?y:void 0,children:[x&&e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":m||v?"true":void 0,className:T("absolute z-10 flex h-7 w-7 items-center justify-center rounded-full border border-border/40 shadow-none bg-background/95 supports-[backdrop-filter]:bg-background/80 hover:bg-accent duration-150","opacity-0 pointer-events-none disabled:opacity-30 disabled:text-muted-foreground/40",N&&"group-hover/message:opacity-60 group-hover/message:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto",(m||v)&&"opacity-100 pointer-events-auto"),style:{insetInlineEnd:"0.32rem",insetBlockStart:"-0.28rem"},disabled:!N,"aria-label":"Copy message text","aria-hidden":!N,onPointerDown:b=>b.stopPropagation(),onClick:S,onFocus:()=>{N&&f(!0)},onBlur:()=>{v||f(!1)},children:v?e.jsx(jt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(ws,{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((b,C)=>{let D;return d&&h&&!g&&Hl(b).includes(h)&&(D=d,g=!0),e.jsx(Ft,{children:e.jsx(Up,{part:b,messageId:r,isMobile:t,agentMention:D})},`user-text-${C}`)})}),e.jsx(Nl,{files:s,onShowPopup:c})]})]})},bh=({messageId:r,parts:s,isMessageCompleted:t,syntaxTheme:n,isMobile:o,hasTouchInput:a,copiedCode:i,onCopyCode:c,expandedTools:d,onToggleTool:m,onShowPopup:f,streamPhase:u,allowAnimation:p,onContentChange:h,shouldShowHeader:g=!0,hasTextContent:x=!1,onCopyMessage:v,copiedMessage:j=!1,onAuxiliaryContentComplete:N,showReasoningTraces:w=!1,turnGroupingContext:y})=>{const[S,b]=l.useState(!1),C=l.useRef(null),D=!!v,k=!!j,M=!!(a??o),E=!t,P=l.useMemo(()=>s.filter(ge=>!Wl(ge)).filter(ge=>ge.type!=="compaction"),[s]),W=l.useMemo(()=>P.filter(ge=>ge.type==="tool"),[P]),F=l.useMemo(()=>P.filter(ge=>ge.type==="text"),[P]),O=pe(ge=>ge.createSessionFromAssistantMessage),z=y?.isLastAssistantInTurn??!1,X=l.useMemo(()=>s.some(ge=>ge.type==="step-finish"&&ge.reason==="stop"),[s]),L=W.length>0,V=l.useMemo(()=>W.some(ge=>{const Ee=(ge.state??{})?.status;return Ee==="pending"||Ee==="running"||Ee==="started"}),[W]),Y=l.useCallback(ge=>{const _e=ge.state??{},Ee=_e?.status;if(Ee==="pending"||Ee==="running"||Ee==="started")return!1;const Ke=_e?.time??{},st=typeof Ke?.end=="number"?Ke.end:void 0,it=typeof Ke?.start=="number"?Ke.start:void 0;return!(typeof st!="number"||typeof it=="number"&&st<it)},[]),ie=l.useMemo(()=>W.length===0?!0:V?!1:W.every(ge=>Y(ge)),[W,V,Y]),we=l.useMemo(()=>F.length===0?!0:F.every(ge=>typeof ge.time?.end=="number"),[F]),ke=l.useMemo(()=>P.filter(ge=>ge.type==="reasoning"),[P]),ze=l.useMemo(()=>ke.length===0?!0:ke.every(ge=>typeof ge.time?.end=="number"),[ke]),le=l.useMemo(()=>{let ge=0,_e=0;return P.forEach(Ee=>{Ee.type==="step-start"?ge+=1:Ee.type==="step-finish"&&(_e+=1)}),{stepStarts:ge,stepFinishes:_e,hasOpenStep:ge>_e}},[P]).hasOpenStep,ve=ke.length>0&&L&&(V||le||!ie),ee=l.useMemo(()=>L?F.length===0?le||V||!ie:!0:F.length>0?ve:!1,[F.length,le,V,L,ve,ie]),Be=E||ee&&(!we||!ie||V||le)||ve,re=E||L&&(V||le||!ie),A=E||ve,ne=L||ke.length>0,G=F.length===0,B=ne&&G&&!re&&!A&&ie&&ze,_=l.useRef(!1),q=l.useRef(!1);l.useEffect(()=>{q.current=!1},[r]),l.useEffect(()=>{if(!B){_.current=!1;return}_.current||(_.current=!0,N?.())},[B,N]),l.useEffect(()=>{if(E){q.current=!1;return}if(L){q.current=!1;return}ke.length!==0&&(A||!ze||q.current||(q.current=!0,h?.("structural")))},[E,L,h,ze,ke.length,A]);const J=!!x&&!E,oe=l.useCallback(()=>{C.current!==null&&typeof window<"u"&&(window.clearTimeout(C.current),C.current=null)},[]),be=l.useCallback(()=>{!M||!D||!J||typeof window>"u"||(oe(),b(!0),C.current=window.setTimeout(()=>{b(!1),C.current=null},1800))},[D,oe,J,M]);l.useEffect(()=>{J||(b(!1),oe())},[oe,J]);const ue=l.useCallback(ge=>{!v||!J||(ge.stopPropagation(),ge.preventDefault(),v(),M&&be())},[J,M,v,be]),K=l.useCallback(ge=>{ge.stopPropagation(),ge.preventDefault(),O&&O(r)},[O,r]);l.useEffect(()=>()=>{oe()},[oe]);const ae=l.useMemo(()=>{const ge={},_e=W.filter(Ee=>re?!1:Y(Ee));return _e.forEach((Ee,Ke)=>{ge[Ee.id]={hasPrev:Ke>0,hasNext:Ke<_e.length-1}}),ge},[W,re,Y]),H=l.useMemo(()=>y?.activityParts??[],[y]),Me=l.useMemo(()=>y?H.filter(ge=>ge.messageId===r):[],[H,r,y]),Se=l.useMemo(()=>{const ge=new Map;return Me.forEach(_e=>{ge.set(_e.part,_e)}),ge},[Me]),Oe=l.useMemo(()=>y?w?H:H.filter(ge=>ge.kind==="tool"):[],[H,w,y]),[et,tt]=l.useState(!1);l.useEffect(()=>{y&&Oe.length>1&&tt(!0)},[y,Oe.length]);const qe=!!(y&&et),Ze=l.useMemo(()=>{if(!y)return[];if(!qe)return[];if(!y.isWorking||y.isGroupExpanded)return[];const ge=[];return Me.forEach(_e=>{if(y.previewedPartIds.has(_e.id)||!w&&_e.kind!=="tool")return;const Ee=_e.part;if(_e.kind==="tool"){const Ke=Ee;if(re||!Y(Ke))return}else if(_e.kind==="reasoning"){if(!w||A||typeof Ee.time?.end!="number")return}else if(_e.kind==="justification"&&(!w||Be||typeof Ee.time?.end!="number"))return;ge.push(_e)}),ge},[Me,Y,Be,A,re,w,qe,y]),Ue=l.useMemo(()=>{const ge=new Set;return Ze.forEach(_e=>{ge.add(_e.id)}),ge},[Ze]),{isAnimating:We}=xh(y,Ue),Ve=l.useMemo(()=>{const ge=[];y&&y.isFirstAssistantInTurn&&qe&&Oe.length>0&&ge.push(e.jsx(ph,{parts:Oe,isExpanded:y.isGroupExpanded,onToggle:y.toggleGroup,syntaxTheme:n,isMobile:o,expandedTools:d,onToggleTool:m,onShowPopup:f,onContentChange:h,isWorking:y.isWorking,previewedPartIds:y.previewedPartIds,diffStats:y.diffStats},"progressive-group"));const _e=[];return P.forEach((Ee,Ke)=>{const st=Se.get(Ee);if(!st||!y)return;let it=null,ct=null;if(!qe){if(st.kind==="tool"){const I=Ee,se=I.state?.time,je=Y(I);if(!(!re&&je))return;const Ie=ae[I.id];ct=e.jsx(Ft,{children:e.jsx(xo,{part:I,isExpanded:d.has(I.id),onToggle:m,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:Ie?.hasPrev??!1,hasNextTool:Ie?.hasNext??!1})},`tool-${I.id}`),it=je&&typeof se?.end=="number"?se.end:null}ct&&_e.push({part:Ee,index:Ke,endTime:it,element:ct});return}if(!y.isWorking||y.isGroupExpanded||y.previewedPartIds.has(st.id)||!w&&st.kind!=="tool")return;const U=Ue.has(st.id);switch(st.kind){case"tool":{const I=Ee,se=I.state?.time,je=Y(I);if(!(!re&&je))break;const Ie=ae[I.id],$e=e.jsx(Ft,{children:e.jsx(xo,{part:I,isExpanded:d.has(I.id),onToggle:m,syntaxTheme:n,isMobile:o,onContentChange:h,hasPrevTool:Ie?.hasPrev??!1,hasNextTool:Ie?.hasNext??!1})},`tool-${I.id}`);ct=U?e.jsx(Xn,{isMigrating:We,children:$e},`migrating-tool-${I.id}`):$e,it=je&&typeof se?.end=="number"?se.end:null;break}case"reasoning":{if(!w)break;const I=Ee.time,$=typeof I?.end=="number";if(!($&&!A))break;const je=e.jsx(Ft,{children:e.jsx($l,{part:Ee,messageId:r,onContentChange:h})},`reasoning-${Ke}`);ct=U?e.jsx(Xn,{isMigrating:We,children:je},`migrating-reasoning-${Ke}`):je,it=$?I?.end??null:null;break}case"justification":{if(!w)break;const I=Ee.time,$=typeof I?.end=="number";if(!($&&!Be))break;const je=e.jsx(Ft,{children:e.jsx(Bp,{part:Ee,messageId:r,streamPhase:"completed",allowAnimation:!1,onContentChange:h,renderAsReasoning:!0})},`assistant-text-${Ke}`);ct=U?e.jsx(Xn,{isMigrating:We,children:je},`migrating-text-${Ke}`):je,it=$?I?.end??null:null;break}}ct&&_e.push({part:Ee,index:Ke,endTime:it,element:ct})}),_e.sort((Ee,Ke)=>Ee.endTime===null&&Ke.endTime===null?Ee.index-Ke.index:Ee.endTime===null?1:Ke.endTime===null?-1:Ee.endTime-Ke.endTime),_e.forEach(({element:Ee})=>{ge.push(Ee)}),ge},[Se,i,j,d,x,We,o,Y,r,h,c,v,f,m,Ue,Be,A,re,qe,g,w,n,ae,y,Oe,P]),He=y?.turnId,at=pe(ge=>ge.currentSessionId),Ge=Qe(ge=>{if(!He||!at)return;const _e=ge.messages.get(at);if(!_e)return;const Ee=_e.find(it=>it.info?.id===He);if(!Ee)return;const st=Ee.info.summary?.body;return typeof st=="string"&&st.trim().length>0?st:void 0}),ye=typeof y?.summaryBody=="string"&&y.summaryBody.trim().length>0?y.summaryBody:Ge,R=l.useRef(void 0);ye&&ye.trim().length>0&&(R.current=ye);const Q=l.useRef(He);Q.current!==He&&(Q.current=He,R.current=void 0);const te=R.current,ce=y?.isLastAssistantInTurn&&te&&te.trim().length>0,Fe=x&&F.length>0&&X&&z,[nt,De]=l.useState(!1),Re=e.jsxs(e.Fragment,{children:[v&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":S||k?"true":void 0,className:T("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!J&&"opacity-50",(S||k)&&"text-primary"),disabled:!J,"aria-label":"Copy message text","aria-hidden":!J,onPointerDown:ge=>ge.stopPropagation(),onClick:ue,onFocus:()=>{J&&b(!0)},onBlur:()=>{k||b(!1)},children:k?e.jsx(jt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(ws,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ce,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:ge=>ge.stopPropagation(),onClick:K,children:e.jsx(gd,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new session from this answer"})]})]});return e.jsx("div",{className:T("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:M&&D&&J?be:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[Ve,ce&&e.jsx(Ft,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>De(!0),onMouseLeave:()=>De(!1),children:[e.jsx(Lp,{content:te}),Fe&&e.jsx("div",{className:T("mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",nt&&"opacity-100 pointer-events-auto"),children:Re})]})},"summary-body")]}),e.jsx(Nl,{files:s,onShowPopup:f}),!ce&&Fe&&e.jsx("div",{className:"mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",children:Re})]})})},wh=({isUser:r,...s})=>r?e.jsx(yh,{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(bh,{...s}),ti=l.memo(wh),Jn=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}},vh=l.lazy(()=>Js(()=>import("./ToolOutputDialog-JB7cKw3B.js"),__vite__mapDeps([5,1,2,3,4])));function Zn(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 as=(r,s)=>{if(typeof r=="object"&&r!==null)return r[s]},jh=({message:r,previousMessage:s,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:c,hasTouchInput:d}=St(),{currentTheme:m}=nr(),f=l.useRef(null),u=pe(Eo($=>({lifecyclePhase:$.messageStreamStates.get(r.info.id)?.phase??null,isStreamingMessage:(()=>{const se=r.info.sessionID??$.currentSessionId??null;return se?($.streamingMessageIds.get(se)??null)===r.info.id:!1})(),currentSessionId:$.currentSessionId,getCurrentAgent:$.getCurrentAgent,getSessionAgentSelection:$.getSessionAgentSelection,getAgentModelForSession:$.getAgentModelForSession,getSessionModelSelection:$.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:h,currentSessionId:g,getCurrentAgent:x,getSessionAgentSelection:v,getAgentModelForSession:j,getSessionModelSelection:N}=u,w=gt($=>$.providers),y=Le($=>$.showReasoningTraces);l.useEffect(()=>{g&&ks.getInstance().recordSessionStart(g)},[g]);const[S,b]=l.useState(null),[C,D]=l.useState(!1),[k,M]=l.useState(new Set),[E,P]=l.useState({open:!1,title:"",content:""}),F=l.useMemo(()=>Jn(r.info),[r.info]).isUser,O=l.useMemo(()=>F?r.parts.map($=>$.type==="compaction"?{type:"text",text:"/summarize"}:$):r.parts,[F,r.parts]),z=l.useMemo(()=>{if(F||!s)return null;const $=as(s.info,"clientRole"),se=as(s.info,"role");if((typeof $=="string"?$:typeof se=="string"?se:void 0)!=="user")return null;const Pe=as(s.info,"mode"),Ie=as(s.info,"providerID"),$e=as(s.info,"modelID"),ot=typeof Pe=="string"&&Pe.trim().length>0?Pe:void 0,Nt=typeof Ie=="string"&&Ie.trim().length>0?Ie:void 0,At=typeof $e=="string"&&$e.trim().length>0?$e:void 0;return!ot&&!Nt&&!At?null:{agentName:ot,providerId:Nt,modelId:At}},[F,s]),X=l.useMemo(()=>{if(F)return;const $=as(r.info,"mode");if(typeof $=="string"&&$.trim().length>0)return $;if(z?.agentName)return z.agentName;const se=r.info.sessionID;if(!se)return;const je=x(se);return je||(v(se)??void 0)},[F,r.info,z,x,v]),L=r.info.sessionID,V=F?null:as(r.info,"providerID"),Y=F?null:as(r.info,"modelID"),ie=l.useMemo(()=>{if(F||!L)return null;if(z?.providerId&&z?.modelId)return{providerId:z.providerId,modelId:z.modelId};if(X){const se=j(L,X);if(se?.providerId&&se?.modelId)return se}const $=N(L);return $?.providerId&&$?.modelId?$:null},[F,L,X,z,j,N]),we=l.useMemo(()=>F?null:typeof V=="string"&&V.trim().length>0?V:ie?.providerId??null,[F,V,ie]),ke=l.useMemo(()=>F?null:typeof Y=="string"&&Y.trim().length>0?Y:ie?.modelId??null,[F,Y,ie]),ze=l.useMemo(()=>{if(!F&&we&&ke&&w.length>0){const $=w.find(se=>se.id===we);if($?.models&&Array.isArray($.models)){const Pe=$.models.find(Ie=>Ie.id===ke)?.name;return typeof Pe=="string"?Pe:void 0}}},[F,we,ke,w]),de=Zn(X),le=Zn(we??void 0),ve=Zn(ze),ee=de??void 0,Be=le??null,re=ve??void 0,A=l.useMemo(()=>{const $=r.info.time;return typeof $?.completed=="number"?$.completed:null},[r.info.time]),ne=l.useMemo(()=>F?!0:!!(A&&A>0),[F,A]),G=l.useMemo(()=>gh(O,{includeReasoning:y}),[O,y]),B=l.useMemo(()=>F||ne?G:[],[F,ne,G]),_=l.useMemo(()=>F?[]:G.filter($=>$.type==="text"),[F,G]),q=l.useMemo(()=>F?[]:G.filter($=>$.type==="tool"),[F,G]),J=l.useMemo(()=>{if(!F)return;const $=r.parts.find(Ie=>Ie.type==="agent");if(!$)return;const se=$,je=typeof se.name=="string"?se.name:void 0;if(!je)return;const Pe=se.source&&typeof se.source.value=="string"&&se.source.value.trim().length>0?se.source.value:`#${je}`;return{name:je,token:Pe}},[F,r.parts]),be=l.useMemo(()=>{let $=0,se=0;return G.forEach(je=>{je.type==="step-start"?$+=1:je.type==="step-finish"&&(se+=1)}),{hasOpenStep:$>se}},[G]).hasOpenStep,ue=l.useMemo(()=>F?!1:_.length===0||q.length===0?be:!0,[_.length,q.length,be,F]),K=m?.metadata.variant,ae=l.useMemo(()=>K?K==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[K]),H=l.useMemo(()=>m?Pl(m):ae?kp:Cp,[m,ae]),Me=l.useMemo(()=>F?!1:ks.getInstance().shouldAnimateMessage(r.info,g||r.info.sessionID),[r.info,g,F]),Se=l.useMemo(()=>s?Jn(s.info):null,[s]),Oe=l.useMemo(()=>t?Jn(t.info):null,[t]),et=l.useMemo(()=>F||!Se?!0:Se.isUser,[F,Se]),tt=l.useMemo(()=>F||!Oe?!1:!Oe.isUser&&Oe.role==="assistant",[F,Oe]),qe=l.useMemo(()=>ne?"completed":p||(h?"streaming":"completed"),[ne,p,h]),Ze=l.useCallback($=>{navigator.clipboard.writeText($),b($),setTimeout(()=>b(null),2e3)},[]),Ue=i?.turnId,We=Qe($=>{if(!Ue)return;const se=r.info.sessionID;if(!se)return;const je=$.messages.get(se);if(!je)return;const Pe=je.find(ot=>ot.info?.id===Ue);if(!Pe)return;const $e=Pe.info.summary?.body;return typeof $e=="string"&&$e.trim().length>0?$e:void 0}),Ve=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:We,He=l.useRef(void 0);Ve&&Ve.trim().length>0&&(He.current=Ve);const at=l.useRef(Ue);at.current!==Ue&&(at.current=Ue,He.current=void 0);const Ge=He.current,ye=l.useMemo(()=>F?B.filter(je=>je.type==="text").map(je=>(je.text||je.content||"").trim()).filter(je=>je.length>0).join(`
|
|
35
35
|
`).replace(/\n\s*\n+/g,`
|
|
36
36
|
`):Ge&&Ge.trim().length>0?Ge:Ji(B),[Ge,B,F]),R=ye.length>0,Q=l.useCallback(()=>{navigator.clipboard.writeText(ye),D(!0),setTimeout(()=>D(!1),2e3)},[ye]),te=l.useCallback($=>{M(se=>{const je=new Set(se);return je.has($)?je.delete($):je.add($),je})},[]),ce=o??null,Fe=l.useRef(!1),nt=l.useRef(!1),De=l.useRef(!1),Re=l.useRef(!1),ge=l.useRef(!1);l.useEffect(()=>{nt.current=!1,De.current=!1,Re.current=!1,ge.current=!1,Fe.current=!1},[r.info.id]);const _e=l.useCallback(()=>{F||Fe.current||(Fe.current=!0,n?.("structural"))},[F,n]),Ee=l.useCallback($=>{$.image&&P($)},[]),Ke=l.useCallback($=>{P(se=>({...se,open:$}))},[]),st=!!as(r.info,"animationSettled"),it=qe==="streaming",ct=l.useMemo(()=>F?!1:G.some($=>$.type==="reasoning"),[F,G]),U=Me&&!st&&!it,I=!F&&Me&&_.length>0&&!ue;return l.useEffect(()=>{if(ce?.onStreamingCandidate){if(!I){De.current&&(ct&&ce?.onReasoningBlock?ce.onReasoningBlock():ce?.onReservationCancelled&&ce.onReservationCancelled(),De.current=!1);return}ge.current||(ge.current=!0,ce.onStreamingCandidate(),De.current=!0)}},[ce,I,ct]),l.useEffect(()=>{ce?.onAnimationStart&&U&&(Re.current||(ce.onAnimationStart(),Re.current=!0))},[ce,U]),l.useEffect(()=>{if(F)return;const $=ce?.onAnimatedHeightChange;if(!$||!(U||I))return;const je=f.current;if(!je)return;if(typeof window>"u"||typeof ResizeObserver>"u"){$(je.getBoundingClientRect().height);return}let Pe=null;const Ie=ot=>{if(typeof window>"u"){$(ot);return}Pe!==null&&window.cancelAnimationFrame(Pe),Pe=window.requestAnimationFrame(()=>{$(ot)})},$e=new ResizeObserver(ot=>{const Nt=ot[0];Nt&&Ie(Nt.contentRect.height)});return $e.observe(je),Ie(je.getBoundingClientRect().height),()=>{Pe!==null&&(window.cancelAnimationFrame(Pe),Pe=null),$e.disconnect()}},[U,F,ce,I]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:T("group w-full",et?"pt-2":"pt-0",F?"pb-2":tt?"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(Ft,{children:e.jsx("div",{className:T("rounded-xl border bg-input/10 dark:bg-input/30 pt-2 pb-2.5 relative"),style:{borderColor:"color-mix(in srgb, var(--primary-muted, var(--primary)) 40%, var(--interactive-border, transparent))"},children:e.jsx(ti,{messageId:r.info.id,parts:G,isUser:F,isMessageCompleted:ne,syntaxTheme:H,isMobile:c,hasTouchInput:d,copiedCode:S,onCopyCode:Ze,expandedTools:k,onToggleTool:te,onShowPopup:Ee,streamPhase:qe,allowAnimation:U,onContentChange:n,shouldShowHeader:!1,hasTextContent:R,onCopyMessage:Q,copiedMessage:C,showReasoningTraces:y,onAuxiliaryContentComplete:_e,agentMention:J})})}):e.jsxs("div",{children:[et&&e.jsx(Ap,{isUser:F,providerID:Be,agentName:ee,modelName:re,isDarkTheme:ae}),e.jsx(ti,{messageId:r.info.id,parts:G,isUser:F,isMessageCompleted:ne,syntaxTheme:H,isMobile:c,hasTouchInput:d,copiedCode:S,onCopyCode:Ze,expandedTools:k,onToggleTool:te,onShowPopup:Ee,streamPhase:qe,allowAnimation:U,onContentChange:n,shouldShowHeader:et,hasTextContent:R,onCopyMessage:Q,copiedMessage:C,onAuxiliaryContentComplete:_e,showReasoningTraces:y,agentMention:J,turnGroupingContext:i})]})})}),e.jsx(l.Suspense,{fallback:null,children:e.jsx(vh,{popup:E,onOpenChange:Ke,syntaxTheme:H,isMobile:c})})]})},Sh=l.memo(jh),Nh=r=>{const s="h-3 w-3",t=r.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(ds,{className:s}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Ds,{className:s}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(no,{className:s}):e.jsx(To,{className:s})},kh=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},Ch=({permission:r,onResponse:s})=>{const[t,n]=l.useState(!1),[o,a]=l.useState(!1),{respondToPermission:i}=pe(),{currentTheme:c}=nr(),d=l.useMemo(()=>Pl(c),[c]),m=async j=>{n(!0);try{await i(r.sessionID,r.id,j),a(!0),s?.(j)}catch{}finally{n(!1)}};if(o)return null;const f=r.type||"Unknown Tool",u=f.toLowerCase(),p=(j,N="")=>{const w=r.metadata[j];return typeof w=="string"?w:typeof w=="number"?String(w):N},h=j=>{const N=r.metadata[j];return typeof N=="number"?N:void 0},g=j=>!!r.metadata[j],x=kh(f),v=()=>{if(u==="bash"||u==="shell"||u==="shell_command"){const w=p("command")||p("cmd")||p("script"),y=p("description"),S=p("cwd")||p("working_directory")||p("directory")||p("path"),b=h("timeout"),C=r.title===w;return e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:y}),S&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Working Directory:"})," ",e.jsx("code",{className:"px-1 py-0.5 bg-muted/30 rounded",children:S})]}),b&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",b,"ms"]}),w&&!C&&e.jsx("div",{children:e.jsx(ls,{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:w})})]})}if(u==="edit"||u==="multiedit"||u==="str_replace"||u==="str_replace_based_edit_tool"){const w=p("path")||p("file_path")||p("filename")||p("filePath"),y=p("old_str")||p("oldString")||p("old_content")||p("before"),S=p("new_str")||p("newString")||p("new_content")||p("after"),b=p("changes")||p("diff"),C=g("replace_all")||g("replaceAll");return e.jsxs(e.Fragment,{children:[w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"File Path:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:w})]}),C&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),b?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Changes:"}),e.jsx(Je,{outerClassName:"max-h-64",className:"overflow-x-auto p-0",children:e.jsx(ls,{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:b})})]}):e.jsxs(e.Fragment,{children:[y&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Remove:"}),e.jsx(Je,{outerClassName:"max-h-32 border border-red-500/20 rounded bg-red-500/5 p-2",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono text-red-600 dark:text-red-400 whitespace-pre-wrap break-all",children:y.length>500?y.substring(0,500)+"...":y})})]}),S&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Replace with:"}),e.jsx(Je,{outerClassName:"max-h-32 border border-green-500/20 rounded bg-green-500/5 p-2",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono text-green-600 dark:text-green-400 whitespace-pre-wrap break-all",children:S.length>500?S.substring(0,500)+"...":S})})]})]})]})}if(u==="webfetch"||u==="fetch"||u==="curl"||u==="wget"){const w=p("url")||p("uri")||p("endpoint"),y=p("method")||"GET",S=r.metadata.headers&&typeof r.metadata.headers=="object"?r.metadata.headers:void 0,b=p("body")||p("data")||p("payload"),C=h("timeout"),D=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[w&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"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:y}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:w})]})]}),S&&Object.keys(S).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(Je,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(ls,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(S,null,2)})})]}),b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(Je,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(ls,{language:typeof b=="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 b=="object"?JSON.stringify(b,null,2):String(b)})})]}),(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 j=p("command")||p("content")||p("action")||p("operation"),N=p("description");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),j&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(Je,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(j)})})]}),Object.keys(r.metadata).length>0&&!j&&!N&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(Je,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(r.metadata,null,2)})})]})]})};return e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20 bg-muted/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jr,{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:[Nh(f),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:x})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[(()=>{let j="",N="text",w=!1;u==="bash"||u==="shell"||u==="shell_command"?(j=p("command")||p("cmd")||p("script"),N="bash",w=!0):u==="edit"||u==="multiedit"||u==="str_replace"||u==="str_replace_based_edit_tool"?(j=p("path")||p("file_path")||p("filename")||p("filePath"),w=!1):(u==="webfetch"||u==="fetch")&&(j=p("url")||p("uri")||p("endpoint"),w=!1);const y=r.title===j;return y&&j&&w?e.jsx("div",{className:"mb-3",children:e.jsx(ls,{language:N,style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:j})}):y&&j&&!w?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:j})}):r.title?e.jsx("div",{className:T("typography-ui-label text-foreground mb-3",(w||j)&&"font-mono"),children:r.title}):null})(),v()]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>m("once"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:j=>{j.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:j=>{j.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(jt,{className:"h-3 w-3"}),"Allow Once"]}),e.jsxs("button",{onClick:()=>m("always"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:j=>{j.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:j=>{j.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(xd,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>m("reject"),disabled:t,className:T("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:j=>{j.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:j=>{j.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(ss,{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},Ah=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}}}},Dh=r=>{const s=Ah(r);let t;const o=r.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let m=0,f=0,u=0;o.forEach(p=>{if(!p)return;const h=typeof p.additions=="number"?p.additions:0,g=typeof p.deletions=="number"?p.deletions:0;(h!==0||g!==0)&&(u+=1),m+=h,f+=g}),u>0&&(t={additions:m,deletions:f,files:u})}let a=!1,i=!1;r.assistantMessages.forEach(m=>{m.parts.forEach(f=>{f.type==="tool"?a=!0:f.type==="reasoning"&&(i=!0)})});const c=[];let d=0;return r.assistantMessages.forEach(m=>{const f=m.info.id;m.parts.forEach(u=>{const p=typeof u.id=="string"&&u.id.trim().length>0?u.id:`${f}-activity-${d++}`;if(u.type==="tool"){const g=u.state?.time,x=typeof g?.end=="number"?g.end:void 0;c.push({id:p,turnId:r.turnId,messageId:f,kind:"tool",part:u,endedAt:x});return}if(u.type==="reasoning"){const h=u.text??u.content;if(typeof h!="string"||h.trim().length===0)return;const g=u.time,x=typeof g?.end=="number"?g.end:void 0;c.push({id:p,turnId:r.turnId,messageId:f,kind:"reasoning",part:u,endedAt:x});return}})}),{activityParts:c,hasTools:a,hasReasoning:i,summaryBody:s,diffStats:t}},Eh=r=>{const{isWorking:s}=El(),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(x=>{h.set(x.info.id,g)})}),h},[t]),a=l.useMemo(()=>{const h=new Map;return t.forEach(g=>{h.set(g.turnId,Dh(g))}),h},[t]),[i,c]=l.useState(()=>new Map),d=l.useCallback(h=>{const g=i.get(h);return g||{isExpanded:!1,previewedPartIds:new Set}},[i]),m=l.useCallback(h=>{c(g=>{const x=new Map(g),v=x.get(h)??{isExpanded:!1,previewedPartIds:new Set};return x.set(h,{...v,isExpanded:!v.isExpanded}),x})},[]),f=l.useCallback((h,g)=>{g.length!==0&&c(x=>{const v=new Map(x),j=v.get(h)??{isExpanded:!1,previewedPartIds:new Set},N=new Set(j.previewedPartIds);return g.forEach(w=>{w&&w.trim().length>0&&N.add(w)}),v.set(h,{...j,previewedPartIds:N}),v})},[]),u=l.useCallback(h=>o.get(h),[o]),p=l.useCallback(h=>{const g=o.get(h);if(!g||!g.assistantMessages.some(P=>P.info.id===h))return;const v=a.get(g.turnId),j=v?.activityParts??[],N=!!v?.hasTools,w=!!v?.hasReasoning,y=v?.summaryBody,S=v?.diffStats,b=g.assistantMessages[0]?.info.id,C=h===b,D=g.assistantMessages[g.assistantMessages.length-1]?.info.id,k=h===D,M=d(g.turnId),E=s&&n===g.turnId;return{turnId:g.turnId,isFirstAssistantInTurn:C,isLastAssistantInTurn:k,summaryBody:y,activityParts:j,hasTools:N,hasReasoning:w,diffStats:S,isWorking:E,isGroupExpanded:M.isExpanded,previewedPartIds:M.previewedPartIds,toggleGroup:()=>m(g.turnId),markPartsPreviewed:P=>f(g.turnId,P)}},[d,n,f,o,s,m,a]);return{turns:t,getTurnForMessage:u,getContextForMessage:p}},Th=({messages:r,permissions:s,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:c,pendingAnchorId:d})=>{l.useEffect(()=>{s.length!==0&&t("permission")},[s,t]);const m=l.useMemo(()=>r.filter(u=>!po(u.parts)),[r]),{getContextForMessage:f}=Eh(m);return e.jsxs("div",{children:[o&&e.jsx("div",{className:"flex justify-center py-3",children:a?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:i,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:m.map((u,p)=>e.jsx(Sh,{message:u,previousMessage:p>0?m[p-1]:void 0,nextMessage:p<m.length-1?m[p+1]:void 0,onContentChange:t,animationHandlers:n(u.info.id),scrollToBottom:c,isPendingAnchor:d===u.info.id,turnGroupingContext:f(u.info.id)},u.info.id))}),s.length>0&&e.jsx("div",{children:s.map(u=>e.jsx(Ch,{permission:u},u.id))})]})},Ih=l.memo(Th);function Ph(...r){return s=>{r.forEach(t=>{typeof t=="function"?t(s):t&&typeof t=="object"&&(t.current=s)})}}const Ul=l.forwardRef(({orientation:r="vertical",offset:s=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:c,children:d,...m},f)=>{const u=l.useRef(null),p=l.useRef("none"),h=m["data-scroll-shadow"];delete m["data-scroll-shadow"];const g=l.useMemo(()=>{const N={...i};return N["--scroll-shadow-size"]=`${t}px`,N},[t,i]),x=l.useCallback((N,w,y,S,b)=>{const C=`${S}${b.charAt(0).toUpperCase()}${b.slice(1)}Scroll`;w&&y?(N.dataset[C]="true",N.removeAttribute(`data-${S}-scroll`),N.removeAttribute(`data-${b}-scroll`)):(N.dataset[`${S}Scroll`]=String(w),N.dataset[`${b}Scroll`]=String(y),N.removeAttribute(`data-${S}-${b}-scroll`))},[]),v=l.useCallback(N=>{["top","bottom","top-bottom","left","right","left-right"].forEach(w=>{N.removeAttribute(`data-${w}-scroll`)})},[]),j=l.useCallback(()=>{const N=u.current;if(!N)return;if(!n){v(N);return}const w=r==="vertical"?N.scrollTop>s:N.scrollLeft>s;let y=r==="vertical"?N.scrollTop+N.clientHeight+s<N.scrollHeight:N.scrollLeft+N.clientWidth+s<N.scrollWidth;o&&r==="vertical"&&(y=!1),x(N,w,y,r==="vertical"?"top":"left",r==="vertical"?"bottom":"right");const S=w&&y?"both":w?r==="vertical"?"top":"left":y?r==="vertical"?"bottom":"right":"none";S!==p.current&&(p.current=S,a?.(S))},[v,o,n,s,a,r,x]);return l.useEffect(()=>{const N=u.current;if(!N)return;const w=()=>j(),y=typeof ResizeObserver<"u"?new ResizeObserver(()=>j()):null,S=typeof MutationObserver<"u"?new MutationObserver(()=>j()):null;return j(),N.addEventListener("scroll",w,{passive:!0}),y?.observe(N),S?.observe(N,{childList:!0,subtree:!0,characterData:!0}),()=>{N.removeEventListener("scroll",w),y?.disconnect(),S?.disconnect()}},[j]),e.jsx("div",{...m,ref:Ph(u,f),className:c,"data-orientation":r,"data-scroll-shadow":h??!0,style:g,children:d})});Ul.displayName="ScrollShadow";const Rh=160,Fh=({containerRef:r})=>{const[s,t]=l.useState(!0),n=l.useRef(!0),o=l.useRef(!1),a=l.useRef(null),i=l.useRef(null),c=l.useRef(0),d=l.useRef(0),m=l.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),f=l.useCallback(w=>{const y=r.current;if(!y){m();return}i.current===null&&(i.current=w);const S=Math.min(1,(w-i.current)/Rh),b=1-Math.pow(1-S,3),C=c.current,D=d.current,k=C+(D-C)*b;if(y.scrollTop=k,S<1){a.current=window.requestAnimationFrame(f);return}y.scrollTop=D,m(),n.current&&(n.current=!1,t(!1))},[m,r,t]),u=l.useCallback((w,y)=>{const S=r.current;if(!S)return;const b=Math.max(0,w),C=y?.instant??!1;if(o.current=!1,typeof window>"u"||C){m(),S.scrollTop=b;const k=b<=1;n.current!==k&&(n.current=k,t(k));return}if(m(),Math.abs(b-S.scrollTop)<=.5){S.scrollTop=b;const k=b<=1;n.current!==k&&(n.current=k,t(k));return}c.current=S.scrollTop,d.current=b,i.current=null,a.current=window.requestAnimationFrame(f)},[m,r,f,t]),p=l.useCallback(()=>{o.current=!0},[]),h=l.useCallback(()=>{o.current=!0},[]),g=l.useCallback(()=>o.current,[]),x=l.useCallback(()=>r.current?.scrollTop??0,[r]),v=l.useCallback(()=>r.current?.scrollHeight??0,[r]),j=l.useCallback(()=>r.current?.clientHeight??0,[r]),N=l.useCallback(()=>{const w=r.current;if(!w)return;o.current&&a.current!==null&&m();const y=w.scrollTop<=1;n.current!==y&&(n.current=y,t(y))},[m,r]);return l.useEffect(()=>{const w=r.current;if(w)return w.addEventListener("wheel",h,{passive:!0}),w.addEventListener("touchstart",h,{passive:!0}),()=>{w.removeEventListener("wheel",h),w.removeEventListener("touchstart",h)}},[r,h]),l.useEffect(()=>()=>{m()},[m]),l.useMemo(()=>({handleScroll:N,scrollToPosition:u,forceManualMode:p,isAtTop:s,isManualOverrideActive:g,getScrollTop:x,getScrollHeight:v,getClientHeight:j}),[N,u,p,s,g,x,v,j])},si=typeof window<"u"?l.useLayoutEffect:l.useEffect,ri=50,ni=40,_h=.2,Lh=.1,Oh=150,Vt=r=>{const s=r.info;return typeof s?.id=="string"?s.id:null},$h=r=>{const s=r.info;if(s?.userMessageMarker===!0)return!0;const t=s?.clientRole,n=s?.role;return t==="user"||n==="user"},zh=({currentSessionId:r,sessionMessages:s,updateViewportAnchor:t,isSyncing:n,isMobile:o,sessionActivityPhase:a})=>{const i=l.useRef(null),c=Fh({containerRef:i}),[d,m]=l.useState(null),[f,u]=l.useState(0),[p,h]=l.useState(!1),[g,x]=l.useState(null),v=l.useRef(null),j=l.useRef(null),N=l.useRef(s.length),w=l.useRef(s.length>0?Vt(s[0]):null),y=l.useRef(s.length>0?Vt(s[s.length-1]):null),S=l.useRef(0),b=l.useRef(0),C=l.useRef(void 0),D=l.useRef(null),k=l.useRef(!1),M=l.useRef(!1),E=r?a?.get(r)??"idle":"idle",P=l.useCallback(de=>{const le=Math.max(0,de);S.current!==le&&(S.current=le,u(le))},[]),W=l.useCallback(()=>{const de=i.current;de&&(b.current=de.clientHeight)},[]),F=l.useCallback(()=>{if(!d)return null;const de=i.current;return de?de.querySelector(`[data-message-id="${d}"]`):null},[d]),O=l.useCallback(()=>{const de=i.current,le=S.current;if(!de||le<=0)return!0;const ve=de.scrollHeight-le;return de.scrollTop+de.clientHeight<ve},[]),z=l.useCallback((de,le)=>{const ve=de.offsetHeight,ee=de.offsetTop;if(ve>le*_h){const re=le*Lh;return ee+ve-re}else return ee-ri},[]),X=l.useCallback(()=>{const de=i.current;if(!de||!D.current)return;const le=F();if(!le)return;const ve=de.clientHeight,ee=de.scrollHeight,re=z(le,ve)+ve,A=S.current,ne=ee-A;if(!k.current&&ne<re){const G=re-ne;G>A&&P(G)}},[z,F,P]),L=l.useCallback(()=>{const de=i.current;if(!de){h(!1);return}if(g){h(!1);return}if(!(de.scrollHeight>de.clientHeight)){h(!1);return}const ve=de.scrollHeight-de.scrollTop-de.clientHeight,ee=S.current;if(ee>0){const Be=de.scrollHeight-ee,re=de.scrollTop+de.clientHeight;h(re<Be)}else h(ve>ni)},[g]),V=l.useCallback(de=>{const le=i.current;if(!le)return;const ve=le.scrollHeight-le.scrollTop-le.clientHeight;if(M.current&&E==="idle"&&!n&&!de?.force&&ve>ni)return;de?.force&&(M.current=!1);const Be=le.scrollHeight-le.clientHeight;c.scrollToPosition(Math.max(0,Be),de)},[E,n,c]),Y=l.useCallback(de=>{if(v.current===de)return;v.current=de,x(de);const le=i.current;if(!le){x(null);return}const ve=le.scrollHeight,ee=S.current,Be=ve-ee,re=b.current>0?b.current:le.clientHeight,ne=Be-ri,G=ne+re;let B=0;Be<G&&(B=G-Be),B!==ee&&P(B),k.current=!0,window.requestAnimationFrame(()=>{c.scrollToPosition(ne,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[c,P]),ie=l.useCallback(de=>{const le=i.current;if(!le||!r)return;de?.isTrusted&&(M.current=!0),c.handleScroll(),L(),E==="idle"&&S.current>0&&O()&&(P(0),D.current=null,m(null));const{scrollTop:ve,scrollHeight:ee,clientHeight:Be}=le,re=(ve+Be/2)/Math.max(ee,1),A=Math.floor(re*s.length);t(r,A)},[r,E,O,c,s.length,L,P,t]);l.useEffect(()=>{const de=i.current;if(de)return de.addEventListener("scroll",ie,{passive:!0}),()=>{de.removeEventListener("scroll",ie)}},[ie]),si(()=>{if(typeof window>"u")return;W();const de=()=>{C.current!==void 0&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{W()},Oh)};return window.addEventListener("resize",de),()=>{window.removeEventListener("resize",de),C.current!==void 0&&window.clearTimeout(C.current)}},[W]),l.useEffect(()=>{r&&r!==j.current&&(j.current=r,ks.getInstance().recordSessionStart(r),N.current=s.length,w.current=s.length>0?Vt(s[0]):null,y.current=s.length>0?Vt(s[s.length-1]):null,v.current=null,D.current=null,k.current=!1,m(null),S.current=0,u(0),M.current=!1)},[r,s.length]),si(()=>{if(n){N.current=s.length,w.current=s.length>0?Vt(s[0]):null,y.current=s.length>0?Vt(s[s.length-1]):null;return}if(j.current!==r)return;const de=N.current,le=s.length;if(le>de&&de>0){const ve=w.current,ee=Vt(s[0]),Be=Vt(s[le-1]),re=y.current,A=ve!==null&&ee!==ve,ne=re!==null&&Be!==re,G=A&&!ne,B=ne&&!A;if(G){D.current=null,k.current=!1,m(null),P(0),N.current=le,w.current=ee,y.current=Be;return}if(B){const q=s.slice(de,le).find($h);if(q){const J=Vt(q);J&&(D.current=J,m(J),Y(J))}else X()}}N.current=le,w.current=s.length>0?Vt(s[0]):null,y.current=s.length>0?Vt(s[s.length-1]):null},[r,n,X,Y,s]),l.useEffect(()=>{const de=i.current;if(!de||typeof ResizeObserver>"u")return;const le=new ResizeObserver(()=>{X(),L()});return le.observe(de),()=>{le.disconnect()}},[X,L]),l.useEffect(()=>{d&&(X(),L())},[d,X,L]),l.useEffect(()=>{E==="idle"&&S.current>0&&O()&&(P(0),D.current=null,k.current=!1,m(null))},[E,O,P]),l.useEffect(()=>{L()},[f,L]);const we=l.useRef(new Map),ke=l.useCallback(()=>{X(),L()},[X,L]),ze=l.useCallback(de=>{const le=we.current.get(de);if(le)return le;const ve={onChunk:()=>{X()},onComplete:()=>{X()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{X()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return we.current.set(de,ve),ve},[X]);return{scrollRef:i,handleMessageContentChange:ke,getAnimationHandlers:ze,showScrollButton:p,scrollToBottom:V,spacerHeight:f,pendingAnchorId:g,hasActiveAnchor:d!==null}},Bh=()=>{const{currentSessionId:r,messages:s,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:c,sessionMemoryState:d,isSyncing:m,messageStreamStates:f,trimToViewportWindow:u,sessionActivityPhase:p}=pe(),h=l.useMemo(()=>r?n.get(r)??null:null,[r,n]),{isMobile:g}=St(),x=l.useMemo(()=>r?s.get(r)||[]:[],[r,s]),v=l.useMemo(()=>r?t.get(r)||[]:[],[r,t]),{scrollRef:j,handleMessageContentChange:N,getAnimationHandlers:w,showScrollButton:y,scrollToBottom:S,spacerHeight:b,pendingAnchorId:C,hasActiveAnchor:D}=zh({currentSessionId:r,sessionMessages:x,updateViewportAnchor:c,isSyncing:m,isMobile:g,sessionActivityPhase:p}),M=!!l.useMemo(()=>r?d.get(r)??null:null,[r,d])?.hasMoreAbove,[E,P]=l.useState(!1);l.useEffect(()=>{P(!1)},[r]);const W=l.useRef(null);l.useLayoutEffect(()=>{if(!r||r===W.current)return;W.current=r;const O=j.current;O&&(O.scrollTop=O.scrollHeight-O.clientHeight)},[r,j]);const F=l.useCallback(async()=>{if(!r||E)return;const O=j.current,z=O?.scrollHeight??null,X=O?.scrollTop??null;P(!0);try{if(await i(r,"up"),O&&z!==null&&X!==null){const L=O.scrollHeight-z;O.scrollTop=X+L}}finally{P(!1)}},[r,E,i,j]);return l.useEffect(()=>{if(!r||(s.has(r)?s.get(r)??[]:[]).length>0)return;(async()=>{try{await a(r)}finally{typeof window>"u"?S():window.requestAnimationFrame(()=>{S()})}})()},[r,a,s,S]),r?o&&x.length===0&&!h&&!s.has(r)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",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(z=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(qn,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(qn,{className:"h-4 w-24"}),e.jsx(qn,{className:"h-20 w-full"})]})]},z))})}),e.jsx(Gn,{scrollToBottom:S})]}):x.length===0&&!h?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Qa,{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(Gn,{scrollToBottom:S})})]}):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(Ul,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:j,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(Ih,{messages:x,permissions:v,onMessageContentChange:N,getAnimationHandlers:w,hasMoreAbove:M,isLoadingOlder:E,onLoadOlder:F,scrollToBottom:S,pendingAnchorId:C}),b>0&&D&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:b},"aria-hidden":"true"})]})}),e.jsx(Bo,{containerRef:j})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[y&&x.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ce,{variant:"outline",size:"sm",onClick:()=>S({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(pr,{className:"h-4 w-4"})})}),e.jsx(Gn,{scrollToBottom:S})]})]}):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(Qa,{width:140,height:140,className:"opacity-20",isAnimated:!0})})})};class Hh 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(zo,{className:"w-full max-w-md",children:[e.jsx(al,{className:"text-center",children:e.jsxs(il,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(yd,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(ll,{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(Ce,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(er,{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 yo=()=>{const r=pe(s=>s.currentSessionId);return e.jsx(Hh,{sessionId:r||void 0,children:e.jsx(Bh,{})})},oi=12,Wh=[{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"}],Uh=({isActive:r,burstKey:s=0,className:t,durationMs:n=900,bursts:o=Wh,onComplete:a})=>{const i=fe.useRef(!1);fe.useEffect(()=>{!r&&i.current&&a?.(),r&&(i.current=!0)},[r,a]);const c=fe.useMemo(()=>Array.from({length:oi},(d,m)=>{const f=Math.PI*2*m/oi;return{x:Math.cos(f),y:Math.sin(f),delay:m*18}}),[]);return r?e.jsx("div",{className:T("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":s,children:o.map(d=>{const m={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:m,children:c.map((f,u)=>{const p=f.x*d.radius,h=f.y*d.radius,g={"--translate-x":`${p}px`,"--translate-y":`${h}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:g},`${d.id}-${u}-${s}`)})},`${d.id}-${s}`)})}):null},Vh=({durationMs:r=3400}={})=>{const[s,t]=fe.useState({isActive:!1,cycle:0}),n=fe.useRef(null),o=fe.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=fe.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),i=fe.useCallback(()=>{o(),t(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{t(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},r)},[o,r]);return fe.useEffect(()=>()=>o(),[o]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:i,dismissFireworks:a}},Vl=l.createContext(void 0),ai=({children:r})=>{const{isActive:s,burstKey:t,triggerFireworks:n,dismissFireworks:o}=Vh(),a=l.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Vl.Provider,{value:a,children:[r,e.jsx(Uh,{isActive:s,burstKey:t})]})},Gh=()=>{const r=l.useContext(Vl);if(!r)throw new Error("useFireworksCelebration must be used within FireworksProvider");return r};function qh({...r}){return e.jsx(bd,{"data-slot":"select",...r})}function Kh({...r}){return e.jsx(jd,{"data-slot":"select-value",...r})}function Yh({className:r,size:s="default",children:t,...n}){return e.jsxs(wd,{"data-slot":"select-trigger","data-size":s,className:T("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-accent hover:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",r),...n,children:[t,e.jsx(vd,{asChild:!0,children:e.jsx(yt,{className:"size-4 opacity-50"})})]})}function Xh({className:r,children:s,position:t="popper",...n}){return e.jsx(Sd,{children:e.jsxs(Nd,{"data-slot":"select-content",className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",r),position:t,...n,children:[e.jsx(Zh,{}),e.jsx(Je,{as:kd,outerClassName:"max-h-[var(--radix-select-content-available-height)] w-full",className:T("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:s}),e.jsx(Qh,{})]})})}function Jh({className:r,children:s,...t}){return e.jsxs(Cd,{"data-slot":"select-item",className:T("hover:bg-accent hover:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",r),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(Md,{children:e.jsx(jt,{className:"size-4"})})}),e.jsx(Ad,{children:s})]})}function Zh({className:r,...s}){return e.jsx(Dd,{"data-slot":"select-scroll-up-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(wo,{className:"size-4"})})}function Qh({className:r,...s}){return e.jsx(Ed,{"data-slot":"select-scroll-down-button",className:T("flex cursor-default items-center justify-center py-1",r),...s,children:e.jsx(yt,{className:"size-4"})})}const eg=r=>r.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),tg=r=>r?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:r}):void 0,sg=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}];let ur=null;const rg=()=>{const{currentSessionId:r,sessions:s,worktreeMetadata:t}=pe(),{currentDirectory:n}=ht(),o=r?t.get(r)??void 0:void 0,i=s.find(c=>c.id===r)?.directory;return o?.path??i??n??void 0},ng=()=>{const{git:r}=Ws(),s=rg(),{currentSessionId:t,worktreeMetadata:n}=pe(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:c,loadGlobalIdentity:d}=kn(),m=el(s??null),f=Qi(s??null),u=Bm(s??null),p=Hm(s??null),h=Wm(s??null),g=wt(U=>U.isLoadingStatus),x=wt(U=>U.isLoadingLog),{setActiveDirectory:v,fetchAll:j,fetchStatus:N,fetchBranches:w,fetchLog:y,fetchIdentity:S,setLogMaxCount:b}=wt(),C=l.useMemo(()=>!ur||ur.directory!==s?null:ur,[s]),[D,k]=l.useState(C?.commitMessage??""),[M,E]=l.useState(""),P=l.useMemo(()=>eg(M),[M]),[W,F]=l.useState(null),[O,z]=l.useState(null),[X,L]=l.useState(!1),[V,Y]=l.useState(null),[ie,we]=l.useState(25),[ke,ze]=l.useState(!1),[de,le]=l.useState(!1),[ve,ee]=l.useState(""),[Be]=l.useState(null),{triggerFireworks:re}=Gh(),[A,ne]=l.useState(()=>new Set(C?.selectedPaths??[])),[G,B]=l.useState(!1),[_,q]=l.useState(new Set),[J,oe]=l.useState(!1),[be,ue]=l.useState([]),K=l.useCallback(()=>{ue([])},[]),[ae,H]=l.useState(null),[Me,Se]=l.useState([]),[Oe,et]=l.useState(!1),tt=l.useMemo(()=>!ae||!p?null:p.all.find(U=>U.hash===ae)??null,[ae,p]),qe=l.useCallback(U=>{navigator.clipboard.writeText(U).then(()=>{he.success("Commit hash copied")}).catch(()=>{he.error("Failed to copy")})},[]);l.useEffect(()=>{if(!ae||!s||!r){Se([]);return}let U=!1;return et(!0),r.getCommitFiles(s,ae).then(I=>{U||Se(I.files)}).catch(I=>{console.error("Failed to fetch commit files:",I),U||Se([])}).finally(()=>{U||et(!1)}),()=>{U=!0}},[ae,s,r]),l.useEffect(()=>()=>{if(!s){ur=null;return}ur={directory:s,selectedPaths:Array.from(A),commitMessage:D}},[D,s,A]),l.useEffect(()=>{c(),d()},[c,d]),l.useEffect(()=>{s&&(v(s),wt.getState().directories.get(s)?.status||j(s,r,{force:!0}))},[s,v,j,r]);const Ze=l.useCallback(async(U=!0)=>{if(s)try{await Promise.all([N(s,r),w(s,r)])}catch(I){if(U){const $=I instanceof Error?I.message:"Failed to refresh repository state";he.error($)}}},[s,r,N,w]),Ue=l.useCallback(async()=>{s&&await y(s,r,ie)},[s,r,y,ie]),We=l.useCallback(async()=>{s&&await S(s,r)},[s,r,S]),Ve=l.useMemo(()=>{if(!f)return[];const U=f.files??[],I=new Map;return U.forEach($=>{I.set($.path,$)}),Array.from(I.values()).sort(($,se)=>$.path.localeCompare(se.path))},[f]);l.useEffect(()=>{if(!f||Ve.length===0){ne(new Set),B(!1);return}ne(U=>{const I=new Set,$=U??new Set;return Ve.forEach(se=>{$.has(se.path)?I.add(se.path):G||I.add(se.path)}),I})},[f,Ve,G]);const He=async U=>{if(s){F(U);try{if(U==="fetch")await r.gitFetch(s),he.success("Fetched latest updates");else if(U==="pull"){const I=await r.gitPull(s);he.success(`Pulled ${I.files.length} file${I.files.length===1?"":"s"}`)}else U==="push"&&(await r.gitPush(s),he.success("Pushed to remote"));Y(`${U.toUpperCase()} completed at ${new Date().toLocaleTimeString()}`),await Ze(!1),await Ue()}catch(I){const $=I instanceof Error?I.message:`Failed to ${U==="pull"?"pull":U}`;he.error($)}finally{F(null)}}},at=async(U={})=>{if(!s)return;if(!D.trim()){he.error("Please enter a commit message");return}const I=Array.from(A).sort();if(I.length===0){he.error("Select at least one file to commit");return}const $=U.pushAfter?"commitAndPush":"commit";z($);try{await r.createGitCommit(s,D.trim(),{files:I}),he.success("Commit created successfully"),k(""),ne(new Set),B(!1),await Ze(),U.pushAfter?(await r.gitPush(s),he.success("Pushed to remote"),re(),await Ze(!1)):await Ze(!1),await Ue()}catch(se){const je=se instanceof Error?se.message:"Failed to create commit";he.error(je)}finally{z(null)}},Ge=l.useCallback(async()=>{if(s){if(A.size===0){he.error("Select at least one file to describe");return}oe(!0);try{const{message:U}=await r.generateCommitMessage(s,Array.from(A)),I=U.subject?.trim()??"",$=Array.isArray(U.highlights)?U.highlights:[];I&&k(I),ue($),he.success("Commit message generated")}catch(U){const I=U instanceof Error?U.message:"Failed to generate commit message";he.error(I)}finally{oe(!1)}}},[s,A,r]),ye=async()=>{if(!s||!f)return;const U=P;if(!U){he.error('Provide a branch name using letters, numbers, ".", "_", "-" or "/".');return}const I=f.current??null;L(!0);try{await r.createBranch(s,U,I??"HEAD"),he.success(`Created branch ${U}`);let $=!1;try{await r.checkoutBranch(s,U),await r.gitPush(s,{remote:"origin",branch:U,options:["--set-upstream"]}),$=!0}catch(se){const je=se instanceof Error?se.message:"Unable to push new branch to origin.";he.warning("Branch created locally",{description:tg(`Upstream setup failed: ${je}`)})}finally{if(I)try{await r.checkoutBranch(s,I)}catch(se){console.warn("Failed to restore original branch after creation:",se)}}E(""),await Ze(),await Ue(),$&&he.success(`Upstream set for ${U}`)}catch($){const se=$ instanceof Error?$.message:"Failed to create branch";he.error(se)}finally{L(!1)}},R=async U=>{if(!s)return;const I=U.replace(/^remotes\//,"");if(f?.current===I){le(!1);return}try{await r.checkoutBranch(s,I),he.success(`Checked out ${I}`),le(!1),ee(""),await Ze();const $=f?.current;$&&(await r.checkoutBranch(s,$),he.success(`Checked out ${$}`)),await Ue()}catch($){const se=$ instanceof Error?$.message:`Failed to checkout ${I}`;he.error(se)}},Q=async U=>{if(s){ze(!0);try{await r.setGitIdentity(s,U.id),he.success(`Applied "${U.name}" to repository`),await We()}catch(I){const $=I instanceof Error?I.message:"Failed to apply git identity";he.error($)}finally{ze(!1)}}},te=l.useMemo(()=>u?.all?u.all.filter(U=>!U.startsWith("remotes/")).sort():[],[u]),ce=l.useMemo(()=>u?.all?u.all.filter(U=>U.startsWith("remotes/")).map(U=>U.replace(/^remotes\//,"")).sort():[],[u]),Fe=l.useMemo(()=>{const U=ve.trim().toLowerCase();return U?{locals:te.filter(I=>I.toLowerCase().includes(U)),remotes:ce.filter(I=>I.toLowerCase().includes(U))}:{locals:te,remotes:ce}},[ve,te,ce]);l.useEffect(()=>{de||ee("")},[de]);const nt=l.useMemo(()=>{const U=new Map;i&&U.set(i.id,i);for(const I of a)U.set(I.id,I);return Array.from(U.values())},[a,i]),De=l.useMemo(()=>{if(h?.userName&&h?.userEmail){const U=a.find(I=>I.userName===h.userName&&I.userEmail===h.userEmail);return U||(i&&i.userName===h.userName&&i.userEmail===h.userEmail?i:{id:"local-config",name:h.userName,userName:h.userName,userEmail:h.userEmail,sshKey:h.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[h,a,i]),Re=Ve.length,ge=A.size,_e=g||W!==null||O!==null,Ee=U=>{ne(I=>{const $=new Set(I);return $.has(U)?$.delete(U):$.add(U),$}),B(!0)},Ke=()=>{const U=new Set(Ve.map(I=>I.path));ne(U),B(!0)},st=()=>{ne(new Set),B(!0)},it=l.useCallback(async U=>{if(s){q(I=>{const $=new Set(I);return $.add(U),$});try{await r.revertGitFile(s,U),he.success(`Reverted ${U}`),await Ze(!1)}catch(I){const $=I instanceof Error?I.message:"Failed to revert changes";he.error($)}finally{q(I=>{const $=new Set(I);return $.delete(U),$})}}},[s,Ze,r]);if(!s)return e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view repository details."})});if(g&&m===null)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Dt,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository…"})]})});if(m===!1)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Et,{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 ct=Re>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(Et,{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(fr,{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(pr,{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(ig,{activeProfile:De,identities:nt,onSelect:Q,isApplying:ke})]}),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(js,{variant:"default",onClick:()=>He("fetch"),disabled:W!==null||!f,children:[W==="fetch"?e.jsx(Dt,{size:16,className:"animate-spin"}):e.jsx(Sn,{size:16}),"Fetch"]}),e.jsxs(js,{variant:"default",onClick:()=>He("pull"),disabled:W!==null||!f,children:[W==="pull"?e.jsx(Dt,{size:16,className:"animate-spin"}):e.jsx(pr,{size:16}),"Pull"]}),e.jsxs(js,{variant:"default",onClick:()=>He("push"),disabled:W!==null||!f,children:[W==="push"?e.jsx(Dt,{size:16,className:"animate-spin"}):e.jsx(fr,{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(Lt,{open:de,onOpenChange:le,children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ot,{asChild:!0,children:e.jsxs(Ce,{variant:"outline",size:"sm",className:"gap-1.5 px-2 py-1 h-8",children:[e.jsx(Et,{className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:f?.current||"Branch"}),e.jsx(yt,{className:"size-4 opacity-60"})]})})}),e.jsxs(lt,{sideOffset:8,children:["Switch branch (",te.length," local · ",ce.length," remote)"]})]}),e.jsx($t,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(xl,{className:"h-full min-h-0",children:[e.jsx(yl,{placeholder:"Search branches…",value:ve,onValueChange:ee}),e.jsxs(bl,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(wl,{children:"No branches found."}),e.jsxs(br,{heading:"Local branches",children:[Fe.locals.map(U=>e.jsxs(Ct,{onSelect:()=>R(U),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:U}),u?.branches?.[U]?.ahead||u?.branches?.[U]?.behind?e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[u.branches[U].ahead||0," ahead ·"," ",u.branches[U].behind||0," behind"]}):null]}),f?.current===U&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${U}`)),Fe.locals.length===0&&e.jsx(Ct,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(mo,{}),e.jsxs(br,{heading:"Remote branches",children:[Fe.remotes.map(U=>e.jsx(Ct,{onSelect:()=>R(U),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:U})},`remote-${U}`)),Fe.remotes.length===0&&e.jsx(Ct,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]}),e.jsx(vt,{placeholder:"New branch",value:M,onChange:U=>E(U.target.value),className:"h-8 w-32 sm:w-40 rounded-lg bg-background/80 text-sm"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ce,{variant:"default",size:"sm",className:"h-8 px-2",onClick:ye,disabled:X||!P,children:X?e.jsx(Dt,{className:"size-4 animate-spin"}):e.jsx(Yt,{className:"size-4"})})}),e.jsx(lt,{sideOffset:8,children:P?`Create branch "${P}"`:"Enter branch name"})]})]}),e.jsx("div",{className:"flex-1"}),V&&e.jsx("span",{className:"typography-micro text-muted-foreground hidden lg:inline",children:V})]}),Be&&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:Be}),e.jsx("p",{className:"typography-meta text-destructive/80",children:"Try refreshing or confirm the repository is accessible."})]}),e.jsx(Je,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[e.jsxs("section",{className:"flex flex-col rounded-2xl border border-border/60 bg-background/70 min-h-[280px] max-h-[400px]",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[ge,"/",Re]}),Re>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ce,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:Ke,children:"All"}),e.jsx(Ce,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:st,disabled:ge===0,children:"None"})]})]})]}),e.jsx(Je,{outerClassName:"flex-1 min-h-0",className:"w-full",children:f?.isClean||Re===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(eo,{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:Ve.map(U=>e.jsx(og,{file:U,checked:A.has(U.path),stats:f?.diffStats?.[U.path],onToggle:()=>Ee(U.path),onViewDiff:()=>Le.getState().navigateToDiff(U.path),onRevert:()=>it(U.path),isReverting:_.has(U.path)},U.path))})})]}),e.jsxs("section",{className:"flex flex-col rounded-2xl border border-border/60 bg-background/70 min-h-[280px]",children:[e.jsx("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"})}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col p-3 gap-3",children:[be.length>0&&e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-background/60 px-3 py-2 shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"AI highlights"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"icon",className:"size-6",onClick:()=>{if(be.length===0)return;const U=be.map(I=>I.trim()).filter(Boolean);if(U.length===0){K();return}k(I=>{const $=I.trim(),se=$.length>0?`
|
|
37
37
|
|