@openchambery/web 1.19.17-beta.3 → 1.19.17
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/{AssistantView-CDXE0eTS.js → AssistantView-Zq6tBjih.js} +3 -3
- package/dist/assets/{DiagramView-BrRV4o5T.js → DiagramView-BVkfNci5.js} +1 -1
- package/dist/assets/MarkdownRenderer-DSqWFDq7.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-D2dIlX0h.js → MarkdownRendererImpl-BlRCMmq2.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-Drb2Tpv-.js → MarkstreamRendererImpl-IxPVvQrK.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-BgCoDqtp.js → MobileDetailNavigation-B2fTY2nU.js} +1 -1
- package/dist/assets/{MobileShareBridge-ZlVURYWR.js → MobileShareBridge-CQBddgDr.js} +1 -1
- package/dist/assets/MobileSurface-DrUFT40n.js +2 -0
- package/dist/assets/{MultiRunWindow-BCvcwItK.js → MultiRunWindow-B8Cc2NUx.js} +1 -1
- package/dist/assets/{SettingsView-D57amZJb.js → SettingsView-DxMrhPpR.js} +3 -3
- package/dist/assets/{SettingsWindow-B5DqLCkD.js → SettingsWindow-Cb8yglVO.js} +1 -1
- package/dist/assets/{TerminalView-2_RFPaVs.js → TerminalView-BZ_OWmUl.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CQs_7KYT.js → ToolOutputDialog-nhZwyPOH.js} +1 -1
- package/dist/assets/{appThemeRegistry-DpLe_jnW.js → appThemeRegistry-nmKlvHum.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-CmQthb6Q.js → fileMentionTouchSelection-DipHuaLB.js} +1 -1
- package/dist/assets/{gitApi-8HxdR1zx.js → gitApi-CbhPyoLY.js} +1 -1
- package/dist/assets/{insertionBoundaries-Cdv9-1Bg.js → insertionBoundaries-DcjuOya1.js} +1 -1
- package/dist/assets/{main-Cfru2-qr.js → main-BoTARB6C.js} +2 -2
- package/dist/assets/{main-CQY7JUX4.js → main-Cua6NA9P.js} +4 -4
- package/dist/assets/{miniChat-BphFgAb_.js → miniChat-alS-GQJT.js} +2 -2
- package/dist/assets/{mobile-BVRPTuLT.js → mobile-B2jIuTOm.js} +2 -2
- package/dist/assets/{multirun-CYdieVzW.js → multirun-DKDs3BMk.js} +1 -1
- package/dist/assets/{projectMeta-D8hiy3Dk.js → projectMeta-D2rOiejm.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-CVqd3Nmc.js → renderElectronMiniChatApp-CaQsjZiI.js} +2 -2
- package/dist/assets/{renderMobileApp-DgtCGRKP.js → renderMobileApp-BFbbXCSX.js} +4 -4
- package/dist/assets/{runtimeConfig-DXXOBrK_.js → runtimeConfig-DFO2rEBa.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-bSVOt7pi.js → runtimeEndpointReset-Dl97vnoo.js} +1 -1
- package/dist/assets/{sessionLookup-BZuujM6l.js → sessionLookup-CZwBZILA.js} +1 -1
- package/dist/assets/{src-C_Yn9Ylz.css → src-DZ60kHBP.css} +1 -1
- package/dist/assets/{useAppFontEffects-DhEfjuPp.js → useAppFontEffects-CCaWyCj1.js} +6 -6
- package/dist/assets/{useDesktopWindowControlsLayout-BhNFU2Wd.js → useDesktopWindowControlsLayout-CLapWnnJ.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-BhhzFJgX.js → useEffectiveDirectory-Cz772BtQ.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-1jdHeA49.js → useMobileNavigationStore-C4HhoiC4.js} +8 -8
- package/dist/assets/{useSessionAutoCleanup-C8u2-jrO.js → useSessionAutoCleanup-0sFR1yLV.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-DFXK66lA.js → useWorkerHighlightedLines-tFoFZt9Z.js} +1 -1
- package/dist/index.html +3 -3
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/dist/assets/MarkdownRenderer-CAdfUgV1.js +0 -2
- package/dist/assets/MobileSurface-DhLOTW0-.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ToolOutputDialog-
|
|
2
|
-
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}from"./runtime-auth-D66yq6ie.js";import{c as i,f as a,i as o,l as s,n as c,o as l,r as u,t as d}from"./runtime-switch-LvWDU-SL.js";import{n as f}from"./runtime-fetch-zIalUnbb.js";import{$ as p,$t as m,C as h,Cn as g,Et as _,G as v,H as y,I as b,J as x,K as S,Kt as C,Lt as w,M as T,N as E,Pt as D,Qt as O,R as k,S as A,T as j,Tt as M,V as N,X as P,Y as F,Yt as I,Z as L,Zt as R,_ as z,b as B,c as V,ct as H,d as ee,et as U,ft as te,g as W,gt as ne,h as G,ht as re,it as ie,j as K,kt as ae,lt as oe,m as se,n as ce,nn as le,nt as ue,ot as de,q as fe,r as pe,st as me,t as he,tn as ge,tt as _e,u as ve,ut as ye,v as be,x as xe,xt as Se,y as Ce,z as we}from"./persistence-DwRBC4zl.js";import{_ as Te,c as Ee,d as De,f as Oe,h as ke,i as Ae,l as je,m as Me,n as Ne,o as Pe,p as Fe,r as Ie,s as Le}from"./desktopHosts-B052a4UK.js";import{r as Re}from"./desktopRelayRestore-OjKNXr10.js";import{a as ze,i as Be,r as Ve,t as He}from"./vendor-zustand-B4dlGEM2.js";import{c as Ue,d as We,f as Ge,l as Ke,nt as qe,rt as Je,tt as Ye,u as Xe}from"./vendor-base-ui-CnHfUmDN.js";import{At as Ze,Bt as Qe,Ct as $e,Gt as et,Ht as tt,Jt as nt,Kt as rt,Nt as it,Ot as at,Pt as ot,Rt as st,St as ct,Ut as lt,Wt as ut,Yt as dt,jt as ft,kt as pt,n as mt,t as ht,zt as gt}from"./platform-DQ5_LNKO.js";import{d as _t,g as vt,h as yt,m as bt,s as xt,t as q,v as St,y as Ct}from"./useUIStore-CxOoCv7B.js";import{a as wt,n as Tt,o as Et}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{n as Dt}from"./vendor-react-DLPElpoQ.js";import{c as Ot,i as kt,n as At,s as jt,t as Mt}from"./vendor-tanstack-react-query-D7pys_c9.js";import{B as Nt,R as Pt,V as Ft,c as It}from"./vendor-codemirror-autocomplete-DHomsvW7.js";import{i as Lt,u as Rt}from"./vendor-pierre-diffs-DX7XTPG3.js";import{t as zt}from"./vendor-sonner-DVzioF3d.js";import{a as Bt,d as Vt,f as Ht,i as Ut,l as Wt,n as J,o as Gt,r as Kt}from"./vendor-reactuses-core-BnW6GxJt.js";import{_ as qt,d as Jt,f as Yt,i as Xt,p as Zt,r as Y,t as Qt,v as $t}from"./button-bhVnVYB_.js";import{i as en,t as tn}from"./store-BoixGrYS.js";import{$ as nn,$i as rn,$r as an,$t as on,A as sn,Aa as cn,An as ln,Ao as un,At as dn,B as fn,Bi as pn,Bn as mn,Br as hn,C as gn,Ci as _n,Cn as vn,Ct as yn,D as bn,Di as xn,Dn as Sn,Dr as Cn,Dt as wn,E as Tn,Ea as En,Ei as Dn,En as On,Er as kn,Et as An,F as jn,Fi as Mn,Fr as Nn,Ft as Pn,G as Fn,Ga as In,Gi as Ln,Gt as Rn,H as zn,Ha as Bn,Hi as Vn,Hr as Hn,Ht as Un,I as Wn,Ii as Gn,It as Kn,J as qn,Ja as Jn,Jr as Yn,Jt as Xn,K as Zn,Ka as Qn,Kr as $n,L as er,La as tr,Li as nr,Lr as rr,M as ir,Mi as ar,Mr as or,N as sr,Na as cr,Ni as lr,Nn as ur,No as dr,Nr as fr,O as pr,Oi as mr,On as hr,Or as gr,Ot as _r,P as vr,Pi as yr,Po as br,Pt as xr,Q as Sr,Qr as Cr,R as wr,Ri as Tr,Rt as Er,Sa as Dr,Si as Or,St as kr,T as Ar,Ti as jr,Tn as Mr,Tr as Nr,Tt as Pr,U as Fr,Ua as Ir,Ui as Lr,Un as Rr,Ur as zr,Ut as Br,V as Vr,Va as Hr,Vi as Ur,Vn as Wr,Vr as Gr,Vt as Kr,W as qr,Wa as Jr,Wi as Yr,Wr as Xr,Wt as Zr,X as Qr,Xa as $r,Xr as ei,Xt as ti,Y as ni,Ya as ri,Yi as ii,Yt as ai,Z as oi,Zt as si,_a as ci,_i as li,_t as ui,a as di,aa as fi,ai as pi,an as mi,ao as hi,b as gi,ba as _i,bi as vi,bn as yi,bo as bi,bt as xi,c as X,ca as Si,ci as Ci,cn as wi,d as Ti,da as Ei,di as Di,dn as Oi,ea as ki,ei as Ai,en as ji,er as Mi,et as Ni,fn as Pi,ft as Fi,ga as Ii,gi as Li,gt as Ri,h as zi,ha as Bi,hi as Vi,hn as Hi,hr as Ui,ht as Wi,i as Gi,ia as Ki,ii as qi,it as Ji,j as Yi,ja as Xi,ji as Zi,jr as Qi,jt as $i,k as ea,ka as ta,kn as na,kt as ra,la as ia,li as aa,ln as oa,ma as sa,mi as ca,mn as la,mr as ua,mt as da,n as fa,na as pa,ni as ma,nn as ha,no as ga,nr as _a,nt as va,on as ya,p as ba,pa as xa,pi as Sa,pn as Ca,pt as wa,q as Ta,qa as Ea,qr as Da,ra as Oa,rn as ka,rr as Aa,rt as ja,sa as Ma,sn as Na,ti as Pa,tn as Fa,to as Ia,tr as La,tt as Ra,ui as za,un as Ba,ut as Va,va as Ha,vi as Ua,vt as Wa,w as Ga,wa as Ka,wi as qa,wn as Ja,wt as Ya,x as Xa,xa as Za,xi as Qa,xn as $a,xo as eo,xt as to,yi as no,yr as ro,yt as io,z as ao,zi as oo,zn as so,zr as co}from"./useMobileNavigationStore-1jdHeA49.js";import{a as lo,i as uo,l as fo,n as po,o as mo,r as ho,s as go,t as _o}from"./dialog-C2Dw0yqA.js";import{t as vo}from"./AgentAvatar-CUDJ3_nZ.js";import{n as Z}from"./Icon-C9ZHbwqp.js";import{E as yo,n as bo}from"./gitApi-8HxdR1zx.js";import{a as xo}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{C as So,D as Co,J as wo,O as To,S as Eo,Y as Do,Z as Oo,_ as ko,a as Ao,b as jo,f as Mo,h as No,i as Po,k as Fo,l as Io,m as Lo,n as Ro,o as zo,q as Bo,s as Vo,u as Ho,w as Uo,x as Wo,y as Go}from"./projectMeta-D8hiy3Dk.js";import{t as Ko}from"./input-8Te_vPwB.js";import{i as qo,n as Jo,t as Yo}from"./tooltip-BLznq5KR.js";import{$t as Xo,A as Zo,At as Qo,B as $o,Ct as es,D as ts,Dt as ns,Et as rs,Ft as is,G as as,Gt as os,H as ss,J as cs,K as ls,M as us,Mt as ds,Nt as fs,Pt as ps,Qt as ms,R as hs,Rt as gs,St as _s,U as vs,V as ys,Vt as bs,W as xs,X as Ss,Y as Cs,Z as ws,Zt as Ts,at as Es,bt as Ds,ct as Os,it as ks,j as As,jt as js,k as Ms,lt as Ns,mt as Ps,n as Fs,nt as Is,ot as Ls,q as Rs,t as zs,tt as Bs,xt as Vs,z as Hs,zt as Us}from"./useSessionAutoCleanup-C8u2-jrO.js";import{n as Ws,r as Gs,t as Ks}from"./useThemeSystem-DMzWVJaW.js";import{i as qs,t as Js}from"./OverlayScrollbar-C7fAOAKT.js";import{a as Ys,c as Xs,i as Zs,l as Qs,n as $s,o as ec,r as tc,s as nc}from"./markdownTheme-DOfGg-A7.js";import{n as rc,r as ic,t as ac}from"./useRuntimeAPIs-DSLXJybW.js";import{A as oc,C as sc,D as cc,E as lc,F as uc,I as dc,N as fc,O as pc,P as mc,S as hc,T as gc,a as _c,b as vc,c as yc,f as bc,i as xc,j as Sc,k as Cc,l as wc,m as Tc,n as Ec,o as Dc,p as Oc,r as kc,s as Ac,t as jc,u as Mc,w as Nc,x as Pc}from"./insertionBoundaries-Cdv9-1Bg.js";import{a as Fc,c as Ic,i as Lc,n as Rc,o as zc,r as Bc,s as Vc}from"./fileMentionTouchSelection-CmQthb6Q.js";import{C as Hc,D as Uc,E as Wc,M as Gc,O as Kc,S as qc,T as Jc,_ as Yc,b as Xc,c as Zc,d as Qc,f as $c,g as el,h as tl,i as nl,k as rl,l as il,m as al,o as ol,p as sl,s as cl,t as ll,u as ul,v as dl,w as fl,x as pl,y as ml}from"./appThemeRegistry-DpLe_jnW.js";import{a as hl,n as gl,o as _l,r as vl,t as yl}from"./MarkdownRenderer-CAdfUgV1.js";import{n as bl,r as xl}from"./textarea-DRL916s6.js";import{_ as Sl,a as Cl,c as wl,g as Tl,l as El,o as Dl,t as Ol,v as kl,y as Al}from"./vendor-dnd-kit-core-CvWxUPdb.js";import{i as jl,n as Ml,o as Nl,s as Pl,t as Fl}from"./vendor-dnd-kit-sortable-hHdP9lLb.js";import{a as Il,n as Ll,t as Rl}from"./url-CMQwHq4k.js";import{c as zl,l as Bl,p as Vl}from"./markdown-worker-CptoICmq.js";import{n as Hl,t as Ul}from"./useEffectiveDirectory-BhhzFJgX.js";import{a as Wl,c as Gl,d as Kl,f as ql,i as Jl,l as Yl,n as Xl,r as Zl,s as Ql,t as $l}from"./FadeInOnReveal-BLSnyG2Z.js";import{c as eu,f as tu,l as nu,m as ru,n as iu,p as au,r as ou,s as su,u as cu}from"./imageSource-BlAJJUEI.js";import{A as lu,C as uu,D as du,E as fu,M as pu,O as mu,S as hu,T as gu,a as _u,b as vu,c as yu,g as bu,h as xu,i as Su,j as Cu,k as wu,o as Tu,p as Eu,r as Du,s as Ou,t as ku,v as Au,w as ju,x as Mu,y as Nu}from"./useWorkerHighlightedLines-DFXK66lA.js";import{C as Pu,D as Fu,S as Iu,T as Lu,_ as Ru,a as zu,b as Bu,c as Vu,d as Hu,f as Uu,g as Wu,h as Gu,l as Ku,m as qu,o as Ju,p as Yu,s as Xu,u as Zu,v as Qu,w as $u,x as ed,y as td}from"./sessionChangeSummary-CfnRZ0gS.js";import{t as nd}from"./vendor-cmdk-CeAGfrLo.js";import{t as rd}from"./sortable-tabs-strip-BmvLnn6O.js";import{a as id}from"./markdownHeightCache-CT2d4yTV.js";import{n as ad,t as od}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";import{t as sd}from"./dualLimitLru-D8Sphgua.js";import{i as cd,t as ld}from"./vendor-framer-motion-DFy_BSVd.js";import{t as ud}from"./vendor-legendapp-list-WE32lwNk.js";import{n as dd,t as fd}from"./useFontPreferences-DCaY8NbU.js";typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=X.getState().currentSessionId;if(!e)return null;let t=Ma(e);if(!t||t.length===0)return null;for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role===`assistant`){let e=(Si(n.id)||[]).map(e=>{let t={id:e.id,type:e.type};return e.type===`text`?(t.text=e.text,t.textLength=e.text?.length||0):e.type===`tool`?(t.tool=e.tool,t.state=e.state?.status):(e.type===`step-start`||e.type===`step-finish`)&&(t.isStepMarker=!0),t}),t=e.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=e.some(e=>e.type===`tool`),i=e.some(e=>e.type===`step-start`||e.type===`step-finish`),a=e.length===0,o=!t&&!r&&(!a||i),s={messageId:n.id,role:n.role,timestamp:n.time?.created||0,partsCount:e.length,parts:e,isEmpty:a,isEmptyResponse:o,raw:n};return s.messageId,s.partsCount,s.isEmpty,s.isEmptyResponse,s.isEmpty&&console.warn(`[WARNING] Message has NO parts!`),s.isEmptyResponse&&(console.warn(`[WARNING] Message has parts but NO meaningful content (empty text, no tools)!`),i&&!t&&!r&&console.warn(`[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!`)),s}}return null},truncateString(e,t=80){return!e||typeof e!=`string`||e.length<=t?e:e.substring(0,t)+`…`},truncateMessages(e){return e.map(e=>({...e,parts:(Si(e.id)||[]).map(e=>{let t={...e};return`text`in e&&(t.text=this.truncateString(e.text)),`textPreview`in e&&(t.textPreview=this.truncateString(e.textPreview)),e.state&&(t.state={...e.state},`output`in e.state&&(t.state.output=this.truncateString(e.state.output)),`error`in e.state&&(t.state.error=this.truncateString(e.state.error)),e.state.metadata&&`preview`in e.state.metadata&&(t.state.metadata={...e.state.metadata,preview:this.truncateString(e.state.metadata.preview)})),t})}))},getAllMessages(e=!1){let t=X.getState().currentSessionId;if(!t)return[];let n=Ma(t);return`${n.length}`,n.forEach((e,t)=>{let n=Si(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=$e.getState(),t=X.getState(),n=eo.getState(),r=e.currentDirectory||null,i=it.getDirectory()??null,a=ia(),o=new Set,s={};a.forEach(e=>{let t=e.directory;typeof t==`string`&&t.trim().length>0?(o.add(t),s[t]=(s[t]??0)+1):s[`(none)`]=(s[`(none)`]??0)+1});let c=(()=>{if(typeof window>`u`)return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem(`lastDirectory`),homeDirectory:window.localStorage.getItem(`homeDirectory`)}}catch(e){return{available:!1,error:e instanceof Error?e.message:String(e)}}})(),l=g(),u=typeof window<`u`&&!!window.__OPENCHAMBER_ELECTRON__,d=async e=>{try{return await e.json()}catch{return null}},p=async e=>{try{return await e.text()}catch{return null}},m=async e=>{try{let t=await f(e);return t.ok?await d(t):{status:t.status}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},h=null,_=null,v=null,y=null;try{let e=await it.getSdkClient().path.get(r?{directory:r}:void 0);h=e.error?{error:e.error}:e.data}catch(e){h={error:e instanceof Error?e.message:String(e)}}try{let e=await it.getSdkClient().project.current(r?{directory:r}:void 0);_=e.error?{error:e.error}:e.data}catch(e){_={error:e instanceof Error?e.message:String(e)}}v=await m(`/api/config/settings`);try{let e=await f(`/api/health`),t=e.headers.get(`content-type`)||``,n=await p(e),r=t.toLowerCase().includes(`application/json`),i=null;if(r&&n)try{let e=JSON.parse(n);e&&typeof e==`object`&&!Array.isArray(e)&&(i=e)}catch{i=null}y={status:e.status,ok:e.ok,contentType:t,type:r?`json`:`html`,openCodePort:i?.openCodePort??null,openCodeRunning:i?.openCodeRunning??null,openCodeSecureConnection:i?.openCodeSecureConnection??null,openCodeAuthSource:i?.openCodeAuthSource??null,isOpenCodeReady:i?.isOpenCodeReady??null,lastOpenCodeError:i?.lastOpenCodeError??null,preview:n?n.slice(0,120):null}}catch(e){y={error:e instanceof Error?e.message:String(e)}}let b={isGitRepo:null};if(r)try{b.isGitRepo=await bo(r)}catch(e){b={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let x=n.projects.map(e=>({id:e.id,path:e.path,label:e.label}));return{runtime:{platform:l?.runtime?.platform??null,isDesktop:u,isVSCode:!!l?.runtime?.isVSCode,hasRuntimeApis:!!l,desktopServerOrigin:null},location:typeof window<`u`?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:r,opencodeDirectory:h?.directory||h?.worktree||i,homeDirectory:e.homeDirectory||null,isHomeReady:e.isHomeReady,hasPersistedDirectory:e.hasPersistedDirectory,isSwitchingDirectory:e.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:x},sessions:{total:a.length,currentSessionId:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,uniqueDirectories:o.size,directorySamples:Array.from(o).slice(0,5),directoryCounts:s},worktrees:{available:t.availableWorktrees.length,metadataEntries:t.worktreeMetadata.size},git:b,localStorage:c,opencode:{pathInfo:h,projectInfo:_,health:y},openchamber:{settingsInfo:v}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return Jt(e)},async copyDiagnosticsReport(){let e=await this.buildDiagnosticsReport();return{...await this.copyTextToClipboard(e),report:e}},checkLastMessage(){let e=this.getLastAssistantMessage();if(!e)return!1;let t=e.isEmpty||e.isEmptyResponse;return t&&(console.error(`[ALERT] PROBLEMATIC MESSAGE DETECTED!`),e.messageId,e.isEmpty,e.isEmptyResponse,e.partsCount,e.parts.length>0&&e.parts),t},getStreamingState(){let e=X.getState(),t=vn.getState(),n=e.currentSessionId?t.streamingMessageIds.get(e.currentSessionId)??null:null;return Array.from(t.streamingMessageIds.entries()),Array.from(t.messageStreamStates.entries()),{streamingMessageId:n,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){let e=X.getState().currentSessionId;if(!e)return[];let t=Ma(e).filter(e=>e.role===`assistant`).filter(e=>{let t=Si(e.id)||[],n=t.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=t.some(e=>e.type===`tool`);return t.length===0||!n&&!r});return`${t.length}`,t.forEach((e,t)=>{let n=Si(e.id)||[];`${t}`,e.id,n.length,e.providerID,e.modelID,e.time?.created}),t},showRetryHelp(){},analyzeMessageCompletionConsistency(e={}){let{includeNonAssistant:t=!1,verbose:n=!0,maxTableRows:r=25}=e,i=X.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=Ma(i),o=t?a:a.filter(e=>e.role===`assistant`),s={totalMessages:a.length,analyzedMessages:o.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},c=e=>typeof e==`number`&&Number.isFinite(e)?e:null,l=e=>{let t=e.filter(e=>typeof e==`number`);return t.length>0?Math.max(...t):null},u=o.map((e,t)=>{let n=e,r=Si(e.id)||[],i=n.time??{},a=c(i.completed),o=a!==null,u=r.filter(e=>e.type===`tool`),d=r.filter(e=>e.type===`reasoning`),f=l(u.map(e=>c(e.state?.time?.end??e.state?.time?.start))),p=l(d.map(e=>c(e.time?.end??e.time?.start))),m=l([f,p].filter(e=>e!==null)),h=u.some(e=>[`pending`,`running`,`started`].includes(e.state?.status)),g=d.some(e=>typeof e.time?.end!=`number`);u.length>0&&(s.withTools+=1),d.length>0&&(s.withReasoning+=1),o||(s.completedMissing+=1);let _=!!(o&&typeof f==`number`&&a<f);_&&(s.completedBeforeTool+=1);let v=!!(o&&typeof p==`number`&&a<p);return v&&(s.completedBeforeReasoning+=1),o&&h&&(s.runningToolsWhenCompleted+=1),o&&g&&(s.reasoningOpenWhenCompleted+=1),{index:t,messageId:n.id,role:n.role,completedAt:a,latestToolTimestamp:f,latestReasoningTimestamp:p,latestPartTimestamp:m,completed_missing:!o,completed_before_tool:_,completed_before_reasoning:v,running_tools_when_completed:!!(o&&h),reasoning_open_when_completed:!!(o&&g),has_tools:u.length>0,has_reasoning:d.length>0}});return n&&(console.table(u.slice(0,r)),u.length>r&&`${r}${u.length}`),{summary:s,rows:u}},checkCompletionStatus(){let e=X.getState().currentSessionId;if(!e)return null;let t=Ma(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=(Si(n.id)||[]).filter(e=>e.type===`step-finish`),i=n.finish===`stop`,a=n.time?.completed,o=n.status,s=typeof a==`number`&&a>0||o===`completed`,c=!!(s&&i),l=vn.getState();n.sessionID&&l.streamingMessageIds.get(n.sessionID);let u=l.messageStreamStates.get(n.id);return n.id,n.id,u?.phase,{messageId:n.id,completed:a,status:o,hasCompletedFlag:s,hasStopReason:i,messageIsComplete:c,stepFinishParts:r,raw:n}}},at(),window.addEventListener(`error`,e=>{try{let t=e.message||``,n=e.filename||``;typeof t==`string`&&t.includes(`this._renderer.value.dimensions`)&&/xterm/i.test(String(n))&&e.preventDefault()}catch{}}));var Q=e(Je(),1),pd=Dt(),md=async()=>{if(typeof window>`u`)return;let e=null;try{e=D(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!ge()&&$e.getState().setDirectory(e,{showOverlay:!1})},hd=new Map,gd=e=>hd.get(e)??null,_d=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=hd.get(e);if(o&&!a.force)return o;let s=(async()=>{o&&await o;try{await t()}catch(e){return i(`appearance`,e),!1}try{await Promise.all([n(),r()])}catch(e){i(`secondary`,e)}return!0})();return hd.set(e,s),s},vd=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await _d({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},yd=(e,t=50)=>{let n=null,r;return{schedule:i=>{r=i,n&&clearTimeout(n),n=setTimeout(()=>{n=null;let t=r;r=void 0,t!==void 0&&e(t)},t)},cancel:()=>{n&&clearTimeout(n),n=null,r=void 0}}};function bd(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function xd(e,t){let n=e.via===`relay`;return t?n:!n}function Sd(e){let{isActive:t,isSsh:n,runtimeIsConnected:r,runtimeConnectionPhase:i,currentTransportIsRelay:a,probe:o,sshPhase:s}=e,c;c=t?r&&i===`connected`?`ok`:`checking`:n?bd(s):o?.status??`checking`;let l=t?a:o?.via===`relay`,u=null;return!n&&c===`ok`&&o?.status===`ok`&&typeof o.latencyMs==`number`&&(!t||xd(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var $=qe(),Cd=`local`,wd=9e4,Td=`SSH connection cancelled`,Ed=e=>Re(e),Dd={},Od=e=>{let t=Fe(e);if(!t)return e.trim();try{let e=new URL(t);return e.pathname.endsWith(`/`)||(e.pathname=`${e.pathname}/`),e.toString()}catch{return t}},kd=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,Ad=async()=>m()?Pe().catch(()=>``):``,jd=e=>e===`ok`?`bg-status-success`:e===`auth`||e===`update-recommended`?`bg-status-warning`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`bg-status-error`:e===`checking`?`bg-status-info`:`bg-muted-foreground/40`,Md=e=>e===`ok`?`text-[var(--status-success)]`:e===`auth`||e===`update-recommended`?`text-[var(--status-warning)]`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`text-[var(--status-error)]`:`text-muted-foreground`,Nd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,Pd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,Fd=e=>e===`ok`?`desktopHostSwitcher.status.connected`:e===`auth`?`desktopHostSwitcher.status.authRequired`:e===`checking`?`desktopHostSwitcher.status.checking`:e===`update-recommended`?`desktopHostSwitcher.status.updateRecommended`:e===`incompatible`?`desktopHostSwitcher.status.incompatible`:e===`wrong-service`?`desktopHostSwitcher.status.wrongService`:e===`unreachable`?`desktopHostSwitcher.status.unreachable`:`desktopHostSwitcher.status.unknown`,Id=e=>new Promise(t=>window.setTimeout(t,e)),Ld=e=>{switch(e){case`ready`:return`desktopHostSwitcher.sshPhase.ready`;case`error`:return`desktopHostSwitcher.sshPhase.error`;case`degraded`:return`desktopHostSwitcher.sshPhase.reconnecting`;case`config_resolved`:return`desktopHostSwitcher.sshPhase.resolvingConfig`;case`auth_check`:return`desktopHostSwitcher.sshPhase.checkingAuth`;case`master_connecting`:return`desktopHostSwitcher.sshPhase.connectingSsh`;case`remote_probe`:return`desktopHostSwitcher.sshPhase.probingRemote`;case`installing`:return`desktopHostSwitcher.sshPhase.installing`;case`updating`:return`desktopHostSwitcher.sshPhase.updating`;case`server_detecting`:return`desktopHostSwitcher.sshPhase.detectingServer`;case`server_starting`:return`desktopHostSwitcher.sshPhase.startingServer`;case`forwarding`:return`desktopHostSwitcher.sshPhase.forwardingPorts`;default:return`desktopHostSwitcher.sshPhase.idle`}},Rd=async()=>{let e=await os().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},zd=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(Td);let t=(await os(e).catch(()=>[])).find(t=>t.id===e);if(t){if(n(t),t.phase===`ready`)return t;if(t.phase===`error`)throw Error(t.detail||`SSH connection failed`)}await Id(700)}throw r?.()?Error(Td):Error(`Timed out waiting for SSH connection`)},Bd=e=>({id:Cd,label:`Local`,url:e||kd()}),Vd=e=>{let t=typeof window>`u`?``:window.location.href,n=e.find(e=>e.id===Cd)?.url||kd(),r=d(),i=Fe(n)||n,a=Fe(t)||t,o=u(),s=e.find(e=>e.relay&&Ed(e)===o);if(s)return{id:s.id,label:s.label,url:s.url};if(r&&Oe(r,n))return{id:Cd,label:`Local`,url:i};let c=e.find(e=>r?Oe(r,je(e)):!1);if(c)return{id:c.id,label:c.label,url:Fe(je(c))||je(c)};if(t&&Oe(t,n))return{id:Cd,label:`Local`,url:i};let l=e.find(e=>t?Oe(t,e.url):!1);return l?{id:l.id,label:l.label,url:Fe(l.url)||l.url}:t.startsWith(`openchamber-ui://`)?{id:Cd,label:`Local`,url:i}:{id:`custom`,label:ke(a||`Instance`),url:a}};function Hd({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){let{t:a}=Yt(),s=q(e=>e.setSettingsDialogOpen),c=q(e=>e.setSettingsPage),l=Oa(e=>e.isConnected),u=Oa(e=>e.connectionPhase),[d,f]=Q.useState([]),[p,h]=Q.useState(null),[g,_]=Q.useState(()=>({...Dd}));Q.useEffect(()=>{Object.assign(Dd,g)},[g]);let[v,y]=Q.useState(!1),[b,x]=Q.useState(!1),[S,C]=Q.useState(!1),w=ms(),T=Xo(),[E,D]=Q.useState(null),k=E||T,[A,j]=Q.useState({}),[M,N]=Q.useState({}),[P,F]=Q.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),[I,L]=Q.useState(``),[R,z]=Q.useState(()=>kd()),[B,V]=Q.useState(null),[H,ee]=Q.useState(``),[U,te]=Q.useState(``),[W,ne]=Q.useState(0),G=Q.useRef(0),re=Q.useMemo(()=>[Bd(R),...d.map(e=>({...e,url:Fe(e.url)||e.url}))],[d,R]),ie=Q.useMemo(()=>new Set(Object.keys(A)),[A]),K=Q.useMemo(()=>re.filter(e=>e.id===Cd||De(e,ie)),[re,ie]);Q.useEffect(()=>i(()=>ne(e=>e+1)),[]);let ae=Q.useMemo(()=>Vd(re),[re,W]),oe=Q.useMemo(()=>o().startsWith(`relay:`),[W]),se=Q.useMemo(()=>{let e=p||Cd;return re.find(t=>t.id===e)?.label||a(`desktopHostSwitcher.instance.local`)},[re,p,a]),ce=Q.useCallback(async(e,t)=>{if(O()){C(!0),L(``);try{let n=e.filter(e=>e.id!==Cd);await Ae({hosts:n,defaultHostId:t}),f(n),h(t)}catch(e){L(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToSave`))}finally{C(!1)}}},[a]),le=Q.useCallback(()=>{c(`remote-instances`),s(!0),t(!1)},[t,s,c]),ue=Q.useCallback(async()=>{if(O()){y(!0),L(``);try{let[e,t,n]=await Promise.all([Ie(),bs().catch(()=>({instances:[]})),Rd()]);e.localOrigin&&z(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;f(e.hosts||[]),h(e.defaultHostId??null),j(r),N(n)}catch(e){L(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToLoad`)),f([]),h(null),j({}),N({})}finally{y(!1)}}},[a]),de=Q.useCallback(async e=>{if(O()){x(!0);try{let t=await Ad(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await Me(e.relay,{clientToken:e.clientToken||null}).catch(()=>({status:`unreachable`,latencyMs:0}));return{status:t.status,latencyMs:t.latencyMs,...t.status===`ok`?{via:`relay`}:{}}};if(e.relay&&!e.apiUrl)return[e.id,await n()];let r=Fe(m()?je(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===Cd?t:e.clientToken||``,a=await Ne(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(Nd(a.status)&&e.relay){let t=await n();if(t.status===`ok`)return[e.id,t]}return[e.id,{status:a.status,latencyMs:a.latencyMs}]})),r={};for(let[e,t]of n)r[e]=t;_(r)}finally{x(!1)}}},[]);Q.useEffect(()=>{if(!e){V(null),ee(``),te(``),D(null),F({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),L(``);return}ue()},[e,ue]),Q.useEffect(()=>{e&&de(K)},[e,K,de]),Q.useEffect(()=>{if(!e||!O())return;let t=!1,n=async()=>{let e=await Rd();t||N(e)};n();let r=window.setInterval(()=>{typeof document<`u`&&document.visibilityState!==`visible`||n()},1500);return()=>{t=!0,window.clearInterval(r)}},[e]);let fe=J(async e=>{let t=e.id===Cd?R:Fe(e.url)||``,n=e.id===Cd?R:Fe(je(e))||``,i=!!e.relay&&!e.apiUrl&&e.id!==Cd;if(!t&&!i)return;if(m()){if(!n&&!e.relay||w)return;let t=e.id===Cd?await Ad():null,i=await Ts({host:e,cachedProbe:g[e.id]||null,...e.id===Cd?{localApiOrigin:n,localClientToken:t}:{}});_(t=>({...t,[e.id]:i.status})),i.ok&&r?.();return}let o=!!A[e.id];if(e.id!==Cd&&o&&O()){let n=M[e.id],i=await os(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);i&&(n=i,N(t=>({...t,[e.id]:i})));let o=Fe(n?.localUrl||e.url||``);if(n?.phase===`ready`&&o){let e=Od(o);r?.(),window.location.assign(e);return}D(e.id);let s=G.current+1;G.current=s,F({open:!0,hostId:e.id,hostLabel:ke(e.label),phase:`master_connecting`,detail:null,error:null,errorCode:null});try{if(await gs(e.id),s!==G.current)return;let n=await zd(e.id,wd,e=>{N(t=>({...t,[e.id]:e})),F(t=>({...t,phase:e.phase,detail:e.detail||null,errorCode:e.errorCode||null}))},()=>s!==G.current);if(s!==G.current)return;let i=Od(Fe(n.localUrl||``)||t);r?.(),window.location.assign(i);return}catch(t){if(s!==G.current)return;let n=t instanceof Error?t.message:String(t);if(n===Td)return;let r=fs(P.errorCode,n);F(e=>({...e,error:n,errorCode:r})),ro.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ke(e.label)}),{description:ds(a(ps(r)),r,n)});return}finally{s===G.current&&D(null)}}if(e.id!==Cd&&O()){D(e.id);let n=await Ne(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(_(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),Nd(n.status)){ro.error(a(`desktopHostSwitcher.toast.instanceUnreachable`,{host:ke(e.label)})),D(null);return}}let s=Od(t);r?.();try{window.location.assign(s)}catch{window.location.href=s}}),pe=Q.useCallback(()=>{V(null),ee(``),te(``)},[]),me=Q.useCallback(e=>{e.stopPropagation()},[]),he=Q.useCallback(async()=>{if(!B)return;if(B===Cd){pe();return}let e=Te(U);if(!e){L(a(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(H||ke(t)).trim(),r=d.map(e=>e.id===B?{...e,label:n,url:t,apiUrl:t}:e);await ce(r,p),pe(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[pe,d,p,H,U,B,ce,a]),ge=Q.useCallback(async e=>{await ce(d,e===Cd?Cd:e)},[d,ce]),_e=Q.useCallback(e=>{let t=e=>{ro.error(a(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==Cd){Ee(e.id).catch(t);return}let n=e.id===Cd?R:je(e);if(!n)return;let r=Od(n);Le(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[R,a]),ve=J(async()=>{G.current+=1,D(null),F(e=>({...e,open:!1,hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}));let e=Od(R);if(m()){if(w)return;let e=await Ad();(await Ts({host:Bd(R),localApiOrigin:R,localClientToken:e})).ok&&r?.();return}r?.(),window.location.assign(e)}),ye=Q.useCallback(async()=>{let e=P.hostId||k;G.current+=1,D(null),F({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),!(!e||e===Cd||!O())&&await Us(e).catch(()=>{})},[P.hostId,k]),be=Q.useCallback(()=>{let e=P.hostId;if(!e)return;let t=re.find(t=>t.id===e);t&&fe(t)},[re,fe,P.hostId]),xe=Q.useCallback(async e=>{if(O()){D(e.id);try{await gs(e.id),(await zd(e.id,wd,e=>{N(t=>({...t,[e.id]:e}))})).phase===`ready`&&ro.success(a(`desktopHostSwitcher.toast.sshConnected`,{host:ke(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);if(n!==Td){let t=fs(null,n);ro.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ke(e.label)}),{description:ds(a(ps(t)),t,n)})}}finally{D(null)}}},[a]);if(!O())return null;let Se=O(),Ce=(0,$.jsxs)($.Fragment,{children:[n?(0,$.jsx)(`div`,{className:`flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex items-baseline gap-1.5 typography-ui-label`,children:[(0,$.jsx)(`span`,{className:`font-medium text-foreground`,children:a(`desktopHostSwitcher.header.current`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ke(ae.label)}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`•`}),(0,$.jsx)(`span`,{className:`font-medium text-foreground`,children:a(`desktopHostSwitcher.header.default`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ke(se)})]}),(0,$.jsx)(`button`,{type:`button`,className:Y(`inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors`,`hover:text-foreground hover:bg-interactive-hover`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`),onClick:()=>void de(K),disabled:!Se||v||b,"aria-label":a(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,$.jsx)(Z,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)})})]})}):(0,$.jsxs)(lo,{className:`flex-shrink-0`,children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`server`,className:`h-5 w-5`}),a(`desktopHostSwitcher.title`)]}),(0,$.jsx)(ho,{children:a(`desktopHostSwitcher.description`)})]}),!n&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a(`desktopHostSwitcher.header.currentColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ke(ae.label)}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a(`desktopHostSwitcher.header.currentDefaultColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ke(se)})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,$.jsxs)(Qt,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void de(K),disabled:!Se||v||b,children:[(0,$.jsx)(Z,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)}),a(`desktopHostSwitcher.actions.refresh`)]})})]}),!Se&&(0,$.jsx)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:a(`desktopHostSwitcher.state.limitedOnPage`)})}),(0,$.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:(0,$.jsx)(`div`,{className:Y(`space-y-1`,n&&`space-y-1.5 px-3 py-1`),children:v?(0,$.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:a(`desktopHostSwitcher.state.loading`)}):K.map(e=>{let t=e.id===Cd,r=!!A[e.id],i=e.id===ae.id,o=(p||Cd)===e.id,s=g[e.id]||null,c=M[e.id]||null,d=Sd({isActive:i,isSsh:r,runtimeIsConnected:l,runtimeConnectionPhase:u,currentTransportIsRelay:oe,probe:s,sshPhase:c?.phase}),f=d.statusKind,m=d.showViaRelay,h=B===e.id,_=t?R:Fe(e.url)||e.url,v=e.id===Cd?a(`desktopHostSwitcher.instance.local`):ke(e.label),y=e.relay&&!e.apiUrl?a(`mobile.connect.relay.badge`):ke(_);return(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden`,n&&`rounded-xl bg-[var(--surface-muted)] px-3 py-2.5`,n&&i&&`bg-[var(--interactive-selection)]/25`,h?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,$.jsxs)(`button`,{type:`button`,className:Y(`flex items-center gap-2 flex-1 min-w-0 text-left`,h&&`pointer-events-none opacity-70`),onClick:()=>void fe(e),disabled:k===e.id,"aria-label":a(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,$.jsx)(`span`,{className:Y(`h-2 w-2 rounded-full flex-shrink-0`,jd(f))}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 space-y-0.5`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`typography-ui-label font-medium truncate text-foreground`,children:v}),i&&(0,$.jsx)(`span`,{className:`typography-micro flex-shrink-0 text-muted-foreground bg-muted px-1 rounded leading-none pb-px border border-border/50`,children:a(`desktopHostSwitcher.header.current`)}),r&&(0,$.jsx)(`span`,{className:`typography-micro flex-shrink-0 px-1 rounded leading-none pb-px text-[var(--status-info)] bg-[var(--status-info)]/10`,children:`SSH`})]}),(0,$.jsxs)(`div`,{className:Y(`typography-micro truncate`,Md(f)),children:[a(r&&!i?Ld(c?.phase):Fd(f)),d.latencyMs==null?``:a(`desktopHostSwitcher.status.ping`,{ms:d.latencyMs}),m?` · ${a(`settings.remoteInstances.clientAuth.state.viaRelay`)}`:``]}),(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground/70 truncate font-mono`,children:y})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[r&&!t&&(c?.phase===`idle`||!c?.phase?(0,$.jsxs)(Qt,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:k===e.id,onClick:t=>{t.stopPropagation(),xe(e)},children:[k===e.id?(0,$.jsx)(Z,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(Z,{name:`plug-2`,className:`h-3.5 w-3.5`}),a(`desktopHostSwitcher.actions.connect`)]}):(0,$.jsx)(`div`,{className:`h-8 w-8 opacity-0 pointer-events-none`,"aria-hidden":`true`})),(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,o?`text-primary hover:text-primary/80`:`text-muted-foreground/60 hover:text-primary/80`),onClick:()=>void ge(e.id),"aria-label":a(o?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:S||!o&&Pd(f),children:o?(0,$.jsx)(Z,{name:`star-fill`,className:`h-4 w-4`}):(0,$.jsx)(Z,{name:`star`,className:`h-4 w-4`})})}),(0,$.jsx)(Jo,{sideOffset:6,children:a(o?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,Pd(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),_e(e)},disabled:Pd(f),"aria-label":a(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,$.jsx)(Z,{name:`window`,className:`h-4 w-4`})})}),(0,$.jsx)(Jo,{sideOffset:6,children:Pd(f)?a(`desktopHostSwitcher.state.instanceUnreachable`):a(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),Se&&B&&B!==Cd&&(0,$.jsxs)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`div`,{className:`typography-ui-label font-medium text-foreground`,children:a(`desktopHostSwitcher.edit.title`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Qt,{type:`button`,variant:`outline`,size:`sm`,onClick:pe,disabled:S,children:a(`desktopHostSwitcher.actions.cancel`)}),(0,$.jsxs)(Qt,{type:`button`,size:`sm`,onClick:()=>void he(),disabled:S,children:[S?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):null,a(`desktopHostSwitcher.actions.save`)]})]})]}),(0,$.jsxs)(`div`,{className:`mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,$.jsx)(Ko,{value:H,onChange:e=>ee(e.target.value),onKeyDown:me,placeholder:a(`desktopHostSwitcher.field.labelPlaceholder`),disabled:S}),(0,$.jsx)(Ko,{value:U,onChange:e=>te(e.target.value),onKeyDown:me,placeholder:a(`desktopHostSwitcher.field.urlPlaceholder`),disabled:S})]})]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 border-t border-[var(--interactive-border)]`,children:(0,$.jsxs)(`button`,{type:`button`,className:`w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,onClick:le,children:[(0,$.jsx)(Z,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-ui-label`,children:a(`desktopHostSwitcher.actions.addInstance`)})]})}),I&&(0,$.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:I})]}),we=(0,$.jsx)(_o,{open:P.open,onOpenChange:e=>{if(!e&&k){ye();return}F(t=>({...t,open:e,...e?{}:{hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}}))},children:(0,$.jsxs)(po,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,$.jsxs)(lo,{children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(`h-4 w-4`,!P.error&&`animate-spin`)}),a(`desktopHostSwitcher.ssh.connectingTo`,{host:P.hostLabel||a(`desktopHostSwitcher.ssh.instanceFallback`)})]}),P.error?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ho,{className:`sr-only`,children:a(is(fs(P.errorCode,P.error)))}),(0,$.jsx)(js,{errorCode:P.errorCode,detail:P.error})]}):(0,$.jsx)(ho,{children:P.detail||a(Ld(P.phase))})]}),P.error?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,$.jsx)(Qt,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{le(),ye()},children:a(`desktopHostSwitcher.sshError.openRemoteSettings`)}),(0,$.jsx)(Qt,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void ve(),children:a(`desktopHostSwitcher.actions.switchToLocal`)}),(0,$.jsx)(Qt,{type:`button`,size:`sm`,onClick:be,disabled:!P.hostId,children:a(`desktopHostSwitcher.actions.retry`)})]}):null]})});return n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`w-full max-h-[70vh] flex flex-col overflow-hidden gap-2`,children:Ce}),we]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsx)(po,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:Ce})}),we]})}function Ud(){let e=(0,pd.c)(11),[t,n]=Q.useState(!1),{t:r}=Yt();if(!O())return null;let i,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>n(!0),a=(0,$.jsx)(Z,{name:`server`,className:`h-4 w-4`}),e[0]=i,e[1]=a):(i=e[0],a=e[1]);let o;e[2]===r?o=e[3]:(o=r(`desktopHostSwitcher.actions.switchInstance`),e[2]=r,e[3]=o);let s;e[4]===o?s=e[5]:(s=(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`sm`,"data-oc-host-switcher":!0,className:`w-full justify-center`,onClick:i,children:[a,o]}),e[4]=o,e[5]=s);let c;e[6]===t?c=e[7]:(c=(0,$.jsx)(Hd,{open:t,onOpenChange:n}),e[6]=t,e[7]=c);let l;return e[8]!==s||e[9]!==c?(l=(0,$.jsxs)($.Fragment,{children:[s,c]}),e[8]=s,e[9]=c,e[10]=l):l=e[10],l}var Wd=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,Gd=`/auth/session`,Kd=4,qd=1500,Jd=`openchamber.uiAuth.trustDevice`,Yd=`desktop-local`,Xd=`desktop-local`,Zd=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},Qd=(e,t)=>{let n=Fe(e),r=Fe(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},$d=()=>O(),ef=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},tf=()=>{if(!O())return!1;let e=Zd();if(!e)return!1;let t=d()||(typeof window<`u`?window.location.origin:``);if(Qd(e,t))return!0;try{let e=Fe(t);return!!(e&&ef(new URL(e).hostname))}catch{return!1}},nf=()=>tf()?{clientKind:Yd,dedupeKey:Xd}:{},rf=async()=>await f(Gd,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),af=()=>typeof window>`u`?!1:window.localStorage.getItem(Jd)===`true`,of=async(e,t)=>{let n=$d();return await f(Gd,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...nf()})})},sf=async()=>{if(!O())return``;let e=await f(`/api/client-auth/clients`,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:`OpenChamber Desktop`,...nf()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},cf=()=>O()&&!tf(),lf=async(e,t)=>{if(!O()||typeof window>`u`)return null;let r=await I(`desktop_remote_password_login`,{url:d(),password:e,trustDevice:t,requestHeaders:n()}).catch(()=>null);if(!r||typeof r!=`object`)return null;let i=r.token,a=r.status;return{token:typeof i==`string`?i.trim():``,...typeof a==`number`?{status:a}:{}}},uf=async(e,t)=>{if(!O()||!t)return;let n=await Ie().catch(()=>null);if(!n)return;if(n.localOrigin&&Qd(n.localOrigin,e)){await Ae({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!Qd(je(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await Ae({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},df=async e=>{if(!e)return;let r=d(),i=n();await uf(r,e),s({apiBaseUrl:r,clientToken:e,requestHeaders:Object.keys(i).length>0?i:null,relay:t()})},ff=e=>{let t=(0,pd.c)(7),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={height:`var(--oc-wco-titlebar-height, 0px)`,right:`var(--oc-wco-right-inset, 0px)`},t[0]=r):r=t[0];let i=r,a,o;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a={fontFamily:`"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif`},o=(0,$.jsx)(`div`,{className:`app-region-drag fixed left-0 top-0 z-20`,style:i,"aria-hidden":!0}),t[1]=a,t[2]=o):(a=t[1],o=t[2]);let s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-55`,style:{background:`radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)`}}),t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,style:{backgroundColor:`var(--surface-subtle)`,opacity:.22}}),t[4]=c):c=t[4];let l;return t[5]===n?l=t[6]:(l=(0,$.jsxs)(`div`,{className:`relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground`,style:a,children:[o,s,c,(0,$.jsx)(`div`,{className:`app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6`,children:n})]}),t[5]=n,t[6]=l),l},pf=()=>{let e=(0,pd.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsx)(`div`,{className:`flex min-h-screen items-center justify-center bg-background text-foreground`,children:(0,$.jsx)(Qo,{width:120,height:120})}),e[0]=t):t=e[0],t},mf=e=>{let t=(0,pd.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=Yt(),c=o===`rate-limit`,l=i?Math.ceil(i/60):1,u;t[0]!==c||t[1]!==s?(u=s(c?`sessionAuth.error.rateLimitTitle`:`sessionAuth.error.networkTitle`),t[0]=c,t[1]=s,t[2]=u):u=t[2];let d;t[3]===u?d=t[4]:(d=(0,$.jsx)(`h1`,{className:`typography-ui-header font-semibold text-destructive`,children:u}),t[3]=u,t[4]=d);let f;t[5]!==c||t[6]!==l||t[7]!==s?(f=c?s(l>1?`sessionAuth.error.rateLimitDescriptionPlural`:`sessionAuth.error.rateLimitDescriptionSingle`,{minutes:l}):s(`sessionAuth.error.networkDescription`),t[5]=c,t[6]=l,t[7]=s,t[8]=f):f=t[8];let p;t[9]===f?p=t[10]:(p=(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground max-w-xs`,children:f}),t[9]=f,t[10]=p);let m;t[11]!==d||t[12]!==p?(m=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[d,p]}),t[11]=d,t[12]=p,t[13]=m):m=t[13];let h;t[14]===s?h=t[15]:(h=s(`sessionAuth.error.retry`),t[14]=s,t[15]=h);let g;t[16]!==n||t[17]!==h?(g=(0,$.jsx)(Qt,{type:`button`,onClick:n,className:`w-full max-w-xs`,children:h}),t[16]=n,t[17]=h,t[18]=g):g=t[18];let _;return t[19]!==a||t[20]!==m||t[21]!==g?(_=(0,$.jsx)(ff,{children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-6 text-center`,children:[m,g,a]})}),t[19]=a,t[20]=m,t[21]=g,t[22]=_):_=t[22],_},hf=({children:e})=>{let{t}=Yt(),n=Q.useMemo(()=>ge(),[]),r=n,a=Q.useMemo(()=>O()&&!n,[n]),[o,s]=Q.useState(()=>r?`authenticated`:`pending`),[c,d]=Q.useState(``),[f,p]=Q.useState(!1),[m,h]=Q.useState(``),[g,_]=Q.useState(void 0),[v,y]=Q.useState(!1),[b,x]=Q.useState(_s),[S,C]=Q.useState(!1),[w,T]=Q.useState(!1),[E,D]=Q.useState(()=>af()),[k,A]=Q.useState(null),[j,M]=Q.useState(r),N=Q.useRef(null),P=Q.useRef(r);Q.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Jd,E?`true`:`false`)},[E]);let F=Q.useCallback(async()=>{if(r)return _s;try{let e=await es();return x(e),e}catch{return x(_s),_s}},[r]);Q.useEffect(()=>{let e=!1;if(!r)return(async()=>{try{if(!window.isSecureContext||!xo()){e||C(!1);return}e||C(!0)}catch{e||C(!1)}})(),()=>{e=!0}},[r]);let I=Q.useRef(0),L=Q.useRef(null),R=Q.useRef(null),z=Q.useCallback(()=>{L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),B=Q.useCallback(()=>{I.current=0,z()},[z]),V=Q.useCallback(()=>I.current>=Kd?!1:(I.current+=1,z(),L.current=window.setTimeout(()=>{L.current=null,R.current?.()},qd*I.current),!0),[z]);Q.useEffect(()=>z,[z]);let H=Q.useCallback(async()=>{if(r){s(`authenticated`);return}s(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([rf(),F()]),n=await e.text();if(e.ok){B(),s(`authenticated`),y(!1),h(``),_(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}B(),y(e.tunnelLocked===!0),x(t),s(`locked`),_(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}B(),_(e.retryAfter),y(!1),s(`rate-limited`);return}if(V())return;s(`error`),y(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),Wd({shouldUseDesktopShellPasswordLogin:cf()})===`locked`){s(`locked`),_(void 0),y(!1);return}if(V())return;s(`error`),y(!1)}},[F,B,V,r]);Q.useEffect(()=>{R.current=H},[H]),Q.useEffect(()=>{r||H()},[H,r]),Q.useEffect(()=>{if(o===`pending`||o===`authenticated`||typeof document>`u`)return;let e=document.getElementById(`initial-loading`);if(!e)return;e.classList.add(`fade-out`);let t=window.setTimeout(()=>{e.remove()},300);return()=>{window.clearTimeout(t)}},[o]),Q.useEffect(()=>{if(r)return;let e=yd(e=>{l(e)&&(d(``),h(``),_(void 0),y(!1),B(),M(!1),P.current=!1,s(`pending`),H())}),t=i(t=>e.schedule(t));return()=>{t(),e.cancel()}},[H,B,r]),Q.useEffect(()=>{!r&&o===`locked`&&(P.current=!1,M(!1))},[r,o]),Q.useEffect(()=>{o===`locked`&&N.current&&(N.current.focus(),N.current.select())},[o]),Q.useEffect(()=>{if(!r&&o===`authenticated`&&!P.current){P.current=!0;let e=!1;return _d({runtimeKey:u(),initializeAppearance:he,syncSettings:ce,applyDirectory:md,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||M(!0)}),()=>{e=!0}}},[r,o]);let ee=async e=>{e.preventDefault(),await W(!1)},U=Q.useCallback(async()=>{A(`register`),T(!0);try{await ns()}finally{A(null),T(!1)}await F()},[F]),te=Q.useCallback(()=>{Vs(),A(null),T(!1)},[]),W=Q.useCallback(async e=>{if(!v&&!(!c||f)){w&&te(),p(!0),h(``);try{if(cf()){let e=await lf(c,E);if(e?.token){d(``),y(!1),await df(e.token),s(`authenticated`);return}if(e?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),y(!1),s(`locked`);return}if(e?.status===429){_(void 0),y(!1),s(`rate-limited`);return}}let n=await of(c,E);if(n.ok){let r=await n.json().catch(()=>null),i=$d(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await lf(c,E))?.token||await sf()),d(``),y(!1),a&&await df(a),e&&S)try{await U(),ro.success(t(`sessionAuth.toast.passkeyAdded`)),s(`authenticated`);return}catch(e){if(rs(e))ro.message(t(`sessionAuth.toast.passkeySetupCanceled`));else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);ro.error(n)}s(`authenticated`);return}s(`authenticated`);return}if(n.status===401){h(t(`sessionAuth.error.incorrectPassword`)),y(!1),s(`locked`);return}if(n.status===429){let e=await n.json().catch(()=>({}));_(e.retryAfter),y(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.unexpectedResponse`)),y(!1),s(`error`)}catch(e){console.warn(`Failed to submit UI password:`,e);let n=cf()?await lf(c,E):null;if(n?.token){d(``),y(!1),await df(n.token),s(`authenticated`);return}if(n?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),y(!1),s(`locked`);return}if(n?.status===429){_(void 0),y(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.networkRetry`)),y(!1),s(`error`)}finally{p(!1)}}},[te,w,f,v,c,U,S,t,E]),ne=Q.useCallback(async()=>{if(!(f||!S)){if(w){te();return}T(!0),A(`auth`),h(``);try{let e=await Ds(E,{issueClientToken:$d(),clientLabel:`OpenChamber Desktop`,...nf()}),t=$d()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await df(t),d(``),s(`authenticated`)}catch(e){if(rs(e))h(``);else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySignInCanceled`);h(n)}}finally{A(null),T(!1)}}},[te,w,f,S,t,E]),G=Q.useCallback(async()=>{if(!(f||v||!S)){if(w){te();return}if(o!==`authenticated`){if(!c){h(t(`sessionAuth.error.enterPasswordForPasskey`));return}await W(!0);return}h(``);try{await U(),ro.success(t(`sessionAuth.toast.passkeyAdded`))}catch(e){if(rs(e)){ro.message(t(`sessionAuth.toast.passkeySetupCanceled`));return}let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);ro.error(n)}}},[te,W,w,f,v,c,U,o,S,t]),re=S&&b.enabled,ie=re&&b.hasPasskeys;return o===`pending`||o===`authenticated`&&!j?(0,$.jsx)(pf,{}):o===`error`?(0,$.jsx)(mf,{onRetry:()=>{B(),H()},errorType:`network`,children:a&&(0,$.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,$.jsx)(Ud,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})}):o===`rate-limited`?(0,$.jsx)(mf,{onRetry:()=>void H(),errorType:`rate-limit`,retryAfter:g}):o===`locked`?(0,$.jsx)(ff,{children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-6 w-full max-w-xs`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-xl font-semibold text-foreground`,children:t(v?`sessionAuth.locked.tunnelTitle`:`sessionAuth.locked.unlockTitle`)}),(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:t(v?`sessionAuth.locked.tunnelDescription`:`sessionAuth.locked.passwordDescription`)})]}),!v&&(0,$.jsxs)(`form`,{onSubmit:ee,className:`w-full space-y-2`,children:[ie&&(0,$.jsxs)(Qt,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void ne(),disabled:f||w&&k!==`auth`,children:[w?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(Z,{name:`lock-unlock`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{children:t(w&&k===`auth`?`sessionAuth.actions.cancelPasskey`:`sessionAuth.actions.usePasskey`)})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(Z,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,$.jsx)(Ko,{id:`openchamber-ui-password`,ref:N,type:`password`,autoComplete:`current-password`,placeholder:t(`sessionAuth.password.placeholder`),value:c,onChange:e=>{d(e.target.value),m&&h(``)},className:`pl-10`,"aria-invalid":!!m||void 0,"aria-describedby":m?`oc-ui-auth-error`:void 0,disabled:f})]}),(0,$.jsx)(Qt,{type:`submit`,size:`icon`,disabled:!c||f,"aria-label":t(f?`sessionAuth.actions.unlockingAria`:`sessionAuth.actions.unlockAria`),children:f?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(Z,{name:`lock-unlock`,className:`h-4 w-4`})})]}),re?(0,$.jsxs)(`div`,{className:`flex items-center justify-between pt-1`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-center typography-micro text-muted-foreground`,children:[(0,$.jsx)(Oo,{checked:E,onChange:D,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void G(),disabled:f,children:t(w&&k===`register`?`sessionAuth.actions.cancelPasskeySetup`:`sessionAuth.actions.addPasskey`)})]}):(0,$.jsxs)(`label`,{className:`flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground`,children:[(0,$.jsx)(Oo,{checked:E,onChange:D,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),m&&(0,$.jsx)(`p`,{id:`oc-ui-auth-error`,className:`typography-meta text-destructive`,children:m})]}),a&&(0,$.jsxs)(`div`,{className:`w-full`,children:[(0,$.jsx)(Ud,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,$.jsx)($.Fragment,{children:e})},gf=e=>{let t=(0,pd.c)(14),{children:n}=e,r=q(_f),i=q(vf),a=q(yf),o=q(bf),s=q(xf),{deviceType:c,hasTouchInput:l}=qs(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&St(),t[0]=u):u=t[0];let d=u,f;t[1]!==s||t[2]!==a?(f=()=>{a(),s()},t[1]=s,t[2]=a,t[3]=f):f=t[3];let p;t[4]!==s||t[5]!==a||t[6]!==i||t[7]!==c||t[8]!==r||t[9]!==l||t[10]!==o?(p=[r,i,a,o,s,c,l,d],t[4]=s,t[5]=a,t[6]=i,t[7]=c,t[8]=r,t[9]=l,t[10]=o,t[11]=p):p=t[11],Q.useLayoutEffect(f,p);let m;return t[12]===n?m=t[13]:(m=(0,$.jsx)($.Fragment,{children:n}),t[12]=n,t[13]=m),m};function _f(e){return e.fontSize}function vf(e){return e.codeFontSize}function yf(e){return e.applyTypography}function bf(e){return e.padding}function xf(e){return e.applyPadding}var Sf=e(Ye(),1),Cf=e=>{if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`#`))return null;let n=t.slice(1);if((n.length===3||n.length===4)&&(n=n.split(``).map(e=>e+e).join(``)),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;let r=Number.parseInt(n,16);return Number.isNaN(r)?null:`${r>>16&255} ${r>>8&255} ${r&255}`},wf=class{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(e){let t=[];return t.push(...this.generateTailwindVariables(e)),t.push(...this.generatePrimaryColors(e.colors.primary)),t.push(...this.generateSurfaceColors(e.colors.surface)),t.push(...this.generateInteractiveColors(e.colors.interactive)),t.push(...this.generateStatusColors(e.colors.status)),t.push(...this.generatePullRequestColors(e)),t.push(...this.generateSyntaxColors(e.colors.syntax)),t.push(...this.generateComponentColors(e.colors,e)),t.push(...this.generateTypographyVariables()),e.config&&t.push(...this.generateConfigVariables(e.config)),t.join(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ToolOutputDialog-nhZwyPOH.js","assets/rolldown-runtime-C0FnF6B9.js","assets/runtime-fetch-zIalUnbb.js","assets/runtime-auth-D66yq6ie.js","assets/runtime-switch-LvWDU-SL.js","assets/vendor-base-ui-CnHfUmDN.js","assets/useUIStore-CxOoCv7B.js","assets/vendor-zustand-B4dlGEM2.js","assets/vendor-react-DLPElpoQ.js","assets/vendor-pierre-diffs-DX7XTPG3.js","assets/vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js","assets/vendor-hast-util-to-html-B0p1k5Xa.js","assets/vendor-character-entities-legacy-Wut6vMuj.js","assets/vendor-character-entities-html4-DlN_yAFd.js","assets/vendor-ccount-CyGsA0u7.js","assets/vendor-comma-separated-tokens-B9ouxNNS.js","assets/vendor-oniguruma-to-es-CrHzjjSU.js","assets/vendor-oniguruma-parser-D2DIvhSP.js","assets/vendor-diff-Dq7CZNim.js","assets/vendor-lru_map-DpDied8H.js","assets/vendor-reactuses-core-BnW6GxJt.js","assets/vendor-lodash-es-DfLbG5Af.js","assets/vendor-js-cookie-hSOiFTtX.js","assets/button-bhVnVYB_.js","assets/persistence-DwRBC4zl.js","assets/vendor-pathe-vBmvQE8f.js","assets/vendor-tanstack-query-core-BWz0ose6.js","assets/store-BoixGrYS.js","assets/vendor-class-variance-authority-BLUaYARZ.js","assets/vendor-tailwind-merge-BicNWLTg.js","assets/dialog-C2Dw0yqA.js","assets/Icon-C9ZHbwqp.js","assets/useThemeSystem-DMzWVJaW.js","assets/markdownTheme-DOfGg-A7.js","assets/appThemeRegistry-nmKlvHum.js","assets/platform-DQ5_LNKO.js","assets/vendor-opencode-sdk-C07HQypa.js","assets/useMobileNavigationStore-C4HhoiC4.js","assets/vendor-tanstack-react-query-D7pys_c9.js","assets/vendor-sonner-DVzioF3d.js","assets/useAssistantUIStore-CLPCNoj_.js","assets/vendor-zod-Dzk5kdUU.js","assets/vendor-fuse.js-DB5wDJbI.js","assets/MarkdownRenderer-DSqWFDq7.js","assets/markdownHeightCache-CT2d4yTV.js","assets/dualLimitLru-D8Sphgua.js","assets/markdown-worker-CptoICmq.js","assets/useEffectiveDirectory-Cz772BtQ.js","assets/imageSource-BlAJJUEI.js","assets/relay-image-stream-DM7atqJs.js","assets/useWorkerHighlightedLines-tFoFZt9Z.js","assets/tooltip-BLznq5KR.js","assets/vendor-tanstack-react-virtual-tlDgH6PG.js","assets/vendor-capacitor-app-PzT84wSx.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}from"./runtime-auth-D66yq6ie.js";import{c as i,f as a,i as o,l as s,n as c,o as l,r as u,t as d}from"./runtime-switch-LvWDU-SL.js";import{n as f}from"./runtime-fetch-zIalUnbb.js";import{$ as p,$t as m,C as h,Cn as g,Et as _,G as v,H as y,I as b,J as x,K as S,Kt as C,Lt as w,M as T,N as E,Pt as D,Qt as O,R as k,S as A,T as j,Tt as M,V as N,X as P,Y as F,Yt as I,Z as L,Zt as R,_ as z,b as B,c as V,ct as H,d as ee,et as U,ft as te,g as W,gt as ne,h as G,ht as re,it as ie,j as K,kt as ae,lt as oe,m as se,n as ce,nn as le,nt as ue,ot as de,q as fe,r as pe,st as me,t as he,tn as ge,tt as _e,u as ve,ut as ye,v as be,x as xe,xt as Se,y as Ce,z as we}from"./persistence-DwRBC4zl.js";import{_ as Te,c as Ee,d as De,f as Oe,h as ke,i as Ae,l as je,m as Me,n as Ne,o as Pe,p as Fe,r as Ie,s as Le}from"./desktopHosts-B052a4UK.js";import{r as Re}from"./desktopRelayRestore-OjKNXr10.js";import{a as ze,i as Be,r as Ve,t as He}from"./vendor-zustand-B4dlGEM2.js";import{c as Ue,d as We,f as Ge,l as Ke,nt as qe,rt as Je,tt as Ye,u as Xe}from"./vendor-base-ui-CnHfUmDN.js";import{At as Ze,Bt as Qe,Ct as $e,Gt as et,Ht as tt,Jt as nt,Kt as rt,Nt as it,Ot as at,Pt as ot,Rt as st,St as ct,Ut as lt,Wt as ut,Yt as dt,jt as ft,kt as pt,n as mt,t as ht,zt as gt}from"./platform-DQ5_LNKO.js";import{d as _t,g as vt,h as yt,m as bt,s as xt,t as q,v as St,y as Ct}from"./useUIStore-CxOoCv7B.js";import{a as wt,n as Tt,o as Et}from"./vendor-aparajita-capacitor-secure-storage-CjQdwfjS.js";import{n as Dt}from"./vendor-react-DLPElpoQ.js";import{c as Ot,i as kt,n as At,s as jt,t as Mt}from"./vendor-tanstack-react-query-D7pys_c9.js";import{B as Nt,R as Pt,V as Ft,c as It}from"./vendor-codemirror-autocomplete-DHomsvW7.js";import{i as Lt,u as Rt}from"./vendor-pierre-diffs-DX7XTPG3.js";import{t as zt}from"./vendor-sonner-DVzioF3d.js";import{a as Bt,d as Vt,f as Ht,i as Ut,l as Wt,n as J,o as Gt,r as Kt}from"./vendor-reactuses-core-BnW6GxJt.js";import{_ as qt,d as Jt,f as Yt,i as Xt,p as Zt,r as Y,t as Qt,v as $t}from"./button-bhVnVYB_.js";import{i as en,t as tn}from"./store-BoixGrYS.js";import{$ as nn,$i as rn,$r as an,$t as on,A as sn,Aa as cn,An as ln,Ao as un,At as dn,B as fn,Bi as pn,Bn as mn,Br as hn,C as gn,Ci as _n,Cn as vn,Ct as yn,D as bn,Di as xn,Dn as Sn,Dr as Cn,Dt as wn,E as Tn,Ea as En,Ei as Dn,En as On,Er as kn,Et as An,F as jn,Fi as Mn,Fr as Nn,Ft as Pn,G as Fn,Ga as In,Gi as Ln,Gt as Rn,H as zn,Ha as Bn,Hi as Vn,Hr as Hn,Ht as Un,I as Wn,Ii as Gn,It as Kn,J as qn,Ja as Jn,Jr as Yn,Jt as Xn,K as Zn,Ka as Qn,Kr as $n,L as er,La as tr,Li as nr,Lr as rr,M as ir,Mi as ar,Mr as or,N as sr,Na as cr,Ni as lr,Nn as ur,No as dr,Nr as fr,O as pr,Oi as mr,On as hr,Or as gr,Ot as _r,P as vr,Pi as yr,Po as br,Pt as xr,Q as Sr,Qr as Cr,R as wr,Ri as Tr,Rt as Er,Sa as Dr,Si as Or,St as kr,T as Ar,Ti as jr,Tn as Mr,Tr as Nr,Tt as Pr,U as Fr,Ua as Ir,Ui as Lr,Un as Rr,Ur as zr,Ut as Br,V as Vr,Va as Hr,Vi as Ur,Vn as Wr,Vr as Gr,Vt as Kr,W as qr,Wa as Jr,Wi as Yr,Wr as Xr,Wt as Zr,X as Qr,Xa as $r,Xr as ei,Xt as ti,Y as ni,Ya as ri,Yi as ii,Yt as ai,Z as oi,Zt as si,_a as ci,_i as li,_t as ui,a as di,aa as fi,ai as pi,an as mi,ao as hi,b as gi,ba as _i,bi as vi,bn as yi,bo as bi,bt as xi,c as X,ca as Si,ci as Ci,cn as wi,d as Ti,da as Ei,di as Di,dn as Oi,ea as ki,ei as Ai,en as ji,er as Mi,et as Ni,fn as Pi,ft as Fi,ga as Ii,gi as Li,gt as Ri,h as zi,ha as Bi,hi as Vi,hn as Hi,hr as Ui,ht as Wi,i as Gi,ia as Ki,ii as qi,it as Ji,j as Yi,ja as Xi,ji as Zi,jr as Qi,jt as $i,k as ea,ka as ta,kn as na,kt as ra,la as ia,li as aa,ln as oa,ma as sa,mi as ca,mn as la,mr as ua,mt as da,n as fa,na as pa,ni as ma,nn as ha,no as ga,nr as _a,nt as va,on as ya,p as ba,pa as xa,pi as Sa,pn as Ca,pt as wa,q as Ta,qa as Ea,qr as Da,ra as Oa,rn as ka,rr as Aa,rt as ja,sa as Ma,sn as Na,ti as Pa,tn as Fa,to as Ia,tr as La,tt as Ra,ui as za,un as Ba,ut as Va,va as Ha,vi as Ua,vt as Wa,w as Ga,wa as Ka,wi as qa,wn as Ja,wt as Ya,x as Xa,xa as Za,xi as Qa,xn as $a,xo as eo,xt as to,yi as no,yr as ro,yt as io,z as ao,zi as oo,zn as so,zr as co}from"./useMobileNavigationStore-C4HhoiC4.js";import{a as lo,i as uo,l as fo,n as po,o as mo,r as ho,s as go,t as _o}from"./dialog-C2Dw0yqA.js";import{t as vo}from"./AgentAvatar-CUDJ3_nZ.js";import{n as Z}from"./Icon-C9ZHbwqp.js";import{E as yo,n as bo}from"./gitApi-CbhPyoLY.js";import{a as xo}from"./vendor-simplewebauthn-browser-Dwhcdg_5.js";import{C as So,D as Co,J as wo,O as To,S as Eo,Y as Do,Z as Oo,_ as ko,a as Ao,b as jo,f as Mo,h as No,i as Po,k as Fo,l as Io,m as Lo,n as Ro,o as zo,q as Bo,s as Vo,u as Ho,w as Uo,x as Wo,y as Go}from"./projectMeta-D2rOiejm.js";import{t as Ko}from"./input-8Te_vPwB.js";import{i as qo,n as Jo,t as Yo}from"./tooltip-BLznq5KR.js";import{$t as Xo,A as Zo,At as Qo,B as $o,Ct as es,D as ts,Dt as ns,Et as rs,Ft as is,G as as,Gt as os,H as ss,J as cs,K as ls,M as us,Mt as ds,Nt as fs,Pt as ps,Qt as ms,R as hs,Rt as gs,St as _s,U as vs,V as ys,Vt as bs,W as xs,X as Ss,Y as Cs,Z as ws,Zt as Ts,at as Es,bt as Ds,ct as Os,it as ks,j as As,jt as js,k as Ms,lt as Ns,mt as Ps,n as Fs,nt as Is,ot as Ls,q as Rs,t as zs,tt as Bs,xt as Vs,z as Hs,zt as Us}from"./useSessionAutoCleanup-0sFR1yLV.js";import{n as Ws,r as Gs,t as Ks}from"./useThemeSystem-DMzWVJaW.js";import{i as qs,t as Js}from"./OverlayScrollbar-C7fAOAKT.js";import{a as Ys,c as Xs,i as Zs,l as Qs,n as $s,o as ec,r as tc,s as nc}from"./markdownTheme-DOfGg-A7.js";import{n as rc,r as ic,t as ac}from"./useRuntimeAPIs-DSLXJybW.js";import{A as oc,C as sc,D as cc,E as lc,F as uc,I as dc,N as fc,O as pc,P as mc,S as hc,T as gc,a as _c,b as vc,c as yc,f as bc,i as xc,j as Sc,k as Cc,l as wc,m as Tc,n as Ec,o as Dc,p as Oc,r as kc,s as Ac,t as jc,u as Mc,w as Nc,x as Pc}from"./insertionBoundaries-DcjuOya1.js";import{a as Fc,c as Ic,i as Lc,n as Rc,o as zc,r as Bc,s as Vc}from"./fileMentionTouchSelection-DipHuaLB.js";import{C as Hc,D as Uc,E as Wc,M as Gc,O as Kc,S as qc,T as Jc,_ as Yc,b as Xc,c as Zc,d as Qc,f as $c,g as el,h as tl,i as nl,k as rl,l as il,m as al,o as ol,p as sl,s as cl,t as ll,u as ul,v as dl,w as fl,x as pl,y as ml}from"./appThemeRegistry-nmKlvHum.js";import{a as hl,n as gl,o as _l,r as vl,t as yl}from"./MarkdownRenderer-DSqWFDq7.js";import{n as bl,r as xl}from"./textarea-DRL916s6.js";import{_ as Sl,a as Cl,c as wl,g as Tl,l as El,o as Dl,t as Ol,v as kl,y as Al}from"./vendor-dnd-kit-core-CvWxUPdb.js";import{i as jl,n as Ml,o as Nl,s as Pl,t as Fl}from"./vendor-dnd-kit-sortable-hHdP9lLb.js";import{a as Il,n as Ll,t as Rl}from"./url-CMQwHq4k.js";import{c as zl,l as Bl,p as Vl}from"./markdown-worker-CptoICmq.js";import{n as Hl,t as Ul}from"./useEffectiveDirectory-Cz772BtQ.js";import{a as Wl,c as Gl,d as Kl,f as ql,i as Jl,l as Yl,n as Xl,r as Zl,s as Ql,t as $l}from"./FadeInOnReveal-BLSnyG2Z.js";import{c as eu,f as tu,l as nu,m as ru,n as iu,p as au,r as ou,s as su,u as cu}from"./imageSource-BlAJJUEI.js";import{A as lu,C as uu,D as du,E as fu,M as pu,O as mu,S as hu,T as gu,a as _u,b as vu,c as yu,g as bu,h as xu,i as Su,j as Cu,k as wu,o as Tu,p as Eu,r as Du,s as Ou,t as ku,v as Au,w as ju,x as Mu,y as Nu}from"./useWorkerHighlightedLines-tFoFZt9Z.js";import{C as Pu,D as Fu,S as Iu,T as Lu,_ as Ru,a as zu,b as Bu,c as Vu,d as Hu,f as Uu,g as Wu,h as Gu,l as Ku,m as qu,o as Ju,p as Yu,s as Xu,u as Zu,v as Qu,w as $u,x as ed,y as td}from"./sessionChangeSummary-CfnRZ0gS.js";import{t as nd}from"./vendor-cmdk-CeAGfrLo.js";import{t as rd}from"./sortable-tabs-strip-BmvLnn6O.js";import{a as id}from"./markdownHeightCache-CT2d4yTV.js";import{n as ad,t as od}from"./vendor-tanstack-react-virtual-tlDgH6PG.js";import{t as sd}from"./dualLimitLru-D8Sphgua.js";import{i as cd,t as ld}from"./vendor-framer-motion-DFy_BSVd.js";import{t as ud}from"./vendor-legendapp-list-WE32lwNk.js";import{n as dd,t as fd}from"./useFontPreferences-DCaY8NbU.js";typeof window<`u`&&(window.__opencodeDebug={getLastAssistantMessage(){let e=X.getState().currentSessionId;if(!e)return null;let t=Ma(e);if(!t||t.length===0)return null;for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role===`assistant`){let e=(Si(n.id)||[]).map(e=>{let t={id:e.id,type:e.type};return e.type===`text`?(t.text=e.text,t.textLength=e.text?.length||0):e.type===`tool`?(t.tool=e.tool,t.state=e.state?.status):(e.type===`step-start`||e.type===`step-finish`)&&(t.isStepMarker=!0),t}),t=e.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=e.some(e=>e.type===`tool`),i=e.some(e=>e.type===`step-start`||e.type===`step-finish`),a=e.length===0,o=!t&&!r&&(!a||i),s={messageId:n.id,role:n.role,timestamp:n.time?.created||0,partsCount:e.length,parts:e,isEmpty:a,isEmptyResponse:o,raw:n};return s.messageId,s.partsCount,s.isEmpty,s.isEmptyResponse,s.isEmpty&&console.warn(`[WARNING] Message has NO parts!`),s.isEmptyResponse&&(console.warn(`[WARNING] Message has parts but NO meaningful content (empty text, no tools)!`),i&&!t&&!r&&console.warn(`[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!`)),s}}return null},truncateString(e,t=80){return!e||typeof e!=`string`||e.length<=t?e:e.substring(0,t)+`…`},truncateMessages(e){return e.map(e=>({...e,parts:(Si(e.id)||[]).map(e=>{let t={...e};return`text`in e&&(t.text=this.truncateString(e.text)),`textPreview`in e&&(t.textPreview=this.truncateString(e.textPreview)),e.state&&(t.state={...e.state},`output`in e.state&&(t.state.output=this.truncateString(e.state.output)),`error`in e.state&&(t.state.error=this.truncateString(e.state.error)),e.state.metadata&&`preview`in e.state.metadata&&(t.state.metadata={...e.state.metadata,preview:this.truncateString(e.state.metadata.preview)})),t})}))},getAllMessages(e=!1){let t=X.getState().currentSessionId;if(!t)return[];let n=Ma(t);return`${n.length}`,n.forEach((e,t)=>{let n=Si(e.id)||[];`${t}${e.role}${e.id}${n.length}`}),e?this.truncateMessages(n):n},async getAppStatus(){let e=$e.getState(),t=X.getState(),n=eo.getState(),r=e.currentDirectory||null,i=it.getDirectory()??null,a=ia(),o=new Set,s={};a.forEach(e=>{let t=e.directory;typeof t==`string`&&t.trim().length>0?(o.add(t),s[t]=(s[t]??0)+1):s[`(none)`]=(s[`(none)`]??0)+1});let c=(()=>{if(typeof window>`u`)return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem(`lastDirectory`),homeDirectory:window.localStorage.getItem(`homeDirectory`)}}catch(e){return{available:!1,error:e instanceof Error?e.message:String(e)}}})(),l=g(),u=typeof window<`u`&&!!window.__OPENCHAMBER_ELECTRON__,d=async e=>{try{return await e.json()}catch{return null}},p=async e=>{try{return await e.text()}catch{return null}},m=async e=>{try{let t=await f(e);return t.ok?await d(t):{status:t.status}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},h=null,_=null,v=null,y=null;try{let e=await it.getSdkClient().path.get(r?{directory:r}:void 0);h=e.error?{error:e.error}:e.data}catch(e){h={error:e instanceof Error?e.message:String(e)}}try{let e=await it.getSdkClient().project.current(r?{directory:r}:void 0);_=e.error?{error:e.error}:e.data}catch(e){_={error:e instanceof Error?e.message:String(e)}}v=await m(`/api/config/settings`);try{let e=await f(`/api/health`),t=e.headers.get(`content-type`)||``,n=await p(e),r=t.toLowerCase().includes(`application/json`),i=null;if(r&&n)try{let e=JSON.parse(n);e&&typeof e==`object`&&!Array.isArray(e)&&(i=e)}catch{i=null}y={status:e.status,ok:e.ok,contentType:t,type:r?`json`:`html`,openCodePort:i?.openCodePort??null,openCodeRunning:i?.openCodeRunning??null,openCodeSecureConnection:i?.openCodeSecureConnection??null,openCodeAuthSource:i?.openCodeAuthSource??null,isOpenCodeReady:i?.isOpenCodeReady??null,lastOpenCodeError:i?.lastOpenCodeError??null,preview:n?n.slice(0,120):null}}catch(e){y={error:e instanceof Error?e.message:String(e)}}let b={isGitRepo:null};if(r)try{b.isGitRepo=await bo(r)}catch(e){b={isGitRepo:null,error:e instanceof Error?e.message:String(e)}}let x=n.projects.map(e=>({id:e.id,path:e.path,label:e.label}));return{runtime:{platform:l?.runtime?.platform??null,isDesktop:u,isVSCode:!!l?.runtime?.isVSCode,hasRuntimeApis:!!l,desktopServerOrigin:null},location:typeof window<`u`?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:r,opencodeDirectory:h?.directory||h?.worktree||i,homeDirectory:e.homeDirectory||null,isHomeReady:e.isHomeReady,hasPersistedDirectory:e.hasPersistedDirectory,isSwitchingDirectory:e.isSwitchingDirectory},projects:{total:n.projects.length,activeProjectId:n.activeProjectId,samples:x},sessions:{total:a.length,currentSessionId:t.currentSessionId,lastLoadedDirectory:t.lastLoadedDirectory,uniqueDirectories:o.size,directorySamples:Array.from(o).slice(0,5),directoryCounts:s},worktrees:{available:t.availableWorktrees.length,metadataEntries:t.worktreeMetadata.size},git:b,localStorage:c,opencode:{pathInfo:h,projectInfo:_,health:y},openchamber:{settingsInfo:v}}},async buildDiagnosticsReport(){let e=await this.getAppStatus();return JSON.stringify(e,null,2)},async copyTextToClipboard(e){return Jt(e)},async copyDiagnosticsReport(){let e=await this.buildDiagnosticsReport();return{...await this.copyTextToClipboard(e),report:e}},checkLastMessage(){let e=this.getLastAssistantMessage();if(!e)return!1;let t=e.isEmpty||e.isEmptyResponse;return t&&(console.error(`[ALERT] PROBLEMATIC MESSAGE DETECTED!`),e.messageId,e.isEmpty,e.isEmptyResponse,e.partsCount,e.parts.length>0&&e.parts),t},getStreamingState(){let e=X.getState(),t=vn.getState(),n=e.currentSessionId?t.streamingMessageIds.get(e.currentSessionId)??null:null;return Array.from(t.streamingMessageIds.entries()),Array.from(t.messageStreamStates.entries()),{streamingMessageId:n,streamingMessageIds:t.streamingMessageIds,streamStates:t.messageStreamStates}},findEmptyMessages(){let e=X.getState().currentSessionId;if(!e)return[];let t=Ma(e).filter(e=>e.role===`assistant`).filter(e=>{let t=Si(e.id)||[],n=t.some(e=>e.type===`text`&&e.text&&e.text.trim().length>0),r=t.some(e=>e.type===`tool`);return t.length===0||!n&&!r});return`${t.length}`,t.forEach((e,t)=>{let n=Si(e.id)||[];`${t}`,e.id,n.length,e.providerID,e.modelID,e.time?.created}),t},showRetryHelp(){},analyzeMessageCompletionConsistency(e={}){let{includeNonAssistant:t=!1,verbose:n=!0,maxTableRows:r=25}=e,i=X.getState().currentSessionId;if(!i)return{summary:null,rows:[]};let a=Ma(i),o=t?a:a.filter(e=>e.role===`assistant`),s={totalMessages:a.length,analyzedMessages:o.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},c=e=>typeof e==`number`&&Number.isFinite(e)?e:null,l=e=>{let t=e.filter(e=>typeof e==`number`);return t.length>0?Math.max(...t):null},u=o.map((e,t)=>{let n=e,r=Si(e.id)||[],i=n.time??{},a=c(i.completed),o=a!==null,u=r.filter(e=>e.type===`tool`),d=r.filter(e=>e.type===`reasoning`),f=l(u.map(e=>c(e.state?.time?.end??e.state?.time?.start))),p=l(d.map(e=>c(e.time?.end??e.time?.start))),m=l([f,p].filter(e=>e!==null)),h=u.some(e=>[`pending`,`running`,`started`].includes(e.state?.status)),g=d.some(e=>typeof e.time?.end!=`number`);u.length>0&&(s.withTools+=1),d.length>0&&(s.withReasoning+=1),o||(s.completedMissing+=1);let _=!!(o&&typeof f==`number`&&a<f);_&&(s.completedBeforeTool+=1);let v=!!(o&&typeof p==`number`&&a<p);return v&&(s.completedBeforeReasoning+=1),o&&h&&(s.runningToolsWhenCompleted+=1),o&&g&&(s.reasoningOpenWhenCompleted+=1),{index:t,messageId:n.id,role:n.role,completedAt:a,latestToolTimestamp:f,latestReasoningTimestamp:p,latestPartTimestamp:m,completed_missing:!o,completed_before_tool:_,completed_before_reasoning:v,running_tools_when_completed:!!(o&&h),reasoning_open_when_completed:!!(o&&g),has_tools:u.length>0,has_reasoning:d.length>0}});return n&&(console.table(u.slice(0,r)),u.length>r&&`${r}${u.length}`),{summary:s,rows:u}},checkCompletionStatus(){let e=X.getState().currentSessionId;if(!e)return null;let t=Ma(e).filter(e=>e.role===`assistant`);if(t.length===0)return null;let n=t[t.length-1],r=(Si(n.id)||[]).filter(e=>e.type===`step-finish`),i=n.finish===`stop`,a=n.time?.completed,o=n.status,s=typeof a==`number`&&a>0||o===`completed`,c=!!(s&&i),l=vn.getState();n.sessionID&&l.streamingMessageIds.get(n.sessionID);let u=l.messageStreamStates.get(n.id);return n.id,n.id,u?.phase,{messageId:n.id,completed:a,status:o,hasCompletedFlag:s,hasStopReason:i,messageIsComplete:c,stepFinishParts:r,raw:n}}},at(),window.addEventListener(`error`,e=>{try{let t=e.message||``,n=e.filename||``;typeof t==`string`&&t.includes(`this._renderer.value.dimensions`)&&/xterm/i.test(String(n))&&e.preventDefault()}catch{}}));var Q=e(Je(),1),pd=Dt(),md=async()=>{if(typeof window>`u`)return;let e=null;try{e=D(`lastDirectory`)}catch(e){console.warn(`Failed to read saved directory preferences:`,e)}e&&!ge()&&$e.getState().setDirectory(e,{showOverlay:!1})},hd=new Map,gd=e=>hd.get(e)??null,_d=({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:i},a={})=>{let o=hd.get(e);if(o&&!a.force)return o;let s=(async()=>{o&&await o;try{await t()}catch(e){return i(`appearance`,e),!1}try{await Promise.all([n(),r()])}catch(e){i(`secondary`,e)}return!0})();return hd.set(e,s),s},vd=async({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,startWatchers:i,onError:a})=>{await _d({runtimeKey:e,initializeAppearance:t,syncSettings:n,applyDirectory:r,onError:a})&&i()},yd=(e,t=50)=>{let n=null,r;return{schedule:i=>{r=i,n&&clearTimeout(n),n=setTimeout(()=>{n=null;let t=r;r=void 0,t!==void 0&&e(t)},t)},cancel:()=>{n&&clearTimeout(n),n=null,r=void 0}}};function bd(e){return!e||e===`idle`?null:e===`ready`?`ok`:e===`error`?`unreachable`:`auth`}function xd(e,t){let n=e.via===`relay`;return t?n:!n}function Sd(e){let{isActive:t,isSsh:n,runtimeIsConnected:r,runtimeConnectionPhase:i,currentTransportIsRelay:a,probe:o,sshPhase:s}=e,c;c=t?r&&i===`connected`?`ok`:`checking`:n?bd(s):o?.status??`checking`;let l=t?a:o?.via===`relay`,u=null;return!n&&c===`ok`&&o?.status===`ok`&&typeof o.latencyMs==`number`&&(!t||xd(o,a))&&(u=Math.max(0,Math.round(o.latencyMs))),{statusKind:c,showViaRelay:l,latencyMs:u}}var $=qe(),Cd=`local`,wd=9e4,Td=`SSH connection cancelled`,Ed=e=>Re(e),Dd={},Od=e=>{let t=Fe(e);if(!t)return e.trim();try{let e=new URL(t);return e.pathname.endsWith(`/`)||(e.pathname=`${e.pathname}/`),e.toString()}catch{return t}},kd=()=>typeof window>`u`?``:window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,Ad=async()=>m()?Pe().catch(()=>``):``,jd=e=>e===`ok`?`bg-status-success`:e===`auth`||e===`update-recommended`?`bg-status-warning`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`bg-status-error`:e===`checking`?`bg-status-info`:`bg-muted-foreground/40`,Md=e=>e===`ok`?`text-[var(--status-success)]`:e===`auth`||e===`update-recommended`?`text-[var(--status-warning)]`:e===`incompatible`||e===`wrong-service`||e===`unreachable`?`text-[var(--status-error)]`:`text-muted-foreground`,Nd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,Pd=e=>e===`unreachable`||e===`wrong-service`||e===`incompatible`,Fd=e=>e===`ok`?`desktopHostSwitcher.status.connected`:e===`auth`?`desktopHostSwitcher.status.authRequired`:e===`checking`?`desktopHostSwitcher.status.checking`:e===`update-recommended`?`desktopHostSwitcher.status.updateRecommended`:e===`incompatible`?`desktopHostSwitcher.status.incompatible`:e===`wrong-service`?`desktopHostSwitcher.status.wrongService`:e===`unreachable`?`desktopHostSwitcher.status.unreachable`:`desktopHostSwitcher.status.unknown`,Id=e=>new Promise(t=>window.setTimeout(t,e)),Ld=e=>{switch(e){case`ready`:return`desktopHostSwitcher.sshPhase.ready`;case`error`:return`desktopHostSwitcher.sshPhase.error`;case`degraded`:return`desktopHostSwitcher.sshPhase.reconnecting`;case`config_resolved`:return`desktopHostSwitcher.sshPhase.resolvingConfig`;case`auth_check`:return`desktopHostSwitcher.sshPhase.checkingAuth`;case`master_connecting`:return`desktopHostSwitcher.sshPhase.connectingSsh`;case`remote_probe`:return`desktopHostSwitcher.sshPhase.probingRemote`;case`installing`:return`desktopHostSwitcher.sshPhase.installing`;case`updating`:return`desktopHostSwitcher.sshPhase.updating`;case`server_detecting`:return`desktopHostSwitcher.sshPhase.detectingServer`;case`server_starting`:return`desktopHostSwitcher.sshPhase.startingServer`;case`forwarding`:return`desktopHostSwitcher.sshPhase.forwardingPorts`;default:return`desktopHostSwitcher.sshPhase.idle`}},Rd=async()=>{let e=await os().catch(()=>[]),t={};for(let n of e)t[n.id]=n;return t},zd=async(e,t,n,r)=>{let i=Date.now()+t;for(;Date.now()<i;){if(r?.())throw Error(Td);let t=(await os(e).catch(()=>[])).find(t=>t.id===e);if(t){if(n(t),t.phase===`ready`)return t;if(t.phase===`error`)throw Error(t.detail||`SSH connection failed`)}await Id(700)}throw r?.()?Error(Td):Error(`Timed out waiting for SSH connection`)},Bd=e=>({id:Cd,label:`Local`,url:e||kd()}),Vd=e=>{let t=typeof window>`u`?``:window.location.href,n=e.find(e=>e.id===Cd)?.url||kd(),r=d(),i=Fe(n)||n,a=Fe(t)||t,o=u(),s=e.find(e=>e.relay&&Ed(e)===o);if(s)return{id:s.id,label:s.label,url:s.url};if(r&&Oe(r,n))return{id:Cd,label:`Local`,url:i};let c=e.find(e=>r?Oe(r,je(e)):!1);if(c)return{id:c.id,label:c.label,url:Fe(je(c))||je(c)};if(t&&Oe(t,n))return{id:Cd,label:`Local`,url:i};let l=e.find(e=>t?Oe(t,e.url):!1);return l?{id:l.id,label:l.label,url:Fe(l.url)||l.url}:t.startsWith(`openchamber-ui://`)?{id:Cd,label:`Local`,url:i}:{id:`custom`,label:ke(a||`Instance`),url:a}};function Hd({open:e,onOpenChange:t,embedded:n=!1,onHostSwitched:r}){let{t:a}=Yt(),s=q(e=>e.setSettingsDialogOpen),c=q(e=>e.setSettingsPage),l=Oa(e=>e.isConnected),u=Oa(e=>e.connectionPhase),[d,f]=Q.useState([]),[p,h]=Q.useState(null),[g,_]=Q.useState(()=>({...Dd}));Q.useEffect(()=>{Object.assign(Dd,g)},[g]);let[v,y]=Q.useState(!1),[b,x]=Q.useState(!1),[S,C]=Q.useState(!1),w=ms(),T=Xo(),[E,D]=Q.useState(null),k=E||T,[A,j]=Q.useState({}),[M,N]=Q.useState({}),[P,F]=Q.useState({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),[I,L]=Q.useState(``),[R,z]=Q.useState(()=>kd()),[B,V]=Q.useState(null),[H,ee]=Q.useState(``),[U,te]=Q.useState(``),[W,ne]=Q.useState(0),G=Q.useRef(0),re=Q.useMemo(()=>[Bd(R),...d.map(e=>({...e,url:Fe(e.url)||e.url}))],[d,R]),ie=Q.useMemo(()=>new Set(Object.keys(A)),[A]),K=Q.useMemo(()=>re.filter(e=>e.id===Cd||De(e,ie)),[re,ie]);Q.useEffect(()=>i(()=>ne(e=>e+1)),[]);let ae=Q.useMemo(()=>Vd(re),[re,W]),oe=Q.useMemo(()=>o().startsWith(`relay:`),[W]),se=Q.useMemo(()=>{let e=p||Cd;return re.find(t=>t.id===e)?.label||a(`desktopHostSwitcher.instance.local`)},[re,p,a]),ce=Q.useCallback(async(e,t)=>{if(O()){C(!0),L(``);try{let n=e.filter(e=>e.id!==Cd);await Ae({hosts:n,defaultHostId:t}),f(n),h(t)}catch(e){L(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToSave`))}finally{C(!1)}}},[a]),le=Q.useCallback(()=>{c(`remote-instances`),s(!0),t(!1)},[t,s,c]),ue=Q.useCallback(async()=>{if(O()){y(!0),L(``);try{let[e,t,n]=await Promise.all([Ie(),bs().catch(()=>({instances:[]})),Rd()]);e.localOrigin&&z(e.localOrigin);let r={};for(let e of t.instances)r[e.id]=!0;f(e.hosts||[]),h(e.defaultHostId??null),j(r),N(n)}catch(e){L(e instanceof Error?e.message:a(`desktopHostSwitcher.error.failedToLoad`)),f([]),h(null),j({}),N({})}finally{y(!1)}}},[a]),de=Q.useCallback(async e=>{if(O()){x(!0);try{let t=await Ad(),n=await Promise.all(e.map(async e=>{let n=async()=>{let t=await Me(e.relay,{clientToken:e.clientToken||null}).catch(()=>({status:`unreachable`,latencyMs:0}));return{status:t.status,latencyMs:t.latencyMs,...t.status===`ok`?{via:`relay`}:{}}};if(e.relay&&!e.apiUrl)return[e.id,await n()];let r=Fe(m()?je(e):e.url);if(!r)return[e.id,{status:`unreachable`,latencyMs:0}];let i=e.id===Cd?t:e.clientToken||``,a=await Ne(r,{clientToken:i||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(Nd(a.status)&&e.relay){let t=await n();if(t.status===`ok`)return[e.id,t]}return[e.id,{status:a.status,latencyMs:a.latencyMs}]})),r={};for(let[e,t]of n)r[e]=t;_(r)}finally{x(!1)}}},[]);Q.useEffect(()=>{if(!e){V(null),ee(``),te(``),D(null),F({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),L(``);return}ue()},[e,ue]),Q.useEffect(()=>{e&&de(K)},[e,K,de]),Q.useEffect(()=>{if(!e||!O())return;let t=!1,n=async()=>{let e=await Rd();t||N(e)};n();let r=window.setInterval(()=>{typeof document<`u`&&document.visibilityState!==`visible`||n()},1500);return()=>{t=!0,window.clearInterval(r)}},[e]);let fe=J(async e=>{let t=e.id===Cd?R:Fe(e.url)||``,n=e.id===Cd?R:Fe(je(e))||``,i=!!e.relay&&!e.apiUrl&&e.id!==Cd;if(!t&&!i)return;if(m()){if(!n&&!e.relay||w)return;let t=e.id===Cd?await Ad():null,i=await Ts({host:e,cachedProbe:g[e.id]||null,...e.id===Cd?{localApiOrigin:n,localClientToken:t}:{}});_(t=>({...t,[e.id]:i.status})),i.ok&&r?.();return}let o=!!A[e.id];if(e.id!==Cd&&o&&O()){let n=M[e.id],i=await os(e.id).then(t=>t.find(t=>t.id===e.id)||null).catch(()=>null);i&&(n=i,N(t=>({...t,[e.id]:i})));let o=Fe(n?.localUrl||e.url||``);if(n?.phase===`ready`&&o){let e=Od(o);r?.(),window.location.assign(e);return}D(e.id);let s=G.current+1;G.current=s,F({open:!0,hostId:e.id,hostLabel:ke(e.label),phase:`master_connecting`,detail:null,error:null,errorCode:null});try{if(await gs(e.id),s!==G.current)return;let n=await zd(e.id,wd,e=>{N(t=>({...t,[e.id]:e})),F(t=>({...t,phase:e.phase,detail:e.detail||null,errorCode:e.errorCode||null}))},()=>s!==G.current);if(s!==G.current)return;let i=Od(Fe(n.localUrl||``)||t);r?.(),window.location.assign(i);return}catch(t){if(s!==G.current)return;let n=t instanceof Error?t.message:String(t);if(n===Td)return;let r=fs(P.errorCode,n);F(e=>({...e,error:n,errorCode:r})),ro.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ke(e.label)}),{description:ds(a(ps(r)),r,n)});return}finally{s===G.current&&D(null)}}if(e.id!==Cd&&O()){D(e.id);let n=await Ne(t,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(()=>({status:`unreachable`,latencyMs:0}));if(_(t=>({...t,[e.id]:{status:n.status,latencyMs:n.latencyMs}})),Nd(n.status)){ro.error(a(`desktopHostSwitcher.toast.instanceUnreachable`,{host:ke(e.label)})),D(null);return}}let s=Od(t);r?.();try{window.location.assign(s)}catch{window.location.href=s}}),pe=Q.useCallback(()=>{V(null),ee(``),te(``)},[]),me=Q.useCallback(e=>{e.stopPropagation()},[]),he=Q.useCallback(async()=>{if(!B)return;if(B===Cd){pe();return}let e=Te(U);if(!e){L(a(`desktopHostSwitcher.error.invalidUrl`));return}let t=e.persistedUrl,n=(H||ke(t)).trim(),r=d.map(e=>e.id===B?{...e,label:n,url:t,apiUrl:t}:e);await ce(r,p),pe(),e.redeemUrl&&window.location.assign(e.redeemUrl)},[pe,d,p,H,U,B,ce,a]),ge=Q.useCallback(async e=>{await ce(d,e===Cd?Cd:e)},[d,ce]),_e=Q.useCallback(e=>{let t=e=>{ro.error(a(`desktopHostSwitcher.error.failedToOpenNewWindow`),{description:e instanceof Error?e.message:String(e)})};if(e.relay&&e.id!==Cd){Ee(e.id).catch(t);return}let n=e.id===Cd?R:je(e);if(!n)return;let r=Od(n);Le(r,{clientToken:e.clientToken||null,requestHeaders:e.requestHeaders||null}).catch(t)},[R,a]),ve=J(async()=>{G.current+=1,D(null),F(e=>({...e,open:!1,hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}));let e=Od(R);if(m()){if(w)return;let e=await Ad();(await Ts({host:Bd(R),localApiOrigin:R,localClientToken:e})).ok&&r?.();return}r?.(),window.location.assign(e)}),ye=Q.useCallback(async()=>{let e=P.hostId||k;G.current+=1,D(null),F({open:!1,hostId:null,hostLabel:``,phase:`idle`,detail:null,error:null,errorCode:null}),!(!e||e===Cd||!O())&&await Us(e).catch(()=>{})},[P.hostId,k]),be=Q.useCallback(()=>{let e=P.hostId;if(!e)return;let t=re.find(t=>t.id===e);t&&fe(t)},[re,fe,P.hostId]),xe=Q.useCallback(async e=>{if(O()){D(e.id);try{await gs(e.id),(await zd(e.id,wd,e=>{N(t=>({...t,[e.id]:e}))})).phase===`ready`&&ro.success(a(`desktopHostSwitcher.toast.sshConnected`,{host:ke(e.label)}))}catch(t){let n=t instanceof Error?t.message:String(t);if(n!==Td){let t=fs(null,n);ro.error(a(`desktopHostSwitcher.toast.sshFailedToConnect`,{host:ke(e.label)}),{description:ds(a(ps(t)),t,n)})}}finally{D(null)}}},[a]);if(!O())return null;let Se=O(),Ce=(0,$.jsxs)($.Fragment,{children:[n?(0,$.jsx)(`div`,{className:`flex-shrink-0 border-b border-[var(--interactive-border)] px-3 py-2`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex items-baseline gap-1.5 typography-ui-label`,children:[(0,$.jsx)(`span`,{className:`font-medium text-foreground`,children:a(`desktopHostSwitcher.header.current`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ke(ae.label)}),(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`•`}),(0,$.jsx)(`span`,{className:`font-medium text-foreground`,children:a(`desktopHostSwitcher.header.default`)}),(0,$.jsx)(`span`,{className:`max-w-[9rem] truncate text-muted-foreground`,children:ke(se)})]}),(0,$.jsx)(`button`,{type:`button`,className:Y(`inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors`,`hover:text-foreground hover:bg-interactive-hover`,`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`),onClick:()=>void de(K),disabled:!Se||v||b,"aria-label":a(`desktopHostSwitcher.actions.refreshInstancesAria`),children:(0,$.jsx)(Z,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)})})]})}):(0,$.jsxs)(lo,{className:`flex-shrink-0`,children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`server`,className:`h-5 w-5`}),a(`desktopHostSwitcher.title`)]}),(0,$.jsx)(ho,{children:a(`desktopHostSwitcher.description`)})]}),!n&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2 flex-shrink-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a(`desktopHostSwitcher.header.currentColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ke(ae.label)}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a(`desktopHostSwitcher.header.currentDefaultColon`)}),(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground truncate`,children:ke(se)})]}),(0,$.jsx)(`div`,{className:`flex items-center gap-1`,children:(0,$.jsxs)(Qt,{type:`button`,size:`sm`,variant:`ghost`,onClick:()=>void de(K),disabled:!Se||v||b,children:[(0,$.jsx)(Z,{name:`refresh`,className:Y(`h-4 w-4`,b&&`animate-spin`)}),a(`desktopHostSwitcher.actions.refresh`)]})})]}),!Se&&(0,$.jsx)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:a(`desktopHostSwitcher.state.limitedOnPage`)})}),(0,$.jsx)(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:(0,$.jsx)(`div`,{className:Y(`space-y-1`,n&&`space-y-1.5 px-3 py-1`),children:v?(0,$.jsx)(`div`,{className:`px-2 py-2 text-muted-foreground text-sm`,children:a(`desktopHostSwitcher.state.loading`)}):K.map(e=>{let t=e.id===Cd,r=!!A[e.id],i=e.id===ae.id,o=(p||Cd)===e.id,s=g[e.id]||null,c=M[e.id]||null,d=Sd({isActive:i,isSsh:r,runtimeIsConnected:l,runtimeConnectionPhase:u,currentTransportIsRelay:oe,probe:s,sshPhase:c?.phase}),f=d.statusKind,m=d.showViaRelay,h=B===e.id,_=t?R:Fe(e.url)||e.url,v=e.id===Cd?a(`desktopHostSwitcher.instance.local`):ke(e.label),y=e.relay&&!e.apiUrl?a(`mobile.connect.relay.badge`):ke(_);return(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 px-2.5 py-2 rounded-md overflow-hidden`,n&&`rounded-xl bg-[var(--surface-muted)] px-3 py-2.5`,n&&i&&`bg-[var(--interactive-selection)]/25`,h?`bg-interactive-hover/20`:`hover:bg-interactive-hover/30`),children:[(0,$.jsxs)(`button`,{type:`button`,className:Y(`flex items-center gap-2 flex-1 min-w-0 text-left`,h&&`pointer-events-none opacity-70`),onClick:()=>void fe(e),disabled:k===e.id,"aria-label":a(`desktopHostSwitcher.actions.switchToAria`,{instance:v}),children:[(0,$.jsx)(`span`,{className:Y(`h-2 w-2 rounded-full flex-shrink-0`,jd(f))}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 space-y-0.5`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`typography-ui-label font-medium truncate text-foreground`,children:v}),i&&(0,$.jsx)(`span`,{className:`typography-micro flex-shrink-0 text-muted-foreground bg-muted px-1 rounded leading-none pb-px border border-border/50`,children:a(`desktopHostSwitcher.header.current`)}),r&&(0,$.jsx)(`span`,{className:`typography-micro flex-shrink-0 px-1 rounded leading-none pb-px text-[var(--status-info)] bg-[var(--status-info)]/10`,children:`SSH`})]}),(0,$.jsxs)(`div`,{className:Y(`typography-micro truncate`,Md(f)),children:[a(r&&!i?Ld(c?.phase):Fd(f)),d.latencyMs==null?``:a(`desktopHostSwitcher.status.ping`,{ms:d.latencyMs}),m?` · ${a(`settings.remoteInstances.clientAuth.state.viaRelay`)}`:``]}),(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground/70 truncate font-mono`,children:y})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-shrink-0`,children:[r&&!t&&(c?.phase===`idle`||!c?.phase?(0,$.jsxs)(Qt,{type:`button`,variant:`outline`,size:`sm`,className:`h-8 px-2.5`,disabled:k===e.id,onClick:t=>{t.stopPropagation(),xe(e)},children:[k===e.id?(0,$.jsx)(Z,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}):(0,$.jsx)(Z,{name:`plug-2`,className:`h-3.5 w-3.5`}),a(`desktopHostSwitcher.actions.connect`)]}):(0,$.jsx)(`div`,{className:`h-8 w-8 opacity-0 pointer-events-none`,"aria-hidden":`true`})),(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,o?`text-primary hover:text-primary/80`:`text-muted-foreground/60 hover:text-primary/80`),onClick:()=>void ge(e.id),"aria-label":a(o?`desktopHostSwitcher.actions.defaultInstanceAria`:`desktopHostSwitcher.actions.setAsDefaultAria`),disabled:S||!o&&Pd(f),children:o?(0,$.jsx)(Z,{name:`star-fill`,className:`h-4 w-4`}):(0,$.jsx)(Z,{name:`star`,className:`h-4 w-4`})})}),(0,$.jsx)(Jo,{sideOffset:6,children:a(o?`desktopHostSwitcher.header.default`:`desktopHostSwitcher.actions.setAsDefault`)})]}),(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,className:Y(`h-8 w-8 rounded-md inline-flex items-center justify-center hover:bg-interactive-hover transition-colors`,Pd(f)?`text-muted-foreground/30 cursor-not-allowed`:`text-muted-foreground/60 hover:text-foreground`),onClick:t=>{t.stopPropagation(),_e(e)},disabled:Pd(f),"aria-label":a(`desktopHostSwitcher.actions.openInNewWindowAria`),children:(0,$.jsx)(Z,{name:`window`,className:`h-4 w-4`})})}),(0,$.jsx)(Jo,{sideOffset:6,children:Pd(f)?a(`desktopHostSwitcher.state.instanceUnreachable`):a(`desktopHostSwitcher.actions.openInNewWindow`)})]})]})]},e.id)})})}),Se&&B&&B!==Cd&&(0,$.jsxs)(`div`,{className:`flex-shrink-0 rounded-lg border border-border/50 bg-muted/20 p-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,$.jsx)(`div`,{className:`typography-ui-label font-medium text-foreground`,children:a(`desktopHostSwitcher.edit.title`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Qt,{type:`button`,variant:`outline`,size:`sm`,onClick:pe,disabled:S,children:a(`desktopHostSwitcher.actions.cancel`)}),(0,$.jsxs)(Qt,{type:`button`,size:`sm`,onClick:()=>void he(),disabled:S,children:[S?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):null,a(`desktopHostSwitcher.actions.save`)]})]})]}),(0,$.jsxs)(`div`,{className:`mt-2 grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[(0,$.jsx)(Ko,{value:H,onChange:e=>ee(e.target.value),onKeyDown:me,placeholder:a(`desktopHostSwitcher.field.labelPlaceholder`),disabled:S}),(0,$.jsx)(Ko,{value:U,onChange:e=>te(e.target.value),onKeyDown:me,placeholder:a(`desktopHostSwitcher.field.urlPlaceholder`),disabled:S})]})]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 border-t border-[var(--interactive-border)]`,children:(0,$.jsxs)(`button`,{type:`button`,className:`w-full flex items-center gap-2 px-2 py-2 text-left text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,onClick:le,children:[(0,$.jsx)(Z,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-ui-label`,children:a(`desktopHostSwitcher.actions.addInstance`)})]})}),I&&(0,$.jsx)(`div`,{className:`flex-shrink-0 typography-meta text-status-error`,children:I})]}),we=(0,$.jsx)(_o,{open:P.open,onOpenChange:e=>{if(!e&&k){ye();return}F(t=>({...t,open:e,...e?{}:{hostId:null,error:null,errorCode:null,detail:null,phase:`idle`}}))},children:(0,$.jsxs)(po,{className:`w-[min(28rem,calc(100vw-2rem))] max-w-none`,children:[(0,$.jsxs)(lo,{children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(`h-4 w-4`,!P.error&&`animate-spin`)}),a(`desktopHostSwitcher.ssh.connectingTo`,{host:P.hostLabel||a(`desktopHostSwitcher.ssh.instanceFallback`)})]}),P.error?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ho,{className:`sr-only`,children:a(is(fs(P.errorCode,P.error)))}),(0,$.jsx)(js,{errorCode:P.errorCode,detail:P.error})]}):(0,$.jsx)(ho,{children:P.detail||a(Ld(P.phase))})]}),P.error?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-2`,children:[(0,$.jsx)(Qt,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{le(),ye()},children:a(`desktopHostSwitcher.sshError.openRemoteSettings`)}),(0,$.jsx)(Qt,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>void ve(),children:a(`desktopHostSwitcher.actions.switchToLocal`)}),(0,$.jsx)(Qt,{type:`button`,size:`sm`,onClick:be,disabled:!P.hostId,children:a(`desktopHostSwitcher.actions.retry`)})]}):null]})});return n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`w-full max-h-[70vh] flex flex-col overflow-hidden gap-2`,children:Ce}),we]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsx)(po,{className:`w-[min(42rem,calc(100vw-2rem))] max-w-none max-h-[70vh] flex flex-col overflow-hidden gap-3`,children:Ce})}),we]})}function Ud(){let e=(0,pd.c)(11),[t,n]=Q.useState(!1),{t:r}=Yt();if(!O())return null;let i,a;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>n(!0),a=(0,$.jsx)(Z,{name:`server`,className:`h-4 w-4`}),e[0]=i,e[1]=a):(i=e[0],a=e[1]);let o;e[2]===r?o=e[3]:(o=r(`desktopHostSwitcher.actions.switchInstance`),e[2]=r,e[3]=o);let s;e[4]===o?s=e[5]:(s=(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`sm`,"data-oc-host-switcher":!0,className:`w-full justify-center`,onClick:i,children:[a,o]}),e[4]=o,e[5]=s);let c;e[6]===t?c=e[7]:(c=(0,$.jsx)(Hd,{open:t,onOpenChange:n}),e[6]=t,e[7]=c);let l;return e[8]!==s||e[9]!==c?(l=(0,$.jsxs)($.Fragment,{children:[s,c]}),e[8]=s,e[9]=c,e[10]=l):l=e[10],l}var Wd=e=>e.shouldUseDesktopShellPasswordLogin?`locked`:`error`,Gd=`/auth/session`,Kd=4,qd=1500,Jd=`openchamber.uiAuth.trustDevice`,Yd=`desktop-local`,Xd=`desktop-local`,Zd=()=>{if(typeof window>`u`)return``;let e=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof e==`string`?e.trim():``},Qd=(e,t)=>{let n=Fe(e),r=Fe(t);if(!n||!r)return!1;try{return new URL(n).origin===new URL(r).origin}catch{return!1}},$d=()=>O(),ef=e=>{let t=e.replace(/^\[|\]$/g,``);return t===`localhost`||t===`127.0.0.1`||t===`::1`},tf=()=>{if(!O())return!1;let e=Zd();if(!e)return!1;let t=d()||(typeof window<`u`?window.location.origin:``);if(Qd(e,t))return!0;try{let e=Fe(t);return!!(e&&ef(new URL(e).hostname))}catch{return!1}},nf=()=>tf()?{clientKind:Yd,dedupeKey:Xd}:{},rf=async()=>await f(Gd,{method:`GET`,credentials:`include`,headers:{Accept:`application/json`}}),af=()=>typeof window>`u`?!1:window.localStorage.getItem(Jd)===`true`,of=async(e,t)=>{let n=$d();return await f(Gd,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({password:e,trustDevice:t,issueClientToken:n,clientLabel:`OpenChamber Desktop`,...nf()})})},sf=async()=>{if(!O())return``;let e=await f(`/api/client-auth/clients`,{method:`POST`,credentials:`include`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:`OpenChamber Desktop`,...nf()})}).catch(()=>null);if(!e?.ok)return``;let t=await e.json().catch(()=>null);return typeof t?.token==`string`?t.token.trim():``},cf=()=>O()&&!tf(),lf=async(e,t)=>{if(!O()||typeof window>`u`)return null;let r=await I(`desktop_remote_password_login`,{url:d(),password:e,trustDevice:t,requestHeaders:n()}).catch(()=>null);if(!r||typeof r!=`object`)return null;let i=r.token,a=r.status;return{token:typeof i==`string`?i.trim():``,...typeof a==`number`?{status:a}:{}}},uf=async(e,t)=>{if(!O()||!t)return;let n=await Ie().catch(()=>null);if(!n)return;if(n.localOrigin&&Qd(n.localOrigin,e)){await Ae({hosts:n.hosts,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted,localClientToken:t}).catch(()=>void 0);return}let r=!1,i=n.hosts.map(n=>!Qd(je(n),e)||n.clientToken===t?n:(r=!0,{...n,clientToken:t}));r&&await Ae({hosts:i,defaultHostId:n.defaultHostId,initialHostChoiceCompleted:n.initialHostChoiceCompleted}).catch(()=>void 0)},df=async e=>{if(!e)return;let r=d(),i=n();await uf(r,e),s({apiBaseUrl:r,clientToken:e,requestHeaders:Object.keys(i).length>0?i:null,relay:t()})},ff=e=>{let t=(0,pd.c)(7),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r={height:`var(--oc-wco-titlebar-height, 0px)`,right:`var(--oc-wco-right-inset, 0px)`},t[0]=r):r=t[0];let i=r,a,o;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(a={fontFamily:`"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif`},o=(0,$.jsx)(`div`,{className:`app-region-drag fixed left-0 top-0 z-20`,style:i,"aria-hidden":!0}),t[1]=a,t[2]=o):(a=t[1],o=t[2]);let s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0 opacity-55`,style:{background:`radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)`}}),t[3]=s):s=t[3];let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=(0,$.jsx)(`div`,{className:`pointer-events-none absolute inset-0`,style:{backgroundColor:`var(--surface-subtle)`,opacity:.22}}),t[4]=c):c=t[4];let l;return t[5]===n?l=t[6]:(l=(0,$.jsxs)(`div`,{className:`relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground`,style:a,children:[o,s,c,(0,$.jsx)(`div`,{className:`app-region-no-drag relative z-10 flex w-full justify-center px-4 py-12 sm:px-6`,children:n})]}),t[5]=n,t[6]=l),l},pf=()=>{let e=(0,pd.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsx)(`div`,{className:`flex min-h-screen items-center justify-center bg-background text-foreground`,children:(0,$.jsx)(Qo,{width:120,height:120})}),e[0]=t):t=e[0],t},mf=e=>{let t=(0,pd.c)(23),{onRetry:n,errorType:r,retryAfter:i,children:a}=e,o=r===void 0?`network`:r,{t:s}=Yt(),c=o===`rate-limit`,l=i?Math.ceil(i/60):1,u;t[0]!==c||t[1]!==s?(u=s(c?`sessionAuth.error.rateLimitTitle`:`sessionAuth.error.networkTitle`),t[0]=c,t[1]=s,t[2]=u):u=t[2];let d;t[3]===u?d=t[4]:(d=(0,$.jsx)(`h1`,{className:`typography-ui-header font-semibold text-destructive`,children:u}),t[3]=u,t[4]=d);let f;t[5]!==c||t[6]!==l||t[7]!==s?(f=c?s(l>1?`sessionAuth.error.rateLimitDescriptionPlural`:`sessionAuth.error.rateLimitDescriptionSingle`,{minutes:l}):s(`sessionAuth.error.networkDescription`),t[5]=c,t[6]=l,t[7]=s,t[8]=f):f=t[8];let p;t[9]===f?p=t[10]:(p=(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground max-w-xs`,children:f}),t[9]=f,t[10]=p);let m;t[11]!==d||t[12]!==p?(m=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[d,p]}),t[11]=d,t[12]=p,t[13]=m):m=t[13];let h;t[14]===s?h=t[15]:(h=s(`sessionAuth.error.retry`),t[14]=s,t[15]=h);let g;t[16]!==n||t[17]!==h?(g=(0,$.jsx)(Qt,{type:`button`,onClick:n,className:`w-full max-w-xs`,children:h}),t[16]=n,t[17]=h,t[18]=g):g=t[18];let _;return t[19]!==a||t[20]!==m||t[21]!==g?(_=(0,$.jsx)(ff,{children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-6 text-center`,children:[m,g,a]})}),t[19]=a,t[20]=m,t[21]=g,t[22]=_):_=t[22],_},hf=({children:e})=>{let{t}=Yt(),n=Q.useMemo(()=>ge(),[]),r=n,a=Q.useMemo(()=>O()&&!n,[n]),[o,s]=Q.useState(()=>r?`authenticated`:`pending`),[c,d]=Q.useState(``),[f,p]=Q.useState(!1),[m,h]=Q.useState(``),[g,_]=Q.useState(void 0),[v,y]=Q.useState(!1),[b,x]=Q.useState(_s),[S,C]=Q.useState(!1),[w,T]=Q.useState(!1),[E,D]=Q.useState(()=>af()),[k,A]=Q.useState(null),[j,M]=Q.useState(r),N=Q.useRef(null),P=Q.useRef(r);Q.useEffect(()=>{typeof window>`u`||window.localStorage.setItem(Jd,E?`true`:`false`)},[E]);let F=Q.useCallback(async()=>{if(r)return _s;try{let e=await es();return x(e),e}catch{return x(_s),_s}},[r]);Q.useEffect(()=>{let e=!1;if(!r)return(async()=>{try{if(!window.isSecureContext||!xo()){e||C(!1);return}e||C(!0)}catch{e||C(!1)}})(),()=>{e=!0}},[r]);let I=Q.useRef(0),L=Q.useRef(null),R=Q.useRef(null),z=Q.useCallback(()=>{L.current!==null&&(window.clearTimeout(L.current),L.current=null)},[]),B=Q.useCallback(()=>{I.current=0,z()},[z]),V=Q.useCallback(()=>I.current>=Kd?!1:(I.current+=1,z(),L.current=window.setTimeout(()=>{L.current=null,R.current?.()},qd*I.current),!0),[z]);Q.useEffect(()=>z,[z]);let H=Q.useCallback(async()=>{if(r){s(`authenticated`);return}s(e=>e===`authenticated`?e:`pending`);try{let[e,t]=await Promise.all([rf(),F()]),n=await e.text();if(e.ok){B(),s(`authenticated`),y(!1),h(``),_(void 0);return}if(e.status===401){let e={};try{e=JSON.parse(n)}catch{e={}}B(),y(e.tunnelLocked===!0),x(t),s(`locked`),_(void 0);return}if(e.status===429){let e={};try{e=JSON.parse(n)}catch{e={}}B(),_(e.retryAfter),y(!1),s(`rate-limited`);return}if(V())return;s(`error`),y(!1)}catch(e){if(console.warn(`Failed to check session status:`,e),Wd({shouldUseDesktopShellPasswordLogin:cf()})===`locked`){s(`locked`),_(void 0),y(!1);return}if(V())return;s(`error`),y(!1)}},[F,B,V,r]);Q.useEffect(()=>{R.current=H},[H]),Q.useEffect(()=>{r||H()},[H,r]),Q.useEffect(()=>{if(o===`pending`||o===`authenticated`||typeof document>`u`)return;let e=document.getElementById(`initial-loading`);if(!e)return;e.classList.add(`fade-out`);let t=window.setTimeout(()=>{e.remove()},300);return()=>{window.clearTimeout(t)}},[o]),Q.useEffect(()=>{if(r)return;let e=yd(e=>{l(e)&&(d(``),h(``),_(void 0),y(!1),B(),M(!1),P.current=!1,s(`pending`),H())}),t=i(t=>e.schedule(t));return()=>{t(),e.cancel()}},[H,B,r]),Q.useEffect(()=>{!r&&o===`locked`&&(P.current=!1,M(!1))},[r,o]),Q.useEffect(()=>{o===`locked`&&N.current&&(N.current.focus(),N.current.select())},[o]),Q.useEffect(()=>{if(!r&&o===`authenticated`&&!P.current){P.current=!0;let e=!1;return _d({runtimeKey:u(),initializeAppearance:he,syncSettings:ce,applyDirectory:md,onError:(e,t)=>{console.error(`[SessionAuthGate] ${e} settings hydration failed:`,t)}},{force:!0}).then(()=>{e||M(!0)}),()=>{e=!0}}},[r,o]);let ee=async e=>{e.preventDefault(),await W(!1)},U=Q.useCallback(async()=>{A(`register`),T(!0);try{await ns()}finally{A(null),T(!1)}await F()},[F]),te=Q.useCallback(()=>{Vs(),A(null),T(!1)},[]),W=Q.useCallback(async e=>{if(!v&&!(!c||f)){w&&te(),p(!0),h(``);try{if(cf()){let e=await lf(c,E);if(e?.token){d(``),y(!1),await df(e.token),s(`authenticated`);return}if(e?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),y(!1),s(`locked`);return}if(e?.status===429){_(void 0),y(!1),s(`rate-limited`);return}}let n=await of(c,E);if(n.ok){let r=await n.json().catch(()=>null),i=$d(),a=``;if(i&&(a=typeof r?.clientToken==`string`&&r.clientToken.trim()?r.clientToken.trim():``,a||=(await lf(c,E))?.token||await sf()),d(``),y(!1),a&&await df(a),e&&S)try{await U(),ro.success(t(`sessionAuth.toast.passkeyAdded`)),s(`authenticated`);return}catch(e){if(rs(e))ro.message(t(`sessionAuth.toast.passkeySetupCanceled`));else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);ro.error(n)}s(`authenticated`);return}s(`authenticated`);return}if(n.status===401){h(t(`sessionAuth.error.incorrectPassword`)),y(!1),s(`locked`);return}if(n.status===429){let e=await n.json().catch(()=>({}));_(e.retryAfter),y(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.unexpectedResponse`)),y(!1),s(`error`)}catch(e){console.warn(`Failed to submit UI password:`,e);let n=cf()?await lf(c,E):null;if(n?.token){d(``),y(!1),await df(n.token),s(`authenticated`);return}if(n?.status===401){h(t(`sessionAuth.error.incorrectPassword`)),y(!1),s(`locked`);return}if(n?.status===429){_(void 0),y(!1),s(`rate-limited`);return}h(t(`sessionAuth.error.networkRetry`)),y(!1),s(`error`)}finally{p(!1)}}},[te,w,f,v,c,U,S,t,E]),ne=Q.useCallback(async()=>{if(!(f||!S)){if(w){te();return}T(!0),A(`auth`),h(``);try{let e=await Ds(E,{issueClientToken:$d(),clientLabel:`OpenChamber Desktop`,...nf()}),t=$d()&&typeof e?.clientToken==`string`&&e.clientToken.trim()?e.clientToken.trim():``;t&&await df(t),d(``),s(`authenticated`)}catch(e){if(rs(e))h(``);else{let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySignInCanceled`);h(n)}}finally{A(null),T(!1)}}},[te,w,f,S,t,E]),G=Q.useCallback(async()=>{if(!(f||v||!S)){if(w){te();return}if(o!==`authenticated`){if(!c){h(t(`sessionAuth.error.enterPasswordForPasskey`));return}await W(!0);return}h(``);try{await U(),ro.success(t(`sessionAuth.toast.passkeyAdded`))}catch(e){if(rs(e)){ro.message(t(`sessionAuth.toast.passkeySetupCanceled`));return}let n=e instanceof Error?e.message:t(`sessionAuth.error.passkeySetupFailed`);ro.error(n)}}},[te,W,w,f,v,c,U,o,S,t]),re=S&&b.enabled,ie=re&&b.hasPasskeys;return o===`pending`||o===`authenticated`&&!j?(0,$.jsx)(pf,{}):o===`error`?(0,$.jsx)(mf,{onRetry:()=>{B(),H()},errorType:`network`,children:a&&(0,$.jsxs)(`div`,{className:`w-full max-w-xs`,children:[(0,$.jsx)(Ud,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})}):o===`rate-limited`?(0,$.jsx)(mf,{onRetry:()=>void H(),errorType:`rate-limit`,retryAfter:g}):o===`locked`?(0,$.jsx)(ff,{children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-6 w-full max-w-xs`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-xl font-semibold text-foreground`,children:t(v?`sessionAuth.locked.tunnelTitle`:`sessionAuth.locked.unlockTitle`)}),(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground`,children:t(v?`sessionAuth.locked.tunnelDescription`:`sessionAuth.locked.passwordDescription`)})]}),!v&&(0,$.jsxs)(`form`,{onSubmit:ee,className:`w-full space-y-2`,children:[ie&&(0,$.jsxs)(Qt,{type:`button`,variant:`outline`,className:`w-full`,onClick:()=>void ne(),disabled:f||w&&k!==`auth`,children:[w?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(Z,{name:`lock-unlock`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{children:t(w&&k===`auth`?`sessionAuth.actions.cancelPasskey`:`sessionAuth.actions.usePasskey`)})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1`,children:[(0,$.jsx)(Z,{name:`lock`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60`}),(0,$.jsx)(Ko,{id:`openchamber-ui-password`,ref:N,type:`password`,autoComplete:`current-password`,placeholder:t(`sessionAuth.password.placeholder`),value:c,onChange:e=>{d(e.target.value),m&&h(``)},className:`pl-10`,"aria-invalid":!!m||void 0,"aria-describedby":m?`oc-ui-auth-error`:void 0,disabled:f})]}),(0,$.jsx)(Qt,{type:`submit`,size:`icon`,disabled:!c||f,"aria-label":t(f?`sessionAuth.actions.unlockingAria`:`sessionAuth.actions.unlockAria`),children:f?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(Z,{name:`lock-unlock`,className:`h-4 w-4`})})]}),re?(0,$.jsxs)(`div`,{className:`flex items-center justify-between pt-1`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2 text-center typography-micro text-muted-foreground`,children:[(0,$.jsx)(Oo,{checked:E,onChange:D,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`sm`,className:`text-muted-foreground hover:text-foreground`,onClick:()=>void G(),disabled:f,children:t(w&&k===`register`?`sessionAuth.actions.cancelPasskeySetup`:`sessionAuth.actions.addPasskey`)})]}):(0,$.jsxs)(`label`,{className:`flex items-center justify-center gap-2 pt-1 text-center typography-micro text-muted-foreground`,children:[(0,$.jsx)(Oo,{checked:E,onChange:D,disabled:f,ariaLabel:t(`sessionAuth.actions.trustDeviceAria`),className:`size-4`,iconClassName:`size-4`}),(0,$.jsx)(`span`,{children:t(`sessionAuth.actions.trustDevice`)})]}),m&&(0,$.jsx)(`p`,{id:`oc-ui-auth-error`,className:`typography-meta text-destructive`,children:m})]}),a&&(0,$.jsxs)(`div`,{className:`w-full`,children:[(0,$.jsx)(Ud,{}),(0,$.jsx)(`p`,{className:`mt-1 text-center typography-micro text-muted-foreground`,children:t(`sessionAuth.locked.hostSwitcherHint`)})]})]})}):(0,$.jsx)($.Fragment,{children:e})},gf=e=>{let t=(0,pd.c)(14),{children:n}=e,r=q(_f),i=q(vf),a=q(yf),o=q(bf),s=q(xf),{deviceType:c,hasTouchInput:l}=qs(),u;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(u=typeof document<`u`&&St(),t[0]=u):u=t[0];let d=u,f;t[1]!==s||t[2]!==a?(f=()=>{a(),s()},t[1]=s,t[2]=a,t[3]=f):f=t[3];let p;t[4]!==s||t[5]!==a||t[6]!==i||t[7]!==c||t[8]!==r||t[9]!==l||t[10]!==o?(p=[r,i,a,o,s,c,l,d],t[4]=s,t[5]=a,t[6]=i,t[7]=c,t[8]=r,t[9]=l,t[10]=o,t[11]=p):p=t[11],Q.useLayoutEffect(f,p);let m;return t[12]===n?m=t[13]:(m=(0,$.jsx)($.Fragment,{children:n}),t[12]=n,t[13]=m),m};function _f(e){return e.fontSize}function vf(e){return e.codeFontSize}function yf(e){return e.applyTypography}function bf(e){return e.padding}function xf(e){return e.applyPadding}var Sf=e(Ye(),1),Cf=e=>{if(!e||typeof e!=`string`)return null;let t=e.trim();if(!t.startsWith(`#`))return null;let n=t.slice(1);if((n.length===3||n.length===4)&&(n=n.split(``).map(e=>e+e).join(``)),n.length===8&&(n=n.slice(0,6)),n.length!==6)return null;let r=Number.parseInt(n,16);return Number.isNaN(r)?null:`${r>>16&255} ${r>>8&255} ${r&255}`},wf=class{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(e){let t=[];return t.push(...this.generateTailwindVariables(e)),t.push(...this.generatePrimaryColors(e.colors.primary)),t.push(...this.generateSurfaceColors(e.colors.surface)),t.push(...this.generateInteractiveColors(e.colors.interactive)),t.push(...this.generateStatusColors(e.colors.status)),t.push(...this.generatePullRequestColors(e)),t.push(...this.generateSyntaxColors(e.colors.syntax)),t.push(...this.generateComponentColors(e.colors,e)),t.push(...this.generateTypographyVariables()),e.config&&t.push(...this.generateConfigVariables(e.config)),t.join(`
|
|
3
3
|
`)}generateTailwindVariables(e){let t=[];t.push(` --background: ${e.colors.surface.background} !important;`),t.push(` --foreground: ${e.colors.surface.foreground} !important;`),t.push(` --muted: ${e.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${e.colors.surface.mutedForeground} !important;`),t.push(` --card: ${e.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${e.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${e.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${e.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${e.colors.interactive.border} !important;`),t.push(` --input: ${e.colors.interactive.border} !important;`),t.push(` --primary: ${e.colors.primary.base} !important;`),t.push(` --primary-foreground: ${e.colors.primary.foreground} !important;`),t.push(` --secondary: ${e.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${e.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${e.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${e.colors.surface.foreground} !important;`),t.push(` --destructive: ${e.colors.status.error} !important;`),t.push(` --destructive-foreground: ${e.colors.status.errorForeground} !important;`),t.push(` --ring: ${e.colors.interactive.focusRing} !important;`);let n=Cf(e.colors.surface.muted),r=Cf(e.colors.surface.subtle),i=Cf(e.colors.interactive.border);t.push(` --sidebar-base: ${e.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(` --sidebar: var(--sidebar-base) !important;`),t.push(` --sidebar-foreground: ${e.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${e.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${e.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${e.colors.surface.subtle} !important;`),r&&t.push(` --sidebar-accent-base-rgb: ${r} !important;`),t.push(` --sidebar-accent: var(--sidebar-accent-base) !important;`),t.push(` --sidebar-accent-foreground: ${e.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${e.colors.interactive.border} !important;`),i&&t.push(` --sidebar-border-rgb: ${i} !important;`),t.push(` --sidebar-ring: ${e.colors.interactive.focusRing} !important;`);let a=e.metadata.variant===`dark`,o=a?.15:.5,s=a?.1:.3,c=a?.42:.52;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${o}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${s}) !important;`),t.push(` --sidebar-vibrancy-overlay: rgb(${n} / ${c}) !important;`);else{let n=e.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(n,o)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(n,s)} !important;`),t.push(` --sidebar-vibrancy-overlay: ${this.opacity(n,c)} !important;`)}return e.colors.charts?.series&&Array.isArray(e.colors.charts.series)&&e.colors.charts.series.forEach((e,n)=>{t.push(` --chart-${n+1}: ${e};`)}),e.colors.loading?(t.push(` --loading-spinner: ${e.colors.loading.spinner||e.colors.primary.base};`),t.push(` --loading-spinner-track: ${e.colors.loading.spinnerTrack||e.colors.surface.muted};`)):(t.push(` --loading-spinner: ${e.colors.primary.base};`),t.push(` --loading-spinner-track: ${e.colors.surface.muted};`)),t}apply(e){let t=this.generate(e),n=document.createElement(`style`);n.id=`opencode-theme-variables`;let r=``;e.metadata.variant===`dark`?(r=`:root {\n${t}\n}\n\n.dark {\n${t}\n}`,document.documentElement.classList.add(`dark`),document.documentElement.classList.remove(`light`)):(r=`:root {\n${t}\n}\n\n:root:not(.dark) {\n${t}\n}`,document.documentElement.classList.remove(`dark`),document.documentElement.classList.add(`light`)),n.textContent=r;let i=document.getElementById(`opencode-theme-variables`);i&&i.remove(),document.head.appendChild(n),document.documentElement.setAttribute(`data-theme`,e.metadata.variant);let a=typeof window<`u`&&window.__OPENCHAMBER_ELECTRON__?.runtime===`electron`&&window.__OPENCHAMBER_ELECTRON__?.macVibrancy===!0;document.documentElement.toggleAttribute(`data-oc-vibrancy`,a),a&&document.documentElement.toggleAttribute(`data-oc-vibrancy-ready`,!0)}generatePrimaryColors(e){let t=[];return t.push(` --primary-base: ${e.base};`),t.push(` --primary-hover: ${e.hover||this.darken(e.base,10)};`),t.push(` --primary-active: ${e.active||this.darken(e.base,20)};`),t.push(` --primary-foreground: ${e.foreground||`#ffffff`};`),t.push(` --primary-muted: ${e.muted||this.opacity(e.base,.5)};`),t.push(` --primary-emphasis: ${e.emphasis||this.lighten(e.base,10)};`),t}generateSurfaceColors(e){let t=[];return t.push(` --surface-background: ${e.background};`),t.push(` --surface-foreground: ${e.foreground};`),t.push(` --surface-muted: ${e.muted};`),t.push(` --surface-muted-foreground: ${e.mutedForeground};`),t.push(` --surface-elevated: ${e.elevated};`),t.push(` --surface-elevated-foreground: ${e.elevatedForeground};`),t.push(` --surface-overlay: ${e.overlay};`),t.push(` --surface-subtle: ${e.subtle};`),t}generateInteractiveColors(e){let t=[];return t.push(` --interactive-border: ${e.border};`),t.push(` --interactive-border-hover: ${e.borderHover};`),t.push(` --interactive-border-focus: ${e.borderFocus};`),t.push(` --interactive-selection: ${e.selection};`),t.push(` --interactive-selection-foreground: ${e.selectionForeground};`),t.push(` --interactive-focus: ${e.focus};`),t.push(` --interactive-focus-ring: ${e.focusRing};`),t.push(` --interactive-cursor: ${e.cursor};`),t.push(` --interactive-hover: ${e.hover};`),t.push(` --interactive-active: ${e.active};`),t}generateStatusColors(e){let t=[];return t.push(` --status-error: ${e.error};`),t.push(` --status-error-foreground: ${e.errorForeground};`),t.push(` --status-error-background: ${e.errorBackground};`),t.push(` --status-error-border: ${e.errorBorder};`),t.push(` --status-warning: ${e.warning};`),t.push(` --status-warning-foreground: ${e.warningForeground};`),t.push(` --status-warning-background: ${e.warningBackground};`),t.push(` --status-warning-border: ${e.warningBorder};`),t.push(` --status-success: ${e.success};`),t.push(` --status-success-foreground: ${e.successForeground};`),t.push(` --status-success-background: ${e.successBackground};`),t.push(` --status-success-border: ${e.successBorder};`),t.push(` --status-info: ${e.info};`),t.push(` --status-info-foreground: ${e.infoForeground};`),t.push(` --status-info-background: ${e.infoBackground};`),t.push(` --status-info-border: ${e.infoBorder};`),t}generatePullRequestColors(e){let t=[],n=e.colors.pr;return t.push(` --pr-open: ${n?.open||e.colors.status.success};`),t.push(` --pr-draft: ${n?.draft||e.colors.surface.mutedForeground};`),t.push(` --pr-blocked: ${n?.blocked||e.colors.status.warning};`),t.push(` --pr-merged: ${n?.merged||(e.metadata.variant===`dark`?`#8957e5`:`#8250df`)};`),t.push(` --pr-closed: ${n?.closed||e.colors.status.error};`),t}generateSyntaxColors(e){let t=[];t.push(` --syntax-background: ${e.base.background};`),t.push(` --syntax-foreground: ${e.base.foreground};`),t.push(` --syntax-comment: ${e.base.comment};`),t.push(` --syntax-keyword: ${e.base.keyword};`),t.push(` --syntax-string: ${e.base.string};`),t.push(` --syntax-number: ${e.base.number};`),t.push(` --syntax-function: ${e.base.function};`),t.push(` --syntax-variable: ${e.base.variable};`),t.push(` --syntax-type: ${e.base.type};`),t.push(` --syntax-operator: ${e.base.operator};`);let n=this.generateSyntaxTokens(e);for(let[e,r]of Object.entries(n))t.push(` --syntax-${this.kebabCase(e)}: ${r};`);return t}generateSyntaxTokens(e){let t=e.base,n=e.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(e,t){let n=[];return e.markdown?n.push(...this.generateMarkdownColors(e.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),e.chat?n.push(...this.generateChatColors(e.chat,t)):n.push(...this.generateDefaultChatColors(t)),e.tools?n.push(...this.generateToolColors(e.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(e,t){let n=[],r=t.colors.primary.base,i=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${e.heading1||r};`),n.push(` --markdown-heading2: ${e.heading2||this.opacity(r,.9)};`),n.push(` --markdown-heading3: ${e.heading3||this.opacity(r,.8)};`),n.push(` --markdown-heading4: ${e.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${e.link||r};`),n.push(` --markdown-link-hover: ${e.linkHover||t.colors.primary.hover||this.darken(r,10)};`),n.push(` --markdown-inline-code: ${e.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${e.inlineCodeBackground||i};`),n.push(` --markdown-blockquote: ${e.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${e.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r};`),n.push(` --markdown-bold: ${e.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${e.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${e.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${e.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(e){let t=[],n=e.colors.primary.base,r=e.colors.chat?.background||e.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${e.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${e.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${e.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${r};`),t.push(` --markdown-blockquote: ${e.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${e.colors.interactive.border};`),t.push(` --markdown-list-marker: ${n};`),t.push(` --markdown-bold: ${e.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(e.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${e.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${e.colors.interactive.border};`),t}generateChatColors(e,t){let n=[],r=e.background||t.colors.surface.background,i=e.composerSkill||this.getDefaultComposerSkillColor(t);return n.push(` --chat-background: ${r};`),n.push(` --chat-user-message: ${e.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${e.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${e.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${e.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${e.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${e.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${e.typing||t.colors.surface.mutedForeground};`),n.push(` --chat-composer-skill: ${i};`),n}generateDefaultChatColors(e){let t=[];return t.push(` --chat-background: ${e.colors.surface.background};`),t.push(` --chat-user-message: ${e.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${e.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${e.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${e.colors.surface.muted};`),t.push(` --chat-timestamp: ${e.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${e.colors.interactive.border};`),t.push(` --chat-typing: ${e.colors.surface.mutedForeground};`),t.push(` --chat-composer-skill: ${this.getDefaultComposerSkillColor(e)};`),t}getDefaultComposerSkillColor(e){return e.metadata.variant===`dark`?this.lighten(e.colors.status.warning,25):e.colors.status.warning}generateToolColors(e,t){let n=[];return n.push(` --tools-background: ${e?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${e?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${e?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${e?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${e?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${e?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),e?.edit?(n.push(` --tools-edit-added: ${e.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${e.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${e.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${e.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${e.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${e.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${e.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(e){let t=[];return t.push(` --tools-background: ${this.opacity(e.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(e.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(e.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${e.colors.surface.mutedForeground};`),t.push(` --tools-title: ${e.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(e.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${e.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(e.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${e.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(e.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${e.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(e.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(e.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(e){let t=[];return e?(e.fonts&&(e.fonts.sans&&(t.push(` --font-sans: ${e.fonts.sans};`),t.push(` --font-family-sans: ${e.fonts.sans};`)),e.fonts.mono&&(t.push(` --font-mono: ${e.fonts.mono};`),t.push(` --font-family-mono: ${e.fonts.mono};`)),e.fonts.heading&&t.push(` --font-heading: ${e.fonts.heading};`)),e.transitions&&(e.transitions.fast&&t.push(` --transition-fast: ${e.transitions.fast};`),e.transitions.normal&&t.push(` --transition-normal: ${e.transitions.normal};`),e.transitions.slow&&t.push(` --transition-slow: ${e.transitions.slow};`)),t):t}generateTypographyVariables(){let e=[],t=ge()?yt:bt;return e.push(` /* Semantic Typography Variables */`),e.push(` --ui-regular-font-weight: 400;`),e.push(` /* Markdown content - all markdown elements use same size */`),e.push(` --text-markdown: ${t.markdown};`),e.push(` /* Code content - all code elements use same size */`),e.push(` --text-code: ${t.code};`),e.push(` /* UI headers - dialog titles, panel headers */`),e.push(` --text-ui-header: ${t.uiHeader};`),e.push(` /* UI labels - buttons, menus, navigation */`),e.push(` --text-ui-label: ${t.uiLabel};`),e.push(` /* Metadata - timestamps, status, helper text */`),e.push(` --text-meta: ${t.meta};`),e.push(` /* Micro text - badges, shortcuts, indicators */`),e.push(` --text-micro: ${t.micro};`),e.push(` /* Heading line height and letter spacing */`),e.push(` --h1-line-height: 1.25rem;`),e.push(` --h2-line-height: 1.25rem;`),e.push(` --h3-line-height: 1.5rem;`),e.push(` --h4-line-height: 1.5rem;`),e.push(` --h5-line-height: 1.5rem;`),e.push(` --h6-line-height: 1.5rem;`),e.push(` --h1-letter-spacing: -0.025em;`),e.push(` --h2-letter-spacing: -0.02em;`),e.push(` --h3-letter-spacing: -0.015em;`),e.push(` --h4-letter-spacing: -0.01em;`),e.push(` --h5-letter-spacing: 0;`),e.push(` --h6-letter-spacing: 0.01em;`),e.push(` /* UI element line height and letter spacing */`),e.push(` --ui-button-line-height: 1.375rem;`),e.push(` --ui-button-letter-spacing: 0.02em;`),e.push(` --ui-button-font-weight: 500;`),e.push(` --ui-label-line-height: 1rem;`),e.push(` --ui-label-letter-spacing: 0.03em;`),e.push(` --ui-label-font-weight: 500;`),e.push(` --ui-caption-line-height: 1rem;`),e.push(` --ui-caption-letter-spacing: 0.025em;`),e.push(` --ui-caption-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` /* Markdown line height and letter spacing */`),e.push(` --markdown-body-line-height: 1.625;`),e.push(` --markdown-body-letter-spacing: 0;`),e.push(` --markdown-body-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-h1-line-height: 1.25rem;`),e.push(` --markdown-h1-letter-spacing: -0.025em;`),e.push(` --markdown-h2-line-height: 1.25rem;`),e.push(` --markdown-h2-letter-spacing: -0.02em;`),e.push(` --markdown-h3-line-height: 1.5rem;`),e.push(` --markdown-h3-letter-spacing: -0.015em;`),e.push(` --markdown-h4-line-height: 1.5rem;`),e.push(` --markdown-h4-letter-spacing: -0.01em;`),e.push(` --markdown-h5-line-height: 1.5rem;`),e.push(` --markdown-h5-letter-spacing: 0;`),e.push(` --markdown-h6-line-height: 1.5rem;`),e.push(` --markdown-h6-letter-spacing: 0.01em;`),e.push(` --markdown-list-line-height: 1.625;`),e.push(` --markdown-code-block-line-height: 1rem;`),e.push(` --ui-button-small-line-height: 1.25rem;`),e.push(` --ui-button-small-letter-spacing: 0.02em;`),e.push(` --ui-button-small-font-weight: 500;`),e.push(` --markdown-body-small-line-height: 1.5;`),e.push(` --markdown-body-small-letter-spacing: 0;`),e.push(` --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --ui-button-large-line-height: 1.5rem;`),e.push(` --ui-button-large-letter-spacing: 0.02em;`),e.push(` --ui-button-large-font-weight: 500;`),e.push(` --markdown-body-large-line-height: 1.625;`),e.push(` --markdown-body-large-letter-spacing: 0;`),e.push(` --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` /* Code line height and letter spacing */`),e.push(` --code-inline-line-height: 1rem;`),e.push(` --code-inline-letter-spacing: 0;`),e.push(` --code-inline-font-weight: 400;`),e.push(` --code-block-line-height: 1.4rem;`),e.push(` --code-block-letter-spacing: 0;`),e.push(` --code-block-font-weight: 400;`),e.push(` --code-line-numbers-line-height: 1.25rem;`),e.push(` --code-line-numbers-letter-spacing: 0;`),e.push(` --code-line-numbers-font-weight: 400;`),e.push(` /* Additional UI element line height and letter spacing */`),e.push(` --ui-badge-line-height: 1rem;`),e.push(` --ui-badge-letter-spacing: 0.025em;`),e.push(` --ui-badge-font-weight: 500;`),e.push(` --ui-tooltip-line-height: 1rem;`),e.push(` --ui-tooltip-letter-spacing: 0.025em;`),e.push(` --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --ui-input-line-height: 1.375rem;`),e.push(` --ui-input-letter-spacing: 0.02em;`),e.push(` --ui-input-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --ui-helper-text-line-height: 1rem;`),e.push(` --ui-helper-text-letter-spacing: 0.025em;`),e.push(` --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` /* Additional markdown line height and letter spacing */`),e.push(` --markdown-blockquote-line-height: 1.625;`),e.push(` --markdown-blockquote-letter-spacing: 0;`),e.push(` --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-list-letter-spacing: 0;`),e.push(` --markdown-list-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-link-line-height: 1.625;`),e.push(` --markdown-link-letter-spacing: 0;`),e.push(` --markdown-link-font-weight: var(--ui-regular-font-weight, 400);`),e.push(` --markdown-code-line-height: 1.35;`),e.push(` --markdown-code-letter-spacing: 0;`),e.push(` --markdown-code-font-weight: 400;`),e.push(` --markdown-code-block-letter-spacing: 0;`),e.push(` --markdown-code-block-font-weight: 400;`),e}initializeInheritanceMap(){this.inheritanceMap.set(`header.background`,`surface.background`),this.inheritanceMap.set(`header.foreground`,`surface.foreground`),this.inheritanceMap.set(`header.logoTint`,`primary.base`),this.inheritanceMap.set(`header.divider`,`interactive.border`),this.inheritanceMap.set(`sidebar.background`,`surface.muted`),this.inheritanceMap.set(`sidebar.foreground`,`surface.mutedForeground`),this.inheritanceMap.set(`sidebar.hover`,`interactive.hover`),this.inheritanceMap.set(`sidebar.active`,`primary.base`),this.inheritanceMap.set(`sidebar.activeForeground`,`primary.foreground`)}opacity(e,t){return e.startsWith(`#`)?`${e}${Math.round(t*255).toString(16).padStart(2,`0`)}`:e.startsWith(`rgb`)?e.replace(`rgb`,`rgba`).replace(`)`,`, ${t})`):e}removeTransparency(e){return e.startsWith(`#`)?e.length===9?e.slice(0,7):e.length===5?e.slice(0,4):e:e.startsWith(`rgba`)?e.replace(`rgba`,`rgb`).replace(/,\s*[\d.]+\)$/,`)`):e}addTransparency(e,t){if(e.startsWith(`#`)){let n=e.slice(1);if(n.length===3)return`rgba(${parseInt(n[0]+n[0],16)}, ${parseInt(n[1]+n[1],16)}, ${parseInt(n[2]+n[2],16)}, ${t})`;if(n.length===6)return`rgba(${parseInt(n.slice(0,2),16)}, ${parseInt(n.slice(2,4),16)}, ${parseInt(n.slice(4,6),16)}, ${t})`}return e.startsWith(`rgb`)?e.replace(`rgb`,`rgba`).replace(`)`,`, ${t})`):e}darken(e,t){if(e.startsWith(`#`)){let n=parseInt(e.slice(1),16),r=Math.round(2.55*t),i=(n>>16)-r,a=(n>>8&255)-r,o=(n&255)-r;return`#`+(16777216+(i<255?i<0?0:i:255)*65536+(a<255?a<0?0:a:255)*256+(o<255?o<0?0:o:255)).toString(16).slice(1)}return e}lighten(e,t){if(e.startsWith(`#`)){let n=parseInt(e.slice(1),16),r=Math.round(2.55*t),i=(n>>16)+r,a=(n>>8&255)+r,o=(n&255)+r;return`#`+(16777216+(i<255?i<0?0:i:255)*65536+(a<255?a<0?0:a:255)*256+(o<255?o<0?0:o:255)).toString(16).slice(1)}return e}adjustHue(e,t){return this.lighten(e,t/10)}emphasize(e){return this.lighten(e,15)}kebabCase(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}},Tf=`openchamber:close-embedded-session-chat`,Ef=`openchamber:embedded-visibility`,Df=`openchamber:embedded-visibility-request`,Of=e=>new URLSearchParams(e).get(`ocPanel`)===`session-chat`,kf=(e,t,n)=>JSON.stringify({sessionID:e,directory:t||``,readOnly:n===!0}),Af=(e,t,n,r)=>{if(typeof window>`u`)return``;let i=new URL(window.location.pathname,window.location.origin);return i.searchParams.set(`ocPanel`,`session-chat`),i.searchParams.set(`surface`,`desktop`),i.searchParams.set(`sessionId`,e),n?i.searchParams.set(`readOnly`,`1`):i.searchParams.delete(`readOnly`),t&&t.trim().length>0?i.searchParams.set(`directory`,t):i.searchParams.delete(`directory`),i.searchParams.set(`themeMode`,r.mode),i.searchParams.set(`lightThemeId`,r.lightThemeId),i.searchParams.set(`darkThemeId`,r.darkThemeId),i.searchParams.set(`themeVariant`,r.currentTheme.metadata.variant===`dark`?`dark`:`light`),i.searchParams.set(`currentTheme`,JSON.stringify(r.currentTheme)),i.hash=``,i.toString()},jf=(e,t,n,r,i,a)=>{let o=kf(n,r,i),s=e.get(t);if(s?.signature===o)return s.src;let c=Af(n,r,i,a);return e.set(t,{signature:o,src:c}),c},Mf=null,Nf=()=>{if(Mf!==null)return Mf;if(typeof window>`u`)return Mf=!1,!1;try{return Mf=new URLSearchParams(window.location.search).get(`ocPanel`)===`session-chat`,Mf}catch{return Mf=!1,!1}},Pf=()=>{if(!Nf())return null;try{let e=new URLSearchParams(window.location.search).get(`sessionId`);return e&&e.trim().length>0?e.trim():null}catch{return null}},Ff=()=>Nf()?new URLSearchParams(window.location.search):null,If=()=>typeof window>`u`||window.matchMedia(`(prefers-color-scheme: dark)`).matches,Lf=()=>{let e=Ff()?.get(`themeVariant`);return e===`dark`||e===`light`?e===`dark`:If()},Rf=(e,t)=>t.reduce((e,t)=>e&&typeof e==`object`?e[t]:void 0,e),zf=e=>typeof e==`string`&&e.trim().length>0,Bf=e=>{if(!e||typeof e!=`object`)return!1;for(let t of[[`metadata`,`id`],[`metadata`,`name`],[`metadata`,`variant`],[`colors`,`primary`,`base`],[`colors`,`primary`,`foreground`],[`colors`,`surface`,`background`],[`colors`,`surface`,`foreground`],[`colors`,`surface`,`muted`],[`colors`,`surface`,`mutedForeground`],[`colors`,`surface`,`elevated`],[`colors`,`surface`,`elevatedForeground`],[`colors`,`surface`,`subtle`],[`colors`,`interactive`,`border`],[`colors`,`interactive`,`selection`],[`colors`,`interactive`,`selectionForeground`],[`colors`,`interactive`,`focusRing`],[`colors`,`interactive`,`hover`],[`colors`,`status`,`error`],[`colors`,`status`,`errorForeground`],[`colors`,`status`,`errorBackground`],[`colors`,`status`,`errorBorder`],[`colors`,`status`,`warning`],[`colors`,`status`,`warningForeground`],[`colors`,`status`,`warningBackground`],[`colors`,`status`,`warningBorder`],[`colors`,`status`,`success`],[`colors`,`status`,`successForeground`],[`colors`,`status`,`successBackground`],[`colors`,`status`,`successBorder`],[`colors`,`status`,`info`],[`colors`,`status`,`infoForeground`],[`colors`,`status`,`infoBackground`],[`colors`,`status`,`infoBorder`],[`colors`,`syntax`,`base`,`background`],[`colors`,`syntax`,`base`,`foreground`],[`colors`,`syntax`,`base`,`keyword`],[`colors`,`syntax`,`base`,`string`],[`colors`,`syntax`,`base`,`number`],[`colors`,`syntax`,`base`,`function`],[`colors`,`syntax`,`base`,`variable`],[`colors`,`syntax`,`base`,`type`],[`colors`,`syntax`,`base`,`comment`],[`colors`,`syntax`,`base`,`operator`],[`colors`,`syntax`,`highlights`,`diffAdded`],[`colors`,`syntax`,`highlights`,`diffRemoved`],[`colors`,`syntax`,`highlights`,`lineNumber`]])if(!zf(Rf(e,t)))return!1;let t=Rf(e,[`metadata`,`variant`]);return t===`light`||t===`dark`},Vf=e=>Bf(e.currentTheme)?e.currentTheme:null,Hf=e=>Vf(e)?.metadata.variant??null,Uf=ec,Wf=Ys,Gf=()=>{let e=Ff()?.get(`currentTheme`);if(!e)return null;try{let t=JSON.parse(e);return Bf(t)?t:null}catch{return null}},Kf=e=>nc(e===`dark`),qf=typeof window<`u`?Q.useLayoutEffect:Q.useEffect,Jf=()=>{if(typeof document>`u`)return;let e=document.documentElement;e.classList.add(`oc-theme-switching`);let t=window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>{e.classList.remove(`oc-theme-switching`)})});return()=>{window.cancelAnimationFrame(t),e.classList.remove(`oc-theme-switching`)}},Yf=e=>{let t=Uf,n=Wf,r=`system`;if(typeof window<`u`){let e=Ff(),i=e?.get(`themeMode`),a=e?.get(`lightThemeId`),o=e?.get(`darkThemeId`),s=G(`themeMode`),c=G(`lightThemeId`),l=G(`darkThemeId`),u=G(`useSystemTheme`),d=G(`selectedThemeId`),f=G(`selectedThemeVariant`);if(i===`light`||i===`dark`||i===`system`)r=i;else if(s===`light`||s===`dark`||s===`system`)r=s;else if(u!==null){if(u===`true`)r=`system`;else if(d){let e=Xs(d);e&&(r=e.metadata.variant===`dark`?`dark`:`light`,e.metadata.variant===`dark`?n=e.metadata.id:t=e.metadata.id)}}else(f===`light`||f===`dark`)&&(r=f);typeof a==`string`&&a.trim().length>0?t=a.trim():typeof c==`string`&&c.trim().length>0&&(t=c.trim()),typeof o==`string`&&o.trim().length>0?n=o.trim():typeof l==`string`&&l.trim().length>0&&(n=l.trim())}if(e){let r=Xs(e);r&&(r.metadata.variant===`light`?t=r.metadata.id:n=r.metadata.id)}return{themeMode:r,lightThemeId:t,darkThemeId:n}};function Xf({children:e,defaultThemeId:t}){let n=(0,Q.useMemo)(()=>new wf,[]),[r,a]=(0,Q.useState)(()=>Yf(t)),[o,s]=(0,Q.useState)(!1),[c,u]=(0,Q.useState)(()=>Lf()),[d,p]=(0,Q.useState)([]),[m]=(0,Q.useState)(()=>Gf()),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(()=>typeof window>`u`||!ge()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),x=(0,Q.useMemo)(()=>ge(),[]),S=(0,Q.useMemo)(()=>R(),[]),C=(0,Q.useMemo)(()=>O(),[]),w=(0,Q.useMemo)(()=>typeof window>`u`?!1:Ff()!==null,[]),T=(0,Q.useMemo)(()=>{let e=[],t=new Set,n=n=>{let r=n.metadata.id;t.has(r)||(t.add(r),e.push(n))};return x&&y&&n(y),h&&n(h),m&&n(m),d.forEach(n),Qs.forEach(n),e},[d,m,h,x,y]),E=(0,Q.useMemo)(()=>e=>T.find(t=>t.metadata.id===e),[T]),D=(0,Q.useMemo)(()=>(e,t)=>{let n=E(e);return n&&n.metadata.variant===t?n:T.find(e=>e.metadata.variant===t)??Kf(t)},[T,E]),k=(0,Q.useMemo)(()=>x&&y?y:r.themeMode===`light`?D(r.lightThemeId,`light`):r.themeMode===`dark`||c?D(r.darkThemeId,`dark`):D(r.lightThemeId,`light`),[D,x,r,c,y]),A=J(async()=>{if(!(typeof window>`u`||x)){v(!0);try{let e=await f(`/api/config/themes`,{method:`GET`,credentials:S?`omit`:`include`,headers:{Accept:`application/json`}});if(e.status===401||!e.ok)return;let t=await e.json(),n=(Array.isArray(t?.themes)?t.themes:[]).filter(Bf);p(n)}catch{}finally{v(!1)}}});(0,Q.useEffect)(()=>{A()},[A]),(0,Q.useEffect)(()=>{if(!x)return;let e=e=>{b(e)},t=t=>{let n=t.detail;n?.theme&&e(n.theme)},n=window.__OPENCHAMBER_VSCODE_THEME__;return n&&e(n),window.addEventListener(`openchamber:vscode-theme`,t),()=>window.removeEventListener(`openchamber:vscode-theme`,t)},[x]);let j=J(e=>{if(typeof document>`u`)return;let t=document.documentElement.hasAttribute(`data-oc-vibrancy`)||window.__OPENCHAMBER_ELECTRON__?.macVibrancy===!0?`transparent`:e.colors.surface.background;document.body.style.backgroundColor=t;let n=document.querySelector(`meta[name="theme-color"]`);n||(n=document.createElement(`meta`),n.setAttribute(`name`,`theme-color`),document.head.appendChild(n)),n.setAttribute(`content`,t);let r=e.metadata.variant===`dark`?`(prefers-color-scheme: dark)`:`(prefers-color-scheme: light)`,i=document.querySelector(`meta[name="theme-color"][media="${r}"]`);i||(i=document.createElement(`meta`),i.setAttribute(`name`,`theme-color`),i.setAttribute(`media`,r),document.head.appendChild(i)),i.setAttribute(`content`,t)}),M=J(e=>{typeof document>`u`||document.documentElement.classList.toggle(`vscode-runtime`,e)});qf(()=>{if(typeof window>`u`)return;let e=Jf();n.apply(k),M(x),j(k);let t=document.documentElement;return t.classList.remove(`light`,`dark`),t.classList.add(k.metadata.variant),e},[M,n,k,x,j]),(0,Q.useEffect)(()=>{if(r.themeMode!==`system`||typeof window>`u`||w)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=e=>{u(e.matches)};return u(e.matches),e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r.themeMode,w]),(0,Q.useEffect)(()=>{if(w||typeof window>`u`)return;W(`themeMode`,r.themeMode),W(`lightThemeId`,r.lightThemeId),W(`darkThemeId`,r.darkThemeId),W(`useSystemTheme`,String(r.themeMode===`system`)),W(`selectedThemeId`,k.metadata.id),W(`selectedThemeVariant`,k.metadata.variant===`light`?`light`:`dark`);let e=D(r.lightThemeId,`light`),t=D(r.darkThemeId,`dark`);W(`splashBgLight`,e.colors.surface.background),W(`splashFgLight`,e.colors.surface.foreground),W(`splashBgDark`,t.colors.surface.background),W(`splashFgDark`,t.colors.surface.foreground),S&&(localStorage.setItem(`themeMode`,r.themeMode),localStorage.setItem(`useSystemTheme`,String(r.themeMode===`system`)),localStorage.setItem(`splashBgLight`,e.colors.surface.background),localStorage.setItem(`splashFgLight`,e.colors.surface.foreground),localStorage.setItem(`splashBgDark`,t.colors.surface.background),localStorage.setItem(`splashFgDark`,t.colors.surface.foreground))},[r,k,D,S,w]),(0,Q.useEffect)(()=>{if(typeof window>`u`||w)return;let e=e=>{e.storageArea===window.localStorage&&(se(e.key,`themeMode`)||se(e.key,`lightThemeId`)||se(e.key,`darkThemeId`))&&a(e=>{let t=G(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=G(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=G(`darkThemeId`),o=typeof a==`string`&&a.trim().length>0?a.trim():e.darkThemeId;return n===e.themeMode&&i===e.lightThemeId&&o===e.darkThemeId?e:{themeMode:n,lightThemeId:i,darkThemeId:o}})};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[w]);let N=J(e=>{let t=e.themeMode,n=e.lightThemeId,r=e.darkThemeId,i=Hf(e),o=Vf(e);if(t!==`light`&&t!==`dark`&&t!==`system`||typeof n!=`string`||typeof r!=`string`)return;let s=n.trim(),c=r.trim();!s||!c||(Jf(),(0,Sf.flushSync)(()=>{w&&o&&g(o),t===`system`&&i&&u(i===`dark`),a(e=>e.themeMode===t&&e.lightThemeId===s&&e.darkThemeId===c?e:{themeMode:t,lightThemeId:s,darkThemeId:c})}))});(0,Q.useEffect)(()=>{if(typeof window>`u`)return;let e=window;return e.__openchamberApplyThemeSync=N,()=>{e.__openchamberApplyThemeSync===N&&delete e.__openchamberApplyThemeSync}},[N]),(0,Q.useEffect)(()=>{if(typeof window>`u`)return;let e=e=>{if(e.origin!==window.location.origin)return;let t=e.data;t?.type!==`openchamber:theme-sync`||!t.payload||N(t.payload)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[N]),(0,Q.useEffect)(()=>{if(w||!o)return;let e=D(r.lightThemeId,`light`),t=D(r.darkThemeId,`dark`);pe({themeId:k.metadata.id,themeVariant:k.metadata.variant===`light`?`light`:`dark`,useSystemTheme:r.themeMode===`system`,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,splashBgLight:e.colors.surface.background,splashFgLight:e.colors.surface.foreground,splashBgDark:t.colors.surface.background,splashFgDark:t.colors.surface.foreground})},[k.metadata.id,k.metadata.variant,D,r.themeMode,r.lightThemeId,r.darkThemeId,w,o]),(0,Q.useEffect)(()=>{w||!C||(async()=>{await qt(r.themeMode,k.metadata.variant)})()},[k.metadata.variant,C,r.themeMode,w]),(0,Q.useEffect)(()=>{if(typeof window>`u`)return;let e=e=>{let t=e.detail;t&&(a(e=>{let n=e.themeMode;t.useSystemTheme===!0?n=`system`:t.useSystemTheme===!1&&(t.themeVariant===`dark`||t.themeVariant===`light`)&&(n=t.themeVariant);let r=e.lightThemeId;typeof t.lightThemeId==`string`&&t.lightThemeId.length>0&&(r=t.lightThemeId.trim());let i=e.darkThemeId;return typeof t.darkThemeId==`string`&&t.darkThemeId.length>0&&(i=t.darkThemeId.trim()),n===e.themeMode&&r===e.lightThemeId&&i===e.darkThemeId?e:{themeMode:n,lightThemeId:r,darkThemeId:i}}),s(!0))};return window.addEventListener(`openchamber:settings-synced`,e),()=>window.removeEventListener(`openchamber:settings-synced`,e)},[]),(0,Q.useEffect)(()=>{if(!(w||typeof window>`u`))return i(e=>{l(e)&&(a(e=>{let t=G(`themeMode`),n=t===`light`||t===`dark`||t===`system`?t:e.themeMode,r=G(`lightThemeId`),i=typeof r==`string`&&r.trim().length>0?r.trim():e.lightThemeId,a=G(`darkThemeId`),o=typeof a==`string`&&a.trim().length>0?a.trim():e.darkThemeId;return n===e.themeMode&&i===e.lightThemeId&&o===e.darkThemeId?e:{themeMode:n,lightThemeId:i,darkThemeId:o}}),s(!1))})},[w]);let P=J(e=>{let t=T.find(t=>t.metadata.id===e);t&&a(e=>t.metadata.variant===`dark`?e.darkThemeId===t.metadata.id&&e.themeMode===`dark`?e:{...e,darkThemeId:t.metadata.id,themeMode:`dark`}:e.lightThemeId===t.metadata.id&&e.themeMode===`light`?e:{...e,lightThemeId:t.metadata.id,themeMode:`light`})}),F=J(e=>{a(t=>t.themeMode===e?t:{...t,themeMode:e})}),I=J(e=>{if(e){a(e=>e.themeMode===`system`?e:{...e,themeMode:`system`});return}let t=k.metadata.variant===`dark`?`dark`:`light`;a(e=>e.themeMode===t?e:{...e,themeMode:t})}),L=J(e=>{let t=T.find(t=>t.metadata.id===e&&t.metadata.variant===`light`);t&&a(e=>e.lightThemeId===t.metadata.id?e:{...e,lightThemeId:t.metadata.id})}),z=J(e=>{let t=T.find(t=>t.metadata.id===e&&t.metadata.variant===`dark`);t&&a(e=>e.darkThemeId===t.metadata.id?e:{...e,darkThemeId:t.metadata.id})}),B=(0,Q.useMemo)(()=>({currentTheme:k,availableThemes:T,setTheme:P,customThemesLoading:_,reloadCustomThemes:A,isSystemPreference:r.themeMode===`system`,setSystemPreference:I,themeMode:r.themeMode,setThemeMode:F,lightThemeId:r.lightThemeId,darkThemeId:r.darkThemeId,setLightThemePreference:L,setDarkThemePreference:z}),[T,k,_,r.darkThemeId,r.lightThemeId,r.themeMode,A,z,L,I,P,F]);return(0,$.jsx)(Gs.Provider,{value:B,children:e})}var Zf=!1,Qf=()=>{if(Zf||typeof window>`u`)return;Zf=!0;let e={showReasoningTraces:q.getState().showReasoningTraces,sessionTitleRefreshEnabled:q.getState().sessionTitleRefreshEnabled,sessionGoalEnabled:q.getState().sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:q.getState().sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:q.getState().sessionGoalDefaultBudget,collapsibleThinkingBlocks:q.getState().collapsibleThinkingBlocks,showDeletionDialog:q.getState().showDeletionDialog,nativeNotificationsEnabled:q.getState().nativeNotificationsEnabled,notificationMode:q.getState().notificationMode,notifyOnSubtasks:q.getState().notifyOnSubtasks,notifyOnCompletion:q.getState().notifyOnCompletion,notifyOnError:q.getState().notifyOnError,notifyOnQuestion:q.getState().notifyOnQuestion,notificationTemplates:q.getState().notificationTemplates,summarizeLastMessage:q.getState().summarizeLastMessage,summaryThreshold:q.getState().summaryThreshold,summaryLength:q.getState().summaryLength,maxLastMessageLength:q.getState().maxLastMessageLength,autoDeleteEnabled:q.getState().autoDeleteEnabled,autoDeleteAfterDays:q.getState().autoDeleteAfterDays,sessionRetentionAction:q.getState().sessionRetentionAction,fontSize:q.getState().fontSize,terminalFontSize:q.getState().terminalFontSize,editorFontSize:q.getState().editorFontSize,uiFont:q.getState().uiFont,monoFont:q.getState().monoFont,padding:q.getState().padding,cornerRadius:q.getState().cornerRadius,inputBarOffset:q.getState().inputBarOffset,mobileKeyboardMode:q.getState().mobileKeyboardMode,diffLayoutPreference:q.getState().diffLayoutPreference,gitChangesViewMode:q.getState().gitChangesViewMode},t=null,n=null,r=()=>{let e=t;t=null,n=null,e&&Object.keys(e).length>0&&pe(e)},i=e=>{t={...t??{},...e},!n&&(n=setTimeout(r,150))};q.subscribe(t=>{let n={showReasoningTraces:t.showReasoningTraces,sessionTitleRefreshEnabled:t.sessionTitleRefreshEnabled,sessionGoalEnabled:t.sessionGoalEnabled,sessionGoalDefaultBudgetEnabled:t.sessionGoalDefaultBudgetEnabled,sessionGoalDefaultBudget:t.sessionGoalDefaultBudget,collapsibleThinkingBlocks:t.collapsibleThinkingBlocks,showDeletionDialog:t.showDeletionDialog,nativeNotificationsEnabled:t.nativeNotificationsEnabled,notificationMode:t.notificationMode,notifyOnSubtasks:t.notifyOnSubtasks,notifyOnCompletion:t.notifyOnCompletion,notifyOnError:t.notifyOnError,notifyOnQuestion:t.notifyOnQuestion,notificationTemplates:t.notificationTemplates,summarizeLastMessage:t.summarizeLastMessage,summaryThreshold:t.summaryThreshold,summaryLength:t.summaryLength,maxLastMessageLength:t.maxLastMessageLength,autoDeleteEnabled:t.autoDeleteEnabled,autoDeleteAfterDays:t.autoDeleteAfterDays,sessionRetentionAction:t.sessionRetentionAction,fontSize:t.fontSize,terminalFontSize:t.terminalFontSize,editorFontSize:t.editorFontSize,uiFont:t.uiFont,monoFont:t.monoFont,padding:t.padding,cornerRadius:t.cornerRadius,inputBarOffset:t.inputBarOffset,mobileKeyboardMode:t.mobileKeyboardMode,diffLayoutPreference:t.diffLayoutPreference,gitChangesViewMode:t.gitChangesViewMode},r={};n.showReasoningTraces!==e.showReasoningTraces&&(r.showReasoningTraces=n.showReasoningTraces),n.sessionTitleRefreshEnabled!==e.sessionTitleRefreshEnabled&&(r.sessionTitleRefreshEnabled=n.sessionTitleRefreshEnabled),n.sessionGoalEnabled!==e.sessionGoalEnabled&&(r.sessionGoalEnabled=n.sessionGoalEnabled),n.sessionGoalDefaultBudgetEnabled!==e.sessionGoalDefaultBudgetEnabled&&(r.sessionGoalDefaultBudgetEnabled=n.sessionGoalDefaultBudgetEnabled),n.sessionGoalDefaultBudget!==e.sessionGoalDefaultBudget&&(r.sessionGoalDefaultBudget=n.sessionGoalDefaultBudget),n.collapsibleThinkingBlocks!==e.collapsibleThinkingBlocks&&(r.collapsibleThinkingBlocks=n.collapsibleThinkingBlocks),n.showDeletionDialog!==e.showDeletionDialog&&(r.showDeletionDialog=n.showDeletionDialog),n.nativeNotificationsEnabled!==e.nativeNotificationsEnabled&&(r.nativeNotificationsEnabled=n.nativeNotificationsEnabled),n.notificationMode!==e.notificationMode&&(r.notificationMode=n.notificationMode),n.notifyOnSubtasks!==e.notifyOnSubtasks&&(r.notifyOnSubtasks=n.notifyOnSubtasks),n.notifyOnCompletion!==e.notifyOnCompletion&&(r.notifyOnCompletion=n.notifyOnCompletion),n.notifyOnError!==e.notifyOnError&&(r.notifyOnError=n.notifyOnError),n.notifyOnQuestion!==e.notifyOnQuestion&&(r.notifyOnQuestion=n.notifyOnQuestion),JSON.stringify(n.notificationTemplates)!==JSON.stringify(e.notificationTemplates)&&(r.notificationTemplates=n.notificationTemplates),n.summarizeLastMessage!==e.summarizeLastMessage&&(r.summarizeLastMessage=n.summarizeLastMessage),n.summaryThreshold!==e.summaryThreshold&&(r.summaryThreshold=n.summaryThreshold),n.summaryLength!==e.summaryLength&&(r.summaryLength=n.summaryLength),n.maxLastMessageLength!==e.maxLastMessageLength&&(r.maxLastMessageLength=n.maxLastMessageLength),n.autoDeleteEnabled!==e.autoDeleteEnabled&&(r.autoDeleteEnabled=n.autoDeleteEnabled),n.autoDeleteAfterDays!==e.autoDeleteAfterDays&&(r.autoDeleteAfterDays=n.autoDeleteAfterDays),n.sessionRetentionAction!==e.sessionRetentionAction&&(r.sessionRetentionAction=n.sessionRetentionAction),n.fontSize!==e.fontSize&&(r.fontSize=n.fontSize),n.terminalFontSize!==e.terminalFontSize&&(r.terminalFontSize=n.terminalFontSize),n.editorFontSize!==e.editorFontSize&&(r.editorFontSize=n.editorFontSize),n.uiFont!==e.uiFont&&(r.uiFont=n.uiFont),n.monoFont!==e.monoFont&&(r.monoFont=n.monoFont),n.padding!==e.padding&&(r.padding=n.padding),n.cornerRadius!==e.cornerRadius&&(r.cornerRadius=n.cornerRadius),n.inputBarOffset!==e.inputBarOffset&&(r.inputBarOffset=n.inputBarOffset),n.mobileKeyboardMode!==e.mobileKeyboardMode&&(r.mobileKeyboardMode=n.mobileKeyboardMode),n.diffLayoutPreference!==e.diffLayoutPreference&&(r.diffLayoutPreference=n.diffLayoutPreference),n.gitChangesViewMode!==e.gitChangesViewMode&&(r.gitChangesViewMode=n.gitChangesViewMode),e=n,Object.keys(r).length>0&&i(r)})},$f=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.providerID!==t[n]?.providerID||e[n]?.modelID!==t[n]?.modelID||e[n]?.variant!==t[n]?.variant)return!1;return!0},ep=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.providerID!==t[n]?.providerID||e[n]?.modelID!==t[n]?.modelID)return!1;return!0},tp=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},np=(e,t)=>{if(e===t)return!0;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Array.isArray(t[n])&&tp(e[n],t[n]))},rp=()=>{let e=q.getState();return{favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts}},ip=(e,t)=>$f(e.favoriteModels,t.favoriteModels)&&ep(e.hiddenModels,t.hiddenModels)&&tp(e.collapsedModelProviders,t.collapsedModelProviders)&&$f(e.recentModels,t.recentModels)&&tp(e.recentAgents,t.recentAgents)&&np(e.recentEfforts,t.recentEfforts),ap=e=>({favoriteModels:e.favoriteModels.slice(),hiddenModels:e.hiddenModels.slice(),collapsedModelProviders:e.collapsedModelProviders.slice(),recentModels:e.recentModels.slice(),recentAgents:e.recentAgents.slice(),recentEfforts:Object.fromEntries(Object.entries(e.recentEfforts).map(([e,t])=>[e,t.slice()]))}),op=()=>{if(typeof window>`u`)return()=>{};let e=null,t=null,n=!1,r=()=>{e=null;let n=rp();t&&ip(t,n)||(t=ap(n),pe(n).catch(()=>{}))},i=()=>{if(!n){n=!0;return}e!==null&&window.clearTimeout(e),e=window.setTimeout(r,1200)},a=q.subscribe((e,t)=>{ip({favoriteModels:e.favoriteModels,hiddenModels:e.hiddenModels,collapsedModelProviders:e.collapsedModelProviders,recentModels:e.recentModels,recentAgents:e.recentAgents,recentEfforts:e.recentEfforts},{favoriteModels:t.favoriteModels,hiddenModels:t.hiddenModels,collapsedModelProviders:t.collapsedModelProviders,recentModels:t.recentModels,recentAgents:t.recentAgents,recentEfforts:t.recentEfforts})||i()});return()=>{a(),e!==null&&window.clearTimeout(e)}},sp=!1,cp=`openchamber-typography-base`,lp=()=>{if(typeof document>`u`)return;let e=`:root {\n${Object.entries(bt).map(([e,t])=>` --text-${e.replace(/([A-Z])/g,`-$1`).toLowerCase()}: ${t};`).join(`
|
|
4
4
|
`)}\n}\n`,t=document.getElementById(cp);if(t){t.textContent=e;return}let n=document.createElement(`style`);n.id=cp,n.textContent=e,document.head.appendChild(n)},up=()=>{sp||typeof window>`u`||(sp=!0,lp())};function dp(e){let t=(0,pd.c)(3),{children:n}=e,r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],(0,Q.useEffect)(fp,r);let i;return t[1]===n?i=t[2]:(i=(0,$.jsx)(Ot,{client:ve,children:n}),t[1]=n,t[2]=i),i}function fp(){return V(ve)}var pp=15,mp=2e3,hp=e=>{let t=Oa(e=>e.isConnected),n=Oa(e=>e.providers.length),r=Oa(e=>e.agents.length),i=Oa(e=>e.activeDirectoryKey),a=Oa(e=>e.refreshMissingCatalogs),o=e.enabled&&t&&(n===0||r===0),s=Q.useRef(0),c=Q.useRef(!1),[l,u]=Q.useState(!1),d=e.source,f=J(async()=>{if(!o||c.current)return;if(s.current>=pp){u(!0);return}let e=Oa.getState();if(!(e.providers.length>0&&e.agents.length>0)){c.current=!0,s.current+=1;try{await a({source:d})}catch{}finally{c.current=!1}}});Q.useEffect(()=>{s.current=0,c.current=!1,u(!1),o&&f()},[o,i]),Bt(f,o&&!l?mp:null)},gp=40,_p=20971520,vp=new Map,yp=0;function bp(e){return e.length*2}function xp(e,t){let n=vp.get(e);n!==void 0&&(yp-=n),vp.delete(e),vp.set(e,t),yp+=t}function Sp(e,t){let n=vp.get(e);(n!==void 0||t!==void 0)&&xp(e,t??n??0)}function Cp(e){let t=vp.get(e);t!==void 0&&(vp.delete(e),yp-=t)}function wp(e,t){let n=e??new Set;for(;vp.size>gp||yp>_p;){let e=vp.keys().next().value;if(!e)return;if(n.has(e)){if(Sp(e),vp.size<=n.size)return;continue}Cp(e),t(e)}}function Tp(e,t){xp(e,t)}function Ep(e){Cp(e)}function Dp(e,t){Sp(e,t)}function Op(e){let t=new Map,n=e=>{t.delete(e),Ep(e)},r=e=>{let r=e.endsWith(`/`)?e:`${e}/`;for(let i of t.keys())(i===e||i.startsWith(r))&&n(i)},i=(e,t)=>t.isFile?e.mtimeMs!==void 0&&t.mtimeMs!==void 0?e.mtimeMs===t.mtimeMs&&e.size===t.size:e.size===t.size:!1,a=(e,n,r)=>{let i=bp(n.content);return t.set(e,{...n,size:r?.isFile?r.size:void 0,mtimeMs:r?.isFile?r.mtimeMs:void 0}),Tp(e,i),wp(new Set,e=>{t.delete(e)}),n},o=async(t,n)=>{let r=await e.statFile?.(t,n).catch(()=>null),i=await e.readFile(t,n),o=await e.statFile?.(t,n).catch(()=>null);if(r&&o&&r.isFile&&o.isFile){if(r.size===o.size&&r.mtimeMs===o.mtimeMs)return a(t,i,o);let s=await e.statFile?.(t,n).catch(()=>null),c=await e.readFile(t,n),l=await e.statFile?.(t,n).catch(()=>null);return s&&l&&s.isFile&&l.isFile&&s.size===l.size&&(s.mtimeMs,l.mtimeMs),a(t,c,l)}return a(t,i,o??r)},s=e.readFile?async(r,a)=>{if(a?.allowOutsideWorkspace)return o(r,a);let s=t.get(r);if(s){if(e.statFile){let t=await e.statFile(r,a).catch(()=>(n(r),null));if(!t||!i(s,t))return n(r),o(r,a)}return Dp(r),{content:s.content,path:s.path}}return o(r,a)}:void 0,c=e.writeFile?async(t,r)=>(n(t),e.writeFile(t,r)):void 0,l=e.delete?async t=>(r(t),e.delete(t)):void 0,u=e.rename?async(t,n)=>(r(t),r(n),e.rename(t,n)):void 0;return{...e,readFile:s,writeFile:c,delete:l,rename:u}}function kp(e){let t=(0,pd.c)(8),{apis:n,children:r}=e,i;t[0]===n.files?i=t[1]:(i=Op(n.files),t[0]=n.files,t[1]=i);let a;t[2]!==n||t[3]!==i?(a={...n,files:i},t[2]=n,t[3]=i,t[4]=a):a=t[4];let o=a,s;return t[5]!==o||t[6]!==r?(s=(0,$.jsx)(ic.Provider,{value:o,children:r}),t[5]=o,t[6]=r,t[7]=s):s=t[7],s}var Ap=`var(--oc-toast-shadow, inset 0 1px 0 0 rgba(255,255,255,0.12), inset 0 0 0 1px rgba(255,255,255,0.08), 0 0 0 1px rgba(0,0,0,0.36), 0 1px 1px -0.5px rgba(0,0,0,0.22), 0 3px 3px -1.5px rgba(0,0,0,0.20), 0 6px 6px -3px rgba(0,0,0,0.16))`,jp=`var(--oc-toast-shadow, inset 0 1px 0 0 rgba(255,255,255,0.8), inset 0 0 0 1px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.10), 0 1px 2px -0.5px rgba(0,0,0,0.08), 0 4px 8px -2px rgba(0,0,0,0.08), 0 12px 20px -4px rgba(0,0,0,0.08))`,Mp={success:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`checkbox-circle-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(Z,{name:`check`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]}),info:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`information-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(Z,{name:`information`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]}),warning:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`alert-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(Z,{name:`error-warning`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]}),error:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`error-warning-fill`,className:`oc-toast-status-icon-desktop size-5`}),(0,$.jsx)(Z,{name:`alert`,className:`oc-toast-status-icon-mobile hidden size-[18px]`})]})};function Np(){let e=(0,pd.c)(2),t=Pp,[n,r]=Q.useState(t),i,a;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=()=>{let e=()=>r(t()),n=new MutationObserver(e);return n.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`]}),e(),()=>n.disconnect()},a=[],e[0]=i,e[1]=a):(i=e[0],a=e[1]),Q.useEffect(i,a),n}function Pp(){return typeof document<`u`&&document.documentElement.classList.contains(`dark`)}function Fp(e){let t=(0,pd.c)(3),n,r;t[0]===e?(n=t[1],r=t[2]):(n=()=>{if(typeof document>`u`)return;let t=t=>{t.style.setProperty(`box-shadow`,e,`important`),t.style.setProperty(`outline`,`none`,`important`),t.getAttribute(`tabindex`)===`0`&&t.setAttribute(`tabindex`,`-1`)},n=()=>{document.querySelectorAll(`[data-sonner-toast]`).forEach(t)};n();let r=new MutationObserver(e=>{for(let n of e)n.addedNodes.forEach(e=>{e instanceof HTMLElement&&(e.matches?.(`[data-sonner-toast]`)&&t(e),e.querySelectorAll?.(`[data-sonner-toast]`).forEach(t))});n()});return r.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`style`,`tabindex`,`data-expanded`,`data-swiping`]}),()=>r.disconnect()},r=[e],t[0]=e,t[1]=n,t[2]=r),Q.useEffect(n,r)}var Ip=e=>{let t=(0,pd.c)(7),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r=Np();Fp(r?Ap:jp);let i=r?`dark`:`light`,a,o;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a={classNames:{toast:`group/toast toast !flex !min-w-[min(var(--width),calc(100vw-2rem))] !max-w-[calc(100vw-2rem)] !items-center !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground`,content:`!min-w-0 !flex-1 !text-left`,title:`typography-ui-label !font-medium !text-foreground`,description:`typography-meta !text-muted-foreground !mt-0.5`,actionButton:`!ms-0 !me-0 !shrink-0 !rounded-[var(--radius-md)] !bg-[var(--oc-toast-action-background,var(--primary-base))] !text-[var(--oc-toast-action-foreground,var(--primary-foreground))] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity`,cancelButton:`!ms-0 !me-0 !shrink-0 !rounded-[var(--radius-md)] !bg-[var(--oc-toast-cancel-background,var(--interactive-hover))] !text-[var(--oc-toast-cancel-foreground,var(--foreground))] hover:!bg-[var(--interactive-active)] !px-2 !py-1 typography-meta !font-medium transition-colors`,closeButton:`!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)]`,icon:`!shrink-0 !text-muted-foreground`,success:`[&_[data-icon]]:!text-[var(--status-success)]`,error:`[&_[data-icon]]:!text-[var(--status-error)]`,warning:`[&_[data-icon]]:!text-[var(--status-warning)]`,info:`[&_[data-icon]]:!text-[var(--status-info)]`},style:{borderRadius:`var(--radius-xl)`,backgroundColor:`var(--oc-toast-background, var(--surface-elevated))`}},o={"--normal-bg":`var(--oc-toast-background, var(--surface-elevated))`,"--normal-text":`var(--foreground)`,"--normal-border":`transparent`,"--error-bg":`var(--oc-toast-background, var(--surface-elevated))`,"--error-text":`var(--foreground)`,"--error-border":`transparent`,"--success-bg":`var(--oc-toast-background, var(--surface-elevated))`,"--success-text":`var(--foreground)`,"--success-border":`transparent`,"--warning-bg":`var(--oc-toast-background, var(--surface-elevated))`,"--warning-text":`var(--foreground)`,"--warning-border":`transparent`,"--info-bg":`var(--oc-toast-background, var(--surface-elevated))`,"--info-text":`var(--foreground)`,"--info-border":`transparent`},t[2]=a,t[3]=o):(a=t[2],o=t[3]);let s;return t[4]!==n||t[5]!==i?(s=(0,$.jsx)(zt,{theme:i,className:`toaster group`,closeButton:!1,icons:Mp,toastOptions:a,style:o,...n}),t[4]=n,t[5]=i,t[6]=s):s=t[6],s},Lp=wt(`OpenChamberMedia`);function Rp(){return mt()&&Tt.getPlatform()===`android`&&Tt.isPluginAvailable(`OpenChamberMedia`)}async function zp(e){if(!Rp())return null;let t=await Lp.pickMedia({limit:e});if(t.cancelled)return[];let n=[];for(let e of t.files){let t=await fetch(Tt.convertFileSrc(e.path));if(!t.ok)throw Error(`Native media fetch failed (${t.status})`);let r=await t.blob();n.push(new File([r],e.name,{type:e.mimeType}))}return n}var Bp=(e,t)=>{let n=t.trim();if(!n.length)return[...e].sort((e,t)=>e.scope===`project`&&t.scope!==`project`?-1:e.scope!==`project`&&t.scope===`project`?1:e.name.localeCompare(t.name));let r=ln([...e],n,e=>[e.name,e.description??``]);return r.sort((e,t)=>e.score===t.score?e.item.scope===`project`&&t.item.scope!==`project`?-1:e.item.scope!==`project`&&t.item.scope===`project`?1:e.item.name.localeCompare(t.item.name):e.score-t.score),r.map(e=>e.item)},Vp=new Map,Hp=(e,t,n)=>`${+!!t}:${n}:${e.map(e=>`${e.id}\0${e.title}\0${e.subtitle??``}\0${e.badge??``}\0${e.iconName}`).join(`|`)}`,Up=async e=>{let t=Wc(`--surface-foreground`);return Promise.all(e.slice(0,40).map(async e=>{let n=`${e.iconName}:${t}`,r=Vp.get(n);return r===void 0&&(r=await Ic(e.iconName,t)??``,Vp.set(n,r)),{id:e.id,title:e.title,subtitle:e.subtitle??``,badge:e.badge??``,iconBase64:r}}))},Wp=[],Gp=e=>void 0,Kp=()=>void 0;function qp(e){let t=Gc()&&e.enabled&&sl(e.isMobile),n=(0,Q.useRef)(null),r=(0,Q.useRef)(e.text),i=(0,Q.useRef)(!1),a=(0,Q.useRef)(-1),o=(0,Q.useRef)(null),s=(0,Q.useRef)(``),c=(0,Q.useRef)([]),l=(0,Q.useRef)(al()),u=J(e.onText),d=J(e.onSend),f=J(e.onAbort),p=J(e.onAttach),m=J(e.onFiles),h=J(e.onRemoveAttachment),g=J(e.onOpenModel),_=J(e.onCycleAgent),v=J(e.onOpenAgent),y=J(e.onScrollToBottom),b=J(e.onAutocompleteAccept??Gp),x=J(e.onAutocompleteDismiss??Kp),S=J(e=>{typeof document>`u`||il(document.documentElement,e)});cl.bind({onText:(e,t,n)=>{rl({incoming:e,replacedText:o.current})||(o.current=null,r.current=e,i.current=!0,u(e,t,n))},onSend:e=>{r.current=e,d(e)},onAbort:f,onAttach:p,onFiles:m,onRemoveAttachment:h,onOpenModel:g,onCycleAgent:_,onOpenAgent:v,onHeight:S,onScrollToBottom:y,onAutocompleteAccept:e=>{i.current=!1,b(e)},onAutocompleteDismiss:x});let C=()=>({text:e.text,placeholder:e.placeholder,modelLabel:e.modelLabel,modelVariantLabel:e.modelVariantLabel,modelIcon:s.current,canSend:e.canSend,canAbort:e.canAbort,attachmentCount:e.attachmentCount,attachmentPreviews:c.current,citationRanges:nt(e.text,e.attachments.map(e=>e.filename)),chipRanges:Qc(dl(e.text,e.chipHighlights),Wc(`--primary`)),appearance:typeof document>`u`?`dark`:pl(document.documentElement),attachAria:e.attachAria,attachTitle:e.attachTitle,attachPhotosLabel:e.attachPhotosLabel,attachFilesLabel:e.attachFilesLabel,attachCancelLabel:e.attachCancelLabel,sendAria:e.sendAria,queueAria:e.queueAria,stopAria:e.stopAria,modelAria:e.modelAria,agentAria:e.agentAria,agentLabel:e.agentLabel,agentColor:Xc(e.agentName||void 0),agentIdenticon:qc(e.agentName||void 0),suppressed:e.suppressed,showScrollToBottom:e.showScrollToBottom,scrollAria:e.scrollAria,autocomplete:l.current});(0,Q.useLayoutEffect)(()=>{if(!t||typeof document>`u`)return;let e=document.documentElement;return Kc(e,!0),()=>{Kc(e,!1)}},[t]),(0,Q.useEffect)(()=>{if(!t||typeof document>`u`)return;let e=document.documentElement,i=C();n.current=i,r.current=i.text,cl.rememberText(i.text),cl.retain(e,i);let a=ol();return()=>{n.current=null,a(),cl.release(e)}},[t]),(0,Q.useEffect)(()=>{if(!t)return;let r=!1,i=wo(e.modelId,e.providerId),a={modelIcon:``,modelLabel:e.modelLabel,modelVariantLabel:e.modelVariantLabel};if(s.current=``,n.current&&={...n.current,...a},tl().update(a),i)return fl(i).then(t=>{if(r)return;let i=t??``;s.current=i;let a={modelIcon:i,modelLabel:e.modelLabel,modelVariantLabel:e.modelVariantLabel};n.current&&={...n.current,...a},tl().update(a)}),()=>{r=!0}},[t,e.modelId,e.providerId,e.modelLabel,e.modelVariantLabel]);let w=ul(e.attachments);(0,Q.useEffect)(()=>{if(!t)return;let r=!1,i=e.attachments;if(i.length===0){c.current=[],n.current&&(n.current={...n.current,attachmentPreviews:[]},cl.rememberState(n.current)),tl().update({attachmentPreviews:[]});return}return Promise.all(i.map(async t=>{let n=t.mimeType.startsWith(`image/`)&&t.dataUrl?await Hc(t.dataUrl):``;return{id:t.id,filename:t.filename,mime:t.mimeType,thumbnailBase64:n??``,removeAria:e.removeAttachmentNamedAria(t.filename)}})).then(e=>{r||(c.current=e,n.current&&(n.current={...n.current,attachmentPreviews:e},cl.rememberState(n.current)),tl().update({attachmentPreviews:e}))}),()=>{r=!0}},[t,w]);let T=e.autocompleteRows??Wp,E=e.autocompleteOpen===!0,D=e.autocompleteHighlightedIndex??0,O=Hp(T,E,D);(0,Q.useEffect)(()=>{if(!t)return;let e=!1;if(!(E&&T.length>0)){let e=al();Yc(l.current,e)||(l.current=e,n.current&&(n.current={...n.current,autocomplete:e},cl.rememberState(n.current)),tl().update({autocomplete:e}));return}return Up(T).then(t=>{if(e)return;let r={open:t.length>0,highlightedIndex:Math.max(0,Math.min(D,Math.max(t.length-1,0))),rows:t};Yc(l.current,r)||(l.current=r,n.current&&(n.current={...n.current,autocomplete:r},cl.rememberState(n.current)),tl().update({autocomplete:r}))}),()=>{e=!0}},[t,O]);let k=t?dl(e.text,e.chipHighlights).map(e=>`${e.start}:${e.end}:${e.triggerLength}`).join(`|`):``;return(0,Q.useEffect)(()=>{if(!t)return;let s=C(),c=n.current;if(c&&ml(c,s)){i.current=!1,a.current=e.textPresetEpoch;return}n.current=s,cl.rememberState(s);let l=e.textPresetEpoch!==a.current;a.current=e.textPresetEpoch;let u=Uc({nextText:s.text,nativeOwnedText:r.current,echoingNative:i.current,preset:l});i.current=!1,!u.omitText&&u.forceText&&(o.current=r.current),u.omitText||(r.current=s.text);let d=$c(c,s,u,{caret:e.caret});d&&tl().update(d)},[t,e.text,e.textPresetEpoch,e.placeholder,e.modelLabel,e.modelVariantLabel,e.modelId,e.providerId,e.canSend,e.canAbort,e.attachmentCount,w,e.suppressed,e.attachAria,e.attachTitle,e.attachPhotosLabel,e.attachFilesLabel,e.attachCancelLabel,e.sendAria,e.queueAria,e.stopAria,e.modelAria,e.agentName,e.agentLabel,e.agentAria,e.showScrollToBottom,e.scrollAria,k]),t}var Jp=(e,t,n)=>{let r=Error(e);return r.name=`DictationStreamError`,r.retryable=t,n&&(r.reasonCode=n),r},Yp=1e4,Xp=15e3,Zp=3e4,Qp=3e4,$p=new class{socket=null;connectPromise=null;idleCloseTimer=null;pendingStarts=new Map;pendingFinishes=new Map;connectionListeners=new Set;partialListeners=new Set;activeDictations=0;get isConnected(){return this.socket?.readyState===WebSocket.OPEN}subscribeConnectionStatus(e){return this.connectionListeners.add(e),()=>{this.connectionListeners.delete(e)}}onPartial(e){return this.partialListeners.add(e),()=>{this.partialListeners.delete(e)}}async ensureConnected(){if(!this.isConnected){if(this.connectPromise){await this.connectPromise;return}try{await r()}catch{}this.connectPromise=new Promise((e,t)=>{let n=!1,r;try{let e=a().websocket(`/api/dictation/ws`);r=ct(e)}catch(e){this.connectPromise=null,t(e instanceof Error?e:Error(String(e)));return}let i=setTimeout(()=>{if(!n){n=!0,this.connectPromise=null;try{r.close()}catch{}t(Error(`Dictation connection timed out`))}},Yp);r.onopen=()=>{},r.onmessage=t=>{let a;try{a=JSON.parse(String(t.data))}catch{return}if(!n&&a.type===`ready`){n=!0,clearTimeout(i),this.socket=r,this.connectPromise=null,this.notifyConnection(!0),e();return}this.handleMessage(a)},r.onerror=()=>{window.setTimeout(()=>{n||(n=!0,clearTimeout(i),this.connectPromise=null,t(Error(`Dictation connection failed`)))},250)},r.onclose=e=>{if(!n){n=!0,clearTimeout(i),this.connectPromise=null;let r=e?.reason?`: ${e.reason}`:``;t(Error(`Dictation connection failed${r}`));return}this.socket===r&&(this.socket=null,this.rejectAllPending(Error(`Dictation connection lost`)),this.notifyConnection(!1))}}),await this.connectPromise}}async startDictationStream(e,t,n){return await this.ensureConnected(),this.activeDictations+=1,this.clearIdleCloseTimer(),new Promise((r,i)=>{let a=setTimeout(()=>{this.pendingStarts.delete(e),this.releaseDictation(),i(Error(`Dictation start timed out`))},Xp);this.pendingStarts.set(e,{resolve:()=>{clearTimeout(a),r()},reject:e=>{clearTimeout(a),this.releaseDictation(),i(e)},timeout:a}),this.send({type:`start`,dictationId:e,format:t,options:n})||(clearTimeout(a),this.pendingStarts.delete(e),this.releaseDictation(),i(Error(`Dictation connection lost`)))})}sendDictationStreamChunk(e,t,n){return this.send({type:`chunk`,dictationId:e,seq:t,audio:n})}finishDictationStream(e,t){return new Promise((n,r)=>{let i={resolve:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),n(e)},reject:e=>{i.timeout&&clearTimeout(i.timeout),this.releaseDictation(),r(e)},timeout:null};i.timeout=setTimeout(()=>{this.pendingFinishes.delete(e),this.releaseDictation(),r(Error(`Timed out waiting for transcription`))},Qp),this.pendingFinishes.set(e,i),this.send({type:`finish`,dictationId:e,finalSeq:t})||(this.pendingFinishes.delete(e),i.reject(Error(`Dictation connection lost`)))})}cancelDictationStream(e){this.send({type:`cancel`,dictationId:e});let t=this.pendingStarts.get(e);t&&(this.pendingStarts.delete(e),t.reject(Error(`Dictation cancelled`)));let n=this.pendingFinishes.get(e);n&&(this.pendingFinishes.delete(e),n.reject(Error(`Dictation cancelled`))),this.releaseDictation(),this.scheduleIdleCloseIfReady()}handleMessage(e){let t=e.dictationId;if(t)switch(e.type){case`ack`:{let e=this.pendingStarts.get(t);e&&(this.pendingStarts.delete(t),e.resolve());return}case`partial`:for(let n of this.partialListeners)n(t,e.text??``);return;case`finish_accepted`:{let n=this.pendingFinishes.get(t);n&&typeof e.timeoutMs==`number`&&(n.timeout&&clearTimeout(n.timeout),n.timeout=setTimeout(()=>{this.pendingFinishes.delete(t),n.reject(Error(`Timed out waiting for transcription`))},e.timeoutMs+5e3));return}case`final`:{let n=this.pendingFinishes.get(t);n&&(this.pendingFinishes.delete(t),n.resolve({text:e.text??``})),this.scheduleIdleCloseIfReady();return}case`error`:{let n=Jp(e.error||`Dictation failed`,e.retryable!==!1,e.reasonCode),r=this.pendingStarts.get(t);r&&(this.pendingStarts.delete(t),r.reject(n));let i=this.pendingFinishes.get(t);i&&(this.pendingFinishes.delete(t),i.reject(n)),this.scheduleIdleCloseIfReady();return}}}send(e){if(!this.isConnected||!this.socket)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch{return!1}}notifyConnection(e){for(let t of this.connectionListeners)t(e)}rejectAllPending(e){for(let[t,n]of this.pendingStarts)this.pendingStarts.delete(t),n.reject(e);for(let[t,n]of this.pendingFinishes)this.pendingFinishes.delete(t),n.reject(e);this.activeDictations=0}releaseDictation(){this.activeDictations=Math.max(0,this.activeDictations-1),this.scheduleIdleCloseIfReady()}scheduleIdleCloseIfReady(){this.activeDictations>0||this.pendingFinishes.size>0||this.pendingStarts.size>0||(this.clearIdleCloseTimer(),this.idleCloseTimer=setTimeout(()=>{if(this.activeDictations===0&&this.pendingFinishes.size===0&&this.pendingStarts.size===0){let e=this.socket;if(this.socket=null,e){try{e.close(1e3,`idle`)}catch{}this.notifyConnection(!1)}}},Zp))}cancelAllForRuntimeSwitch(){this.clearIdleCloseTimer();let e=this.socket;if(this.socket=null,this.connectPromise=null,this.rejectAllPending(Error(`Runtime changed`)),e){try{e.close(1e3,`runtime switch`)}catch{}this.notifyConnection(!1)}}clearIdleCloseTimer(){this.idleCloseTimer&&=(clearTimeout(this.idleCloseTimer),null)}};typeof window<`u`&&window.addEventListener(`openchamber:runtime-endpoint-changed`,()=>{$p.cancelAllForRuntimeSwitch()});var em=128,tm=`audio/pcm;rate=16000;bits=16`,nm=()=>new Promise(e=>setTimeout(e,0)),rm=()=>{let e=Math.random().toString(36).slice(2,10);return`dic_${Date.now().toString(16)}${e}`},im=class{client;format;createDictationId;getStartOptions;dictationId=null;sendSeq=0;segments=[];streamReady=!1;flushTimer=null;drainWaiters=[];startGeneration=0;startPromise=null;constructor(e){this.client=e.client,this.format=e.format??tm,this.getStartOptions=e.getStartOptions,this.createDictationId=e.createDictationId??rm}getDictationId(){return this.dictationId}getFinalSeq(){return this.segments.length-1}hasSegments(){return this.segments.length>0}clearAll(){this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.segments=[],this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}resetStreamForReplay(){this.clearScheduledFlush(),this.dictationId=null,this.sendSeq=0,this.streamReady=!1,this.startPromise=null,this.startGeneration+=1}enqueueSegment(e){if(this.segments.push(e),this.client.isConnected){if(!this.dictationId){this.startPromise||this.restartStream().catch(()=>{});return}this.flush()}}flush(){let e=this.dictationId;if(!this.client.isConnected||!e||!this.streamReady)return 0;let t=0;for(;this.sendSeq<this.segments.length&&t<em;){let n=this.sendSeq,r=this.segments[n];if(!this.client.sendDictationStreamChunk(e,n,r))break;this.sendSeq=n+1,t+=1}return this.hasPendingSegments()?this.scheduleFlush():this.resolveDrainWaiters(),t}async restartStream(){this.startGeneration+=1;let e=this.startGeneration,t=this.createDictationId();this.dictationId=t,this.sendSeq=0,this.streamReady=!1;let n=(async()=>{await this.client.startDictationStream(t,this.format,this.getStartOptions()),this.startGeneration===e&&this.dictationId===t&&(this.streamReady=!0,this.flush())})().catch(n=>{throw this.startGeneration===e&&this.dictationId===t&&(this.dictationId=null,this.streamReady=!1),n}).finally(()=>{this.startPromise===n&&(this.startPromise=null)});this.startPromise=n,await n}async finish(e){this.dictationId||await this.restartStream(),this.startPromise&&await this.startPromise;let t=this.dictationId;if(!t||!this.streamReady)throw Error(`Failed to start dictation stream`);return this.flush(),await this.waitForFlushDrain(),{dictationId:t,text:(await this.client.finishDictationStream(t,e)).text}}cancel(){let e=this.dictationId;this.client.isConnected&&e&&this.client.cancelDictationStream(e),this.resetStreamForReplay()}hasPendingSegments(){return this.sendSeq<this.segments.length}scheduleFlush(){this.flushTimer||=setTimeout(()=>{this.flushTimer=null,this.flush()},0)}clearScheduledFlush(){this.flushTimer&&=(clearTimeout(this.flushTimer),null)}async waitForFlushDrain(){for(;this.hasPendingSegments();){if(!this.client.isConnected||!this.dictationId||!this.streamReady)throw Error(`Failed to flush dictation stream`);await new Promise(e=>{this.drainWaiters.push(e)}),await nm()}}resolveDrainWaiters(){let e=this.drainWaiters;this.drainWaiters=[];for(let t of e)t()}},am=16e3,om=am,sm=()=>{if(typeof window>`u`)return null;let e=window;return e.AudioContext||e.webkitAudioContext||null},cm=e=>{let t=Math.max(-1,Math.min(1,e));return Math.round(t<0?t*32768:t*32767)},lm=(e,t,n)=>{if(e.length===0)return new Int16Array;if(t===n){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++)t[n]=cm(e[n]);return t}let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Int16Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=cm(e[i]*(1-s)+e[o]*s)}return a},um=(e,t)=>{if(e.length===0)return t;if(t.length===0)return e;let n=new Int16Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n},dm=e=>{let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``;for(let e=0;e<t.length;e++)n+=String.fromCharCode(t[e]);return btoa(n)},fm=()=>({stream:null,context:null,source:null,processor:null,gain:null,pending:new Int16Array,started:!1}),pm=e=>{if(e)try{e.disconnect()}catch{}},mm=()=>typeof navigator>`u`||typeof window>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`?!1:sm()!==null;function hm(e){let t=(0,pd.c)(12),[n,r]=(0,Q.useState)(0),i=(0,Q.useRef)(e.onPcmSegment),a=(0,Q.useRef)(e.onError),o,s;t[0]!==e.onError||t[1]!==e.onPcmSegment?(o=()=>{i.current=e.onPcmSegment,a.current=e.onError},s=[e.onPcmSegment,e.onError],t[0]=e.onError,t[1]=e.onPcmSegment,t[2]=o,t[3]=s):(o=t[2],s=t[3]),(0,Q.useEffect)(o,s);let c;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(c=fm(),t[4]=c):c=t[4];let l=(0,Q.useRef)(c),u;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(u=async()=>{if(l.current.started)return;if(typeof navigator>`u`||!navigator.mediaDevices||typeof navigator.mediaDevices.getUserMedia!=`function`)throw Error(`Microphone capture is not supported in this environment`);let e=sm();if(!e)throw Error(`AudioContext unavailable`);let t=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,noiseSuppression:!0,echoCancellation:!0,autoGainControl:!0}}),n=new e;try{n.state===`suspended`&&await n.resume().catch(vm);let e=n.createMediaStreamSource(t),a=n.createScriptProcessor(4096,1,1),o=n.createGain();o.gain.value=0,l.current={stream:t,context:n,source:e,processor:a,gain:o,pending:new Int16Array,started:!0},a.onaudioprocess=e=>{let t=l.current;if(!t.started)return;let a=e.inputBuffer.getChannelData(0),o=0;for(let e=0;e<a.length;e++)o+=a[e]*a[e];let s=Math.sqrt(o/Math.max(1,a.length));r(Math.min(1,Math.max(0,s*2)));let c=lm(a,n.sampleRate,am);for(t.pending=um(t.pending,c);t.pending.length>=om;){let e=t.pending.slice(0,om);t.pending=t.pending.slice(om),i.current(dm(e))}},e.connect(a),a.connect(o),o.connect(n.destination)}catch(e){let r=e;t.getTracks().forEach(_m);try{await n.close()}catch{}throw l.current=fm(),r instanceof Error?r:Error(String(r))}},t[5]=u):u=t[5];let d=u,f;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(f=async()=>{let e=l.current;if(e.started=!1,r(0),e.processor)try{e.processor.onaudioprocess=null}catch{}pm(e.processor),pm(e.source),pm(e.gain),e.stream&&e.stream.getTracks().forEach(gm);let t=e.pending;if(e.pending=new Int16Array,t.length>0&&i.current(dm(t)),e.context)try{await e.context.close()}catch{}l.current===e&&(l.current=fm())},t[6]=f):f=t[6];let p=f,m,h;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(m=()=>()=>{p().catch(e=>{a.current?.(e instanceof Error?e:Error(String(e)))})},h=[p],t[7]=m,t[8]=h):(m=t[7],h=t[8]),(0,Q.useEffect)(m,h);let g;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(g=async()=>{try{await d()}catch(e){let t=e,n=t instanceof Error?t:Error(String(t));throw a.current?.(n),n}},t[9]=g):g=t[9];let _;return t[10]===n?_=t[11]:(_={start:g,stop:p,volume:n},t[10]=n,t[11]=_),_}function gm(e){try{e.stop()}catch{}}function _m(e){try{e.stop()}catch{}}function vm(){}var ym=1e3,bm=e=>e instanceof Error?e:Error(String(e)),xm=()=>{let e=Oa.getState(),t=e.sttLanguage?.trim();return e.sttProvider===`openai-compatible`?{provider:`openai-compatible`,...t?{language:t}:{},openaiCompatible:{baseUrl:e.sttServerUrl,model:e.sttModel,...e.sttApiKey?{apiKey:e.sttApiKey}:{}}}:{provider:`local`,...t?{language:t}:{},localModel:e.sttLocalModel}};function Sm(e={}){let{onTranscript:t,onError:n,canStart:r}=e,[i,a]=(0,Q.useState)(`idle`),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(0),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),m=(0,Q.useRef)(i);(0,Q.useEffect)(()=>{m.current=i},[i]);let h=(0,Q.useRef)(``),g=(0,Q.useRef)(null),_=(0,Q.useRef)({starting:!1,confirming:!1,cancelling:!1}),v=(0,Q.useRef)(t),y=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{v.current=t,y.current=n},[t,n]);let b=(0,Q.useRef)(null);b.current||=new im({client:$p,getStartOptions:xm});let x=(0,Q.useCallback)(()=>{g.current&&=(clearInterval(g.current),null)},[]),S=(0,Q.useCallback)(()=>{g.current||=setInterval(()=>{l(e=>e+1)},ym)},[]),C=(0,Q.useCallback)(e=>{let t=bm(e);d(t.message);let n=t.reasonCode;p(typeof n==`string`?n:null),y.current?.(t)},[]),w=(0,Q.useCallback)(()=>{d(null),p(null)},[]),T=(0,Q.useCallback)(()=>{b.current?.clearAll(),h.current=``,s(``)},[]);(0,Q.useEffect)(()=>$p.onPartial((e,t)=>{let n=b.current?.getDictationId();!n||e!==n||(h.current=t,s(t))}),[]),(0,Q.useEffect)(()=>$p.subscribeConnectionStatus(e=>{e&&m.current===`recording`&&b.current?.restartStream().catch(e=>{C(e)})}),[C]);let E=hm({onPcmSegment:e=>{b.current?.enqueueSegment(e)},onError:e=>{y.current?.(e)}}),D=(0,Q.useRef)(E.stop);(0,Q.useEffect)(()=>{D.current=E.stop},[E.stop]);let O=(0,Q.useCallback)(e=>{l(0),a(`idle`);let t=e.trim().length>0?e.trim():h.current.trim();return T(),t?(v.current?.(t),t):null},[T]),k=(0,Q.useCallback)(e=>{b.current?.hasSegments()?a(`failed`):a(`idle`),C(e)},[C]),A=(0,Q.useCallback)(async()=>{let e=_.current;if(!(e.starting||e.confirming||e.cancelling)&&m.current===`idle`&&!(r&&!r())){e.starting=!0,w(),s(``),l(0),a(`recording`),m.current=`recording`,T();try{await E.start(),S(),await b.current?.restartStream().catch(e=>{C(e)})}catch(e){await E.stop().catch(()=>void 0),x(),a(`idle`),m.current=`idle`,C(e)}finally{e.starting=!1}}},[E,r,w,T,C,S,x]),j=(0,Q.useCallback)(async()=>{let e=_.current;if(!e.cancelling&&(m.current===`recording`||m.current===`uploading`)){e.cancelling=!0,x(),l(0),w(),a(`idle`),m.current=`idle`;try{b.current?.cancel()}catch{}T();try{await E.stop()}catch{}finally{e.cancelling=!1}}},[E,w,T,x]),M=(0,Q.useCallback)(async()=>{let e=_.current;if(e.confirming||m.current!==`recording`)return null;e.confirming=!0,w(),x();try{await E.stop(),a(`uploading`),m.current=`uploading`;let e=b.current?.getFinalSeq()??-1;if(e<0)return O(``);let t=await b.current.finish(e);return O(t.text)}catch(e){return k(e),null}finally{e.confirming=!1}},[E,w,k,O,x]),N=(0,Q.useCallback)(async()=>{if(m.current!==`failed`||!b.current?.hasSegments())return null;w(),a(`uploading`),m.current=`uploading`;try{b.current.resetStreamForReplay();let e=b.current.getFinalSeq(),t=await b.current.finish(e);return O(t.text)}catch(e){return k(e),null}},[w,k,O]),P=(0,Q.useCallback)(()=>{if(m.current!==`failed`)return null;let e=h.current.trim();l(0),a(`idle`),m.current=`idle`,w();try{b.current?.cancel()}catch{}return T(),e?(v.current?.(e),e):null},[w,T]),F=(0,Q.useCallback)(()=>{l(0),a(`idle`),m.current=`idle`,w(),T()},[w,T]);return(0,Q.useEffect)(()=>{if(i!==`recording`||f!==`model_download_in_progress`)return;let e=setInterval(()=>{m.current!==`recording`||b.current?.getDictationId()||b.current?.restartStream().then(()=>{w()}).catch(e=>{C(e)})},3e3);return()=>clearInterval(e)},[i,f,w,C]),(0,Q.useEffect)(()=>()=>{x(),D.current().catch(()=>void 0),b.current?.cancel()},[x]),{status:i,isRecording:i===`recording`,isProcessing:i===`uploading`,partialTranscript:o,volume:E.volume,duration:c,error:u,errorReason:f,startDictation:A,confirmDictation:M,cancelDictation:j,retryFailedDictation:N,acceptPartialTranscript:P,discardFailedDictation:F}}var Cm=e=>{let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`},wm=e=>{let t=(0,pd.c)(4),{volume:n}=e,{currentTheme:r}=Ws(),i=Math.min(1,Math.max(0,n)),a;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(a=[.45,.7,1,.7,.45],t[0]=a):a=t[0];let o=a,s;return t[1]!==r||t[2]!==i?(s=(0,$.jsx)(`div`,{className:`flex h-6 w-10 flex-shrink-0 items-center justify-center gap-1`,"aria-hidden":`true`,children:o.map((e,t)=>(0,$.jsx)(`span`,{className:`h-full w-1 rounded-full transition-transform duration-75 ease-out motion-reduce:transition-none`,style:{backgroundColor:r.colors.primary.base,transform:`scaleY(${.25+i*e*.75})`}},t))}),t[1]=r,t[2]=i,t[3]=s):s=t[3],s},Tm=e=>{let t=Oa(e=>e.sttLocalModel),[n,r]=Q.useState(null);return Q.useEffect(()=>{if(!e){r(null);return}let n=!1,i=async()=>{try{let e=await f(`/api/dictation/status`,{query:{provider:`local`,localModel:t}});if(!e.ok||n)return;let i=await e.json(),a=Array.isArray(i?.models)?i.models.find(e=>e.id===t):null;n||r(typeof a?.downloadProgress==`number`?a.downloadProgress:null)}catch{}};i();let a=setInterval(()=>{i()},2e3);return()=>{n=!0,clearInterval(a)}},[e,t]),e?n:null},Em=e=>{let t=(0,pd.c)(86),{radius:n,isMobile:r,footerIconButtonClass:i,footerPaddingClass:a,iconSizeClass:o,sendIconSizeClass:s,disabled:c,onInsert:l,onInsertAndSend:u,onActiveChange:d,onContentHeightChange:f,renderTrigger:p,topAccessory:m}=e,h=p===void 0||p,{t:g}=Yt(),{currentTheme:_}=Ws(),v=Oa(Dm),y=q(Om),b;t[0]===y?b=t[1]:(b=Ls(Os(`toggle_dictation`,y)),t[0]=y,t[1]=b);let x=b,[S]=Q.useState(km),C=Q.useRef(null),w=Q.useRef(l),T=Q.useRef(u),E,D;t[2]!==l||t[3]!==u?(E=()=>{w.current=l,T.current=u},D=[l,u],t[2]=l,t[3]=u,t[4]=E,t[5]=D):(E=t[4],D=t[5]),Q.useEffect(E,D);let O;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(O={onTranscript:e=>{let t=C.current;C.current=null,t===`send`?T.current(e):w.current(e)}},t[6]=O):O=t[6];let{status:k,partialTranscript:A,volume:j,duration:M,error:N,errorReason:P,startDictation:F,confirmDictation:I,cancelDictation:L,retryFailedDictation:R,acceptPartialTranscript:z,discardFailedDictation:B}=Sm(O),V=k===`recording`&&P===`model_download_in_progress`,H=Tm(V),ee=Q.useRef(k),U,te;t[7]===k?(U=t[8],te=t[9]):(U=()=>{ee.current=k},te=[k],t[7]=k,t[8]=U,t[9]=te),Q.useEffect(U,te);let W,ne;t[10]!==d||t[11]!==k?(W=()=>{d?.(k!==`idle`)},ne=[k,d],t[10]=d,t[11]=k,t[12]=W,t[13]=ne):(W=t[12],ne=t[13]),Q.useLayoutEffect(W,ne);let G,re;t[14]!==I||t[15]!==F?(G=()=>{let e=()=>{ee.current===`idle`?F():ee.current===`recording`&&(C.current=`insert`,I())};return window.addEventListener(`openchamber:dictation-toggle`,e),()=>window.removeEventListener(`openchamber:dictation-toggle`,e)},re=[F,I],t[14]=I,t[15]=F,t[16]=G,t[17]=re):(G=t[16],re=t[17]),Q.useEffect(G,re);let ie,K;t[18]!==L||t[19]!==I||t[20]!==k?(ie=()=>{if(k!==`recording`)return;let e=e=>{if(!e.isComposing){if(e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&!e.altKey){e.preventDefault(),e.stopPropagation(),C.current=`insert`,I();return}e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),L())}};return window.addEventListener(`keydown`,e,{capture:!0}),()=>window.removeEventListener(`keydown`,e,{capture:!0})},K=[k,I,L],t[18]=L,t[19]=I,t[20]=k,t[21]=ie,t[22]=K):(ie=t[21],K=t[22]),Q.useEffect(ie,K);let ae=Q.useRef(null),oe=Q.useRef(null),se=Q.useRef(null),[ce,le]=Q.useState(null),ue=k!==`idle`,de=Q.useRef(f),fe,pe;t[23]===f?(fe=t[24],pe=t[25]):(fe=()=>{de.current=f},pe=[f],t[23]=f,t[24]=fe,t[25]=pe),Q.useEffect(fe,pe);let me=Q.useRef(!1),he;t[26]===ue?he=t[27]:(he=()=>{if(!ue){me.current&&(me.current=!1,de.current?.(null));return}let e=oe.current,t=se.current;if(!e||!t)return;let n=window.getComputedStyle(e),r=(parseFloat(n.paddingTop)||0)+(parseFloat(n.paddingBottom)||0);me.current=!0,de.current?.(t.offsetHeight+r),e.scrollTop=e.scrollHeight},t[26]=ue,t[27]=he);let ge;t[28]!==N||t[29]!==ue||t[30]!==A||t[31]!==k?(ge=[ue,A,k,N],t[28]=N,t[29]=ue,t[30]=A,t[31]=k,t[32]=ge):ge=t[32],Q.useLayoutEffect(he,ge);let _e,ve;t[33]===Symbol.for(`react.memo_cache_sentinel`)?(_e=()=>()=>{me.current&&(me.current=!1,de.current?.(null))},ve=[],t[33]=_e,t[34]=ve):(_e=t[33],ve=t[34]),Q.useEffect(_e,ve);let ye,be;if(t[35]===ue?(ye=t[36],be=t[37]):(ye=()=>{if(!ue)return;let e=ae.current?.closest(`[data-chat-input-footer="true"]`);e&&e.offsetHeight>0&&le(e.offsetHeight)},be=[ue],t[35]=ue,t[36]=ye,t[37]=be),Q.useLayoutEffect(ye,be),!S||!v)return null;let xe=k!==`idle`,Se;t[38]===I?Se=t[39]:(Se=e=>{C.current=e,I()},t[38]=I,t[39]=Se);let Ce=Se,we;t[40]===R?we=t[41]:(we=()=>{C.current=`insert`,R()},t[40]=R,t[41]=we);let Te=we,Ee;bb0:{if(k===`failed`){Ee=``;break bb0}if(k===`uploading`){let e;t[42]===g?e=t[43]:(e=g(`chat.dictation.processing`),t[42]=g,t[43]=e),Ee=e;break bb0}if(V){let e;t[44]!==H||t[45]!==g?(e=H===null?g(`chat.dictation.downloadingModel`):g(`chat.dictation.downloadingModelProgress`,{percent:String(H)}),t[44]=H,t[45]=g,t[46]=e):e=t[46],Ee=e;break bb0}let e;t[47]===g?e=t[48]:(e=g(`chat.dictation.listening`),t[47]=g,t[48]=e),Ee=e}let De=Ee,Oe;t[49]===Symbol.for(`react.memo_cache_sentinel`)?(Oe={onMouseDown:Am,onPointerDownCapture:jm},t[49]=Oe):Oe=t[49];let ke=Oe,Ae;t[50]!==x||t[51]!==c||t[52]!==i||t[53]!==o||t[54]!==xe||t[55]!==h||t[56]!==F||t[57]!==g?(Ae=h?(0,$.jsx)(`button`,{type:`button`,...ke,className:i,onClick:()=>{F()},disabled:c||xe,title:x?`${g(`chat.dictation.start`)} (${x})`:g(`chat.dictation.start`),"aria-label":g(`chat.dictation.start`),children:(0,$.jsx)(Z,{name:`mic`,className:Y(o,`text-current`)})}):null,t[50]=x,t[51]=c,t[52]=i,t[53]=o,t[54]=xe,t[55]=h,t[56]=F,t[57]=g,t[58]=Ae):Ae=t[58];let je;t[59]!==z||t[60]!==L||t[61]!==Ce||t[62]!==_||t[63]!==B||t[64]!==M||t[65]!==N||t[66]!==ce||t[67]!==i||t[68]!==a||t[69]!==o||t[70]!==xe||t[71]!==r||t[72]!==V||t[73]!==A||t[74]!==De||t[75]!==n||t[76]!==Te||t[77]!==s||t[78]!==k||t[79]!==g||t[80]!==m||t[81]!==j?(je=xe?(0,$.jsxs)(`div`,{ref:ae,className:Y(`absolute inset-0 z-50 flex flex-col overflow-x-hidden overflow-y-hidden`,r&&`oc-composer-morph-content-fade`),style:{borderRadius:n,backgroundColor:_.colors.surface.subtle},role:`dialog`,"aria-label":g(`chat.dictation.overlayAria`),children:[m,(0,$.jsx)(`div`,{ref:oe,className:Y(`scrollbar-none flex-1 min-h-0 overflow-y-auto px-3`,r?`pt-3.5 pb-2.5`:`pt-5 pb-2`),children:(0,$.jsxs)(`div`,{ref:se,className:Y(!A&&`translate-y-1.5`),children:[A?(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label whitespace-pre-wrap`,style:{color:_.colors.surface.foreground},children:A}):k===`recording`?(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,style:{color:_.colors.surface.mutedForeground},children:[(0,$.jsx)(wm,{volume:j}),(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label`,children:De})]}):(0,$.jsx)(`p`,{className:`typography-markdown md:typography-ui-label`,style:{color:_.colors.surface.mutedForeground},children:De}),k===`failed`?(0,$.jsx)(`p`,{className:`typography-meta mt-1`,style:{color:_.colors.status.error},children:N||g(`chat.dictation.failed`)}):null,k===`recording`&&N&&!V?(0,$.jsx)(`p`,{className:`typography-meta mt-1`,style:{color:_.colors.status.warning},children:N}):null]})}),(0,$.jsxs)(`div`,{className:Y(`flex flex-shrink-0 items-center gap-x-3`,a),style:ce?{height:ce}:void 0,children:[k===`recording`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`relative ml-1 flex h-2 w-2 flex-shrink-0`,"aria-hidden":`true`,children:[(0,$.jsx)(`span`,{className:`absolute inline-flex h-full w-full animate-ping rounded-full opacity-60`,style:{backgroundColor:_.colors.status.error}}),(0,$.jsx)(`span`,{className:`relative inline-flex h-2 w-2 rounded-full`,style:{backgroundColor:_.colors.status.error}})]}),(0,$.jsx)(wm,{volume:j}),(0,$.jsx)(`span`,{className:`typography-meta tabular-nums`,style:{color:_.colors.surface.mutedForeground},children:Cm(M)})]}):k===`uploading`?(0,$.jsx)(Z,{name:`loader-4`,className:`ml-1 h-4 w-4 animate-spin`,style:{color:_.colors.surface.mutedForeground}}):null,(0,$.jsx)(`div`,{className:Y(`ml-auto flex items-center`,r?`gap-x-1`:`gap-x-1.5 md:gap-x-3`),children:k===`recording`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,...ke,className:Y(i,`text-muted-foreground hover:text-foreground`),onClick:()=>{L()},title:g(`chat.dictation.cancel`),"aria-label":g(`chat.dictation.cancel`),children:(0,$.jsx)(Z,{name:`close`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...ke,className:i,onClick:()=>Ce(`insert`),title:g(`chat.dictation.insert`),"aria-label":g(`chat.dictation.insert`),children:(0,$.jsx)(Z,{name:`check`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...ke,className:Y(i,`text-primary hover:text-primary`),onClick:()=>Ce(`send`),title:g(`chat.dictation.insertAndSend`),"aria-label":g(`chat.dictation.insertAndSend`),children:(0,$.jsx)(Z,{name:`send-plane-2`,className:s})})]}):k===`uploading`?(0,$.jsx)(`button`,{type:`button`,...ke,className:Y(i,`text-muted-foreground hover:text-foreground`),onClick:()=>{L()},title:g(`chat.dictation.cancel`),"aria-label":g(`chat.dictation.cancel`),children:(0,$.jsx)(Z,{name:`close`,className:o})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,...ke,className:Y(i,`text-muted-foreground hover:text-foreground`),onClick:B,title:g(`chat.dictation.discard`),"aria-label":g(`chat.dictation.discard`),children:(0,$.jsx)(Z,{name:`close`,className:o})}),(0,$.jsx)(`button`,{type:`button`,...ke,className:i,onClick:Te,title:g(`chat.dictation.retry`),"aria-label":g(`chat.dictation.retry`),children:(0,$.jsx)(Z,{name:`refresh`,className:o})}),A.trim()?(0,$.jsx)(`button`,{type:`button`,...ke,className:i,onClick:()=>{C.current=`insert`,z()},title:g(`chat.dictation.insert`),"aria-label":g(`chat.dictation.insert`),children:(0,$.jsx)(Z,{name:`check`,className:o})}):null]})})]})]}):null,t[59]=z,t[60]=L,t[61]=Ce,t[62]=_,t[63]=B,t[64]=M,t[65]=N,t[66]=ce,t[67]=i,t[68]=a,t[69]=o,t[70]=xe,t[71]=r,t[72]=V,t[73]=A,t[74]=De,t[75]=n,t[76]=Te,t[77]=s,t[78]=k,t[79]=g,t[80]=m,t[81]=j,t[82]=je):je=t[82];let Me;return t[83]!==Ae||t[84]!==je?(Me=(0,$.jsxs)($.Fragment,{children:[Ae,je]}),t[83]=Ae,t[84]=je,t[85]=Me):Me=t[85],Me};function Dm(e){return e.dictationEnabled}function Om(e){return e.shortcutOverrides}function km(){return!ge()&&mm()}function Am(e){return e.preventDefault()}function jm(e){e.pointerType===`touch`&&e.preventDefault()}var Mm=2e3,Nm=ze((e,t)=>({pending:!1,expiresAt:null,arm:(t=Mm)=>{let n=Date.now()+t;return e({pending:!0,expiresAt:n}),n},clear:()=>{!t().pending&&t().expiresAt===null||e({pending:!1,expiresAt:null})}})),Pm=new class{inFlightByScope=new WeakMap;generationByScope=new WeakMap;run(e){let t=this.inFlightByScope.get(e.scope);t||(t=new Map,this.inFlightByScope.set(e.scope,t));let n=t.get(e.key);if(n)return n;let r=this.generationByScope.get(e.scope);r||(r=new Map,this.generationByScope.set(e.scope,r));let i=(r.get(e.key)??0)+1;r.set(e.key,i);let a=e.request(()=>r?.get(e.key)!==i);return t.set(e.key,a),a.finally(()=>{t?.get(e.key)===a&&t.delete(e.key)}).catch(()=>{}),a}},Fm=15e3,Im=100,Lm=new Map,Rm=new Map,zm=e=>`${e.runtimeKey}\n${e.directory}\n${e.sessionID}`,Bm=e=>{let t=zm(e),n=e.now??Date.now(),r=Rm.get(t);if(r&&n-r.loadedAt<Fm)return Promise.resolve(r.sessions);let i=Lm.get(t);if(i)return i;let a=e.request().then(e=>{for(Rm.delete(t);Rm.size>=Im;){let e=Rm.keys().next().value;if(typeof e!=`string`)break;Rm.delete(e)}return Rm.set(t,{loadedAt:Date.now(),sessions:e}),e});return Lm.set(t,a),a.then(()=>{Lm.get(t)===a&&Lm.delete(t)},()=>{Lm.get(t)===a&&Lm.delete(t)}),a},Vm=(e,t)=>e.id<t.id?-1:+(e.id>t.id),Hm=(e,t,n)=>{let r=new Set(e.map(e=>e.id)),i=t.filter(e=>!!e?.id&&!r.has(e.id)&&e.parentID===n);return i.length===0?e:[...e,...i].sort(Vm)},Um=30;function Wm(e){return e===`busy`||e===`retry`}var Gm=new Map;function Km(e,t=!1){return{limit:e.loadedTurns,cursor:e.kind===`has-more`?e.cursor:void 0,complete:e.kind===`exhausted`,loading:t}}function qm(e){if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(e&&typeof e==`object`){let t=e.message;if(typeof t==`string`&&t.length>0)return t}try{return JSON.stringify(e)}catch{return String(e)}}function Jm(e,t){if(!e.error)return;let n=e.response?.status;throw Error(`${t} failed${n?` (${n})`:``}: ${qm(e.error)}`)}function Ym(e,t){let n=Ha();if(!n)return!1;let r=n.getTranscript(En(e,t));return r.messageOrder.length!==0&&r.messageOrder.length>lr()}function Xm(e){return!!e.force||!e.hasSession||e.shouldLoadMessages}function Zm(e,t,n){let r=[...e.getState().session],i=Xi.search(r,t,e=>e.id);i.found?r[i.index]=n:r.splice(i.index,0,n),e.setState({session:r})}function Qm(){let e=la(),t=Br(),n=Kr(),r=(0,Q.useCallback)((t,n=e)=>`${n}\n${t}`,[e]),i=(0,Q.useCallback)((t,n=e)=>{let r=Ha();if(!r||!t)return Km({kind:`unknown`,loadedTurns:0},!1);let i=En(n,t),a=r.getPagination(i),o=r.getRequestState?.(i);return Km(a.boundary,o?.status===`loading`)},[e]),a=(0,Q.useCallback)((e,t)=>{if(t.length===0)return;let r=n.getChild(e);if(!r)return;let i=r.getState(),a={session_status:{...i.session_status},session_status_observed_at:{...i.session_status_observed_at},session_error_at:{...i.session_error_at},session_diff:{...i.session_diff},todo:{...i.todo},permission:{...i.permission},question:{...i.question}};Mr(a,t),xr(r,t),r.setState(a);for(let n of t)Za(e,n)},[n]),o=(0,Q.useCallback)((t=e)=>{let n=Gm.get(t);if(n)return Gm.delete(t),Gm.set(t,n),n;let r=new Set;for(Gm.set(t,r);Gm.size>Um;){let e=Gm.keys().next().value;if(!e)break;let t=[...Gm.get(e)??[]];Gm.delete(e),a(e,t)}return r},[e,a]),s=(0,Q.useCallback)((r,i=e)=>{let s=i===e?t:n.ensureChild(i,{bootstrap:!1}),c=o(i),l=On(s.getState()),u=Zi(),d=Sn({seen:c,keep:r,limit:u,preserve:l});if(a(i,d),ar()){let e=new Set([r,...c,...l]),t=(Ha()?.getCacheBudget?.().listCanonical({directory:i})??[]).map(e=>e.scope.sessionID),n=(t.length>0?t:Array.from(c)).filter(t=>t===r||e.has(t)?!1:Ym(i,t));if(n.length>0){for(let e of n)c.delete(e);a(i,n)}}},[n,e,o,a,t]),c=(0,Q.useCallback)(async(r,i)=>{let a=i?.directory??e;if(!r||!a||a===`global`)return;let o=a===e?t:n.ensureChild(a,{bootstrap:!1}),s=o.getState(),c=s.session_status?.[r],l=s.session_status_observed_at?.[r];try{i?.purpose===`prepend`||i?.before?await Ii(a,r):await Bi(a,r)}catch{return}if(i?.isStale?.())return;let u=Ha()?.getTranscript(En(a,r));Ai({directory:a,sessionID:r,store:o,transcript:u,isStale:i?.isStale}),await pi({directory:a,sessionID:r,store:o,statusBeforePull:c,statusObservedAtBeforePull:l,hasMessages:(u?.messageOrder.length??0)>0,isTailPage:!i?.before,isStale:i?.isStale})},[n,t,e]),l=(0,Q.useCallback)(async(t,i)=>{await dr();let a=typeof i==`boolean`?i:i?.force,o=typeof i==`object`?i.directory??e:e,l=n.ensureChild(o,{bootstrap:!1}),u=it.getScopedSdkClient(o);s(t,o);let d=r(t,o);return Pm.run({scope:l,key:d,request:async e=>{let n=l.getState(),r=Ha(),i=En(o,t),s=r?.hasSession?.(i)??(r?.getTranscript(i).messageOrder.length??0)>0,d=r?.getPagination(i)?.boundary??{kind:`unknown`,loadedTurns:0},f=Xi.search(n.session,t,e=>e.id).found,p=r?.getRequestState?.(i);if(!a&&s&&d.kind!==`unknown`&&p?.status!==`error`&&f&&Mn(o,t)){Ai({directory:o,sessionID:t,store:l,isStale:e});return}let m=!!(a||!s||f),h=Xm({hasSession:f,shouldLoadMessages:m,force:!!a});await Promise.all([h?(async()=>{try{let n=await ki(async()=>{let e=await u.session.get({sessionID:t,directory:o});return Jm(e,`session.get`),e});if(n.data&&!e()){let r=rn(n.data);e()||Zm(l,t,r)}}catch(e){console.error(`[sync] failed to fetch session`,t,e)}})():Promise.resolve(),m?c(t,{isStale:e,directory:o}):Promise.resolve()])}})},[n,r,s,c,e]),d=(0,Q.useCallback)(async(t,r)=>{let i=r||e;if(!t||!i)return;let a=n.ensureChild(i,{bootstrap:!1}),o=it.getScopedSdkClient(i),s=await Bm({runtimeKey:u(),directory:i,sessionID:t,request:async()=>{let e=await o.session.children({sessionID:t,directory:i});return Jm(e,`session.children`),e.data??[]}});a.setState(e=>{let n=Hm(e.session,s,t);return n===e.session?e:{session:n,limit:Math.max(e.limit,n.length)}})},[n,e]),f=(0,Q.useCallback)((t,n)=>{let r=i(t,n?.directory??e);return!r.complete&&!!r.cursor},[e,i]),p=(0,Q.useCallback)((t,n)=>i(t,n?.directory??e).loading,[e,i]),m=(0,Q.useCallback)((t,n)=>i(t,n?.directory??e).complete,[e,i]),h=(0,Q.useCallback)(t=>{let n=t.directory||e;sa(En(n,t.sessionID),{type:`optimistic-add`,message:t.message,parts:t.parts})},[e]),g=(0,Q.useCallback)(t=>{let n=t.directory||e;sa(En(n,t.sessionID),{type:`optimistic-remove`,messageID:t.messageID})},[e]),_=(0,Q.useCallback)(t=>{let n=t.directory||e;sa(En(n,t.sessionID),{type:`optimistic-confirm`,messageID:t.messageID})},[e]),v=(0,Q.useCallback)(async(t,r)=>{if(!t)return;await dr();let i=r?.directory??e;if(!i||i===`global`)return;let a=n.ensureChild(i,{bootstrap:!1}),o=a.getState().session_status?.[t]?.type;if(Wm(o))throw Error(`refresh transcript busy`);try{await Dr(i,t),Ai({directory:i,sessionID:t,store:a})}catch(e){throw e instanceof Error&&e.message===`refresh transcript busy`?e:Error(`refresh transcript failed`)}},[n,e]);return(0,Q.useMemo)(()=>({ensureSessionRenderable:l,syncSession:l,loadChildren:d,hasMore:f,isLoading:p,isComplete:m,refreshSessionTranscript:v,optimistic:{add:h,remove:g,confirm:_}}),[l,d,f,p,m,v,h,g,_])}var $m=e=>e===`diff`||e===`file`||e===`preview-console`||e===`preview-annotation`,eh=e=>e===`original`||e===`modified`,th=e=>{let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.floor(t)):null},nh=e=>{if(!e||typeof e!=`object`)return null;let t=e;if(typeof t.sessionKey!=`string`||t.sessionKey.trim().length===0||!$m(t.source))return null;let n=th(t.startLine),r=th(t.endLine);return!n||!r?null:{id:typeof t.id==`string`&&t.id.trim().length>0?t.id:`icd-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,sessionKey:t.sessionKey,source:t.source,fileLabel:typeof t.fileLabel==`string`?t.fileLabel:`unknown`,startLine:n,endLine:r,side:eh(t.side)?t.side:void 0,code:typeof t.code==`string`?t.code:``,language:typeof t.language==`string`?t.language:`text`,text:typeof t.text==`string`?t.text:``,createdAt:Number.isFinite(t.createdAt)?Number(t.createdAt):Date.now()}},rh=e=>{if(!e||typeof e!=`object`)return{};let t=Object.entries(e),n={};for(let[e,r]of t){if(!Array.isArray(r))continue;let t=r.map(nh).filter(e=>!!e).filter(t=>t.sessionKey===e);t.length>0&&(n[e]=t)}return n},ih=ze()(Ve(Be((e,t)=>({drafts:{},addDraft:t=>{let n=`icd-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,r={...t,id:n,createdAt:Date.now()};return e(e=>{let n=e.drafts[t.sessionKey]??[];return{drafts:{...e.drafts,[t.sessionKey]:[...n,r]}}}),n},updateDraft:(t,n,r)=>{e(e=>{let i=(e.drafts[t]??[]).map(e=>e.id===n?{...e,...r}:e);return{drafts:{...e.drafts,[t]:i}}})},removeDraft:(t,n)=>{e(e=>{let r=(e.drafts[t]??[]).filter(e=>e.id!==n);if(r.length===0){let{[t]:n,...r}=e.drafts;return{drafts:r}}return{drafts:{...e.drafts,[t]:r}}})},clearDrafts:t=>{e(e=>{let{[t]:n,...r}=e.drafts;return{drafts:r}})},getDrafts:e=>t().drafts[e]??[],consumeDrafts:n=>{let r=t().drafts[n]??[];if(r.length===0)return[];let i=[...r].sort((e,t)=>e.createdAt-t.createdAt);return e(e=>{let{[n]:t,...r}=e.drafts;return{drafts:r}}),i},getDraftCount:e=>(t().drafts[e]??[]).length,hasDrafts:e=>(t().drafts[e]??[]).length>0}),{name:`openchamber-inline-comment-drafts`,storage:Ct(),version:1,migrate:e=>!e||typeof e!=`object`?{drafts:{}}:{drafts:rh(e.drafts)}}),{name:`inline-comment-draft-store`}));function ah(e){let{fileLabel:t,startLine:n,endLine:r,side:i,language:a,code:o,text:s}=e;return e.source===`diff`&&i?`Comment on \`${t}\` lines ${n}-${r} (${i}):\n\`\`\`${a}\n${o}\n\`\`\`\n\n${s}`:e.source===`preview-console`?`Attached preview context from \`${t}\`:\n\`\`\`${a}\n${o}\n\`\`\`\n\n${s}`:e.source===`preview-annotation`?s?`${o}\n\n${s}`:o:`Comment on \`${t}\` lines ${n}-${r}:\n\`\`\`${a}\n${o}\n\`\`\`\n\n${s}`}function oh(e){return e.length===0?``:e.every(e=>e.source===`preview-annotation`)?e.map(ah).join(`
|
|
5
5
|
|
|
@@ -6522,7 +6522,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}f
|
|
|
6522
6522
|
`)?`...`:``),R_=(e,t={})=>{let n=L_(e);if(!n)return null;let r=I_(t.composerDocument);return t_(n,{citationIcons:P_(t.attachments),sessionMentions:F_(t.composerDocument),skillNames:r.skillNames,commandNames:r.commandNames,allowPathHeuristics:!0})},z_=e=>{if(!e||typeof e!=`object`)return!1;let t=e;return(t.kind===`edit`||t.kind===`send`||t.kind===`remove`||t.kind===`reorder`)&&typeof t.transportIdentity==`string`&&typeof t.runtimeGeneration==`number`&&Number.isSafeInteger(t.runtimeGeneration)&&t.runtimeGeneration>=0&&typeof t.directory==`string`&&typeof t.sessionID==`string`&&typeof t.scopeID==`string`&&typeof t.queueItemID==`string`&&(t.queueItemIDs===void 0||Array.isArray(t.queueItemIDs)&&t.queueItemIDs.every(e=>typeof e==`string`))},B_=(0,Q.memo)(e=>{let t=(0,pd.c)(132),{message:n,server:r,frozen:i,hasDispatchLock:a,pendingOperationKinds:o,sendPendingTimedOut:s,abortSendPending:c,isMobile:l,onEdit:u,onSend:d,onRemove:f}=e,{t:p}=Yt(),m;t[0]===n?m=t[1]:(m=Wa(n),t[0]=n,t[1]=m);let h=m,g=n.queueItemID||n.id,_;t[2]!==o||t[3]!==r?(_=r&&o.has(`edit`),t[2]=o,t[3]=r,t[4]=_):_=t[4];let v=_,y;t[5]!==o||t[6]!==r?(y=r&&o.has(`remove`),t[5]=o,t[6]=r,t[7]=y):y=t[7];let b=y,x;t[8]!==o||t[9]!==r?(x=r&&o.has(`reorder`),t[8]=o,t[9]=r,t[10]=x):x=t[10];let S=x,C=r||h?void 0:n,w;t[11]!==n||t[12]!==h||t[13]!==r?(w=r&&!h&&x_(n),t[11]=n,t[12]=h,t[13]=r,t[14]=w):w=t[14];let T=w,E;t[15]===C?E=t[16]:(E=C&&b_(C),t[15]=C,t[16]=E);let D=!!E,O;t[17]!==n||t[18]!==h||t[19]!==r?(O=r&&!h&&y_(n),t[17]=n,t[18]=h,t[19]=r,t[20]=O):O=t[20];let k=O,A;t[21]!==T||t[22]!==D||t[23]!==o||t[24]!==r?(A=r&&o.has(`send`)||T||D,t[21]=T,t[22]=D,t[23]=o,t[24]=r,t[25]=A):A=t[25];let j=c||A&&!s,M=i||h,N;t[26]!==i||t[27]!==n?(N=__(n,{frozen:i}),t[26]=i,t[27]=n,t[28]=N):N=t[28];let P=N,F;t[29]!==i||t[30]!==n?(F=v_(n,{frozen:i}),t[29]=i,t[30]=n,t[31]=F):F=t[31];let I=F,L=C?.owner?.state===`unbound-legacy`||M||k,R;t[32]!==M||t[33]!==a||t[34]!==n||t[35]!==j||t[36]!==s||t[37]!==r?(R=!M&&!j&&(r?g_(n,a,{allowManualDispatchRetry:s}):h_(n,a)),t[32]=M,t[33]=a,t[34]=n,t[35]=j,t[36]=s,t[37]=r,t[38]=R):R=t[38];let z=R,B=C?.failure?.recovery,V;t[39]===n?V=t[40]:(V=N_(n),t[39]=n,t[40]=V);let H=V,ee=h?void 0:B?.attachments??n.attachments,U=B?.composerDocument??(`composerDocument`in n?n.composerDocument:void 0),te;t[41]!==L||t[42]!==g?(te={id:g,disabled:L},t[41]=L,t[42]=g,t[43]=te):te=t[43];let{attributes:W,listeners:ne,setNodeRef:G,transform:re,transition:ie,isDragging:K}=Nl(te),ae;t[44]===H?ae=t[45]:(ae=L_(H),t[44]=H,t[45]=ae);let oe=ae,se;t[46]!==ee||t[47]!==U||t[48]!==H?(se=R_(H,{attachments:ee,composerDocument:U}),t[46]=ee,t[47]=U,t[48]=H,t[49]=se):se=t[49];let ce=se,le=h?n.attachmentCount:ee?.length??0,ue;t[50]!==n||t[51]!==f?(ue=()=>f(n),t[50]=n,t[51]=f,t[52]=ue):ue=t[52];let de=!I,fe=b||void 0,pe=l?`h-7 w-3`:`size-7`,me;t[53]===pe?me=t[54]:(me=Y(`inline-flex shrink-0 items-center justify-center bg-transparent text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50`,pe),t[53]=pe,t[54]=me);let he;t[55]===p?he=t[56]:(he=p(`chat.queuedMessage.removeAria`),t[55]=p,t[56]=he);let ge=b?`loader-4`:`delete-bin`,_e=l?`size-3`:`size-3.5`,ve=b&&`animate-spin`,ye;t[57]!==_e||t[58]!==ve?(ye=Y(_e,ve),t[57]=_e,t[58]=ve,t[59]=ye):ye=t[59];let be;t[60]!==ge||t[61]!==ye?(be=(0,$.jsx)(Z,{name:ge,className:ye,"aria-hidden":`true`}),t[60]=ge,t[61]=ye,t[62]=be):be=t[62];let xe;t[63]!==ue||t[64]!==de||t[65]!==fe||t[66]!==me||t[67]!==he||t[68]!==be?(xe=(0,$.jsx)(`button`,{type:`button`,onClick:ue,disabled:de,"aria-busy":fe,className:me,"aria-label":he,children:be}),t[63]=ue,t[64]=de,t[65]=fe,t[66]=me,t[67]=he,t[68]=be,t[69]=xe):xe=t[69];let Se=xe,Ce;t[70]===re?Ce=t[71]:(Ce=Al.Translate.toString(re),t[70]=re,t[71]=Ce);let we;t[72]!==Ce||t[73]!==ie?(we={transform:Ce,transition:ie},t[72]=Ce,t[73]=ie,t[74]=we):we=t[74];let Te=l?`gap-1 py-0.5`:`flex gap-1.5 md:gap-2`,Ee=K&&`z-10 opacity-60`,De;t[75]!==Te||t[76]!==Ee?(De=Y(`flex min-w-0 items-center`,Te,Ee),t[75]=Te,t[76]=Ee,t[77]=De):De=t[77];let Oe=S||void 0,ke=l?`h-7 w-3`:`size-auto`,Ae=L?`cursor-default opacity-50`:`cursor-grab hover:text-foreground active:cursor-grabbing`,je;t[78]!==ke||t[79]!==Ae?(je=Y(`flex flex-shrink-0 touch-none select-none items-center justify-center text-muted-foreground`,ke,`transition-colors`,Ae),t[78]=ke,t[79]=Ae,t[80]=je):je=t[80];let Me;t[81]===p?Me=t[82]:(Me=p(`chat.queuedMessage.reorderAria`),t[81]=p,t[82]=Me);let Ne=S?`loader-4`:`draggable`,Pe=l?`size-3`:`size-3.5`,Fe=S&&`animate-spin`,Ie;t[83]!==Pe||t[84]!==Fe?(Ie=Y(Pe,Fe),t[83]=Pe,t[84]=Fe,t[85]=Ie):Ie=t[85];let Le;t[86]!==Ne||t[87]!==Ie?(Le=(0,$.jsx)(Z,{name:Ne,className:Ie,"aria-hidden":`true`}),t[86]=Ne,t[87]=Ie,t[88]=Le):Le=t[88];let Re;t[89]!==W||t[90]!==L||t[91]!==ne||t[92]!==Oe||t[93]!==je||t[94]!==Me||t[95]!==Le?(Re=(0,$.jsx)(`button`,{type:`button`,...W,...ne,disabled:L,"aria-busy":Oe,className:je,"aria-label":Me,children:Le}),t[89]=W,t[90]=L,t[91]=ne,t[92]=Oe,t[93]=je,t[94]=Me,t[95]=Le,t[96]=Re):Re=t[96];let ze=l?Se:null,Be=l?`text-xs leading-5`:`typography-ui-label leading-5`,Ve;t[97]===Be?Ve=t[98]:(Ve=Y(`flex min-w-0 flex-1 items-baseline overflow-hidden whitespace-nowrap text-foreground`,Be),t[97]=Be,t[98]=Ve);let He;t[99]!==oe||t[100]!==ce||t[101]!==p?(He=ce?ce.map(Y_):oe||p(`chat.queuedMessage.empty`),t[99]=oe,t[100]=ce,t[101]=p,t[102]=He):He=t[102];let Ue;t[103]!==le||t[104]!==p?(Ue=le>0&&(0,$.jsx)(`span`,{className:`ml-1 shrink-0 text-muted-foreground`,children:p(`chat.queuedMessage.attachments`,{count:le})}),t[103]=le,t[104]=p,t[105]=Ue):Ue=t[105];let We;t[106]!==Ve||t[107]!==He||t[108]!==Ue?(We=(0,$.jsxs)(`span`,{className:Ve,children:[He,Ue]}),t[106]=Ve,t[107]=He,t[108]=Ue,t[109]=We):We=t[109];let Ge;t[110]!==P||t[111]!==z||t[112]!==v||t[113]!==l||t[114]!==n||t[115]!==u||t[116]!==d||t[117]!==h||t[118]!==j||t[119]!==p?(Ge=h?(0,$.jsxs)(`span`,{className:Y(`inline-flex items-center gap-1 font-medium text-muted-foreground`,l?`h-7 text-[11px] leading-none`:`h-7 typography-ui-label`),"aria-live":`polite`,"aria-label":p(`chat.queuedMessage.queuingAria`),children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(l?`size-3`:`size-3.5`,`animate-spin`),"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:p(`chat.queuedMessage.queuing`)})]}):j?(0,$.jsxs)(`span`,{className:Y(`inline-flex items-center gap-1 font-medium text-muted-foreground`,l?`h-7 text-[11px] leading-none`:`h-7 typography-ui-label`),"aria-live":`polite`,"aria-label":p(`chat.queuedMessage.sendingAria`),children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(l?`size-3`:`size-3.5`,`animate-spin`),"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:p(`chat.queuedMessage.sending`)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,onClick:()=>u(n),disabled:!P,"aria-busy":v||void 0,"aria-label":p(`chat.queuedMessage.edit`),className:Y(`inline-flex items-center bg-transparent text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50`,l?`h-7 gap-1.5 px-0 text-[11px]`:`h-7 gap-1 px-0.5`),children:[(0,$.jsx)(Z,{name:v?`loader-4`:`edit`,className:Y(l?`size-3`:`size-3.5`,v&&`animate-spin`),"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`font-medium`,l?`leading-none`:`typography-ui-label`),children:p(`chat.queuedMessage.edit`)})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{j||d(n)},disabled:!z||j,"aria-busy":j||void 0,"aria-label":p(`chat.queuedMessage.send`),className:Y(`inline-flex items-center bg-transparent text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50`,l?`h-7 gap-1.5 px-0 text-[11px]`:`h-7 gap-1 px-0.5`),children:[(0,$.jsx)(Z,{name:`send-plane`,className:Y(l?`size-3`:`size-3.5`),"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`font-medium`,l?`leading-none`:`typography-ui-label`),children:p(`chat.queuedMessage.send`)})]})]}),t[110]=P,t[111]=z,t[112]=v,t[113]=l,t[114]=n,t[115]=u,t[116]=d,t[117]=h,t[118]=j,t[119]=p,t[120]=Ge):Ge=t[120];let Ke=!l&&!h?Se:null,qe;t[121]!==Ge||t[122]!==Ke?(qe=(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1.5 text-muted-foreground`,children:[Ge,Ke]}),t[121]=Ge,t[122]=Ke,t[123]=qe):qe=t[123];let Je;return t[124]!==G||t[125]!==we||t[126]!==De||t[127]!==Re||t[128]!==ze||t[129]!==We||t[130]!==qe?(Je=(0,$.jsxs)(`div`,{ref:G,style:we,className:De,children:[Re,ze,We,qe]}),t[124]=G,t[125]=we,t[126]=De,t[127]=Re,t[128]=ze,t[129]=We,t[130]=qe,t[131]=Je):Je=t[131],Je});B_.displayName=`QueuedMessageChip`;var V_=[],H_=[],U_=[],W_=new Set,G_=(e,t)=>t?f_(T(e,E(t.sessionID)),T(e,t)):V_,K_=(e,t)=>{if(!t)return H_;let n=G_(e,t),r=[...K(e,E(t.sessionID)),...K(e,t)];return r.length===0?n:[...n,...r]},q_=(e,t)=>{let n=e.owner;return n?n.state===`unbound-legacy`?n.sessionID===t.sessionID?E(t.sessionID):null:b(n)===b(t)?t:null:null},J_=(0,Q.memo)(e=>{let t=(0,pd.c)(152),{onEditMessage:n,onSendMessage:r,onEditCommitted:i,draftKey:a,scope:o,draftTarget:s,clientPendingItems:c,onRemoveClientPending:l,trailing:u}=e,d=c===void 0?U_:c,{t:f}=Yt(),p=q(X_),m=o?.transportIdentity??``,h=o?.directory??``,g=o?.sessionID??``,_;t[0]!==m||t[1]!==h||t[2]!==g?(_={transportIdentity:m,directory:h,sessionID:g},t[0]=m,t[1]=h,t[2]=g,t[3]=_):_=t[3];let v=_h(_),y;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(y=new Map,t[4]=y):y=t[4];let x=Q.useRef(y);o?.runtimeGeneration,o?.transportIdentity;let S=o?.transportIdentity??``,C=o?.runtimeGeneration??-1,w;t[5]!==S||t[6]!==C?(w=[S,`messageQueue`,`scopeMutation`,C],t[5]=S,t[6]=C,t[7]=w):w=t[7];let T=w,E;t[8]===v.actions?E=t[9]:(E=e=>ni(x,`${e.transportIdentity}\u0000${e.runtimeGeneration}\u0000${e.directory}\u0000${e.sessionID}\u0000${e.scopeID}`,()=>{if(e.transportIdentity!==e.runtime.transportIdentity||e.runtimeGeneration!==e.runtime.generation)return Promise.resolve({status:`stale`});let t=v.actions.captureRuntime();if(t.transportIdentity!==e.runtime.transportIdentity||t.generation!==e.runtime.generation)return Promise.resolve({status:`stale`});switch(e.kind){case`edit`:return v.actions.editIntoDraft(e.input);case`send`:return v.actions.manualSend(e.input);case`remove`:return v.actions.remove(e.input);case`reorder`:return v.actions.reorder(e.input)}throw Error(`Unsupported server queue operation`)}),t[8]=v.actions,t[9]=E);let D,O;t[10]!==v.actions||t[11]!==f?(D=(e,t)=>{let n=v.actions.captureRuntime();n.transportIdentity===t.runtime.transportIdentity&&n.generation===t.runtime.generation&&e.status!==`stale`&&t.kind===`edit`&&e.status!==`committed`&&ro.error(f(`chat.chatInput.toast.queueOperationFailed`))},O=(e,t)=>{let n=v.actions.captureRuntime();n.transportIdentity===t.runtime.transportIdentity&&n.generation===t.runtime.generation&&ro.error(f(e instanceof to&&e.code===`unavailable`?`chat.chatInput.toast.queueOperationStatusUnknown`:`chat.chatInput.toast.queueOperationFailed`))},t[10]=v.actions,t[11]=f,t[12]=D,t[13]=O):(D=t[12],O=t[13]);let A;t[14]!==T||t[15]!==E||t[16]!==D||t[17]!==O?(A={mutationKey:T,mutationFn:E,onSuccess:D,onError:O},t[14]=T,t[15]=E,t[16]=D,t[17]=O,t[18]=A):A=t[18];let j=At(A),M;t[19]===T?M=t[20]:(M={filters:{mutationKey:T,exact:!0,status:`pending`},select:Z_},t[19]=T,t[20]=M);let N=kt(M),P;t[21]===T?P=t[22]:(P={filters:{mutationKey:T,exact:!0,status:`success`},select:Q_},t[21]=T,t[22]=P);let F=kt(P),I;bb0:{if(!o||!v.scope){I=null;break bb0}let e=o.runtimeGeneration??v.runtimeCapture.generation,n;t[23]!==o.directory||t[24]!==o.sessionID||t[25]!==o.transportIdentity||t[26]!==v.scope.scopeID||t[27]!==e?(n={transportIdentity:o.transportIdentity,directory:o.directory,sessionID:o.sessionID,scopeID:v.scope.scopeID,runtimeGeneration:e},t[23]=o.directory,t[24]=o.sessionID,t[25]=o.transportIdentity,t[26]=v.scope.scopeID,t[27]=e,t[28]=n):n=t[28],I=n}let L=I,R;bb1:{if(!L){let e;t[29]===Symbol.for(`react.memo_cache_sentinel`)?(e=[],t[29]=e):e=t[29],R=e;break bb1}let e;if(t[30]!==L||t[31]!==N){let n;t[33]===L?n=t[34]:(n=e=>z_(e)&&e.scopeID===L.scopeID,t[33]=L,t[34]=n),e=T_(N.filter(n),L),t[30]=L,t[31]=N,t[32]=e}else e=t[32];R=e}let z=R,B;t[35]!==L||t[36]!==v.scope?.revision||t[37]!==F?(B=()=>L?E_(F.filter($_),L,v.scope?.revision):[],t[35]=L,t[36]=v.scope?.revision,t[37]=F,t[38]=B):B=t[38],v.scope?.revision;let V;t[39]===B?V=t[40]:(V=B(),t[39]=B,t[40]=V);let H=V,ee;t[41]!==H||t[42]!==z?(ee=[...z,...H],t[41]=H,t[42]=z,t[43]=ee):ee=t[43];let U=ee,te;t[44]===o?te=t[45]:(te=e=>K_(e,o),t[44]=o,t[45]=te);let W=k(te);Q.useSyncExternalStore(jn,ir,ir);let ne;t[46]!==U||t[47]!==W||t[48]!==v.items||t[49]!==v.mode?(ne=v.mode===`server`?k_(v.items,U):W,t[46]=U,t[47]=W,t[48]=v.items,t[49]=v.mode,t[50]=ne):ne=t[50];let G=ne,re;t[51]!==G||t[52]!==d?(re=d.length===0?G:[...G,...d],t[51]=G,t[52]=d,t[53]=re):re=t[53];let ie=re,K;t[54]!==o?.sessionID||t[55]!==ie?(K=()=>{let e=o?.sessionID,t=new Set;if(!e)return t;for(let n of ie){let r=n.queueItemID||n.id;r&&sr(e,r)&&t.add(r)}return t},t[54]=o?.sessionID,t[55]=ie,t[56]=K):K=t[56],o?.sessionID;let ae;t[57]===K?ae=t[58]:(ae=K(),t[57]=K,t[58]=ae);let oe=ae,se;if(t[59]!==U){se=new Map;for(let e of U){let t=se.get(e.queueItemID)??new Set;t.add(e.kind),se.set(e.queueItemID,t)}t[59]=U,t[60]=se}else se=t[60];let ce=se,le;if(t[61]!==U||t[62]!==ie||t[63]!==v.mode){bb2:{let e=new Set;if(v.mode===`server`){for(let t of U)t.kind===`send`&&e.add(t.queueItemID);for(let t of ie){if(Wa(t))continue;let n=t.queueItemID;n&&x_(t)&&e.add(n)}le=e;break bb2}for(let t of ie){if(Wa(t))continue;let n=t;b_(n)&&e.add(n.queueItemID||n.id)}le=e}t[61]=U,t[62]=ie,t[63]=v.mode,t[64]=le}else le=t[64];let de=le,[fe,pe]=Q.useState(ev),me;t[65]===Symbol.for(`react.memo_cache_sentinel`)?(me=new Map,t[65]=me):me=t[65];let he=Q.useRef(me),ge,_e;t[66]!==de||t[67]!==fe?(ge=()=>{let e=he.current,t=Date.now();for(let t of[...e.keys()])de.has(t)||e.delete(t);pe(e=>{let t=!1,n=new Set;for(let r of e)de.has(r)?n.add(r):t=!0;return t?n:e});let n=[];for(let r of de){if(e.has(r)||(e.set(r,t),pe(e=>{if(!e.has(r))return e;let t=new Set(e);return t.delete(r),t})),fe.has(r))continue;let i=C_-(t-(e.get(r)??t));if(i<=0){pe(e=>{if(e.has(r))return e;let t=new Set(e);return t.add(r),t});continue}n.push(setTimeout(()=>{he.current.has(r)&&pe(e=>{if(e.has(r))return e;let t=new Set(e);return t.add(r),t})},i))}return()=>{for(let e of n)clearTimeout(e)}},_e=[de,fe],t[66]=de,t[67]=fe,t[68]=ge,t[69]=_e):(ge=t[68],_e=t[69]),Q.useEffect(ge,_e);let ve;t[70]===v.mode?ve=t[71]:(ve=d_(v.mode),t[70]=v.mode,t[71]=ve);let ye=!ve,be=Vr(o),xe;t[72]!==be||t[73]!==ie||t[74]!==v.mode?(xe=v.mode===`server`?!1:be||ie.some(tv),t[72]=be,t[73]=ie,t[74]=v.mode,t[75]=xe):xe=t[75];let Se=xe,Ce=k(nv),we;t[76]===Symbol.for(`react.memo_cache_sentinel`)?(we={activationConstraint:{distance:8}},t[76]=we):we=t[76];let Te;t[77]===Symbol.for(`react.memo_cache_sentinel`)?(Te={activationConstraint:{delay:200,tolerance:6}},t[77]=Te):Te=t[77];let Ee=kl(Sl(Dl,we),Sl(wl,Te)),De;t[78]!==ye||t[79]!==o||t[80]!==ie||t[81]!==Ce||t[82]!==j||t[83]!==v.actions||t[84]!==v.mode||t[85]!==v.scope?(De=e=>{if(ye)return;let{active:t,over:n}=e;if(!n||t.id===n.id)return;if(v.mode===`server`){if(!o||!v.scope)return;let e=ie,r=e.find(e=>e.queueItemID===t.id),i=e.find(e=>e.queueItemID===n.id);if(!r||!i||Wa(r)||Wa(i)||y_(r)||y_(i))return;let a=v.scope,s=v.actions.captureRuntime();if(s.transportIdentity!==o.transportIdentity||s.generation!==o.runtimeGeneration)return;let c=ue(),l=M_(a,String(t.id),String(n.id),c,e);if(!l)return;j.mutateAsync({kind:`reorder`,transportIdentity:s.transportIdentity,directory:a.directory,sessionID:a.sessionID,scopeID:a.scopeID,queueItemID:String(t.id),queueItemIDs:l.queueItemIDs,requestID:c,runtime:s,runtimeGeneration:s.generation,input:l}).catch(rv);return}let r=ie.filter(iv),i=r.find(e=>(e.queueItemID??e.id)===t.id),a=r.find(e=>(e.queueItemID??e.id)===n.id);if(!i||!a||!o)return;let s=q_(i,o),c=q_(a,o);!s||!c||b(s)!==b(c)||Ce(s,String(t.id),String(n.id),i.operationID)},t[78]=ye,t[79]=o,t[80]=ie,t[81]=Ce,t[82]=j,t[83]=v.actions,t[84]=v.mode,t[85]=v.scope,t[86]=De):De=t[86];let Oe=J(De),ke;t[87]!==a||t[88]!==s||t[89]!==ye||t[90]!==i||t[91]!==n||t[92]!==o||t[93]!==j||t[94]!==v.actions||t[95]!==v.mode||t[96]!==v.scope?(ke=e=>{if(ye||Wa(e))return;if(v.mode===`server`){if(!o||!v.scope||!a||!s)return;let t=e,n=s.expectedRevision(),r=v.scope,c=v.actions.captureRuntime();if(c.transportIdentity!==o.transportIdentity||c.generation!==o.runtimeGeneration)return;j.mutateAsync({kind:`edit`,transportIdentity:c.transportIdentity,directory:r.directory,sessionID:r.sessionID,scopeID:r.scopeID,queueItemID:t.queueItemID,requestID:ue(),runtime:c,runtimeGeneration:c.generation,input:j_(r,t,s.key,n)}).then(e=>{(e.status===`committed`||`draftDurable`in e&&e.draftDurable)&&i?.()}).catch(av);return}if(!o)return;let t=e,r=q_(t,o);if(!r)return;let c=t.queueItemID??t.id,l=t.operationID,u=m_(t);(async()=>{let e;try{e=await Promise.resolve(n(u.content,u.attachments,u.composerDocument,u.composerMentions))}catch{e=!1}e&&(i?.(),k.getState().removeFromQueue(r,c,l))})()},t[87]=a,t[88]=s,t[89]=ye,t[90]=i,t[91]=n,t[92]=o,t[93]=j,t[94]=v.actions,t[95]=v.mode,t[96]=v.scope,t[97]=ke):ke=t[97];let Ae=J(ke),je;t[98]!==ye||t[99]!==r||t[100]!==o||t[101]!==j||t[102]!==v.actions||t[103]!==v.mode||t[104]!==v.scope?(je=e=>{if(ye||Wa(e))return;if(v.mode===`server`){if(!o||!v.scope)return;let t=e,n=v.scope,r=v.actions.captureRuntime();if(r.transportIdentity!==o.transportIdentity||r.generation!==o.runtimeGeneration)return;let i=t.queueItemID;he.current.delete(i),pe(e=>{if(!e.has(i))return e;let t=new Set(e);return t.delete(i),t});let a=ue();j.mutateAsync({kind:`send`,transportIdentity:r.transportIdentity,directory:n.directory,sessionID:n.sessionID,scopeID:n.scopeID,queueItemID:t.queueItemID,requestID:a,runtime:r,runtimeGeneration:r.generation,input:A_(n,t,a)}).catch(ov);return}if(!o)return;let t=e;if(!q_(t,o))return;let n=t.queueItemID??t.id;he.current.delete(n),pe(e=>{if(!e.has(n))return e;let t=new Set(e);return t.delete(n),t}),r(n)},t[98]=ye,t[99]=r,t[100]=o,t[101]=j,t[102]=v.actions,t[103]=v.mode,t[104]=v.scope,t[105]=je):je=t[105];let Me=J(je),Ne;t[106]!==d||t[107]!==ye||t[108]!==l||t[109]!==o||t[110]!==j||t[111]!==v.actions||t[112]!==v.mode||t[113]!==v.scope?(Ne=e=>{if(Wa(e)){d.some(t=>t.requestID===e.requestID)&&l?.(e.requestID);return}if(ye)return;if(v.mode===`server`){if(!o||!v.scope)return;let t=e,n=v.scope,r=v.actions.captureRuntime();if(r.transportIdentity!==o.transportIdentity||r.generation!==o.runtimeGeneration)return;let i=ue();j.mutateAsync({kind:`remove`,transportIdentity:r.transportIdentity,directory:n.directory,sessionID:n.sessionID,scopeID:n.scopeID,queueItemID:t.queueItemID,requestID:i,runtime:r,runtimeGeneration:r.generation,input:A_(n,t,i)}).catch(sv);return}if(!o)return;let t=e,n=q_(t,o);n&&k.getState().removeFromQueue(n,t.queueItemID??t.id,t.operationID)},t[106]=d,t[107]=ye,t[108]=l,t[109]=o,t[110]=j,t[111]=v.actions,t[112]=v.mode,t[113]=v.scope,t[114]=Ne):Ne=t[114];let Pe=J(Ne),Fe=ie.length>0&&(o||d.length>0);if(!Fe&&!u)return null;let Ie=p?`px-2`:`px-4`,Le;t[115]===Ie?Le=t[116]:(Le=Y(`oc-composer-queue relative z-0 -mb-5 w-full`,Ie),t[115]=Ie,t[116]=Le);let Re=p?`rounded-[1.25rem]`:`rounded-3xl`,ze;t[117]===Re?ze=t[118]:(ze=Y(`overflow-hidden border border-border/60 bg-[var(--surface-subtle)] text-foreground`,Re),t[117]=Re,t[118]=ze);let Be=p?`px-1.5 py-1`:`gap-0.5 px-3 pb-1 pt-1.5`,Ve;t[119]===Be?Ve=t[120]:(Ve=Y(`flex flex-col`,Be),t[119]=Be,t[120]=Ve);let He;t[121]!==oe||t[122]!==ye||t[123]!==Oe||t[124]!==Ae||t[125]!==Pe||t[126]!==Me||t[127]!==Se||t[128]!==Fe||t[129]!==p||t[130]!==ce||t[131]!==ie||t[132]!==fe||t[133]!==Ee||t[134]!==v.mode?(He=Fe?(0,$.jsx)(Ol,{sensors:Ee,collisionDetection:El,onDragEnd:Oe,children:(0,$.jsx)(Fl,{items:ie.map(cv),strategy:Pl,children:ie.map(e=>{let t=e.queueItemID||e.id;return(0,$.jsx)(B_,{message:e,server:v.mode===`server`,frozen:ye,hasDispatchLock:Se,pendingOperationKinds:ce.get(t)??W_,sendPendingTimedOut:fe.has(t),abortSendPending:oe.has(t),isMobile:p,onEdit:Ae,onSend:Me,onRemove:Pe},t)})})}):null,t[121]=oe,t[122]=ye,t[123]=Oe,t[124]=Ae,t[125]=Pe,t[126]=Me,t[127]=Se,t[128]=Fe,t[129]=p,t[130]=ce,t[131]=ie,t[132]=fe,t[133]=Ee,t[134]=v.mode,t[135]=He):He=t[135];let Ue;t[136]!==Fe||t[137]!==u?(Ue=u?(0,$.jsxs)($.Fragment,{children:[Fe?(0,$.jsx)(`div`,{"aria-hidden":`true`,className:`my-0.5 border-t border-border/40`}):null,u]}):null,t[136]=Fe,t[137]=u,t[138]=Ue):Ue=t[138];let We;t[139]!==Ve||t[140]!==He||t[141]!==Ue?(We=(0,$.jsxs)(`div`,{"data-oc-queue-card-body":``,className:Ve,children:[He,Ue]}),t[139]=Ve,t[140]=He,t[141]=Ue,t[142]=We):We=t[142];let Ge=p?`h-4`:`h-5`,Ke;t[143]===Ge?Ke=t[144]:(Ke=(0,$.jsx)(`div`,{"data-oc-queue-composer-overlap":``,"aria-hidden":`true`,className:Ge}),t[143]=Ge,t[144]=Ke);let qe;t[145]!==ze||t[146]!==We||t[147]!==Ke?(qe=(0,$.jsxs)(`div`,{"data-oc-queue-card":``,className:ze,children:[We,Ke]}),t[145]=ze,t[146]=We,t[147]=Ke,t[148]=qe):qe=t[148];let Je;return t[149]!==Le||t[150]!==qe?(Je=(0,$.jsx)(`div`,{className:Le,children:qe}),t[149]=Le,t[150]=qe,t[151]=Je):Je=t[151],Je});J_.displayName=`QueuedMessageChips`;function Y_(e,t){return e.type===`text`?(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:e.text},`text-${t}`):(0,$.jsx)(l_,{decoration:e.decoration,interactive:!1},`ref-${t}-${e.span.start}`)}function X_(e){return e.isMobile}function Z_(e){return e.state.variables}function Q_(e){let t=e.state.variables;if(!z_(t)||t.kind!==`send`)return;let n=e.state.data;if(!n||n.status!==`committed`)return;let r=`committedRevision`in n&&typeof n.committedRevision==`number`&&Number.isSafeInteger(n.committedRevision)?n.committedRevision:void 0,i=`scope`in n&&n.scope&&typeof n.scope.revision==`number`&&Number.isSafeInteger(n.scope.revision)?n.scope.revision:void 0,a=r??i;if(!(a===void 0||a<=0))return{...t,kind:`send`,committedRevision:a}}function $_(e){return e!==void 0}function ev(){return new Set}function tv(e){return!Wa(e)&&(e.status===`sending`||e.status===`reconciling`)}function nv(e){return e.reorderQueue}function rv(){}function iv(e){return!Wa(e)}function av(){}function ov(){}function sv(){}function cv(e){return e.queueItemID||e.id}var lv=[0,200,400],uv=e=>{let t=(0,pd.c)(5),{className:n}=e,r;t[0]===n?r=t[1]:(r=Y(`inline-flex`,n),t[0]=n,t[1]=r);let i;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(i=lv.map(dv),t[2]=i):i=t[2];let a;return t[3]===r?a=t[4]:(a=(0,$.jsxs)($.Fragment,{children:[`\xA0`,(0,$.jsx)(`span`,{className:r,"aria-hidden":`true`,children:i})]}),t[3]=r,t[4]=a),a};function dv(e){return(0,$.jsx)(`span`,{className:`animate-busy-pulse`,style:{animationDelay:`${e}ms`},children:`.`},e)}var fv=(0,Q.memo)(()=>{let e=(0,pd.c)(55),{t}=Yt(),n=X(pv),r;e[0]===n?r=e[1]:(r=e=>{if(!n)return null;let t=e.runsByOriginalSessionID[n]??null;return t?.runtimeKey===u()?t:null},e[0]=n,e[1]=r);let i=Yr(r),a=Yr(mv),o=q(hv),s=q(gv);if(!n||!i||i.status!==`running`)return null;let c;e[2]!==i.phase||e[3]!==t?(c=i.phase===`waiting_for_reviewer`?t(`chat.autoReview.status.waitingForReviewer`):t(`chat.autoReview.status.waitingForImplementer`),e[2]=i.phase,e[3]=t,e[4]=c):c=e[4];let l=c,d;e[5]!==o||e[6]!==i.directory||e[7]!==i.reviewSessionID||e[8]!==t?(d=()=>{o(i.directory,{mode:`chat`,dedupeKey:`session:${i.reviewSessionID}`,label:t(`chat.autoReview.reviewSessionLabel`),readOnly:!0})},e[5]=o,e[6]=i.directory,e[7]=i.reviewSessionID,e[8]=t,e[9]=d):d=e[9];let f=d,p=s?`pb-1 text-xs`:`pb-2`,m;e[10]===p?m=e[11]:(m=Y(`w-full px-1`,p),e[10]=p,e[11]=m);let h=s?`rounded-lg`:`rounded-xl`,g;e[12]===h?g=e[13]:(g=Y(`border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm dark:shadow-none overflow-hidden`,h),e[12]=h,e[13]=g);let _=s?`gap-1.5 px-2 py-1`:`gap-2 px-3 py-2`,v;e[14]===_?v=e[15]:(v=Y(`flex w-full items-center text-left`,_),e[14]=_,e[15]=v);let y=s?`size-3.5`:`size-4`,b;e[16]===y?b=e[17]:(b=Y(`animate-spin text-muted-foreground`,y),e[16]=y,e[17]=b);let x;e[18]===b?x=e[19]:(x=(0,$.jsx)(Z,{name:`loader-4`,className:b,"aria-hidden":`true`}),e[18]=b,e[19]=x);let S;e[20]===t?S=e[21]:(S=t(`chat.autoReview.title`),e[20]=t,e[21]=S);let C;e[22]===Symbol.for(`react.memo_cache_sentinel`)?(C=(0,$.jsx)(uv,{}),e[22]=C):C=e[22];let w;e[23]===S?w=e[24]:(w=(0,$.jsxs)(`span`,{className:`typography-ui-label font-medium text-foreground`,children:[S,C]}),e[23]=S,e[24]=w);let T;e[25]===l?T=e[26]:(T=(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground`,children:l}),e[25]=l,e[26]=T);let E;e[27]!==w||e[28]!==T?(E=(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[w,T]}),e[27]=w,e[28]=T,e[29]=E):E=e[29];let D;e[30]===t?D=e[31]:(D=t(`chat.autoReview.actions.open`),e[30]=t,e[31]=D);let O;e[32]!==f||e[33]!==D?(O=(0,$.jsx)(Qt,{type:`button`,variant:`secondary`,size:`xs`,onClick:f,children:D}),e[32]=f,e[33]=D,e[34]=O):O=e[34];let k;e[35]!==n||e[36]!==a?(k=()=>a(n),e[35]=n,e[36]=a,e[37]=k):k=e[37];let A;e[38]===t?A=e[39]:(A=t(`chat.autoReview.actions.stop`),e[38]=t,e[39]=A);let j;e[40]!==k||e[41]!==A?(j=(0,$.jsx)(Qt,{type:`button`,variant:`secondary`,size:`xs`,onClick:k,children:A}),e[40]=k,e[41]=A,e[42]=j):j=e[42];let M;e[43]!==x||e[44]!==E||e[45]!==O||e[46]!==j||e[47]!==v?(M=(0,$.jsxs)(`div`,{className:v,children:[x,E,O,j]}),e[43]=x,e[44]=E,e[45]=O,e[46]=j,e[47]=v,e[48]=M):M=e[48];let N;e[49]!==M||e[50]!==g?(N=(0,$.jsx)(`div`,{className:g,children:M}),e[49]=M,e[50]=g,e[51]=N):N=e[51];let P;return e[52]!==N||e[53]!==m?(P=(0,$.jsx)(`div`,{className:m,children:N}),e[52]=N,e[53]=m,e[54]=P):P=e[54],P});fv.displayName=`AutoReviewBanner`;function pv(e){return e.currentSessionId}function mv(e){return e.stopRun}function hv(e){return e.openContextPanelTab}function gv(e){return e.isMobile}var _v=Q.forwardRef(({searchQuery:e,onSkillSelect:t,onClose:n,directory:r,style:i,onRowsChange:a},o)=>{let s=Q.useRef(null),c=q(e=>e.isMobile),[l,u]=Q.useState(0),d=Q.useRef(0),f=Q.useRef(!1),[p,m]=Q.useState([]),h=Q.useRef([]),g=Q.useRef(null),_=hi({directory:r}),v=Q.useMemo(()=>_.data??[],[_.data]);Q.useEffect(()=>{m(Bp(v,e)),u(0)},[v,e]),Q.useEffect(()=>{d.current=l},[l]),Q.useEffect(()=>{h.current[l]?.scrollIntoView({block:`nearest`})},[l]),Q.useEffect(()=>{let e=e=>{let t=e.target;!t||!s.current||s.current.contains(t)||n()};return document.addEventListener(`pointerdown`,e,!0),()=>{document.removeEventListener(`pointerdown`,e,!0)}},[n]),Q.useEffect(()=>{mc(a,g,{rows:dc(p),highlightedIndex:l})},[p,a,l]);let y=Q.useRef(a);y.current=a,Q.useEffect(()=>()=>{uc(y.current,g)},[]),Q.useImperativeHandle(o,()=>({acceptIndex:e=>{let n=p[e];n&&t(n)},handleKeyDown:e=>{if(e===`Escape`){n();return}if(p.length){if(e===`ArrowDown`){f.current=!0,u(e=>(e+1)%p.length);return}if(e===`ArrowUp`){f.current=!0,u(e=>(e-1+p.length)%p.length);return}if(e===`Enter`||e===`Tab`){let e=(d.current%p.length+p.length)%p.length,n=p[e];n&&t(n)}}}}),[p,t,n]);let b=(e,n)=>{let r=e.scope===`project`,i=e.source||`opencode`;return(0,$.jsx)(`div`,{ref:e=>{h.current[n]=e},className:Y(`flex gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label`,c?`items-center`:`items-start`,Bc(c,n===l)),onClick:()=>t(e),onMouseMove:()=>{f.current=!1,u(n)},children:(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`font-semibold truncate`,children:e.name}),(0,$.jsx)(`span`,{className:Y(`text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 transition-colors`,r?`bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]`:`bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]`),children:e.scope}),(0,$.jsx)(`span`,{className:`text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 bg-[var(--surface-muted)] text-muted-foreground border-[var(--interactive-border)]/60`,children:i})]}),e.description&&!c&&(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mt-0.5 truncate`,children:e.description})]})},`${e.name}-${e.scope}`)};return(0,$.jsxs)(Rc,{ref:s,isMobile:c,className:`max-w-[450px] max-h-60`,style:i,children:[(0,$.jsx)(bl,{preventOverscroll:!0,outerClassName:`flex-1 min-h-0`,className:`px-0 pb-2`,children:p.length?(0,$.jsx)(`div`,{children:p.map((e,t)=>b(e,t))}):(0,$.jsx)(`div`,{className:`px-3 py-2 typography-ui-label text-muted-foreground`,children:`No skills found`})}),!c&&(0,$.jsx)(`div`,{className:`px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground`,children:`↑↓ navigate • Enter select • Esc close`})]})});_v.displayName=`SkillAutocomplete`;function vv(e){let t=(0,pd.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`pointer-events-none inline-flex h-5 min-w-5 shrink-0 select-none items-center justify-center`,`rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)]`,`px-1.5 font-mono typography-micro font-medium leading-none normal-case`,`text-[var(--surface-muted-foreground)] whitespace-nowrap`,`shadow-[inset_0_-1px_0_0_rgba(0,0,0,0.12)]`,`dark:shadow-[inset_0_-1px_0_0_rgba(255,255,255,0.08)]`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,$.jsx)(`kbd`,{"data-slot":`kbd`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function yv(e){let t=(0,pd.c)(15),{shortcut:n,className:r,tone:i}=e,a=i===void 0?`default`:i,o,s,c,l;if(t[0]!==r||t[1]!==n||t[2]!==a){l=Symbol.for(`react.early_return_sentinel`);bb0:{let e=n.split(`+`).map(bv).filter(Boolean);if(e.length===0){l=null;break bb0}o=`shortcut-kbd`,t[7]===r?s=t[8]:(s=Y(`inline-flex items-center gap-1 whitespace-nowrap normal-case`,r),t[7]=r,t[8]=s);let i;t[9]===a?i=t[10]:(i=(e,t)=>(0,$.jsxs)(Q.Fragment,{children:[t>0?(0,$.jsx)(`span`,{className:`typography-micro font-semibold text-[var(--surface-muted-foreground)]`,children:`+`}):null,(0,$.jsx)(vv,{className:Y(a===`selection`&&`border-[var(--interactive-selection)] bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]`),children:/^[a-z]$/i.test(e)?e.toUpperCase():e})]},`${e}-${t}`),t[9]=a,t[10]=i),c=e.map(i)}t[0]=r,t[1]=n,t[2]=a,t[3]=o,t[4]=s,t[5]=c,t[6]=l}else o=t[3],s=t[4],c=t[5],l=t[6];if(l!==Symbol.for(`react.early_return_sentinel`))return l;let u;return t[11]!==o||t[12]!==s||t[13]!==c?(u=(0,$.jsx)(`span`,{"data-slot":o,className:s,children:c}),t[11]=o,t[12]=s,t[13]=c,t[14]=u):u=t[14],u}function bv(e){return e.trim()}var xv=e=>e===`full`||e===`allow`?{text:`var(--status-info)`,border:`color-mix(in srgb, var(--status-info) 25%, transparent)`,background:`color-mix(in srgb, var(--status-info) 4%, transparent)`,borderWidth:1.5}:null,Sv=1e3,Cv=e=>{let t=(0,pd.c)(24),{name:n,label:r,revealed:i,avatarSize:a,slotClassName:o,colorVar:s}=e,c;t[0]===o?c=t[1]:(c=Y(`inline-flex shrink-0 items-center justify-center`,o),t[0]=o,t[1]=c);let l=i?void 0:r,u;t[2]!==a||t[3]!==n||t[4]!==l?(u=(0,$.jsx)(vo,{name:n,size:a,label:l}),t[2]=a,t[3]=n,t[4]=l,t[5]=u):u=t[5];let d;t[6]!==c||t[7]!==u?(d=(0,$.jsx)(`span`,{className:c,children:u}),t[6]=c,t[7]=u,t[8]=d):d=t[8];let f=i?`grid-cols-[1fr] opacity-100`:`grid-cols-[0fr] opacity-0`,p;t[9]===f?p=t[10]:(p=Y(`grid min-w-0 items-center ease-in-out`,f),t[9]=f,t[10]=p);let m;t[11]===Symbol.for(`react.memo_cache_sentinel`)?(m={transitionProperty:`grid-template-columns, opacity`,transitionDuration:`280ms`,transitionTimingFunction:`ease-in-out`},t[11]=m):m=t[11];let h=!i,g;t[12]===s?g=t[13]:(g=s?{color:`var(${s})`}:void 0,t[12]=s,t[13]=g);let _;t[14]!==r||t[15]!==g?(_=(0,$.jsx)(`span`,{className:`flex min-w-0 items-center overflow-hidden`,children:(0,$.jsx)(`span`,{className:`inline-block whitespace-nowrap pl-1.5 pr-0.5 typography-micro leading-none font-medium`,style:g,children:r})}),t[14]=r,t[15]=g,t[16]=_):_=t[16];let v;t[17]!==_||t[18]!==p||t[19]!==h?(v=(0,$.jsx)(`span`,{className:p,style:m,"aria-hidden":h,children:_}),t[17]=_,t[18]=p,t[19]=h,t[20]=v):v=t[20];let y;return t[21]!==v||t[22]!==d?(y=(0,$.jsxs)($.Fragment,{children:[d,v]}),t[21]=v,t[22]=d,t[23]=y):y=t[23],y};function wv(e){let t=(0,pd.c)(5),[n,r]=Q.useState(!1),i=Q.useRef(void 0),a=Q.useRef(!1),o=Q.useRef(null),s,c;t[0]===e?(s=t[1],c=t[2]):(s=()=>{if(!a.current){a.current=!0,i.current=e;return}if(e===i.current)return;let t=i.current;if(i.current=e,!t||!e){r(!1);return}return r(!0),o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{r(!1),o.current=null},Sv),()=>{o.current&&=(clearTimeout(o.current),null)}},c=[e],t[0]=e,t[1]=s,t[2]=c),Q.useEffect(s,c);let l,u;return t[3]===Symbol.for(`react.memo_cache_sentinel`)?(l=()=>()=>{o.current&&clearTimeout(o.current)},u=[],t[3]=l,t[4]=u):(l=t[3],u=t[4]),Q.useEffect(l,u),n}var Tv=`oc-tool-row -mx-2 rounded-lg px-2 py-0.5 cursor-pointer`,Ev=e=>`flow-root ${e?`py-1`:`py-1.5`}`,Dv=e=>`relative ml-2 flex flex-col pl-3 ${e?`gap-1 pt-1`:`gap-1.5 pt-1.5`}`,Ov=`${Tv} hover:bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)]`,kv=`hover:!bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] data-[popup-open]:!bg-[color-mix(in_srgb,var(--surface-foreground)_10%,transparent)] data-[state=open]:!bg-[color-mix(in_srgb,var(--surface-foreground)_10%,transparent)]`,Av=`inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1 ${kv}`,jv=`rounded-md ${kv}`,Mv=()=>{if(!(typeof window>`u`))return window.__zustand_config_store__},Nv=e=>{if(e)try{let t=Mv();if(t?.getState)return t.getState().agents?.find?.(t=>t.name===e)}catch{}},Pv=(e,t)=>{if(!e||e.length===0)return`ask`;for(let n=e.length-1;n>=0;--n){let r=e[n];if(r.permission===t&&r.pattern===`*`)return r.action}for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.permission===`*`&&n.pattern===`*`)return n.action}return`ask`},Fv=e=>{let t=Nv(e);return t?Pv(t.permission,`edit`):`ask`},Iv=e=>{if(!e||typeof e!=`object`)return 0;let t=e.input??0,n=e.output??0,r=e.reasoning??0,i=e.cache&&typeof e.cache==`object`?e.cache.read??0:0,a=e.cache&&typeof e.cache==`object`?e.cache.write??0:0;return t+n+r+i+a},Lv=e=>{let t=e.info.tokens;if(typeof t==`number`)return t;if(t&&typeof t==`object`)return Iv(t);let n=e.parts.find(e=>e.tokens!==void 0);return!n||n.tokens===void 0?0:typeof n.tokens==`number`?n.tokens:Iv(n.tokens)},Rv=e=>{if(!e||typeof e!=`object`)return{percent:0,hasInput:!1};let t=e.input??0,n=e.cache&&typeof e.cache==`object`?e.cache.read??0:0,r=e.cache&&typeof e.cache==`object`?e.cache.write??0:0,i=t+n+r;return i<=0?{percent:0,hasInput:!1}:{percent:Math.min(100,Math.max(0,Math.max(0,n)/i*100)),hasInput:!0}},zv=(e,t,n)=>{let r=Number.isFinite(t)?Math.max(t,0):0,i=Number.isFinite(n)&&n>0,a=i?Math.max(n,0):0,o=Math.min(Math.min(i?a:32e3,32e3),r),s=r>0?Math.max(r-o,1):0,c=s>0?e/s*100:0;return{percentage:Math.min(c,100),contextLimit:r,outputLimit:a,thresholdLimit:s||1,normalizedOutput:o}},Bv=[`ask`,`allow`,`full`],Vv=`__global__`,Hv=ze()(Ve(Be((e,t)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>`u`,saveSessionModelSelection:(t,n,r)=>{e(e=>{let i=new Map(e.sessionModelSelections);return i.set(t,{providerId:n,modelId:r}),{sessionModelSelections:i}})},getSessionModelSelection:e=>{let{sessionModelSelections:n}=t();return n.get(e)||null},saveSessionAgentSelection:(t,n)=>{e(e=>{let r=new Map(e.sessionAgentSelections);r.set(t,n);let i=new Map(e.currentAgentContext);return i.set(t,n),{sessionAgentSelections:r,currentAgentContext:i}})},getSessionAgentSelection:e=>{let{sessionAgentSelections:n}=t();return n.get(e)||null},saveAgentModelForSession:(t,n,r,i)=>{e(e=>{let a=new Map(e.sessionAgentModelSelections),o=a.get(t);return o=o?new Map(o):new Map,o.set(n,{providerId:r,modelId:i}),a.set(t,o),{sessionAgentModelSelections:a}})},getAgentModelForSession:(e,n)=>{let{sessionAgentModelSelections:r}=t(),i=r.get(e);return i&&i.get(n)||null},saveAgentModelVariantForSession:(t,n,r,i,a)=>{e(e=>{let o=new Map(e.sessionAgentModelVariantSelections),s=o.get(t);s=s?new Map(s):new Map;let c=s.get(n);c=c?new Map(c):new Map;let l=`${r}/${i}`;return a===void 0?(c.delete(l),c.size===0?(s.delete(n),s.size===0?o.delete(t):o.set(t,s)):(s.set(n,c),o.set(t,s))):(c.set(l,a),s.set(n,c),o.set(t,s)),{sessionAgentModelVariantSelections:o}})},getAgentModelVariantForSession:(e,n,r,i)=>{let{sessionAgentModelVariantSelections:a}=t(),o=a.get(e);if(!o)return;let s=o.get(n);if(s)return s.get(`${r}/${i}`)},getContextUsage:(n,r,i,a)=>{if(!n)return null;let o=zv(0,r,i),s=o.contextLimit,c=o.normalizedOutput??0,l=o.thresholdLimit;if(s===0||l===0)return null;let u=(a.get(n)||[]).filter(e=>e.info.role===`assistant`);if(u.length===0)return null;let d=u[u.length-1],f=d.info.id,p=t=>{let r=()=>{e(e=>{let r=e.sessionContextUsage.get(n);if(r&&r.totalTokens===t.totalTokens&&r.percentage===t.percentage&&r.contextLimit===t.contextLimit&&(r.outputLimit??0)===(t.outputLimit??0)&&(r.normalizedOutput??0)===(t.normalizedOutput??0)&&r.thresholdLimit===t.thresholdLimit&&r.lastMessageId===t.lastMessageId)return e;let i=new Map(e.sessionContextUsage);return i.set(n,t),{sessionContextUsage:i}})};typeof queueMicrotask==`function`?queueMicrotask(r):typeof window<`u`?window.setTimeout(r,0):setTimeout(r,0)},m=t().sessionContextUsage.get(n);if(m&&m.lastMessageId===f){let e=m.normalizedOutput??m.outputLimit??0,t=m.contextLimit!==s||e!==c||m.thresholdLimit!==l;if(t&&m.totalTokens>0){let e=m.totalTokens/l*100,t={totalTokens:m.totalTokens,percentage:Math.min(e,100),contextLimit:s,outputLimit:o.outputLimit,normalizedOutput:c,thresholdLimit:l,lastMessageId:f};return p(t),t}if(!t&&m.totalTokens>0)return m}let h=Lv(d);if(h===0)return m||null;let g=zv(h,r,i),_={totalTokens:h,percentage:g.percentage,contextLimit:g.contextLimit,outputLimit:g.outputLimit,normalizedOutput:g.normalizedOutput,thresholdLimit:g.thresholdLimit,lastMessageId:f};return p(_),_},updateSessionContextUsage:(t,n,r,i)=>{let a=(i.get(t)||[]).filter(e=>e.info.role===`assistant`);if(a.length===0)return;let o=a[a.length-1],s=Lv(o);if(s===0)return;let c=zv(s,n,r);e(e=>{let n=new Map(e.sessionContextUsage);return n.set(t,{totalTokens:s,percentage:c.percentage,contextLimit:c.contextLimit,outputLimit:c.outputLimit,normalizedOutput:c.normalizedOutput,thresholdLimit:c.thresholdLimit,lastMessageId:o.info.id}),{sessionContextUsage:n}})},initializeSessionContextUsage:(e,n,r,i)=>{let a=t().sessionContextUsage.get(e);(!a||a.totalTokens===0)&&t().updateSessionContextUsage(e,n,r,i)},pollForTokenUpdates:(e,n,r,i=10)=>{let a=0,o=()=>{a++;let s=(r.get(e)||[]).find(e=>e.info.id===n);if(s&&s.info.role===`assistant`&&Lv(s)>0){t().updateSessionContextUsage(e,0,0,r);return}a<i&&setTimeout(o,1e3)};setTimeout(o,2e3)},getCurrentAgent:e=>{let{currentAgentContext:n}=t();return n.get(e)},getSessionAgentEditMode:(e,n,r=Fv(n))=>{if(!e||!n)return r;let i=t().sessionAgentEditModes.get(e)?.get(n);if(i!==void 0)return i;if(e!==Vv){let e=t().sessionAgentEditModes.get(Vv)?.get(n);if(e!==void 0)return e}return r},setSessionAgentEditMode:(t,n,r,i=Fv(n))=>{if(!t||!n)return;let a=i??`ask`;a!==`deny`&&r!==`deny`&&Bv.includes(r)&&e(e=>{let i=new Map(e.sessionAgentEditModes),o=new Map(i.get(t)??new Map);return r===a?(o.delete(n),o.size===0?i.delete(t):i.set(t,o)):(o.set(n,r),i.set(t,o)),{sessionAgentEditModes:i}})},toggleSessionAgentEditMode:(e,n,r=Fv(n))=>{if(!e||!n)return;let i=r??`ask`;if(i===`deny`)return;let a=t().getSessionAgentEditMode(e,n,i),o=Bv.indexOf(a),s=Bv.indexOf(i),c=Bv[((o>=0?o:s>=0?s:0)+1)%Bv.length];t().setSessionAgentEditMode(e,n,c,i)}}),{name:`context-store`,storage:Ct(),partialize:e=>({sessionModelSelections:Array.from(e.sessionModelSelections.entries()),sessionAgentSelections:Array.from(e.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(e.sessionAgentModelSelections.entries()).map(([e,t])=>[e,Array.from(t.entries())]),sessionAgentModelVariantSelections:Array.from(e.sessionAgentModelVariantSelections.entries()).map(([e,t])=>[e,Array.from(t.entries()).map(([e,t])=>[e,Array.from(t.entries())])]),currentAgentContext:Array.from(e.currentAgentContext.entries()),sessionContextUsage:Array.from(e.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(e.sessionAgentEditModes.entries()).map(([e,t])=>[e,Array.from(t.entries())])}),merge:(e,t)=>{let n=new Map;e?.sessionAgentModelSelections&&e.sessionAgentModelSelections.forEach(([e,t])=>{n.set(e,new Map(t))});let r=new Map;e?.sessionAgentModelVariantSelections&&e.sessionAgentModelVariantSelections.forEach(([e,t])=>{let n=new Map;t.forEach(([e,t])=>{n.set(e,new Map(t))}),r.set(e,n)});let i=new Map;return e?.sessionAgentEditModes&&e.sessionAgentEditModes.forEach(([e,t])=>{i.set(e,new Map(t))}),{...t,...e,sessionModelSelections:new Map(e?.sessionModelSelections||[]),sessionAgentSelections:new Map(e?.sessionAgentSelections||[]),sessionAgentModelSelections:n,sessionAgentModelVariantSelections:r,currentAgentContext:new Map(e?.currentAgentContext||[]),sessionContextUsage:new Map(e?.sessionContextUsage||[]),sessionAgentEditModes:i,hasHydrated:!0}}}),{name:`context-store`})),Uv=e=>$r([...e??[]]),Wv=typeof window<`u`?Q.useLayoutEffect:Q.useEffect,Gv=(e,t)=>{let n=(0,pd.c)(16),r;n[0]===t?r=n[1]:(r=t===void 0?[]:t,n[0]=t,n[1]=r);let i=r,[a,o]=Q.useState(!1),s;n[2]===e?s=n[3]:(s=()=>{let t=e.current;if(!t)return;let n=t.scrollWidth>t.clientWidth+1;o(e=>e===n?e:n)},n[2]=e,n[3]=s);let c=s,l;n[4]===c?l=n[5]:(l=()=>{c()},n[4]=c,n[5]=l);let u;n[6]!==c||n[7]!==i?(u=[c,...i],n[6]=c,n[7]=i,n[8]=u):u=n[8],Wv(l,u);let d,f;n[9]!==c||n[10]!==e?(d=()=>{let t=e.current;if(!t||typeof ResizeObserver>`u`)return;let n=new ResizeObserver(()=>{c()});return n.observe(t),()=>n.disconnect()},f=[c,e],n[9]=c,n[10]=e,n[11]=d,n[12]=f):(d=n[11],f=n[12]),Q.useEffect(d,f);let p,m;return n[13]===c?(p=n[14],m=n[15]):(p=()=>{if(typeof window>`u`||typeof ResizeObserver<`u`)return;let e=()=>c();return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},m=[c],n[13]=c,n[14]=p,n[15]=m),Q.useEffect(p,m),a};function Kv(e,t){return!e&&t===`trigger-hover`}var qv=e=>{let t=e.current;return!t||!t.isConnected||t.disabled?null:t},Jv=e=>{let t=qv(e);return t?(t.focus({preventScroll:!0}),!0):!1},Yv=(e,t)=>e&&!t,Xv=e=>{let t=e?.variants;return t?Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length>0):typeof t==`object`?Object.keys(t):[]:[]},Zv=(e,t,n,r)=>{if(e.providerID!==n||e.modelID!==r||t?.variantsReady===!1)return[];if(t?.variants)return[...t.variants];let i=(t?.providers?.find(e=>e.id===n))?.models?.find(e=>e.id===r);return Xv(i)},Qv=()=>!0,$v=(e,t)=>(e.commandPolicy??Qv)(t),ey=Q.createContext(null),ty=()=>Q.useContext(ey),ny=e=>e,ry=(e,t)=>t??e,iy=e=>{if(e.kind!==`primary`&&(!e.sessionID||!e.directory||!e.draftKey||!e.transportIdentity||!Number.isSafeInteger(e.runtimeGeneration)||!e.resources||typeof e.resources.busy!=`boolean`||!e.activity||!e.commands||!e.shortcuts))throw Error(`chat-input-secondary-surface-incomplete`)},ay=(e,t)=>e.kind===`secondary`?e.resources?.busy??!1:t,oy=e=>!e.sessionID||!e.directory?null:{deliveryTarget:e.deliveryTarget,sessionID:e.queueSessionID??e.sessionID,directory:e.directory,transportIdentity:e.transportIdentity,runtimeGeneration:e.runtimeGeneration},sy=(e,t,n)=>{if(e.kind===`secondary`){if(!e.commands)throw Error(`chat-input-secondary-commands-incomplete`);return e.commands}return e.commands?e.commands:{sessionID:e.sessionID,hasMessages:t,hasNewDraft:n}},cy=(e,t)=>`${e}:${t}`,ly=`transition-none animate-none data-[starting-style]:!opacity-100 data-[starting-style]:!scale-100 data-[ending-style]:!opacity-100 data-[ending-style]:!scale-100`,uy=e=>{if(!Array.isArray(e))return null;let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;typeof e.permission==`string`&&typeof e.pattern==`string`&&typeof e.action==`string`&&(e.action===`allow`||e.action===`ask`||e.action===`deny`)&&t.push({permission:e.permission,pattern:e.pattern,action:e.action})}return t},dy=(e,t)=>{let n=uy(e);if(!(!n||n.length===0)){for(let e=n.length-1;e>=0;--e){let r=n[e];if(r.permission===t&&r.pattern===`*`)return r.action}for(let e=n.length-1;e>=0;--e){let t=n[e];if(t.permission===`*`&&t.pattern===`*`)return t.action}}},fy=[{key:`tool_call`,icon:`tools`,label:`Tool calling`,isActive:e=>e?.tool_call===!0},{key:`reasoning`,icon:`brain-ai-3`,label:`Reasoning`,isActive:e=>e?.reasoning===!0}],py={text:{icon:`text`,label:`Text`},image:{icon:`file-image`,label:`Image`},video:{icon:`file-video`,label:`Video`},audio:{icon:`file-music`,label:`Audio`},pdf:{icon:`file-pdf`,label:`PDF`}},my=e=>e.trim().toLowerCase(),hy=(e,t)=>{let n=t===`input`?e?.modalities?.input:e?.modalities?.output;if(!Array.isArray(n)||n.length===0)return[];let r=Array.from(new Set(n.map(e=>my(e)))),i=[];for(let e of r){let t=py[e];t&&i.push({key:e,icon:t.icon,label:t.label})}return i},gy=e=>ss(e),_y=e=>ls(e),vy=e=>vs(e),yy=`__add_provider__`,by=e=>{let t=(0,pd.c)(5),{iconName:n,label:r}=e,i;t[0]===n?i=t[1]:(i=(0,$.jsx)(Z,{name:n,className:`size-3.5`}),t[0]=n,t[1]=i);let a;return t[2]!==r||t[3]!==i?(a=(0,$.jsx)(`span`,{className:`flex size-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground`,title:r,"aria-label":r,role:`img`,children:i}),t[2]=r,t[3]=i,t[4]=a):a=t[4],a},xy=e=>{let t=(0,pd.c)(18),{mode:n,className:r}=e,i;t[0]===r?i=t[1]:(i=Y(r,`flex-shrink-0`),t[0]=r,t[1]=i);let a=i,o;t[2]===n?o=t[3]:(o=xv(n),t[2]=n,t[3]=o);let s=o,c=s?s.text:`var(--foreground)`,l;t[4]===c?l=t[5]:(l={color:c},t[4]=c,t[5]=l);let u=l;if(n===`full`){let e;return t[6]!==a||t[7]!==u?(e=(0,$.jsx)(Z,{name:`pencil-ai`,className:a,style:u}),t[6]=a,t[7]=u,t[8]=e):e=t[8],e}if(n===`allow`){let e;return t[9]!==a||t[10]!==u?(e=(0,$.jsx)(Z,{name:`checkbox-circle`,className:a,style:u}),t[9]=a,t[10]=u,t[11]=e):e=t[11],e}if(n===`deny`){let e;return t[12]!==a||t[13]!==u?(e=(0,$.jsx)(Z,{name:`close-circle`,className:a,style:u}),t[12]=a,t[13]=u,t[14]=e):e=t[14],e}let d;return t[15]!==a||t[16]!==u?(d=(0,$.jsx)(Z,{name:`question`,className:a,style:u}),t[15]=a,t[16]=u,t[17]=d):d=t[17],d},Sy=e=>{if(typeof e!=`number`||Number.isNaN(e))return`—`;if(e===0)return`0`;let t=gy(e);return t.endsWith(`.0`)?t.slice(0,-2):t},Cy=e=>typeof e!=`number`||!Number.isFinite(e)?`—`:_y(e),wy=e=>{let t=[];for(let n of fy)n.isActive(e)&&t.push({key:n.key,icon:n.icon,label:n.label});return t},Ty=e=>{if(!e)return`—`;let t=new Date(e);return Number.isNaN(t.getTime())?e:vy(t)},Ey=({className:e,composerTextareaRef:t,mobilePanel:n,onMobilePanelChange:r,selectionAdapter:i})=>{let{t:a}=Yt(),o=Q.useId(),{isReady:s,isUnavailable:c}=cs(),l=c||i?.catalog?.error?a(`common.unavailable`):a(`common.loading`),u=Oa(e=>e.providerConfigLoadingByDirectory[e.activeDirectoryKey]===!0),d=Oa(e=>e.agentConfigLoadingByDirectory[e.activeDirectoryKey]===!0),f=i?.catalog,p=s&&(f?.ready??!u)&&!f?.loading&&!f?.error&&!i?.disabled,m=s&&(f?.ready??!d)&&!f?.loading&&!f?.error&&!i?.disabled,h=p&&m,g=Oa(e=>e.providers),_=f?.providers??g,v=Oa(e=>e.currentProviderId),y=Oa(e=>e.currentModelId),b=i?.selection.providerID??v,x=i?.selection.modelID??y,S=Oa(e=>e.currentVariant),C=i?i.selection.variant:S,w=Oa(e=>e.currentAgentName),T=i?i.selection.agent??void 0:w,E=Oa(e=>e.settingsDefaultVariant),D=Oa(e=>e.settingsDefaultAgent),O=Oa(e=>e.setProvider),k=Oa(e=>e.setSelectedProvider),A=Oa(e=>e.setModel),j=Oa(e=>e.setCurrentVariant),M=Oa(e=>e.getCurrentModelVariants),N=Oa(e=>e.setAgent),P=Oa(e=>e.getCurrentProvider),F=Oa(e=>e.getModelMetadata),I=Oa(e=>e.getCurrentAgent),L=Oa(e=>e.getVisibleAgents),R=Uv(f?.agents??L()),z=Q.useMemo(()=>R.filter(e=>e.mode===`primary`),[R]),B=Q.useRef(!1);Q.useEffect(()=>{B.current||!h||(B.current=!0,ot(`ModelControls:ready`,{providers:_.length,agents:R.length,currentProviderId:b,currentModelId:x,currentAgentName:T}))},[R.length,h,T,x,b,_.length]);let V=X(e=>i?null:e.currentSessionId),H=X(e=>e.getDirectoryForSession),ee=Qm(),U=Hr(e=>e.getSessionModelSelection),te=Hr(e=>e.saveSessionModelSelection),W=Hr(e=>e.saveSessionAgentSelection),ne=Hr(e=>e.saveAgentModelForSession),G=Hr(e=>e.getAgentModelForSession),re=Hr(e=>e.saveAgentModelVariantForSession),ie=Hr(e=>e.getAgentModelVariantForSession),K=Hv(e=>e.hasHydrated),ae=Hr(e=>V?e.sessionAgentSelections.get(V)??null:null),oe=Q.useRef(null);Q.useEffect(()=>{if(!V){oe.current=null;return}ae&&(oe.current=ae)},[V,ae]);let se=V?oe.current:null,ce=i?i.selection.agent??void 0:V&&(ae||se)||T,le=q(e=>e.toggleFavoriteModel),ue=q(e=>e.reorderFavoriteModel),de=q(e=>e.providerOrder),fe=q(e=>e.setProviderOrder),pe=q(e=>e.isFavoriteModel),me=q(e=>e.addRecentModel),he=q(e=>e.addRecentAgent),ge=q(e=>e.addRecentEffort),_e=q(e=>e.isModelSelectorOpen),ve=q(e=>e.setModelSelectorOpen),ye=q(e=>e.isAgentSelectorOpen),be=q(e=>e.setAgentSelectorOpen),xe=q(e=>e.isModelSelectorInstant),Se=q(e=>e.isAgentSelectorInstant),Ce=q(e=>e.setSettingsDialogOpen),we=q(e=>e.setSettingsPage),Te=q(e=>e.hiddenModels),Ee=q(e=>e.shortcutOverrides.cycle_agent),De=Q.useMemo(()=>Os(`cycle_agent`,Ee?{cycle_agent:Ee}:void 0),[Ee]),{favoriteModelsList:Oe,recentModelsList:ke}=Co({currentProviderID:b,currentModelID:x}),{isMobile:Ae}=qs(),je=q(e=>e.isMobile),Me=Ae||je,Ne=ac(),Pe=Me,[Fe,Ie]=Q.useState(null),Le=n!==void 0&&typeof r==`function`,Re=Le?n:Fe,ze=Le?r:Ie,Be=J(e=>{ze(e),Oa.getState().refreshCatalogsOnPickerOpen({source:`modelControls:mobilePanel`})}),Ve=J((e,t)=>{if(Kv(e,t?.reason)){t?.cancel?.();return}be(e),e&&Oa.getState().refreshCatalogsOnPickerOpen({source:`modelControls:desktopAgentMenu`})}),[He,Ue]=Q.useState(null),We=Q.useRef(!1),Ge=Q.useCallback(()=>ze(null),[ze]),Ke=Q.useCallback(()=>Ue(null),[]),qe=Q.useRef(void 0),Je=_e,Ye=ve,Xe=Q.useCallback(()=>{k(yy),we(`providers`),Ce(!0),Ye(!1),Ge()},[k,we,Ce,Ye,Ge]),[Ze,Qe]=Q.useState(``),[$e,et]=Q.useState(null),[tt,nt]=Q.useState(!1),rt=Q.useRef(0),it=J((e,t)=>{if(Kv(e,t?.reason)){t?.cancel?.();return}nt(!1),e||(rt.current=performance.now()+200,et(null),Qe(``)),Ye(e),e&&Oa.getState().refreshCatalogsOnPickerOpen({source:`modelControls:desktopModelMenu`})}),at=Q.useRef(!1),st=Q.useRef(null),ct=Q.useRef(void 0),[lt,ut]=Q.useState(new Map),[dt,ft]=Q.useState(new Set),[pt,mt]=Q.useState(0),ht=Q.useCallback(()=>{let e=()=>{let e=q.getState();!e.isModelSelectorOpen&&!e.isAgentSelectorOpen&&Jv(t)};window.setTimeout(()=>{requestAnimationFrame(()=>{e(),requestAnimationFrame(e)})},0)},[t]),gt=Q.useCallback(e=>{let t=q.getState();(e===`model`?t.isModelSelectorOpen:t.isAgentSelectorOpen)||(q.setState(e===`model`?{isModelSelectorInstant:!1}:{isAgentSelectorInstant:!1}),!q.getState().isMobile&&ht())},[ht]),_t=Q.useCallback(()=>{let e=q.getState();return e.isModelSelectorOpen||e.isAgentSelectorOpen?!1:qv(t)},[t]),vt=Q.useRef(_e);Q.useEffect(()=>{let e=vt.current;vt.current=_e,_e||(Qe(``),at.current=!1,st.current=null,ut(new Map),ft(new Set),e&&!Pe&&(nt(!1),rt.current=performance.now()+200))},[_e,Pe]);let[yt,bt]=Q.useState(``);Q.useEffect(()=>{ye||bt(``)},[ye]);let xt=Q.useMemo(()=>R.filter(e=>Qn(e.mode)),[R]),St=Q.useMemo(()=>yt.trim()?ln(xt,yt.trim(),e=>[e.name,e.description??``]).map(e=>e.item):[...xt].sort((e,t)=>e.name.localeCompare(t.name)),[xt,yt]),Ct=Q.useMemo(()=>{if(D){let e=xt.find(e=>e.name===D);if(e)return e.name}let e=xt.find(e=>e.name===`build`);return e?e.name:xt[0]?.name},[D,xt]),wt=Q.useMemo(()=>ce?R.find(e=>e.name===ce):I?.(),[R,I,ce]),Tt=Me?`mobile`:Ne?`vscode`:`default`,Et=Tt===`mobile`?`size-5`:`size-4`,Dt=Pe?`typography-micro`:`typography-meta`,Ot=Tt===`mobile`?`gap-x-1`:Tt===`vscode`?`gap-x-2`:`gap-x-1.5`,kt=Tt===`mobile`?`h-8 w-8`:Tt===`vscode`?`h-5 w-5`:`h-6 w-6`,At=Tt===`mobile`?18:Tt===`vscode`?14:16,jt=wv(ce),Mt=i?_.find(e=>e.id===b):P(),Nt=Array.isArray(Mt?.models)?Mt.models:[],Pt=x?Nt.find(e=>e.id===x):void 0,Ft=b&&x&&Pt?Uo(b,Pt,F(b,x)):b&&x?F(b,x):void 0,It=Q.useCallback(e=>e===`Tool calling`?a(`chat.modelControls.capability.toolCalling`):e===`Reasoning`?a(`chat.modelControls.capability.reasoning`):e===`Text`?a(`chat.modelControls.modality.text`):e===`Image`?a(`chat.modelControls.modality.image`):e===`Video`?a(`chat.modelControls.modality.video`):e===`Audio`?a(`chat.modelControls.modality.audio`):e===`PDF`?a(`chat.modelControls.modality.pdf`):e,[a]),Lt=Q.useMemo(()=>wy(Ft).map(e=>({...e,label:It(e.label)})),[Ft,It]),Rt=Q.useMemo(()=>hy(Ft,`input`).map(e=>({...e,label:It(e.label)})),[Ft,It]),zt=Q.useMemo(()=>hy(Ft,`output`).map(e=>({...e,label:It(e.label)})),[Ft,It]),Bt=Q.useMemo(()=>{if(f?.variantsReady===!1)return[];if(f?.variants)return[...f.variants];if(b&&x){let e=_.find(e=>e.id===b)?.models?.find(e=>e.id===x);return Xv(e)}return i?[]:M()},[x,b,M,_,i,f?.variants,f?.variantsReady]),Vt=Bt.length>0,Ht=[{label:`Input`,value:Cy(Ft?.cost?.input)},{label:`Output`,value:Cy(Ft?.cost?.output)},{label:`Cache read`,value:Cy(Ft?.cost?.cache_read)},{label:`Cache write`,value:Cy(Ft?.cost?.cache_write)}],Ut=[{label:`Context`,value:Sy(Ft?.limit?.context)},{label:`Output`,value:Sy(Ft?.limit?.output)}],Wt=Q.useRef(void 0),Gt=Q.useRef(null),Kt=Q.useRef(null),qt=V?H(V):void 0,Jt=on(V??``,qt??void 0).renderable,Xt=ka(V??``,qt??void 0),Zt=Q.useMemo(()=>{for(let e=Xt.length-1;e>=0;--e){let t=Xt[e];if(t.role!==`user`)continue;let n=typeof t.model?.providerID==`string`&&t.model.providerID.trim().length>0?t.model.providerID:void 0,r=typeof t.model?.modelID==`string`&&t.model.modelID.trim().length>0?t.model.modelID:void 0,i=typeof t.agent==`string`&&t.agent.trim().length>0?t.agent:typeof t.mode==`string`&&t.mode.trim().length>0?t.mode:void 0,a=t.model?.variant??t.variant,o=typeof a==`string`&&a.trim().length>0?a:void 0;return{id:t.id,agent:i,providerID:n,modelID:r,variant:o}}return null},[Xt]),Qt=Q.useCallback((e,t,n)=>{if(!e||!t)return`model-missing`;let r=_.find(t=>t.id===e);return r?(Array.isArray(r.models)?r.models:[]).find(e=>e.id===t)?b===e&&x===t?`applied`:(O(e),A(t),V&&(te(V,e,t),n&&ne(V,n,e,t)),`applied`):`model-missing`:`provider-missing`},[_,b,x,O,A,V,ne,te]),$t=Q.useCallback((e,t)=>{if(i&&i.selection.providerID===e&&i.selection.modelID===t)return Zv(i.selection,i.catalog,e,t);let n=_.find(t=>t.id===e)?.models?.find(e=>e.id===t);return Xv(n)},[_,i,i?.selection.providerID,i?.selection.modelID,f?.variants,f?.variantsReady]),en=Q.useCallback((e,t)=>{let n=i?Zv(i.selection,i.catalog,e,t):[],r=n.length>0?n:$t(e,t);if(r.length===0)return;if(i){let n=i.selection.variant;if(i.selection.providerID===e&&i.selection.modelID===t&&n&&r.includes(n))return n}let a=ce||T;if(V&&a){let n=ie(V,a,e,t);if(n&&r.includes(n))return n}if(b===e&&x===t&&C&&r.includes(C))return C;if(!V&&E&&r.includes(E))return E},[T,x,b,V,C,ie,$t,i,E,ce]),tn=Q.useCallback(()=>{if(i)return i.selection.agent??void 0;let e=Oa.getState().currentAgentName;return V?Hr.getState().getSessionAgentSelection(V)||oe.current||e||T:e||T},[T,V,i]),nn=Q.useCallback((e,t,n,r)=>{if(i){i.onChange({...i.selection,providerID:e,modelID:t,variant:n}).catch(()=>void 0);return}if($t(e,t).length===0){We.current=!1,j(void 0);return}We.current=!0,j(n),ge(e,t,n);let a=r??tn();V&&a&&re(V,a,e,t,n)},[ge,V,$t,tn,re,i,j]),rn=Q.useCallback((e,t,n,r)=>{let a=r??tn()??void 0,o=Qt(e,t,a);if(o!==`applied`)return o;nn(e,t,n,a);let s=i?n:Oa.getState().currentVariant;return me(e,t,s),`applied`},[me,nn,tn,i,Qt]);Q.useEffect(()=>{if(i)return;if(!V){Kt.current=null;return}if(!K||_.length===0||!Jt||!Zt?.providerID||!Zt.modelID)return;let e=[V,Zt.id,Zt.agent??``,Zt.providerID,Zt.modelID,Zt.variant??``].join(`|`);if(Kt.current===e)return;Zt.agent&&T!==Zt.agent&&N(Zt.agent);let t=Zt.variant&&$t(Zt.providerID,Zt.modelID).includes(Zt.variant)?Zt.variant:void 0;rn(Zt.providerID,Zt.modelID,t,Zt.agent||T||void 0)===`applied`&&(Zt.agent&&(W(V,Zt.agent),re(V,Zt.agent,Zt.providerID,Zt.modelID,t)),te(V,Zt.providerID,Zt.modelID),Kt.current=e)},[i,V,T,K,_,Jt,Zt,N,rn,$t,W,re,te]),Q.useEffect(()=>{if(i)return;if(!V){Kt.current=null;return}if(!K||_.length===0||R.length===0)return;let e=()=>{let e=U(V),t=V?Hr.getState().getSessionAgentSelection(V):null;if(t){T!==t&&N(t);let e=G(V,t);if(e){let n=Qt(e.providerId,e.modelId,t);if(n===`applied`)return`resolved`;if(n===`provider-missing`)return`waiting`}}if(e){let n=Qt(e.providerId,e.modelId,t||T||void 0);if(n===`applied`)return`resolved`;if(n===`provider-missing`)return`waiting`}for(let e of R){let t=G(V,e.name);if(!t)continue;T!==e.name&&N(e.name),Hr.getState().getSessionAgentSelection(V)||oe.current||W(V,e.name);let n=Qt(t.providerId,t.modelId,e.name);if(n===`applied`)return`resolved`;if(n===`provider-missing`)return`waiting`}return`continue`},t=()=>{if(R.length===0)return;let e=V?Hr.getState().getSessionAgentSelection(V)||oe.current:null,t=(V?Hr.getState().getSessionAgentSelection(V)||oe.current:null)||T;if(t&&R.some(e=>e.name===t)){T!==t&&N(t);return}let n=R.find(e=>e.name===`build`)||z[0]||R[0];n&&(e||W(V,n.name),T!==n.name&&N(n.name),n.model?.providerID&&n.model?.modelID&&Qt(n.model.providerID,n.model.modelID,n.name))},n=e();if(n!==`resolved`&&n!==`waiting`){if(!Jt){ee.isLoading(V)||ee.ensureSessionRenderable(V);return}Zt||t()}},[i,V,Jt,Zt,R,z,T,U,G,N,Qt,W,K,_,ee]),Q.useEffect(()=>{if(i||!K)return;let e=new AbortController;return(async()=>{try{if(T!==Wt.current&&(Wt.current=T,T&&V)){let t=Gt.current===T;if(Gt.current=null,await new Promise(t=>{let n=setTimeout(t,50);e.signal.addEventListener(`abort`,()=>{clearTimeout(n),t()})}),e.signal.aborted)return;let n=G(V,T);if(n){let e=Qt(n.providerId,n.modelId,T);if(e===`applied`||e===`provider-missing`)return}let r=Oa.getState().getAgentModelSelection(T);if(r){let e=Qt(r.providerId,r.modelId,T);if(e===`applied`||e===`provider-missing`){e===`applied`&&(te(V,r.providerId,r.modelId),ne(V,T,r.providerId,r.modelId),r.variant!==void 0&&(re(V,T,r.providerId,r.modelId,r.variant),j(r.variant)));return}}let i=t?R.find(e=>e.name===T):void 0;if(i?.model?.providerID&&i.model.modelID){let e=Qt(i.model.providerID,i.model.modelID,T);if(e===`applied`||e===`provider-missing`){e===`applied`&&(te(V,i.model.providerID,i.model.modelID),ne(V,T,i.model.providerID,i.model.modelID));return}}}}catch(e){console.error(`[ModelControls] Agent change error:`,e)}})(),()=>{e.abort()}},[i,R,T,V,G,ne,re,te,j,Qt,K]),Q.useEffect(()=>{if(i)return;if(!K||!T){We.current=!1,j(void 0);return}if(!b||!x){We.current=!1,j(void 0);return}if(Bt.length===0){We.current=!1,j(void 0);return}if(C&&!Bt.includes(C)){j(void 0);return}if(!V){if(!C&&!We.current){let e=E&&Bt.includes(E)?E:void 0;j(e)}return}let e=ie(V,T,b,x),t=e&&Bt.includes(e)?e:E&&Bt.includes(E)?E:void 0;j(t),We.current=!1},[i,Bt,K,V,T,b,x,C,ie,j,E]),Q.useEffect(()=>{We.current=!1},[b,x]);let an=Q.useCallback((e,t)=>{if(i){let n=Ea(i.selection,e,R,_),r=n.providerID===i.selection.providerID&&n.modelID===i.selection.modelID;Pe&&Ge(),i.onChange({...n,variant:r?i.selection.variant:void 0}).then(()=>{he(e),(t?.closeModelSelector??!0)&&Ye(!1)}).catch(()=>void 0);return}try{Gt.current=e,N(e),he(e),(t?.closeModelSelector??!0)&&Ye(!1),V&&W(V,e),Pe&&Ge()}catch(e){console.error(`[ModelControls] Handle agent change error:`,e)}},[he,R,Ge,V,Pe,_,W,i,N,Ye]),sn=Q.useCallback(e=>{let t=Jr(R,T,e);t&&an(t,{closeModelSelector:!1})},[R,T,an]),cn=Q.useCallback(e=>{let t=De&&!De.includes(`shift`)?Ps(`shift+${De}`):``;return t&&ks(e,t)?-1:ks(e,De)?1:null},[De]),un=Q.useCallback(e=>{let t=cn(e);t&&(e.preventDefault(),e.stopPropagation(),sn(t))},[cn,sn]),dn=Q.useCallback((e,t,n,r)=>{!e||!t||!n||Oa.getState().saveAgentModelSelection(e,t,n,r)},[]),fn=(e,t,n)=>{let r=()=>{Ye(!1,n?.closeInstant?{instant:!0}:void 0)};if(i){Pe&&Ge();let a=n?.applyVariant?n.variant:en(e,t);i.onChange({providerID:e,modelID:t,agent:n?.agentName??i.selection.agent,variant:a}).then(()=>{me(e,t,a),r()}).catch(()=>void 0);return}try{let i=n?.agentName??tn()??void 0,a=n?.applyVariant?rn(e,t,n.variant,i):Qt(e,t,i);if(a!==`applied`){a===`provider-missing`?console.error(`[ModelControls] Provider not available for selection:`,e):a===`model-missing`&&console.error(`[ModelControls] Model not available for selection:`,{providerId:e,modelId:t});return}dn(i,e,t,n?.applyVariant?n.variant:Oa.getState().currentVariant),n?.applyVariant||me(e,t,Oa.getState().currentVariant),r(),Pe&&Ge()}catch(e){console.error(`[ModelControls] Handle model change error:`,e)}},pn=(e,t)=>Jn(e,t,{maxLength:40}),mn=()=>_.find(e=>e.id===b)?.name||b,hn=()=>{if(!x)return a(`chat.modelControls.selectModel`);let e=Nt.find(e=>e.id===x);return pn(e,x)||a(`chat.modelControls.selectModel`)},gn=hn(),_n=Q.useRef(null),vn=Gv(_n,[gn,C,Pe]),yn=()=>{if(!ce){let e=z.find(e=>e.name===`build`)||z[0];return e?bn(e.name):`Select Agent`}let e=R.find(e=>e.name===ce);return bn(e?e.name:ce)},bn=e=>e.charAt(0).toUpperCase()+e.slice(1),xn=Q.useCallback(e=>{qe.current&&clearTimeout(qe.current),qe.current=setTimeout(()=>{Ue(e)},500)},[]),Sn=Q.useCallback(()=>{qe.current&&clearTimeout(qe.current)},[]);Q.useEffect(()=>()=>{qe.current&&clearTimeout(qe.current)},[]);let Cn=()=>!Pe||He!==`model`?null:(0,$.jsx)(Hs,{open:!0,onClose:Ke,title:Ft?.name||hn(),children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-0.5`,children:a(`chat.modelControls.provider`)}),(0,$.jsx)(`div`,{className:`typography-meta text-foreground font-medium`,children:mn()})]}),Lt.length>0&&(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:a(`chat.modelControls.capabilities`)}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:Lt.map(({key:e,icon:t,label:n})=>(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(by,{iconName:t,label:n},`cap-${e}`),(0,$.jsx)(`span`,{className:`typography-meta text-foreground`,children:n})]},e))})]}),(Rt.length>0||zt.length>0)&&(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:a(`chat.modelControls.modalities`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[Rt.length>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80 w-12`,children:a(`chat.modelControls.input`)}),(0,$.jsx)(`div`,{className:`flex gap-1`,children:Rt.map(({key:e,icon:t,label:n})=>(0,$.jsx)(by,{iconName:t,label:`${n} input`},`input-${e}`))})]}),zt.length>0&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80 w-12`,children:a(`chat.modelControls.output`)}),(0,$.jsx)(`div`,{className:`flex gap-1`,children:zt.map(({key:e,icon:t,label:n})=>(0,$.jsx)(by,{iconName:t,label:`${n} output`},`output-${e}`))})]})]})]}),(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:a(`chat.modelControls.limits`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.context`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:Sy(Ft?.limit?.context)})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.output`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:Sy(Ft?.limit?.output)})]})]})]}),Ft?.release_date?(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:a(`chat.modelControls.metadata`)}),(0,$.jsx)(`div`,{className:`flex flex-col gap-0.5`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.release`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:Ty(Ft.release_date)})]})})]}):null]})}),wn=()=>{if(!Pe||He!==`agent`||!wt)return null;let e=!!(wt.prompt&&wt.prompt.trim().length>0),t=wt.model?.providerID&&wt.model?.modelID,n=wt.temperature!==void 0||wt.topP!==void 0,r=e=>{let t=uy(wt.permission)??[],n=t.some(t=>t.permission===e&&t.pattern!==`*`),r=dy(t,e)??`ask`;return n?{mode:`ask`,label:a(`chat.modelControls.permissionLabel.custom`)}:r===`allow`?{mode:`allow`,label:a(`chat.modelControls.permissionLabel.allow`)}:r===`deny`?{mode:`deny`,label:a(`chat.modelControls.permissionLabel.deny`)}:{mode:`ask`,label:a(`chat.modelControls.permissionLabel.ask`)}},i=r(`edit`),o=r(`bash`),s=r(`webfetch`);return(0,$.jsx)(Hs,{open:!0,onClose:Ke,title:bn(wt.name),children:(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[wt.description&&(0,$.jsx)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:(0,$.jsx)(`div`,{className:`typography-meta text-foreground`,children:wt.description})}),(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-0.5`,children:a(`chat.modelControls.mode`)}),(0,$.jsx)(`div`,{className:`typography-meta text-foreground font-medium`,children:wt.mode===`primary`?a(`chat.modelControls.modeValue.primary`):wt.mode===`subagent`?a(`chat.modelControls.modeValue.subagent`):wt.mode===`all`?a(`chat.modelControls.modeValue.all`):a(`chat.modelControls.modeValue.none`)})]}),(t||n)&&(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:a(`chat.modelControls.model`)}),t&&(0,$.jsxs)(`div`,{className:`typography-meta text-foreground font-medium mb-1`,children:[wt.model.providerID,` / `,wt.model.modelID]}),n&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[wt.temperature!==void 0&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.temperature`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:wt.temperature})]}),wt.topP!==void 0&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.topP`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:wt.topP})]})]})]}),(0,$.jsxs)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:a(`chat.modelControls.permissions`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.edit`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(xy,{mode:i.mode,className:`size-3.5`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:i.label})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.bash`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(xy,{mode:o.mode,className:`size-3.5`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:o.label})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.webFetch`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(xy,{mode:s.mode,className:`size-3.5`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:s.label})]})]})]})]}),e&&(0,$.jsx)(`div`,{className:`rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.customPrompt`)}),(0,$.jsx)(Z,{name:`checkbox-circle`,className:`size-4 text-foreground`})]})})]})})},Tn=()=>Pe?(0,$.jsx)(ys,{open:Re===`model`||Re===`variant`,view:Re===`variant`?`variant`:`model`,onViewChange:e=>ze(e),onClose:Ge,selectedProviderID:b||``,selectedModelID:x||``,resolveSelectedVariant:en,onSelect:(e,t,n)=>{if(i){Ge(),i.onChange({providerID:e,modelID:t,agent:i.selection.agent,variant:n}).then(()=>{me(e,t,n)}).catch(()=>void 0);return}let r=rn(e,t,n);if(r!==`applied`){r===`provider-missing`?console.error(`[ModelControls] Provider not available for selection:`,e):r===`model-missing`&&console.error(`[ModelControls] Model not available for selection:`,{providerId:e,modelId:t});return}dn(tn(),e,t,n),Ge()},providers:_,favoriteModels:Oe,recentModels:ke,hiddenModels:Te,providerOrder:de,isFavorite:pe,onToggleFavorite:(e,t)=>le(e,t,e===b&&t===x?C:Oe.find(n=>n.providerID===e&&n.modelID===t)?.variant??ke.find(n=>n.providerID===e&&n.modelID===t)?.variant),getMetadata:F}):null,En=()=>Pe?(0,$.jsx)(Fo,{id:`mobile-agent-picker-sheet-${o}`,open:Re===`agent`,onOpenChange:e=>{e||Ge()},ariaLabel:a(`chat.modelControls.selectAgent`),closeAriaLabel:a(`mobile.surface.closeAria`),resizeAriaLabel:a(`mobile.sessions.sheet.resizeAria`),bodyClassName:`px-2`,children:(0,$.jsx)(bl,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:`min-h-0 flex-1`,className:`flex flex-col gap-2 overscroll-contain`,children:xt.map(e=>{let t=e.name===ce,n=fo(e.name);return(0,$.jsx)(`button`,{type:`button`,className:Y(`flex w-full flex-col gap-1.5 rounded-xl border px-3 py-2.5 text-left`,`focus:outline-none focus-visible:ring-2 focus-visible:ring-primary`,`touch-manipulation cursor-pointer transition-colors`,`active:bg-interactive-hover`,t?`border-primary/50 bg-interactive-selection/20`:`border-border/40 hover:bg-interactive-hover/50`),onClick:()=>an(e.name),children:(0,$.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[1.125rem_minmax(0,1fr)_auto] items-start gap-x-2`,children:[(0,$.jsx)(vo,{name:e.name,size:18}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{className:`block typography-ui-label font-semibold`,style:t?{color:`var(${n.var})`}:void 0,children:bn(e.name)}),e.description&&(0,$.jsx)(`span`,{className:`mt-1 block min-w-0 whitespace-normal break-words typography-micro text-muted-foreground`,children:e.description})]}),t&&(0,$.jsx)(Z,{name:`check`,className:`size-4 shrink-0 text-primary`})]})},e.name)})})}):null,Dn=()=>(0,$.jsx)(Jo,{align:`start`,sideOffset:8,className:`max-w-[320px]`,children:Ft?(0,$.jsxs)(`div`,{className:`flex min-w-[240px] flex-col gap-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,$.jsx)(`span`,{className:`typography-micro font-semibold text-foreground`,children:Ft.name||hn()}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:mn()})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.capabilities`)}),(0,$.jsx)(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:Lt.length>0?Lt.map(({key:e,icon:t,label:n})=>(0,$.jsx)(by,{iconName:t,label:n},`cap-${e}`)):(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a(`chat.modelControls.modeValue.none`)})})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.modalities`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground/80`,children:a(`chat.modelControls.input`)}),(0,$.jsx)(`div`,{className:`flex items-center gap-1.5`,children:Rt.length>0?Rt.map(({key:e,icon:t,label:n})=>(0,$.jsx)(by,{iconName:t,label:`${n} input`},`input-${e}`)):(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:`-`})})]}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground/80`,children:a(`chat.modelControls.output`)}),(0,$.jsx)(`div`,{className:`flex items-center gap-1.5`,children:zt.length>0?zt.map(({key:e,icon:t,label:n})=>(0,$.jsx)(by,{iconName:t,label:`${n} output`},`output-${e}`)):(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:`-`})})]})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.costPerMillion`)}),Ht.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground/80`,children:e.label}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:e.value})]},e.label))]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.limits`)}),Ut.map(e=>(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground/80`,children:e.label}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:e.value})]},e.label))]}),Ft.release_date?(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.metadata`)}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground/80`,children:a(`chat.modelControls.release`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:Ty(Ft.release_date)})]})]}):null]}):(0,$.jsx)(`div`,{className:`min-w-[200px] typography-meta text-muted-foreground`,children:a(`chat.modelControls.metadataUnavailable`)})}),On=()=>{let e=(e,t)=>{if(at.current=!0,e.key!==`ArrowLeft`&&e.key!==`ArrowRight`)return!1;let{providerID:n,modelID:r}=t,i=$t(n,r);if(i.length===0)return!1;e.preventDefault(),e.stopPropagation();let a=cy(n,r),o=lt.has(a),s=lt.get(a),c=o?s:b===n&&x===r?C:void 0,l=[void 0,...i],u=l.indexOf(c),d=l[((u>=0?u:0)+(e.key===`ArrowRight`?1:-1)+l.length)%l.length];return ut(e=>{let t=new Map(e);return t.set(a,d),t}),ft(e=>{let t=new Set(e);return t.add(a),t}),mt(e=>e+1),!0},t=(t,n)=>{let r=cn(t);if(r){t.preventDefault(),sn(r);return}n&&e(t,n)},n=e=>{let t=cy(e.providerID,e.modelID),n=lt.get(t),r=dt.has(t),i=tn();if(r){fn(e.providerID,e.modelID,{applyVariant:!0,variant:n,agentName:i});return}let a=$t(e.providerID,e.modelID),o=e.variant!==void 0&&a.includes(e.variant)?e.variant:void 0;if(o!==void 0){fn(e.providerID,e.modelID,{applyVariant:!0,variant:o,agentName:i});return}fn(e.providerID,e.modelID,{agentName:i})},r=e=>{let t=cn(e);t&&(e.preventDefault(),e.stopPropagation(),at.current=!0,sn(t))},i=e=>e?.trim()?Bn(e):a(`chat.modelControls.default`),o=(e,t)=>{let n=tn();fn(e.providerID,e.modelID,{applyVariant:!0,variant:t,agentName:n,closeInstant:!0})},s=e=>{e&&(Je||performance.now()<rt.current)||nt(e)},c={searchPlaceholder:a(`chat.modelControls.searchModels`),noResults:a(`chat.modelControls.noModelsFound`),favorites:a(`chat.modelControls.favorites`),recent:a(`chat.modelControls.recent`),keyboardHint:a(`chat.modelControls.keyboardHintNavigate`),favorite:a(`chat.modelControls.favoriteAria`),unfavorite:a(`chat.modelControls.unfavoriteAria`),provider:a(`chat.modelControls.provider`),capabilities:a(`chat.modelControls.capabilities`),capabilityToolCalling:a(`chat.modelControls.capability.toolCalling`),capabilityReasoning:a(`chat.modelControls.capability.reasoning`),modalityImage:a(`chat.modelControls.modality.image`),modalityVideo:a(`chat.modelControls.modality.video`),modalityAudio:a(`chat.modelControls.modality.audio`),costPerMillion:a(`chat.modelControls.costPerMillion`),costInput:a(`chat.modelControls.costInput`),costOutput:a(`chat.modelControls.costOutput`)},u=(e,{isSelected:t})=>{let n=$t(e.providerID,e.modelID);if(n.length===0)return null;let r=cy(e.providerID,e.modelID),o=lt.has(r),s=lt.get(r),c=e.variant!==void 0&&n.includes(e.variant)?e.variant:void 0,l=o?s:t?C:c,u=dt.has(r);return(0,$.jsxs)(`button`,{type:`button`,className:Y(`group/thinking flex shrink-0 items-center gap-0.5 rounded-md px-1.5 py-0.5 typography-micro font-medium transition-colors`,u||l?`text-foreground/80`:`text-muted-foreground`,`hover:bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] hover:text-foreground`),onClick:t=>{t.preventDefault(),t.stopPropagation(),et(e)},"aria-label":a(`chat.modelControls.showThinkingModes`),children:[(0,$.jsx)(Z,{name:`brain-ai-3`,className:`size-3 opacity-70`}),(0,$.jsx)(`span`,{className:`max-w-20 truncate`,children:i(l)}),(0,$.jsx)(Z,{name:`arrow-right-s`,className:`size-3 opacity-60 transition-transform group-hover/thinking:translate-x-px`})]})},d=()=>{if(!$e)return null;let e=$t($e.providerID,$e.modelID),t=cy($e.providerID,$e.modelID),n=lt.has(t),r=lt.get(t),s=$e.providerID===b&&$e.modelID===x,c=$e.variant!==void 0&&e.includes($e.variant)?$e.variant:void 0,l=n?r:s?C:c,u=Jn($e.model,$e.modelID,{maxLength:40});return(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,onKeyDownCapture:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),et(null))},children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-b border-border/40 px-1.5 py-1.5`,children:[(0,$.jsx)(`button`,{type:`button`,className:`flex size-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground`,onClick:()=>et(null),"aria-label":a(`header.actions.backAria`),children:(0,$.jsx)(Z,{name:`arrow-left`,className:`size-3.5`})}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1.5`,children:[(0,$.jsx)(To,{modelId:$e.modelID,providerId:$e.providerID,className:`size-3.5 shrink-0`}),(0,$.jsx)(`span`,{className:`truncate typography-meta font-medium text-foreground`,children:u}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`shrink-0 text-border`,children:`·`}),(0,$.jsxs)(`span`,{className:`inline-flex shrink-0 items-center gap-1 typography-micro text-muted-foreground`,children:[(0,$.jsx)(Z,{name:`brain-ai-3`,className:`size-3 opacity-70`}),a(`chat.modelControls.thinking`)]})]})]}),(0,$.jsx)(`div`,{className:`flex flex-col gap-0.5 p-1`,role:`listbox`,"aria-label":a(`chat.modelControls.thinking`),children:[void 0,...e].map(e=>{let t=e===l||!e&&!l;return(0,$.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t,className:Y(`flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left typography-meta transition-colors`,t?`bg-interactive-selection text-interactive-selection-foreground`:`text-foreground hover:bg-interactive-hover/50`),onClick:()=>o($e,e),children:[(0,$.jsx)(`span`,{className:Y(`truncate font-medium`,!e&&!t&&`text-muted-foreground`),children:i(e)}),t?(0,$.jsx)(Z,{name:`check`,className:`size-3.5 shrink-0 text-primary`}):(0,$.jsx)(`span`,{className:`size-3.5 shrink-0`,"aria-hidden":`true`})]},e??`__default`)})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border/40 px-2 py-1.5 typography-micro text-muted-foreground`,children:[(0,$.jsx)(vv,{className:`h-4 min-w-4 rounded-[3px] px-1 text-[10px] font-medium tracking-tight shadow-none`,children:`Esc`}),(0,$.jsx)(`span`,{children:a(`header.actions.backAria`)}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`text-border`,children:`·`}),(0,$.jsx)(`span`,{children:a(`chat.modelControls.keyboardHintThinking`)})]})]})},f=C&&Vt?Bn(C):null;return(0,$.jsxs)(Yo,{open:!Je&&tt,onOpenChange:s,delayDuration:200,children:[Pe?(0,$.jsx)(`button`,{type:`button`,onClick:p?()=>Be(`model`):void 0,onTouchStart:p?()=>xn(`model`):void 0,onTouchEnd:p?Sn:void 0,onTouchCancel:p?Sn:void 0,disabled:!p,className:Y(`model-controls__model-trigger min-w-0 focus:outline-none`,p?Y(`cursor-pointer`,Av):`opacity-60 cursor-not-allowed`),children:p?(0,$.jsxs)($.Fragment,{children:[b||x?(0,$.jsx)(To,{modelId:x,providerId:b,className:Y(Et,`flex-shrink-0`)}):(0,$.jsx)(Z,{name:`pencil-ai`,className:Y(Et,`text-muted-foreground`)}),(0,$.jsx)(`span`,{ref:_n,className:Y(`model-controls__model-label typography-micro font-medium overflow-hidden min-w-0`,Me?`max-w-[120px]`:`max-w-[220px]`),children:(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 items-center gap-1`,vn&&`marquee-text marquee-text--active`),children:[(0,$.jsx)(`span`,{className:`truncate`,children:gn}),f?(0,$.jsx)(`span`,{className:`shrink-0 font-normal text-muted-foreground`,children:f}):null]})})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(Et,`animate-spin text-muted-foreground flex-shrink-0`)}),(0,$.jsx)(`span`,{className:`typography-micro font-medium text-muted-foreground min-w-0`,children:l})]})}):(0,$.jsxs)(Cs,{open:p&&Je,onOpenChange:p?it:void 0,onOpenChangeComplete:e=>{e||gt(`model`)},children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Is,{asChild:!0,children:(0,$.jsxs)(`div`,{className:Y(`model-controls__model-trigger cursor-pointer min-w-0`,Av),children:[p?b?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(To,{modelId:x,providerId:b,className:Y(Et,`flex-shrink-0`)}),(0,$.jsx)(Z,{name:`pencil-ai`,className:Y(Et,`text-primary/60 hidden`)})]}):(0,$.jsx)(Z,{name:`pencil-ai`,className:Y(Et,`text-muted-foreground`)}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(Et,`animate-spin text-muted-foreground flex-shrink-0`)}),(0,$.jsx)(`span`,{className:Y(`model-controls__model-label`,Dt,`font-medium whitespace-nowrap text-muted-foreground min-w-0`),children:l})]}),p&&(0,$.jsx)(`span`,{ref:_n,className:Y(`model-controls__model-label overflow-hidden`,Dt,`font-medium whitespace-nowrap text-foreground min-w-0`,`max-w-[260px]`),children:(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 items-center gap-1`,vn&&`marquee-text marquee-text--active`),children:[(0,$.jsx)(`span`,{className:`truncate`,children:gn}),f?(0,$.jsx)(`span`,{className:`shrink-0 font-normal text-muted-foreground`,children:f}):null]})},`${b}-${x}-${C??``}`)]})})}),(0,$.jsx)(Ss,{className:Y(`w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col`,xe&&ly),align:`end`,alignOffset:-40,onKeyDownCapture:r,finalFocus:_t,children:$e?d():(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`p-1 border-b border-border/40`,children:(0,$.jsxs)(`button`,{type:`button`,onClick:Xe,className:`typography-meta group flex w-full items-center gap-1 rounded-md px-2 py-1.5 cursor-pointer hover:bg-interactive-hover/50`,children:[(0,$.jsx)(`span`,{className:`flex size-4 items-center justify-center text-muted-foreground`,children:(0,$.jsx)(Z,{name:`add`,className:`size-4 -mr-0.5`})}),(0,$.jsx)(`span`,{className:`font-medium text-foreground`,children:a(`chat.modelControls.addNewProvider`)})]})}),(0,$.jsx)(Eo,{providers:_,favoriteModels:Oe,recentModels:ke,getMetadata:F,searchQuery:Ze,onSearchQueryChange:Qe,onSelect:n,labels:c,selectedModel:b&&x?{providerID:b,modelID:x}:null,hiddenModels:Te,onActiveKeyDown:t,onActiveEntryChange:e=>{ct.current=e},onVariantKey:e,isFavorite:e=>pe(e.providerID,e.modelID),onToggleFavorite:e=>le(e.providerID,e.modelID,e.providerID===b&&e.modelID===x?C:e.variant),renderRowEnd:u,renderVersion:pt,onReorderFavorite:(e,t)=>ue(e.providerID,e.modelID,t.providerID,t.modelID),reorderFavoriteAriaLabel:a(`chat.modelControls.reorderFavoriteAria`),reorderFavoriteTitle:a(`chat.modelControls.reorderFavoriteTitle`),providerOrder:de,onReorderProvider:fe,reorderProviderTitle:a(`chat.modelControls.reorderProviderTitle`),footerContent:e=>{let t=e?$t(e.providerID,e.modelID).length>0:!1;return(0,$.jsxs)(`div`,{className:`flex items-center gap-x-2 whitespace-nowrap overflow-hidden`,children:[(0,$.jsx)(`span`,{children:a(`chat.modelControls.keyboardHintNavigate`)}),(0,$.jsx)(`span`,{children:a(`chat.modelControls.keyboardHintSwitchAgent`,{shortcut:`Tab`})}),t?(0,$.jsx)(`span`,{children:a(`chat.modelControls.keyboardHintThinking`)}):null]})},tooltipsEnabled:Je&&!$e,onEscape:()=>{if($e){et(null);return}Ye(!1)}})]})})]}),Dn()]})},kn=()=>{if(!wt)return(0,$.jsx)(Jo,{align:`start`,sideOffset:8,className:`max-w-[320px]`,children:(0,$.jsx)(`div`,{className:`min-w-[200px] typography-meta text-muted-foreground`,children:a(`chat.modelControls.noAgentSelected`)})});let e=!!(wt.prompt&&wt.prompt.trim().length>0),t=wt.model?.providerID&&wt.model?.modelID,n=wt.temperature!==void 0||wt.topP!==void 0,r=e=>{let t=uy(wt.permission)??[],n=t.some(t=>t.permission===e&&t.pattern!==`*`),r=dy(t,e)??`ask`;return n?{mode:`ask`,label:a(`chat.modelControls.permissionLabel.custom`)}:r===`allow`?{mode:`allow`,label:a(`chat.modelControls.permissionLabel.allow`)}:r===`deny`?{mode:`deny`,label:a(`chat.modelControls.permissionLabel.deny`)}:{mode:`ask`,label:a(`chat.modelControls.permissionLabel.ask`)}},i=r(`edit`),o=r(`bash`),s=r(`webfetch`);return(0,$.jsx)(Jo,{align:`start`,sideOffset:8,className:`max-w-[280px]`,children:(0,$.jsxs)(`div`,{className:`flex min-w-[200px] flex-col gap-2.5`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,$.jsx)(`span`,{className:`typography-micro font-semibold text-foreground`,children:bn(wt.name)}),wt.description&&(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:wt.description})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.mode`)}),(0,$.jsx)(`span`,{className:`typography-meta text-foreground`,children:wt.mode===`primary`?a(`chat.modelControls.modeValue.primary`):wt.mode===`subagent`?a(`chat.modelControls.modeValue.subagent`):wt.mode===`all`?a(`chat.modelControls.modeValue.all`):a(`chat.modelControls.modeValue.none`)})]}),(t||n)&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.model`)}),t?(0,$.jsxs)(`span`,{className:`typography-meta text-foreground`,children:[wt.model.providerID,` / `,wt.model.modelID]}):(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a(`chat.modelControls.modeValue.none`)}),n&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-0.5 mt-0.5`,children:[wt.temperature!==void 0&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.temperature`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:wt.temperature})]}),wt.topP!==void 0&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.topP`)}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground`,children:wt.topP})]})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90`,children:a(`chat.modelControls.permissions`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80 w-16`,children:a(`chat.modelControls.edit`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(xy,{mode:i.mode,className:`size-3.5`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground w-12`,children:i.label})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80 w-16`,children:a(`chat.modelControls.bash`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(xy,{mode:o.mode,className:`size-3.5`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground w-12`,children:o.label})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80 w-16`,children:a(`chat.modelControls.webFetch`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(xy,{mode:s.mode,className:`size-3.5`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-foreground w-12`,children:s.label})]})]})]}),e&&(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/80`,children:a(`chat.modelControls.customPrompt`)}),(0,$.jsx)(Z,{name:`checkbox-circle`,className:`size-4 text-foreground`})]})]})})},An=()=>{let e=yn(),t=ce?fo(ce):null;return Pe?(0,$.jsx)(`button`,{type:`button`,onClick:m?()=>Be(`agent`):void 0,onTouchStart:m?()=>xn(`agent`):void 0,onTouchEnd:m?Sn:void 0,onTouchCancel:m?Sn:void 0,disabled:!m,className:Y(`model-controls__agent-trigger inline-flex items-center flex-shrink-0 min-w-0 focus:outline-none`,jv,m?`cursor-pointer`:`opacity-60 cursor-not-allowed`),children:m?(0,$.jsx)(Cv,{name:ce,label:e,revealed:jt,avatarSize:At,slotClassName:kt,colorVar:t?.var}):(0,$.jsx)(`span`,{className:Y(`inline-flex items-center justify-center`,kt),children:(0,$.jsx)(Z,{name:`loader-4`,className:Y(Et,`flex-shrink-0 animate-spin text-muted-foreground`)})})}):(0,$.jsx)(`div`,{className:`flex items-center gap-2 min-w-0`,children:(0,$.jsxs)(Yo,{delayDuration:600,children:[(0,$.jsxs)(Cs,{open:m&&ye,onOpenChange:m?Ve:void 0,onOpenChangeComplete:e=>{e||gt(`agent`)},children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Is,{asChild:!0,children:(0,$.jsx)(`div`,{className:Y(`inline-flex cursor-pointer items-center flex-shrink-0 min-w-0`,jv),children:m?(0,$.jsx)(Cv,{name:ce,label:e,revealed:jt,avatarSize:At,slotClassName:kt,colorVar:t?.var}):(0,$.jsx)(`span`,{className:Y(`inline-flex items-center justify-center`,kt),children:(0,$.jsx)(Z,{name:`loader-4`,className:Y(Et,`flex-shrink-0 animate-spin text-muted-foreground`)})})})})}),(0,$.jsxs)(Ss,{align:`end`,alignOffset:-40,className:Y(`w-[min(280px,calc(100vw-2rem))] p-0 flex flex-col`,Se&&ly),onKeyDownCapture:un,finalFocus:_t,children:[(0,$.jsx)(`div`,{className:`p-1.5 pb-1`,children:(0,$.jsxs)(`div`,{className:`relative`,children:[(0,$.jsx)(Z,{name:`search`,className:`absolute left-2.5 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground`}),(0,$.jsx)(Ko,{type:`text`,placeholder:a(`chat.modelControls.searchAgents`),value:yt,onChange:e=>bt(e.target.value),onKeyDown:e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),be(!1);return}e.stopPropagation()},className:`pl-8 h-8 typography-meta`})]})}),(0,$.jsx)(bl,{outerClassName:`max-h-[min(400px,calc(100dvh-12rem))] flex-1`,children:(0,$.jsxs)(`div`,{className:`p-1`,children:[!yt.trim()&&Ct&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ws,{className:`typography-meta`,onSelect:()=>an(Ct),children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(Z,{name:`arrow-go-back`,className:`size-3.5 text-muted-foreground`}),(0,$.jsx)(`span`,{className:`font-medium`,children:a(`chat.modelControls.resetToDefault`)})]})}),(0,$.jsx)(Bs,{})]}),St.length===0?(0,$.jsx)(`div`,{className:`px-2 py-4 text-center typography-meta text-muted-foreground`,children:`No agents found`}):St.map(e=>(0,$.jsx)(ws,{className:`typography-meta`,onSelect:()=>an(e.name),children:(0,$.jsxs)(`div`,{className:`flex w-full min-w-0 flex-col gap-0.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(vo,{name:e.name,size:14}),(0,$.jsx)(`span`,{className:`font-medium`,children:bn(e.name)})]}),e.description&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground min-w-0 max-w-full ml-5 break-words`,children:e.description})]})},e.name))]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 border-t border-border/40 px-2 py-1.5 typography-micro text-muted-foreground`,children:[(0,$.jsx)(vv,{className:`h-4 min-w-4 rounded-[3px] px-1 text-[10px] font-medium tracking-tight shadow-none`,children:`Tab`}),(0,$.jsx)(`span`,{children:a(`chat.modelControls.keyboardHintSwitchAgentLabel`)})]})]})]}),kn()]})})},jn=Y(`@container/model-controls flex items-center min-w-0`,Me&&`w-full`,e),Mn=An();return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:jn,children:(0,$.jsxs)(`div`,{className:Y(`flex items-center min-w-0 flex-1 justify-end`,Ot,Me&&`overflow-hidden`),children:[Mn,On()]})}),Tn(),En(),Cn(),wn()]})},Dy=[{key:`M`,labelKey:`chat.leaderKey.action.model`},{key:`A`,labelKey:`chat.leaderKey.action.agent`},{key:`N`,labelKey:`chat.leaderKey.action.newSession`},{key:`C`,labelKey:`chat.leaderKey.action.compact`}],Oy=e=>{let t=(0,pd.c)(16),{className:n}=e,{t:r}=Yt(),i=Nm(ky),a=q(Ay),o;t[0]===a?o=t[1]:(o=Ls(Os(`leader_key`,a)||`ctrl+x`),t[0]=a,t[1]=o);let s=o;if(!i)return null;let c;t[2]===r?c=t[3]:(c=r(`chat.leaderKey.pendingAria`),t[2]=r,t[3]=c);let l;t[4]===n?l=t[5]:(l=Y(`pointer-events-none absolute left-1/2 top-0 z-20 -translate-x-1/2 -translate-y-[calc(100%+0.4rem)]`,`inline-flex max-w-[calc(100cqw-1rem)] items-center gap-2 overflow-x-auto rounded-lg border px-2.5 py-1.5`,`border-[var(--interactive-border)] bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)]`,`shadow-sm animate-in fade-in-0 zoom-in-95 duration-150 whitespace-nowrap`,n),t[4]=n,t[5]=l);let u;t[6]===s?u=t[7]:(u=(0,$.jsx)(yv,{shortcut:s,className:`opacity-[0.35] [&_[data-slot=kbd]]:rounded-md [&_[data-slot=kbd]]:border-0 [&_[data-slot=kbd]]:bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] [&_[data-slot=kbd]]:text-muted-foreground/65 [&_[data-slot=kbd]]:shadow-none`}),t[6]=s,t[7]=u);let d;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,$.jsx)(`span`,{className:`typography-micro text-[var(--surface-muted-foreground)]`,children:`·`}),t[8]=d):d=t[8];let f;t[9]===r?f=t[10]:(f=Dy.map((e,t)=>(0,$.jsxs)(Q.Fragment,{children:[t>0?(0,$.jsx)(`span`,{className:`typography-micro text-[var(--surface-muted-foreground)]`,children:`·`}):null,(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1 typography-micro`,children:[(0,$.jsx)(vv,{className:`rounded-md border-0 bg-[color-mix(in_srgb,var(--surface-foreground)_6%,transparent)] text-muted-foreground/65 shadow-none`,children:e.key}),(0,$.jsx)(`span`,{className:`text-[var(--surface-muted-foreground)]`,children:r(e.labelKey)})]})]},e.key)),t[9]=r,t[10]=f);let p;return t[11]!==c||t[12]!==l||t[13]!==u||t[14]!==f?(p=(0,$.jsxs)(`div`,{role:`status`,"aria-live":`polite`,"aria-label":c,className:l,children:[u,d,f]}),t[11]=c,t[12]=l,t[13]=u,t[14]=f,t[15]=p):p=t[15],p};function ky(e){return e.pending}function Ay(e){return e.shortcutOverrides}var jy=28,My=8,Ny=10.5,Py=Math.PI/2,Fy=e=>Array.from({length:My},(t,n)=>{let r=n/My*Math.PI*2-Math.PI/2+e;return[Math.cos(r)*Ny,Math.sin(r)*Ny]}),Iy=[Fy(0),Fy(Py),Fy(Math.PI),Fy(Math.PI*1.5)],Ly=([e,t])=>`${e.toFixed(1)}px, ${t.toFixed(1)}px`,Ry=e=>{let t=(0,pd.c)(9),{size:n,isMobile:r,className:i}=e,a=n??(r!==void 0&&r?12:14),o;t[0]===i?o=t[1]:(o=Y(`oc-morph-orb-glyph shrink-0`,i),t[0]=i,t[1]=o);let s=a/jy,c;t[2]!==a||t[3]!==s?(c={width:a,height:a,"--orb-k":s},t[2]=a,t[3]=s,t[4]=c):c=t[4];let l=c,u;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(u=(0,$.jsx)(`span`,{className:`oc-morph-orb-stage`,children:Iy[0].map(zy)}),t[5]=u):u=t[5];let d;return t[6]!==o||t[7]!==l?(d=(0,$.jsx)(`span`,{className:o,style:l,"aria-hidden":`true`,children:u}),t[6]=o,t[7]=l,t[8]=d):d=t[8],d};function zy(e,t){return(0,$.jsx)(`span`,{className:`oc-morph-orb-dot`,style:{"--m-1":Ly(Iy[0][t]),"--m-2":Ly(Iy[1][t]),"--m-3":Ly(Iy[2][t]),"--m-4":Ly(Iy[3][t])}},t)}var By=1200,Vy=600,Hy=1e9,Uy=0xe8d4a51000,Wy=e=>e>=Uy?e:e>=Hy?e*1e3:Date.now()+e;function Gy({isWorking:e,isMobile:t,statusText:n,isGenericStatus:r,isWaitingForPermission:i,retryInfo:a,turnStartedAt:o,isTurnSettled:s=!1}){let{locale:c,t:l}=Yt(),[u,d]=Q.useState(null),[f,p]=Q.useState(!1),m=Q.useRef(u),h=Q.useRef(f),g=Q.useRef(!1);m.current=u,h.current=f;let _=Q.useRef(0),v=Q.useRef(null),y=Q.useRef(null),b=Q.useRef(null),[x,S]=Q.useState(null),[C,w]=Q.useState(()=>Date.now());Q.useEffect(()=>{if(!e||typeof o!=`number`||a)return;w(Date.now());let t=window.setInterval(()=>w(Date.now()),1e3);return()=>window.clearInterval(t)},[e,o,a]),Q.useEffect(()=>{let e=a?.next;if(!e||e<=0){S(null);return}let t=Wy(e),n=()=>{let e=Math.max(0,t-Date.now());S(Math.ceil(e/1e3))};n();let r=setInterval(n,500);return()=>clearInterval(r)},[a?.next,a?.attempt]);let T=J(()=>{y.current&&=(clearTimeout(y.current),null),b.current&&=(clearTimeout(b.current),null)}),E=J((e,t,n=!1)=>{T(),v.current=null,d(e),p(t),g.current=n,_.current=Date.now()}),D=J(()=>{if(y.current)return;let e=Date.now()-_.current,t=Math.max(0,By-e);y.current=setTimeout(()=>{y.current=null;let e=v.current;e&&E(e.text,e.permission,e.generic)},t)});if(Q.useEffect(()=>{if(s){T(),v.current=null,m.current&&(d(null),p(!1),g.current=!1);return}if(!e){if(y.current&&=(clearTimeout(y.current),null),v.current=null,!m.current||b.current)return;b.current=setTimeout(()=>{b.current=null,d(null),p(!1),g.current=!1},Vy);return}if(b.current&&=(clearTimeout(b.current),null),a){T(),v.current=null;return}let t=i?l(`chat.assistantStatus.waitingForPermission`):n,o=!!i,c=!!r&&!o;if(t){if(!m.current){E(t,o,c);return}if((t!==m.current||o!==h.current)&&!(c&&g.current)){if(c){v.current={text:t,permission:o,generic:c},D();return}E(t,o,c)}}},[e,s,n,r,i,a,l]),Q.useEffect(()=>()=>T(),[]),s||!e&&!u)return null;if(a&&e){let e=x!==null&&x>0?new Intl.RelativeTimeFormat(c,{numeric:`always`,style:`short`}).format(x,`second`):null,n=e?a.attempt&&a.attempt>1?l(`chat.assistantStatus.retryingInAttempt`,{duration:e,attempt:a.attempt}):l(`chat.assistantStatus.retryingIn`,{duration:e}):a.attempt&&a.attempt>1?l(`chat.assistantStatus.retryingAttempt`,{attempt:a.attempt}):l(`chat.assistantStatus.retrying`);return(0,$.jsx)(`div`,{className:`flex h-full items-center text-muted-foreground`,role:`status`,"aria-live":`polite`,"aria-label":n,children:(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center ${t?`gap-1 typography-meta !text-[length:var(--text-meta)]`:`gap-1.5 typography-ui-header`}`,children:[(0,$.jsx)(`span`,{className:`inline-flex flex-none items-center justify-center ${t?`h-5 w-4`:`h-6 w-3.5`}`,children:(0,$.jsx)(Ry,{isMobile:t})}),(0,$.jsx)(`span`,{className:`animate-text-shimmer min-w-0 truncate whitespace-nowrap`,children:n})]})})}if(!u)return null;let O=u,k=typeof o==`number`&&e?ea(Math.max(0,C-o)):null;return(0,$.jsx)(`div`,{className:`flex h-full items-center text-muted-foreground`,role:`status`,"aria-live":f?`assertive`:`polite`,"aria-label":O,"data-waiting":f?`true`:void 0,children:(0,$.jsxs)(`span`,{className:`flex min-w-0 items-center ${t?`gap-1 typography-meta !text-[length:var(--text-meta)]`:`gap-1.5 typography-ui-header`}`,children:[(0,$.jsx)(`span`,{className:`inline-flex flex-none items-center justify-center ${t?`h-5 w-4`:`h-6 w-3.5`}`,children:(0,$.jsx)(Ry,{isMobile:t})}),(0,$.jsx)(`span`,{className:`animate-text-shimmer min-w-0 truncate whitespace-nowrap`,children:O}),k?(0,$.jsx)(`span`,{className:`typography-meta shrink-0 font-light text-muted-foreground/70 tabular-nums`,"aria-hidden":`true`,children:k}):null]})})}var Ky={compose:!0,mutateSession:!0,answerRequests:!0,openTimeline:!0,navigateNestedSession:!0,textSelectionActions:!0,forkSession:!0},qy={compose:!1,mutateSession:!1,answerRequests:!1,openTimeline:!1,navigateNestedSession:!0,textSelectionActions:!1,forkSession:!1},Jy={kind:`primary`,surfaceId:`primary`,sessionId:null,directory:null,active:!0,capabilities:Ky},Yy=e=>({kind:`primary`,surfaceId:`explicit:${e.viewKey}`,sessionId:e.sessionId,directory:e.directory,active:e.active,capabilities:e.active?Ky:qy}),Xy=Q.createContext(Jy),Zy=()=>Q.useContext(Xy),Qy=e=>({fork:e.capabilities.forkSession,revert:e.capabilities.mutateSession,edit:e.capabilities.mutateSession,reviewTransfer:e.capabilities.mutateSession,timeline:e.capabilities.openTimeline,textSelectionMutation:e.capabilities.textSelectionActions,openSourceSession:!!e.openSourceSession}),$y=(e,t,n,r)=>e.capabilities.navigateNestedSession?e.navigateSession?(e.navigateSession(t,n),!0):e.kind===`primary`&&(r(),!0):!1,eb={containerType:`inline-size`,containerName:`status-row`},tb=[],nb=e=>{let t=(0,pd.c)(99),{isWorking:n,statusText:r,isGenericStatus:i,isWaitingForPermission:a,wasAborted:o,abortActive:s,retryInfo:c,turnStartedAt:l,isTurnSettled:u,showAbortStatus:d,showAbortPrompt:f,showAssistantStatus:p,showTodos:m,agentName:h,leftAccessory:g}=e,_=n!==void 0&&n,v=r===void 0?null:r,y=u!==void 0&&u,b=f!==void 0&&f,x=p===void 0||p,S=m===void 0||m,{t:C}=Yt(),[w,T]=Q.useState(!1),E=Zy(),D=X(rb),O=E.sessionId??D,k;t[0]!==O||t[1]!==S?(k=e=>!S||!O?tb:e.todo[O]??tb,t[0]=O,t[1]=S,t[2]=k):k=t[2];let A=Zr(k,E.directory??void 0),j;t[3]!==O||t[4]!==S?(j=e=>S&&O?e.sessions[O]?.todos:void 0,t[3]=O,t[4]=S,t[5]=j):j=t[5];let M=Pa(j),N;bb0:{if(!O){N=tb;break bb0}if(A.length>0){N=A;break bb0}N=M??tb}let P=N,F=q(ib),I;t[6]===F?I=t[7]:(I=F||ge(),t[6]=F,t[7]=I);let L=I,R;t[8]===P?R=t[9]:(R=P.filter(ab),t[8]=P,t[9]=R);let z=R,B;t[10]===z?B=t[11]:(B=z.find(ob)||z.find(sb)||null,t[10]=z,t[11]=B);let V=B,H;t[12]===z?H=t[13]:(H=z.find(cb)??null,t[12]=z,t[13]=H);let ee=H,U;t[14]===P?U=t[15]:(U=P.filter(lb),t[14]=P,t[15]=U);let te=U.length,W;t[16]===P?W=t[17]:(W=P.filter(ub),t[16]=P,t[17]=W);let ne=W.length,G;t[18]!==ne||t[19]!==te?(G={completed:ne,total:te},t[18]=ne,t[19]=te,t[20]=G):G=t[20];let re=G,ie;t[21]===z?ie=t[22]:(ie=z.filter(db),t[21]=z,t[22]=ie);let K=ie.length,ae;t[23]===z?ae=t[24]:(ae=z.filter(fb),t[23]=z,t[24]=ae);let oe=ae.length,se;t[25]!==K||t[26]!==oe?(se={active:K,left:oe},t[25]=K,t[26]=oe,t[27]=se):se=t[27];let ce=se,le=S&&ce.left>0,ue=!!b,[de,fe]=Q.useState(!1),pe,me;t[28]!==de||t[29]!==y||t[30]!==_?(pe=()=>{if(y){fe(!1);return}if(_){fe(!0);return}if(!de)return;let e=window.setTimeout(()=>fe(!1),600);return()=>window.clearTimeout(e)},me=[_,de,y],t[28]=de,t[29]=y,t[30]=_,t[31]=pe,t[32]=me):(pe=t[31],me=t[32]),Q.useEffect(pe,me);let he=x&&(!y&&(_||de)||!!o||!!d),_e=!!g,ve=!d&&!ue&&(o||!s),ye=ue||he||le||_e,be=Q.useRef(null),xe=Q.useRef(null),Se=Q.useRef(null),Ce,we;t[33]===w?(Ce=t[34],we=t[35]):(Ce=()=>{let e=xe.current,t=Se.current;if(!w||!e||!t)return;let n=t.offsetTop-e.offsetTop-(e.clientHeight-t.offsetHeight)/2,r=e.scrollHeight-e.clientHeight;e.scrollTop=Math.min(r,Math.max(0,n))},we=[w],t[33]=w,t[34]=Ce,t[35]=we),Q.useLayoutEffect(Ce,we);let Te,Ee;t[36]===w?(Te=t[37],Ee=t[38]):(Te=()=>{if(!w)return;let e=e=>{be.current&&!be.current.contains(e.target)&&T(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},Ee=[w],t[36]=w,t[37]=Te,t[38]=Ee),Q.useEffect(Te,Ee);let De;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(De=()=>T(pb),t[39]=De):De=t[39];let Oe=J(De),ke;t[40]!==ce.active||t[41]!==ce.left||t[42]!==C?(ke=C(`chat.statusRow.summary.activeLeft`,{active:ce.active,left:ce.left}),t[40]=ce.active,t[41]=ce.left,t[42]=C,t[43]=ke):ke=t[43];let Ae=ke,je;t[44]!==V||t[45]!==le||t[46]!==L||t[47]!==w||t[48]!==re||t[49]!==C||t[50]!==Ae||t[51]!==Oe?(je=le?(0,$.jsxs)(`button`,{type:`button`,onClick:Oe,className:Y(du,`shrink-0`),"aria-label":Ae,title:Ae,children:[(0,$.jsx)(Z,{name:`list-check-3`,className:mu}),!L&&V?(0,$.jsx)(`span`,{className:Y(`status-row__active-todo max-w-[200px]`,wu),children:V.content}):(0,$.jsx)(`span`,{className:`text-xs leading-4 md:text-[0.8125rem] md:leading-5`,children:C(`chat.statusRow.tasksTitle`)}),(0,$.jsxs)(`span`,{className:lu,"aria-hidden":`true`,children:[re.completed,`/`,re.total]}),w?(0,$.jsx)(Z,{name:`arrow-up-s`,className:mu}):(0,$.jsx)(Z,{name:`arrow-down-s`,className:mu})]}):null,t[44]=V,t[45]=le,t[46]=L,t[47]=w,t[48]=re,t[49]=C,t[50]=Ae,t[51]=Oe,t[52]=je):je=t[52];let Me=je;if(!ye)return null;let Ne=!_e&&`chat-column`,Pe;t[53]===Ne?Pe=t[54]:(Pe=Y(`mb-1`,Ne),t[53]=Ne,t[54]=Pe);let Fe=_e&&`px-3`,Ie;t[55]===Fe?Ie=t[56]:(Ie=Y(`flex items-center justify-between py-0.5 gap-2 h-[1.2rem]`,Fe),t[55]=Fe,t[56]=Ie);let Le=!_e&&`overflow-x-hidden`,Re;t[57]===Le?Re=t[58]:(Re=Y(`flex-1 flex items-center min-w-0 gap-2`,Le),t[57]=Le,t[58]=Re);let ze;t[59]!==h||t[60]!==O||t[61]!==ue||t[62]!==i||t[63]!==F||t[64]!==y||t[65]!==a||t[66]!==_||t[67]!==g||t[68]!==c||t[69]!==ve||t[70]!==d||t[71]!==x||t[72]!==v||t[73]!==C||t[74]!==l?(ze=ue?(0,$.jsx)(`div`,{className:`flex min-w-0 items-center text-muted-foreground`,role:`status`,"aria-live":`polite`,"aria-label":C(`chat.statusRow.abortPrompt`),children:(0,$.jsxs)(`span`,{className:Y(`flex min-w-0 items-center typography-ui-label`,F?`gap-1`:`gap-1.5`),children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center`,F?`h-5 w-4`:`h-6 w-3.5`),children:(0,$.jsx)(Z,{name:`error-warning`,className:`size-3.5`,"aria-hidden":`true`})}),(0,$.jsx)(`span`,{className:`animate-text-shimmer truncate whitespace-nowrap`,children:C(`chat.statusRow.abortPrompt`)})]})}):x&&d?(0,$.jsx)(`div`,{className:`flex h-full items-center text-[var(--status-error)]`,children:(0,$.jsxs)(`span`,{className:Y(`flex items-center typography-ui-label`,F?`gap-1`:`gap-1.5`),children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center`,F?`h-5 w-4`:`h-6 w-3.5`),children:(0,$.jsx)(Z,{name:`close-circle`,className:`size-3.5`,"aria-hidden":`true`})}),C(`chat.statusRow.aborted`)]})}):x&&ve?(0,$.jsx)(Gy,{isWorking:_,isMobile:F,statusText:v,isGenericStatus:i,isWaitingForPermission:a,retryInfo:c,turnStartedAt:l,isTurnSettled:y,agentName:h},O??`no-session`):g||null,t[59]=h,t[60]=O,t[61]=ue,t[62]=i,t[63]=F,t[64]=y,t[65]=a,t[66]=_,t[67]=g,t[68]=c,t[69]=ve,t[70]=d,t[71]=x,t[72]=v,t[73]=C,t[74]=l,t[75]=ze):ze=t[75];let Be;t[76]!==Re||t[77]!==ze?(Be=(0,$.jsx)(`div`,{className:Re,children:ze}),t[76]=Re,t[77]=ze,t[78]=Be):Be=t[78];let Ve=!_e&&`-mr-3`,He;t[79]===Ve?He=t[80]:(He=Y(`relative flex items-center gap-2 flex-shrink-0`,Ve),t[79]=Ve,t[80]=He);let Ue;t[81]!==ee||t[82]!==le||t[83]!==w||t[84]!==re||t[85]!==C||t[86]!==z?(Ue=w&&le&&(0,$.jsxs)(`div`,{style:fu,className:Y(vu,`absolute right-0 bottom-full mb-1 z-50`,`animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2`,`duration-150`),children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3 border-b border-[var(--surface-subtle)] px-3 py-2.5`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium leading-4 text-foreground md:text-[0.8125rem] md:leading-5`,children:C(`chat.statusRow.tasksTitle`)}),(0,$.jsxs)(`span`,{className:`text-xs tabular-nums leading-4 text-muted-foreground md:text-[0.8125rem] md:leading-5`,children:[re.completed,`/`,re.total]})]}),(0,$.jsx)(`ul`,{ref:xe,className:ju,children:z.map((e,t)=>(0,$.jsx)(Nu,{todo:e,isActive:e===ee,activeRef:e===ee?Se:void 0},e.id??`todo-${t}`))})]}),t[81]=ee,t[82]=le,t[83]=w,t[84]=re,t[85]=C,t[86]=z,t[87]=Ue):Ue=t[87];let We;t[88]!==He||t[89]!==Ue||t[90]!==Me?(We=(0,$.jsxs)(`div`,{className:He,ref:be,children:[Me,Ue]}),t[88]=He,t[89]=Ue,t[90]=Me,t[91]=We):We=t[91];let Ge;t[92]!==Ie||t[93]!==Be||t[94]!==We?(Ge=(0,$.jsxs)(`div`,{className:Ie,children:[Be,We]}),t[92]=Ie,t[93]=Be,t[94]=We,t[95]=Ge):Ge=t[95];let Ke;return t[96]!==Pe||t[97]!==Ge?(Ke=(0,$.jsx)(`div`,{className:Pe,style:eb,children:Ge}),t[96]=Pe,t[97]=Ge,t[98]=Ke):Ke=t[98],Ke};function rb(e){return e.currentSessionId}function ib(e){return e.isMobile}function ab(e){return e.status!==`cancelled`}function ob(e){return e.status===`in_progress`}function sb(e){return e.status===`pending`}function cb(e){return e.status===`in_progress`}function lb(e){return e.status!==`cancelled`}function ub(e){return e.status===`completed`}function db(e){return e.status===`in_progress`}function fb(e){return e.status===`in_progress`||e.status===`pending`}function pb(e){return!e}var mb=new Set([`edit`,`multiedit`,`write`,`apply_patch`,`create`,`file_write`]),hb=e=>`insertions`in e,gb=e=>{if(typeof e==`number`&&Number.isFinite(e))return Math.max(0,Math.trunc(e))},_b=e=>{let t=0,n=0;for(let r of e.split(`
|
|
6523
6523
|
`))r.startsWith(`+`)&&!r.startsWith(`+++`)&&t++,r.startsWith(`-`)&&!r.startsWith(`---`)&&n++;return{added:t,removed:n}},vb=e=>{let t=[],n=new Set;for(let r of e){if(r.type!==`tool`||!mb.has(r.tool))continue;let e=r.state;if(e.status&&e.status!==`completed`)continue;let i=t.length,a=e.metadata,o=Array.isArray(a?.files)?a.files:[];for(let e of o){if(!e||typeof e!=`object`)continue;let i=e,a=i.relativePath||i.filePath||``;!a||n.has(a)||(n.add(a),t.push({path:a,tool:r.tool,partId:r.id,messageID:r.messageID,additions:gb(i.additions)??void 0,deletions:gb(i.deletions)??void 0,patch:typeof i.patch==`string`?i.patch:void 0}))}if(o.length===0&&a?.filediff&&typeof a.filediff==`object`){let e=a.filediff,i=typeof e.file==`string`?e.file:``;i&&!n.has(i)&&(n.add(i),t.push({path:i,tool:r.tool,partId:r.id,messageID:r.messageID,additions:gb(e.additions)??void 0,deletions:gb(e.deletions)??void 0,patch:typeof e.patch==`string`?e.patch:void 0}))}if(o.length===0&&Array.isArray(a?.results))for(let e of a.results){if(!e||typeof e!=`object`)continue;let i=e.filediff;if(!i||typeof i!=`object`)continue;let a=typeof i.file==`string`?i.file:``;!a||n.has(a)||(n.add(a),t.push({path:a,tool:r.tool,partId:r.id,messageID:r.messageID,additions:gb(i.additions)??void 0,deletions:gb(i.deletions)??void 0,patch:typeof i.patch==`string`?i.patch:void 0}))}if(t.length===i){let i=e.input,a=typeof i?.filePath==`string`?i.filePath:typeof i?.file_path==`string`?i.file_path:typeof i?.path==`string`?i.path:void 0;a&&!n.has(a)&&(n.add(a),t.push({path:a,tool:r.tool,partId:r.id,messageID:r.messageID}))}if(t.length===i){let e=typeof a?.patch==`string`?a.patch.trim():typeof a?.diff==`string`?a.diff.trim():``;if(e&&!n.has(`Diff`)){n.add(`Diff`);let i=_b(e);t.push({path:`Diff`,tool:r.tool,partId:r.id,messageID:r.messageID,additions:i.added,deletions:i.removed})}}}return t},yb=(e,t,n)=>{let r=[];for(let i of e){let e=i.index?.trim()??``,a=i.working_dir?.trim()??``,o=!!(e&&e!==`?`),s=!!(a||e===`?`),c=a||e;if(!c||c===`!`)continue;let l=t?.[i.path];r.push({path:ru(n,i.path),relativePath:i.path,insertions:l?.insertions??0,deletions:l?.deletions??0,status:c,hasStagedChanges:o,hasWorkingChanges:s})}return r},bb=e=>{for(let t of e){let e=t.index?.trim()??``,n=(t.working_dir?.trim()??``)||e;if(!(!n||n===`!`))return!0}return!1},xb=(e,t)=>cu(e,t),Sb=(e,t)=>{let n=hb(e)&&e.relativePath?e.relativePath:xb(e.path,t);return{fileName:n.split(`/`).pop()??n,dirPart:n.includes(`/`)?n.slice(0,n.lastIndexOf(`/`)):``}},Cb=e=>hb(e)?{additions:e.insertions,deletions:e.deletions}:{additions:e.additions??0,deletions:e.deletions??0},wb=2;function Tb(e){let t=e.lastIndexOf(`.`);return t<=0||t===e.length-1?{stem:e,ext:``}:{stem:e.slice(0,t),ext:e.slice(t)}}function Eb(e,t=wb){let n=e??``,r=n.startsWith(`/`),i=n.split(`/`).filter(Boolean);if(i.length===0)return{prefix:``,parent:``,stem:``,ext:``,name:``,leadingSlash:r};let a=i[i.length-1]??``,{stem:o,ext:s}=Tb(a),c=Math.max(1,Math.floor(t)),l=Math.min(i.length-1,c-1),u=i.length-1-l,d=l>0?i.slice(u,-1).join(`/`):``,f=i.slice(0,u).join(`/`),p=f?r?`/${f}`:f:``;return{prefix:p,parent:d,stem:o,ext:s,name:a,leadingSlash:r&&!p}}function Db(e){let t=(0,pd.c)(36),{path:n,className:r,title:i,dirClassName:a,nameClassName:o}=e,s=a===void 0?`text-muted-foreground`:a,c=o===void 0?`text-foreground`:o,l;t[0]===n?l=t[1]:(l=Eb(n),t[0]=n,t[1]=l);let{prefix:u,parent:d,stem:f,ext:p,leadingSlash:m}=l,h=!!(u||d),g;t[2]===r?g=t[3]:(g=Y(`flex min-w-0 items-baseline overflow-hidden`,r),t[2]=r,t[3]=g);let _=i??n,v;t[4]!==s||t[5]!==m?(v=m?(0,$.jsx)(`span`,{className:Y(`shrink-0`,s),children:`/`}):null,t[4]=s,t[5]=m,t[6]=v):v=t[6];let y;t[7]!==s||t[8]!==u?(y=u?(0,$.jsx)(`span`,{className:Y(`min-w-0 shrink-[9999] truncate`,s),children:u}):null,t[7]=s,t[8]=u,t[9]=y):y=t[9];let b;t[10]!==s||t[11]!==d||t[12]!==u?(b=d?(0,$.jsxs)(`span`,{className:Y(`shrink-0`,s),children:[u?`/`:``,d]}):null,t[10]=s,t[11]=d,t[12]=u,t[13]=b):b=t[13];let x;t[14]!==s||t[15]!==h?(x=h?(0,$.jsx)(`span`,{className:s,children:`/`}):null,t[14]=s,t[15]=h,t[16]=x):x=t[16];let S;t[17]===c?S=t[18]:(S=Y(`min-w-0 truncate`,c),t[17]=c,t[18]=S);let C;t[19]!==f||t[20]!==S?(C=(0,$.jsx)(`span`,{className:S,children:f}),t[19]=f,t[20]=S,t[21]=C):C=t[21];let w;t[22]!==p||t[23]!==c?(w=p?(0,$.jsx)(`span`,{className:Y(`shrink-0`,c),children:p}):null,t[22]=p,t[23]=c,t[24]=w):w=t[24];let T;t[25]!==C||t[26]!==w||t[27]!==x?(T=(0,$.jsxs)(`span`,{className:`flex min-w-0 shrink items-baseline`,children:[x,C,w]}),t[25]=C,t[26]=w,t[27]=x,t[28]=T):T=t[28];let E;return t[29]!==T||t[30]!==g||t[31]!==_||t[32]!==v||t[33]!==y||t[34]!==b?(E=(0,$.jsxs)(`span`,{className:g,title:_,children:[v,y,b,T]}),t[29]=T,t[30]=g,t[31]=_,t[32]=v,t[33]=y,t[34]=b,t[35]=E):E=t[35],E}var Ob=e=>{let t=(0,pd.c)(23),{files:n,currentDirectory:r,onOpenFile:i}=e,{t:a}=Yt(),o;t[0]===a?o=t[1]:(o=a(`chat.changedFiles.title`),t[0]=a,t[1]=o);let s;t[2]===o?s=t[3]:(s=(0,$.jsx)(`span`,{className:uu,children:o}),t[2]=o,t[3]=s);let c;t[4]===n.length?c=t[5]:(c=(0,$.jsx)(`span`,{className:hu,children:n.length}),t[4]=n.length,t[5]=c);let l;t[6]!==s||t[7]!==c?(l=(0,$.jsxs)(`div`,{className:Mu,children:[s,c]}),t[6]=s,t[7]=c,t[8]=l):l=t[8];let u;if(t[9]!==r||t[10]!==n||t[11]!==i||t[12]!==a){let e;t[14]!==r||t[15]!==i||t[16]!==a?(e=(e,t)=>{let{fileName:n,dirPart:o}=Sb(e,r),s=Cb(e);return(0,$.jsxs)(`button`,{type:`button`,className:Y(`relative flex w-full cursor-pointer items-center gap-2.5 outline-hidden select-none text-left hover:bg-interactive-hover`,gu),title:a(`chat.changedFiles.actions.openFileTitle`,{path:e.path}),onClick:()=>i(e),children:[(0,$.jsx)(Hh,{filePath:e.path,className:`h-3 w-3 shrink-0 md:h-3.5 md:w-3.5`}),(0,$.jsx)(Db,{path:o?`${o}/${n}`:n,title:e.path,className:`min-w-0 flex-1`}),s.additions>0||s.deletions>0?(0,$.jsxs)(`span`,{className:`flex-shrink-0 inline-flex items-baseline gap-1 text-xs tabular-nums leading-4 md:text-[0.8125rem] md:leading-5`,children:[s.additions>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,s.additions]}):null,s.deletions>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,s.deletions]}):null]}):null]},`${e.path}:${t}`)},t[14]=r,t[15]=i,t[16]=a,t[17]=e):e=t[17],u=n.map(e),t[9]=r,t[10]=n,t[11]=i,t[12]=a,t[13]=u}else u=t[13];let d;t[18]===u?d=t[19]:(d=(0,$.jsx)(`div`,{className:ju,children:u}),t[18]=u,t[19]=d);let f;return t[20]!==l||t[21]!==d?(f=(0,$.jsxs)($.Fragment,{children:[l,d]}),t[20]=l,t[21]=d,t[22]=f):f=t[22],f},kb=`${vu} origin-[var(--transform-origin)]`,Ab=fu,jb=Q.memo(()=>{let e=(0,pd.c)(60),{t}=Yt(),[n,r]=Q.useState(!1),i=Q.useRef(null),a=Hl()??null,o=Q.useContext(ic),s=Pc(a),c;e[0]===a?c=e[1]:(c=e=>a?e.directories.get(a)?.status??null:null,e[0]=a,e[1]=c);let l=vc(c),u=Fu(),d,f;e[2]===n?(d=e[3],f=e[4]):(d=()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&r(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},f=[n],e[2]=n,e[3]=d,e[4]=f),Q.useEffect(d,f);let p;bb0:{if(!a||s!==!0||!l||l.isClean){let t;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[5]=t):t=e[5],p=t;break bb0}let t;e[6]!==a||e[7]!==l.diffStats||e[8]!==l.files?(t=yb(l.files,l.diffStats,a),e[6]=a,e[7]=l.diffStats,e[8]=l.files,e[9]=t):t=e[9],p=t}let m=p,h=0,g=0;if(e[10]!==h||e[11]!==m||e[12]!==g){for(let e of m)h+=e.insertions,g+=e.deletions;e[10]=h,e[11]=m,e[12]=g,e[13]=h,e[14]=g}else h=e[13],g=e[14];let _;e[15]!==h||e[16]!==g?(_={totalAdded:h,totalRemoved:g},e[15]=h,e[16]=g,e[17]=_):_=e[17];let{totalAdded:v,totalRemoved:y}=_;if(!a||s!==!0||m.length===0)return null;let b;e[18]!==a||e[19]!==u||e[20]!==o?.editor?(b=e=>{if(!a||!hb(e))return;r(!1);let t=e.path;if(u){u.openChanges({diffPath:e.relativePath,staged:e.hasStagedChanges&&!e.hasWorkingChanges});return}let n=o?.editor;if(n){n.openFile(t);return}let i=q.getState(),s=e.hasStagedChanges&&!e.hasWorkingChanges;if(!i.isMobile){i.openContextDiff(a,e.relativePath,s);return}i.navigateToDiff(e.relativePath,s),i.setRightSidebarOpen(!1)},e[18]=a,e[19]=u,e[20]=o?.editor,e[21]=b):b=e[21];let x=b,S=m.length,C;e[22]!==S||e[23]!==t?(C=t(S===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:S}),e[22]=S,e[23]=t,e[24]=C):C=e[24];let w=C,T,E;e[25]===Symbol.for(`react.memo_cache_sentinel`)?(T=Y(du,`max-w-full text-left`),E=()=>r(Mb),e[25]=T,e[26]=E):(T=e[25],E=e[26]);let D,O;e[27]===Symbol.for(`react.memo_cache_sentinel`)?(O=(0,$.jsx)(Z,{name:`file-edit`,className:mu}),D=Y(wu,`shrink-0`),e[27]=D,e[28]=O):(D=e[27],O=e[28]);let k;e[29]===w?k=e[30]:(k=(0,$.jsx)(`span`,{className:D,children:w}),e[29]=w,e[30]=k);let A;e[31]===Symbol.for(`react.memo_cache_sentinel`)?(A=Y(`status-row__changed-label`,wu),e[31]=A):A=e[31];let j;e[32]===t?j=e[33]:(j=t(`chat.pendingChanges.changedInWorkspace`),e[32]=t,e[33]=j);let M;e[34]===j?M=e[35]:(M=(0,$.jsx)(`span`,{className:A,children:j}),e[34]=j,e[35]=M);let N;e[36]===Symbol.for(`react.memo_cache_sentinel`)?(N=Y(lu,`items-baseline gap-0.5`),e[36]=N):N=e[36];let P;e[37]===v?P=e[38]:(P=v>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,v]}):null,e[37]=v,e[38]=P);let F;e[39]===y?F=e[40]:(F=y>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,y]}):null,e[39]=y,e[40]=F);let I;e[41]!==P||e[42]!==F?(I=(0,$.jsxs)(`span`,{className:N,children:[P,F]}),e[41]=P,e[42]=F,e[43]=I):I=e[43];let L;e[44]===n?L=e[45]:(L=n?(0,$.jsx)(Z,{name:`arrow-up-s`,className:mu}):(0,$.jsx)(Z,{name:`arrow-down-s`,className:mu}),e[44]=n,e[45]=L);let R;e[46]!==n||e[47]!==k||e[48]!==M||e[49]!==I||e[50]!==L?(R=(0,$.jsxs)(`button`,{type:`button`,className:T,onClick:E,"aria-expanded":n,children:[O,k,M,I,L]}),e[46]=n,e[47]=k,e[48]=M,e[49]=I,e[50]=L,e[51]=R):R=e[51];let z;e[52]!==a||e[53]!==m||e[54]!==x||e[55]!==n?(z=n&&(0,$.jsx)(`div`,{style:Ab,className:Y(kb,`absolute left-0 bottom-full mb-1 z-50`,`animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2`,`duration-150`),children:(0,$.jsx)(Ob,{files:m,currentDirectory:a,onOpenFile:x})}),e[52]=a,e[53]=m,e[54]=x,e[55]=n,e[56]=z):z=e[56];let B;return e[57]!==R||e[58]!==z?(B=(0,$.jsxs)(`div`,{className:`relative`,ref:i,children:[R,z]}),e[57]=R,e[58]=z,e[59]=B):B=e[59],B});jb.displayName=`PendingChangesBar`;function Mb(e){return!e}var Nb=Q.memo(e=>{let t=(0,pd.c)(22),{visible:n,onClick:r,placement:i}=e,a=i===void 0?`default`:i,{t:o}=Yt(),s=a===`compact`;if(s&&!n)return null;let c=a==="default"&&`absolute left-1/2 bottom-full mb-2 -translate-x-1/2`,l=a===`expanded`&&`absolute left-1/2 -translate-x-1/2 oc-scroll-to-bottom--expanded mb-2`,u=a===`compact`&&`oc-scroll-to-bottom--compact relative shrink-0`,d;t[0]!==a||t[1]!==c||t[2]!==l||t[3]!==u||t[4]!==n?(d=Y(c,l,u,n?Y(`pointer-events-auto`,a==="default"&&`opacity-100`):Y(`opacity-0 pointer-events-none`,a===`expanded`&&`oc-scroll-to-bottom--hidden`)),t[0]=a,t[1]=c,t[2]=l,t[3]=u,t[4]=n,t[5]=d):d=t[5];let f=s?`ghost`:`outline`,p=s?`composer-mobile-actions h-8 w-8 rounded-none bg-transparent hover:bg-transparent text-foreground`:`size-8 rounded-full [corner-shape:round] bg-background/95 hover:bg-interactive-hover`,m;t[6]===p?m=t[7]:(m=Y(`p-0 shadow-none`,p),t[6]=p,t[7]=m);let h;t[8]===o?h=t[9]:(h=o(`chat.scrollToBottom.aria`),t[8]=o,t[9]=h);let g=s?`size-5`:`size-4`,_=s?`medium`:`regular`,v;t[10]!==g||t[11]!==_?(v=(0,$.jsx)(Z,{name:`arrow-down`,className:g,weight:_}),t[10]=g,t[11]=_,t[12]=v):v=t[12];let y;t[13]!==r||t[14]!==v||t[15]!==f||t[16]!==m||t[17]!==h?(y=(0,$.jsx)(Qt,{variant:f,size:`sm`,onClick:r,className:m,"aria-label":h,children:v}),t[13]=r,t[14]=v,t[15]=f,t[16]=m,t[17]=h,t[18]=y):y=t[18];let b;return t[19]!==y||t[20]!==d?(b=(0,$.jsx)(`div`,{className:d,children:y}),t[19]=y,t[20]=d,t[21]=b):b=t[21],b}),Pb=Q.createContext(`default`),Fb=()=>Q.useContext(Pb),Ib=500,Lb=e=>{let t=(0,pd.c)(31),{onCycleAgent:n,onOpenAgentPanel:r,className:i,agentName:a,agents:o,disabled:s}=e,c;t[0]===o?c=t[1]:(c=o===void 0?[]:o,t[0]=o,t[1]=c);let l=c,u=s!==void 0&&s,d=a??void 0,f;t[2]!==l||t[3]!==d?(f=Ir(l,d),t[2]=l,t[3]=d,t[4]=f):f=t[4];let p=f,m=wv(d),h;t[5]===d?h=t[6]:(h=fo(d),t[5]=d,t[6]=h);let g=h,_=Q.useRef(null),v=Q.useRef(!1),y;t[7]!==u||t[8]!==r?(y=e=>{e.preventDefault(),!u&&(v.current=!1,_.current=setTimeout(()=>{v.current=!0,r()},Ib))},t[7]=u,t[8]=r,t[9]=y):y=t[9];let b=y,x;t[10]!==u||t[11]!==n?(x=()=>{_.current&&=(clearTimeout(_.current),null),!u&&!v.current&&n()},t[10]=u,t[11]=n,t[12]=x):x=t[12];let S=x,C;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(C=()=>{_.current&&=(clearTimeout(_.current),null)},t[13]=C):C=t[13];let w=C,T,E;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(E=()=>()=>{_.current&&clearTimeout(_.current)},T=[],t[14]=T,t[15]=E):(T=t[14],E=t[15]),Q.useEffect(E,T);let D;t[16]===i?D=t[17]:(D=Y(`inline-flex flex-shrink-0 items-center select-none focus:outline-none touch-none disabled:cursor-not-allowed disabled:opacity-40`,jv,i),t[16]=i,t[17]=D);let O;t[18]===Symbol.for(`react.memo_cache_sentinel`)?(O={height:`26px`,maxHeight:`26px`,minHeight:`26px`},t[18]=O):O=t[18];let k;t[19]!==g.var||t[20]!==p||t[21]!==d||t[22]!==m?(k=(0,$.jsx)(Cv,{name:d,label:p,revealed:m,avatarSize:16,slotClassName:`h-[26px] w-6`,colorVar:g.var}),t[19]=g.var,t[20]=p,t[21]=d,t[22]=m,t[23]=k):k=t[23];let A;return t[24]!==p||t[25]!==u||t[26]!==b||t[27]!==S||t[28]!==D||t[29]!==k?(A=(0,$.jsx)(`button`,{type:`button`,disabled:u,onPointerDown:b,onPointerUp:S,onPointerLeave:w,onContextMenu:Rb,onMouseDown:zb,className:D,style:O,title:p,"aria-label":p,children:k}),t[24]=p,t[25]=u,t[26]=b,t[27]=S,t[28]=D,t[29]=k,t[30]=A):A=t[30],A};function Rb(e){return e.preventDefault()}function zb(e){return e.preventDefault()}var Bb=e=>{let t=(0,pd.c)(28),{onOpenModel:n,className:r,providerID:i,modelID:a,provider:o,variant:s,disabled:c}=e,l=c!==void 0&&c,{t:u}=Yt(),d;t[0]!==a||t[1]!==o||t[2]!==u?(d=In(o,a,u(`chat.modelControls.selectModel`)),t[0]=a,t[1]=o,t[2]=u,t[3]=d):d=t[3];let f=d,p;t[4]===s?p=t[5]:(p=s?.trim()?Bn(s):null,t[4]=s,t[5]=p);let m=p,h=m?`${f} ${m}`:f,g;t[6]===r?g=t[7]:(g=Y(`inline-flex min-w-0 max-w-36 items-stretch`,`rounded-lg`,`focus:outline-none hover:bg-[var(--interactive-hover)] disabled:cursor-not-allowed disabled:opacity-40`,r),t[6]=r,t[7]=g);let _;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(_={height:`26px`,maxHeight:`26px`,minHeight:`26px`},t[8]=_):_=t[8];let v;t[9]!==a||t[10]!==i?(v=a||i?(0,$.jsx)(To,{modelId:a,providerId:i,className:`size-4 flex-shrink-0`}):null,t[9]=a,t[10]=i,t[11]=v):v=t[11];let y;t[12]===f?y=t[13]:(y=(0,$.jsx)(`span`,{className:`truncate text-[11px] leading-none font-medium text-foreground/80`,children:f}),t[12]=f,t[13]=y);let b;t[14]===m?b=t[15]:(b=m?(0,$.jsx)(`span`,{className:`shrink-0 text-[11px] leading-none font-normal text-muted-foreground`,children:m}):null,t[14]=m,t[15]=b);let x;t[16]!==y||t[17]!==b?(x=(0,$.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-1`,children:[y,b]}),t[16]=y,t[17]=b,t[18]=x):x=t[18];let S;t[19]!==v||t[20]!==x?(S=(0,$.jsxs)(`span`,{className:`flex h-full w-full min-w-0 items-center gap-1`,children:[v,x]}),t[19]=v,t[20]=x,t[21]=S):S=t[21];let C;return t[22]!==h||t[23]!==l||t[24]!==n||t[25]!==S||t[26]!==g?(C=(0,$.jsx)(`button`,{type:`button`,disabled:l,onClick:n,onMouseDown:Vb,onPointerDownCapture:Hb,className:g,style:_,title:h,"aria-label":h,children:S}),t[22]=h,t[23]=l,t[24]=n,t[25]=S,t[26]=g,t[27]=C):C=t[27],C};function Vb(e){return e.preventDefault()}function Hb(e){e.preventDefault()}var Ub={phase:`idle`,isWorking:!1,isBusy:!1,isCooldown:!1},Wb=e=>e.hasPendingAssistant?e.messages.some(e=>e.role===`assistant`&&typeof e.time?.completed==`number`):!1;function Gb(e,t){let n=(0,pd.c)(6),r=wi(e??``,t),i=oa(e??``,t),a=ka(e??``,t),o=ya(e??``,t),s=Na(e??``,t),c=Ba(t),l;bb0:{if(!e){l=Ub;break bb0}if(o.length>0||s.length>0){l=Ub;break bb0}let t=r?.type??`idle`,u=a[a.length-1],d=!!(u&&u.role===`assistant`&&typeof u.time?.completed!=`number`),f=a,p;n[0]!==d||n[1]!==f?(p=Wb({messages:f,hasPendingAssistant:d}),n[0]=d,n[1]=f,n[2]=p):p=n[2];let m=p,h=u?.time?.created,g=!!(m&&typeof c==`number`&&typeof h==`number`&&h<=c),_=r!==void 0,v=_&&t!==`idle`,y=v||m&&!g;if(_&&!v&&(!m||_&&!v&&typeof i==`number`&&typeof h==`number`&&h<=i)){l=Ub;break bb0}if(!y){l=Ub;break bb0}let b=v?t:`busy`,x=t===`busy`||!v&&m,S;n[3]!==b||n[4]!==x?(S={phase:b,isWorking:!0,isBusy:x,isCooldown:!1},n[3]=b,n[4]=x,n[5]=S):S=n[5],l=S}return l}var Kb=e=>!(!e.sessionId||e.composerSurfaceKind===`secondary`||e.hasSessionEntity||e.hasRenderableSessionSnapshot),qb=e=>{let t=e.isSubagentSession&&!e.allowPromptingSubagentSessions;return{showReadOnlyBanner:e.isSubagentSession&&(e.readOnly||t),blockSubmission:e.sessionIdentityPending}},Jb=(e,t)=>({agentName:t.agentName??e?.agentName,providerId:t.providerId??e?.providerId,modelId:t.modelId??e?.modelId}),Yb=(e,t)=>e.id===t.id&&e.directory===t.directory,Xb=(e,t)=>e.agentName===t.agentName&&e.providerId===t.providerId&&e.modelId===t.modelId,Zb=(e,t,n,r)=>{if(!t)return null;let i=n??(e?.viewKey===t?e.parentTarget:null);if(!i)return null;let a=Jb(e?.viewKey===t?e.execution:void 0,r);return e&&e.viewKey===t&&Yb(e.parentTarget,i)&&Xb(e.execution,a)?e:{viewKey:t,parentTarget:i,execution:a}},Qb=e=>{let{inFlight:t,establishing:n}=e.sendPhase,r=!n&&(e.draftSubmitting||t);return{sendDisabled:!e.canSend||!e.hasSessionTarget||e.submissionBlocked||r,queueDisabled:!e.hasSessionTarget||e.submissionBlocked||!n&&t||e.queueFrozen&&!e.queueFallbackAvailable,disabledClass:`opacity-30 pointer-events-none`}},$b=`data-mobile-overlay-active`,ex=e=>Array.from(e).some(e=>e.getAttribute($b)!==`false`),tx=`artful.bionic.cosmic.disco.focal.groovy.jammy.kinetic.lunar.noble.bold.brave.calm.eager.gentle.happy.keen.lively.merry.swift.warm.wise.bright.clever.daring.agile.crisp.fresh.lucid.quick.sharp.vivid.zealous`.split(`.`),nx=`aardvark.beaver.chipmunk.dolphin.falcon.gopher.hedgehog.jackal.koala.lemur.mongoose.narwhal.otter.pangolin.quokka.raccoon.salamander.toucan.walrus.yak.zebra.badger.condor.dingo.egret.ferret.gecko.heron.iguana`.split(`.`);function rx(){return`${tx[Math.floor(Math.random()*tx.length)]}-${nx[Math.floor(Math.random()*nx.length)]}`}function ix(e){let t=rx();return e&&e.trim()?`${e.trim().replace(/\/+$/,``)}/${t}`:t}var ax=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||e,ox=e=>({agentName:e.currentAgentName,providerId:e.currentProviderId,modelId:e.currentModelId,variant:e.currentVariant}),sx=(e,t,n)=>{let r=t.agentName?.trim()||void 0,i=t.providerId?.trim()||void 0,a=t.modelId?.trim()||void 0;!r||!i||!a||(n.saveSessionAgentSelection(e,r),n.saveSessionModelSelection(e,i,a),n.saveAgentModelForSession(e,r,i,a),n.saveAgentModelVariantForSession(e,r,i,a,t.variant))},cx=async(e,t)=>{await Wr(e)&&await Mi(t)},lx=e=>{let t=ax(e),n=eo.getState().projects;if(n.length===0)return null;let r=eo.getState().getActiveProject();if(r?.path){let e=ax(r.path);if(t===e||t.startsWith(`${e}/`))return{id:r.id,path:r.path}}let i=n.filter(e=>{let n=ax(e.path);return t===n||t.startsWith(`${n}/`)}).sort((e,t)=>ax(t.path).length-ax(e.path).length)[0];return i?{id:i.id,path:i.path}:null},ux=!1,dx=async(e,t)=>{try{let n=eo.getState().projects.find(e=>e.id===t.id)??eo.getState().projects.find(e=>ax(e.path)===ax(t.path)),r=pa(t.path);await Oa.getState().activateDirectory(t.path,{source:`worktreeSessionCreator`});let i=Oa.getState();if(i.activeDirectoryKey!==r||i.providers.length===0||i.agents.length===0)return;i.applyDefaultModelAgentSelection({projectDefaultModel:n?.defaultModel??void 0}),sx(e,ox(Oa.getState()),Hr.getState())}catch{}},fx=async(e,t,n)=>{let r=X.getState(),i=Oa.getState();r.initializeNewOpenChamberSession(e,i.agents),r.setSessionDirectory(e,t.path),r.setWorktreeMetadata(e,t),await dx(e,n),$e.getState().setDirectory(t.path,{showOverlay:!1})},px=e=>e.trim().replace(/^remotes\//,``).replace(/[^A-Za-z0-9._/-]+/g,`-`).replace(/\/+/g,`-`).replace(/-+/g,`-`).replace(/^-+|-+$/g,``)||`worktree`,mx=async e=>{if(ux)return null;let t=eo.getState().getActiveProject(),n=e?.projectDirectory?.trim()||t?.path;if(!n)return ro.error(`No active project`,{description:`Please select a project first.`}),null;let r=lx(n)??(t?.path?{id:t.id,path:t.path}:null);if(!r)return ro.error(`No active project`,{description:`Please select a project first.`}),null;let i=!1;try{i=await bo(r.path)}catch{}if(!i)return ro.error(`Not a Git repository`,{description:`Worktrees can only be created in Git repositories.`}),null;ux=!0;try{let t=La(),n=e?.existingBranch?.trim().replace(/^remotes\//,``)||``,i=n?px(n):ix(),a=n?`existing`:`new`,o=X.getState();o.newSessionDraft?.open?o.overrideNewSessionDraftTarget({projectId:r.id,directoryOverride:o.newSessionDraft.directoryOverride??r.path,pendingWorktreeRequestId:t,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt}):o.openNewSessionDraft({selectedProjectId:r.id,directoryOverride:r.path,pendingWorktreeRequestId:t,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt});let s=await yo(r.path,{mode:a,...a===`new`?{branchName:i,worktreeName:i}:{existingBranch:n,worktreeName:i}}).catch(()=>null);s?.path&&(X.getState().overrideNewSessionDraftTarget({projectId:r.id,directoryOverride:s.path,pendingWorktreeRequestId:t,bootstrapPendingDirectory:s.path,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt}),$e.getState().setDirectory(s.path,{showOverlay:!1}));let c=await mn(r),l=await yc(r,{preferredName:i,mode:a,worktreeName:i,setupCommands:c,returnAfterDirectoryCreated:!0,...a===`new`?{branchName:i}:{existingBranch:n}});return Aa(t,l.path),X.getState().overrideNewSessionDraftTarget({projectId:r.id,directoryOverride:l.path,pendingWorktreeRequestId:null,bootstrapPendingDirectory:l.path,preserveDirectoryOverride:!0,title:e?.title,initialPrompt:e?.initialPrompt}),$e.getState().setDirectory(l.path,{showOverlay:!1}),l.path}catch(e){let t=e instanceof Error?e.message:`Failed to create worktree`,n=X.getState().newSessionDraft.pendingWorktreeRequestId;return n&&(_a(n,e instanceof Error?e:Error(t)),X.getState().resolvePendingDraftWorktreeTarget(n,null)),X.getState().setDraftBootstrapPendingDirectory(null),ro.error(`Failed to create worktree`,{description:t}),null}finally{ux=!1}};async function hx(){return mx()}async function gx(e){let t=e.branch?.trim();return t?mx({existingBranch:t,projectDirectory:e.projectDirectory,initialPrompt:e.initialPrompt,title:e.title}):null}async function _x(e,t,n,r){if(ux)return null;ux=!0;try{let i=n?.trim()||`HEAD`,a=t?.trim();if(!a)throw Error(`Branch name is required`);let o=r?.kind??`standard`,s=lx(e);if(!s)throw Error(`Project is not registered in OpenChamber`);let c=!1;try{c=await bo(s.path)}catch{}if(!c)return ro.error(`Not a Git repository`,{description:`Worktrees can only be created in Git repositories.`}),null;let l=await mn(s),u=await Mo(s.path);try{let e=await yc(s,{preferredName:a,mode:`new`,branchName:a,worktreeName:r?.worktreeName||a,startRef:i,setUpstream:r?.setUpstream,upstreamRemote:r?.upstreamRemote,upstreamBranch:r?.upstreamBranch,ensureRemoteName:r?.ensureRemoteName,ensureRemoteUrl:r?.ensureRemoteUrl,setupCommands:l,returnAfterDirectoryCreated:r?.returnAfterDirectoryCreated}),t={...e,createdFromBranch:r?.createdFromBranch||u||i,kind:o};await cx(s,e.path);let n=await X.getState().createSession(void 0,e.path);if(!n)throw await Io(s,e,{deleteLocalBranch:!0}).catch(()=>void 0),Error(`Could not create a session for the worktree.`);return await fx(n.id,t,s),{id:n.id,branch:e.branch||a,path:e.path}}catch(e){let t=e instanceof Error?e.message:`Failed to create worktree session`;return ro.error(`Failed to create worktree`,{description:t}),null}}finally{ux=!1}}var vx=e=>{let t=e.trim();if(!t)return null;let n=t.match(/\/issues\/(\d+)(?:\b|\/|$)/i);if(n){let e=Number(n[1]);return Number.isFinite(e)&&e>0?e:null}let r=t.match(/^#?(\d+)$/);if(r){let e=Number(r[1]);return Number.isFinite(e)&&e>0?e:null}return null},yx=e=>{let t={repo:e.repo??null,issue:e.issue,comments:e.comments};return`GitHub issue context (JSON)\n${JSON.stringify(t,null,2)}`};function bx({open:e,onOpenChange:t,mode:n=`createSession`,onSelect:r}){let{t:i}=Yt(),{github:a}=rc(),o=hs(),s=o.data??null,c=o.isFetched,l=q(e=>e.setSettingsDialogOpen),u=q(e=>e.setSettingsPage),d=q(e=>e.isMobile),{isTablet:f}=qs(),p=d||f,m=eo(e=>e.getActiveProject()),h=$e(e=>e.currentDirectory),g=Q.useMemo(()=>m?.path?.trim()||h?.trim()||null,[m?.path,h]),[_,v]=Q.useState(``),[y,b]=Q.useState(!1),[x,S]=Q.useState(null),C=Q.useRef(0),w=Q.useMemo(()=>vx(_),[_]),T=Sc(_,350),E=w?``:T.trim(),D=!!w||_===T,O=e&&D&&!!g&&!!a?.issuesList&&!(c&&s?.connected===!1),k=Mt({queryKey:ee.scoped(`github-issues`,g,E),enabled:O,initialPageParam:1,refetchOnMount:`always`,queryFn:({pageParam:e})=>a.issuesList(g,{page:e,...E?{query:E}:{}}),getNextPageParam:e=>e.hasMore?(e.page??1)+1:void 0}),A=D?k.data?.pages.at(-1)??null:null,j=D?k.data?.pages.flatMap(e=>e.issues??[])??[]:[],M=D&&k.hasNextPage,N=!w&&!D||k.isLoading,P=D&&k.isFetchingNextPage,F=D&&k.error?k.error instanceof Error?k.error.message:String(k.error):null,I=Q.useCallback(()=>k.refetch(),[k]),L=Q.useCallback(async()=>{try{await k.fetchNextPage()}catch(e){let t=e instanceof Error?e.message:String(e);ro.error(i(`session.githubIssuePicker.toast.loadMoreFailed`),{description:t})}},[k,i]);Q.useEffect(()=>{e||(++C.current,v(``),b(!1),S(null))},[e]),Q.useEffect(()=>{++C.current},[e,g]);let R=!c||s?.connected!==!1&&A?.connected!==!1,z=A?.repo?.url??null,B=Q.useCallback(()=>{u(`github`),l(!0)},[l,u]),V=Q.useCallback(()=>{let e=Oa.getState(),t=e.getVisibleAgents();if(e.settingsDefaultAgent){let n=t.find(t=>t.name===e.settingsDefaultAgent);if(n)return n.name}return t.find(e=>e.name===`build`)?.name||t[0]?.name},[]),H=Q.useCallback(()=>{let e=Oa.getState(),t=e.settingsDefaultModel;if(!t)return null;let n=tr(t);if(!n)return null;let{providerId:r,modelId:i}=n;return e.getModelMetadata(r,i)?{providerID:r,modelID:i}:null},[]),U=Q.useCallback((e,t)=>{let n=Oa.getState(),r=n.settingsDefaultVariant,i=n.currentProviderId===e&&n.currentModelId===t?n.currentVariant:void 0,a=n.providers.find(t=>t.id===e)?.models.find(e=>e.id===t)?.variants;if(!a)return r||i||void 0;if(r&&Object.prototype.hasOwnProperty.call(a,r))return r;if(i&&Object.prototype.hasOwnProperty.call(a,i))return i},[]),te=Q.useCallback(async(e,o)=>{let s=++C.current,c=()=>C.current===s;if(n===`select`){if(!g){ro.error(i(`session.githubIssuePicker.error.noActiveProject`));return}if(!a?.issueGet||!a?.issueComments){ro.error(i(`session.githubIssuePicker.error.runtimeUnavailable`));return}if(x)return;S(e);try{let n=await a.issueGet(g,e,{sourceRepo:o});if(!c())return;if(n.connected===!1){ro.error(i(`session.githubIssuePicker.error.notConnected`));return}if(!n.repo){ro.error(i(`session.githubIssuePicker.error.repoNotResolvable`),{description:i(`session.githubIssuePicker.error.repoMustBeGithub`)});return}let s=n.issue;if(!s){ro.error(i(`session.githubIssuePicker.error.issueNotFound`));return}let l=await a.issueComments(g,e,{sourceRepo:o});if(!c())return;if(l.connected===!1){ro.error(i(`session.githubIssuePicker.error.notConnected`));return}let u=l.comments??[],d=yx({repo:n.repo,issue:s,comments:u});r&&r({number:s.number,title:s.title,url:s.url,contextText:d,author:s.author?{login:s.author.login,avatarUrl:s.author.avatarUrl}:void 0}),t(!1)}catch(e){if(!c())return;let t=e instanceof Error?e.message:String(e);ro.error(i(`session.githubIssuePicker.toast.loadIssueDetailsFailed`),{description:t})}finally{c()&&S(null)}return}if(!g){ro.error(i(`session.githubIssuePicker.error.noActiveProject`));return}if(!a?.issueGet||!a?.issueComments){ro.error(i(`session.githubIssuePicker.error.runtimeUnavailable`));return}if(!x){S(e);try{let n=await a.issueGet(g,e,{sourceRepo:o});if(!c())return;if(n.connected===!1){ro.error(i(`session.githubIssuePicker.error.notConnected`));return}if(!n.repo){ro.error(i(`session.githubIssuePicker.error.repoNotResolvable`),{description:i(`session.githubIssuePicker.error.repoMustBeGithub`)});return}let r=n.issue;if(!r){ro.error(i(`session.githubIssuePicker.error.issueNotFound`));return}let s=await a.issueComments(g,e,{sourceRepo:o});if(!c())return;if(s.connected===!1){ro.error(i(`session.githubIssuePicker.error.notConnected`));return}let l=s.comments??[],u=`#${r.number} ${r.title}`.trim(),{sessionId:d}=await(async()=>{if(y){let e=`issue-${r.number}-${rx()}`,t=await _x(g,e,void 0,{returnAfterDirectoryCreated:!0});if(!t?.id)throw Error(`Failed to create worktree session`);return{sessionId:t.id,sessionDirectory:t.path}}let e=await hn(u,g,null);if(!e?.id)throw Error(`Failed to create session`);return{sessionId:e.id,sessionDirectory:e.directory??g}})();if(!c())return;Cr(d,u).catch(()=>void 0);try{X.getState().initializeNewOpenChamberSession(d,Oa.getState().agents)}catch{}t(!1);let f=Oa.getState(),p=Hr.getState().lastUsedProvider,m=H(),h=m?.providerID||f.currentProviderId||p?.providerID,_=m?.modelID||f.currentModelId||p?.modelID,v=V()||f.currentAgentName||void 0;if(!h||!_){ro.error(i(`session.githubIssuePicker.error.noModelSelected`));return}let b=U(h,_),x=await ii(`github.issue.review.visible`,{issue_number:String(r.number)});if(!c())return;let S=await ii(`github.issue.review.instructions`);if(!c())return;let C=yx({repo:n.repo,issue:r,comments:l});X.getState().sendMessage(x,h,_,v,void 0,void 0,[{text:S,synthetic:!0},{text:C,synthetic:!0}],b,void 0,{sessionId:d}).catch(e=>{let t=e instanceof Error?e.message:String(e);ro.error(i(`session.githubIssuePicker.toast.sendContextFailed`),{description:t})}),ro.success(i(`session.githubIssuePicker.toast.sessionCreated`))}catch(e){if(!c())return;let t=e instanceof Error?e.message:String(e);ro.error(i(`session.githubIssuePicker.toast.startSessionFailed`),{description:t})}finally{c()&&S(null)}}},[y,a,n,t,r,g,V,H,U,x,i]),W=i(n===`select`?`session.githubIssuePicker.title.select`:`session.githubIssuePicker.title.createSession`),ne=i(n===`select`?`session.githubIssuePicker.description.select`:`session.githubIssuePicker.description.createSession`),G=(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[(0,$.jsx)(Z,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Ko,{placeholder:i(`session.githubIssuePicker.searchPlaceholder`),value:_,onChange:e=>{v(e.target.value)},className:`pl-9 w-full`})]}),(0,$.jsxs)(`div`,{className:Y(d?`min-h-0 mt-2`:`flex-1 overflow-y-auto mt-2`),children:[g?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:i(`session.githubIssuePicker.empty.noActiveProject`)}),a?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:i(`session.githubIssuePicker.empty.runtimeUnavailable`)}),N?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 flex items-center justify-center gap-2`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),i(`session.githubIssuePicker.loading.issues`)]}):null,R===!1?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 space-y-3`,children:[(0,$.jsx)(`div`,{children:i(`session.githubIssuePicker.empty.notConnected`)}),(0,$.jsx)(`div`,{className:`flex justify-center`,children:(0,$.jsx)(Qt,{variant:`outline`,size:`sm`,onClick:B,children:i(`session.githubIssuePicker.actions.openSettings`)})})]}):null,F?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8 break-words`,children:F}):null,w&&g&&a&&R?(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,x===w&&`bg-interactive-selection/30`),onClick:()=>void te(w),children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground w-5 text-right flex-shrink-0`,children:`#`}),(0,$.jsx)(`p`,{className:`flex-1 min-w-0 typography-small text-foreground truncate ml-0.5`,children:i(`session.githubIssuePicker.actions.useIssue`,{number:w})}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:x===w?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):null})]}):null,j.length===0&&!N&&!F&&R&&a&&g?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:T.trim()?i(`session.githubIssuePicker.empty.noIssuesFound`):i(`session.githubIssuePicker.empty.noOpenIssuesFound`)}):null,j.map(e=>(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,x===e.number&&`bg-interactive-selection/30`),onClick:()=>void te(e.number,e.sourceRepo),children:[(0,$.jsxs)(`span`,{className:`typography-meta text-muted-foreground w-12 text-right flex-shrink-0`,children:[`#`,e.number]}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 ml-0.5`,children:[(0,$.jsx)(`p`,{className:`typography-small text-foreground truncate`,children:e.title}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info mt-0.5 inline-block`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:x===e.number?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):(0,$.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:Y(`h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,p?`flex`:`hidden group-hover:flex`),onClick:e=>e.stopPropagation(),"aria-label":i(`session.githubIssuePicker.actions.openInGitHubAria`),children:(0,$.jsx)(Z,{name:`external-link`,className:`h-4 w-4`})})})]},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)),M&&R&&g&&a?(0,$.jsx)(`div`,{className:`py-2 flex justify-center`,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void L(),disabled:P||!!x,className:Y(`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4`,(P||!!x)&&`opacity-50 cursor-not-allowed hover:text-muted-foreground`),children:P?(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),i(`session.githubIssuePicker.loading.more`)]}):i(`session.githubIssuePicker.actions.loadMore`)})}):null]}),n!==`select`&&(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:i(`session.githubIssuePicker.actions.sectionTitle`)}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 cursor-pointer`,role:`button`,tabIndex:0,"aria-pressed":y,onClick:()=>b(e=>!e),onKeyDown:e=>{(e.key===` `||e.key===`Enter`)&&(e.preventDefault(),b(e=>!e))},children:[(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.preventDefault(),e.stopPropagation(),b(e=>!e)},"aria-label":i(`session.githubIssuePicker.actions.toggleWorktreeAria`),className:`flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary`,children:y?(0,$.jsx)(Z,{name:`checkbox`,className:`h-4 w-4 text-primary`}):(0,$.jsx)(Z,{name:`checkbox-blank`,className:`h-4 w-4`})}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:i(`session.githubIssuePicker.actions.createInWorktree`)}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground/70 hidden sm:inline`,children:`(issue-<number>-<slug>)`})]}),(0,$.jsx)(`div`,{className:`hidden sm:block sm:flex-1`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[z?(0,$.jsx)(Qt,{variant:`outline`,size:`sm`,asChild:!0,children:(0,$.jsxs)(`a`,{href:z,target:`_blank`,rel:`noopener noreferrer`,children:[(0,$.jsx)(Z,{name:`external-link`,className:`size-4`}),i(`session.githubIssuePicker.actions.openRepo`)]})}):null,(0,$.jsx)(Qt,{variant:`outline`,size:`sm`,onClick:I,disabled:N||!!x,children:i(`session.githubIssuePicker.actions.refresh`)})]})]})]})]});return d?(0,$.jsx)(Hs,{open:e,title:W,onClose:()=>t(!1),renderHeader:e=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 px-3 py-2 border-b border-border/40`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`typography-ui-label font-semibold text-foreground`,children:W}),e]}),(0,$.jsx)(`p`,{className:`typography-small text-muted-foreground`,children:ne})]}),children:G}):(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsxs)(po,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsxs)(lo,{className:`flex-shrink-0`,children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`github`,className:`h-5 w-5`}),W]}),(0,$.jsx)(ho,{children:ne})]}),G]})})}var xx=e=>{let t=e.trim();if(!t)return null;let n=t.match(/\/pull\/(\d+)(?:\b|\/|$)/i);if(n){let e=Number(n[1]);return Number.isFinite(e)&&e>0?e:null}let r=t.match(/^#?(\d+)$/);if(r){let e=Number(r[1]);return Number.isFinite(e)&&e>0?e:null}return null},Sx=e=>`GitHub pull request context (JSON)\n${JSON.stringify(e,null,2)}`;function Cx({open:e,onOpenChange:t,onSelect:n}){let{t:r}=Yt(),{github:i}=rc(),a=hs(),o=a.data??null,s=a.isFetched,c=q(e=>e.setSettingsDialogOpen),l=q(e=>e.setSettingsPage),u=q(e=>e.isMobile),{isTablet:d}=qs(),f=u||d,p=eo(e=>e.getActiveProject())?.path??null,[m,h]=Q.useState(``),[g,_]=Q.useState(!1),[v,y]=Q.useState(null),b=Q.useRef(0),x=Q.useMemo(()=>xx(m),[m]),S=Sc(m,350),C=x?``:S.trim(),w=!!x||m===S,T=e&&w&&!!p&&!!i?.prsList&&!(s&&o?.connected===!1),E=Mt({queryKey:ee.scoped(`github-prs`,p,C),enabled:T,initialPageParam:1,refetchOnMount:`always`,queryFn:({pageParam:e})=>i.prsList(p,{page:e,...C?{query:C}:{}}),getNextPageParam:e=>e.hasMore?(e.page??1)+1:void 0}),D=w?E.data?.pages.at(-1)??null:null,O=w?E.data?.pages.flatMap(e=>e.prs??[])??[]:[],k=w&&E.hasNextPage,A=!x&&!w||E.isLoading,j=w&&E.isFetchingNextPage,M=w&&E.error?E.error instanceof Error?E.error.message:String(E.error):null,N=J(async()=>{try{await E.fetchNextPage()}catch(e){let t=e instanceof Error?e.message:String(e);ro.error(r(`session.githubPrPicker.toast.loadMoreFailed`),{description:t})}});Q.useEffect(()=>{e||(++b.current,h(``),_(!1),y(null))},[e]),Q.useEffect(()=>{++b.current},[e,p]);let P=!s||o?.connected!==!1&&D?.connected!==!1,F=J(()=>{l(`github`),c(!0)}),I=J(async(e,a)=>{if(!p){ro.error(r(`session.githubPrPicker.error.noActiveProject`));return}if(!i?.prContext){ro.error(r(`session.githubPrPicker.error.runtimeUnavailable`));return}if(v)return;let o=++b.current,s=()=>b.current===o;y(e);try{let o=await i.prContext(p,e,{includeDiff:g,includeCheckDetails:!1,sourceRepo:a});if(!s())return;if(o.connected===!1){ro.error(r(`session.githubPrPicker.error.notConnected`));return}if(!o.pr){ro.error(r(`session.githubPrPicker.error.prNotFound`));return}if(!o.repo){ro.error(r(`session.githubPrPicker.error.repoNotResolvable`),{description:r(`session.githubPrPicker.error.repoMustBeGithub`)});return}if(n){let e=await ii(`github.pr.review.instructions`);if(!s())return;n({number:o.pr.number,title:o.pr.title,url:o.pr.url,head:o.pr.head,base:o.pr.base,includeDiff:g,instructionsText:e,contextText:Sx(o),author:o.pr.author?{login:o.pr.author.login,avatarUrl:o.pr.author.avatarUrl}:void 0})}t(!1)}catch(e){if(!s())return;let t=e instanceof Error?e.message:String(e);ro.error(r(`session.githubPrPicker.toast.loadDetailsFailed`),{description:t})}finally{s()&&y(null)}}),L=r(`session.githubPrPicker.title`),R=r(`session.githubPrPicker.description`),z=(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`mt-2 flex items-center gap-3`,children:[(0,$.jsxs)(`div`,{className:`relative flex-1 min-w-0`,children:[(0,$.jsx)(Z,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Ko,{placeholder:r(`session.githubPrPicker.searchPlaceholder`),value:m,onChange:e=>{h(e.target.value)},className:`pl-9 w-full`})]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>_(e=>!e),className:`h-9 shrink-0 flex items-center gap-2 text-left`,"aria-pressed":g,"aria-label":r(`session.githubPrPicker.includeDiffAria`),children:[(0,$.jsx)(`span`,{onClick:e=>e.stopPropagation(),children:(0,$.jsx)(Oo,{checked:g,onChange:e=>_(e),ariaLabel:r(`session.githubPrPicker.includeDiffAria`)})}),(0,$.jsx)(`span`,{className:`typography-small text-muted-foreground whitespace-nowrap`,children:r(`session.githubPrPicker.includeDiff`)})]})]}),(0,$.jsxs)(`div`,{className:Y(u?`min-h-0`:`flex-1 overflow-y-auto`),children:[p?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:r(`session.githubPrPicker.empty.noActiveProject`)}),i?null:(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:r(`session.githubPrPicker.empty.runtimeUnavailable`)}),A?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 flex items-center justify-center gap-2`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),r(`session.githubPrPicker.loading.pullRequests`)]}):null,P===!1?(0,$.jsxs)(`div`,{className:`text-center text-muted-foreground py-8 space-y-3`,children:[(0,$.jsx)(`div`,{children:r(`session.githubPrPicker.empty.notConnected`)}),(0,$.jsx)(`div`,{className:`flex justify-center`,children:(0,$.jsx)(Qt,{variant:`outline`,size:`sm`,onClick:F,children:r(`session.githubPrPicker.actions.openSettings`)})})]}):null,M?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8 break-words`,children:M}):null,x&&p&&i&&P?(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,v===x&&`bg-interactive-selection/30`),onClick:()=>void I(x),children:[(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground w-5 text-right flex-shrink-0`,children:`#`}),(0,$.jsx)(`p`,{className:`flex-1 min-w-0 typography-small text-foreground truncate ml-0.5`,children:r(`session.githubPrPicker.actions.usePullRequest`,{number:x})}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:v===x?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):null})]}):null,O.length===0&&!A&&!M&&P&&i&&p?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:S.trim()?r(`session.githubPrPicker.empty.noPullRequestsFound`):r(`session.githubPrPicker.empty.noOpenPullRequestsFound`)}):null,O.map(e=>(0,$.jsxs)(`div`,{className:Y(`group flex items-center gap-2 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,v===e.number&&`bg-interactive-selection/30`),onClick:()=>void I(e.number,e.sourceRepo),children:[(0,$.jsxs)(`div`,{className:`flex-1 min-w-0 ml-0.5`,children:[(0,$.jsxs)(`p`,{className:`typography-small text-foreground truncate`,children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground mr-1`,children:[`#`,e.number]}),e.title]}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null,(0,$.jsxs)(`p`,{className:`typography-meta text-muted-foreground truncate`,children:[e.head,` → `,e.base]})]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:v===e.number?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`}):(0,$.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noopener noreferrer`,className:Y(`h-5 w-5 items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,f?`flex`:`hidden group-hover:flex`),onClick:e=>e.stopPropagation(),"aria-label":r(`session.githubPrPicker.actions.openInGitHubAria`),children:(0,$.jsx)(Z,{name:`external-link`,className:`h-4 w-4`})})})]},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)),k&&P&&p&&i?(0,$.jsx)(`div`,{className:`py-2 flex justify-center`,children:(0,$.jsx)(`button`,{type:`button`,onClick:()=>void N(),disabled:j||!!v,className:Y(`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-4`,(j||!!v)&&`opacity-50 cursor-not-allowed hover:text-muted-foreground`),children:j?(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}),r(`session.githubPrPicker.loading.more`)]}):r(`session.githubPrPicker.actions.loadMore`)})}):null]})]});return u?(0,$.jsx)(Hs,{open:e,title:L,onClose:()=>t(!1),renderHeader:e=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 px-3 py-2 border-b border-border/40`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`typography-ui-label font-semibold text-foreground`,children:L}),e]}),(0,$.jsx)(`p`,{className:`typography-small text-muted-foreground`,children:R})]}),children:z}):(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsxs)(po,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsxs)(lo,{className:`flex-shrink-0`,children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`github`,className:`h-5 w-5`}),L]}),(0,$.jsx)(ho,{children:R})]}),z]})})}function wx(e){let t=(0,pd.c)(12),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({className:n,style:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a;t[4]===i?a=t[5]:(a={color:`var(--surface-elevated-foreground)`,...i},t[4]=i,t[5]=a);let o;t[6]===n?o=t[7]:(o=Y(`flex h-full w-full flex-col overflow-hidden rounded-xl`,n),t[6]=n,t[7]=o);let s;return t[8]!==r||t[9]!==a||t[10]!==o?(s=(0,$.jsx)(nd,{"data-slot":`command`,style:a,className:o,...r}),t[8]=r,t[9]=a,t[10]=o,t[11]=s):s=t[11],s}var Tx=Q.forwardRef((e,t)=>{let n=(0,pd.c)(11),r,i;n[0]===e?(r=n[1],i=n[2]):({className:r,...i}=e,n[0]=e,n[1]=r,n[2]=i);let a,o;n[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=Y(`flex h-8 items-center gap-2 rounded-lg px-3`,`bg-[var(--surface-elevated)] ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)] hover:[&:not(:focus-within)]:ring-transparent`,`focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]`),o=(0,$.jsx)(Z,{name:`search`,className:`size-4 shrink-0 opacity-50`}),n[3]=a,n[4]=o):(a=n[3],o=n[4]);let s;n[5]===r?s=n[6]:(s=Y(`placeholder:text-muted-foreground flex h-8 w-full bg-transparent typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50`,r),n[5]=r,n[6]=s);let c;return n[7]!==i||n[8]!==t||n[9]!==s?(c=(0,$.jsx)(`div`,{"data-slot":`command-input-wrapper`,className:`p-1.5 pb-1`,children:(0,$.jsxs)(`div`,{"data-slot":`command-input-field`,className:a,children:[o,(0,$.jsx)(nd.Input,{ref:t,"data-slot":`command-input`,className:s,...i})]})}),n[7]=i,n[8]=t,n[9]=s,n[10]=c):c=n[10],c});Tx.displayName=`CommandInput`;function Ex(e){let t=(0,pd.c)(14),n,r,i,a,o;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5]):({className:r,children:n,scrollbarClassName:o,disableHorizontal:i,...a}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o);let s;t[6]===r?s=t[7]:(s=Y(`scroll-py-1 overflow-x-hidden h-full min-h-0`,r),t[6]=r,t[7]=s);let c=o??`overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero`,l=i??!0,u;return t[8]!==n||t[9]!==a||t[10]!==s||t[11]!==c||t[12]!==l?(u=(0,$.jsx)(bl,{as:nd.List,"data-slot":`command-list`,outerClassName:`max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0`,className:s,scrollbarClassName:c,disableHorizontal:l,...a,children:n}),t[8]=n,t[9]=a,t[10]=s,t[11]=c,t[12]=l,t[13]=u):u=t[13],u}function Dx(e){let t=(0,pd.c)(4),n;t[0]===e?n=t[1]:({...n}=e,t[0]=e,t[1]=n);let r;return t[2]===n?r=t[3]:(r=(0,$.jsx)(nd.Empty,{"data-slot":`command-empty`,className:`py-6 text-center typography-ui-label`,...n}),t[2]=n,t[3]=r),r}function Ox(e){let t=(0,pd.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,$.jsx)(nd.Group,{"data-slot":`command-group`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function kx(e){let t=(0,pd.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`bg-border -mx-1 h-px`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,$.jsx)(nd.Separator,{"data-slot":`command-separator`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}function Ax(e){let t=(0,pd.c)(8),n,r;t[0]===e?(n=t[1],r=t[2]):({className:n,...r}=e,t[0]=e,t[1]=n,t[2]=r);let i;t[3]===n?i=t[4]:(i=Y(`data-[selected=true]:bg-interactive-selection data-[selected=true]:text-interactive-selection-foreground data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,n),t[3]=n,t[4]=i);let a;return t[5]!==r||t[6]!==i?(a=(0,$.jsx)(nd.Item,{"data-slot":`command-item`,className:i,...r}),t[5]=r,t[6]=i,t[7]=a):a=t[7],a}var jx=(e,t)=>`${e}:${j(t)}`,Mx=e=>e.type===`skill`||!xe(e.name);function Nx(e){let{t}=Yt(),n=Q.useMemo(()=>ge(),[]),r=q(e=>e.globalDraftStarters),i=eo(e=>e.activeProjectId),a=eo(e=>e.projects),o=Q.useMemo(()=>{if(!i)return null;let e=a.find(e=>e.id===i);return e?.path?{id:e.id,path:e.path}:null},[i,a]),[s,c]=Q.useState([]),l=Q.useMemo(()=>r??Ce,[r]),u=l.some(Mx)||s.some(Mx),d=bi({directory:e,enabled:u}),f=Q.useMemo(()=>d.data??[],[d.data]),{refetch:p}=d,m=hi({directory:e,enabled:u}),g=Q.useMemo(()=>m.data??[],[m.data]),{refetch:_}=m;Q.useEffect(()=>{let e=!1;if(!o){c([]);return}return so(o).then(t=>{e||c(t)}).catch(()=>{e||c([])}),()=>{e=!0}},[o?.id]);let v=Q.useCallback(()=>{p(),_()},[p,_]),y=Q.useMemo(()=>new Set(f.map(e=>e.name)),[f]),b=Q.useMemo(()=>new Set(g.map(e=>e.name)),[g]),x=Q.useCallback((e,r)=>{if(n&&e.type===`command`&&e.name===`craft-goal`)return null;if(e.type===`command`){let n=xe(e.name);return n?{id:jx(r,e),ref:e,group:r,label:t(n.labelKey),icon:n.icon,submitText:n.command}:y.has(e.name)?{id:jx(r,e),ref:e,group:r,label:A(e.name),icon:be,submitText:`/${e.name}`}:null}return b.has(e.name)?{id:jx(r,e),ref:e,group:r,label:A(e.name),icon:B,submitText:`/${e.name}`}:null},[t,y,b,n]),S=Q.useMemo(()=>l.map(e=>x(e,`global`)).filter(e=>e!==null),[l,x]),C=Q.useMemo(()=>s.map(e=>x(e,`project`)).filter(e=>e!==null),[s,x]),w=Q.useMemo(()=>{let e=new Set;for(let t of l)e.add(j(t));for(let t of s)e.add(j(t));return e},[l,s]),T=Q.useMemo(()=>{let e=[];for(let r of z)n&&r.name===`craft-goal`||e.push({type:`command`,name:r.name,label:t(r.labelKey),icon:r.icon,section:`built-in`,scope:`user`});for(let t of f)t.isBuiltIn||t.source===`skill`||xe(t.name)||e.push({type:`command`,name:t.name,label:A(t.name),icon:be,section:`command`,scope:t.scope===`project`?`project`:`user`});for(let t of g)e.push({type:`skill`,name:t.name,label:A(t.name),icon:B,section:`skill`,scope:t.scope===`project`?`project`:`user`});return e.filter(e=>!w.has(`${e.type}:${e.name}`))},[t,f,g,w,n]),E=Q.useCallback(e=>{q.getState().setGlobalDraftStarters(e),pe({draftStarters:e})},[]),D=Q.useCallback(e=>{c(e),o&&Rr(o,e)},[o]),O=Q.useCallback(e=>{let t={type:e.type,name:e.name};if(e.scope===`project`){if(!o||s.some(e=>h(e,t)))return;D([...s,t])}else{let e=r??Ce;if(e.some(e=>h(e,t)))return;E([...e,t])}},[o,s,r,D,E]),k=Q.useCallback((e,t)=>{e===`project`?D(s.filter(e=>!h(e,t))):E((r??Ce).filter(e=>!h(e,t)))},[s,r,D,E]),M=Q.useCallback((e,t,n)=>{let i=e===`project`?s:r??Ce,a=i.findIndex(n=>jx(e,n)===t),o=i.findIndex(t=>jx(e,t)===n);if(a<0||o<0||a===o)return;let c=Ml([...i],a,o);e===`project`?D(c):E(c)},[s,r,D,E]);return{global:S,project:C,pinnable:T,hasProject:!!o,ensureLoaded:v,addStarter:O,removeStarter:k,reorder:M}}var Px=`__draft-starter-trash__`,Fx=`inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-[var(--interactive-hover)] hover:text-foreground`,Ix=`max-h-7`,Lx=[{key:`built-in`,headingKey:`chat.draftStarters.sectionBuiltIn`},{key:`command`,headingKey:`chat.draftStarters.sectionCommands`},{key:`skill`,headingKey:`chat.draftStarters.sectionSkills`}],Rx=e=>{let t=(0,pd.c)(35),{item:n,onSubmit:r,onRemove:i,hideRemove:a}=e,{t:o}=Yt(),s;t[0]===n.id?s=t[1]:(s={id:n.id},t[0]=n.id,t[1]=s);let{attributes:c,listeners:l,setNodeRef:u,transform:d,transition:f,isDragging:p}=Nl(s),m;t[2]===d?m=t[3]:(m=Al.Translate.toString(d),t[2]=d,t[3]=m);let h;t[4]!==m||t[5]!==f?(h={transform:m,transition:f},t[4]=m,t[5]=f,t[6]=h):h=t[6];let g=p&&`z-10 opacity-60`,_;t[7]===g?_=t[8]:(_=Y(`group/chip relative`,g),t[7]=g,t[8]=_);let v;t[9]!==n.submitText||t[10]!==r?(v=()=>r(n.submitText),t[9]=n.submitText,t[10]=r,t[11]=v):v=t[11];let y=!a&&`pr-5`,b;t[12]===y?b=t[13]:(b=Y(`group inline-flex touch-none select-none items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors`,`hover:bg-[var(--interactive-hover)] hover:text-foreground`,y),t[12]=y,t[13]=b);let x;t[14]===n.icon?x=t[15]:(x=(0,$.jsx)(Z,{name:n.icon,className:`h-3 w-3 shrink-0 opacity-60 transition-opacity group-hover:opacity-100`}),t[14]=n.icon,t[15]=x);let S;t[16]===n.label?S=t[17]:(S=(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:n.label}),t[16]=n.label,t[17]=S);let C;t[18]!==c||t[19]!==l||t[20]!==S||t[21]!==v||t[22]!==b||t[23]!==x?(C=(0,$.jsxs)(`button`,{type:`button`,...c,...l,onClick:v,className:b,children:[x,S]}),t[18]=c,t[19]=l,t[20]=S,t[21]=v,t[22]=b,t[23]=x,t[24]=C):C=t[24];let w;t[25]!==a||t[26]!==i||t[27]!==o?(w=a?null:(0,$.jsx)(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),i()},"aria-label":o(`chat.draftStarters.remove`),title:o(`chat.draftStarters.remove`),className:`absolute right-0.5 top-1/2 hidden h-4 w-4 -translate-y-1/2 items-center justify-center rounded text-muted-foreground hover:text-foreground group-hover/chip:flex`,children:(0,$.jsx)(Z,{name:`close`,className:`h-2.5 w-2.5`})}),t[25]=a,t[26]=i,t[27]=o,t[28]=w):w=t[28];let T;return t[29]!==u||t[30]!==C||t[31]!==w||t[32]!==h||t[33]!==_?(T=(0,$.jsxs)(`div`,{ref:u,style:h,className:_,children:[C,w]}),t[29]=u,t[30]=C,t[31]=w,t[32]=h,t[33]=_,t[34]=T):T=t[34],T},zx=e=>{let t=(0,pd.c)(14),{items:n,onSubmit:r,onRemove:i,hideRemove:a}=e,o;t[0]===n?o=t[1]:(o=n.map(Wx),t[0]=n,t[1]=o);let s;if(t[2]!==a||t[3]!==n||t[4]!==i||t[5]!==r){let e;t[7]!==a||t[8]!==i||t[9]!==r?(e=e=>(0,$.jsx)(Rx,{item:e,onSubmit:r,onRemove:()=>i(e),hideRemove:a},e.id),t[7]=a,t[8]=i,t[9]=r,t[10]=e):e=t[10],s=n.map(e),t[2]=a,t[3]=n,t[4]=i,t[5]=r,t[6]=s}else s=t[6];let c;return t[11]!==o||t[12]!==s?(c=(0,$.jsx)(Fl,{items:o,strategy:jl,children:s}),t[11]=o,t[12]=s,t[13]=c):c=t[13],c},Bx=()=>{let e=(0,pd.c)(13),{t}=Yt(),n;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(n={id:Px},e[0]=n):n=e[0];let{setNodeRef:r,isOver:i}=Tl(n),a;e[1]===t?a=e[2]:(a=t(`chat.draftStarters.remove`),e[1]=t,e[2]=a);let o;e[3]===t?o=e[4]:(o=t(`chat.draftStarters.remove`),e[3]=t,e[4]=o);let s=i&&`text-destructive hover:text-destructive`,c;e[5]===s?c=e[6]:(c=Y(Fx,s),e[5]=s,e[6]=c);let l;e[7]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,$.jsx)(Z,{name:`delete-bin`,className:`h-3.5 w-3.5`}),e[7]=l):l=e[7];let u;return e[8]!==r||e[9]!==a||e[10]!==o||e[11]!==c?(u=(0,$.jsx)(`button`,{type:`button`,ref:r,"aria-label":a,title:o,className:c,children:l}),e[8]=r,e[9]=a,e[10]=o,e[11]=c,e[12]=u):u=e[12],u},Vx=e=>{let t=(0,pd.c)(21),{pinnable:n,onPick:r,className:i}=e,{t:a}=Yt(),o;t[0]===i?o=t[1]:(o=Y(`min-h-0`,i),t[0]=i,t[1]=o);let s;t[2]===a?s=t[3]:(s=a(`chat.draftStarters.searchPlaceholder`),t[2]=a,t[3]=s);let c;t[4]===s?c=t[5]:(c=(0,$.jsx)(Tx,{placeholder:s}),t[4]=s,t[5]=c);let l;t[6]===a?l=t[7]:(l=a(`chat.draftStarters.empty`),t[6]=a,t[7]=l);let u;t[8]===l?u=t[9]:(u=(0,$.jsx)(Dx,{children:l}),t[8]=l,t[9]=u);let d;t[10]!==r||t[11]!==n||t[12]!==a?(d=Lx.map(e=>{let t=n.filter(t=>t.section===e.key);return t.length===0?null:(0,$.jsx)(Ox,{heading:a(e.headingKey),children:t.map(e=>(0,$.jsx)(Ax,{value:`${e.section} ${e.label} ${e.name}`,onSelect:()=>r(e),children:(0,$.jsx)(`span`,{className:`truncate`,children:e.label})},`${e.type}:${e.name}`))},e.key)}),t[10]=r,t[11]=n,t[12]=a,t[13]=d):d=t[13];let f;t[14]!==u||t[15]!==d?(f=(0,$.jsxs)(Ex,{children:[u,d]}),t[14]=u,t[15]=d,t[16]=f):f=t[16];let p;return t[17]!==o||t[18]!==c||t[19]!==f?(p=(0,$.jsxs)(wx,{className:o,children:[c,f]}),t[17]=o,t[18]=c,t[19]=f,t[20]=p):p=t[20],p},Hx=e=>{let t=(0,pd.c)(27),{pinnable:n,onOpen:r,onAdd:i}=e,{t:a}=Yt(),[o,s]=Q.useState(!1),c;t[0]===r?c=t[1]:(c=e=>{s(e),e&&r()},t[0]=r,t[1]=c);let l;t[2]===a?l=t[3]:(l=a(`chat.draftStarters.add`),t[2]=a,t[3]=l);let u;t[4]===a?u=t[5]:(u=a(`chat.draftStarters.add`),t[4]=a,t[5]=u);let d;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(d=(0,$.jsx)(Z,{name:`add`,className:`h-3.5 w-3.5`}),t[6]=d):d=t[6];let f;t[7]!==l||t[8]!==u?(f=(0,$.jsx)(go,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,"aria-label":l,title:u,className:Fx,children:d})}),t[7]=l,t[8]=u,t[9]=f):f=t[9];let p;t[10]===a?p=t[11]:(p=a(`chat.draftStarters.add`),t[10]=a,t[11]=p);let m;t[12]===p?m=t[13]:(m=(0,$.jsx)(lo,{className:`px-4 pb-2 pt-4 text-left`,children:(0,$.jsx)(mo,{children:p})}),t[12]=p,t[13]=m);let h;t[14]===i?h=t[15]:(h=e=>{i(e),s(!1)},t[14]=i,t[15]=h);let g;t[16]!==n||t[17]!==h?(g=(0,$.jsx)(Vx,{pinnable:n,onPick:h,className:`flex max-h-[60vh] flex-col`}),t[16]=n,t[17]=h,t[18]=g):g=t[18];let _;t[19]!==m||t[20]!==g?(_=(0,$.jsxs)(po,{className:`gap-0 overflow-hidden p-0 sm:max-w-sm`,children:[m,g]}),t[19]=m,t[20]=g,t[21]=_):_=t[21];let v;return t[22]!==o||t[23]!==c||t[24]!==_||t[25]!==f?(v=(0,$.jsxs)(_o,{open:o,onOpenChange:c,children:[f,_]}),t[22]=o,t[23]=c,t[24]=_,t[25]=f,t[26]=v):v=t[26],v},Ux=e=>{let t=(0,pd.c)(63),{onSubmit:n,className:r}=e,{t:i}=Yt(),{global:a,project:o,pinnable:s,ensureLoaded:c,addStarter:l,removeStarter:u,reorder:d}=Nx(Hl()),{isMobile:f}=qs(),[p,m]=Q.useState(!1),[h,g]=Q.useState(!1),[_,v]=Q.useState(!1),y=Q.useRef(null),b;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(b={activationConstraint:{distance:8}},t[0]=b):b=t[0];let x;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(x={activationConstraint:{delay:200,tolerance:6}},t[1]=x):x=t[1];let S=kl(Sl(Dl,b),Sl(wl,x)),C;t[2]!==a||t[3]!==o?(C=e=>a.find(t=>t.id===e)??o.find(t=>t.id===e),t[2]=a,t[3]=o,t[4]=C):C=t[4];let w=C,T=a.length+o.length,E;t[5]===T?E=t[6]:(E=()=>{let e=y.current;if(!e||T===0){v(!1);return}let t=()=>{let t=e.firstElementChild?.offsetHeight??28;v(e.scrollHeight>t+4)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},t[5]=T,t[6]=E);let D;t[7]!==h||t[8]!==a||t[9]!==o||t[10]!==T?(D=[T,h,a,o],t[7]=h,t[8]=a,t[9]=o,t[10]=T,t[11]=D):D=t[11],Q.useLayoutEffect(E,D);let O,k;t[12]!==_||t[13]!==h?(O=()=>{!_&&h&&g(!1)},k=[_,h],t[12]=_,t[13]=h,t[14]=O,t[15]=k):(O=t[14],k=t[15]),Q.useEffect(O,k);let A;t[16]===Symbol.for(`react.memo_cache_sentinel`)?(A=()=>m(!0),t[16]=A):A=t[16];let j=A,M;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(M=()=>m(!1),t[17]=M):M=t[17];let N=M,P;t[18]!==w||t[19]!==u||t[20]!==d?(P=e=>{m(!1);let{active:t,over:n}=e;if(!n)return;let r=String(t.id),i=w(r);if(!i)return;if(String(n.id)===Px){u(i.group,i.ref);return}let a=String(n.id);if(r===a)return;let o=w(a);o&&o.group===i.group&&d(i.group,r,a)},t[18]=w,t[19]=u,t[20]=d,t[21]=P):P=t[21];let F=P,I=_||h,L;t[22]===Symbol.for(`react.memo_cache_sentinel`)?(L={droppable:{strategy:Cl.Always}},t[22]=L):L=t[22];let R;t[23]===r?R=t[24]:(R=Y(`flex min-w-0 max-w-full items-start justify-center gap-0.5`,r),t[23]=r,t[24]=R);let z=!h&&Ix,B=!h&&`overflow-clip`,V;t[25]!==z||t[26]!==B?(V=Y(`flex min-w-0 flex-1 flex-wrap items-center justify-center gap-x-0.5 gap-y-0.5`,z,B),t[25]=z,t[26]=B,t[27]=V):V=t[27];let H;t[28]!==a||t[29]!==f||t[30]!==n||t[31]!==u?(H=a.length>0?(0,$.jsx)(zx,{items:a,onSubmit:n,onRemove:e=>u(`global`,e.ref),hideRemove:f}):null,t[28]=a,t[29]=f,t[30]=n,t[31]=u,t[32]=H):H=t[32];let ee;t[33]!==f||t[34]!==n||t[35]!==o||t[36]!==u?(ee=o.length>0?(0,$.jsx)(zx,{items:o,onSubmit:n,onRemove:e=>u(`project`,e.ref),hideRemove:f}):null,t[33]=f,t[34]=n,t[35]=o,t[36]=u,t[37]=ee):ee=t[37];let U;t[38]!==V||t[39]!==H||t[40]!==ee?(U=(0,$.jsxs)(`div`,{ref:y,className:V,children:[H,ee]}),t[38]=V,t[39]=H,t[40]=ee,t[41]=U):U=t[41];let te;t[42]!==h||t[43]!==I||t[44]!==i?(te=I?(0,$.jsx)(`button`,{type:`button`,onClick:()=>g(Gx),"aria-expanded":h,"aria-label":i(h?`chat.draftStarters.collapse`:`chat.draftStarters.expand`),title:i(h?`chat.draftStarters.collapse`:`chat.draftStarters.expand`),className:Fx,children:(0,$.jsx)(Z,{name:h?`arrow-up-s`:`arrow-down-s`,className:`h-3.5 w-3.5`})}):null,t[42]=h,t[43]=I,t[44]=i,t[45]=te):te=t[45];let W;t[46]!==l||t[47]!==c||t[48]!==p||t[49]!==f||t[50]!==s?(W=f&&p?(0,$.jsx)(Bx,{}):(0,$.jsx)(Hx,{pinnable:s,onOpen:c,onAdd:l}),t[46]=l,t[47]=c,t[48]=p,t[49]=f,t[50]=s,t[51]=W):W=t[51];let ne;t[52]!==te||t[53]!==W?(ne=(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-0.5 self-start`,children:[te,W]}),t[52]=te,t[53]=W,t[54]=ne):ne=t[54];let G;t[55]!==R||t[56]!==U||t[57]!==ne?(G=(0,$.jsxs)(`div`,{className:R,children:[U,ne]}),t[55]=R,t[56]=U,t[57]=ne,t[58]=G):G=t[58];let re;return t[59]!==F||t[60]!==S||t[61]!==G?(re=(0,$.jsx)(Ol,{sensors:S,collisionDetection:El,measuring:L,onDragStart:j,onDragCancel:N,onDragEnd:F,children:G}),t[59]=F,t[60]=S,t[61]=G,t[62]=re):re=t[62],re};function Wx(e){return e.id}function Gx(e){return!e}var Kx=e=>e.trim().replace(/\s+/g,`-`).replace(/[^A-Za-z0-9._/-]/g,`-`).replace(/-+/g,`-`).replace(/\/{2,}/g,`/`).replace(/\/-+/g,`/`).replace(/-+\//g,`/`).replace(/^[-/]+/,``).replace(/[-/]+$/,``),qx=({currentBranch:e,localBranches:t,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:o=[],disabled:s=!1,iconOnly:c=!1,trigger:l,triggerLabel:u,contentAlign:d,hideTooltip:f=!1,projectRootOption:p=null,worktreeOptions:m=[],selectedDirectory:h=null,onSelectDirectory:g,onCreateWorktree:_,worktreesLabel:v,worktreeNewLabel:y,projectRootLabel:b,onOpenChange:x,open:S,presentation:C=`dropdown`})=>{let{t:w}=Yt(),[T,E]=Q.useState(!1),[D,O]=Q.useState(``),[k,A]=Q.useState(!1),[j,M]=Q.useState(!1),[N,P]=Q.useState(``),[F,I]=Q.useState(!1),L=Q.useRef(null),R=Q.useId(),z=S??T,B=e=>{S===void 0&&E(e),x?.(e)},V=Q.useCallback(e=>{e.stopPropagation()},[]),H=o.length>1,ee=!!(g||_),U=Q.useMemo(()=>Kx(N),[N]),te=Q.useMemo(()=>{let e=D.trim();return e?ln(t,e,e=>e).map(e=>e.item):t},[D,t]),W=Q.useMemo(()=>{let e=D.trim();return e?ln(n,e,e=>e).map(e=>e.item):n},[D,n]),ne=Q.useMemo(()=>{let e=D.trim();return e?ln(m,e,e=>e.label).map(e=>e.item):m},[D,m]),G=Q.useMemo(()=>{if(!p)return!1;let e=D.trim();return!e||ln([p],e,e=>[e.label,b??``]).length>0},[b,p,D]),re=t=>{if(t===e){B(!1);return}i(t),B(!1),O(``)},ie=e=>{g?.(e),B(!1),O(``)},K=()=>{A(!0),setTimeout(()=>L.current?.focus(),50)},ae=async()=>{if(!(!U||F)){if(H){M(!0);return}I(!0);try{await a(U,o[0]),P(``),A(!1),B(!1)}finally{I(!1)}}},oe=async e=>{if(!(!U||F)){I(!0);try{await a(U,e),P(``),A(!1),M(!1),B(!1)}finally{I(!1)}}},se=()=>{M(!1)},ce=()=>{P(``),A(!1),M(!1)};Q.useEffect(()=>{z||(O(``),A(!1),M(!1),P(``))},[z]);let le=u||e||w(`gitView.branch.detachedHead`),ue=d??(c?`end`:`start`),de=v??w(`chat.chatInput.worktrees`),fe=y??w(`chat.chatInput.worktreeNew`),pe=b??w(`chat.chatInput.projectRoot`),me=c?(0,$.jsx)(`button`,{type:`button`,className:`flex size-6 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] disabled:cursor-not-allowed disabled:opacity-50`,disabled:s,"aria-label":le,children:(0,$.jsx)(Z,{name:`git-branch`,className:`size-3.5`})}):(0,$.jsxs)(Qt,{variant:`ghost`,size:`xs`,className:`h-6 min-w-0 max-w-full justify-start gap-1 px-0 hover:bg-transparent`,disabled:s,"aria-label":le,children:[(0,$.jsx)(Z,{name:`git-branch`,className:`size-3.5 text-primary`}),(0,$.jsx)(`span`,{className:`min-w-0 truncate typography-ui-label font-semibold text-left text-foreground`,children:le}),(0,$.jsx)(Z,{name:`arrow-down-s`,className:`size-3 shrink-0 text-muted-foreground`})]}),he=(0,$.jsx)(Is,{asChild:!0,disabled:s,children:l??me}),ge=(0,$.jsxs)(wx,{className:`h-full min-h-0`,children:[(0,$.jsx)(`div`,{"data-mobile-sheet-no-dismiss":C===`mobile-sheet`?``:void 0,children:(0,$.jsx)(Tx,{placeholder:w(`gitView.branch.searchPlaceholder`),value:D,onValueChange:O,onKeyDown:V})}),(0,$.jsxs)(Ex,{scrollbarClassName:`overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero`,disableHorizontal:!0,children:[(0,$.jsx)(Dx,{children:w(`gitView.branch.empty`)}),(0,$.jsx)(Ox,{children:j?(0,$.jsxs)(`div`,{className:`px-2 py-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mb-2`,children:[(0,$.jsx)(`button`,{type:`button`,onClick:se,disabled:F,className:`shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50`,children:(0,$.jsx)(Z,{name:`arrow-left`,className:`size-4`})}),(0,$.jsxs)(`span`,{className:`typography-meta text-muted-foreground`,children:[w(`gitView.branch.pushToPrefix`),` `,(0,$.jsx)(`span`,{className:`text-foreground font-medium`,children:U}),` `,w(`gitView.branch.pushToSuffix`)]})]}),(0,$.jsx)(`div`,{className:`flex flex-col gap-1`,children:o.map(e=>(0,$.jsxs)(`button`,{type:`button`,onClick:()=>oe(e),disabled:F,className:`flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50`,children:[(0,$.jsxs)(`span`,{className:`typography-ui-label text-foreground`,children:[F?(0,$.jsx)(Z,{name:`loader-4`,className:`inline size-3 mr-1.5 animate-spin`}):null,e.name]}),(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground truncate max-w-full`,children:e.pushUrl})]},e.name))})]}):k?(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1.5 rounded-lg`,children:[(0,$.jsx)(`input`,{ref:L,placeholder:w(`gitView.branch.newBranchPlaceholder`),value:N,onChange:e=>P(e.target.value),onClick:e=>e.stopPropagation(),onKeyDown:e=>{V(e),e.key===`Enter`?(e.preventDefault(),ae()):e.key===`Escape`&&(e.preventDefault(),ce())},className:`flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground`}),(0,$.jsx)(`button`,{type:`button`,onClick:ae,disabled:!U||F,className:`shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50`,children:F?(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}):(0,$.jsx)(Z,{name:`add`,className:`size-4`})}),(0,$.jsx)(`button`,{type:`button`,onClick:ce,disabled:F,className:`shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50`,children:(0,$.jsx)(Z,{name:`close`,className:`size-4`})})]}):(0,$.jsxs)(Ax,{onSelect:K,children:[(0,$.jsx)(Z,{name:`add`,className:`size-4`}),(0,$.jsx)(`span`,{children:w(`gitView.branch.create`)})]})}),(0,$.jsx)(kx,{}),(0,$.jsxs)(Ox,{heading:w(`gitView.branch.localBranches`),children:[te.map(t=>(0,$.jsxs)(Ax,{onSelect:()=>re(t),children:[(0,$.jsxs)(`span`,{className:`flex flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground`,children:t}),(r?.[t]?.ahead||r?.[t]?.behind)&&(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[r[t].ahead||0,` ahead ·`,` `,r[t].behind||0,` behind`]})]}),e===t&&(0,$.jsx)(`span`,{className:`typography-micro text-primary`,children:w(`gitView.branch.currentBadge`)})]},`local-${t}`)),te.length===0&&(0,$.jsx)(Ax,{disabled:!0,className:`justify-center`,children:(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:w(`gitView.branch.noLocalBranches`)})})]}),(0,$.jsx)(kx,{}),(0,$.jsxs)(Ox,{heading:w(`gitView.branch.remoteBranches`),children:[W.map(e=>(0,$.jsx)(Ax,{onSelect:()=>re(e),children:(0,$.jsx)(`span`,{className:`typography-ui-label text-foreground`,children:e})},`remote-${e}`)),W.length===0&&(0,$.jsx)(Ax,{disabled:!0,className:`justify-center`,children:(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:w(`gitView.branch.noRemoteBranches`)})})]}),ee?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(kx,{}),(0,$.jsxs)(Ox,{children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between px-2 py-1.5`,children:[(0,$.jsx)(`span`,{className:`text-muted-foreground typography-meta`,children:de}),_?(0,$.jsx)(`button`,{type:`button`,className:`cursor-pointer text-muted-foreground typography-meta hover:text-foreground`,onPointerDown:e=>{e.stopPropagation()},onClick:e=>{e.preventDefault(),e.stopPropagation(),B(!1),_()},children:fe}):null]}),p&&G?(0,$.jsxs)(Ax,{onSelect:()=>ie(p.value),children:[(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground`,children:pe}),(0,$.jsx)(`span`,{className:`truncate typography-ui-label text-foreground`,children:p.label})]}),h===p.value?(0,$.jsx)(`span`,{className:`typography-micro text-primary`,children:w(`gitView.branch.currentBadge`)}):null]}):null,ne.map(e=>(0,$.jsxs)(Ax,{onSelect:()=>ie(e.value),children:[(0,$.jsxs)(`span`,{className:`truncate typography-ui-label text-foreground`,children:[e.pending?`⏳ `:``,e.label]}),h===e.value?(0,$.jsx)(`span`,{className:`typography-micro text-primary`,children:w(`gitView.branch.currentBadge`)}):null]},`worktree-${e.value}`))]})]}):null]})]});if(C===`mobile-sheet`){let e=Q.cloneElement(l??me,{onClick:()=>B(!0),"data-popup-open":z?``:void 0});return(0,$.jsxs)($.Fragment,{children:[e,(0,$.jsx)(Fo,{id:`mobile-draft-branch-picker-sheet-${R}`,open:z,onOpenChange:B,ariaLabel:w(`gitView.branch.selectBranch`),closeAriaLabel:w(`mobile.surface.closeAria`),resizeAriaLabel:w(`mobile.sessions.sheet.resizeAria`),children:ge})]})}return(0,$.jsxs)(Cs,{open:z,onOpenChange:B,children:[f||l?he:(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:he}),(0,$.jsx)(Jo,{sideOffset:8,children:c?le:w(`gitView.branch.currentBranchTooltip`)})]}),(0,$.jsx)(Ss,{align:ue,className:`w-72 p-0 max-h-[60vh] flex flex-col`,children:ge})]})};function Jx(e){let{localBranches:t,remoteBranches:n,query:r}=e,i=r.trim();if(!i)return{matching:[],otherLocal:t,otherRemote:n};let a=ln(t,i,e=>e),o=ln(n,i,e=>e),s=new Set(a.map(e=>e.item)),c=new Set(o.map(e=>e.item));return{matching:[...a.map(e=>({label:e.item,value:e.item,source:`local`,score:e.score})),...o.map(e=>({label:e.item,value:`remotes/${e.item}`,source:`remote`,score:e.score}))].sort((e,t)=>e.score===t.score?e.source===t.source?e.label.length===t.label.length?e.label.localeCompare(t.label,void 0,{sensitivity:`accent`}):e.label.length-t.label.length:e.source===`local`?-1:1:e.score-t.score).map(({label:e,value:t,source:n})=>({label:e,value:t,source:n})),otherLocal:t.filter(e=>!s.has(e)),otherRemote:n.filter(e=>!c.has(e))}}function Yx(e,t){return`${e}\0${t}`}function Xx({open:e,onOpenChange:t,onSelect:n}){let{t:r}=Yt(),i=q(e=>e.isMobile),{github:a}=rc(),o=hs(),s=o.data??null,c=o.isFetched,l=q(e=>e.setSettingsDialogOpen),u=q(e=>e.setSettingsPage),d=eo(e=>e.getActiveProject()),f=d?.id??null,p=d?.path??null,m=Q.useMemo(()=>p&&f?{id:f,path:p}:null,[f,p]),[h,g]=Q.useState(`issues`),[_,v]=Q.useState(``),[y,b]=Q.useState([]),[x,S]=Q.useState([]),[C,w]=Q.useState(!1),[T,E]=Q.useState(!1),[D,O]=Q.useState(null),[k,A]=Q.useState(null),[j,M]=Q.useState(null),[N,P]=Q.useState(!1),[F,I]=Q.useState(new Map),[L,R]=Q.useState(1),[z,B]=Q.useState(!1),V=Q.useRef(0),H=Sc(_,350),ee=J(async e=>{if(!(!p||!a)&&!(c&&s?.connected===!1)){w(!0),O(null),R(1),B(!1);try{if(h===`issues`&&a.issuesList){let t=await a.issuesList(p,{page:1,query:e});t.connected===!1?(O(r(`session.githubIntegration.error.notConnected`)),b([])):(b(t.issues??[]),R(t.page??1),B(!!t.hasMore))}else if(h===`prs`&&a.prsList){let t=await a.prsList(p,{page:1,query:e});t.connected===!1?(O(r(`session.githubIntegration.error.notConnected`)),S([])):(S(t.prs??[]),R(t.page??1),B(!!t.hasMore))}}catch(e){O(e instanceof Error?e.message:r(`session.githubIntegration.error.loadDataFailed`))}finally{w(!1)}}});Q.useEffect(()=>{if(!e||!p||c&&s?.connected===!1||!a)return;if(!H.trim()){ee();return}let t=new AbortController;w(!0),O(null),R(1),B(!1);let n=h===`issues`&&a.issuesList?a.issuesList(p,{page:1,query:H.trim()}):h===`prs`&&a.prsList?a.prsList(p,{page:1,query:H.trim()}):null;if(!n){w(!1);return}return n.then(e=>{t.signal.aborted||(`issues`in e?e.connected===!1?(O(r(`session.githubIntegration.error.notConnected`)),b([])):(b(e.issues??[]),R(e.page??1),B(!!e.hasMore)):`prs`in e&&(e.connected===!1?(O(r(`session.githubIntegration.error.notConnected`)),S([])):(S(e.prs??[]),R(e.page??1),B(!!e.hasMore))))}).catch(e=>{t.signal.aborted||O(e instanceof Error?e.message:r(`session.githubIntegration.error.loadDataFailed`))}).finally(()=>{t.signal.aborted||w(!1)}),()=>t.abort()},[e,p,a,c,s,h,H,ee,r]);let U=J(async()=>{if(!(!p||!a)&&!(C||T)&&z){E(!0);try{let e=L+1;if(h===`issues`&&a.issuesList){let t=H.trim()?await a.issuesList(p,{page:e,query:H.trim()}):await a.issuesList(p,{page:e});t.connected!==!1&&(b(e=>[...e,...t.issues??[]]),R(t.page??e),B(!!t.hasMore))}else if(h===`prs`&&a.prsList){let t=H.trim()?await a.prsList(p,{page:e,query:H.trim()}):await a.prsList(p,{page:e});t.connected!==!1&&(S(e=>[...e,...t.prs??[]]),R(t.page??e),B(!!t.hasMore))}}catch{}finally{E(!1)}}});Q.useEffect(()=>{if(!e){g(`issues`),v(``),b([]),S([]),A(null),M(null),P(!1),O(null),I(new Map),R(1),B(!1);return}ee()},[e,ee]),Q.useEffect(()=>{V.current+=1,I(new Map)},[p,m]);let te=J(async e=>{if(!m||!e)return;let t=Yx(m.path,e);if(F.has(t))return;let n=V.current;try{let i=await Ho(m,{mode:`new`,branchName:e,worktreeName:e});if(n!==V.current)return;let a=i.errors.find(e=>e.code===`branch_in_use`);I(e=>new Map(e).set(t,{isValid:!a,error:a?r(a.code===`branch_exists`?`session.githubIntegration.validation.branchAlreadyExists`:`session.githubIntegration.validation.branchAlreadyCheckedOut`):null}))}catch{if(n!==V.current)return;I(e=>new Map(e).set(t,{isValid:!1,error:r(`session.githubIntegration.validation.failed`)}))}});Q.useEffect(()=>{!e||h!==`prs`||x.forEach(e=>{e.head&&te(e.head)})},[e,h,x,p,m,te]);let W=c&&s?.connected===!0,ne=()=>{u(`github`),l(!0)},G=e=>{A(e),M(null)},re=e=>{M(e),A(null)},ie=()=>{k?n({type:`issue`,item:k}):j&&n({type:`pr`,item:j,includeDiff:N}),t(!1)},K=()=>{A(null),M(null),P(!1)},ae=k||(j?.head&&p?F.get(Yx(p,j.head))?.isValid!==!1:!1),oe=e=>!e.head||(p?F.get(Yx(p,e.head)):void 0)?.isValid===!1,se=(0,$.jsx)($.Fragment,{children:W?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[(0,$.jsx)(Z,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),(0,$.jsx)(Ko,{value:_,onChange:e=>v(e.target.value),placeholder:r(h===`issues`?`session.githubIntegration.search.issuesPlaceholder`:`session.githubIntegration.search.prsPlaceholder`),className:`h-8 pl-9`})]}),(0,$.jsx)(`div`,{className:`mt-2 h-[300px] overflow-hidden`,children:(0,$.jsxs)(`div`,{className:`h-full overflow-y-auto`,children:[C&&(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsx)(Z,{name:`loader-4`,className:`h-5 w-5 animate-spin text-muted-foreground`})}),D&&(0,$.jsx)(`div`,{className:`flex items-center justify-center h-full`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2 p-2 rounded-md bg-destructive/10 text-destructive`,children:[(0,$.jsx)(Z,{name:`error-warning`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`typography-small`,children:D})]})}),!C&&!D&&h===`issues`&&(0,$.jsxs)(`div`,{className:`space-y-0.5 min-h-full`,children:[y.length>0?y.map(e=>(0,$.jsx)(`button`,{onClick:()=>G(e),className:Y(`w-full text-left px-2 py-1.5 rounded transition-colors`,k?.number===e.number?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground shrink-0 typography-micro`,children:[`#`,e.number]}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`typography-small line-clamp-2`,children:e.title}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info mt-0.5 inline-block`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null]})]})},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)):(0,$.jsx)(`div`,{className:`flex items-center justify-center h-[300px] text-center typography-small text-muted-foreground`,children:r(`session.githubIntegration.empty.noIssuesFound`)}),z&&!T&&(0,$.jsx)(`div`,{className:`flex justify-center pt-2`,children:(0,$.jsx)(Qt,{variant:`ghost`,size:`sm`,onClick:()=>void U(),className:`h-7 text-xs`,children:r(`session.githubIntegration.actions.loadMore`)})}),T&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-2`,children:(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`})})]}),!C&&!D&&h===`prs`&&(0,$.jsxs)(`div`,{className:`space-y-0.5 min-h-full`,children:[x.length>0?x.map(e=>{let t=oe(e),n=e.head&&p?F.get(Yx(p,e.head)):void 0;return(0,$.jsx)(`button`,{onClick:()=>!t&&re(e),disabled:t,className:Y(`w-full text-left px-2 py-1.5 rounded transition-colors`,j?.number===e.number?`bg-interactive-selection text-interactive-selection-foreground`:t?`opacity-50 cursor-not-allowed`:`hover:bg-interactive-hover`),children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsxs)(`span`,{className:`text-muted-foreground shrink-0 typography-micro`,children:[`#`,e.number]}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`span`,{className:`typography-small line-clamp-1`,children:e.title}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-0.5`,children:[(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[e.head,` → `,e.base]}),e.sourceRepo?.source===`upstream`?(0,$.jsxs)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-info/10 text-status-info`,children:[e.sourceRepo.owner,`/`,e.sourceRepo.repo]}):null,t&&n?.error&&(0,$.jsx)(`span`,{className:`typography-micro text-destructive`,children:n.error})]})]})]})},`${e.sourceRepo?.owner??``}-${e.sourceRepo?.repo??``}-${e.number}`)}):(0,$.jsx)(`div`,{className:`flex items-center justify-center h-[300px] text-center typography-small text-muted-foreground`,children:r(`session.githubIntegration.empty.noPullRequestsFound`)}),z&&!T&&(0,$.jsx)(`div`,{className:`flex justify-center pt-2`,children:(0,$.jsx)(Qt,{variant:`ghost`,size:`sm`,onClick:()=>void U(),className:`h-7 text-xs`,children:r(`session.githubIntegration.actions.loadMore`)})}),T&&(0,$.jsx)(`div`,{className:`flex items-center justify-center py-2`,children:(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin text-muted-foreground`})})]})]})})]}):(0,$.jsxs)(`div`,{className:`flex-1 flex flex-col items-center justify-center p-8 gap-4`,children:[(0,$.jsx)(Z,{name:`github`,className:`h-12 w-12 text-muted-foreground`}),(0,$.jsxs)(`div`,{className:`text-center`,children:[(0,$.jsx)(`p`,{className:`typography-ui-label text-foreground`,children:r(`session.githubIntegration.connect.title`)}),(0,$.jsx)(`p`,{className:`typography-small text-muted-foreground mt-1`,children:r(`session.githubIntegration.connect.description`)})]}),(0,$.jsx)(Qt,{onClick:ne,size:`sm`,children:r(`session.githubIntegration.connect.action`)})]})}),ce=(0,$.jsxs)(`div`,{className:Y(`w-full`,i?`flex flex-col gap-2`:`flex flex-row items-center`),children:[(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-4`,i?`w-full justify-center order-1`:`flex-1`),children:[!i&&(k||j)&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 h-8 rounded-md bg-muted/50 border border-border/50`,children:[(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),(0,$.jsx)(`span`,{className:`typography-small truncate max-w-[150px]`,children:k?r(`session.githubIntegration.selected.issueNumber`,{number:k.number}):r(`session.githubIntegration.selected.prNumber`,{number:j?.number??``})}),(0,$.jsx)(`button`,{onClick:K,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(Z,{name:`close`,className:`h-3.5 w-3.5`})})]}),h===`prs`&&j&&(0,$.jsxs)(`label`,{className:`flex items-center gap-2 cursor-pointer h-8`,children:[(0,$.jsx)(Oo,{checked:N,onChange:e=>P(e),ariaLabel:r(`session.githubIntegration.includeDiffAria`)}),(0,$.jsx)(`span`,{className:`typography-small text-foreground`,children:r(`session.githubIntegration.includeDiff`)})]})]}),(0,$.jsxs)(`div`,{className:Y(`flex gap-2`,i?`w-full order-2`:`justify-end`),children:[(0,$.jsx)(Qt,{variant:`outline`,size:`sm`,onClick:()=>t(!1),className:Y(i&&`flex-1`),children:r(`session.githubIntegration.actions.cancel`)}),(0,$.jsx)(Qt,{size:`sm`,onClick:ie,disabled:!ae,className:Y(i&&`flex-1`),children:r(`session.githubIntegration.actions.select`)})]})]});return(0,$.jsx)($.Fragment,{children:i?(0,$.jsx)(Hs,{open:e,title:r(`session.githubIntegration.title`),onClose:()=>t(!1),footer:W?ce:void 0,renderHeader:e=>(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 px-3 py-2 border-b border-border/40`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`h2`,{className:`typography-ui-label font-semibold text-foreground`,children:r(`session.githubIntegration.title`)}),e]}),(0,$.jsx)(`div`,{className:`w-full`,children:(0,$.jsx)(rd,{items:[{id:`issues`,label:r(`session.githubIntegration.tabs.issues`),icon:(0,$.jsx)(Z,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`prs`,label:r(`session.githubIntegration.tabs.pullRequests`),icon:(0,$.jsx)(Z,{name:`git-pull-request`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>{g(e),v(``)},variant:`active-pill`,layoutMode:`fit`})}),(k||j)&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 px-2 py-1 rounded-md bg-muted/50 border border-border/50`,children:[(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),(0,$.jsx)(`span`,{className:`typography-small truncate flex-1`,children:k?r(`session.githubIntegration.selected.issueNumber`,{number:k.number}):r(`session.githubIntegration.selected.prNumber`,{number:j?.number??``})}),(0,$.jsx)(`button`,{onClick:K,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(Z,{name:`close`,className:`h-3.5 w-3.5`})})]})]}),children:se}):(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsxs)(po,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:[(0,$.jsx)(lo,{className:`flex flex-row items-center justify-between`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2 shrink-0`,children:[(0,$.jsx)(Z,{name:`github`,className:`h-5 w-5`}),r(`session.githubIntegration.title`)]}),(0,$.jsx)(`div`,{className:`w-[220px]`,children:(0,$.jsx)(rd,{items:[{id:`issues`,label:r(`session.githubIntegration.tabs.issues`),icon:(0,$.jsx)(Z,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`prs`,label:r(`session.githubIntegration.tabs.pullRequests`),icon:(0,$.jsx)(Z,{name:`git-pull-request`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>{g(e),v(``)},variant:`active-pill`,layoutMode:`fit`})})]})}),se,(0,$.jsx)(uo,{className:`mt-1`,children:ce})]})})})}var Zx=(e,t,n)=>{let r=n??t;return r?e.find(e=>e.id===r)??null:null},Qx=e=>e.trim().replace(/^refs\/heads\//,``).replace(/^heads\//,``).replace(/\s+/g,`-`).replace(/^\/+|\/+$/g,``),$x=e=>e.trim().replace(/^refs\/heads\//,``).replace(/^heads\//,``).replace(/\s+/g,`-`).replace(/^\/+|\/+$/g,``).split(`/`).join(`-`).replace(/[^A-Za-z0-9._-]+/g,`-`).replace(/-+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80),eS=e=>String(e||``).trim().toLowerCase().replace(/[^a-z0-9._-]+/g,`-`).replace(/-+/g,`-`).replace(/^-+|-+$/g,``)||`pr-head`,tS=(e,t,n)=>{let r=Qx(e.head||``);if(!r)throw Error(`PR head branch is missing`);if(t.includes(r))return{existingBranch:r,setUpstream:void 0,upstreamRemote:void 0,upstreamBranch:void 0,ensureRemoteName:void 0,ensureRemoteUrl:void 0,sourceLabel:r};let i=n.find(e=>{let t=e.indexOf(`/`);return t<=0||t>=e.length-1?!1:e.slice(t+1)===r});if(i){let e=i.indexOf(`/`),t=i.slice(0,e);return{existingBranch:`remotes/${i}`,setUpstream:!0,upstreamRemote:t,upstreamBranch:r,ensureRemoteName:void 0,ensureRemoteUrl:void 0,sourceLabel:`${t}/${r}`}}let a=String(e.headLabel||``).split(`:`)[0]?.trim(),o=`pr-${eS(e.headRepo?.owner||a||`pr-head`)}`,s=e.headRepo?.sshUrl||e.headRepo?.cloneUrl||``;if(!s)throw Error(`PR head repository URL is unavailable`);return{existingBranch:`remotes/${o}/${r}`,setUpstream:!0,upstreamRemote:o,upstreamBranch:r,ensureRemoteName:o,ensureRemoteUrl:s,sourceLabel:`${o}/${r}`}},nS=e=>{let t={repo:e.repo??null,issue:e.issue,comments:e.comments};return`GitHub issue context (JSON)\n${JSON.stringify(t,null,2)}`},rS=e=>`GitHub pull request context (JSON)\n${JSON.stringify(e,null,2)}`;function iS({open:e,onOpenChange:t,onWorktreeCreated:n,projectId:r}){let{t:i}=Yt(),{github:a,git:o}=rc(),s=q(e=>e.isMobile),c=Q.useId(),l=hs(),u=l.data??null,d=l.isFetched,f=eo(e=>Zx(e.projects,e.activeProjectId,r)),p=f?.path??null,m=Q.useMemo(()=>p&&f?{id:f.id,path:p}:null,[f,p]),[h,g]=Q.useState(`new-branch`),[_,v]=Q.useState({branchName:``,worktreeName:``,isSyncingWorktreeName:!0,sourceBranch:``,linkedIssue:null,linkedPr:null,includePrDiff:!1}),[y,b]=Q.useState({selectedBranch:``,worktreeName:``}),x=Oc(p),S=Tc(p),C=vc(e=>e.fetchBranches),w=Q.useMemo(()=>x?.all?x.all.filter(e=>!e.startsWith(`remotes/`)).sort():[],[x]),T=Q.useMemo(()=>x?.all?x.all.filter(e=>e.startsWith(`remotes/`)).map(e=>e.replace(/^remotes\//,``)).sort():[],[x]),E=X(e=>e.availableWorktreesByProject),D=Q.useMemo(()=>{if(!p)return new Set;let e=E.get(p)??[];return new Set(e.map(e=>e.name))},[E,p]),O=Q.useCallback((e=10)=>{for(let t=0;t<e;t++){let e=rx();if(!D.has(e))return e}return`${rx()}-${Date.now().toString(36).slice(-4)}`},[D]),[k,A]=Q.useState(!1),[j,M]=Q.useState(!1),[N,P]=Q.useState(!1),[F,I]=Q.useState(!1),[L,R]=Q.useState(!1),[z,B]=Q.useState(``),[V,H]=Q.useState(``),ee=Q.useRef(null),U=Q.useRef(null),te=Q.useRef(null),W=Q.useRef(null),ne=Q.useCallback(e=>{e.stopPropagation()},[]),G=Q.useCallback(e=>{let t=e;for(;t&&t!==document.body;){let{overflowY:e}=window.getComputedStyle(t);if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null},[]),re=Q.useCallback(e=>{e&&(e.scrollTop=0)},[]),ie=Q.useCallback(e=>{let t=e.current?.querySelector(`[data-slot="command-list"]`)??null;re(t)},[re]),K=Q.useCallback(e=>{let t=G(e.current);re(t)},[G,re]),ae=Q.useMemo(()=>Jx({localBranches:w,remoteBranches:T,query:z}),[w,T,z]),oe=Q.useMemo(()=>Jx({localBranches:w,remoteBranches:T,query:V}),[w,T,V]),se=z.trim().length>0,ce=V.trim().length>0,le=ae.matching.length>0,ue=oe.matching.length>0,de=!!(p&&o),fe=Q.useCallback(()=>{!p||!o||C(p,o)},[p,o,C]);Q.useEffect(()=>{!e||!p||!o||x?.all||C(p,o)},[e,p,o,x?.all,C]),Q.useEffect(()=>{!j&&!F&&B(``)},[j,F]),Q.useEffect(()=>{!N&&!L&&H(``)},[N,L]),Q.useEffect(()=>{j&&ie(ee),F&&K(te)},[j,F,z,ie,K]),Q.useEffect(()=>{N&&ie(U),L&&K(W)},[N,L,V,ie,K]);let[pe,me]=Q.useState({isValidating:!1,branchError:null,worktreeError:null,touched:!1}),[he,ge]=Q.useState(!1),[_e,ve]=Q.useState(null),ye=Q.useCallback(()=>{let e=Oa.getState(),t=e.getVisibleAgents();if(e.settingsDefaultAgent){let n=t.find(t=>t.name===e.settingsDefaultAgent);if(n)return n.name}return t.find(e=>e.name===`build`)?.name||t[0]?.name},[]),be=Q.useCallback(()=>{let e=Oa.getState(),t=e.settingsDefaultModel;if(!t)return null;let n=tr(t);if(!n)return null;let{providerId:r,modelId:i}=n;return e.getModelMetadata(r,i)?{providerID:r,modelID:i}:null},[]),xe=Q.useCallback((e,t)=>{let n=Oa.getState(),r=n.settingsDefaultVariant,i=n.currentProviderId===e&&n.currentModelId===t?n.currentVariant:void 0,a=n.providers.find(t=>t.id===e)?.models.find(e=>e.id===t)?.variants;if(!a)return r||i||void 0;if(r&&Object.prototype.hasOwnProperty.call(a,r))return r;if(i&&Object.prototype.hasOwnProperty.call(a,i))return i},[]),Se=Q.useCallback(async e=>{if(!p||!a)return;let t=Oa.getState(),n=Hr.getState().lastUsedProvider,r=be(),o=r?.providerID||t.currentProviderId||n?.providerID,s=r?.modelID||t.currentModelId||n?.modelID,c=ye()||t.currentAgentName||void 0;if(!o||!s){ro.error(i(`session.newWorktree.error.noModelSelected`));return}let l=xe(o,s);if(e.issue){if(!a.issueGet||!a.issueComments)return;let t=await a.issueGet(p,e.issue.number,{sourceRepo:e.issue.sourceRepo??null});if(t.connected===!1||!t.repo||!t.issue)throw Error(`Failed to load issue context`);let n=await a.issueComments(p,e.issue.number,{sourceRepo:e.issue.sourceRepo??null});if(n.connected===!1)throw Error(`Failed to load issue comments`);let r=await ii(`github.issue.review.visible`,{issue_number:String(e.issue.number)}),u=await ii(`github.issue.review.instructions`),d=nS({repo:t.repo,issue:t.issue,comments:n.comments??[]});await X.getState().sendMessage(r,o,s,c,void 0,void 0,[{text:u,synthetic:!0},{text:d,synthetic:!0}],l,void 0,{sessionId:e.sessionId}),ro.success(i(`session.newWorktree.toast.sessionFromIssue`));return}if(e.pr){if(!a.prContext)return;let t=await a.prContext(p,e.pr.number,{sourceRepo:e.pr.sourceRepo??null,includeDiff:e.includeDiff,includeCheckDetails:!1});if(t.connected===!1||!t.repo||!t.pr)throw Error(`Failed to load PR context`);let n=await ii(`github.pr.review.visible`,{pr_number:String(e.pr.number)}),r=await ii(`github.pr.review.instructions`),u=rS(t);await X.getState().sendMessage(n,o,s,c,void 0,void 0,[{text:r,synthetic:!0},{text:u,synthetic:!0}],l,void 0,{sessionId:e.sessionId}),ro.success(i(`session.newWorktree.toast.sessionFromPr`))}},[a,p,ye,be,xe,i]),Ce=h===`new-branch`?_:y;Q.useEffect(()=>{if(!e||!x?.all||!p||_.sourceBranch)return;let t=_.sourceBranch,n=!1;return(async()=>{try{let e=await Mo(p).catch(()=>null);if(n)return;let r=localStorage.getItem(_c),{sourceBranch:i,shouldClearSavedSourceBranch:a}=Dc({branches:x.all,savedSourceBranch:r,rootBranch:e});if(a&&localStorage.removeItem(_c),n||t)return;i&&v(e=>({...e,sourceBranch:i}))}catch{}})(),()=>{n=!0}},[e,x?.all,p,_.sourceBranch]),Q.useLayoutEffect(()=>{if(!e)return;g(`new-branch`),b({selectedBranch:``,worktreeName:``}),M(!1),P(!1),I(!1),R(!1),B(``),H(``),me({isValidating:!1,branchError:null,worktreeError:null,touched:!1});let t=O();v({branchName:t,worktreeName:t,isSyncingWorktreeName:!0,sourceBranch:``,linkedIssue:null,linkedPr:null,includePrDiff:!1})},[e,O]),Q.useEffect(()=>{if(h!==`new-branch`||!_.isSyncingWorktreeName)return;let e=$x(Qx(_.branchName));v(t=>({...t,worktreeName:e}))},[h,_.branchName,_.isSyncingWorktreeName]);let we=Q.useCallback(async()=>{if(!m||!pe.touched||he)return;_e&&_e.abort();let e=new AbortController;ve(e),me(e=>({...e,isValidating:!0}));try{let t=h===`new-branch`?_.branchName:y.selectedBranch,n=Ce.worktreeName,r=Qx(t),a=$x(n),o=null,s=null;if(r||(o=i(`session.newWorktree.error.branchNameRequired`)),a||(s=i(`session.newWorktree.error.worktreeDirectoryRequired`)),r&&a){let t=h===`new-branch`?_.linkedPr:null,n=t?tS(t,w,T):null,i=await Ho(m,{mode:h===`existing-branch`||n?`existing`:`new`,branchName:r,worktreeName:a,existingBranch:n?.existingBranch??(h===`existing-branch`?r:void 0),...n?.ensureRemoteName?{ensureRemoteName:n.ensureRemoteName}:{},...n?.ensureRemoteUrl?{ensureRemoteUrl:n.ensureRemoteUrl}:{}});if(e.signal.aborted)return;i.ok||i.errors.forEach(e=>{if(e.code===`worktree_exists`){s??=e.message;return}e.code.startsWith(`branch_`)&&(o??=e.message)})}e.signal.aborted||me(e=>({...e,isValidating:!1,branchError:o,worktreeError:s}))}catch{e.signal.aborted||me(e=>({...e,isValidating:!1}))}},[m,h,_.branchName,_.linkedPr,y.selectedBranch,Ce.worktreeName,w,T,pe.touched,_e,he,i]),Te=h===`new-branch`?_.branchName:y.selectedBranch;Q.useEffect(()=>{if(!e||!m||!pe.touched||he)return;let t=setTimeout(()=>{we()},300);return()=>clearTimeout(t)},[Ce.worktreeName,Te,e,m,we,pe.touched,he]);let Ee=async()=>{if(!m||!p){ro.error(i(`session.newWorktree.error.noActiveProject`));return}me(e=>({...e,touched:!0}));let e=h===`new-branch`?_.branchName:y.selectedBranch,r=Ce.worktreeName,a=Qx(e),o=$x(r);if(!a){ro.error(i(`session.newWorktree.error.branchNameRequired`));return}if(!o){ro.error(i(`session.newWorktree.error.worktreeDirectoryRequired`));return}_e&&(_e.abort(),ve(null)),me(e=>({...e,isValidating:!1,branchError:null,worktreeError:null})),ge(!0);try{let e=h===`new-branch`?_.linkedPr:null,r=h===`new-branch`?_.linkedIssue:null,s=h===`new-branch`?_.linkedPr:null,c=h===`new-branch`&&_.includePrDiff,l=!!(r||s),[u,d]=await Promise.all([mn(m),wc(p)]),f=_.sourceBranch,g=``,v=(()=>{if(e){let t=tS(e,w,T);return g=t.sourceLabel,{preferredName:a||o,mode:`existing`,branchName:a,worktreeName:o,existingBranch:t.existingBranch,setupCommands:u,setUpstream:t.setUpstream,upstreamRemote:t.upstreamRemote,upstreamBranch:t.upstreamBranch,returnAfterDirectoryCreated:!0,...t.ensureRemoteName?{ensureRemoteName:t.ensureRemoteName}:{},...t.ensureRemoteUrl?{ensureRemoteUrl:t.ensureRemoteUrl}:{}}}return g=h===`new-branch`?f:``,{preferredName:a||o,mode:h===`existing-branch`?`existing`:`new`,branchName:h===`existing-branch`?void 0:a,worktreeName:o,existingBranch:h===`existing-branch`?a:void 0,setupCommands:u,returnAfterDirectoryCreated:!0,...f&&h===`new-branch`?{startRef:f}:{}}})(),b=await Mc(p,v,{resolvedRootTrackingRemote:d}),x=await zo(m,b),S=null;if(l){await Wr(m)&&await Mi(x.path);let e=r?`#${r.number} ${r.title}`.trim():s?`#${s.number} ${s.title}`.trim():i(`session.newWorktree.newSessionTitle`),a=await hn(e,x.path,null);if(!a?.id)throw Error(`Failed to create session`);S=a.id,n?.(x.path,{sessionId:S}),t(!1),ge(!1),Cr(a.id,e).catch(()=>void 0);try{X.getState().initializeNewOpenChamberSession(a.id,Oa.getState().agents)}catch{}}else t(!1),ge(!1);let C=Ac({mode:h,sourceBranch:_.sourceBranch,linkedPr:!!_.linkedPr,selectedBranch:y.selectedBranch});C&&localStorage.setItem(_c,C),ro.success(i(`session.newWorktree.toast.worktreeCreated`),{description:i(`session.newWorktree.toast.worktreeCreatedDescription`,{target:`${x.branch||x.name}${g?` ${i(`session.newWorktree.fromSource`,{source:g})}`:``}`})}),S?Se({sessionId:S,directory:x.path,issue:r,pr:s,includeDiff:c}).catch(e=>{let t=e instanceof Error?e.message:i(`session.newWorktree.error.sendGitHubContextFailed`);ro.error(i(`session.newWorktree.error.sendGitHubContextFailed`),{description:t})}):n?.(x.path)}catch(e){let t=e instanceof Error?e.message:i(`session.newWorktree.error.createWorktreeFailed`);ro.error(i(`session.newWorktree.error.createWorktreeFailed`),{description:t})}finally{ge(!1)}},De=e=>{g(e),me(e=>({...e,touched:!1,branchError:null,worktreeError:null}))},Oe=e=>{if(!e){v(e=>({...e,linkedIssue:null,linkedPr:null,includePrDiff:!1,branchName:``}));return}if(e.type===`issue`){let t=e.item,n=`issue-${t.number}-${rx()}`;v(e=>({...e,linkedIssue:t,linkedPr:null,includePrDiff:!1,branchName:n,worktreeName:$x(n),isSyncingWorktreeName:!0}))}else if(e.type===`pr`){let t=e.item;v(n=>({...n,linkedPr:t,linkedIssue:null,includePrDiff:e.includeDiff??!1,branchName:t.head,worktreeName:$x(t.head),isSyncingWorktreeName:!0}))}},ke=d&&u?.connected===!0,Ae=(h===`existing-branch`?!!y.selectedBranch&&!!y.worktreeName&&!pe.branchError&&!pe.worktreeError:!!Qx(_.branchName)&&!!_.worktreeName&&!pe.branchError&&!pe.worktreeError)&&!he,je=()=>{v(e=>({...e,linkedIssue:null,linkedPr:null,branchName:``,includePrDiff:!1,isSyncingWorktreeName:!0}))},Me=(0,$.jsxs)(`div`,{className:Y(`flex gap-2`,s?`flex-col w-full`:`flex-row items-center`),children:[(0,$.jsx)(`div`,{className:Y(`flex items-center gap-1.5 text-destructive`,s?`w-full justify-center order-first`:`mr-auto`),children:pe.touched&&(pe.branchError||pe.worktreeError)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`error-warning`,className:`h-3.5 w-3.5`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:pe.branchError||pe.worktreeError})]})}),(0,$.jsxs)(`div`,{className:Y(`flex gap-2`,s&&`w-full`),children:[(0,$.jsx)(Qt,{variant:`outline`,size:`sm`,onClick:()=>t(!1),disabled:he,className:Y(s&&`flex-1`),children:i(`session.newWorktree.actions.cancel`)}),(0,$.jsxs)(Qt,{size:`sm`,onClick:Ee,disabled:!Ae||he,className:Y(`gap-1.5`,s&&`flex-1`),children:[he&&(0,$.jsx)(Z,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}),i(he?`session.newWorktree.actions.creating`:`session.newWorktree.actions.createWorktree`)]})]})]});return(0,$.jsxs)($.Fragment,{children:[s?(0,$.jsx)(Fo,{id:`new-worktree-sheet-${c}`,open:e,onOpenChange:t,title:(0,$.jsx)(`h2`,{className:`truncate typography-ui-label font-semibold text-foreground`,children:i(`session.newWorktree.title`)}),ariaLabel:i(`session.newWorktree.title`),closeAriaLabel:i(`mobile.surface.closeAria`),resizeAriaLabel:i(`mobile.sessions.sheet.resizeAria`),children:(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col`,children:[(0,$.jsxs)(bl,{useScrollShadow:!0,disableHorizontal:!0,preventOverscroll:!0,outerClassName:`min-h-0 flex-1`,className:`overscroll-contain px-4 pb-4 pt-2`,children:[(0,$.jsx)(`div`,{className:`w-full mb-4`,children:(0,$.jsx)(rd,{items:[{id:`new-branch`,label:i(`session.newWorktree.mode.newBranch`),icon:(0,$.jsx)(Z,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`existing-branch`,label:i(`session.newWorktree.mode.existingBranch`),icon:(0,$.jsx)(Z,{name:`git-repository`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>De(e),variant:`active-pill`,layoutMode:`fit`,className:`w-full`})}),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[h===`existing-branch`?(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.selectBranch`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(Qt,{variant:`outline`,size:`sm`,onClick:()=>I(!0),className:`flex-1 justify-between h-9`,children:[(0,$.jsx)(`span`,{className:y.selectedBranch?`text-foreground`:`text-muted-foreground`,children:y.selectedBranch||i(`session.newWorktree.chooseBranch`)}),(0,$.jsx)(Z,{name:`git-branch`,className:`h-4 w-4 text-muted-foreground`})]}),(0,$.jsx)(Qt,{variant:`ghost`,size:`sm`,className:`h-8 w-8 px-0 shrink-0`,onClick:fe,disabled:!de||S,title:i(`session.newWorktree.fetchBranches`),children:S?(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}):(0,$.jsx)(Z,{name:`refresh`,className:`size-4`})})]}),(0,$.jsx)(Hs,{open:F,title:i(`session.newWorktree.selectBranch`),onClose:()=>I(!1),children:(0,$.jsxs)(`div`,{className:`space-y-4`,ref:te,children:[(0,$.jsx)(Ko,{value:z,onChange:e=>B(e.target.value),placeholder:i(`session.newWorktree.searchBranches`),className:`h-8`}),S?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):w.length===0&&T.length===0?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[se&&le&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(`session.newWorktree.matchingBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:ae.matching.map(e=>(0,$.jsx)(`button`,{onClick:()=>{b(t=>({...t,selectedBranch:e.value,worktreeName:$x(e.label)})),me(e=>({...e,touched:!0})),I(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,y.selectedBranch===e.value?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))})]}),se&&!le&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),ae.otherLocal.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(se?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:ae.otherLocal.map(e=>(0,$.jsx)(`button`,{onClick:()=>{b(t=>({...t,selectedBranch:e,worktreeName:$x(e)})),me(e=>({...e,touched:!0})),I(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,y.selectedBranch===e?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},e))})]}),ae.otherRemote.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(se?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:ae.otherRemote.map(e=>(0,$.jsx)(`button`,{onClick:()=>{b(t=>({...t,selectedBranch:`remotes/${e}`,worktreeName:$x(e)})),me(e=>({...e,touched:!0})),I(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,y.selectedBranch===`remotes/${e}`?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remotes/${e}`))})]})]})]})})]}):(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col items-start gap-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.branchName`)}),h===`new-branch`&&ke&&(0,$.jsxs)(Qt,{variant:`outline`,size:`sm`,onClick:()=>A(!0),className:`gap-1.5 h-7`,children:[(0,$.jsx)(Z,{name:`github`,className:`size-4 text-status-success`}),_.linkedIssue||_.linkedPr?i(`session.newWorktree.actions.change`):i(`session.newWorktree.actions.startFromGitHubIssuePr`)]})]}),(0,$.jsx)(Ko,{value:_.branchName,onChange:e=>{v(t=>({...t,branchName:e.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>me(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.branchNamePlaceholder`),disabled:!!_.linkedPr,className:Y(`h-8`,pe.touched&&pe.branchError&&`border-destructive`,_.linkedPr&&`bg-muted text-muted-foreground`)}),_.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.usingPrBranch`,{branch:_.linkedPr.head})})]}),_.linkedIssue&&!_.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.fromIssue`,{number:_.linkedIssue.number,title:_.linkedIssue.title})})]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground font-semibold`,children:i(`session.newWorktree.worktreeDirectory`)}),h!==`existing-branch`&&(0,$.jsxs)(`button`,{onClick:()=>{let e=$x(h===`new-branch`?_.branchName:``);v(t=>({...t,worktreeName:e,isSyncingWorktreeName:!0}))},disabled:!_.branchName||_.worktreeName===$x(_.branchName),className:Y(`flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded`,_.worktreeName===$x(_.branchName)||!_.branchName?`text-muted-foreground/40 cursor-not-allowed`:`text-muted-foreground hover:text-foreground hover:bg-muted`),title:i(`session.newWorktree.resetToMatchBranchName`),children:[(0,$.jsx)(Z,{name:`refresh`,className:`h-3 w-3`}),(0,$.jsx)(`span`,{children:i(`session.newWorktree.actions.reset`)})]})]}),(0,$.jsx)(Ko,{value:Ce.worktreeName,onChange:e=>{h===`new-branch`?v(t=>({...t,worktreeName:e.target.value,isSyncingWorktreeName:!1})):b(t=>({...t,worktreeName:e.target.value}))},onBlur:()=>me(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.worktreeDirectoryPlaceholder`),className:Y(`h-8`,pe.touched&&pe.worktreeError&&`border-destructive`)})]}),h===`new-branch`&&!_.linkedPr&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.sourceBranch`)}),(0,$.jsxs)(Qt,{variant:`outline`,size:`sm`,onClick:()=>R(!0),className:`w-full justify-between h-9`,children:[(0,$.jsx)(`span`,{className:_.sourceBranch?`text-foreground`:`text-muted-foreground`,children:_.sourceBranch||i(`session.newWorktree.selectSourceBranchPlaceholder`)}),(0,$.jsx)(Z,{name:`git-branch`,className:`h-4 w-4 text-muted-foreground`})]}),_.sourceBranch&&(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:i(`session.newWorktree.newBranchFromSource`,{source:_.sourceBranch})}),(0,$.jsx)(Hs,{open:L,title:i(`session.newWorktree.selectSourceBranch`),onClose:()=>R(!1),children:(0,$.jsxs)(`div`,{className:`space-y-4`,ref:W,children:[(0,$.jsx)(Ko,{value:V,onChange:e=>H(e.target.value),placeholder:i(`session.newWorktree.searchBranches`),className:`h-8`}),S?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):w.length===0&&T.length===0?(0,$.jsx)(`div`,{className:`px-2 py-8 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)(`div`,{className:`space-y-4`,children:[ce&&ue&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(`session.newWorktree.matchingBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:oe.matching.map(e=>(0,$.jsx)(`button`,{onClick:()=>{v(t=>({...t,sourceBranch:e.value})),R(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,_.sourceBranch===e.value?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))})]}),ce&&!ue&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),oe.otherLocal.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(ce?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:oe.otherLocal.map(e=>(0,$.jsx)(`button`,{onClick:()=>{v(t=>({...t,sourceBranch:e})),R(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,_.sourceBranch===e?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},e))})]}),oe.otherRemote.length>0&&(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`div`,{className:`typography-small font-semibold text-foreground px-2`,children:i(ce?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`)}),(0,$.jsx)(`div`,{className:`space-y-1`,children:oe.otherRemote.map(e=>(0,$.jsx)(`button`,{onClick:()=>{v(t=>({...t,sourceBranch:`remotes/${e}`})),R(!1)},className:Y(`w-full text-left px-3 py-2.5 rounded-md transition-colors`,_.sourceBranch===`remotes/${e}`?`bg-interactive-selection text-interactive-selection-foreground`:`hover:bg-interactive-hover`),children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remotes/${e}`))})]})]})]})})]}),(_.linkedIssue||_.linkedPr)&&h===`new-branch`&&(0,$.jsxs)(`div`,{className:`mt-2 px-2 py-1.5 rounded bg-muted/30`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`github`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),_.linkedIssue&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.issueNumber`,{number:_.linkedIssue.number})}),_.linkedPr&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.prNumber`,{number:_.linkedPr.number})}),(0,$.jsx)(`span`,{className:`typography-micro text-foreground truncate flex-1`,children:_.linkedIssue?.title||_.linkedPr?.title}),(0,$.jsx)(`a`,{href:_.linkedIssue?.url||_.linkedPr?.url,target:`_blank`,rel:`noopener noreferrer`,className:`text-muted-foreground hover:text-foreground shrink-0`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(Z,{name:`external-link`,className:`h-3 w-3`})}),(0,$.jsx)(`button`,{onClick:je,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(Z,{name:`close`,className:`h-3.5 w-3.5`})})]}),_.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-0.5 pl-5`,children:[(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[_.linkedPr.head,` → `,_.linkedPr.base]}),_.includePrDiff&&(0,$.jsx)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success`,children:i(`session.newWorktree.includeDiffBadge`)})]})]})]})]}),(0,$.jsx)(`div`,{className:`shrink-0 border-t border-border/50 px-4 pb-3 pt-2`,children:Me})]})}):(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsxs)(po,{className:`max-w-lg max-h-[80vh] flex flex-col`,children:[(0,$.jsx)(lo,{className:`flex flex-row items-center justify-between`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsxs)(mo,{className:`flex items-center gap-2 shrink-0`,children:[(0,$.jsx)(Z,{name:`git-branch`,className:`h-5 w-5`}),i(`session.newWorktree.title`)]}),(0,$.jsx)(`div`,{className:`w-[280px] shrink-0`,children:(0,$.jsx)(rd,{items:[{id:`new-branch`,label:i(`session.newWorktree.mode.newBranch`),icon:(0,$.jsx)(Z,{name:`git-branch`,className:`h-3.5 w-3.5`})},{id:`existing-branch`,label:i(`session.newWorktree.mode.existingBranch`),icon:(0,$.jsx)(Z,{name:`git-repository`,className:`h-3.5 w-3.5`})}],activeId:h,onSelect:e=>De(e),variant:`active-pill`,layoutMode:`fit`,className:`w-full`})})]})}),(0,$.jsxs)(`div`,{className:`flex-1 overflow-y-auto mt-2 space-y-6`,children:[h===`existing-branch`?(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.selectBranch`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsxs)(Cs,{open:j,onOpenChange:M,children:[(0,$.jsx)(Is,{asChild:!0,children:(0,$.jsxs)(Qt,{variant:`outline`,size:`sm`,className:`h-9 min-w-[220px] max-w-full justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:Y(`truncate`,y.selectedBranch?`text-foreground`:`text-muted-foreground`),children:y.selectedBranch||i(`session.newWorktree.chooseBranch`)}),(0,$.jsx)(Z,{name:`arrow-down-s`,className:`h-4 w-4 shrink-0 text-muted-foreground`})]})}),(0,$.jsx)(Ss,{align:`start`,sideOffset:6,portalToBody:!0,className:`w-[min(42rem,calc(100vw-2rem))] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden`,ref:ee,children:(0,$.jsxs)(wx,{shouldFilter:!1,children:[(0,$.jsx)(Tx,{placeholder:i(`session.newWorktree.searchBranches`),value:z,onValueChange:B,onKeyDown:ne}),(0,$.jsx)(Ex,{disableHorizontal:!0,children:S?(0,$.jsx)(`div`,{className:`px-2 py-4 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):w.length===0&&T.length===0?(0,$.jsx)(Dx,{children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)($.Fragment,{children:[se&&le&&(0,$.jsx)(Ox,{heading:i(`session.newWorktree.matchingBranches`),children:ae.matching.map(e=>(0,$.jsx)(Ax,{value:e.value,onSelect:()=>{b(t=>({...t,selectedBranch:e.value,worktreeName:$x(e.label)})),me(e=>({...e,touched:!0})),M(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))}),se&&!le&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),ae.otherLocal.length>0&&(0,$.jsxs)($.Fragment,{children:[se&&(0,$.jsx)(kx,{}),(0,$.jsx)(Ox,{heading:i(se?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`),children:ae.otherLocal.map(e=>(0,$.jsx)(Ax,{value:e,onSelect:()=>{b(t=>({...t,selectedBranch:e,worktreeName:$x(e)})),me(e=>({...e,touched:!0})),M(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`local-${e}`))})]}),ae.otherRemote.length>0&&(0,$.jsxs)($.Fragment,{children:[(ae.otherLocal.length>0||se)&&(0,$.jsx)(kx,{}),(0,$.jsx)(Ox,{heading:i(se?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`),children:ae.otherRemote.map(e=>(0,$.jsx)(Ax,{value:`remotes/${e}`,onSelect:()=>{b(t=>({...t,selectedBranch:`remotes/${e}`,worktreeName:$x(e)})),me(e=>({...e,touched:!0})),M(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remote-${e}`))})]})]})})]})})]}),(0,$.jsx)(Qt,{variant:`ghost`,size:`sm`,className:`h-8 w-8 px-0 shrink-0`,onClick:fe,disabled:!de||S,title:i(`session.newWorktree.fetchBranches`),children:S?(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}):(0,$.jsx)(Z,{name:`refresh`,className:`size-4`})})]})]}):(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.branchName`)}),h===`new-branch`&&ke&&(0,$.jsxs)(Qt,{variant:`outline`,size:`sm`,onClick:()=>A(!0),className:`gap-1.5 h-7`,children:[(0,$.jsx)(Z,{name:`github`,className:`size-4 text-status-success`}),_.linkedIssue||_.linkedPr?i(`session.newWorktree.actions.change`):i(`session.newWorktree.actions.startFromGitHubIssuePr`)]})]}),(0,$.jsx)(Ko,{value:_.branchName,onChange:e=>{v(t=>({...t,branchName:e.target.value,isSyncingWorktreeName:!0,linkedIssue:null,linkedPr:null}))},onBlur:()=>me(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.branchNamePlaceholder`),disabled:!!_.linkedPr,className:Y(`h-8`,pe.touched&&pe.branchError&&`border-destructive`,_.linkedPr&&`bg-muted text-muted-foreground`)}),_.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.usingPrBranch`,{branch:_.linkedPr.head})})]}),_.linkedIssue&&!_.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 text-muted-foreground`,children:[(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5 text-status-success`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:i(`session.newWorktree.fromIssue`,{number:_.linkedIssue.number,title:_.linkedIssue.title})})]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground font-semibold`,children:i(`session.newWorktree.worktreeDirectory`)}),h!==`existing-branch`&&(0,$.jsxs)(`button`,{onClick:()=>{let e=$x(h===`new-branch`?_.branchName:``);v(t=>({...t,worktreeName:e,isSyncingWorktreeName:!0}))},disabled:!_.branchName||_.worktreeName===$x(_.branchName),className:Y(`flex items-center gap-1 typography-micro transition-colors px-1.5 py-0.5 rounded`,_.worktreeName===$x(_.branchName)||!_.branchName?`text-muted-foreground/40 cursor-not-allowed`:`text-muted-foreground hover:text-foreground hover:bg-muted`),title:i(`session.newWorktree.resetToMatchBranchName`),children:[(0,$.jsx)(Z,{name:`refresh`,className:`h-3 w-3`}),(0,$.jsx)(`span`,{children:i(`session.newWorktree.actions.reset`)})]})]}),(0,$.jsx)(Ko,{value:Ce.worktreeName,onChange:e=>{h===`new-branch`?v(t=>({...t,worktreeName:e.target.value,isSyncingWorktreeName:!1})):b(t=>({...t,worktreeName:e.target.value}))},onBlur:()=>me(e=>({...e,touched:!0})),placeholder:i(`session.newWorktree.worktreeDirectoryPlaceholder`),className:Y(`h-8`,pe.touched&&pe.worktreeError&&`border-destructive`)})]}),h===`new-branch`&&!_.linkedPr&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`typography-ui-label text-foreground block font-semibold`,children:i(`session.newWorktree.sourceBranch`)}),(0,$.jsxs)(Cs,{open:N,onOpenChange:P,children:[(0,$.jsx)(Is,{asChild:!0,children:(0,$.jsxs)(Qt,{variant:`outline`,size:`sm`,className:`h-9 min-w-[220px] max-w-full justify-between gap-2`,children:[(0,$.jsx)(`span`,{className:Y(`truncate`,_.sourceBranch?`text-foreground`:`text-muted-foreground`),children:_.sourceBranch||i(`session.newWorktree.selectSourceBranchPlaceholder`)}),(0,$.jsx)(Z,{name:`arrow-down-s`,className:`h-4 w-4 shrink-0 text-muted-foreground`})]})}),(0,$.jsx)(Ss,{align:`start`,portalToBody:!0,className:`w-[min(42rem,calc(100vw-2rem))] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden`,ref:U,children:(0,$.jsxs)(wx,{shouldFilter:!1,children:[(0,$.jsx)(Tx,{placeholder:i(`session.newWorktree.searchBranches`),value:V,onValueChange:H,onKeyDown:ne}),(0,$.jsx)(Ex,{disableHorizontal:!0,children:S?(0,$.jsx)(`div`,{className:`px-2 py-4 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.loadingBranches`)}):w.length===0&&T.length===0?(0,$.jsx)(Dx,{children:i(`session.newWorktree.noBranchesFound`)}):(0,$.jsxs)($.Fragment,{children:[ce&&ue&&(0,$.jsx)(Ox,{heading:i(`session.newWorktree.matchingBranches`),children:oe.matching.map(e=>(0,$.jsx)(Ax,{value:e.value,onSelect:()=>{v(t=>({...t,sourceBranch:e.value})),P(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e.label})},`${e.source}-${e.value}`))}),ce&&!ue&&(0,$.jsx)(`div`,{className:`px-2 py-1 text-center typography-small text-muted-foreground`,children:i(`session.newWorktree.noMatchingBranches`)}),oe.otherLocal.length>0&&(0,$.jsxs)($.Fragment,{children:[ce&&(0,$.jsx)(kx,{}),(0,$.jsx)(Ox,{heading:i(ce?`session.newWorktree.otherLocalBranches`:`session.newWorktree.localBranches`),children:oe.otherLocal.map(e=>(0,$.jsx)(Ax,{value:e,onSelect:()=>{v(t=>({...t,sourceBranch:e})),P(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`local-${e}`))})]}),oe.otherRemote.length>0&&(0,$.jsxs)($.Fragment,{children:[(oe.otherLocal.length>0||ce)&&(0,$.jsx)(kx,{}),(0,$.jsx)(Ox,{heading:i(ce?`session.newWorktree.otherRemoteBranches`:`session.newWorktree.remoteBranches`),children:oe.otherRemote.map(e=>(0,$.jsx)(Ax,{value:`remotes/${e}`,onSelect:()=>{v(t=>({...t,sourceBranch:`remotes/${e}`})),P(!1)},children:(0,$.jsx)(`span`,{className:`typography-small break-all`,children:e})},`remote-${e}`))})]})]})})]})})]}),_.sourceBranch&&(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:i(`session.newWorktree.newBranchFromSource`,{source:_.sourceBranch})})]}),(_.linkedIssue||_.linkedPr)&&h===`new-branch`&&(0,$.jsxs)(`div`,{className:`mt-2 px-2 py-1.5 rounded bg-muted/30`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`github`,className:`h-3.5 w-3.5 text-status-success shrink-0`}),_.linkedIssue&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.issueNumber`,{number:_.linkedIssue.number})}),_.linkedPr&&(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground shrink-0`,children:i(`session.newWorktree.prNumber`,{number:_.linkedPr.number})}),(0,$.jsx)(`span`,{className:`typography-micro text-foreground truncate flex-1`,children:_.linkedIssue?.title||_.linkedPr?.title}),(0,$.jsx)(`a`,{href:_.linkedIssue?.url||_.linkedPr?.url,target:`_blank`,rel:`noopener noreferrer`,className:`text-muted-foreground hover:text-foreground shrink-0`,onClick:e=>e.stopPropagation(),children:(0,$.jsx)(Z,{name:`external-link`,className:`h-3 w-3`})}),(0,$.jsx)(`button`,{onClick:je,className:`text-muted-foreground hover:text-foreground shrink-0 p-0.5 rounded hover:bg-muted transition-colors`,children:(0,$.jsx)(Z,{name:`close`,className:`h-3.5 w-3.5`})})]}),_.linkedPr&&(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-0.5 pl-5`,children:[(0,$.jsxs)(`span`,{className:`typography-micro text-muted-foreground`,children:[_.linkedPr.head,` → `,_.linkedPr.base]}),_.includePrDiff&&(0,$.jsx)(`span`,{className:`typography-micro px-1 py-0.5 rounded bg-status-success/10 text-status-success`,children:i(`session.newWorktree.includeDiffBadge`)})]})]})]}),(0,$.jsxs)(uo,{className:`mt-1 flex items-center justify-between`,children:[(0,$.jsx)(`div`,{className:`flex items-center gap-1.5 text-destructive`,children:pe.touched&&(pe.branchError||pe.worktreeError)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`error-warning`,className:`h-3.5 w-3.5`}),(0,$.jsx)(`span`,{className:`typography-micro`,children:pe.branchError||pe.worktreeError})]})}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Qt,{variant:`outline`,size:`sm`,onClick:()=>t(!1),disabled:he,children:i(`session.newWorktree.actions.cancel`)}),(0,$.jsxs)(Qt,{size:`sm`,onClick:Ee,disabled:!Ae||he,className:`gap-1.5`,children:[he&&(0,$.jsx)(Z,{name:`loader-4`,className:`h-3.5 w-3.5 animate-spin`}),i(he?`session.newWorktree.actions.creating`:`session.newWorktree.actions.createWorktree`)]})]})]})]})}),(0,$.jsx)(Xx,{open:k,onOpenChange:A,onSelect:Oe})]})}function aS(e){let t=e.selectedDirectory??e.projectRootOption?.value??e.worktreeOptions[0]?.value??null;return t?e.projectRootOption?.value===t?e.projectRootOption.label?.trim()||null:e.worktreeOptions.find(e=>e.value===t)?.label?.trim()||null:null}function oS(e,t){if(!e||!t)return!1;let n=t.replace(/\\/g,`/`).replace(/\/+$/,``);if(!n)return!1;let r=n===`/`?`/`:n.split(`/`).pop()||``;return!!r&&e===r}var sS=(e,t)=>e??t??null,cS=(e,t)=>!!e&&t!==!1,lS=e=>e?.length?{localBranches:e.filter(e=>!e.startsWith(`remotes/`)).sort(),remoteBranches:e.filter(e=>e.startsWith(`remotes/`)).map(e=>e.replace(/^remotes\//,``)).sort()}:{localBranches:[],remoteBranches:[]},uS=e=>e.replace(/^remotes\//,``).trim(),dS=e=>{let t=uS(e),n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t},fS=({directory:e,projectDirectory:t,label:n,projectRootOption:r,worktreeOptions:i,onSelectDirectory:a,className:o,maxWidthClassName:s=`max-w-[48vw] sm:max-w-[20rem]`,presentation:c=`dropdown`})=>{let{t:l}=Yt(),{git:u}=rc(),d=sS(t,e),f=e,p=Pc(d),m=Pc(f),h=cS(d,p),g=f!==d&&cS(f,m),_=sc(d,u,h),v=sc(f,u,g),y=_.data,b=f===d?y:v.data,x=vc(e=>e.fetchStatus),S=vc(e=>f&&e.directories.get(f)?.status?.current?.trim()||null),[C,w]=Q.useState(!1),T=Nc(d,u,h&&C).data??[],[E,D]=Q.useState(null),[O,k]=Q.useState(!1),[A,j]=Q.useState(!1),M=eo(e=>e.projects),N=eo(e=>e.activeProjectId);Q.useEffect(()=>{u&&(d&&p===null&&x(d,u,{silent:!0}),f&&f!==d&&m===null&&x(f,u,{silent:!0}))},[x,u,p,m,d,f]);let P=Q.useMemo(()=>{let e=_e(t);if(e){let t=M.find(t=>_e(t.path)===e);if(t)return t.id}return N},[N,t,M]),{localBranches:F,remoteBranches:I}=Q.useMemo(()=>lS(y?.all),[y]),L=b?.current?.trim()||S||null,R=!oS(n,e)&&n||L||n||l(`chat.chatInput.branch`),z=J(async()=>{if(!u)return;let e=new Set;d&&e.add(d),f&&e.add(f),await Promise.all([...e].map(async e=>{await hc(e,u),await x(e,u,{silent:!0})}))}),B=J(e=>{let t=uS(e),n=dS(t);return i.find(e=>{let r=e.label.trim();return r===t||r===n})??null}),V=J(async e=>{if(!f||!u)return;let t=uS(e);if(L!==t&&L!==dS(t))try{await u.checkoutBranch(f,t),ro.success(l(`gitView.toast.checkedOut`,{name:t})),await z()}catch(e){let n=e instanceof Error?e.message:l(`gitView.toast.checkoutFailed`,{name:t});ro.error(n)}}),H=J(e=>{let t=uS(e);if(!t||L===t||L===dS(t))return;let n=B(t);if(n){a(n.value);return}D(t)}),ee=J(async()=>{if(!(!E||O)){k(!0);try{await V(E),D(null)}finally{k(!1)}}}),U=J(async()=>{if(!(!E||O)){k(!0);try{await gx({branch:E,projectDirectory:t??void 0})&&D(null)}finally{k(!1)}}}),te=J(async(e,t)=>{if(!f||!u)return;let n=t?.name??`origin`;try{await u.createBranch(f,e,L??`HEAD`),ro.success(l(`gitView.toast.createdBranch`,{name:e})),D(e),u.gitPush(f,{remote:n,branch:e,options:[`--set-upstream`]}).then(async()=>{await z(),ro.success(l(`gitView.toast.upstreamSet`,{branch:e,remote:n}))}).catch(async e=>{let t=e instanceof Error?e.message:l(`gitView.toast.branchCreatedLocally`);ro.warning(l(`gitView.toast.branchCreatedLocally`),{description:(0,$.jsx)(`span`,{className:`text-foreground/80 dark:text-foreground/70`,children:t})}),await z()})}catch(e){let t=e instanceof Error?e.message:l(`gitView.toast.createBranchFailed`);throw ro.error(t),e}}),W=J(()=>{let e=eo.getState(),n=_e(t),r=n?e.projects.find(e=>_e(e.path)===n)??null:null;r&&e.activeProjectId!==r.id&&e.setActiveProjectIdOnly(r.id),j(!0)}),ne=J((e,n)=>{if(j(!1),n?.sessionId){X.getState().setCurrentSession(n.sessionId,e);return}let r=eo.getState(),i=_e(t),a=(i?r.projects.find(e=>_e(e.path)===i)??null:null)?.id??r.activeProjectId??null,o=X.getState();if(o.newSessionDraft?.open){o.overrideNewSessionDraftTarget({...a?{selectedProjectId:a}:{},directoryOverride:e,bootstrapPendingDirectory:e,preserveDirectoryOverride:!0}),$e.getState().setDirectory(e,{showOverlay:!1});return}o.openNewSessionDraft({...a?{selectedProjectId:a}:{},directoryOverride:e,preserveDirectoryOverride:!0})}),G=(0,$.jsxs)(`button`,{type:`button`,className:Y(`group relative inline-flex min-w-0 w-fit items-center gap-1.5 rounded-lg !border-0 px-1.5 font-medium text-foreground/80`,c===`mobile-sheet`?`h-[26px] text-[11px] leading-none`:`h-6 py-1 pr-1.5 typography-micro transition-[padding] hover:pr-5 focus-visible:pr-5 data-[popup-open]:pr-5`,s,kv,o),"aria-label":R,children:[(0,$.jsx)(Z,{name:`git-branch`,className:`size-3.5 shrink-0 text-muted-foreground`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:R}),c===`dropdown`?(0,$.jsx)(Z,{name:`arrow-down-s`,className:`pointer-events-none absolute right-1 size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100 group-data-[popup-open]:opacity-100`,"aria-hidden":`true`}):null]});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(qx,{currentBranch:L,localBranches:F,remoteBranches:I,branchInfo:y?.branches,onCheckout:H,onCreate:te,remotes:T,trigger:G,triggerLabel:R,hideTooltip:!0,projectRootOption:r,worktreeOptions:i,selectedDirectory:e,onSelectDirectory:a,onCreateWorktree:W,open:C,presentation:c,onOpenChange:w}),A?(0,$.jsx)(iS,{open:!0,projectId:P,onOpenChange:j,onWorktreeCreated:ne}):null,(0,$.jsx)(_o,{open:!!E,onOpenChange:e=>{!e&&!O&&D(null)},children:(0,$.jsxs)(po,{showCloseButton:!1,className:`max-w-sm gap-4`,children:[(0,$.jsxs)(lo,{children:[(0,$.jsx)(mo,{children:l(`chat.chatInput.branchSwitch.title`,{branch:E??``})}),(0,$.jsx)(ho,{children:l(`chat.chatInput.branchSwitch.description`)})]}),(0,$.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,$.jsxs)(`button`,{type:`button`,disabled:O,onClick:()=>{ee()},className:`flex w-full flex-col items-start gap-0.5 rounded-lg border border-border px-3 py-2.5 text-left hover:bg-interactive-hover disabled:opacity-50`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 typography-ui-label font-medium text-foreground`,children:[O?(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(Z,{name:`arrow-left-right`,className:`size-3.5 text-muted-foreground`}),l(`chat.chatInput.branchSwitch.checkoutHere`)]}),(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground`,children:l(`chat.chatInput.branchSwitch.checkoutHereDescription`)})]}),(0,$.jsxs)(`button`,{type:`button`,disabled:O,onClick:()=>{U()},className:`flex w-full flex-col items-start gap-0.5 rounded-lg border border-border px-3 py-2.5 text-left hover:bg-interactive-hover disabled:opacity-50`,children:[(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 typography-ui-label font-medium text-foreground`,children:[O?(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(Z,{name:`git-branch`,className:`size-3.5 text-muted-foreground`}),l(`chat.chatInput.branchSwitch.createWorktree`)]}),(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground`,children:l(`chat.chatInput.branchSwitch.createWorktreeDescription`)})]})]}),(0,$.jsx)(uo,{children:(0,$.jsx)(`button`,{type:`button`,disabled:O,onClick:()=>D(null),className:`inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 disabled:opacity-50`,children:l(`chat.chatInput.branchSwitch.cancel`)})})]})})]})},pS=[],mS=[],hS={revertMessageID:void 0,records:mS},gS=e=>e.role===`user`,_S=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]?.message!==t[n]?.message||e[n]?.parts!==t[n]?.parts)return!1;return!0},vS=(e,t,n=hS)=>{if(!t)return hS;let r=(`session`in e?e.session:[]).find(e=>e.id===t)?.revert?.messageID;if(!r)return hS;let i=`messages`in e?e.messages:e.message[t]??[],a=`partsByMessageID`in e?e.partsByMessageID:e.part,o=[];for(let e of i)!gS(e)||!cn(i,e.id,r)||o.push({message:e,parts:a[e.id]??pS});let s=o.length===0?mS:o;return n.revertMessageID===r&&_S(n.records,s)?n:{revertMessageID:r,records:s}},yS=`bg-[var(--surface-subtle)]`,bS=91,xS=94,SS={keyword:8,function:7,type:6,string:5,number:5,variable:4,operator:3,comment:2},CS={keyword:`${yS} text-[var(--syntax-keyword)]`,string:`${yS} text-[var(--syntax-string)]`,number:`${yS} text-[var(--syntax-number)]`,comment:`${yS} text-[var(--syntax-comment)]`,function:`${yS} text-[var(--syntax-function)]`,type:`${yS} text-[var(--syntax-type)]`,variable:`${yS} text-[var(--syntax-variable)]`,operator:`${yS} text-[var(--syntax-operator)]`},wS=Nt([{tag:[Ft.comment,Ft.lineComment,Ft.blockComment,Ft.docComment,Ft.meta],class:`comment`},{tag:[Ft.keyword,Ft.modifier,Ft.controlKeyword,Ft.operatorKeyword,Ft.definitionKeyword,Ft.moduleKeyword,Ft.self,Ft.null],class:`keyword`},{tag:[Ft.string,Ft.special(Ft.string),Ft.docString,Ft.character,Ft.regexp],class:`string`},{tag:[Ft.number,Ft.integer,Ft.float,Ft.bool,Ft.atom],class:`number`},{tag:[Ft.function(Ft.variableName),Ft.function(Ft.propertyName),Ft.macroName,Ft.standard(Ft.variableName)],class:`function`},{tag:[Ft.typeName,Ft.className,Ft.namespace,Ft.tagName],class:`type`},{tag:[Ft.variableName,Ft.propertyName,Ft.attributeName,Ft.labelName,Ft.definition(Ft.variableName)],class:`variable`},{tag:[Ft.operator,Ft.punctuation,Ft.bracket,Ft.derefOperator,Ft.separator],class:`operator`},{tag:[Ft.heading,Ft.heading1,Ft.heading2,Ft.heading3,Ft.heading4,Ft.heading5,Ft.heading6,Ft.strong],class:`keyword`},{tag:[Ft.emphasis,Ft.quote],class:`type`},{tag:[Ft.link,Ft.url],class:`function`},{tag:[Ft.monospace],class:`string`},{tag:[Ft.strikethrough],class:`comment`}]),TS=e=>{let t=null;for(let n of e.split(` `)){let e=n;SS[e]!==void 0&&(t===null||SS[e]>SS[t])&&(t=e)}return t?CS[t]:null},ES=2e4,DS=e=>{if(!e)return null;try{let t=us(e);return t instanceof It?t:null}catch{return null}};function OS(e){if(!e||!e.includes("```")&&!e.includes(`~~~`))return[];let t=[],n=e.split(`
|
|
6524
6524
|
`),r=0;for(let e=0;e<n.length;e+=1){let i=n[e];r+=i.length+1;let a=Ru(i);if(!a)continue;let o=DS(a.lang),s=r,c=[],l=e+1,u=r;for(;l<n.length;l+=1){let e=n[l];if(Wu(e,a.marker)){u+=e.length+1;break}c.push(e),u+=e.length+1}if(e=l,r=u,!o||c.length===0)continue;let d=c.join(`
|
|
6525
|
-
`);if(d.trim()&&(t.push({start:s,end:s+d.length,style:`codeFence`,className:`${yS} text-[var(--syntax-foreground)]`,priority:bS}),!(d.length>ES)))try{let e=o.parser.parse(d);Pt(e,wS,(e,n,r)=>{let i=TS(r);i&&t.push({start:s+e,end:s+n,style:`codeFence`,className:i,priority:xS})})}catch{}}return t}var kS=[`CodeFiles`,`codefiles`,`application/vnd.code.tree`,`application/vnd.code.tree.explorer`,`text/uri-list`,`text/plain`],AS=e=>e.startsWith(`/`)||e.startsWith(`//`)||e.startsWith(`\\\\`)||/^[A-Za-z]:[\\/]/.test(e),jS=e=>{if(!AS(e)||/\s/.test(e))return!1;if(e.startsWith(`//`)||e.startsWith(`\\\\`)){let t=e.replace(/^[\\/]+/,``);return/[\\/]/.test(t)}if(/^[A-Za-z]:[\\/]/.test(e)){let t=e.slice(3);return t.includes(`\\`)||t.includes(`/`)||t.includes(`.`)}return e.replace(/^\/+/,``).includes(`/`)},MS=(e,{fromPlainText:t=!1}={})=>{let n=e.trim().replace(/^['"]+|['"]+$/g,``);return!n||n===`/>`||/[\r\n]/.test(n)?null:n.toLowerCase().startsWith(`file://`)||(t?jS(n):AS(n))?n:null},NS=(e,t,n=0)=>{if(!(n>6||e==null)){if(typeof e==`string`){t.add(e);return}if(Array.isArray(e)){for(let r of e)NS(r,t,n+1);return}if(typeof e==`object`)for(let r of Object.values(e))NS(r,t,n+1)}},PS=(e,{allowMultipleLines:t=!0,allowStructuredPayload:n=!0,fromPlainText:r=!1}={})=>{let i=new Set,a=e=>{let n=MS(e,{fromPlainText:r});if(n){i.add(n);return}if(t)for(let t of e.split(/\r?\n/)){let e=MS(t,{fromPlainText:r});e&&i.add(e)}};if(a(e),n)try{let t=JSON.parse(e),n=new Set;NS(t,n);for(let e of n)a(e)}catch{}return Array.from(i)},FS=e=>{if(!e||typeof e.getData!=`function`)return[];let t=new Set;for(let n of kS){let r=``;try{r=e.getData(n)}catch{continue}let i=n===`text/plain`?{allowMultipleLines:!1,allowStructuredPayload:!1,fromPlainText:!0}:n===`text/uri-list`?{allowStructuredPayload:!1}:void 0;for(let e of PS(r,i))t.add(e)}return Array.from(t)},IS=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(`file://`))return t;try{let e=new URL(t),n=decodeURIComponent(e.pathname||``);return e.hostname&&e.hostname!==`localhost`&&(n=`//${e.hostname}${n}`),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),n||t}catch{let e=t.replace(/^file:\/\//i,``);try{return decodeURIComponent(e)}catch{return e}}},LS=e=>AS(e);function RS(e,t){let n=(0,pd.c)(5),r=si(e,t),i=q(zS),a;n[0]===r?a=n[1]:(a=Yi(r),n[0]=r,n[1]=a);let o;return n[2]!==i||n[3]!==a?(o={goal:a,enabled:i},n[2]=i,n[3]=a,n[4]=o):o=n[4],o}function zS(e){return e.sessionGoalEnabled}function BS(e,t){let n=(0,pd.c)(4),[r,i]=Q.useState(null),a=t?.objectiveFile?`${e}:${t.id}:${t.updatedAt}`:``,o,s;return n[0]!==a||n[1]!==e?(o=()=>{if(!a){i(null);return}let t=!0;return Ar(e).then(e=>{t&&i(e)}),()=>{t=!1}},s=[a,e],n[0]=a,n[1]=e,n[2]=o,n[3]=s):(o=n[2],s=n[3]),Q.useEffect(o,s),t?t.objectiveFile?r:t.objective:null}var VS={active:`var(--status-info)`,paused:`var(--surface-muted-foreground)`,blocked:`var(--status-warning)`,budgetLimited:`var(--status-warning)`,complete:`var(--status-success)`},HS={active:`chat.goal.status.active`,paused:`chat.goal.status.paused`,blocked:`chat.goal.status.blocked`,budgetLimited:`chat.goal.status.budgetLimited`,complete:`chat.goal.status.complete`},US=Q.memo(({sessionId:e,directory:t,className:n})=>{let{t:r}=Yt(),i=q(e=>e.isMobile),{goal:a,enabled:o}=RS(e??``,t),s=BS(e??``,a),c=wi(e??``,t),l=ti(e,t),u=Q.useRef(null),[d,f]=Q.useState(!1),[p,m]=Q.useState(()=>Date.now());Q.useEffect(()=>{if(!a||a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`)return;let e=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(e)},[a?.id,a?.status]),Q.useEffect(()=>{if(!e||!a||a.status!==`active`)return;let n=l[0]?.id;if(!n)return;let r=`${e}:${a.id}:${n}`;u.current!==r&&(u.current=r,Tn(e,t))},[e,t,a,l]);let h=J(async n=>{if(!(!e||d)){f(!0);try{await bn(e,t,n)}catch(e){console.warn(`[session-goal] status change failed:`,e),ro.error(r(`chat.goal.toast.actionFailed`))}finally{f(!1)}}});if(!e||!o||!a)return null;let g=Math.max(0,(a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`?a.updatedAt:p)-(a.createdAt||p)),_=ea(g),v=a.tokenBudget?`${sn(a.tokensUsed)}/${sn(a.tokenBudget)}`:a.tokensUsed>0?sn(a.tokensUsed):null,y=a.status===`active`?{icon:`pause`,labelKey:`chat.goal.action.pause`,next:`paused`}:a.status===`paused`||a.status===`blocked`||a.status===`budgetLimited`?{icon:`play`,labelKey:`chat.goal.action.resume`,next:`active`}:null,b=i?`text-[11px] leading-none text-muted-foreground`:`typography-meta text-muted-foreground`,x=i?`text-xs leading-5 text-foreground`:`typography-ui-label leading-5 text-foreground`,S=i?`size-3`:`size-3.5`;return(0,$.jsxs)(`div`,{className:Y(`flex w-full min-w-0 items-center`,i?`gap-1 py-0.5`:`gap-1.5 py-0.5 md:gap-2`,n),"aria-label":r(`chat.goal.row.aria`),title:s??void 0,children:[(0,$.jsx)(Z,{name:`target`,className:Y(S,`flex-shrink-0`),style:{color:VS[a.status]},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 truncate`,x),children:a.note||s||``}),a.status===`active`&&(!c||c.type===`idle`)?(0,$.jsxs)(`span`,{className:Y(`flex flex-shrink-0 items-center gap-1`,b),children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(S,`animate-spin`),"aria-hidden":`true`}),r(`chat.goal.status.evaluating`)]}):(0,$.jsx)(`span`,{className:Y(`flex-shrink-0`,b),children:r(HS[a.status])}),(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,b,`text-muted-foreground/70`),children:_}),v?(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,b,`text-muted-foreground/70`),children:v}):null,y?(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void h(y.next),disabled:d,className:Y(`inline-flex flex-shrink-0 cursor-pointer items-center bg-transparent text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50`,i?`h-7 gap-1.5 px-0 text-[11px]`:`h-7 gap-1 px-0.5`),"aria-label":r(y.labelKey),children:[(0,$.jsx)(Z,{name:y.icon,className:S,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`font-medium`,i?`leading-none`:`typography-ui-label`),children:r(y.labelKey)})]}):null]})});US.displayName=`SessionGoalRow`;var WS=Q.memo(({sessionId:e,directory:t,draftOpen:n=!1})=>{let{t:r}=Yt(),{goal:i,enabled:a}=RS(e??``,t),o=An(e=>e.armed),s=An(e=>e.setArmed),[c,l]=Q.useState(!1);if(ge()||!a||!e&&!n||!o&&!i)return null;let u=i?.status===`complete`?`text-[var(--status-success)]`:i?.status===`blocked`||i?.status===`budgetLimited`?`text-[var(--status-error)]`:o||i?.status===`active`||i?.status===`paused`?`text-[var(--status-info)]`:``,d=async()=>{if(o){s(!1);return}if(!(!e||c)){l(!0);try{await Ga(e,t)}catch(e){console.warn(`[session-goal] clear failed:`,e),ro.error(r(`chat.goal.toast.actionFailed`))}finally{l(!1)}}};return(0,$.jsxs)(`span`,{className:Y(`inline-flex h-7 items-center gap-1 rounded-full bg-[var(--surface-muted)] py-1 pl-2 pr-1 typography-ui-label`,u),children:[(0,$.jsx)(Z,{name:`target`,className:`h-4 w-4`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:r(`chat.goal.chip.label`)}),(0,$.jsx)(`button`,{type:`button`,className:`flex h-5 w-5 items-center justify-center rounded-full text-current hover:bg-[var(--interactive-hover)] disabled:opacity-50`,onClick:()=>void d(),disabled:c,"aria-label":r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),title:r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),children:(0,$.jsx)(Z,{name:`close`,className:`h-3 w-3`,"aria-hidden":`true`})})]})});WS.displayName=`SessionGoalButton`;var GS=Q.memo(e=>{let t=(0,pd.c)(11),{length:n}=e,{t:r}=Yt();if(!An(KS)||n===0)return null;let i=n>5e3?`text-[var(--status-error)]`:`text-muted-foreground/70`,a;t[0]===i?a=t[1]:(a=Y(`flex-shrink-0 self-center typography-micro tabular-nums`,i),t[0]=i,t[1]=a);let o;t[2]===r?o=t[3]:(o=r(`chat.goal.counter.aria`),t[2]=r,t[3]=o);let s;t[4]===r?s=t[5]:(s=r(`chat.goal.counter.aria`),t[4]=r,t[5]=s);let c;return t[6]!==n||t[7]!==a||t[8]!==o||t[9]!==s?(c=(0,$.jsxs)(`span`,{className:a,"aria-label":o,title:s,children:[n,`/`,pr]}),t[6]=n,t[7]=a,t[8]=o,t[9]=s,t[10]=c):c=t[10],c});GS.displayName=`SessionGoalObjectiveCounter`;function KS(e){return e.armed}var qS=new Set([`new`,`fork`,`compact`,`undo`,`redo`,`timeline`,`model`,`summary`,`workspace-review`,`handoff-review`,`goal`,`craft-goal`,`catch-up`,`debug`,`weigh`,`explore`]),JS=new Set([`new`,`compact`,`fork`,`undo`,`redo`]),YS=/^\/\u2003?([^\s]+)/i,XS=/^\/\u2003?goal\b/i,ZS=(e,t)=>{if(t!==`normal`)return null;let n=e.trimStart().match(YS)?.[1]?.toLowerCase();return n&&qS.has(n)?n:null},QS=(e,t)=>ZS(e,t)===`goal`?e.trimStart().replace(XS,``).trim():null,$S=(e,t)=>ZS(e,t)!==null,eC=(e,t)=>{let n=ZS(e,t);return n!==null&&JS.has(n)},tC=({currentSessionId:e,messageRef:t,replacePlainDocument:n})=>{let r=e;return t.current=``,n(``),r},nC=async({command:e,consumeCommandText:t,forkSession:n,waitForConnection:r,getDirectoryForSession:i,summarizeSession:a,onCompactError:o,onForkError:s})=>{if(t(),e===`fork`){try{await n()}catch(e){s(e)}return}try{await r();let e=i();if(!e){o();return}await a(e)}catch{o()}},rC=e=>!e.queuedOnly&&!e.resourcePolicy&&e.rootAttachmentCount>0,iC=e=>e.surfaceKind===`primary`&&!!e.currentSessionId&&!e.queuedOnly&&!e.resourcePolicy&&e.inputMode!==`shell`&&!e.localCommand,aC=e=>e.surfaceKind!==`primary`||!e.stagedSessionId||!e.stagedMessageId||e.stagedMessageId!==e.blurredMessageId||e.submitInFlight||e.focusHeld||e.overlayOpen||e.focusInsideComposer?{action:`keep`}:{action:`disarm`,sessionId:e.stagedSessionId},oC=e=>({state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:{kind:`primary`},runtimeGeneration:e.runtimeGeneration}),sC=(e,t)=>{let n=k.getState();return n.bindLegacyQueue(E(e.sessionID),e),n.stageAdmission(e,{requestID:t.requestID,queueItemID:t.queueItemID,operationID:t.operationID,messageID:t.messageID,content:t.content,createdAt:t.createdAt,attachmentCount:t.attachments.length,...t.composerDocument?{composerDocument:t.composerDocument}:{},...t.composerMentions?{composerMentions:t.composerMentions}:{}}),n.confirmAdmission(e,{requestID:t.requestID,sendConfig:t.sendConfig,attachments:t.attachments}).ok},cC=async e=>{let t=$i.getState().takeEstablishingPending(e.draftID);if(t.length===0)return{drained:0,failed:0};let n=oC(e),r=0,i=0;for(let a of t)try{if(e.admitServer&&(await e.admitServer(a)).status===`committed`){r+=1;continue}sC(n,a)?r+=1:i+=1}catch{try{sC(n,a)?r+=1:i+=1}catch{i+=1}}return{drained:r,failed:i}},lC=(e,t)=>Promise.resolve().then(()=>e()).catch(()=>{t()}),uC=e=>e===`allow`||e===`ask`||e===`deny`,dC=e=>{if(uC(e))return[{permission:`*`,pattern:`*`,action:e}];if(Array.isArray(e))return e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.permission==`string`&&typeof t.pattern==`string`&&uC(t.action)?[{permission:t.permission,pattern:t.pattern,action:t.action}]:[]});if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e))if(n!==`__originalKeys`){if(uC(r)){t.push({permission:n,pattern:`*`,action:r});continue}if(!(!r||typeof r!=`object`||Array.isArray(r)))for(let[e,i]of Object.entries(r))uC(i)&&t.push({permission:n,pattern:e,action:i})}return t},fC=e=>{let t=dC(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.permission===`*`&&n.pattern===`*`)return n.action===`ask`;if(n.action===`ask`)return!0}return!0},pC=(e,t)=>{let n=t?.trim();if(!n)return e.length===0||e.some(e=>fC(e.permission));let r=e.find(e=>e?.name===n);return!r||fC(r.permission)},mC=e=>{let{permissionScopeSessionId:t,newSessionDraftOpen:n,draftPermissionAutoAcceptEnabled:r,permissionAutoAcceptEnabled:i,setDraftPermissionAutoAcceptEnabled:a,setSessionAutoAccept:o,onOpenSessionFirst:s,onToggleFailed:c}=e;if(!t){if(!n){s();return}a(!r);return}o(t,!i).catch(c)},hC=null,gC=new Set,_C=()=>{for(let e of gC)e()},vC=e=>e===`chat`||e===`assistant`,yC=()=>hC,bC=e=>{hC!==e&&(hC=e,_C())},xC=e=>{hC&&(e&&hC.surfaceID!==e||(hC=null,_C()))},SC=(e,t)=>{if(e.transportIdentity!==t.transportIdentity||e.runtimeGeneration!==t.runtimeGeneration)throw Error(`chat-input-delivery-runtime-stale`)},CC=e=>{let t={...e.options?.delivery===`steer`?{delivery:`steer`}:{},...e.options?.commitStagedMessageEdit===void 0?{}:{commitStagedMessageEdit:e.options.commitStagedMessageEdit},...e.options?.messageID?{messageID:e.options.messageID}:{},...e.options?.ticket?{ticket:e.options.ticket}:{}},n=e.options?.sessionId??e.sessionID??void 0;if(!n)return t;let r=e.options?.directoryHint===void 0?e.directory||null:e.options.directoryHint;return{...t,sessionId:n,directoryHint:r}},wC=(e,t,n={})=>({operation:t,surfaceID:e.surfaceID,transportIdentity:e.transportIdentity,runtimeGeneration:e.runtimeGeneration,sessionID:e.sessionID,directory:e.directory??``,draftKey:e.draftKey,deliveryTarget:e.deliveryTarget,...n}),TC=e=>{if(!e.active||!e.draftKey||!e.directory)return null;let t=e.activity?.phase??`idle`,n=e.activity?.canAbort??(t===`busy`||t===`retry`);return{send:async t=>{let n=wC(e,`send`,t);return await e.selection.flush(),e.kind===`secondary`&&await e.shortcuts.submit(),e.backend.send(n)},sendQueued:async(t,n={})=>{let{manual:r,...i}=n,a=wC(e,`send`,i),o=oy(e);if(await e.selection.flush(),!o)throw Error(`chat-input-queue-scope-incomplete`);return e.backend.sendQueued({...a,queueItemID:t,manual:r,queueScope:o})},create:async()=>{let t=wC(e,`create`);return await e.selection.flush(),e.backend.create(t)},compact:async t=>{let n=wC(e,`compact`,t);return await e.selection.flush(),e.backend.compact(n)},abort:async()=>{let t=wC(e,`abort`);return await e.selection.flush(),e.backend.abort(t)},queueScope:oy(e),canAbort:n,canQueue:t===`busy`||t===`retry`,allowsCommand:t=>$v(e,{name:t,source:`openchamber`}),shortcut:async(t,n=1)=>{if(e.kind===`secondary`){t===`cycle`?await e.shortcuts.cycle(n):t===`new`?await e.shortcuts.new():t===`abort`?await e.shortcuts.abort():await e.shortcuts.submit();return}if(t===`abort`){let t=wC(e,`abort`);await e.selection.flush(),await e.backend.abort(t);return}if(t===`new`){let t=wC(e,`create`);await e.selection.flush(),await e.backend.create(t);return}t!==`submit`&&await e.shortcuts?.cycle(n)},resources:e.resources??null}},EC=(e,t,n)=>{let r=e.agent;r&&r!==t.currentAgentName&&t.setAgent(r),e.providerID&&t.setProvider(e.providerID),e.modelID&&t.setModel(e.modelID),t.setCurrentVariant(e.variant);let i=r??t.currentAgentName;i&&e.providerID&&e.modelID&&t.saveAgentModelSelection(i,e.providerID,e.modelID,e.variant);let a=n?.sessionId,o=n?.memory;!a||!o||!e.providerID||!e.modelID||(o.saveSessionModelSelection(a,e.providerID,e.modelID),i&&o.saveSessionAgentSelection&&o.saveSessionAgentSelection(a,i),i&&(o.saveAgentModelForSession(a,i,e.providerID,e.modelID),o.saveAgentModelVariantForSession(a,i,e.providerID,e.modelID,e.variant)))},DC=(e,t,n)=>{let r=e.providers.find(e=>e.id===t);return r?(Array.isArray(r.models)?r.models:[]).some(e=>e.id===n):!1},OC=(e,t)=>e.agents.some(e=>e.name===t),kC=(e,t,n,r)=>{if(!r)return!0;let i=e.providers.find(e=>e.id===t)?.models?.find(e=>e.id===n)?.variants;return i?Array.isArray(i)?i.includes(r):typeof i==`object`&&Object.prototype.hasOwnProperty.call(i,r):!1},AC=e=>{let{catalog:t,providerID:n,modelID:r,historyVariant:i,memoryVariant:a}=e;if(i)return kC(t,n,r,i)?i:void 0;if(a&&kC(t,n,r,a))return a},jC=e=>{let{sessionId:t,choice:n,catalog:r,memory:i,fallbackAgentName:a,source:o}=e;if(!n.providerID||!n.modelID||!DC(r,n.providerID,n.modelID))return null;let s=n.agent&&OC(r,n.agent)?n.agent:i?.getSessionAgentSelection?.(t)&&OC(r,i.getSessionAgentSelection(t))?i.getSessionAgentSelection(t):a&&OC(r,a)?a:void 0,c=s?i?.getAgentModelVariantForSession?.(t,s,n.providerID,n.modelID):void 0,l=AC({catalog:r,providerID:n.providerID,modelID:n.modelID,historyVariant:n.variant,memoryVariant:c});return{agent:s,providerID:n.providerID,modelID:n.modelID,variant:l,source:o,messageId:n.id}},MC=e=>{let{sessionId:t,latestUserChoice:n,latestExecution:r,catalog:i,memory:a,sessionEntity:o,fallbackAgentName:s,transcriptReady:c=!0}=e;if(c&&r){let e=jC({sessionId:t,choice:r,catalog:i,memory:a,fallbackAgentName:s,source:`execution`});if(e)return e}if(c&&n){let e=jC({sessionId:t,choice:n,catalog:i,memory:a,fallbackAgentName:s,source:`history`});if(e)return e}if(c&&a){let e=a.getSessionAgentSelection?.(t)??null,n=e&&OC(i,e)?e:s&&OC(i,s)?s:void 0;if(n){let e=a.getAgentModelForSession?.(t,n);if(e&&DC(i,e.providerId,e.modelId)){let r=a.getAgentModelVariantForSession?.(t,n,e.providerId,e.modelId),o=r&&kC(i,e.providerId,e.modelId,r)?r:void 0;return{agent:n,providerID:e.providerId,modelID:e.modelId,variant:o,source:`session-memory`}}}let r=a.getSessionModelSelection?.(t);if(r&&DC(i,r.providerId,r.modelId)){let e=n?a.getAgentModelVariantForSession?.(t,n,r.providerId,r.modelId):void 0,o=e&&kC(i,r.providerId,r.modelId,e)?e:void 0;return{agent:n,providerID:r.providerId,modelID:r.modelId,variant:o,source:`session-memory`}}}let l=o?.model;if(l&&DC(i,l.providerID,l.id)){let e=a?.getSessionAgentSelection?.(t)??null,n=(o?.agent&&OC(i,o.agent)?o.agent:void 0)??(e&&OC(i,e)?e:s&&OC(i,s)?s:void 0),r=l.variant,c=r&&kC(i,l.providerID,l.id,r)?r:void 0;return{agent:n,providerID:l.providerID,modelID:l.id,variant:c,source:`session-entity`}}return null},NC=(e,t,n)=>{let r=e.agent;r&&r!==t.currentAgentName&&t.setAgent(r),e.providerID&&t.setProvider(e.providerID),e.modelID&&t.setModel(e.modelID),t.setCurrentVariant(e.variant);let{sessionId:i,memory:a}=n;a.saveSessionModelSelection(i,e.providerID,e.modelID);let o=r??t.currentAgentName;o&&a.saveSessionAgentSelection&&a.saveSessionAgentSelection(i,o),o&&(a.saveAgentModelForSession(i,o,e.providerID,e.modelID),a.saveAgentModelVariantForSession(i,o,e.providerID,e.modelID,e.variant))},PC=(e,t)=>{if((t?.expectedConfigKey===void 0||t.activeDirectoryKey===t.expectedConfigKey)&&!(!e.currentProviderId||!e.currentModelId))return{providerID:e.currentProviderId,modelID:e.currentModelId,agent:e.currentAgentName,variant:e.currentVariant}},FC=e=>e.editRevision<=0?!1:e.pinnedHistoryMessageId==null||e.latestHistoryMessageId==null||e.latestHistoryMessageId===e.pinnedHistoryMessageId,IC=e=>{if(e.captured?.providerID&&e.captured?.modelID)return e.captured;let t=e.surfaceSelection;if(!(!t?.providerID||!t?.modelID))return{providerID:t.providerID,modelID:t.modelID,...t.agent?{agent:t.agent}:{},...t.variant?{variant:t.variant}:{}}},LC=e=>typeof e==`string`&&e.trim().length>0?e:void 0,RC=e=>LC(e.agent)??LC(e.mode),zC=e=>LC(e.model?.variant)??LC(e.variant),BC=e=>{let t=LC(e.model?.providerID),n=LC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},VC=e=>{let t=LC(e.providerID)??LC(e.model?.providerID),n=LC(e.modelID)??LC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},HC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role!==`user`)continue;let r=BC(n);return{id:typeof n.id==`string`?n.id:void 0,agent:RC(n),providerID:r?.providerID,modelID:r?.modelID,variant:zC(n)}}return null},UC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`){if(BC(n))return null;continue}if(n.role!==`assistant`)continue;let r=VC(n);if(r)return{id:typeof n.id==`string`?n.id:void 0,agent:RC(n),providerID:r.providerID,modelID:r.modelID,variant:zC(n)}}return null},WC=500,GC=e=>Array.from(e).length,KC=e=>{let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(36)},qC=e=>GC(e)>=WC,JC=e=>{let t=P(e.text,e.references).document.references,n=t.reduce((e,t)=>{let n=t.kind===`paste`?t.index:0;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=1?Math.max(e,n):e},0);if(n<2**53-1)return n+1;let r=new Set(t.flatMap(e=>e.kind===`paste`&&typeof e.index==`number`&&Number.isSafeInteger(e.index)&&e.index>=1?[e.index]:[]));for(let e=1;e<=t.length+1;e+=1)if(!r.has(e))return e;return 1},YC=(e,t)=>{let n=t??e;return typeof n!=`string`||!qC(n)?!1:we(typeof e==`string`?{text:``,references:[]}:e,n)},XC=(e,t,n,r,i=1)=>{let a=GC(e),o=new Set(n.map(e=>e.token));for(let n=i;n<2**53-1;n+=1){let i=`[${r({index:n,count:a})}]`;if(!(t.includes(i)||o.has(i)))return{id:`pasted-text-${n}-${KC(e)}`,token:i,text:e,characterCount:a,index:n}}throw Error(`Unable to create a unique pasted text reference`)},ZC=e=>({text:e?.text??``,references:e?.composerReferences??[]}),QC=e=>({text:e.text,references:e.references.map(e=>({...e}))}),$C=e=>({transportIdentity:e.transportIdentity,owner:{...e.owner}}),ew=e=>JSON.stringify([e.text,e.references]),tw=(e,t)=>e!==null&&t!==null&&Se(e)===t,nw=(e,t,n)=>{let r=e?$C(e):null,i=r?n(r):void 0;return{document:y(ZC(i),t),mentions:i?.mentions??[],revision:i?.revision??0,key:r,keyID:r?Se(r):null}},rw=(e,t,n,r)=>{if(!t||Se(t.key)!==r.keyID||t.revision<r.appliedRevision)return`ignore`;let i=ew(ZC(t));return n?.keyID===r.keyID&&n.revision===t.revision&&n.fingerprint===i?`local-echo`:t.revision===r.appliedRevision?`ignore`:i===ew(e)?`same-document-metadata`:`external-document`},iw=(e,t,n)=>{let r=n.newEnd-n.oldEnd;return e.flatMap(e=>{if(e.range.start<n.oldEnd&&e.range.end>n.oldStart)return[];let i=e.range.start>=n.oldEnd?{start:e.range.start+r,end:e.range.end+r}:e.range;return t.text.slice(i.start,i.end)===`@${e.value}`?[{...e,range:i}]:[]})},aw=e=>e.map((e,t)=>({mention:e,index:t})).sort((e,t)=>e.mention.range.start-t.mention.range.start||e.mention.range.end-t.mention.range.end||e.index-t.index).map(({mention:e})=>e),ow=(e,t,n,r,i=r)=>{let a=fe(e,n,r,i);return{document:a.document,mentions:iw(t,a.document,a.edit),requiresTextCorrection:a.requiresTextCorrection,selectionStart:a.selectionStart,selectionEnd:a.selectionEnd,removedReferences:a.removedReferences}},sw=(e,t,n)=>({preview:{real:QC(e),realMentions:[...t]},document:{text:n.text,references:[]},mentions:[]}),cw=e=>({document:e.real,mentions:e.realMentions}),lw=(e,t,n,r)=>{let i=[...e,...t.map(e=>({...e,range:{start:e.range.start+r,end:e.range.end+r}}))],a=new Set;return i.filter(e=>{let t=`${e.kind}:${e.value}:${e.range.start}:${e.range.end}`;return a.has(t)||n.text.slice(e.range.start,e.range.end)!==`@${e.value}`?!1:(a.add(t),!0)})},uw=(e,t)=>{let n=ZC(t),r=v(e.document,n),i=e.document.text===n.text&&JSON.stringify(e.document.references)===JSON.stringify(n.references)?0:e.document.text.length+2;return{document:r,mentions:lw(e.mentions,t?.mentions??[],r,i)}},dw=({draftKey:e,sessionTitles:t,persistenceEnabled:n,onResourcesChanged:r,store:i=un})=>{let a=e?Se(e):null,o=(0,Q.useSyncExternalStore)(i.subscribe,()=>a?i.getState().drafts[a]:void 0,()=>void 0),s=(0,Q.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftHydration[a]??`idle`:`idle`,()=>`idle`),c=(0,Q.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftPersistence[a]:void 0,()=>void 0),[l,u]=(0,Q.useState)(()=>nw(e,t,i.getState().getDraft).document),[d,f]=(0,Q.useState)(()=>nw(e,t,i.getState().getDraft).mentions),[m,h]=(0,Q.useState)(`compose`),[g,v]=(0,Q.useState)(0),b=(0,Q.useRef)(l),C=(0,Q.useRef)(d),w=(0,Q.useRef)(t),T=(0,Q.useRef)(r),E=(0,Q.useRef)(e),D=(0,Q.useRef)(e?$C(e):null),O=(0,Q.useRef)(a),k=(0,Q.useRef)(a),A=(0,Q.useRef)(0),j=(0,Q.useRef)(o?.revision??0),M=(0,Q.useRef)(void 0),F=(0,Q.useRef)(void 0),I=(0,Q.useRef)(Ku());b.current=l,C.current=d,w.current=t,T.current=r,E.current=e,O.current=a;let L=(0,Q.useCallback)((e,t)=>{b.current=e,C.current=t,u(e),f(t)},[]),R=(0,Q.useCallback)((e,t)=>{let n=p(e,t);T.current?.(n)},[]);(0,Q.useEffect)(()=>{i.getState().setDraftPersistenceEnabled(n)},[n,i]),(0,Q.useLayoutEffect)(()=>{A.current+=1;let e=A.current;k.current=a;let t=nw(E.current,w.current,i.getState().getDraft),n=t.key;if(D.current=t.key,M.current=void 0,F.current=void 0,I.current=Ku(),h(`compose`),j.current=t.revision,L(t.document,t.mentions),v(e=>e+1),n?.owner.kind===`draft`){let r=t.revision;i.getState().claimLegacyNewDraft(n).then(t=>{let o=i.getState().getDraft(n);!t||!tw(D.current,a)||k.current!==a||O.current!==a||A.current!==e||j.current!==r||o?.revision!==t.revision||(j.current=t.revision,L(y(ZC(t),w.current),t.mentions))})}},[a,L,i]),(0,Q.useEffect)(()=>{if(!a||k.current!==a||F.current)return;let e=rw(b.current,o,M.current,{keyID:a,epoch:A.current,appliedRevision:j.current});if(e!==`ignore`){if(o&&(j.current=o.revision),e===`local-echo`||e===`same-document-metadata`){o&&f(o.mentions);return}e===`external-document`&&o&&(M.current=void 0,L(y(ZC(o),w.current),o.mentions),h(`compose`),v(e=>e+1))}},[a,L,o]);let z=(0,Q.useCallback)((e,t)=>{let n=D.current;if(!tw(n,O.current)||F.current)return;let r=b.current,a=i.getState().setDraftComposerState(n,{document:e,mentions:aw(t)});if(!a)return;let o=ZC(a);return M.current={keyID:Se(n),revision:a.revision,fingerprint:ew(o)},j.current=a.revision,L(o,a.mentions),R(r,o),a},[i,L,R]),B=(0,Q.useCallback)((e,t,n,r,i,a)=>{I.current=Zu(I.current,{before:Vu(e,t,n),after:Vu(r,i,a)})},[]),V=(0,Q.useCallback)(()=>F.current?(F.current=void 0,h(`compose`),!0):!1,[]),H=(0,Q.useCallback)(e=>(V(),z({text:e,references:[]},[])),[z,V]),ee=(0,Q.useCallback)((e,t=[])=>{V();let n=_(e.text,e.references);return n?z(y(n,w.current),t):void 0},[z,V]),U=(0,Q.useCallback)((e,t,n=t,r)=>{let i=V(),a=QC(b.current),o=i?[]:C.current,s=ow(a,o,e,t,n),c=r?r(s.mentions,s.document):s.mentions;return z(s.document,c),s.removedReferences.length>0&&B(a,o,{start:s.selectionStart,end:s.selectionEnd},s.document,c,{start:s.selectionStart,end:s.selectionEnd}),{start:s.selectionStart,end:s.selectionEnd,requiresTextCorrection:s.requiresTextCorrection}},[z,V,B]),te=(0,Q.useCallback)((e,t)=>{let n=b.current,r=Math.max(0,Math.min(e.start,n.text.length)),i=Math.max(r,Math.min(e.end,n.text.length)),a=V(),o=fe(n,`${n.text.slice(0,r)}${e.text}${n.text.slice(i)}`,r+e.text.length),s=iw(a?[]:C.current,o.document,o.edit);return z(o.document,t?t(s,o.document):s),{start:o.selectionStart,end:o.selectionEnd}},[z,V]),W=(0,Q.useCallback)((e,t)=>{let n=b.current;return te({start:0,end:n.text.length,text:e},t)},[te]),ne=(0,Q.useCallback)((e,t,n,r)=>{let i=V(),a=N(b.current,e,t,n,r);return z(a.document,iw(i?[]:C.current,a.document,a.edit)),{start:a.caret,end:a.caret,caret:a.caret,document:a.document}},[z,V]),G=(0,Q.useCallback)(e=>{let t=QC(b.current),n=x(t,e);if(!n)return null;let r=V()?[]:C.current,i=iw(r,n.document,n.edit),a=S(n.document.text,n.caret),o=fe(n.document,a.text,a.caret),s=iw(i,o.document,o.edit);return z(o.document,s),B(t,r,{start:e.selectionStart,end:e.selectionEnd},o.document,s,{start:o.selectionStart,end:o.selectionEnd}),{start:o.selectionStart,end:o.selectionEnd}},[z,V,B]),re=(0,Q.useCallback)(e=>{if(F.current)return null;let t=e===`undo`?Uu(I.current,b.current):Hu(I.current,b.current);return!t||!z(t.snapshot.document,t.snapshot.mentions)?null:(I.current=t.history,t.snapshot.selection)},[z]),ie=(0,Q.useCallback)(e=>z(b.current,e),[z]),K=(0,Q.useCallback)(e=>{let t=F.current?{document:{text:e.text,references:[]},mentions:[]}:sw(b.current,C.current,e);`preview`in t&&(F.current=t.preview),h(`history-preview`),L(t.document,t.mentions),v(e=>e+1)},[L]),ae=(0,Q.useCallback)(()=>{let e=F.current;if(!e)return;F.current=void 0,h(`compose`);let t=cw(e);L(t.document,t.mentions),v(e=>e+1)},[L]),oe=(0,Q.useCallback)(()=>{let e=D.current;if(!tw(e,O.current))return null;let t=i.getState().getDraft(e);return{key:$C(e),keyID:Se(e),revision:t?.revision??0,document:QC(b.current),mentions:C.current.map(e=>({...e,range:{...e.range}})),epoch:A.current,runtime:i.getState().captureDraftRuntime()}},[i]),se=(0,Q.useCallback)(e=>{let t=uw(e,i.getState().getDraft(e.key)),n=ZC(i.getState().getDraft(e.key)),r=P(n.text,n.references).document,a=i.getState().setDraftComposerState(e.key,{...t,mentions:aw(t.mentions)});if(a){let e=ZC(a);R(r,e)}return a},[R,i]),ce=(0,Q.useCallback)(()=>b.current,[]);return(0,Q.useMemo)(()=>({document:l,mentions:d,confirmedFileMentions:d.filter(e=>e.kind===`file`||e.kind===`directory`),inputMode:m,hydration:s,persistence:c,textPresetEpoch:g,getDocument:ce,replacePlainDocument:H,replaceMaterializedDocument:ee,applyBrowserEdit:U,applyProgrammaticEdit:te,replaceProgrammaticText:W,insertReference:ne,deleteReference:G,restoreReferenceHistory:re,commitMentions:ie,enterHistoryPreview:K,exitHistoryPreview:ae,captureSubmission:oe,recoverSubmission:se}),[U,te,oe,ie,G,l,K,ae,ce,s,m,ne,d,c,se,ee,H,W,re,g])};function fw(e){let t=e.maxLines??8,n=e.lineHeight*t+e.paddingTotal,r=Math.max(e.scrollHeight,e.dictationHeight);return{height:Math.min(r,n),maxHeight:n,overflowY:r>n?`auto`:`hidden`}}var pw=`box-border w-full whitespace-pre-wrap break-words px-3 typography-markdown [font-family:inherit] [font-style:inherit] [font-weight:inherit] leading-[inherit] tracking-[inherit] md:typography-ui-label`,mw=_l(()=>Et(()=>import(`./ToolOutputDialog-CQs_7KYT.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52]))),hw=[],gw=[],_w=[],vw=[],yw=/^@[^\s]+$/,bw=({inputMode:e,message:t,showCommandAutocomplete:n,showSkillAutocomplete:r})=>e!==`shell`&&(n||r||/(^|\s)\/[A-Za-z0-9_-]*/.test(t)),xw=/^(https?:\/\/|mailto:)\S+$/i,Sw=560,Cw=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),ww=(e,t)=>{if(e===t)return``;let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;let r=e.length,i=t.length;for(;r>n&&i>n&&e[r-1]===t[i-1];)--r,--i;return t.slice(n,i)},Tw=e=>e.includes(`@`)?`paste`:`manual`,Ew=(e,t)=>{let n=t,r=t;for(;n>0&&/\s/.test(e[n-1]);)--n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;let i=n>0&&r<e.length?` `:``;return{text:`${e.slice(0,n)}${i}${e.slice(r)}`,caret:n+i.length}},Dw=(e,t)=>Ma(e,t).some(e=>e.role===`user`),Ow=(e,t)=>{let n=e.filter(e=>e.type===`text`&&!Lr(e)).map(e=>{let t=e;return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:``}).join(`
|
|
6525
|
+
`);if(d.trim()&&(t.push({start:s,end:s+d.length,style:`codeFence`,className:`${yS} text-[var(--syntax-foreground)]`,priority:bS}),!(d.length>ES)))try{let e=o.parser.parse(d);Pt(e,wS,(e,n,r)=>{let i=TS(r);i&&t.push({start:s+e,end:s+n,style:`codeFence`,className:i,priority:xS})})}catch{}}return t}var kS=[`CodeFiles`,`codefiles`,`application/vnd.code.tree`,`application/vnd.code.tree.explorer`,`text/uri-list`,`text/plain`],AS=e=>e.startsWith(`/`)||e.startsWith(`//`)||e.startsWith(`\\\\`)||/^[A-Za-z]:[\\/]/.test(e),jS=e=>{if(!AS(e)||/\s/.test(e))return!1;if(e.startsWith(`//`)||e.startsWith(`\\\\`)){let t=e.replace(/^[\\/]+/,``);return/[\\/]/.test(t)}if(/^[A-Za-z]:[\\/]/.test(e)){let t=e.slice(3);return t.includes(`\\`)||t.includes(`/`)||t.includes(`.`)}return e.replace(/^\/+/,``).includes(`/`)},MS=(e,{fromPlainText:t=!1}={})=>{let n=e.trim().replace(/^['"]+|['"]+$/g,``);return!n||n===`/>`||/[\r\n]/.test(n)?null:n.toLowerCase().startsWith(`file://`)||(t?jS(n):AS(n))?n:null},NS=(e,t,n=0)=>{if(!(n>6||e==null)){if(typeof e==`string`){t.add(e);return}if(Array.isArray(e)){for(let r of e)NS(r,t,n+1);return}if(typeof e==`object`)for(let r of Object.values(e))NS(r,t,n+1)}},PS=(e,{allowMultipleLines:t=!0,allowStructuredPayload:n=!0,fromPlainText:r=!1}={})=>{let i=new Set,a=e=>{let n=MS(e,{fromPlainText:r});if(n){i.add(n);return}if(t)for(let t of e.split(/\r?\n/)){let e=MS(t,{fromPlainText:r});e&&i.add(e)}};if(a(e),n)try{let t=JSON.parse(e),n=new Set;NS(t,n);for(let e of n)a(e)}catch{}return Array.from(i)},FS=e=>{if(!e||typeof e.getData!=`function`)return[];let t=new Set;for(let n of kS){let r=``;try{r=e.getData(n)}catch{continue}let i=n===`text/plain`?{allowMultipleLines:!1,allowStructuredPayload:!1,fromPlainText:!0}:n===`text/uri-list`?{allowStructuredPayload:!1}:void 0;for(let e of PS(r,i))t.add(e)}return Array.from(t)},IS=e=>{let t=e.trim();if(!t.toLowerCase().startsWith(`file://`))return t;try{let e=new URL(t),n=decodeURIComponent(e.pathname||``);return e.hostname&&e.hostname!==`localhost`&&(n=`//${e.hostname}${n}`),/^\/[A-Za-z]:\//.test(n)&&(n=n.slice(1)),n||t}catch{let e=t.replace(/^file:\/\//i,``);try{return decodeURIComponent(e)}catch{return e}}},LS=e=>AS(e);function RS(e,t){let n=(0,pd.c)(5),r=si(e,t),i=q(zS),a;n[0]===r?a=n[1]:(a=Yi(r),n[0]=r,n[1]=a);let o;return n[2]!==i||n[3]!==a?(o={goal:a,enabled:i},n[2]=i,n[3]=a,n[4]=o):o=n[4],o}function zS(e){return e.sessionGoalEnabled}function BS(e,t){let n=(0,pd.c)(4),[r,i]=Q.useState(null),a=t?.objectiveFile?`${e}:${t.id}:${t.updatedAt}`:``,o,s;return n[0]!==a||n[1]!==e?(o=()=>{if(!a){i(null);return}let t=!0;return Ar(e).then(e=>{t&&i(e)}),()=>{t=!1}},s=[a,e],n[0]=a,n[1]=e,n[2]=o,n[3]=s):(o=n[2],s=n[3]),Q.useEffect(o,s),t?t.objectiveFile?r:t.objective:null}var VS={active:`var(--status-info)`,paused:`var(--surface-muted-foreground)`,blocked:`var(--status-warning)`,budgetLimited:`var(--status-warning)`,complete:`var(--status-success)`},HS={active:`chat.goal.status.active`,paused:`chat.goal.status.paused`,blocked:`chat.goal.status.blocked`,budgetLimited:`chat.goal.status.budgetLimited`,complete:`chat.goal.status.complete`},US=Q.memo(({sessionId:e,directory:t,className:n})=>{let{t:r}=Yt(),i=q(e=>e.isMobile),{goal:a,enabled:o}=RS(e??``,t),s=BS(e??``,a),c=wi(e??``,t),l=ti(e,t),u=Q.useRef(null),[d,f]=Q.useState(!1),[p,m]=Q.useState(()=>Date.now());Q.useEffect(()=>{if(!a||a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`)return;let e=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(e)},[a?.id,a?.status]),Q.useEffect(()=>{if(!e||!a||a.status!==`active`)return;let n=l[0]?.id;if(!n)return;let r=`${e}:${a.id}:${n}`;u.current!==r&&(u.current=r,Tn(e,t))},[e,t,a,l]);let h=J(async n=>{if(!(!e||d)){f(!0);try{await bn(e,t,n)}catch(e){console.warn(`[session-goal] status change failed:`,e),ro.error(r(`chat.goal.toast.actionFailed`))}finally{f(!1)}}});if(!e||!o||!a)return null;let g=Math.max(0,(a.status===`complete`||a.status===`blocked`||a.status===`budgetLimited`?a.updatedAt:p)-(a.createdAt||p)),_=ea(g),v=a.tokenBudget?`${sn(a.tokensUsed)}/${sn(a.tokenBudget)}`:a.tokensUsed>0?sn(a.tokensUsed):null,y=a.status===`active`?{icon:`pause`,labelKey:`chat.goal.action.pause`,next:`paused`}:a.status===`paused`||a.status===`blocked`||a.status===`budgetLimited`?{icon:`play`,labelKey:`chat.goal.action.resume`,next:`active`}:null,b=i?`text-[11px] leading-none text-muted-foreground`:`typography-meta text-muted-foreground`,x=i?`text-xs leading-5 text-foreground`:`typography-ui-label leading-5 text-foreground`,S=i?`size-3`:`size-3.5`;return(0,$.jsxs)(`div`,{className:Y(`flex w-full min-w-0 items-center`,i?`gap-1 py-0.5`:`gap-1.5 py-0.5 md:gap-2`,n),"aria-label":r(`chat.goal.row.aria`),title:s??void 0,children:[(0,$.jsx)(Z,{name:`target`,className:Y(S,`flex-shrink-0`),style:{color:VS[a.status]},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 truncate`,x),children:a.note||s||``}),a.status===`active`&&(!c||c.type===`idle`)?(0,$.jsxs)(`span`,{className:Y(`flex flex-shrink-0 items-center gap-1`,b),children:[(0,$.jsx)(Z,{name:`loader-4`,className:Y(S,`animate-spin`),"aria-hidden":`true`}),r(`chat.goal.status.evaluating`)]}):(0,$.jsx)(`span`,{className:Y(`flex-shrink-0`,b),children:r(HS[a.status])}),(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,b,`text-muted-foreground/70`),children:_}),v?(0,$.jsx)(`span`,{className:Y(`flex-shrink-0 tabular-nums`,b,`text-muted-foreground/70`),children:v}):null,y?(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void h(y.next),disabled:d,className:Y(`inline-flex flex-shrink-0 cursor-pointer items-center bg-transparent text-muted-foreground transition-colors hover:text-foreground disabled:pointer-events-none disabled:opacity-50`,i?`h-7 gap-1.5 px-0 text-[11px]`:`h-7 gap-1 px-0.5`),"aria-label":r(y.labelKey),children:[(0,$.jsx)(Z,{name:y.icon,className:S,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:Y(`font-medium`,i?`leading-none`:`typography-ui-label`),children:r(y.labelKey)})]}):null]})});US.displayName=`SessionGoalRow`;var WS=Q.memo(({sessionId:e,directory:t,draftOpen:n=!1})=>{let{t:r}=Yt(),{goal:i,enabled:a}=RS(e??``,t),o=An(e=>e.armed),s=An(e=>e.setArmed),[c,l]=Q.useState(!1);if(ge()||!a||!e&&!n||!o&&!i)return null;let u=i?.status===`complete`?`text-[var(--status-success)]`:i?.status===`blocked`||i?.status===`budgetLimited`?`text-[var(--status-error)]`:o||i?.status===`active`||i?.status===`paused`?`text-[var(--status-info)]`:``,d=async()=>{if(o){s(!1);return}if(!(!e||c)){l(!0);try{await Ga(e,t)}catch(e){console.warn(`[session-goal] clear failed:`,e),ro.error(r(`chat.goal.toast.actionFailed`))}finally{l(!1)}}};return(0,$.jsxs)(`span`,{className:Y(`inline-flex h-7 items-center gap-1 rounded-full bg-[var(--surface-muted)] py-1 pl-2 pr-1 typography-ui-label`,u),children:[(0,$.jsx)(Z,{name:`target`,className:`h-4 w-4`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:r(`chat.goal.chip.label`)}),(0,$.jsx)(`button`,{type:`button`,className:`flex h-5 w-5 items-center justify-center rounded-full text-current hover:bg-[var(--interactive-hover)] disabled:opacity-50`,onClick:()=>void d(),disabled:c,"aria-label":r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),title:r(o?`chat.goal.button.disarmAria`:`chat.goal.action.clear`),children:(0,$.jsx)(Z,{name:`close`,className:`h-3 w-3`,"aria-hidden":`true`})})]})});WS.displayName=`SessionGoalButton`;var GS=Q.memo(e=>{let t=(0,pd.c)(11),{length:n}=e,{t:r}=Yt();if(!An(KS)||n===0)return null;let i=n>5e3?`text-[var(--status-error)]`:`text-muted-foreground/70`,a;t[0]===i?a=t[1]:(a=Y(`flex-shrink-0 self-center typography-micro tabular-nums`,i),t[0]=i,t[1]=a);let o;t[2]===r?o=t[3]:(o=r(`chat.goal.counter.aria`),t[2]=r,t[3]=o);let s;t[4]===r?s=t[5]:(s=r(`chat.goal.counter.aria`),t[4]=r,t[5]=s);let c;return t[6]!==n||t[7]!==a||t[8]!==o||t[9]!==s?(c=(0,$.jsxs)(`span`,{className:a,"aria-label":o,title:s,children:[n,`/`,pr]}),t[6]=n,t[7]=a,t[8]=o,t[9]=s,t[10]=c):c=t[10],c});GS.displayName=`SessionGoalObjectiveCounter`;function KS(e){return e.armed}var qS=new Set([`new`,`fork`,`compact`,`undo`,`redo`,`timeline`,`model`,`summary`,`workspace-review`,`handoff-review`,`goal`,`craft-goal`,`catch-up`,`debug`,`weigh`,`explore`]),JS=new Set([`new`,`compact`,`fork`,`undo`,`redo`]),YS=/^\/\u2003?([^\s]+)/i,XS=/^\/\u2003?goal\b/i,ZS=(e,t)=>{if(t!==`normal`)return null;let n=e.trimStart().match(YS)?.[1]?.toLowerCase();return n&&qS.has(n)?n:null},QS=(e,t)=>ZS(e,t)===`goal`?e.trimStart().replace(XS,``).trim():null,$S=(e,t)=>ZS(e,t)!==null,eC=(e,t)=>{let n=ZS(e,t);return n!==null&&JS.has(n)},tC=({currentSessionId:e,messageRef:t,replacePlainDocument:n})=>{let r=e;return t.current=``,n(``),r},nC=async({command:e,consumeCommandText:t,forkSession:n,waitForConnection:r,getDirectoryForSession:i,summarizeSession:a,onCompactError:o,onForkError:s})=>{if(t(),e===`fork`){try{await n()}catch(e){s(e)}return}try{await r();let e=i();if(!e){o();return}await a(e)}catch{o()}},rC=e=>!e.queuedOnly&&!e.resourcePolicy&&e.rootAttachmentCount>0,iC=e=>e.surfaceKind===`primary`&&!!e.currentSessionId&&!e.queuedOnly&&!e.resourcePolicy&&e.inputMode!==`shell`&&!e.localCommand,aC=e=>e.surfaceKind!==`primary`||!e.stagedSessionId||!e.stagedMessageId||e.stagedMessageId!==e.blurredMessageId||e.submitInFlight||e.focusHeld||e.overlayOpen||e.focusInsideComposer?{action:`keep`}:{action:`disarm`,sessionId:e.stagedSessionId},oC=e=>({state:`bound`,transportIdentity:e.transportIdentity,directory:e.directory,sessionID:e.sessionID,deliveryTarget:{kind:`primary`},runtimeGeneration:e.runtimeGeneration}),sC=(e,t)=>{let n=k.getState();return n.bindLegacyQueue(E(e.sessionID),e),n.stageAdmission(e,{requestID:t.requestID,queueItemID:t.queueItemID,operationID:t.operationID,messageID:t.messageID,content:t.content,createdAt:t.createdAt,attachmentCount:t.attachments.length,...t.composerDocument?{composerDocument:t.composerDocument}:{},...t.composerMentions?{composerMentions:t.composerMentions}:{}}),n.confirmAdmission(e,{requestID:t.requestID,sendConfig:t.sendConfig,attachments:t.attachments}).ok},cC=async e=>{let t=$i.getState().takeEstablishingPending(e.draftID);if(t.length===0)return{drained:0,failed:0};let n=oC(e),r=0,i=0;for(let a of t)try{if(e.admitServer&&(await e.admitServer(a)).status===`committed`){r+=1;continue}sC(n,a)?r+=1:i+=1}catch{try{sC(n,a)?r+=1:i+=1}catch{i+=1}}return{drained:r,failed:i}},lC=(e,t)=>Promise.resolve().then(()=>e()).catch(()=>{t()}),uC=e=>e===`allow`||e===`ask`||e===`deny`,dC=e=>{if(uC(e))return[{permission:`*`,pattern:`*`,action:e}];if(Array.isArray(e))return e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=e;return typeof t.permission==`string`&&typeof t.pattern==`string`&&uC(t.action)?[{permission:t.permission,pattern:t.pattern,action:t.action}]:[]});if(!e||typeof e!=`object`)return[];let t=[];for(let[n,r]of Object.entries(e))if(n!==`__originalKeys`){if(uC(r)){t.push({permission:n,pattern:`*`,action:r});continue}if(!(!r||typeof r!=`object`||Array.isArray(r)))for(let[e,i]of Object.entries(r))uC(i)&&t.push({permission:n,pattern:e,action:i})}return t},fC=e=>{let t=dC(e);for(let e=t.length-1;e>=0;--e){let n=t[e];if(n.permission===`*`&&n.pattern===`*`)return n.action===`ask`;if(n.action===`ask`)return!0}return!0},pC=(e,t)=>{let n=t?.trim();if(!n)return e.length===0||e.some(e=>fC(e.permission));let r=e.find(e=>e?.name===n);return!r||fC(r.permission)},mC=e=>{let{permissionScopeSessionId:t,newSessionDraftOpen:n,draftPermissionAutoAcceptEnabled:r,permissionAutoAcceptEnabled:i,setDraftPermissionAutoAcceptEnabled:a,setSessionAutoAccept:o,onOpenSessionFirst:s,onToggleFailed:c}=e;if(!t){if(!n){s();return}a(!r);return}o(t,!i).catch(c)},hC=null,gC=new Set,_C=()=>{for(let e of gC)e()},vC=e=>e===`chat`||e===`assistant`,yC=()=>hC,bC=e=>{hC!==e&&(hC=e,_C())},xC=e=>{hC&&(e&&hC.surfaceID!==e||(hC=null,_C()))},SC=(e,t)=>{if(e.transportIdentity!==t.transportIdentity||e.runtimeGeneration!==t.runtimeGeneration)throw Error(`chat-input-delivery-runtime-stale`)},CC=e=>{let t={...e.options?.delivery===`steer`?{delivery:`steer`}:{},...e.options?.commitStagedMessageEdit===void 0?{}:{commitStagedMessageEdit:e.options.commitStagedMessageEdit},...e.options?.messageID?{messageID:e.options.messageID}:{},...e.options?.ticket?{ticket:e.options.ticket}:{}},n=e.options?.sessionId??e.sessionID??void 0;if(!n)return t;let r=e.options?.directoryHint===void 0?e.directory||null:e.options.directoryHint;return{...t,sessionId:n,directoryHint:r}},wC=(e,t,n={})=>({operation:t,surfaceID:e.surfaceID,transportIdentity:e.transportIdentity,runtimeGeneration:e.runtimeGeneration,sessionID:e.sessionID,directory:e.directory??``,draftKey:e.draftKey,deliveryTarget:e.deliveryTarget,...n}),TC=e=>{if(!e.active||!e.draftKey||!e.directory)return null;let t=e.activity?.phase??`idle`,n=e.activity?.canAbort??(t===`busy`||t===`retry`);return{send:async t=>{let n=wC(e,`send`,t);return await e.selection.flush(),e.kind===`secondary`&&await e.shortcuts.submit(),e.backend.send(n)},sendQueued:async(t,n={})=>{let{manual:r,...i}=n,a=wC(e,`send`,i),o=oy(e);if(await e.selection.flush(),!o)throw Error(`chat-input-queue-scope-incomplete`);return e.backend.sendQueued({...a,queueItemID:t,manual:r,queueScope:o})},create:async()=>{let t=wC(e,`create`);return await e.selection.flush(),e.backend.create(t)},compact:async t=>{let n=wC(e,`compact`,t);return await e.selection.flush(),e.backend.compact(n)},abort:async()=>{let t=wC(e,`abort`);return await e.selection.flush(),e.backend.abort(t)},queueScope:oy(e),canAbort:n,canQueue:t===`busy`||t===`retry`,allowsCommand:t=>$v(e,{name:t,source:`openchamber`}),shortcut:async(t,n=1)=>{if(e.kind===`secondary`){t===`cycle`?await e.shortcuts.cycle(n):t===`new`?await e.shortcuts.new():t===`abort`?await e.shortcuts.abort():await e.shortcuts.submit();return}if(t===`abort`){let t=wC(e,`abort`);await e.selection.flush(),await e.backend.abort(t);return}if(t===`new`){let t=wC(e,`create`);await e.selection.flush(),await e.backend.create(t);return}t!==`submit`&&await e.shortcuts?.cycle(n)},resources:e.resources??null}},EC=(e,t,n)=>{let r=e.agent;r&&r!==t.currentAgentName&&t.setAgent(r),e.providerID&&t.setProvider(e.providerID),e.modelID&&t.setModel(e.modelID),t.setCurrentVariant(e.variant);let i=r??t.currentAgentName;i&&e.providerID&&e.modelID&&t.saveAgentModelSelection(i,e.providerID,e.modelID,e.variant);let a=n?.sessionId,o=n?.memory;!a||!o||!e.providerID||!e.modelID||(o.saveSessionModelSelection(a,e.providerID,e.modelID),i&&o.saveSessionAgentSelection&&o.saveSessionAgentSelection(a,i),i&&(o.saveAgentModelForSession(a,i,e.providerID,e.modelID),o.saveAgentModelVariantForSession(a,i,e.providerID,e.modelID,e.variant)))},DC=(e,t,n)=>{let r=e.providers.find(e=>e.id===t);return r?(Array.isArray(r.models)?r.models:[]).some(e=>e.id===n):!1},OC=(e,t)=>e.agents.some(e=>e.name===t),kC=(e,t,n,r)=>{if(!r)return!0;let i=e.providers.find(e=>e.id===t)?.models?.find(e=>e.id===n)?.variants;return i?Array.isArray(i)?i.includes(r):typeof i==`object`&&Object.prototype.hasOwnProperty.call(i,r):!1},AC=e=>{let{catalog:t,providerID:n,modelID:r,historyVariant:i,memoryVariant:a}=e;if(i)return kC(t,n,r,i)?i:void 0;if(a&&kC(t,n,r,a))return a},jC=e=>{let{sessionId:t,choice:n,catalog:r,memory:i,fallbackAgentName:a,source:o}=e;if(!n.providerID||!n.modelID||!DC(r,n.providerID,n.modelID))return null;let s=n.agent&&OC(r,n.agent)?n.agent:i?.getSessionAgentSelection?.(t)&&OC(r,i.getSessionAgentSelection(t))?i.getSessionAgentSelection(t):a&&OC(r,a)?a:void 0,c=s?i?.getAgentModelVariantForSession?.(t,s,n.providerID,n.modelID):void 0,l=AC({catalog:r,providerID:n.providerID,modelID:n.modelID,historyVariant:n.variant,memoryVariant:c});return{agent:s,providerID:n.providerID,modelID:n.modelID,variant:l,source:o,messageId:n.id}},MC=e=>{let{sessionId:t,latestUserChoice:n,latestExecution:r,catalog:i,memory:a,sessionEntity:o,fallbackAgentName:s,transcriptReady:c=!0}=e;if(c&&r){let e=jC({sessionId:t,choice:r,catalog:i,memory:a,fallbackAgentName:s,source:`execution`});if(e)return e}if(c&&n){let e=jC({sessionId:t,choice:n,catalog:i,memory:a,fallbackAgentName:s,source:`history`});if(e)return e}if(c&&a){let e=a.getSessionAgentSelection?.(t)??null,n=e&&OC(i,e)?e:s&&OC(i,s)?s:void 0;if(n){let e=a.getAgentModelForSession?.(t,n);if(e&&DC(i,e.providerId,e.modelId)){let r=a.getAgentModelVariantForSession?.(t,n,e.providerId,e.modelId),o=r&&kC(i,e.providerId,e.modelId,r)?r:void 0;return{agent:n,providerID:e.providerId,modelID:e.modelId,variant:o,source:`session-memory`}}}let r=a.getSessionModelSelection?.(t);if(r&&DC(i,r.providerId,r.modelId)){let e=n?a.getAgentModelVariantForSession?.(t,n,r.providerId,r.modelId):void 0,o=e&&kC(i,r.providerId,r.modelId,e)?e:void 0;return{agent:n,providerID:r.providerId,modelID:r.modelId,variant:o,source:`session-memory`}}}let l=o?.model;if(l&&DC(i,l.providerID,l.id)){let e=a?.getSessionAgentSelection?.(t)??null,n=(o?.agent&&OC(i,o.agent)?o.agent:void 0)??(e&&OC(i,e)?e:s&&OC(i,s)?s:void 0),r=l.variant,c=r&&kC(i,l.providerID,l.id,r)?r:void 0;return{agent:n,providerID:l.providerID,modelID:l.id,variant:c,source:`session-entity`}}return null},NC=(e,t,n)=>{let r=e.agent;r&&r!==t.currentAgentName&&t.setAgent(r),e.providerID&&t.setProvider(e.providerID),e.modelID&&t.setModel(e.modelID),t.setCurrentVariant(e.variant);let{sessionId:i,memory:a}=n;a.saveSessionModelSelection(i,e.providerID,e.modelID);let o=r??t.currentAgentName;o&&a.saveSessionAgentSelection&&a.saveSessionAgentSelection(i,o),o&&(a.saveAgentModelForSession(i,o,e.providerID,e.modelID),a.saveAgentModelVariantForSession(i,o,e.providerID,e.modelID,e.variant))},PC=(e,t)=>{if((t?.expectedConfigKey===void 0||t.activeDirectoryKey===t.expectedConfigKey)&&!(!e.currentProviderId||!e.currentModelId))return{providerID:e.currentProviderId,modelID:e.currentModelId,agent:e.currentAgentName,variant:e.currentVariant}},FC=e=>e.editRevision<=0?!1:e.pinnedHistoryMessageId==null||e.latestHistoryMessageId==null||e.latestHistoryMessageId===e.pinnedHistoryMessageId,IC=e=>{if(e.captured?.providerID&&e.captured?.modelID)return e.captured;let t=e.surfaceSelection;if(!(!t?.providerID||!t?.modelID))return{providerID:t.providerID,modelID:t.modelID,...t.agent?{agent:t.agent}:{},...t.variant?{variant:t.variant}:{}}},LC=e=>typeof e==`string`&&e.trim().length>0?e:void 0,RC=e=>LC(e.agent)??LC(e.mode),zC=e=>LC(e.model?.variant)??LC(e.variant),BC=e=>{let t=LC(e.model?.providerID),n=LC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},VC=e=>{let t=LC(e.providerID)??LC(e.model?.providerID),n=LC(e.modelID)??LC(e.model?.modelID);return!t||!n?null:{providerID:t,modelID:n}},HC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role!==`user`)continue;let r=BC(n);return{id:typeof n.id==`string`?n.id:void 0,agent:RC(n),providerID:r?.providerID,modelID:r?.modelID,variant:zC(n)}}return null},UC=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(n.role===`user`){if(BC(n))return null;continue}if(n.role!==`assistant`)continue;let r=VC(n);if(r)return{id:typeof n.id==`string`?n.id:void 0,agent:RC(n),providerID:r.providerID,modelID:r.modelID,variant:zC(n)}}return null},WC=500,GC=e=>Array.from(e).length,KC=e=>{let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(36)},qC=e=>GC(e)>=WC,JC=e=>{let t=P(e.text,e.references).document.references,n=t.reduce((e,t)=>{let n=t.kind===`paste`?t.index:0;return typeof n==`number`&&Number.isSafeInteger(n)&&n>=1?Math.max(e,n):e},0);if(n<2**53-1)return n+1;let r=new Set(t.flatMap(e=>e.kind===`paste`&&typeof e.index==`number`&&Number.isSafeInteger(e.index)&&e.index>=1?[e.index]:[]));for(let e=1;e<=t.length+1;e+=1)if(!r.has(e))return e;return 1},YC=(e,t)=>{let n=t??e;return typeof n!=`string`||!qC(n)?!1:we(typeof e==`string`?{text:``,references:[]}:e,n)},XC=(e,t,n,r,i=1)=>{let a=GC(e),o=new Set(n.map(e=>e.token));for(let n=i;n<2**53-1;n+=1){let i=`[${r({index:n,count:a})}]`;if(!(t.includes(i)||o.has(i)))return{id:`pasted-text-${n}-${KC(e)}`,token:i,text:e,characterCount:a,index:n}}throw Error(`Unable to create a unique pasted text reference`)},ZC=e=>({text:e?.text??``,references:e?.composerReferences??[]}),QC=e=>({text:e.text,references:e.references.map(e=>({...e}))}),$C=e=>({transportIdentity:e.transportIdentity,owner:{...e.owner}}),ew=e=>JSON.stringify([e.text,e.references]),tw=(e,t)=>e!==null&&t!==null&&Se(e)===t,nw=(e,t,n)=>{let r=e?$C(e):null,i=r?n(r):void 0;return{document:y(ZC(i),t),mentions:i?.mentions??[],revision:i?.revision??0,key:r,keyID:r?Se(r):null}},rw=(e,t,n,r)=>{if(!t||Se(t.key)!==r.keyID||t.revision<r.appliedRevision)return`ignore`;let i=ew(ZC(t));return n?.keyID===r.keyID&&n.revision===t.revision&&n.fingerprint===i?`local-echo`:t.revision===r.appliedRevision?`ignore`:i===ew(e)?`same-document-metadata`:`external-document`},iw=(e,t,n)=>{let r=n.newEnd-n.oldEnd;return e.flatMap(e=>{if(e.range.start<n.oldEnd&&e.range.end>n.oldStart)return[];let i=e.range.start>=n.oldEnd?{start:e.range.start+r,end:e.range.end+r}:e.range;return t.text.slice(i.start,i.end)===`@${e.value}`?[{...e,range:i}]:[]})},aw=e=>e.map((e,t)=>({mention:e,index:t})).sort((e,t)=>e.mention.range.start-t.mention.range.start||e.mention.range.end-t.mention.range.end||e.index-t.index).map(({mention:e})=>e),ow=(e,t,n,r,i=r)=>{let a=fe(e,n,r,i);return{document:a.document,mentions:iw(t,a.document,a.edit),requiresTextCorrection:a.requiresTextCorrection,selectionStart:a.selectionStart,selectionEnd:a.selectionEnd,removedReferences:a.removedReferences}},sw=(e,t,n)=>({preview:{real:QC(e),realMentions:[...t]},document:{text:n.text,references:[]},mentions:[]}),cw=e=>({document:e.real,mentions:e.realMentions}),lw=(e,t,n,r)=>{let i=[...e,...t.map(e=>({...e,range:{start:e.range.start+r,end:e.range.end+r}}))],a=new Set;return i.filter(e=>{let t=`${e.kind}:${e.value}:${e.range.start}:${e.range.end}`;return a.has(t)||n.text.slice(e.range.start,e.range.end)!==`@${e.value}`?!1:(a.add(t),!0)})},uw=(e,t)=>{let n=ZC(t),r=v(e.document,n),i=e.document.text===n.text&&JSON.stringify(e.document.references)===JSON.stringify(n.references)?0:e.document.text.length+2;return{document:r,mentions:lw(e.mentions,t?.mentions??[],r,i)}},dw=({draftKey:e,sessionTitles:t,persistenceEnabled:n,onResourcesChanged:r,store:i=un})=>{let a=e?Se(e):null,o=(0,Q.useSyncExternalStore)(i.subscribe,()=>a?i.getState().drafts[a]:void 0,()=>void 0),s=(0,Q.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftHydration[a]??`idle`:`idle`,()=>`idle`),c=(0,Q.useSyncExternalStore)(i.subscribe,()=>a?i.getState().draftPersistence[a]:void 0,()=>void 0),[l,u]=(0,Q.useState)(()=>nw(e,t,i.getState().getDraft).document),[d,f]=(0,Q.useState)(()=>nw(e,t,i.getState().getDraft).mentions),[m,h]=(0,Q.useState)(`compose`),[g,v]=(0,Q.useState)(0),b=(0,Q.useRef)(l),C=(0,Q.useRef)(d),w=(0,Q.useRef)(t),T=(0,Q.useRef)(r),E=(0,Q.useRef)(e),D=(0,Q.useRef)(e?$C(e):null),O=(0,Q.useRef)(a),k=(0,Q.useRef)(a),A=(0,Q.useRef)(0),j=(0,Q.useRef)(o?.revision??0),M=(0,Q.useRef)(void 0),F=(0,Q.useRef)(void 0),I=(0,Q.useRef)(Ku());b.current=l,C.current=d,w.current=t,T.current=r,E.current=e,O.current=a;let L=(0,Q.useCallback)((e,t)=>{b.current=e,C.current=t,u(e),f(t)},[]),R=(0,Q.useCallback)((e,t)=>{let n=p(e,t);T.current?.(n)},[]);(0,Q.useEffect)(()=>{i.getState().setDraftPersistenceEnabled(n)},[n,i]),(0,Q.useLayoutEffect)(()=>{A.current+=1;let e=A.current;k.current=a;let t=nw(E.current,w.current,i.getState().getDraft),n=t.key;if(D.current=t.key,M.current=void 0,F.current=void 0,I.current=Ku(),h(`compose`),j.current=t.revision,L(t.document,t.mentions),v(e=>e+1),n?.owner.kind===`draft`){let r=t.revision;i.getState().claimLegacyNewDraft(n).then(t=>{let o=i.getState().getDraft(n);!t||!tw(D.current,a)||k.current!==a||O.current!==a||A.current!==e||j.current!==r||o?.revision!==t.revision||(j.current=t.revision,L(y(ZC(t),w.current),t.mentions))})}},[a,L,i]),(0,Q.useEffect)(()=>{if(!a||k.current!==a||F.current)return;let e=rw(b.current,o,M.current,{keyID:a,epoch:A.current,appliedRevision:j.current});if(e!==`ignore`){if(o&&(j.current=o.revision),e===`local-echo`||e===`same-document-metadata`){o&&f(o.mentions);return}e===`external-document`&&o&&(M.current=void 0,L(y(ZC(o),w.current),o.mentions),h(`compose`),v(e=>e+1))}},[a,L,o]);let z=(0,Q.useCallback)((e,t)=>{let n=D.current;if(!tw(n,O.current)||F.current)return;let r=b.current,a=i.getState().setDraftComposerState(n,{document:e,mentions:aw(t)});if(!a)return;let o=ZC(a);return M.current={keyID:Se(n),revision:a.revision,fingerprint:ew(o)},j.current=a.revision,L(o,a.mentions),R(r,o),a},[i,L,R]),B=(0,Q.useCallback)((e,t,n,r,i,a)=>{I.current=Zu(I.current,{before:Vu(e,t,n),after:Vu(r,i,a)})},[]),V=(0,Q.useCallback)(()=>F.current?(F.current=void 0,h(`compose`),!0):!1,[]),H=(0,Q.useCallback)(e=>(V(),z({text:e,references:[]},[])),[z,V]),ee=(0,Q.useCallback)((e,t=[])=>{V();let n=_(e.text,e.references);return n?z(y(n,w.current),t):void 0},[z,V]),U=(0,Q.useCallback)((e,t,n=t,r)=>{let i=V(),a=QC(b.current),o=i?[]:C.current,s=ow(a,o,e,t,n),c=r?r(s.mentions,s.document):s.mentions;return z(s.document,c),s.removedReferences.length>0&&B(a,o,{start:s.selectionStart,end:s.selectionEnd},s.document,c,{start:s.selectionStart,end:s.selectionEnd}),{start:s.selectionStart,end:s.selectionEnd,requiresTextCorrection:s.requiresTextCorrection}},[z,V,B]),te=(0,Q.useCallback)((e,t)=>{let n=b.current,r=Math.max(0,Math.min(e.start,n.text.length)),i=Math.max(r,Math.min(e.end,n.text.length)),a=V(),o=fe(n,`${n.text.slice(0,r)}${e.text}${n.text.slice(i)}`,r+e.text.length),s=iw(a?[]:C.current,o.document,o.edit);return z(o.document,t?t(s,o.document):s),{start:o.selectionStart,end:o.selectionEnd}},[z,V]),W=(0,Q.useCallback)((e,t)=>{let n=b.current;return te({start:0,end:n.text.length,text:e},t)},[te]),ne=(0,Q.useCallback)((e,t,n,r)=>{let i=V(),a=N(b.current,e,t,n,r);return z(a.document,iw(i?[]:C.current,a.document,a.edit)),{start:a.caret,end:a.caret,caret:a.caret,document:a.document}},[z,V]),G=(0,Q.useCallback)(e=>{let t=QC(b.current),n=x(t,e);if(!n)return null;let r=V()?[]:C.current,i=iw(r,n.document,n.edit),a=S(n.document.text,n.caret),o=fe(n.document,a.text,a.caret),s=iw(i,o.document,o.edit);return z(o.document,s),B(t,r,{start:e.selectionStart,end:e.selectionEnd},o.document,s,{start:o.selectionStart,end:o.selectionEnd}),{start:o.selectionStart,end:o.selectionEnd}},[z,V,B]),re=(0,Q.useCallback)(e=>{if(F.current)return null;let t=e===`undo`?Uu(I.current,b.current):Hu(I.current,b.current);return!t||!z(t.snapshot.document,t.snapshot.mentions)?null:(I.current=t.history,t.snapshot.selection)},[z]),ie=(0,Q.useCallback)(e=>z(b.current,e),[z]),K=(0,Q.useCallback)(e=>{let t=F.current?{document:{text:e.text,references:[]},mentions:[]}:sw(b.current,C.current,e);`preview`in t&&(F.current=t.preview),h(`history-preview`),L(t.document,t.mentions),v(e=>e+1)},[L]),ae=(0,Q.useCallback)(()=>{let e=F.current;if(!e)return;F.current=void 0,h(`compose`);let t=cw(e);L(t.document,t.mentions),v(e=>e+1)},[L]),oe=(0,Q.useCallback)(()=>{let e=D.current;if(!tw(e,O.current))return null;let t=i.getState().getDraft(e);return{key:$C(e),keyID:Se(e),revision:t?.revision??0,document:QC(b.current),mentions:C.current.map(e=>({...e,range:{...e.range}})),epoch:A.current,runtime:i.getState().captureDraftRuntime()}},[i]),se=(0,Q.useCallback)(e=>{let t=uw(e,i.getState().getDraft(e.key)),n=ZC(i.getState().getDraft(e.key)),r=P(n.text,n.references).document,a=i.getState().setDraftComposerState(e.key,{...t,mentions:aw(t.mentions)});if(a){let e=ZC(a);R(r,e)}return a},[R,i]),ce=(0,Q.useCallback)(()=>b.current,[]);return(0,Q.useMemo)(()=>({document:l,mentions:d,confirmedFileMentions:d.filter(e=>e.kind===`file`||e.kind===`directory`),inputMode:m,hydration:s,persistence:c,textPresetEpoch:g,getDocument:ce,replacePlainDocument:H,replaceMaterializedDocument:ee,applyBrowserEdit:U,applyProgrammaticEdit:te,replaceProgrammaticText:W,insertReference:ne,deleteReference:G,restoreReferenceHistory:re,commitMentions:ie,enterHistoryPreview:K,exitHistoryPreview:ae,captureSubmission:oe,recoverSubmission:se}),[U,te,oe,ie,G,l,K,ae,ce,s,m,ne,d,c,se,ee,H,W,re,g])};function fw(e){let t=e.maxLines??8,n=e.lineHeight*t+e.paddingTotal,r=Math.max(e.scrollHeight,e.dictationHeight);return{height:Math.min(r,n),maxHeight:n,overflowY:r>n?`auto`:`hidden`}}var pw=`box-border w-full whitespace-pre-wrap break-words px-3 typography-markdown [font-family:inherit] [font-style:inherit] [font-weight:inherit] leading-[inherit] tracking-[inherit] md:typography-ui-label`,mw=_l(()=>Et(()=>import(`./ToolOutputDialog-nhZwyPOH.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52]))),hw=[],gw=[],_w=[],vw=[],yw=/^@[^\s]+$/,bw=({inputMode:e,message:t,showCommandAutocomplete:n,showSkillAutocomplete:r})=>e!==`shell`&&(n||r||/(^|\s)\/[A-Za-z0-9_-]*/.test(t)),xw=/^(https?:\/\/|mailto:)\S+$/i,Sw=560,Cw=(e,t)=>e.name===t?e:new File([e],t,{type:e.type,lastModified:e.lastModified}),ww=(e,t)=>{if(e===t)return``;let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;let r=e.length,i=t.length;for(;r>n&&i>n&&e[r-1]===t[i-1];)--r,--i;return t.slice(n,i)},Tw=e=>e.includes(`@`)?`paste`:`manual`,Ew=(e,t)=>{let n=t,r=t;for(;n>0&&/\s/.test(e[n-1]);)--n;for(;r<e.length&&/\s/.test(e[r]);)r+=1;let i=n>0&&r<e.length?` `:``;return{text:`${e.slice(0,n)}${i}${e.slice(r)}`,caret:n+i.length}},Dw=(e,t)=>Ma(e,t).some(e=>e.role===`user`),Ow=(e,t)=>{let n=e.filter(e=>e.type===`text`&&!Lr(e)).map(e=>{let t=e;return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:``}).join(`
|
|
6526
6526
|
`).replace(/\s+/g,` `).trim();if(n)return n;let r=e.find(e=>e.type===`file`);return r?.filename?`[${r.filename}]`:t},kw=`file://`,Aw=e=>{let t=e.replace(/\\/g,`/`);return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split(`/`).map((e,t)=>t===1&&/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`)},jw=e=>{let t=e.replace(/\\/g,`/`).trim();return t.toLowerCase().startsWith(kw)?t:`file://${Aw(t)}`},Mw=e=>{if(!e)return[];let t=[...FS(e).map(IS),...Array.from(e.files||[]).map(e=>C(e)).filter(e=>!!e)];return Array.from(new Set(t.filter(LS)))},Nw=e=>{if(typeof e!=`string`)return null;let t=e.trim();if(!t)return null;let n=t.replace(/\\/g,`/`);return n===`/`?`/`:n.length>1?n.replace(/\/+$/,``):n},Pw=e=>Xt(e.path),Fw=(e,t)=>{if(!t)return e;let n=e.indexOf(t);return n===-1?e:(0,$.jsxs)($.Fragment,{children:[e.slice(0,n),(0,$.jsx)(`span`,{className:`font-medium`,children:t}),e.slice(n+t.length)]})},Iw=Q.memo(Ey),Lw=Q.memo(Em),Rw=Q.memo(Lb),zw=Q.memo(Bb),Bw=Q.memo(nb),Vw=Q.memo(({sessionId:e,directory:t})=>{let{t:n}=Yt(),r=q(e=>e.isMobile),i=X(e=>e.revertToMessage),a=X(e=>e.forkFromMessage),o=X(e=>e.handleSlashRedo),[s,c]=Q.useState(null),[l,u]=Q.useState(null),[d,f]=Q.useState(!0),p=Q.useRef(hS),m=la(),h=t||m,g=Br(h),_=xa(e??``,h,g),v=Zr(e=>e.session,h),y=Q.useMemo(()=>{let t=_.messageOrder.map(e=>_.messagesByID[e]).filter(e=>!!e),n=vS({session:v,messages:t,partsByMessageID:_.partsByMessageID},e,p.current);return p.current=n,n},[e,v,_]),b=y.revertMessageID,x=Q.useMemo(()=>y.records.map(e=>e.message),[y]),S=n(`chat.revertPopover.noTextContent`),C=Q.useMemo(()=>b?y.records.map(e=>({id:e.message.id,text:Ow(e.parts,S)})):[],[S,b,y]),w=C[0]?.id;Q.useEffect(()=>{f(!0)},[b,w]);let T=Q.useCallback(async t=>{if(!(!e||s)){c(t);try{let n=x.find(e=>e.id>t);n?await i(e,n.id,{skipRedoPush:!0}):await o(e,{fullUnrevert:!0})}finally{c(null)}}},[o,i,s,e,x]),E=Q.useCallback(async t=>{if(!(!e||l)){u(t);try{await a(e,t)}finally{u(null)}}},[a,l,e]);return!e||C.length===0?null:(0,$.jsx)(`div`,{className:Y(`w-full px-1`,r?`pb-1 text-xs`:`pb-2`),children:(0,$.jsxs)(`div`,{className:Y(`border border-border/60 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm dark:shadow-none overflow-hidden`,r?`rounded-lg`:`rounded-xl`),children:[(0,$.jsxs)(`button`,{type:`button`,className:Y(`flex w-full items-center text-left hover:bg-[var(--interactive-hover)] transition-colors`,r?`gap-1.5 px-2 py-1`:`gap-2 px-3 py-2`),onClick:()=>f(e=>!e),"aria-expanded":!d,children:[(0,$.jsxs)(`span`,{className:`typography-ui-label font-medium text-foreground flex-shrink-0`,children:[n(`chat.revertPopover.title`),` messages `,C.length]}),(0,$.jsx)(Z,{name:`arrow-down-s`,className:Y(`ml-auto text-muted-foreground transition-transform`,r?`size-3.5`:`size-4`,!d&&`rotate-180`),"aria-hidden":`true`})]}),!d&&(0,$.jsx)(`div`,{className:Y(`flex flex-col overflow-y-auto`,r?`max-h-[8rem] gap-1 px-2 pb-1.5`:`max-h-[10.5rem] gap-1.5 px-3 pb-3`),children:C.map(e=>(0,$.jsxs)(`div`,{className:Y(`flex min-w-0 items-center`,r?`gap-1.5`:`gap-2 py-1`),children:[(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate typography-ui-label text-foreground`,children:e.text}),(0,$.jsxs)(Qt,{type:`button`,variant:`secondary`,size:`xs`,disabled:!!(s||l),onClick:()=>{E(e.id)},children:[l===e.id?(0,$.jsx)(Z,{name:`loader-4`,className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):(0,$.jsx)(Z,{name:`git-branch`,className:`h-3 w-3`,"aria-hidden":`true`}),n(`chat.revertPopover.fork`)]}),(0,$.jsxs)(Qt,{type:`button`,variant:`secondary`,size:`xs`,disabled:!!(s||l),onClick:()=>{T(e.id)},children:[s===e.id?(0,$.jsx)(Z,{name:`loader-4`,className:`h-3 w-3 animate-spin`,"aria-hidden":`true`}):(0,$.jsx)(Z,{name:`arrow-go-forward`,className:`h-3 w-3`,"aria-hidden":`true`}),n(`chat.revertPopover.restore`)]})]},e.id))})]})})});Vw.displayName=`RevertedMessageDock`;var Hw=Q.memo(function(e){let t=(0,pd.c)(41),{t:n}=Yt(),{isVSCode:r,footerIconButtonClass:i,iconSizeClass:a,handlePickLocalFiles:o,openIssuePicker:s,openPrPicker:c,onOpenSettings:l,withTooltip:u}=e,d=u!==void 0&&u,f=!!e.onOpenMobileSheet,p;t[0]===n?p=t[1]:(p=n(`chat.chatInput.actions.attachFiles`),t[0]=n,t[1]=p);let m=p,h=o,g;t[2]!==h||t[3]!==e?(g=()=>e.onOpenAndroidPickSheet?e.onOpenAndroidPickSheet():h(),t[2]=h,t[3]=e,t[4]=g):g=t[4];let _=f?Qw:void 0,v=f?$w:void 0,y;t[5]===a?y=t[6]:(y=Y(a,`text-current`),t[5]=a,t[6]=y);let b;t[7]===y?b=t[8]:(b=(0,$.jsx)(Z,{name:`attachment-2`,className:y}),t[7]=y,t[8]=b);let x;t[9]!==m||t[10]!==i||t[11]!==g||t[12]!==_||t[13]!==v||t[14]!==b?(x=(0,$.jsx)(`button`,{type:`button`,className:i,onClick:g,onMouseDown:_,onPointerDownCapture:v,title:m,"aria-label":m,children:b}),t[9]=m,t[10]=i,t[11]=g,t[12]=_,t[13]=v,t[14]=b,t[15]=x):x=t[15];let S=x,C;t[16]!==S||t[17]!==m||t[18]!==d?(C=d?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:S}),(0,$.jsx)(Jo,{side:`top`,sideOffset:8,children:m})]}):S,t[16]=S,t[17]=m,t[18]=d,t[19]=C):C=t[19];let w;t[20]!==i||t[21]!==o||t[22]!==a||t[23]!==r||t[24]!==s||t[25]!==c||t[26]!==e.onMenuOpenChange||t[27]!==e.onOpenMobileSheet||t[28]!==n?(w=null,t[20]=i,t[21]=o,t[22]=a,t[23]=r,t[24]=s,t[25]=c,t[26]=e.onMenuOpenChange,t[27]=e.onOpenMobileSheet,t[28]=n,t[29]=w):w=t[29];let T;t[30]!==C||t[31]!==w?(T=(0,$.jsxs)(`div`,{className:`relative inline-flex`,children:[C,w]}),t[30]=C,t[31]=w,t[32]=T):T=t[32];let E;t[33]!==i||t[34]!==a||t[35]!==l||t[36]!==n?(E=l?(0,$.jsx)(`button`,{type:`button`,onClick:l,className:i,title:n(`chat.chatInput.actions.modelAgentSettings`),"aria-label":n(`chat.chatInput.actions.modelAgentSettings`),children:(0,$.jsx)(Z,{name:`ai-agent`,className:Y(a,`text-current`)})}):null,t[33]=i,t[34]=a,t[35]=l,t[36]=n,t[37]=E):E=t[37];let D;return t[38]!==T||t[39]!==E?(D=(0,$.jsxs)(`div`,{className:`flex items-center gap-x-1.5`,children:[T,E]}),t[38]=T,t[39]=E,t[40]=D):D=t[40],D},(e,t)=>e.isVSCode===t.isVSCode&&e.footerIconButtonClass===t.footerIconButtonClass&&e.iconSizeClass===t.iconSizeClass&&e.onOpenSettings===t.onOpenSettings&&e.onMenuOpenChange===t.onMenuOpenChange&&e.onOpenMobileSheet===t.onOpenMobileSheet&&e.onOpenAndroidPickSheet===t.onOpenAndroidPickSheet&&e.withTooltip===t.withTooltip),Uw=Q.memo(function(e){let t=(0,pd.c)(29),{t:n}=Yt(),r=e.enabled?`chat.chatInput.permissionAutoAccept.disable`:`chat.chatInput.permissionAutoAccept.enable`,i;t[0]!==n||t[1]!==r?(i=n(r),t[0]=n,t[1]=r,t[2]=i):i=t[2];let a=i,o=e.saving,s=e.enabled,c=e.footerIconButtonClass,l;t[3]!==e.draftEnabled||t[4]!==e.draftOpen||t[5]!==e.enabled||t[6]!==e.onOpenSessionFirst||t[7]!==e.onSetDraftEnabled||t[8]!==e.onSetSessionEnabled||t[9]!==e.onToggleFailed||t[10]!==e.sessionId?(l=()=>mC({permissionScopeSessionId:e.sessionId,newSessionDraftOpen:e.draftOpen,draftPermissionAutoAcceptEnabled:e.draftEnabled,permissionAutoAcceptEnabled:e.enabled,setDraftPermissionAutoAcceptEnabled:e.onSetDraftEnabled,setSessionAutoAccept:e.onSetSessionEnabled,onOpenSessionFirst:e.onOpenSessionFirst,onToggleFailed:e.onToggleFailed}),t[3]=e.draftEnabled,t[4]=e.draftOpen,t[5]=e.enabled,t[6]=e.onOpenSessionFirst,t[7]=e.onSetDraftEnabled,t[8]=e.onSetSessionEnabled,t[9]=e.onToggleFailed,t[10]=e.sessionId,t[11]=l):l=t[11];let u=e.enabled?`shield-check`:`shield`,d;t[12]===e.iconSizeClass?d=t[13]:(d=Y(e.iconSizeClass,`text-current`),t[12]=e.iconSizeClass,t[13]=d);let f;t[14]!==u||t[15]!==d?(f=(0,$.jsx)(Z,{name:u,className:d}),t[14]=u,t[15]=d,t[16]=f):f=t[16];let p;t[17]!==a||t[18]!==e.enabled||t[19]!==e.footerIconButtonClass||t[20]!==e.saving||t[21]!==l||t[22]!==f?(p=(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(`button`,{type:`button`,disabled:o,"aria-pressed":s,"aria-label":a,className:c,onClick:l,onMouseDown:eT,onPointerDownCapture:tT,children:f})}),t[17]=a,t[18]=e.enabled,t[19]=e.footerIconButtonClass,t[20]=e.saving,t[21]=l,t[22]=f,t[23]=p):p=t[23];let m;t[24]===a?m=t[25]:(m=(0,$.jsx)(Jo,{side:`top`,sideOffset:8,children:a}),t[24]=a,t[25]=m);let h;return t[26]!==m||t[27]!==p?(h=(0,$.jsxs)(Yo,{children:[p,m]}),t[26]=m,t[27]=p,t[28]=h):h=t[28],h}),Ww=Q.memo(function(e){let t=(0,pd.c)(67),{isMobile:n,compact:r,footerIconButtonClass:i,stopFooterIconButtonClass:a,compactCircleButtonClass:o,sendIconSizeClass:s,stopIconSizeClass:c,canSend:l,canAbort:u,hasContent:d,currentSessionId:f,newSessionDraftOpen:p,draftSubmitting:m,submissionBlocked:h,sendPhase:g,queueFrozen:_,queueFallbackAvailable:v,onPrimaryAction:y,onAbort:b}=e,x=r!==void 0&&r,{t:S}=Yt(),C,w,T,E,D;if(t[0]!==u||t[1]!==l||t[2]!==x||t[3]!==o||t[4]!==f||t[5]!==m||t[6]!==i||t[7]!==d||t[8]!==n||t[9]!==p||t[10]!==y||t[11]!==v||t[12]!==_||t[13]!==s||t[14]!==g||t[15]!==a||t[16]!==c||t[17]!==h||t[18]!==S){D=Symbol.for(`react.early_return_sentinel`);bb0:{let e=Qb({canSend:l,hasSessionTarget:!!(f||p),draftSubmitting:!!m,submissionBlocked:h,sendPhase:g,queueFrozen:_,queueFallbackAvailable:v}),r;t[24]===n?r=t[25]:(r=n?{onMouseDown:nT,onPointerDownCapture:rT}:{},t[24]=n,t[25]=r);let b=r,O=g.inFlight,k=O&&g.flightKind===`queue`,A=O&&g.flightKind!==`queue`,j;t[26]!==u||t[27]!==v||t[28]!==_||t[29]!==k||t[30]!==A||t[31]!==S?(j=S(k?`chat.chatInput.actions.queuingMessageAria`:A?`chat.chatInput.actions.sendingMessageAria`:_&&v&&u?`chat.chatInput.actions.sendMessageAria`:u?`chat.chatInput.actions.queueMessageAria`:`chat.chatInput.actions.sendMessageAria`),t[26]=u,t[27]=v,t[28]=_,t[29]=k,t[30]=A,t[31]=S,t[32]=j):j=t[32];let M=j;C=x?o??a??i:a??i,w=c;let N=!u&&(!e.sendDisabled||O),P;t[33]!==n||t[34]!==y?(P=e=>{n&&(e.preventDefault(),y())},t[33]=n,t[34]=y,t[35]=P):P=t[35];let F;t[36]!==u||t[37]!==O||t[38]!==k||t[39]!==A||t[40]!==S?(F=S(A||!u&&O?k?`chat.chatInput.actions.queuingMessageAria`:`chat.chatInput.actions.sendingMessageAria`:`chat.chatInput.actions.sendMessageAria`),t[36]=u,t[37]=O,t[38]=k,t[39]=A,t[40]=S,t[41]=F):F=t[41];let I;t[42]!==u||t[43]!==w||t[44]!==O||t[45]!==s||t[46]!==N?(I=N?(0,$.jsx)(Pu,{className:w,spinning:!!(O&&!u)}):(0,$.jsx)(Z,{name:`send-plane-2`,className:s}),t[42]=u,t[43]=w,t[44]=O,t[45]=s,t[46]=N,t[47]=I):I=t[47];let L=(0,$.jsx)(`button`,{type:n?`button`:`submit`,"data-composer-send":`true`,"data-composer-circle":N?`true`:void 0,disabled:e.sendDisabled,"aria-busy":O||void 0,...b,onClick:P,className:Y(N?C:i,N?void 0:e.sendDisabled?e.disabledClass:`text-primary hover:text-primary`),"aria-label":F,children:I});if(!u){D=L;break bb0}let R=!x&&(d||k),z=!e.sendDisabled&&!k,B=x&&`h-full`;t[48]===B?T=t[49]:(T=Y(`relative z-30 overflow-visible`,B),t[48]=B,t[49]=T),E=R?(0,$.jsx)(`button`,{type:`button`,"data-composer-send":`true`,"data-composer-circle":z||k?`true`:void 0,disabled:e.sendDisabled||k,"aria-busy":k||void 0,...b,onClick:e=>{e.preventDefault(),!k&&y()},className:Y(z||k?C:i,`absolute z-30 bottom-full left-1/2 -translate-x-1/2 mb-1`,z||k?void 0:e.disabledClass),"aria-label":M,children:z||k?(0,$.jsx)(Pu,{className:w,spinning:k}):(0,$.jsx)(Z,{name:`send-plane-2`,className:s})}):null}t[0]=u,t[1]=l,t[2]=x,t[3]=o,t[4]=f,t[5]=m,t[6]=i,t[7]=d,t[8]=n,t[9]=p,t[10]=y,t[11]=v,t[12]=_,t[13]=s,t[14]=g,t[15]=a,t[16]=c,t[17]=h,t[18]=S,t[19]=C,t[20]=w,t[21]=T,t[22]=E,t[23]=D}else C=t[19],w=t[20],T=t[21],E=t[22],D=t[23];if(D!==Symbol.for(`react.early_return_sentinel`))return D;let O;t[50]===C?O=t[51]:(O=Y(C,`relative z-30`),t[50]=C,t[51]=O);let k;t[52]===S?k=t[53]:(k=S(`chat.chatInput.actions.stopGeneratingAria`),t[52]=S,t[53]=k);let A;t[54]===w?A=t[55]:(A=Y(w),t[54]=w,t[55]=A);let j;t[56]===A?j=t[57]:(j=(0,$.jsx)($u,{className:A}),t[56]=A,t[57]=j);let M;t[58]!==b||t[59]!==O||t[60]!==k||t[61]!==j?(M=(0,$.jsx)(`button`,{type:`button`,"data-composer-stop":`true`,onClick:b,className:O,"aria-label":k,children:j}),t[58]=b,t[59]=O,t[60]=k,t[61]=j,t[62]=M):M=t[62];let N;return t[63]!==T||t[64]!==E||t[65]!==M?(N=(0,$.jsxs)(`div`,{className:T,children:[E,M]}),t[63]=T,t[64]=E,t[65]=M,t[66]=N):N=t[66],N},(e,t)=>e.isMobile===t.isMobile&&e.compact===t.compact&&e.footerIconButtonClass===t.footerIconButtonClass&&e.stopFooterIconButtonClass===t.stopFooterIconButtonClass&&e.compactCircleButtonClass===t.compactCircleButtonClass&&e.sendIconSizeClass===t.sendIconSizeClass&&e.stopIconSizeClass===t.stopIconSizeClass&&e.canSend===t.canSend&&e.canAbort===t.canAbort&&e.hasContent===t.hasContent&&e.currentSessionId===t.currentSessionId&&e.newSessionDraftOpen===t.newSessionDraftOpen&&e.draftSubmitting===t.draftSubmitting&&e.submissionBlocked===t.submissionBlocked&&e.sendPhase===t.sendPhase&&e.queueFrozen===t.queueFrozen&&e.queueFallbackAvailable===t.queueFallbackAvailable&&e.onPrimaryAction===t.onPrimaryAction&&e.onAbort===t.onAbort),Gw=(e,t)=>`${e}${e?e.endsWith(`
|
|
6527
6527
|
|
|
6528
6528
|
`)?``:e.endsWith(`
|
|
@@ -6572,7 +6572,7 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}f
|
|
|
6572
6572
|
|
|
6573
6573
|
`):bA(Array.from(t.childNodes).map(e=>TA(e)).join(``))},OA=e=>Array.from(e.childNodes).every(e=>{if(e.nodeType===Node.TEXT_NODE||e.nodeType!==Node.ELEMENT_NODE)return!0;let t=e;return!vA.has(t.tagName.toLowerCase())}),kA=(e,t)=>{let n=e.cloneContents();if(OA(n)){let e=bA(Array.from(n.childNodes).map(e=>TA(e)).join(``));if(e)return e}return Array.from(n.childNodes).map(e=>DA(e)).filter(e=>e.length>0).join(`
|
|
6574
6574
|
|
|
6575
|
-
`).trim()||bA(t)},AA=({containerRef:e})=>{let{t}=Yt(),[n,r]=Q.useState({x:0,y:0,show:!1}),[i,a]=Q.useState(``),[o,s]=Q.useState(``),c=Q.useRef(!1),[l,u]=Q.useState(!1),d=Q.useRef(null),f=Q.useRef(gA),p=Q.useRef(null),m=Q.useRef(null),h=Q.useRef(null),g=Q.useRef(!1),_=X(e=>e.createSession),v=un(e=>e.setPendingInputText),y=q(e=>e.isMobile),b=Qy(Zy()).textSelectionMutation;Q.useEffect(()=>{g.current=n.show},[n.show]),Q.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),h.current!==null&&(window.clearTimeout(h.current),h.current=null)},[]);let x=Q.useCallback(()=>{p.current=null,_A===x&&(_A=null),g.current&&=(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),u(!1),r(e=>({...e,show:!1})),a(``),s(``),!1)},[]);Q.useEffect(()=>()=>{_A===x&&(_A=null)},[x]);let S=Q.useCallback(e=>{if(typeof window>`u`)return e;let t=window.innerWidth,n=f.current/2,r=hA+n,i=t-hA-n;return r>i?t/2:Math.min(Math.max(e,r),i)},[]),C=Q.useCallback(()=>{if(!p.current)return;_A!==x&&(_A?.(),_A=x);let{plainText:e,markdownText:t,rect:i}=p.current,o=!n.show,c=y?i.left+i.width/2:S(i.left+i.width/2),l=i.top-10;a(e),s(t),r({x:c,y:l,show:!0}),g.current=!0,o&&(u(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{u(!1),m.current=null}))},[S,x,y,n.show]);Q.useLayoutEffect(()=>{if(!n.show||y||!d.current)return;let e=d.current.offsetWidth;!Number.isFinite(e)||e<=0||e===f.current||(f.current=e,r(e=>({...e,x:S(e.x)})))},[S,y,n.show]),Q.useEffect(()=>{if(!n.show||y)return;let e=()=>{r(e=>({...e,x:S(e.x)}))};return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[S,y,n.show]);let w=Q.useCallback(()=>{let t=window.getSelection(),n=e.current;if(!t||!n){c.current||x();return}let r=bA(t.toString());if(!r){c.current||x();return}let i=CA(t,n);if(!i){c.current||x();return}let a=i.getBoundingClientRect();p.current={plainText:r,markdownText:kA(i,r),rect:a},c.current||C()},[e,x,C]);Q.useEffect(()=>{let t=e.current;if(!t)return;let n=()=>{c.current=!0,x()},r=()=>{c.current=!1,h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,w()},10)},i=new Set,a=()=>{for(let e of SA(t))i.has(e)||(i.add(e),e.addEventListener(`selectionchange`,w))};a();let o=new MutationObserver(a);o.observe(t,{childList:!0,subtree:!0}),document.addEventListener(`selectionchange`,w),t.addEventListener(`mousedown`,n),document.addEventListener(`mouseup`,r);let s=e=>{d.current&&!d.current.contains(e.target)&&!window.getSelection()?.toString().trim()&&x()};return document.addEventListener(`mousedown`,s),()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),o.disconnect();for(let e of i)e.removeEventListener(`selectionchange`,w);document.removeEventListener(`selectionchange`,w),t.removeEventListener(`mousedown`,n),document.removeEventListener(`mouseup`,r),document.removeEventListener(`mousedown`,s)}},[e,w,x,C]),Q.useEffect(()=>{if(!n.show)return;let e=e=>{d.current&&e.target instanceof Node&&d.current.contains(e.target)||x()};return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),()=>{window.removeEventListener(`scroll`,e,!0)}},[n.show,x]);let T=Q.useCallback(e=>{if(!e)return;let t=`\`\`\`md\n${e}\n\`\`\``;v(t,`append`),x(),window.getSelection()?.removeAllRanges()},[v,x]),E=Q.useCallback(()=>{T(o)},[T,o]);Q.useEffect(()=>{let t=t=>{if(!b||!t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||t.key.toLowerCase()!==`i`)return;let n=window.getSelection(),r=e.current;if(!n||!r||!n.toString().trim())return;let i=CA(n,r);i&&(t.preventDefault(),T(kA(i,n.toString())))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[T,b,e]);let D=Q.useCallback(async()=>{i&&(await _(void 0,null,null)&&v(i,`replace`),x(),window.getSelection()?.removeAllRanges())},[i,_,v,x]),O=Q.useCallback(async()=>{if(!i)return;let e=await Jt(i);e.ok||console.error(`Failed to copy:`,e.error),x(),window.getSelection()?.removeAllRanges()},[i,x]);return n.show?y?(0,Sf.createPortal)((0,$.jsx)(`div`,{ref:d,className:Y(`fixed left-3 right-3 bottom-0 z-50 mx-auto max-w-[420px]`,`rounded-2xl border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] p-2 shadow-lg`,`safe-area-bottom`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),style:{bottom:`calc(0.5rem + env(safe-area-inset-bottom, 0px))`},children:(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[b?(0,$.jsxs)(`button`,{onClick:E,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--primary-base)] text-[var(--primary-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(Z,{name:`add`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.addToChat`)})]}):null,b?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(Z,{name:`chat-new`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.newSession`)})]}):null,(0,$.jsxs)(`button`,{onClick:O,className:Y(`col-span-2 flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--surface-muted)] text-[var(--surface-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(Z,{name:`file-copy`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):(0,Sf.createPortal)((0,$.jsx)(`div`,{ref:d,className:`fixed z-50`,style:{left:n.x,top:n.y,transform:`translate(-50%, -100%)`},children:(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-1 whitespace-nowrap`,`rounded-lg border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] shadow-none`,`px-1.5 py-1`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),children:[b?(0,$.jsxs)(`button`,{onClick:E,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(Z,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.addToChat`)}),(0,$.jsx)(yv,{shortcut:`⌘+I`})]}):null,b?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,b?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(Z,{name:`chat-new`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.newSession`)})]}):null,b?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,(0,$.jsxs)(`button`,{onClick:O,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(Z,{name:`file-copy`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):null},jA=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),MA=(e,t)=>{let n=new Date(t);return n.setDate(t.getDate()-1),jA(e,n)},NA=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),PA=(e,t)=>{if(!NA(e))return``;let n=new Date(e),r=new Date,i=Ms(n,t),a=Zt(),o=en.getState().dictionary;if(jA(n,r))return i;if(MA(n,r))return tn(o,`common.date.yesterdayWithTime`,{time:i});let s=`${n.toLocaleString(a,{month:`short`})} ${n.getDate()}`;return n.getFullYear()===r.getFullYear()?`${s}, ${i}`:`${s}, ${n.getFullYear()}, ${i}`},FA=e=>typeof e!=`number`||!Number.isFinite(e)||e<0?0:e,IA=e=>e,LA=e=>{if(!Array.isArray(e)||e.length===0)return 0;let t=0;for(let n of e){let e=IA(n);if(e.type!==`tool`)continue;let r=e.state,i=r?.time?.start,a=r?.time?.end;typeof i!=`number`||!Number.isFinite(i)||typeof a!=`number`||!Number.isFinite(a)||a<i||(t+=a-i)}return t},RA=(e,t,n,r)=>{let i=(typeof e==`number`&&Number.isFinite(e)&&e>0&&typeof t==`number`&&Number.isFinite(t)&&t>e?t-e:null)??(typeof r==`number`&&Number.isFinite(r)&&r>0?r:null);if(i===null)return null;let a=i-LA(n);return!Number.isFinite(a)||a<=0?null:a},zA=e=>{let t=RA(e.createdAt,e.completedAt,e.parts,e.fallbackDurationMs);if(t===null)return null;let n=FA(e.outputTokens)+FA(e.reasoningTokens);if(n<=0)return null;let r=t/1e3;if(r<=0)return null;let i=n/r;return!Number.isFinite(i)||i<=0?null:i},BA=e=>{if(!Number.isFinite(e)||e<=0)return``;if(e>=1e3){let t=e/1e3;return`${t>=10?t.toFixed(0):t.toFixed(1)}k tok/s`}return e>=100?`${Math.round(e)} tok/s`:e>=10?`${e.toFixed(1)} tok/s`:`${e.toFixed(2)} tok/s`},VA=e=>{let t=(0,pd.c)(20),{text:n,active:r,className:i}=e,a=Q.useRef(n),[o,s]=Q.useState(n),[c,l]=Q.useState(null),u,d;t[0]!==r||t[1]!==n?(u=()=>{if(n===a.current)return;let e=a.current;if(a.current=n,!r||e.length===0){l(null),s(n);return}l(e),s(n)},d=[r,n],t[0]=r,t[1]=n,t[2]=u,t[3]=d):(u=t[2],d=t[3]),Q.useEffect(u,d);let f;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(f=()=>{l(null)},t[4]=f):f=t[4];let p=J(f),m;t[5]===i?m=t[6]:(m=Y(`oc-summary-flip-viewport relative block h-5 min-h-0 w-full min-w-0 max-w-full overflow-clip sm:h-6`,i),t[5]=i,t[6]=m);let h=c&&`invisible`,g;t[7]===h?g=t[8]:(g=Y(`block h-full min-w-0 truncate leading-5 sm:leading-6`,h),t[7]=h,t[8]=g);let _;t[9]!==o||t[10]!==g?(_=(0,$.jsx)(`span`,{className:g,children:o}),t[9]=o,t[10]=g,t[11]=_):_=t[11];let v;t[12]!==o||t[13]!==p||t[14]!==c?(v=c?(0,$.jsxs)(`span`,{className:`oc-summary-flip-stage absolute inset-0 block overflow-clip`,children:[(0,$.jsx)(`span`,{className:`oc-summary-flip-out absolute inset-x-0 top-0 block h-full truncate`,"aria-hidden":`true`,children:c}),(0,$.jsx)(`span`,{className:`oc-summary-flip-in absolute inset-x-0 top-0 block h-full truncate`,onAnimationEnd:p,children:o})]}):null,t[12]=o,t[13]=p,t[14]=c,t[15]=v):v=t[15];let y;return t[16]!==m||t[17]!==_||t[18]!==v?(y=(0,$.jsxs)(`span`,{className:m,children:[_,v]}),t[16]=m,t[17]=_,t[18]=v,t[19]=y):y=t[19],y},HA=[`search`,`read`,`list`];function UA(e){let t=UD(e);return t===`read`?`read`:t===`glob`||t===`grep`?`search`:t===`list`?`list`:null}function WA(e){let t={read:0,search:0,list:0};for(let n of e){let e=UA(n);e&&(t[e]+=1)}return t}var GA=[`edit`,`command`,`other`],KA=new Set([`edit`,`multiedit`,`write`,`create`,`file_write`,`apply_patch`,`patch`]),qA=new Set([`bash`,`shell`,`cmd`,`command`,`exec`,`terminal`]);function JA(e){if(!zD(e))return null;let t=UD(e);return KA.has(t)?`edit`:qA.has(t)?`command`:`other`}function YA(e){let t={edit:0,command:0,other:0};for(let n of e){let e=JA(n);e&&(t[e]+=1)}return t}function XA(e){return fD(e)}var ZA=[...HA,...GA];function QA(e){return{...WA(e),...YA(e)}}function $A(e){return HD(e)}function ej(e){return e.kind===`reasoning`||e.type===`reasoning`?!1:e.kind===`justification`||e.type===`text`?!0:e.kind===`tool`||e.type===`tool`?!BD(e.toolName):e.kind!=null||e.type!=null}function tj(e,t,n){for(let r=t;r<e.length;r+=1)if(ej(n(e[r])))return!0;return!1}function nj(e){return`parts`in e?e.parts.some(e=>$A(e))?!0:!e.hasFollowingOtherType&&e.isTurnLive:e.some(e=>$A(e))}function rj(e,t,n){let r=[],i=t;for(;i<e.length&&BD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var ij=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,aj=e=>{let t=(0,pd.c)(12),{added:n,removed:r}=e;if(n<=0&&r<=0)return null;let i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=Y(`inline-flex flex-none items-center gap-0.5 tabular-nums`,ij),t[0]=i):i=t[0];let a;t[1]===n?a=t[2]:(a=n>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,n]}):null,t[1]=n,t[2]=a);let o;t[3]!==n||t[4]!==r?(o=n>0&&r>0?(0,$.jsx)(`span`,{style:{color:`var(--tools-description)`},children:`/`}):null,t[3]=n,t[4]=r,t[5]=o):o=t[5];let s;t[6]===r?s=t[7]:(s=r>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,r]}):null,t[6]=r,t[7]=s);let c;return t[8]!==a||t[9]!==o||t[10]!==s?(c=(0,$.jsxs)(`span`,{className:i,children:[a,o,s]}),t[8]=a,t[9]=o,t[10]=s,t[11]=c):c=t[11],c},oj=({activities:e,isMobile:t,isTurnLive:n=!1,hasFollowingOtherType:r=!1,exploring:i,children:a})=>{let{t:o}=Yt(),[s,c]=Q.useState(!1),l=Q.useId(),u=e.map(e=>e.part),d=i??nj({parts:u,hasFollowingOtherType:r,isTurnLive:n}),f=QA(u.map(e=>e.tool)),p=XA(u),m=ZA.filter(e=>f[e]>0).map(e=>{let t=f[e];return o(e===`search`?t===1?`chat.contextGroup.searchSingle`:`chat.contextGroup.searchPlural`:e===`read`?t===1?`chat.contextGroup.readSingle`:`chat.contextGroup.readPlural`:e===`list`?t===1?`chat.contextGroup.listSingle`:`chat.contextGroup.listPlural`:e===`edit`?t===1?`chat.usedGroup.editSingle`:`chat.usedGroup.editPlural`:e===`command`?t===1?`chat.usedGroup.commandSingle`:`chat.usedGroup.commandPlural`:t===1?`chat.usedGroup.otherSingle`:`chat.usedGroup.otherPlural`,{count:t})}).join(`, `),h=J(()=>{c(e=>!e)}),g=J(e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),h())}),_=o(s?`chat.usedGroup.collapseAria`:`chat.usedGroup.expandAria`),v=o(d?`chat.usedGroup.running`:`chat.usedGroup.used`),y=t?`h-5`:`h-6`;return(0,$.jsxs)(`div`,{"data-component":`context-tool-group`,className:Ev(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":s,"aria-controls":l,"aria-label":_,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,Ov),onClick:h,onKeyDown:g,children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center self-center`,y,t?`w-4`:`w-3.5`),style:{color:`var(--tools-icon)`},children:d?(0,$.jsx)(TD,{isMobile:t,label:o(`chat.usedGroup.running`),className:`block`}):(0,$.jsx)(Z,{name:`search`,className:`block h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex flex-none items-center self-center font-medium`,y,ij,d&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...d?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:v}),m?(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex min-h-0 w-0 min-w-0 max-w-full flex-1 items-center self-center overflow-clip`,y,ij),style:{color:`var(--tools-description)`},children:(0,$.jsx)(VA,{text:m,active:d,className:t?`!h-5 sm:!h-5`:`!h-6 sm:!h-6`})}):null,(0,$.jsx)(aj,{added:p.added,removed:p.removed}),(0,$.jsx)(Z,{name:s?`arrow-down-s`:`arrow-right-s`,className:`ml-auto size-3.5 flex-none self-center text-muted-foreground opacity-70`})]}),s&&a?(0,$.jsxs)(`div`,{id:l,className:Dv(t),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute bottom-0 left-0 top-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),a]}):null]})};function sj(e,t,n){let r=[],i=t;for(;i<e.length&&RD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var cj=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null};function lj(e){if(!e||typeof e!=`object`)return null;let t=e.state;if(!t||typeof t!=`object`)return null;let n=t;if(n.metadata&&typeof n.metadata==`object`){let e=cj(n.metadata.name);if(e)return e}if(n.input&&typeof n.input==`object`){let e=n.input,t=cj(e.name);if(t)return t;let r=cj(e.id);if(r)return r}if(n.output&&typeof n.output==`object`){let e=cj(n.output.name);if(e)return e}return null}function uj(e){let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n.trim();e&&t.push(e)}let n=t.slice(0,3);return{visibleNames:n,hiddenCount:Math.max(0,t.length-n.length),joinedVisible:n.join(`, `)}}var dj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,fj=({activities:e,isMobile:t,children:n})=>{let{t:r}=Yt(),[i,a]=Q.useState(!1),o=Q.useId(),s=e.map(e=>e.part),c=s.some(e=>HD(e)),{joinedVisible:l,hiddenCount:u}=uj(s.map(lj)),d=u>0?r(`chat.skillGroup.summaryOverflow`,{names:l,count:u}):l,f=J(()=>{a(e=>!e)}),p=J(e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),f())}),m=r(i?`chat.skillGroup.collapseAria`:`chat.skillGroup.expandAria`),h=r(`chat.tools.display.skill`);return(0,$.jsxs)(`div`,{"data-component":`skill-tool-group`,className:Ev(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":i,"aria-controls":o,"aria-label":m,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,Ov),onClick:f,onKeyDown:p,children:[(0,$.jsx)(`span`,{className:Y(`flex flex-none items-center justify-center`,t?`size-4`:`size-3.5`),style:{color:`var(--tools-icon)`},children:c?(0,$.jsx)(TD,{isMobile:t,label:h,className:`block`}):(0,$.jsx)(Z,{name:`book`,className:`h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta flex-none font-medium`,dj,c&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...c?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:h}),d?(0,$.jsx)(`span`,{className:Y(`typography-meta h-5 min-h-0 w-0 min-w-0 max-w-full flex-1 overflow-clip sm:h-6`,dj),style:{color:`var(--tools-description)`},children:(0,$.jsx)(VA,{text:d,active:c})}):null,(0,$.jsx)(Z,{name:i?`arrow-down-s`:`arrow-right-s`,className:`ml-auto size-3.5 flex-none text-muted-foreground opacity-70`})]}),i&&n?(0,$.jsxs)(`div`,{id:o,className:Dv(t),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute bottom-0 left-0 top-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),n]}):null]})},pj=Q.memo(e=>{let t=(0,pd.c)(18),{part:n,messageId:r,onContentChange:i,actions:a,streamPhase:o,onShowPopup:s}=e,c=q(mj),l=n,u=typeof l.text==`string`?l.text:``,d=typeof l.content==`string`?l.content:``,f=d.length>u.length?d:u,p=l.time,m=n.sessionID,h=o===void 0||o!==`completed`,g,_;if(t[0]!==i||t[1]!==f?(g=()=>{f.trim().length!==0&&i?.(`structural`)},_=[i,f],t[0]=i,t[1]=f,t[2]=g,t[3]=_):(g=t[2],_=t[3]),Q.useEffect(g,_),!f||f.trim().length===0)return null;let v=o??`streaming`,y=h&&typeof p?.end!=`number`,b;t[4]!==c||t[5]!==r||t[6]!==i||t[7]!==s||t[8]!==n||t[9]!==m||t[10]!==v||t[11]!==y?(b=(0,$.jsx)(`div`,{"data-message-text-export-source":`true`,children:(0,$.jsx)(xk,{part:n,sessionId:m,messageId:r,streamPhase:v,chatRenderMode:c,hasStreamingHapticLifecycle:y,onContentChange:i,onShowPopup:s})}),t[4]=c,t[5]=r,t[6]=i,t[7]=s,t[8]=n,t[9]=m,t[10]=v,t[11]=y,t[12]=b):b=t[12];let x;t[13]===a?x=t[14]:(x=a?(0,$.jsx)(`div`,{className:`mt-2 mb-1 flex items-center justify-start gap-1.5`,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:`flex items-center gap-1.5`,"data-message-action-group":`true`,children:a})}):null,t[13]=a,t[14]=x);let S;return t[15]!==b||t[16]!==x?(S=(0,$.jsxs)(`div`,{"data-message-text-export-root":`true`,children:[b,x]}),t[15]=b,t[16]=x,t[17]=S):S=t[17],S});function mj(e){return e.chatRenderMode}var hj=e=>{let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`},gj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,_j=Y(`typography-meta font-medium`,gj),vj=Y(`typography-meta`,gj),yj=[],bj=e=>{let t=e.part;return t.slim===!0&&(t.type===`tool`||t.type===`reasoning`||t.type===`file`)},xj=e=>{let t=new Set;for(let n of e)bj(n)&&n.messageId&&t.add(n.messageId);return[...t]},Sj=(e,t)=>e.some(e=>{if(!t.has(e.messageId))return!1;let n=e.part;if(n.slim===!0)return!1;if(n.type===`reasoning`)return typeof n.text==`string`&&n.text.trim().length>0;if(n.type===`file`)return typeof n.url==`string`&&n.url.trim().length>0;if(n.type===`tool`){let e=n.state?.output,t=n.state?.error;return(typeof e==`string`?e.trim().length>0:e!=null)||(typeof t==`string`?t.trim().length>0:t!=null)}return!1}),Cj=e=>{let t=(0,pd.c)(5),{href:n}=e,[r,i]=Q.useState(!1),a;t[0]===n?a=t[1]:(a=Ll(n),t[0]=n,t[1]=a);let o=a;if(!o||r)return null;let s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>i(!0),t[2]=s):s=t[2];let c;return t[3]===o?c=t[4]:(c=(0,$.jsx)(`span`,{className:`inline-flex size-[18px] flex-shrink-0 items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)]`,children:(0,$.jsx)(`img`,{src:o,alt:``,"aria-hidden":`true`,loading:`lazy`,decoding:`async`,className:`size-3.5 rounded-sm`,onError:s})}),t[3]=o,t[4]=c),c},wj=e=>e,Tj=e=>{let t=e.part.state,n=t?.input,r=t?.metadata,i=n?.filePath||n?.file_path||n?.path||r?.filePath||r?.file_path||r?.path;if(typeof i==`string`&&i.trim().length>0){let e=i.lastIndexOf(`/`);return e>=0?i.slice(e+1):i}return null},Ej=e=>{let t=e.part.state,n=t?.input,r=t?.metadata,i=n?.filePath||n?.file_path||n?.path||r?.filePath||r?.file_path||r?.path;return typeof i==`string`&&i.trim().length>0?i:null},Dj=e=>{let t=e.part.state?.metadata?.dir;return typeof t==`string`&&t.trim().length>0?t:null},Oj=e=>{if(typeof e!=`string`)return null;let t=e.trim().toLowerCase();return t===`pending`?`pending`:t===`in_progress`||t===`in progress`||t===`inprogress`?`in_progress`:t===`completed`||t===`done`?`completed`:t===`cancelled`||t===`canceled`?`cancelled`:null},kj=e=>{if(e.length===0)return`0 tasks`;let t=0,n=0;for(let r of e){if(!r||typeof r!=`object`)continue;let e=Oj(r.status);e&&(e===`pending`&&(t+=1),e===`in_progress`&&(n+=1))}let r=t+n;return r===0?`0 tasks`:`${r} ${r===1?`task`:`tasks`}`},Aj=e=>{let t=e.part.state,n=t?.input,r=t?.output;if(Array.isArray(n?.todos)){let e=kj(n.todos);if(e)return e}if(Array.isArray(r)){let e=kj(r);if(e)return e}if(r&&typeof r==`object`&&Array.isArray(r.todos)){let e=kj(r.todos);if(e)return e}if(typeof r==`string`&&r.trim().length>0)try{let e=JSON.parse(r);if(Array.isArray(e)){let t=kj(e);if(t)return t}if(e&&typeof e==`object`&&Array.isArray(e.todos)){let t=kj(e.todos);if(t)return t}}catch{}return null},jj=e=>{let t=e.part.state,n=t?.input,r=t?.metadata,i=(typeof n?.offset==`number`&&Number.isFinite(n.offset)?n.offset:void 0)??(typeof n?.line==`number`&&Number.isFinite(n.line)?n.line:void 0)??(typeof r?.offset==`number`&&Number.isFinite(r.offset)?r.offset:void 0)??(typeof r?.line==`number`&&Number.isFinite(r.line)?r.line:void 0);if(!(typeof i!=`number`||i<=0))return Math.floor(i)},Mj=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(LT,{variant:t?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,vj),style:{color:`var(--tools-description)`},title:e,children:e});let r=e.slice(0,n),i=e.slice(n+1),a=r.startsWith(`/`),o=a?r.slice(1):r;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex max-w-full flex-1 items-baseline overflow-hidden`,vj),title:e,children:[a?(0,$.jsx)(`span`,{className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:`/`}):null,(0,$.jsx)(`span`,{className:`min-w-0 shrink truncate whitespace-nowrap`,style:{color:`var(--tools-description)`,direction:`rtl`,textAlign:`left`,unicodeBidi:`plaintext`},children:o}),(0,$.jsx)(`span`,{className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:`/`}),(0,$.jsx)(LT,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:i})]})},Nj=e=>{let t=au(e);return t?t.toLowerCase().endsWith(`/skill.md`)?t:`${t}/SKILL.md`:``},Pj=e=>{let t=e.part,n=t.tool?.toLowerCase()??``,r=t.state,i=r?.input,a=r?.metadata;if(n===`grep`||n===`search`||n===`find`||n===`ripgrep`){let e=i?.pattern;if(typeof e==`string`&&e.trim().length>0)return e.length>40?e.slice(0,40)+`...`:e}if(n===`glob`){let e=i?.pattern;if(typeof e==`string`&&e.trim().length>0)return e.length>40?e.slice(0,40)+`...`:e}if(n===`websearch`||n===`web-search`||n===`search_web`||n===`codesearch`||n===`perplexity`){let e=i?.query;if(typeof e==`string`&&e.trim().length>0)return e.length>50?e.slice(0,50)+`...`:e}if(n===`skill`)return lj(t);if(n===`webfetch`||n===`fetch`||n===`curl`||n===`wget`){let e=typeof i?.url==`string`&&i.url||typeof i?.URL==`string`&&i.URL||typeof a?.url==`string`&&a.url||typeof a?.URL==`string`&&a.URL||``;if(typeof e==`string`&&e.trim().length>0)return e.trim()}return n===`todowrite`||n===`todoread`?Aj(e):Tj(e)},Fj=e=>{let t=[],n=[];for(let r of e){if(r.kind!==`tool`)continue;let e=r.part;if(e.tool?.trim().toLowerCase()!==`task`)continue;let i=typeof e.id==`string`?e.id.trim():``;if(!i)continue;let a=e.state;if(!a||typeof a!=`object`)continue;let o=a;n.push(i),(o.status===`pending`||o.status===`running`)&&t.push(i)}return{active:t,all:n}},Ij=Q.memo(e=>{let t=(0,pd.c)(16),{activity:n,isExpanded:r,isMobile:i,onToggleTool:a,onShowPopup:o,onContentChange:s}=e,c;t[0]!==n.id||t[1]!==a?(c=()=>{a(n.id)},t[0]=n.id,t[1]=a,t[2]=c):c=t[2];let l=J(c),u;t[3]===i?u=t[4]:(u=Ev(i),t[3]=i,t[4]=u);let d=n.part,f;t[5]!==n.messageId||t[6]!==l||t[7]!==r||t[8]!==i||t[9]!==s||t[10]!==o||t[11]!==d?(f=(0,$.jsx)(tk,{part:d,messageId:n.messageId,isExpanded:r,onToggle:l,isMobile:i,onContentChange:s,onShowPopup:o,animateTailText:!1}),t[5]=n.messageId,t[6]=l,t[7]=r,t[8]=i,t[9]=s,t[10]=o,t[11]=d,t[12]=f):f=t[12];let p;return t[13]!==u||t[14]!==f?(p=(0,$.jsx)(`div`,{className:u,children:f}),t[13]=u,t[14]=f,t[15]=p):p=t[15],p},(e,t)=>e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.onToggleTool===t.onToggleTool&&e.onShowPopup===t.onShowPopup&&e.onContentChange===t.onContentChange&&e.activity.id===t.activity.id&&e.activity.messageId===t.activity.messageId&&e.activity.kind===t.activity.kind&&e.activity.endedAt===t.activity.endedAt&&TE([e.activity.part],[t.activity.part])),Lj=Q.memo(e=>{let t=(0,pd.c)(9),{toolName:n,activities:r,isMobile:i}=e,a;t[0]===i?a=t[1]:(a=Ev(i),t[0]=i,t[1]=a);let o;t[2]!==r||t[3]!==i||t[4]!==n?(o=(0,$.jsx)(Bj,{toolName:n,activities:r,isMobile:i,animateTailText:!1}),t[2]=r,t[3]=i,t[4]=n,t[5]=o):o=t[5];let s;return t[6]!==a||t[7]!==o?(s=(0,$.jsx)(`div`,{className:a,children:o}),t[6]=a,t[7]=o,t[8]=s):s=t[8],s},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&zj(e.activities,t.activities)),Rj=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.kind===`reasoning`){if(!qa(r.part).trim()){n++;continue}t.push({type:`reasoning`,activity:r}),n++;continue}if(r.kind===`justification`){t.push({type:`justification`,activity:r}),n++;continue}let i=r.part.tool?.toLowerCase()??``;if(BD(i)){let r=rj(e,n,e=>e.part.tool);t.push({type:`tool-context-group`,activities:r.items,hasFollowingOtherType:tj(e,r.end,e=>({kind:e.kind,toolName:e.part.tool}))}),n=r.end;continue}if(RD(i)){let r=sj(e,n,e=>e.part.tool);if(r.items.length>0){t.push({type:`tool-skill-group`,activities:r.items}),n=r.end;continue}}if(FD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(PD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(ID(i)){t.push({type:`tool-static-group`,toolName:i,activities:[r]}),n++;continue}t.push({type:`tool-fallback`,activity:r}),n++}return t},zj=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.id!==i.id||r.kind!==i.kind||r.endedAt!==i.endedAt||!TE([r.part],[i.part]))return!1}return!0},Bj=Q.memo(e=>{let t=(0,pd.c)(106),{toolName:n,activities:r,isMobile:i,animateTailText:a}=e,{t:o}=Yt(),s=q(Wj),c=Vl(n,o),l;t[0]===n?l=t[1]:(l=RT(n),t[0]=n,t[1]=l);let u=l,d;t[2]===n?d=t[3]:(d=n.toLowerCase(),t[2]=n,t[3]=d);let f=d===`read`,p=Q.useContext(ic),m=Fu(),h=$e(Gj),g=Zy(),_=g.kind===`embedded`?g.directory:h,v;t[4]===n?v=t[5]:(v=n.toLowerCase(),t[4]=n,t[5]=v);let y=v===`skill`,b;t[6]===y?b=t[7]:(b={enabled:y},t[6]=y,t[7]=b);let x=hi(b),S;t[8]===x.data?S=t[9]:(S=x.data??[],t[8]=x.data,t[9]=S);let C=S,w;t[10]===C?w=t[11]:(w=new Map(C.map(Kj)),t[10]=C,t[11]=w);let T=w,E=r[0]??null,D=!E||HD(E.part),O;t[12]===E?O=t[13]:(O=E?Pj(E):null,t[12]=E,t[13]=O);let k=O,A;if(t[14]!==k||t[15]!==E||t[16]!==T||t[17]!==n){bb0:{if(n.toLowerCase()!==`skill`||!E||!k){A=null;break bb0}let e=T.get(k)?.path||Dj(E);if(!e||e===`<built-in>`){A=null;break bb0}let r=Nj(e);if(!r){A=null;break bb0}let i;t[19]!==k||t[20]!==r?(i={name:k,path:r},t[19]=k,t[20]=r,t[21]=i):i=t[21],A=i}t[14]=k,t[15]=E,t[16]=T,t[17]=n,t[18]=A}else A=t[18];let j=A,M;if(t[22]!==_||t[23]!==f||t[24]!==E){bb1:{if(!f||!E){M=null;break bb1}let e=Ej(E);if(!e){M=null;break bb1}let n=cu(e,_);if(!n){M=null;break bb1}let r;t[26]===E?r=t[27]:(r=jj(E),t[26]=E,t[27]=r);let i;t[28]!==n||t[29]!==e||t[30]!==r?(i={path:e,displayPath:n,offset:r},t[28]=n,t[29]=e,t[30]=r,t[31]=i):i=t[31],M=i}t[22]=_,t[23]=f,t[24]=E,t[25]=M}else M=t[25];let N=M,P;t[32]!==_||t[33]!==m||t[34]!==p?(P=(e,t)=>{if(!_)return;let n=ru(_,e);if(!n)return;if(m){m.openFile({path:n,targetLine:t&&Number.isFinite(t)?Math.max(1,Math.trunc(t)):void 0});return}if(p?.editor){p.editor.openFile(n,t);return}if(!tu(n,_)){Wl(n,_).then(()=>{let e=q.getState(),r=_||nu(_,n);if(t&&Number.isFinite(t)){e.openContextFileAtLine(r,n,Math.max(1,Math.trunc(t)),1);return}e.openContextFile(r,n)});return}let r=q.getState(),i=nu(_,n);if(t&&Number.isFinite(t)){r.openContextFileAtLine(i,n,Math.max(1,Math.trunc(t)),1);return}r.openContextFile(i,n)},t[32]=_,t[33]=m,t[34]=p,t[35]=P):P=t[35];let F=J(P),I;t[36]!==_||t[37]!==m?(I=e=>{let t=au(e);if(!t)return;let n=()=>{if(m){m.openFile({path:t});return}let e=q.getState(),n=_||nu(``,t);e.openContextFile(n,t)};if(_&&!tu(t,_)){Wl(t,_).then(n);return}n()},t[36]=_,t[37]=m,t[38]=I):I=t[38];let L=J(I),R;t[39]===n?R=t[40]:(R=n.toLowerCase(),t[39]=n,t[40]=R);let z=R,B=z===`grep`||z===`search`||z===`find`||z===`ripgrep`||z===`glob`,V=z===`webfetch`||z===`fetch`||z===`curl`||z===`wget`,H=z===`skill`,ee=!!(N||j),U=!!(N&&_||j),te;t[41]!==U||t[42]!==F||t[43]!==L||t[44]!==ee||t[45]!==N||t[46]!==j?(te=()=>{if(!(!ee||!U)){if(N){F(N.path,N.offset);return}j&&L(j.path)}},t[41]=U,t[42]=F,t[43]=L,t[44]=ee,t[45]=N,t[46]=j,t[47]=te):te=t[47];let W=J(te),ne;t[48]===W?ne=t[49]:(ne=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),W())},t[48]=W,t[49]=ne);let G=J(ne),re=ee&&U&&`cursor-pointer`,ie=ee&&!U&&`cursor-default opacity-70`,K;t[50]!==re||t[51]!==ie?(K=Y(`flex w-full items-center gap-x-1.5 min-w-0`,Ov,re,ie),t[50]=re,t[51]=ie,t[52]=K):K=t[52];let ae=ee?`soft`:void 0,oe=ee?W:void 0,se=ee?G:void 0,ce=ee?`button`:void 0,le=ee&&U?0:void 0,ue=ee&&!U?!0:void 0,de=i?`size-4`:`size-3.5`,fe;t[53]===de?fe=t[54]:(fe=Y(`inline-flex items-center justify-center flex-shrink-0`,de),t[53]=de,t[54]=fe);let pe;t[55]===Symbol.for(`react.memo_cache_sentinel`)?(pe={color:`var(--tools-icon)`},t[55]=pe):pe=t[55];let me=D?(0,$.jsx)(TD,{isMobile:i,label:o(`chat.assistantStatus.usingTool`,{tool:c})}):u,he;t[56]!==fe||t[57]!==pe||t[58]!==me?(he=(0,$.jsx)(`div`,{className:fe,style:pe,children:me}),t[56]=fe,t[57]=pe,t[58]=me,t[59]=he):he=t[59];let ge,_e;t[60]===Symbol.for(`react.memo_cache_sentinel`)?(ge=Y(_j,`inline-flex items-center flex-shrink-0 opacity-85`),_e={color:`var(--tools-title)`},t[60]=ge,t[61]=_e):(ge=t[60],_e=t[61]);let ve;t[62]===c?ve=t[63]:(ve=(0,$.jsx)(`span`,{className:ge,style:_e,title:c,children:c}),t[62]=c,t[63]=ve);let ye;t[64]!==a||t[65]!==f||t[66]!==N||t[67]!==s?(ye=f&&N?(0,$.jsxs)(`span`,{className:Y(`inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left`,vj),style:{color:`var(--tools-description)`},title:N.offset?`${N.displayPath}:${N.offset}`:N.displayPath,children:[s?(0,$.jsx)(Hh,{filePath:N.path,className:`h-3.5 w-3.5`}):null,Mj(N.displayPath,a)]}):null,t[64]=a,t[65]=f,t[66]=N,t[67]=s,t[68]=ye):ye=t[68];let be;t[69]!==a||t[70]!==k||t[71]!==B?(be=B&&k?(0,$.jsx)(`span`,{className:`inline-flex min-w-0 flex-1`,children:(0,$.jsxs)(LT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,vj),style:{color:`var(--tools-description)`},title:k,children:[`"`,k,`"`]})}):null,t[69]=a,t[70]=k,t[71]=B,t[72]=be):be=t[72];let xe;t[73]!==k||t[74]!==V?(xe=V&&k?(0,$.jsxs)(`a`,{href:k,target:`_blank`,rel:`noopener noreferrer`,onClick:qj,className:Y(`min-w-0 flex-1 inline-flex items-center gap-1.5 underline decoration-[color:var(--status-info)] underline-offset-2 hover:opacity-90`,`truncate whitespace-nowrap`,vj),style:{color:`var(--status-info)`},title:k,children:[(0,$.jsx)(Cj,{href:k}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:k})]}):null,t[73]=k,t[74]=V,t[75]=xe):xe=t[75];let Se;t[76]!==H||t[77]!==j?(Se=H&&j?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,vj),style:{color:`var(--tools-description)`},title:j.path,children:j.name}):null,t[76]=H,t[77]=j,t[78]=Se):Se=t[78];let Ce;t[79]!==k||t[80]!==H||t[81]!==j?(Ce=H&&!j&&k?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,vj),style:{color:`var(--tools-description)`},title:k,children:k}):null,t[79]=k,t[80]=H,t[81]=j,t[82]=Ce):Ce=t[82];let we;t[83]!==a||t[84]!==k||t[85]!==V||t[86]!==f||t[87]!==B||t[88]!==H?(we=!f&&!B&&!V&&!H&&k?(0,$.jsx)(LT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,vj),style:{color:`var(--tools-description)`},children:k}):null,t[83]=a,t[84]=k,t[85]=V,t[86]=f,t[87]=B,t[88]=H,t[89]=we):we=t[89];let Te;return t[90]!==K||t[91]!==ae||t[92]!==oe||t[93]!==se||t[94]!==ce||t[95]!==le||t[96]!==ue||t[97]!==he||t[98]!==ve||t[99]!==ye||t[100]!==be||t[101]!==xe||t[102]!==Se||t[103]!==Ce||t[104]!==we?(Te=(0,$.jsxs)(`div`,{className:K,"data-mobile-press-feedback":ae,onClick:oe,onKeyDown:se,role:ce,tabIndex:le,"aria-disabled":ue,children:[he,ve,ye,be,xe,Se,Ce,we]}),t[90]=K,t[91]=ae,t[92]=oe,t[93]=se,t[94]=ce,t[95]=le,t[96]=ue,t[97]=he,t[98]=ve,t[99]=ye,t[100]=be,t[101]=xe,t[102]=Se,t[103]=Ce,t[104]=we,t[105]=Te):Te=t[105],Te},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&zj(e.activities,t.activities)),Vj=Q.memo(e=>{let t=(0,pd.c)(5),{activity:n,onContentChange:r,streamPhase:i}=e,a;return t[0]!==n.messageId||t[1]!==n.part||t[2]!==r||t[3]!==i?(a=(0,$.jsx)(Nk,{part:n.part,messageId:n.messageId,streamPhase:i,onContentChange:r}),t[0]=n.messageId,t[1]=n.part,t[2]=r,t[3]=i,t[4]=a):a=t[4],a}),Hj=Q.memo(e=>{let t=(0,pd.c)(7),{activity:n,onContentChange:r,onShowPopup:i,actions:a,streamPhase:o}=e,s;return t[0]!==a||t[1]!==n.messageId||t[2]!==n.part||t[3]!==r||t[4]!==i||t[5]!==o?(s=(0,$.jsx)(pj,{part:n.part,messageId:n.messageId,onContentChange:r,onShowPopup:i,actions:a,streamPhase:o}),t[0]=a,t[1]=n.messageId,t[2]=n.part,t[3]=r,t[4]=i,t[5]=o,t[6]=s):s=t[6],s}),Uj=Q.memo(({parts:e,materializationParts:t=e,isExpanded:n,collapsedPreviewCount:r=0,completionDisposition:i,activityPresentationKind:a=`default`,durationMs:o,onToggle:s,isMobile:c,expandedTools:l,onToggleTool:u,onShowPopup:d,onContentChange:f,streamPhase:p,showHeader:m,renderJustificationActions:h})=>{let{t:g}=Yt(),_=Hl()??``,v=Q.useMemo(()=>xj(t),[t]),y=Q.useRef(new Set),b=Q.useRef(new Map),x=Q.useRef(new Set),[,S]=Q.useState(0),C=Q.useRef(null),w=Q.useRef(null),T=i===`active`,E=!T&&(i===`normal`||i===`abnormal`)&&typeof o==`number`&&Number.isFinite(o)&&o>=0?hj(o):null,D=i===`normal`||i===`abnormal`,O=a===`compaction`,k=O?`fold-vertical`:`stack`,A=g(i===void 0?`chat.activity.title`:T?O?`chat.activity.compacting`:`chat.activity.active`:D?O?`chat.activity.compactionCompleted`:`chat.activity.completedStatus`:`chat.activity.title`),j=Q.useMemo(()=>Fj(e),[e]),M=T?j.active:j.all,N=M.slice(0,c?2:3),P=J((e=!1,n=!1)=>{if(!(!_||!v.length)){for(let r of v){let i=t.find(e=>e.messageId===r)?.part.sessionID;if(!i)continue;let a=ci(_,i,r);if(a.status===`ready`||n&&a.status===`error`||e&&a.status!==`error`&&!x.current.has(r)||(y.current.add(r),x.current.delete(r),b.current.has(r)))continue;let o=_i(_,i,r,{priority:n?`background`:`user`}).catch(()=>{x.current.add(r)}).finally(()=>{b.current.delete(r),S(e=>e+1)});b.current.set(r,o)}S(e=>e+1)}}),F=J(e=>{e.stopPropagation(),P(!0)}),I=T,L=I||n,R=J(()=>{if(I)return;let e=C.current;w.current=e?{top:e.getBoundingClientRect().top,scrollContainer:e.closest(`[data-scrollbar="chat"]`)}:null,L||P(),s()});Q.useEffect(()=>{T||!L||P(!1,!0)},[T,L]),Q.useLayoutEffect(()=>{let e=w.current,t=C.current;if(!e||!t)return;let n=()=>{if(!t.isConnected)return;let n=t.getBoundingClientRect().top-e.top;if(!(Math.abs(n)<.5)){if(e.scrollContainer?.isConnected){e.scrollContainer.scrollTop+=n;return}window.scrollBy(0,n)}};if(n(),typeof window>`u`||typeof window.requestAnimationFrame!=`function`){w.current=null;return}let r=window.requestAnimationFrame(()=>{n(),w.current=null});return()=>window.cancelAnimationFrame(r)},[L]);let z=m&&!L?Math.max(0,Math.floor(r)):0,B=!m||L||z>0,V=y.current,H=[...V].map(e=>{if(b.current.has(e))return`loading`;if(x.current.has(e))return`error`;let n=t.find(t=>t.messageId===e)?.part.sessionID??``;return ci(_,n,e).status}),ee=H.includes(`loading`),U=H.includes(`error`),te=H.length>0&&H.every(e=>e===`ready`),W=t.some(e=>V.has(e.messageId)&&bj(e)),ne=te&&!W&&!Sj(t,V),G=Q.useMemo(()=>B?wj(e):yj,[e,B]),re=Q.useMemo(()=>B?Rj(G):[],[B,G]),ie=Q.useMemo(()=>L||z===0?0:Math.max(0,re.length-z),[L,z,re.length]),K=Q.useMemo(()=>L||z===0?re:re.slice(-z),[L,z,re]);if((!m||I&&!O)&&re.length===0)return null;let ae=(e,t)=>{let n=(0,$.jsx)(`div`,{className:Ev(c),children:t});return(0,$.jsx)(Q.Fragment,{children:n},e)},oe=B?K.map((e,t)=>{switch(e.type){case`reasoning`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Vj,{activity:e.activity,streamPhase:p,onContentChange:f})}));case`justification`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Hj,{activity:e.activity,onContentChange:f,onShowPopup:d,actions:h?.(e.activity),streamPhase:p})}));case`tool-expandable`:return(0,$.jsx)(Ij,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);case`tool-static-group`:return(0,$.jsx)(Lj,{toolName:e.toolName,activities:e.activities,isMobile:c},e.activities[0]?.id??`static-${e.toolName}-${t}`);case`tool-context-group`:return(0,$.jsx)(oj,{activities:e.activities,isMobile:c,isTurnLive:T,hasFollowingOtherType:e.hasFollowingOtherType,children:e.activities.map(e=>{let t=e.part,n=t.tool?.toLowerCase()??``;return LD(n)?(0,$.jsx)(Bj,{toolName:n,activities:[e],isMobile:c,animateTailText:!1},e.id):(0,$.jsx)(tk,{part:t,messageId:e.messageId,isExpanded:l.has(e.id),onToggle:u,isMobile:c,onContentChange:f,onShowPopup:d,animateTailText:!1},e.id)})},e.activities[0]?.id??`context-${t}`);case`tool-skill-group`:return(0,$.jsx)(fj,{activities:e.activities,isMobile:c,children:e.activities.map(e=>{let t=e.part;return(0,$.jsx)(Bj,{toolName:t.tool?.toLowerCase()??``,activities:[e],isMobile:c,animateTailText:!1},e.id)})},e.activities[0]?.id??`skill-${t}`);case`tool-fallback`:return(0,$.jsx)(Ij,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);default:return null}}):null,se=K.length>0;return m?(0,$.jsxs)(`div`,{className:Ev(c),children:[(0,$.jsxs)(`button`,{ref:C,type:`button`,className:Y(`group/tool flex w-full min-w-0 flex-nowrap items-center text-left`,c?`gap-x-1`:`gap-x-2`,!I&&Ov,I&&`oc-tool-row -mx-2 rounded-lg px-2 py-0.5 cursor-default`,c&&`pr-0`),"data-mobile-press-feedback":I?void 0:`soft`,onClick:I?void 0:R,"aria-expanded":L,"aria-disabled":I||void 0,"aria-label":I?A:g(L?`chat.activity.collapseAria`:`chat.activity.expandAria`),children:[(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 flex-1 items-center overflow-clip`,c?`gap-x-1`:`gap-x-1.5`),children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center`,c?`h-5 w-4`:`h-6 w-3.5`),style:{color:`var(--tools-icon)`},children:T&&!O?(0,$.jsx)(TD,{isMobile:c,label:A,className:`block`}):(0,$.jsx)(Z,{name:k,className:`h-3.5 w-3.5`})}),(0,$.jsx)(`span`,{className:Y(`inline-flex flex-shrink-0 items-center`,c?`typography-meta h-5`:`typography-ui-label h-5 font-semibold`,T?`animate-text-shimmer text-[var(--status-info)] [--oc-text-shimmer-base:var(--status-info)]`:`text-foreground/85`),children:A}),E?(0,$.jsx)(`span`,{className:`typography-meta shrink-0 tabular-nums text-muted-foreground`,children:E}):null]}),(0,$.jsxs)(`span`,{className:Y(`ml-auto inline-flex max-w-[min(14rem,55%)] shrink-0 items-center justify-end`,c?`gap-0.5`:`gap-1`),children:[M.length>0?(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 items-center text-muted-foreground`,c?`gap-1`:`gap-1.5`),children:[(0,$.jsx)(`span`,{className:`inline-flex shrink-0 items-center gap-0.5`,"aria-hidden":`true`,children:N.map((e,t)=>(0,$.jsx)(vo,{name:e,size:c?12:14,className:Y(`flex-none`,c?`size-3 min-h-3 min-w-3 max-h-3 max-w-3`:`size-3.5 min-h-3.5 min-w-3.5 max-h-3.5 max-w-3.5`)},`${e}-${t}`))}),(0,$.jsx)(`span`,{className:`typography-meta min-w-0 truncate`,children:g(T?`chat.activity.agentsWorking`:`chat.activity.agentsInvolved`,{count:M.length})})]}):null,I?null:(0,$.jsx)(Z,{name:L?`arrow-down-s`:`arrow-right-s`,className:Y(`flex-shrink-0 text-muted-foreground opacity-70`,c&&`-mr-0.5`,c?`size-3`:`size-3.5`)})]})]}),se?(0,$.jsxs)(`div`,{className:I?void 0:`relative ml-2 pl-3`,children:[I?null:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute left-0 top-px bottom-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),ie>0?(0,$.jsxs)(`button`,{type:`button`,onClick:R,className:`typography-meta leading-4 px-2 py-1 text-muted-foreground/45 hover:text-muted-foreground/65 text-left`,children:[`+`,ie,` more...`]}):null,(0,$.jsx)(`div`,{className:`flow-root`,children:oe})]}):null,L&&(ee||U||ne)?(0,$.jsx)(`div`,{className:Y(`typography-meta flex min-h-9 items-center gap-2 px-2 text-muted-foreground`,I?void 0:`ml-5`,U&&`text-[var(--status-error)]`),role:U?`alert`:`status`,children:ee?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 shrink-0 animate-spin`}),(0,$.jsx)(`span`,{children:g(`chat.activity.outputLoading`)})]}):U?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`error-warning`,className:`size-3.5 shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:g(`chat.activity.outputLoadFailed`)}),(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`xs`,onClick:F,children:g(`chat.activity.outputRetry`)})]}):(0,$.jsx)(`span`,{children:g(`chat.toolOutputDialog.noOutputProduced`)})}):null]}):(0,$.jsx)(`div`,{className:Ev(c),children:oe})});function Wj(e){return e.showToolFileIcons}function Gj(e){return e.currentDirectory}function Kj(e){return[e.name,e]}function qj(e){e.stopPropagation()}var Jj=Q.memo(e=>{let t=(0,pd.c)(2),n;return t[0]===e?n=t[1]:(n=(0,$.jsx)(Uj,{...e}),t[0]=e,t[1]=n),n}),Yj={contain:`layout`},Xj={containerType:`inline-size`,containerName:`message-footer`},Zj=`mt-1.5 mb-0.5 flex items-center justify-start gap-1.5`,Qj=`mt-3 mb-0.5 flex items-center justify-start gap-1.5`,$j=`size-6! p-0 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`,eM=`size-3.5!`,tM=`mt-1.5 mb-0.5 flex flex-wrap items-center gap-3`,nM=`mt-3 mb-0.5 flex flex-wrap items-center gap-3 -ml-[5px]`,rM=`flex items-center gap-2`,iM=`flex items-center gap-2 text-muted-foreground`,aM=`inline-flex h-3.5 items-center gap-1 text-[11px] leading-none tabular-nums text-muted-foreground`,oM=`size-3.5!`,sM=`medium`,cM=e=>e.replace(/\\/g,`/`).split(`/`).filter(Boolean).at(-1)??e,lM=`w-full min-w-0 justify-start rounded-[var(--radius-md)] bg-transparent px-1 hover:!bg-interactive-hover focus-visible:!bg-interactive-hover active:!bg-interactive-active supports-[corner-shape:squircle]:rounded-[var(--radius-md)]`,uM=`h-7 gap-1.5`,dM=`h-6 gap-1`,fM=`text-[11px] leading-none`,pM=`size-3.5`,mM=`size-3`,hM=5,gM=Q.memo(e=>{let t=(0,pd.c)(30),{file:n,isMobile:r}=e,i=r?`gap-1 text-[11px]`:`gap-1.5 text-xs`,a;t[0]===i?a=t[1]:(a=Y(`flex min-w-0 flex-1 items-center leading-none text-muted-foreground`,i),t[0]=i,t[1]=a);let o=n.file,s=r?`h-3 w-3`:`h-3.5 w-3.5`,c;t[2]===s?c=t[3]:(c=Y(`flex-shrink-0`,s),t[2]=s,t[3]=c);let l;t[4]!==n.file||t[5]!==c?(l=(0,$.jsx)(Hh,{filePath:o,className:c}),t[4]=n.file,t[5]=c,t[6]=l):l=t[6];let u=n.file,d;t[7]===n.file?d=t[8]:(d=cM(n.file),t[7]=n.file,t[8]=d);let f;t[9]!==n.file||t[10]!==d?(f=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-left text-foreground/80`,title:u,children:d}),t[9]=n.file,t[10]=d,t[11]=f):f=t[11];let p=r?`text-[11px]`:`typography-meta`,m;t[12]===p?m=t[13]:(m=Y(`inline-flex flex-shrink-0 items-center gap-0 leading-none tabular-nums`,p),t[12]=p,t[13]=m);let h;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(h={color:`var(--status-success)`},t[14]=h):h=t[14];let g;t[15]===n.additions?g=t[16]:(g=(0,$.jsxs)(`span`,{style:h,children:[`+`,n.additions]}),t[15]=n.additions,t[16]=g);let _,v;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(_=(0,$.jsx)(`span`,{className:`text-muted-foreground/70`,children:`/`}),v={color:`var(--status-error)`},t[17]=_,t[18]=v):(_=t[17],v=t[18]);let y;t[19]===n.deletions?y=t[20]:(y=(0,$.jsxs)(`span`,{style:v,children:[`-`,n.deletions]}),t[19]=n.deletions,t[20]=y);let b;t[21]!==m||t[22]!==g||t[23]!==y?(b=(0,$.jsxs)(`span`,{className:m,children:[g,_,y]}),t[21]=m,t[22]=g,t[23]=y,t[24]=b):b=t[24];let x;return t[25]!==b||t[26]!==a||t[27]!==l||t[28]!==f?(x=(0,$.jsxs)(`span`,{className:a,children:[l,f,b]}),t[25]=b,t[26]=a,t[27]=l,t[28]=f,t[29]=x):x=t[29],x}),_M=Q.memo(e=>{let t=(0,pd.c)(18),{file:n,canOpen:r,isMobile:i,onOpen:a}=e,{t:o}=Yt(),s;t[0]!==n.file||t[1]!==a?(s=()=>{a(n.file)},t[0]=n.file,t[1]=a,t[2]=s):s=t[2];let c=J(s),l=!r,u=i?dM:uM,d;t[3]===u?d=t[4]:(d=Y(lM,u),t[3]=u,t[4]=d);let f;t[5]!==n.file||t[6]!==o?(f=o(`chat.changedFiles.actions.openFileTitle`,{path:n.file}),t[5]=n.file,t[6]=o,t[7]=f):f=t[7];let p;t[8]!==n||t[9]!==i?(p=(0,$.jsx)(gM,{file:n,isMobile:i}),t[8]=n,t[9]=i,t[10]=p):p=t[10];let m;return t[11]!==n.file||t[12]!==c||t[13]!==l||t[14]!==d||t[15]!==f||t[16]!==p?(m=(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`xs`,disabled:l,"data-turn-change-file":`true`,className:d,"aria-label":f,title:n.file,onClick:c,children:p}),t[11]=n.file,t[12]=c,t[13]=l,t[14]=d,t[15]=f,t[16]=p,t[17]=m):m=t[17],m}),vM=Q.memo(e=>{let t=(0,pd.c)(53),{fileCount:n,changedFiles:r,turnId:i,isLatestTurn:a,isMobile:o}=e,{t:s}=Yt(),c=Hl(),l=Zy(),u=l.directory||c,d=l.sessionId,f=Fu(),p=q(MM),m;t[0]===r?m=t[1]:(m=r??[],t[0]=r,t[1]=m);let h=m,g;t[2]===h?g=t[3]:(g=h.slice(0,hM),t[2]=h,t[3]=g);let _=g,v=Math.max(0,h.length-_.length),y=h.length>0?h.length:n,b=!!(f||!o&&u||o&&a),x;t[4]!==y||t[5]!==s?(x=s(y===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:y}),t[4]=y,t[5]=s,t[6]=x):x=t[6];let S=x,C;t[7]!==v||t[8]!==s?(C=s(v===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:v}),t[7]=v,t[8]=s,t[9]=C):C=t[9];let w=C,T=Y(lM,o?dM:uM),E=o?mM:pM,D;t[10]===o?D=t[11]:(D=o?Y(fM,`font-semibold text-foreground/85`):`typography-meta font-semibold text-foreground/85`,t[10]=o,t[11]=D);let O=D,k;t[12]===o?k=t[13]:(k=o?Y(fM,`text-muted-foreground`):`typography-meta text-muted-foreground`,t[12]=o,t[13]=k);let A=k,j;t[14]===o?j=t[15]:(j=o?Y(fM,`font-medium`):`typography-meta font-medium`,t[14]=o,t[15]=j);let M=j,N;t[16]!==u||t[17]!==d||t[18]!==a||t[19]!==o||t[20]!==f||t[21]!==i?(N=e=>{if(f){f.openTurnDiff(i,d,e);return}if(!o&&u){Ik({directory:u,filePath:e,turnMessageId:i,sessionId:d});return}o&&a&&u&&Ik({directory:u,filePath:e,turnMessageId:i,sessionId:d,mobile:!0})},t[16]=u,t[17]=d,t[18]=a,t[19]=o,t[20]=f,t[21]=i,t[22]=N):N=t[22];let P=J(N),F;t[23]!==u||t[24]!==d||t[25]!==a||t[26]!==o||t[27]!==f||t[28]!==p||t[29]!==i||t[30]!==_[0]?.file?(F=()=>{if(f){f.openTurnDiff(i,d);return}if(!o&&u){p(u,{mode:`diff`,dedupeKey:`turn-diff:${d||`session`}:${i}`,targetPath:null,diffScope:`turn`,diffTurnMessageId:i,diffSessionId:d});return}let e=_[0]?.file;e&&o&&a&&u&&Ik({directory:u,filePath:e,turnMessageId:i,sessionId:d,mobile:!0})},t[23]=u,t[24]=d,t[25]=a,t[26]=o,t[27]=f,t[28]=p,t[29]=i,t[30]=_[0]?.file,t[31]=F):F=t[31];let I=J(F),L=o?`gap-0 border-foreground/15 p-1`:`gap-0.5 border-border/50 p-1.5`,R;t[32]===L?R=t[33]:(R=Y(`mt-4 flex min-w-0 flex-col rounded-[var(--radius-lg)] border bg-muted/20`,L),t[32]=L,t[33]=R);let z=Y(T,`max-w-full text-muted-foreground hover:text-foreground`),B;t[34]===s?B=t[35]:(B=s(`diffView.actions.reviewAria`),t[34]=s,t[35]=B);let V;t[36]===s?V=t[37]:(V=s(`diffView.actions.reviewAria`),t[36]=s,t[37]=V);let H;t[38]===E?H=t[39]:(H=(0,$.jsx)(Z,{name:`file-edit`,className:E}),t[38]=E,t[39]=H);let ee=`turn-changes-${i}`,U;t[40]===s?U=t[41]:(U=s(`chat.changedFiles.title`),t[40]=s,t[41]=U);let te;t[42]!==ee||t[43]!==U||t[44]!==O?(te=(0,$.jsx)(`span`,{id:ee,className:O,children:U}),t[42]=ee,t[43]=U,t[44]=O,t[45]=te):te=t[45];let W;t[46]!==S||t[47]!==A?(W=(0,$.jsx)(`span`,{className:A,children:S}),t[46]=S,t[47]=A,t[48]=W):W=t[48];let ne;t[49]===E?ne=t[50]:(ne=Y(E,`opacity-60`),t[49]=E,t[50]=ne);let G;return t[51]===ne?G=t[52]:(G=(0,$.jsx)(Z,{name:`arrow-right-s`,className:ne}),t[51]=ne,t[52]=G),(0,$.jsxs)(`section`,{className:R,"data-turn-changes-preview":`true`,"data-message-action-group":`true`,"aria-labelledby":`turn-changes-${i}`,children:[(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,onClick:I,className:z,"aria-label":B,title:V,children:[H,te,W,G]}),_.length>0?(0,$.jsxs)(`div`,{className:Y(`flex min-w-0 flex-col`,o?`gap-0`:`gap-0.5`),children:[_.map(e=>(0,$.jsx)(_M,{file:e,canOpen:b,isMobile:o,onOpen:P},e.file)),v>0?(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,className:Y(T,`text-muted-foreground hover:text-foreground`),onClick:I,"aria-label":s(`diffView.actions.reviewAria`),title:s(`diffView.actions.reviewAria`),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(E,`flex-shrink-0`)}),(0,$.jsxs)(`span`,{className:M,children:[`+`,w]}),(0,$.jsx)(Z,{name:`arrow-right-s`,className:E})]}):null]}):null]})}),yM=e=>e.type===`subtask`,bM=e=>{let t=e;return t.type===`text`&&typeof t.shellAction==`object`&&t.shellAction!==null},xM=e=>{if(!e||typeof e!=`object`)return null;let t=typeof e.providerID==`string`?e.providerID.trim():``,n=typeof e.modelID==`string`?e.modelID.trim():``;return!t||!n?null:`${t}/${n}`},SM=e=>{let t=(0,pd.c)(49),{part:n}=e,[r,i]=Q.useState(!1),a=Hl(),{isMobile:o}=qs(),s=X(NM),c=q(PM),l=Zy(),{t:u}=Yt(),d;t[0]===n.description?d=t[1]:(d=typeof n.description==`string`?n.description.trim():``,t[0]=n.description,t[1]=d);let f=d,p;t[2]===n.command?p=t[3]:(p=typeof n.command==`string`?n.command.trim():``,t[2]=n.command,t[3]=p);let m=p,h;t[4]===n.agent?h=t[5]:(h=typeof n.agent==`string`?n.agent.trim():``,t[4]=n.agent,t[5]=h);let g=h,_;t[6]===n.prompt?_=t[7]:(_=typeof n.prompt==`string`?n.prompt.trim():``,t[6]=n.prompt,t[7]=_);let v=_,y;t[8]===n.taskSessionID?y=t[9]:(y=typeof n.taskSessionID==`string`?n.taskSessionID.trim():``,t[8]=n.taskSessionID,t[9]=y);let b=y,x;t[10]===n.model?x=t[11]:(x=xM(n.model),t[10]=n.model,t[11]=x);let S=x,C=!!v&&!(o&&l.kind===`primary`),w;t[12]===u?w=t[13]:(w=u(`chat.messageBody.subtask.title`),t[12]=u,t[13]=w);let T;t[14]===w?T=t[15]:(T=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:w}),t[14]=w,t[15]=T);let E;t[16]===m?E=t[17]:(E=m?(0,$.jsxs)(`span`,{className:`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground`,children:[`/`,m]}):null,t[16]=m,t[17]=E);let D;t[18]===g?D=t[19]:(D=g?(0,$.jsxs)(`span`,{className:`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground`,children:[`@`,g]}):null,t[18]=g,t[19]=D);let O;t[20]===S?O=t[21]:(O=S?(0,$.jsx)(`span`,{className:`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground`,children:S}):null,t[20]=S,t[21]=O);let k;t[22]!==D||t[23]!==O||t[24]!==T||t[25]!==E?(k=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[T,E,D,O]}),t[22]=D,t[23]=O,t[24]=T,t[25]=E,t[26]=k):k=t[26];let A;t[27]===f?A=t[28]:(A=f?(0,$.jsx)(`div`,{className:`typography-ui-label text-foreground/90 mt-1.5`,children:f}):null,t[27]=f,t[28]=A);let j;t[29]!==r||t[30]!==v||t[31]!==C||t[32]!==u?(j=C?(0,$.jsxs)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:[(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>i(FM),children:u(r?`chat.messageBody.subtask.hidePrompt`:`chat.messageBody.subtask.showPrompt`)}),r?(0,$.jsx)(`pre`,{className:`typography-meta mt-1.5 overflow-x-auto whitespace-pre-wrap break-words text-foreground/85`,children:v}):null]}):null,t[29]=r,t[30]=v,t[31]=C,t[32]=u,t[33]=j):j=t[33];let M;t[34]!==g||t[35]!==f||t[36]!==a||t[37]!==o||t[38]!==c||t[39]!==l||t[40]!==s||t[41]!==u||t[42]!==b?(M=b&&l.capabilities.navigateNestedSession?(0,$.jsx)(`div`,{className:`mt-1.5`,children:(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>{let e=l.directory||a;e&&$y(l,b,e,()=>{if(!fa({sessionId:b,directory:e})){if(Nf()||o||ge()){s(b,e);return}c(e,{mode:`chat`,dedupeKey:`session:${b}`,label:f||g||u(`contextPanel.mode.chat`),readOnly:!0})}})},children:u(`chat.messageBody.subtask.openSession`)})}):null,t[34]=g,t[35]=f,t[36]=a,t[37]=o,t[38]=c,t[39]=l,t[40]=s,t[41]=u,t[42]=b,t[43]=M):M=t[43];let N;return t[44]!==k||t[45]!==A||t[46]!==j||t[47]!==M?(N=(0,$.jsxs)(`div`,{className:`mt-2`,children:[k,A,j,M]}),t[44]=k,t[45]=A,t[46]=j,t[47]=M,t[48]=N):N=t[48],N},CM=e=>{let t=(0,pd.c)(34),{notification:n}=e,r=Hl(),i=q(IM),{isMobile:a}=qs(),{t:o}=Yt(),s;t[0]!==r||t[1]!==a?(s=r&&!a&&!ge(),t[0]=r,t[1]=a,t[2]=s):s=t[2];let c=!!s,l;t[3]!==n.state||t[4]!==o?(l=n.state===`completed`?o(`chat.messageBody.subagent.completed`):n.state===`error`?o(`chat.messageBody.subagent.error`):o(`chat.messageBody.subagent.cancelled`),t[3]=n.state,t[4]=o,t[5]=l):l=t[5];let u=l,d=n.state===`completed`?o(`chat.messageBody.subagent.completedDescription`):n.state===`error`?o(`chat.messageBody.subagent.errorDescription`):o(`chat.messageBody.subagent.cancelledDescription`),f=n.description||d,p=J(()=>{!c||!r||i(r,{mode:`chat`,dedupeKey:`session:${n.sessionID}`,label:f,readOnly:!0})}),m;t[6]===p?m=t[7]:(m=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),p())},t[6]=p,t[7]=m);let h=J(m),g=c&&`cursor-pointer hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]`,_;t[8]===g?_=t[9]:(_=Y(`mt-2 flex min-w-0 gap-2.5 rounded-[var(--radius-lg)] border border-border/60 bg-muted/20 px-3 py-2.5`,g),t[8]=g,t[9]=_);let v=c?`button`:void 0,y=c?0:void 0,b=c?o(`chat.messageBody.subagent.openSession`,{label:f}):void 0,x=c?p:void 0,S=c?h:void 0,C;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(C=(0,$.jsx)(`span`,{className:`mt-0.5 flex size-6 flex-shrink-0 items-center justify-center rounded-md bg-foreground/5 text-muted-foreground`,children:(0,$.jsx)(Z,{name:`robot-2`,className:`size-3.5`})}),t[10]=C):C=t[10];let w;t[11]===f?w=t[12]:(w=(0,$.jsx)(`span`,{className:`typography-meta min-w-0 flex-1 truncate font-semibold text-foreground/90`,children:f}),t[11]=f,t[12]=w);let T=n.state===`completed`?`bg-[var(--status-success-background)] text-[var(--status-success)]`:n.state===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`,E;t[13]===T?E=t[14]:(E=Y(`inline-flex h-5 flex-shrink-0 items-center rounded px-1.5 text-[11px] leading-none`,T),t[13]=T,t[14]=E);let D;t[15]!==u||t[16]!==E?(D=(0,$.jsx)(`span`,{className:E,children:u}),t[15]=u,t[16]=E,t[17]=D):D=t[17];let O;t[18]!==w||t[19]!==D?(O=(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[w,D]}),t[18]=w,t[19]=D,t[20]=O):O=t[20];let k;t[21]===n.body?k=t[22]:(k=n.body?(0,$.jsx)(`div`,{className:`typography-meta mt-1 max-h-16 overflow-clip text-muted-foreground [&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,children:(0,$.jsx)(gl,{content:n.body,variant:`tool`,enableFileReferences:!1})}):null,t[21]=n.body,t[22]=k);let A;t[23]!==O||t[24]!==k?(A=(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[O,k]}),t[23]=O,t[24]=k,t[25]=A):A=t[25];let j;return t[26]!==S||t[27]!==A||t[28]!==_||t[29]!==v||t[30]!==y||t[31]!==b||t[32]!==x?(j=(0,$.jsxs)(`div`,{className:_,role:v,tabIndex:y,"aria-label":b,onClick:x,onKeyDown:S,children:[C,A]}),t[26]=S,t[27]=A,t[28]=_,t[29]=v,t[30]=y,t[31]=b,t[32]=x,t[33]=j):j=t[33],j},wM={background:`transparent`,backgroundColor:`transparent`},TM=e=>{let t=(0,pd.c)(36),{part:n}=e,[r,i]=Q.useState(!1),[a,o]=Q.useState(!1),s=Q.useRef(null),{t:c}=Yt(),l;t[0]===n.shellAction?l=t[1]:(l=typeof n.shellAction?.command==`string`?n.shellAction.command.trim():``,t[0]=n.shellAction,t[1]=l);let u=l,d=typeof n.shellAction?.output==`string`?n.shellAction.output:``,f;t[2]===n.shellAction?f=t[3]:(f=typeof n.shellAction?.status==`string`?n.shellAction.status.trim().toLowerCase():``,t[2]=n.shellAction,t[3]=f);let p=f,m;t[4]===d?m=t[5]:(m=d.trim(),t[4]=d,t[5]=m);let h=m.length>0,g;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>{s.current!==null&&typeof window<`u`&&(window.clearTimeout(s.current),s.current=null)},t[6]=g):g=t[6];let _=J(g),v,y;t[7]===_?(v=t[8],y=t[9]):(v=()=>()=>{_()},y=[_],t[7]=_,t[8]=v,t[9]=y),Q.useEffect(v,y);let b;t[10]!==_||t[11]!==h||t[12]!==d?(b=async()=>{h&&(await Jt(d)).ok&&(_(),o(!0),typeof window<`u`&&(s.current=window.setTimeout(()=>{o(!1),s.current=null},2e3)))},t[10]=_,t[11]=h,t[12]=d,t[13]=b):b=t[13];let x=J(b),S;t[14]===c?S=t[15]:(S=c(`chat.messageBody.shellCommand.title`),t[14]=c,t[15]=S);let C;t[16]===S?C=t[17]:(C=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:S}),t[16]=S,t[17]=C);let w;t[18]===p?w=t[19]:(w=p?(0,$.jsx)(`span`,{className:Y(`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none`,p===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`),children:p}):null,t[18]=p,t[19]=w);let T;t[20]!==w||t[21]!==C?(T=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[C,w]}),t[20]=w,t[21]=C,t[22]=T):T=t[22];let E;t[23]===u?E=t[24]:(E=u?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 overflow-x-auto font-mono`,children:(0,$.jsx)(bu,{language:`bash`,code:u,codeStyle:wM,wrap:!0})}):null,t[23]=u,t[24]=E);let D;t[25]!==a||t[26]!==x||t[27]!==r||t[28]!==h||t[29]!==d||t[30]!==c?(D=h?(0,$.jsxs)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 flex-wrap`,children:[(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>i(LM),children:c(r?`chat.messageBody.shellCommand.hideOutput`:`chat.messageBody.shellCommand.showOutput`)}),(0,$.jsx)(`button`,{type:`button`,className:`inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,onClick:()=>{x()},"aria-label":c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),title:c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),children:a?(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5`}):(0,$.jsx)(Z,{name:`file-copy`,className:`h-3.5 w-3.5`})})]}),r?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85`,children:(0,$.jsx)(bu,{language:`bash`,code:d,codeStyle:wM,wrap:!0})}):null]}):null,t[25]=a,t[26]=x,t[27]=r,t[28]=h,t[29]=d,t[30]=c,t[31]=D):D=t[31];let O;return t[32]!==T||t[33]!==E||t[34]!==D?(O=(0,$.jsxs)(`div`,{className:`mt-2`,children:[T,E,D]}),t[32]=T,t[33]=E,t[34]=D,t[35]=O):O=t[35],O},EM=e=>{let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`},DM=(e,t)=>{if(t&&typeof t==`object`)return{output:typeof t.output==`number`&&Number.isFinite(t.output)?Math.max(0,t.output):0,reasoning:typeof t.reasoning==`number`&&Number.isFinite(t.reasoning)?Math.max(0,t.reasoning):0};for(let t of e){let e=t.tokens;if(!(!e||typeof e!=`object`))return{output:typeof e.output==`number`&&Number.isFinite(e.output)?Math.max(0,e.output):0,reasoning:typeof e.reasoning==`number`&&Number.isFinite(e.reasoning)?Math.max(0,e.reasoning):0}}return{output:0,reasoning:0}},OM=Q.memo(({sessionId:e,messageId:t,parts:n,sourceParts:r,messageCreatedAt:i,isMobile:a,alwaysShowActions:o=a,hasTouchInput:s,hasTextContent:c,onCopyMessage:l,copiedMessage:u,onShowPopup:d,agentMention:f,onEdit:p,onRevert:m,onFork:h,pendingMessageAction:g,editing:_,editStaged:v,onCancelEdit:y,userActionsMode:b=`inline`,stickyUserHeaderEnabled:x=!0})=>{let{locale:S,t:C}=Yt(),w=Fb(),T=Qy(Zy()),E=q(e=>e.timeFormatPreference),[D,O]=Q.useState(!1),k=Q.useRef(null),A=Q.useMemo(()=>n.filter(e=>e.type===`text`?!Dn(e):!!(yM(e)||bM(e))),[n]),j=Q.useMemo(()=>A.map(e=>Lr(e)?iE(qa(e)):void 0),[A]),M=f?.token,N=!1,P=!!l,F=!!u,I=!!(s??a),L=!!c,R=b!==`external-actions`,z=b!==`external-content`,B=x&&b===`inline`,V=J(()=>{k.current!==null&&typeof window<`u`&&(window.clearTimeout(k.current),k.current=null)}),H=J(()=>{!I||!P||!L||typeof window>`u`||(V(),O(!0),k.current=window.setTimeout(()=>{O(!1),k.current=null},1800))});Q.useEffect(()=>{L||(O(!1),V())},[V,L]);let ee=J(e=>{!l||!L||(e.stopPropagation(),e.preventDefault(),l(),I&&H())}),U=w===`mini-chat`||!T.fork?void 0:h,te=Q.useMemo(()=>{if(typeof i!=`number`||i<=0)return null;let e=PA(i,E);return e.length>0?e:null},[S,i,E]),W=Y(`group/user-actions`,a?b===`inline`?`flex items-center justify-end pt-2 pb-3`:x?`flex h-9 items-start justify-end pt-0`:`flex h-11 items-start justify-end pt-0`:b===`inline`?`absolute top-full left-0 right-0 z-10 pt-5`:`flex h-8 items-start justify-end pt-2`),ne=!_&&v&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsxs)(`div`,{className:Y(rM,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-auto opacity-100`),"data-message-action-group":`true`,children:[(0,$.jsxs)(`span`,{className:Y(aM,`text-primary`),"aria-live":`polite`,children:[(0,$.jsx)(Z,{weight:sM,name:`edit`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:C(`chat.messageBody.actions.editStaged`)})]}),y?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.cancelEdit`),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),y()},children:(0,$.jsx)(Z,{weight:sM,name:`close`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.cancelEdit`)})]}):null]})}):null,G=(_&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsx)(`div`,{className:Y(rM,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-none opacity-100`),children:(0,$.jsx)(`span`,{className:Y(aM,`animate-text-shimmer`),"aria-live":`polite`,children:C(`chat.messageBody.actions.editing`)})})}):null)??ne??((P&&L||p||m||U)&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsxs)(`div`,{className:Y(rM,`justify-end`,!a&&b===`inline`&&`translate-x-5`,o?`pointer-events-auto opacity-100`:`pointer-events-none opacity-0 transition-opacity duration-150 group-hover/message:pointer-events-auto group-hover/message:opacity-100 group-hover/user-actions:pointer-events-auto group-hover/user-actions:opacity-100 group-hover/user-shell:pointer-events-auto group-hover/user-shell:opacity-100`),"data-message-action-group":`true`,children:[te?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:Y(aM,`mr-1`),"aria-label":`Message time: ${te}`,children:[(0,$.jsx)(Z,{weight:sM,name:`time`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:te})]})}),(0,$.jsx)(Jo,{children:te})]}):null,m&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.revertAria`),"aria-busy":g===`revert`,disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),m()},children:(0,$.jsx)(Z,{weight:sM,name:g===`revert`?`loader-4`:`arrow-go-back`,className:Y(eM,g===`revert`&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.revert`)})]}),p&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.editAria`),disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),p()},children:(0,$.jsx)(Z,{weight:sM,name:`edit`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.edit`)})]}),U&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.forkAria`),"aria-busy":g===`fork`,disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),U()},children:(0,$.jsx)(Z,{weight:sM,name:g===`fork`?`loader-4`:`git-branch`,className:Y(eM,g===`fork`&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.fork`)})]}),P&&L&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":D||F?`true`:void 0,className:$j,"aria-label":C(`chat.messageBody.actions.copyMessageAria`),onPointerDown:e=>e.stopPropagation(),onClick:ee,onFocus:()=>O(!0),onBlur:()=>{F||O(!1)},children:F?(0,$.jsx)(Z,{weight:sM,name:`check`,className:Y(eM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(Z,{weight:sM,name:`file-copy`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.copyMessage`)})]})]})}):null);return R?(0,$.jsxs)(`div`,{className:`relative w-full group/message`,"data-user-message-body":`true`,style:Yj,onTouchStart:I&&P&&L?H:void 0,children:[(0,$.jsx)(`div`,{className:Y(`leading-relaxed text-foreground/90 text-base overflow-x-hidden`,B?`overflow-y-auto overscroll-contain scrollbar-none`:`overflow-y-hidden`),style:B?{maxHeight:`calc(var(--chat-scroll-height, 100dvh) * 0.4)`}:void 0,children:A.map((e,i)=>{if(yM(e))return(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(SM,{part:e})},e.id??`user-subtask-${i}`);if(bM(e))return(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(TM,{part:e})},e.id??`user-shell-${i}`);let o=j[i];if(o)return(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(CM,{notification:o})},e.id??`subagent-notification-${i}`);let s;return f&&M&&!N&&qa(e).includes(M)&&(s=f,N=!0),(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(FT,{part:e,messageId:t,isMobile:a,agentMention:s,messageParts:r??n})},e.id??`user-text-${i}`)})}),(0,$.jsx)(mg,{files:n,messageID:t,sessionID:e,onShowPopup:d,compact:!0}),G]}):(0,$.jsx)($.Fragment,{children:G})}),kM=Q.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,reviewTransferAction:r,ttsText:i,sessionId:a})=>{let{t:o}=Yt(),s=Fb(),c=Zy(),l=Qy(c),{isPlaying:u,play:d,stop:f}=mA(),p=Oa(e=>e.showMessageTTSButtons),m=Oa(e=>e.voiceProvider),[h,g]=Q.useState(!1),[_,v]=Q.useState(!1),[y,b]=Q.useState(!1),x=Q.useRef(null),S=Q.useRef(null),C=!!n,w=!!((c.sessionId||a)&&c.directory&&l.openSourceSession&&s!==`mini-chat`),T=J(()=>{x.current!==null&&typeof window<`u`&&(window.clearTimeout(x.current),x.current=null)}),E=J(()=>{S.current!==null&&typeof window<`u`&&(window.clearTimeout(S.current),S.current=null)});Q.useEffect(()=>()=>{T(),E()},[E,T]),Q.useEffect(()=>{(!e||!C)&&(g(!1),v(!1),T(),E())},[C,E,T,e]);let D=J(()=>{!t||!C||!e||typeof window>`u`||(T(),g(!0),x.current=window.setTimeout(()=>{g(!1),x.current=null},1800))}),O=J(async r=>{!n||!e||(r.stopPropagation(),r.preventDefault(),await n()!==!1&&(E(),v(!0),typeof window<`u`&&(S.current=window.setTimeout(()=>{v(!1),S.current=null},2e3)),t&&D()))}),k=J(async t=>{if(t.stopPropagation(),t.preventDefault(),!(!r||y||!e)){b(!0);try{await r.onClick()}finally{b(!1)}}}),A=J(e=>{e.stopPropagation(),e.preventDefault();let t=c.sessionId||a;!t||!c.directory||!c.openSourceSession||c.openSourceSession(t,c.directory)}),j=Q.useMemo(()=>u?o(`chat.messageBody.tts.stopSpeaking`):o(`chat.messageBody.tts.readAloudWithProvider`,{provider:m===`browser`?`Browser`:m===`openai`?`OpenAI`:m===`openai-compatible`?`Custom`:`Say`}),[u,o,m]),M=J(e=>{if(e.stopPropagation(),e.preventDefault(),u){f();return}i.trim()&&d(i)});return(0,$.jsxs)($.Fragment,{children:[n&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":h||_?`true`:void 0,className:Y($j,!e&&`opacity-50`),disabled:!e,"aria-label":o(`chat.messageBody.actions.copyMessageAria`),"aria-hidden":!e,onPointerDown:e=>e.stopPropagation(),onClick:e=>{O(e)},onFocus:()=>{e&&g(!0)},onBlur:()=>{_||g(!1)},children:_?(0,$.jsx)(Z,{weight:sM,name:`check`,className:Y(eM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(Z,{weight:sM,name:`file-copy`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:o(`chat.messageBody.actions.copyAnswer`)})]}),w?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":o(`chat.messageBody.actions.openSourceSessionAria`),onPointerDown:e=>e.stopPropagation(),onClick:A,children:(0,$.jsx)(Z,{weight:sM,name:`target`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:o(`chat.messageBody.actions.openSourceSession`)})]}):null,r&&s!==`mini-chat`&&l.reviewTransfer?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,size:`icon`,variant:`ghost`,disabled:y||!e,className:Y($j,(!e||y)&&`opacity-50`),"aria-label":r.ariaLabel,onPointerDown:e=>e.stopPropagation(),onClick:e=>{k(e)},children:y?(0,$.jsx)(Z,{weight:sM,name:`loader-4`,className:Y(eM,`animate-spin`)}):(0,$.jsx)(Z,{weight:sM,name:`arrow-left-right`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:r.tooltip})]}):null,s!==`mini-chat`&&p&&e&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:Y($j,u?`text-green-500`:`hover:text-foreground/80`),"aria-label":o(u?`chat.messageBody.tts.stopSpeaking`:`chat.messageBody.tts.readAloud`),onPointerDown:e=>e.stopPropagation(),onClick:M,children:u?(0,$.jsx)(Z,{weight:sM,name:`stop`,className:eM}):(0,$.jsx)(Z,{weight:sM,name:`volume-up`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:j})]})]})}),AM=Q.memo(({sessionId:e,messageId:t,parts:n,sourceParts:r,isMessageCompleted:i,messageFinish:a,messageCompletedAt:o,messageCreatedAt:s,messageTokens:c,isMobile:l,alwaysShowActions:u,hasTouchInput:d,expandedTools:f,onToggleTool:p,onShowPopup:m,streamPhase:h,allowAnimation:g,onContentChange:_,hasTextContent:v=!1,onCopyMessage:y,onAuxiliaryContentComplete:b,showReasoningTraces:x=!1,turnGroupingContext:S,errorMessage:C,errorVariant:w=`error`,reviewTransferDirection:T=null})=>{let{t:E,locale:D}=Yt(),O=Fb(),k=Qy(Zy()),A=h,j=Q.useRef(null),M=Q.useRef(null),N=h===`streaming`||h===`cooldown`,P=Q.useRef({messageId:t,experiencedStreamingOrCooldown:N});P.current.messageId===t?N&&(P.current.experiencedStreamingOrCooldown=!0):P.current={messageId:t,experiencedStreamingOrCooldown:N};let F=!!(d??l),I=!!(u??l),L=l?nM:tM,R=!i,z=Q.useMemo(()=>n.filter(e=>!Dn(e)).filter(e=>e.type!==`compaction`),[n]),B=Q.useMemo(()=>z.filter(e=>e.type===`tool`),[z]),V=Q.useMemo(()=>z.filter(e=>e.type===`text`),[z]),H=Q.useMemo(()=>Ln(V),[V]),ee=q(e=>e.openContextPreview),U=ge(),te=O===`mini-chat`,W=Q.useMemo(()=>{if(U||l||te)return null;for(let e of V){let t=e.text;if(typeof t!=`string`||t.length===0)continue;let n=Rl(t)[0];if(n)return n.includes(`0.0.0.0`)?n.replace(`0.0.0.0`,`127.0.0.1`):n}for(let e of B){let t=e.state,n=t&&typeof t.output==`string`?t.output:null;if(!n)continue;let r=Rl(n.replace(/\x1b\[[0-9;]*m/g,``))[0];if(r)return r.includes(`0.0.0.0`)?r.replace(`0.0.0.0`,`127.0.0.1`):r}return null},[V,l,te,U,B]),ne=X(e=>e.forkFromMessage),G=X(e=>e.forkTransition),re=X(e=>e.currentSessionId),ie=X(e=>e.getDirectoryForSession),K=Hl(),ae=T===`review-to-original`,oe=!l&&!U?T:null,se=Q.useMemo(()=>{let t=H.trim();if(!(!e||!K||!t||!oe))return oe===`review-to-original`?{ariaLabel:E(`chat.messageBody.actions.sendReviewFeedback`),tooltip:E(`chat.messageBody.actions.sendReviewFeedback`),onClick:async()=>{try{await or(e,K,t)}catch(e){console.error(`[review-flow] failed to send review feedback`,e)}}}:{ariaLabel:E(`chat.messageBody.actions.sendImplementationResponse`),tooltip:E(`chat.messageBody.actions.sendImplementationResponse`),onClick:async()=>{try{await Qi(e,K,t)}catch(e){console.error(`[review-flow] failed to send implementation response`,e)}}}},[H,K,oe,e,E]),[ce,le]=Q.useState(!1),ue=q(e=>e.chatRenderMode),de=q(e=>e.collapsibleThinkingBlocks),fe=q(e=>e.showSplitAssistantMessageActions),pe=q(e=>e.showAssistantTps),me=q(e=>e.timeFormatPreference),he=ue===`sorted`,_e=S?.isLastAssistantInTurn??!1,ve=a===`stop`,ye=(ve||i||!!C)&&(S?.isTurnSettled??!0),be=ve?`completed`:A,xe=B.length>0,Se=Q.useMemo(()=>B.some(e=>HD(e)),[B]),Ce=HD,we=VD,Te=P.current.experiencedStreamingOrCooldown,Ee=Q.useRef({messageId:t,initialized:!1,observedPartIds:new Set});Q.useEffect(()=>{if(Ee.current.messageId!==t&&(Ee.current={messageId:t,initialized:!1,observedPartIds:new Set}),!Te||!Cn())return;let n=Ee.current,r=!n.initialized;n.initialized=!0;for(let i of B){if(n.observedPartIds.has(i.id))continue;if(!gr(r,Ce(i))){n.observedPartIds.add(i.id);continue}let a=e??i.sessionID;a&&(n.observedPartIds.add(i.id),Nr({sessionID:a,messageID:t,partID:i.id,kind:`tool`}))}},[Te,Ce,t,e,B]);let De=Q.useMemo(()=>B.length===0||!Se&&B.every(e=>we(e)),[B,Se,we]),Oe=Q.useMemo(()=>z.filter(e=>e.type===`reasoning`),[z]),ke=Q.useMemo(()=>Oe.length===0||Oe.every(e=>typeof e.time?.end==`number`),[Oe]),Ae=typeof a!=`string`,je=Oe.length>0&&xe&&(Se||Ae||!De),Me=R||xe&&(Se||Ae||!De),Ne=R||je,Pe=xe||Oe.length>0,Fe=V.length===0,Ie=Pe&&Fe&&!Me&&!Ne&&De&&ke,Le=Q.useRef(!1),Re=Q.useRef(!1);Q.useEffect(()=>{Re.current=!1},[t]),Q.useEffect(()=>{if(!Ie){Le.current=!1;return}Le.current||(Le.current=!0,b?.())},[Ie,b]),Q.useEffect(()=>{if(R){Re.current=!1;return}if(xe){Re.current=!1;return}Oe.length!==0&&(Ne||!ke||Re.current||(Re.current=!0,_?.(`structural`)))},[R,xe,_,ke,Oe.length,Ne]);let ze=!!v&&!R,Be=J(async n=>{if(n.stopPropagation(),n.preventDefault(),!(!e||!t||ce||G)){le(!0);try{await ne(e,t)}finally{le(!1)}}}),Ve=Q.useMemo(()=>{let e=S?.activityParts;return!he||!e?[]:e},[he,S?.activityParts]),He=Q.useMemo(()=>{let e=S?.activityGroupSegments;return!he||!e?[]:e.filter(e=>e.anchorMessageId===t)},[he,t,S?.activityGroupSegments]),Ue=He.length>0,We=Q.useMemo(()=>{let e=new Map,t=new Map;return Ve.forEach(n=>{e.set(n.part,n);let r=n.part.id;typeof r==`string`&&r.length>0&&t.set(r,n)}),{get:n=>{let r=e.get(n);if(r)return r;let i=n.id;if(typeof i==`string`&&i.length>0)return t.get(i)}}},[Ve]),Ge=S?.toggleGroup,Ke=S?.activityPresentationKind===`compaction`,qe=S?.isGroupExpanded===!0,Je=he&&Ke&&!qe,Ye=he?S?.activityOwnerMessageId===t||Ue:!S?.activityOwnerMessageId||S.activityOwnerMessageId===t||Ue,Xe=he&&Ye&&(Ue||Ke)&&!!Ge,Ze=Uk(a,z),Qe={finish:a,parts:z,streamPhase:be,error:C,isLastAssistantInTurn:_e},$e=Jk(Qe),et=he&&Yk(Qe),tt=he&&!$e&&!(Ke&&qe),nt=!!C,rt=w===`info`?`information`:`error-warning`,it=w===`muted`,at=ze,ot=_e&&ye&&!Je&&(v||!!C||i),st=S?.diffStats?.hasDiffs===!0,ct=!te&&_e&&Ze&&ye&&!Je&&S?.diffStats?.hasDiffs===!0,lt=fe&&at&&!ot&&!he,ut=Q.useMemo(()=>(0,$.jsx)(kM,{hasCopyableText:ze,isTouchContext:F,onCopyMessage:y,ttsText:H,reviewTransferAction:se,sessionId:e}),[H,ze,F,y,se,e]),dt=Q.useMemo(()=>e=>{if(!fe||!he)return null;let t=qa(e.part).trim();return t?(0,$.jsx)(kM,{hasCopyableText:!0,isTouchContext:F,onCopyMessage:async()=>(await Jt(t)).ok,ttsText:t}):null},[he,F,fe]),ft=Q.useMemo(()=>{if(!lt)return-1;let e=-1;for(let t=0;t<z.length;t+=1){let n=z[t];!n||n.type!==`text`||tt||We.get(n)?.kind!==`justification`&&(e=t)}return e},[We,tt,lt,z]),pt=lt&&ft<0,mt=Q.useMemo(()=>{let n=[];if(Xe&&Ge&&S){let e=(e,t,r=t)=>{n.push((0,$.jsx)(`div`,{children:(0,$.jsx)(Jj,{parts:t,materializationParts:r,isExpanded:S.isGroupExpanded===!0,collapsedPreviewCount:0,completionDisposition:S.completionDisposition,activityPresentationKind:S.activityPresentationKind,durationMs:S.durationMs,startedAt:S.userMessageCreatedAt,onToggle:Ge,isMobile:l,expandedTools:f,onToggleTool:p,onShowPopup:m,onContentChange:_,streamPhase:be,showHeader:!0,diffStats:S.diffStats,renderJustificationActions:dt})},`progressive-group-${e}`))};He.length>0?He.forEach(t=>{let n=x?t.parts:t.parts.filter(e=>e.kind!==`reasoning`);e(t.id,n,t.parts)}):Ke&&e(`${t}:compaction-status`,[])}let r=0;for(;r<z.length;){let i=z[r];if(i.type===`text`){let a=We.get(i);if(tt){r+=1;continue}if(Je){r+=1;continue}if(a?.kind===`justification`){r+=1;continue}n.push((0,$.jsx)(`div`,{ref:M,"data-message-text-export-source":`true`,children:(0,$.jsx)(xk,{part:i,sessionId:e,messageId:t,streamPhase:be,chatRenderMode:ue,allowSortedFinalStreaming:et,hasStreamingHapticLifecycle:Te,onContentChange:_,onShowPopup:m})},`assistant-text-${t}-${i.id??r}`)),lt&&r===ft&&n.push((0,$.jsx)(`div`,{className:l?Qj:Zj,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:rM,"data-message-action-group":`true`,children:ut})},`message-actions-${t}`)),r++;continue}if(i.type===`reasoning`){if(We.get(i)?.kind===`reasoning`){r+=1;continue}if(!qa(i).trim()){r+=1;continue}x&&(de?n.push((0,$.jsx)(`div`,{className:Ev(l),children:(0,$.jsx)(Nk,{part:i,messageId:t,streamPhase:be,onContentChange:_})},`reasoning-${t}-${i.id??r}`)):n.push((0,$.jsx)(xk,{part:i,sessionId:e,messageId:t,streamPhase:be,chatRenderMode:ue,hasStreamingHapticLifecycle:Te,onContentChange:_,onShowPopup:m},`reasoning-${t}-${i.id??r}`))),r++;continue}if(i.type===`tool`){let e=i,a=e.tool?.toLowerCase()??``;if(he&&!Ye){r+=1;continue}if(We.get(i)?.kind===`tool`){r+=1;continue}if(BD(a)){let e=rj(z,r,e=>e.type!==`tool`||We.get(e)?.kind===`tool`?``:e.tool);if(e.items.length>0){let i=e.items.map((e,n)=>{let i=e;return{id:i.id,turnId:``,messageId:t,partIndex:r+n,part:i,kind:`tool`}});n.push((0,$.jsx)(oj,{activities:i,isMobile:l,isTurnLive:be!==`completed`,hasFollowingOtherType:tj(z,e.end,e=>({type:e.type,toolName:e.type===`tool`?e.tool:void 0})),children:i.map(e=>{let n=e.part.tool?.toLowerCase()??``;return LD(n)?(0,$.jsx)(Bj,{toolName:n,activities:[e],isMobile:l,animateTailText:!1},e.id):(0,$.jsx)(tk,{part:e.part,messageId:t,isExpanded:f.has(e.part.id),onToggle:p,isMobile:l,alwaysShowActions:I,onContentChange:_,onShowPopup:m,animateTailText:!1},e.id)})},`context-tools-${i[0].id}`)),r=e.end;continue}}if(RD(a)){let e=sj(z,r,e=>e.type!==`tool`||We.get(e)?.kind===`tool`?``:e.tool);if(e.items.length>0){let i=e.items.map((e,n)=>{let i=e;return{id:i.id,turnId:``,messageId:t,partIndex:r+n,part:i,kind:`tool`}});n.push((0,$.jsx)(fj,{activities:i,isMobile:l,children:i.map(e=>(0,$.jsx)(Bj,{toolName:e.part.tool?.toLowerCase()??``,activities:[e],isMobile:l,animateTailText:!1},e.id))},`skill-tools-${i[0].id}`)),r=e.end;continue}}if(PD(a)){n.push((0,$.jsx)(`div`,{className:Ev(l),children:(0,$.jsx)(tk,{part:e,messageId:t,isExpanded:f.has(e.id),onToggle:p,isMobile:l,alwaysShowActions:I,onContentChange:_,onShowPopup:m,animateTailText:!1})},`tool-${e.id}`)),r++;continue}n.push((0,$.jsx)(`div`,{className:Ev(l),children:(0,$.jsx)(Bj,{toolName:a,activities:[{id:e.id,turnId:``,messageId:t,partIndex:r,part:e,kind:`tool`}],isMobile:l,animateTailText:!1})},`static-tools-${e.id}`)),r++;continue}r++}return n},[We,He,I,ue,de,0,f,Je,Ke,l,Ye,he,ft,t,ut,dt,e,_,m,p,Xe,lt,be,Te,x,tt,et,Ge,S,z]),ht=Q.useMemo(()=>{if(!_e||!ye)return;let e=S?.durationMs;if(!(typeof e!=`number`||e<=0))return EM(e)},[_e,ye,S?.durationMs]),gt=Q.useMemo(()=>{let e=typeof o==`number`&&o>0?o:typeof s==`number`&&s>0?s:null;if(e===null)return null;let t=PA(e,me);return t.length>0?t:null},[o,s,me,D]),_t=Q.useMemo(()=>{if(!pe||!_e||!ye)return null;let e=r??n,t=DM(e,c),i=zA({createdAt:s,completedAt:o,fallbackDurationMs:S?.durationMs,outputTokens:t.output,reasoningTokens:t.reasoning,parts:e});if(i===null)return null;let a=BA(i);return a.length>0?a:null},[pe,_e,ye,n,r,c,s,o,S?.durationMs]),vt=(0,$.jsxs)($.Fragment,{children:[!te&&!l&&!U&&W?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":E(`chat.messageBody.actions.openPreviewAria`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let e=K??(re?ie(re):null);e&&ee(e,W)},children:(0,$.jsx)(Z,{weight:sM,name:`global`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:E(`chat.messageBody.actions.openPreview`)})]}):null,!te&&!ae&&k.fork?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,size:`icon`,variant:`ghost`,className:$j,"aria-label":E(`chat.messageBody.actions.forkAria`),"aria-busy":ce,disabled:ce||!!G,onPointerDown:e=>e.stopPropagation(),onClick:e=>{Be(e)},children:(0,$.jsx)(Z,{weight:sM,name:ce?`loader-4`:`git-branch`,className:Y(eM,ce&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:E(`chat.messageBody.actions.fork`)})]}):null]});return(0,$.jsxs)(`div`,{ref:j,"data-message-text-export-root":`true`,className:Y(`relative w-full group/message`),style:Yj,children:[(0,$.jsx)(AA,{containerRef:j}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`message-content-text leading-relaxed text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0`,children:[mt,nt&&(0,$.jsx)(Xl,{children:it?(0,$.jsxs)(`div`,{role:`status`,className:`my-1.5 flex max-w-full items-center gap-1.5 break-words typography-meta text-muted-foreground`,children:[(0,$.jsx)(Z,{name:`stop-circle`,className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`min-w-0`,children:C})]}):(0,$.jsxs)(`div`,{className:Y(`group/assistant-text relative flow-root my-1.5 break-words max-w-full`,w===`info`?Y(`inline-flex w-fit max-w-full border border-[var(--status-info-border)]/45 bg-[var(--status-info-background)]/40`,l?`items-start gap-1.5 rounded-lg px-2.5 py-1.5`:Y(`items-center gap-1.5`,`rounded-lg px-2 py-0.5`)):`mt-3 flex items-center gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3`),children:[w===`info`&&l?(0,$.jsx)(`span`,{className:`inline-flex h-5 w-3.5 shrink-0 items-center justify-center translate-y-[2px]`,"aria-hidden":`true`,children:(0,$.jsx)(Z,{name:rt,weight:sM,className:Y(eM,`text-[var(--status-info)]/80`)})}):(0,$.jsx)(Z,{name:rt,weight:w===`info`?sM:void 0,className:Y(`shrink-0`,w===`info`?Y(eM,`text-[var(--status-info)]/80`):`h-4 w-4 text-[var(--status-error)]`)}),(0,$.jsx)(`div`,{className:Y(`min-w-0 break-words`,w===`info`?Y(`text-muted-foreground [&_.markdown-content]:text-muted-foreground [&_p]:m-0`,`[&_.markdown-content]:!leading-5`,l?`[&_.markdown-content]:!text-[length:var(--text-meta)]`:`[&_.markdown-content]:!text-[13px]`):`flex-1`),children:(0,$.jsx)(gl,{content:C??``,onShowPopup:m,className:`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,enableFileReferences:!1})})]})},`assistant-error`)]}),ct&&S?.diffStats?(0,$.jsx)(vM,{fileCount:S.diffStats.files,changedFiles:S.changedFiles,turnId:S.turnId,isLatestTurn:S.isLatestTurn,isMobile:l}):null,(0,$.jsx)(mg,{files:n,messageID:t,sessionID:e,onShowPopup:m}),pt&&(0,$.jsx)(`div`,{className:Y(l?Qj:Zj),"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:rM,"data-message-action-group":`true`,children:ut})}),ot&&(0,$.jsxs)(`div`,{className:L,"data-message-footer":`true`,style:Xj,children:[(0,$.jsxs)(`div`,{className:rM,"data-message-action-group":`true`,children:[ut,vt]}),_t||ht||gt?(0,$.jsxs)(`div`,{className:iM,children:[_t?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:aM,"aria-label":E(`chat.messageBody.meta.tpsAria`,{rate:_t}),children:[(0,$.jsx)(Z,{weight:sM,name:`pulse`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:_t})]})}),(0,$.jsx)(Jo,{children:E(`chat.messageBody.meta.tpsTooltip`)})]}):null,ht?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:aM,children:[(0,$.jsx)(Z,{weight:sM,name:`hourglass`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:ht})]})}),(0,$.jsx)(Jo,{children:ht})]}):null,gt?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:aM,"aria-label":`Message time: ${gt}`,children:[(0,$.jsx)(Z,{weight:sM,name:`time`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:gt})]})}),(0,$.jsx)(Jo,{children:gt})]}):null]}):null,!te&&_e&&ve&&!st?(0,$.jsx)(Lk,{activityParts:S?.activityParts}):null]})]})]})}),jM=Q.memo(e=>{let t=(0,pd.c)(28),n,r;if(t[0]===e?(n=t[1],r=t[2]):({isUser:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),n){let e;return t[3]!==r.agentMention||t[4]!==r.alwaysShowActions||t[5]!==r.copiedMessage||t[6]!==r.editStaged||t[7]!==r.editing||t[8]!==r.hasTextContent||t[9]!==r.hasTouchInput||t[10]!==r.isMobile||t[11]!==r.messageCreatedAt||t[12]!==r.messageId||t[13]!==r.onCancelEdit||t[14]!==r.onCopyMessage||t[15]!==r.onEdit||t[16]!==r.onFork||t[17]!==r.onRevert||t[18]!==r.onShowPopup||t[19]!==r.parts||t[20]!==r.pendingMessageAction||t[21]!==r.sessionId||t[22]!==r.sourceParts||t[23]!==r.stickyUserHeaderEnabled||t[24]!==r.userActionsMode?(e=(0,$.jsx)(OM,{sessionId:r.sessionId,messageId:r.messageId,parts:r.parts,sourceParts:r.sourceParts,messageCreatedAt:r.messageCreatedAt,isMobile:r.isMobile,alwaysShowActions:r.alwaysShowActions,hasTouchInput:r.hasTouchInput,hasTextContent:r.hasTextContent,onCopyMessage:r.onCopyMessage,copiedMessage:r.copiedMessage,onShowPopup:r.onShowPopup,agentMention:r.agentMention,onEdit:r.onEdit,onRevert:r.onRevert,onFork:r.onFork,pendingMessageAction:r.pendingMessageAction,editing:r.editing,editStaged:r.editStaged,onCancelEdit:r.onCancelEdit,userActionsMode:r.userActionsMode,stickyUserHeaderEnabled:r.stickyUserHeaderEnabled}),t[3]=r.agentMention,t[4]=r.alwaysShowActions,t[5]=r.copiedMessage,t[6]=r.editStaged,t[7]=r.editing,t[8]=r.hasTextContent,t[9]=r.hasTouchInput,t[10]=r.isMobile,t[11]=r.messageCreatedAt,t[12]=r.messageId,t[13]=r.onCancelEdit,t[14]=r.onCopyMessage,t[15]=r.onEdit,t[16]=r.onFork,t[17]=r.onRevert,t[18]=r.onShowPopup,t[19]=r.parts,t[20]=r.pendingMessageAction,t[21]=r.sessionId,t[22]=r.sourceParts,t[23]=r.stickyUserHeaderEnabled,t[24]=r.userActionsMode,t[25]=e):e=t[25],e}let i;return t[26]===r?i=t[27]:(i=(0,$.jsx)(AM,{...r}),t[26]=r,t[27]=i),i});function MM(e){return e.openContextPanelTab}function NM(e){return e.setCurrentSession}function PM(e){return e.openContextPanelTab}function FM(e){return!e}function IM(e){return e.openContextPanelTab}function LM(e){return!e}var RM=e=>{let t=e,n=t?.clientRole,r=t?.role;return t?.userMessageMarker===!0||n===`user`||r===`user`||t?.origin===`user`||t?.source===`user`?{role:`user`,isUser:!0}:{role:n||r||`assistant`,isUser:!1}},zM=(e,t,n)=>e===`active`||n?.isLastTurn&&n.hasConfirmedFinalBody!==!0?!0:t===`summary`,BM=e=>!e,VM=e=>e.completionDisposition===`active`?e.isLastTurn&&e.sessionIsWorking?{completionDisposition:`active`,durationMs:e.durationMs}:{completionDisposition:`abnormal`,durationMs:e.durationMs}:{completionDisposition:e.completionDisposition,durationMs:e.durationMs},HM=e=>!(e.completionDisposition===`active`||e.isLastTurn&&e.sessionIsWorking&&!e.hasConfirmedSettledAssistant),UM=e=>e.isWorking?!0:e.isInActiveTurn?e.headerCompletionDisposition!==`normal`&&e.headerCompletionDisposition!==`abnormal`:!1,WM=e=>e.turnCompletionDisposition===`active`&&(e.isLastTurn||e.hasAssistantMessages)?`active`:e.headerPresentationDisposition,GM=`Authentication failed for this provider. Please re-authenticate and retry.`,KM=e=>{if(typeof e!=`string`)return!1;let t=e.toLowerCase().trim();if(!t)return!1;if(t.includes(`token refresh failed`)||t.includes(`unauthorized`)||t.includes(`invalid token`)||t.includes(`expired token`))return!0;let n=t.includes(`oauth`),r=t.includes(`failed`)||t.includes(`invalid`)||t.includes(`expired`);if(n&&r)return!0;let i=/\b401\b/.test(t),a=t.includes(`auth`)||t.includes(`token`)||t.includes(`unauthorized`);return i&&a};function qM(e,t){if(!e||typeof e!=`object`)return;let n=e,r=typeof n.data?.message==`string`?n.data.message:void 0,i=typeof n.message==`string`?n.message:void 0,a=typeof n.name==`string`?n.name:void 0,o=r||i||a;if(o)return a===`SessionRetry`?{text:`Opencode failed to send a message. Retry attempt info: \n\`${o}\``,variant:`info`}:KM(o)?{text:GM,variant:`error`}:a===`MessageAbortedError`||o.trim().toLowerCase()===`aborted`?{text:t,variant:`muted`}:{text:`Opencode failed to send message with error:\n\`${o}\``,variant:`error`}}var JM=_l(()=>Et(()=>import(`./ToolOutputDialog-CQs_7KYT.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52]))),YM=4e3,XM=new Map,ZM=new Map,QM=new Set([`bash`,`shell`,`cmd`,`terminal`]),$M=e=>{if(typeof e!=`string`)return``;let t=e.trim().toLowerCase();if(!t)return``;let n=t.replace(/:\d+$/,``);if(!n.includes(`.`))return n;let r=n.split(`.`).filter(Boolean);return r[r.length-1]??n},eN=e=>{let t=XM.get(e);return t?new Set(t):new Set},tN=(e,t)=>{if(XM.size>=YM&&!XM.has(e)){let e=XM.keys().next().value;typeof e==`string`&&XM.delete(e)}XM.set(e,new Set(t))},nN=e=>{let t=ZM.get(e);return t?new Set(t):new Set},rN=(e,t)=>{if(ZM.size>=YM&&!ZM.has(e)){let e=ZM.keys().next().value;typeof e==`string`&&ZM.delete(e)}ZM.set(e,new Set(t))},iN=200,aN=new Map,oN=e=>aN.get(e),sN=(e,t)=>{if(!t.agent&&!t.provider&&!t.model)return;let n=aN.get(e);if(!(n&&n.agent===t.agent&&n.provider===t.provider&&n.model===t.model)){if(aN.size>=iN&&!aN.has(e)){let e=aN.keys().next().value;typeof e==`string`&&aN.delete(e)}aN.set(e,t)}};function cN(e){let t=(0,pd.c)(3),[n,r]=Q.useState(e),i,a;return t[0]===e?(i=t[1],a=t[2]):(i=()=>{e!=null&&r(e)},a=[e],t[0]=e,t[1]=i,t[2]=a),Q.useEffect(i,a),e??n}var lN=(e,t)=>{if(typeof e==`object`&&e)return e[t]},uN=Q.memo(({message:e,previousMessage:t,nextMessage:n,onContentChange:r,animationHandlers:i,turnGroupingContext:a,assistantHeaderMessageId:o,turnOwnsAssistantHeader:s=!1,isInActiveTurn:c=!1,activeStreamingPhase:l=null,animateUserOnMount:u=!1,onUserAnimationConsumed:d,reviewTransferDirection:f=null})=>{let{t:p}=Yt(),{isMobile:m,isTablet:h,hasTouchInput:g}=qs(),_=Zy(),v=Qy(_),y=m||h,b=Q.useRef(null),x=X(e=>e.currentSessionId),S=Hr(e=>e.getAgentModelForSession),C=Hr(e=>e.getSessionModelSelection),w=X(e=>e.revertToMessage),T=X(e=>e.editMessagePreservingChanges),E=X(e=>e.forkFromMessage),D=X(t=>t.messageEditCommitting?.messageId===e.info.id&&t.messageEditCommitting?.sessionId===e.info.sessionID),O=X(t=>t.stagedMessageEdit?.messageId===e.info.id&&t.stagedMessageEdit?.sessionId===e.info.sessionID),k=X(e=>e.clearStagedMessageEdit);pt(`ui.chat_message.render`),c&&pt(`ui.chat_message.render.streaming`);let A=Oa(e=>e.providers),{showReasoningTraces:j,stickyUserHeader:M,chatRenderMode:N,showExpandedBashTools:P}=q(He(e=>({showReasoningTraces:e.showReasoningTraces,stickyUserHeader:e.stickyUserHeader,chatRenderMode:e.chatRenderMode,showExpandedBashTools:e.showExpandedBashTools})));Q.useEffect(()=>{x&&CT.getInstance().recordSessionStart(x)},[x]);let[F,I]=Q.useState(null),[L,R]=Q.useState(!1),[z,B]=Q.useState(null),V=Q.useRef(null),[H,ee]=Q.useState(()=>eN(e.info.id)),[U,te]=Q.useState(()=>nN(e.info.id)),[W,ne]=Q.useState({open:!1,title:``,content:``});Q.useEffect(()=>{ee(eN(e.info.id)),te(nN(e.info.id))},[e.info.id]);let G=Q.useMemo(()=>RM(e.info),[e.info]).isUser,re=G&&(m||!M),ie=G&&!m&&M&&!re,K=e.info.sessionID,{currentContextAgent:ae,savedSessionAgentSelection:oe}=Hv(He(e=>({currentContextAgent:c&&K?e.currentAgentContext.get(K):void 0,savedSessionAgentSelection:c&&K?e.sessionAgentSelections.get(K):void 0}))),se=Q.useMemo(()=>xn(e.sourceParts??e.parts),[e.parts,e.sourceParts]),ce=Q.useMemo(()=>G?_n(se):xn(e.parts),[G,e.parts,se]),le=Q.useMemo(()=>{if(G||!t)return null;let e=lN(t.info,`clientRole`),n=lN(t.info,`role`);if((typeof e==`string`?e:typeof n==`string`?n:void 0)!==`user`)return null;let r=lN(t.info,`mode`),i=lN(t.info,`agent`),a=lN(t.info,`providerID`),o=lN(t.info,`modelID`),s=lN(t.info,`model`),c=typeof s==`object`&&s?s.variant:void 0,l=lN(t.info,`variant`),u=c??l,d=typeof s==`object`&&s?s.providerID:void 0,f=typeof s==`object`&&s?s.modelID:void 0,p=typeof r==`string`&&r.trim().length>0?r:typeof i==`string`&&i.trim().length>0?i:void 0,m=typeof a==`string`&&a.trim().length>0?a:typeof d==`string`&&d.trim().length>0?d:void 0,h=typeof o==`string`&&o.trim().length>0?o:typeof f==`string`&&f.trim().length>0?f:void 0,g=typeof u==`string`&&u.trim().length>0?u:void 0;return!p&&!m&&!h&&!g?null:{agentName:p,providerId:m,modelId:h,variant:g}},[G,t]),ue=Q.useMemo(()=>{if(G)return;let t=lN(e.info,`mode`);if(typeof t==`string`&&t.trim().length>0)return t;let n=lN(e.info,`agent`);if(typeof n==`string`&&n.trim().length>0)return n;if(le?.agentName)return le.agentName;if(K)return ae||(oe??void 0)},[G,e.info,le,K,ae,oe]),de=G?null:lN(e.info,`providerID`),fe=G?null:lN(e.info,`modelID`),pe=Q.useMemo(()=>{if(G||!K)return null;if(le?.providerId&&le?.modelId)return{providerId:le.providerId,modelId:le.modelId};if(ue){let e=S(K,ue);if(e?.providerId&&e?.modelId)return e}let e=C(K);return e?.providerId&&e?.modelId?e:null},[G,K,ue,le,S,C]),me=Q.useMemo(()=>G?null:typeof de==`string`&&de.trim().length>0?de:pe?.providerId??null,[G,de,pe]),he=Q.useMemo(()=>G?null:typeof fe==`string`&&fe.trim().length>0?fe:pe?.modelId??null,[G,fe,pe]),ge=e.info.id?oN(e.info.id):void 0;G||sN(e.info.id,{agent:ue,provider:me??void 0,model:he??void 0});let _e=ue??ge?.agent,ve=me??ge?.provider??null,ye=he??ge?.model??null,be=Q.useMemo(()=>{if(G)return;let e=ve&&A.length>0?A.find(e=>e.id===ve):void 0;return ri(e,ye)||void 0},[G,ve,ye,A]),xe=Q.useMemo(()=>{if(G||!me||!he)return!1;let e=A.find(e=>e.id===me);if(!e?.models||!Array.isArray(e.models))return!1;let t=e.models.find(e=>e.id===he)?.variants;return!!(t&&Object.keys(t).length>0)},[G,he,me,A]),Se=cN(_e),Ce=cN(ve??void 0),we=cN(ye??void 0),Te=cN(be),Ee=Se??void 0,De=Ce??null,Oe=we??null,ke=Te??void 0,Ae=Q.useMemo(()=>{let t=e.info.time;return typeof t?.completed==`number`?t.completed:null},[e.info.time]),je=Q.useMemo(()=>{let t=e.info.time;return typeof t?.created==`number`?t.created:null},[e.info.time]),Me=Q.useMemo(()=>G?!0:!!(Ae&&Ae>0),[G,Ae]),Ne=Q.useMemo(()=>{let t=e.info.finish;return typeof t==`string`?t:void 0},[e.info]),Pe=Q.useMemo(()=>{if(G)return null;let t=e.info.tokens;return!t||typeof t!=`object`?null:{output:typeof t.output==`number`?t.output:void 0,reasoning:typeof t.reasoning==`number`?t.reasoning:void 0}},[G,e.info]),Fe=Q.useMemo(()=>jr(ce,{includeReasoning:j}),[ce,j]),Ie=Q.useMemo(()=>G?Fe:!Me&&N===`sorted`?[]:Fe,[N,Me,G,Fe]),Le=Q.useMemo(()=>G?[]:Fe.filter(e=>e.type===`text`),[G,Fe]),Re=Q.useMemo(()=>G?[]:Fe.filter(e=>e.type===`tool`),[G,Fe]),ze=Q.useMemo(()=>{if(!P)return new Set;let e=new Set;for(let t of Re){let n=typeof t?.id==`string`?t.id:``;if(!n)continue;let r=$M(t.tool);!r||!QM.has(r)||e.add(n)}for(let t of a?.activityParts??[]){if(t.kind!==`tool`)continue;let n=$M(t.part.tool);!n||!QM.has(n)||e.add(t.id)}return e},[P,Re,a?.activityParts]),Be=Q.useMemo(()=>{if(ze.size===0&&U.size===0)return H;let e=new Set(H);return ze.forEach(t=>{U.has(t)||e.add(t)}),U.forEach(t=>{e.delete(t)}),e},[U,ze,H]),Ve=Q.useMemo(()=>{if(!G)return;let e=ce.find(e=>e.type===`agent`);if(!e)return;let t=e,n=typeof t.name==`string`?t.name:void 0;if(n)return{name:n,token:t.source&&typeof t.source.value==`string`&&t.source.value.trim().length>0?t.source.value:`@${n}`}},[G,ce]),Ue=G&&!Or(Ie),We=typeof Ne!=`string`,Ge=Q.useMemo(()=>G?!1:Le.length===0||Re.length===0?We:!0,[Le.length,Re.length,We,G]),Ke=Q.useMemo(()=>!G&&CT.getInstance().shouldAnimateMessage(e.info,x||e.info.sessionID),[e.info,x,G]),[qe,Je]=Q.useState(!1),Ye=Q.useMemo(()=>n?RM(n.info):null,[n]),Xe=!!a,Ze=a?.isLastAssistantInTurn??!1,Qe=UM({isWorking:a?.isWorking===!0,isInActiveTurn:c,headerCompletionDisposition:a?.completionDisposition}),$e=Q.useMemo(()=>G?!1:Xe?!Ze:Ye?!Ye.isUser&&Ye.role===`assistant`:!1,[Xe,Ze,G,Ye]),et=Q.useMemo(()=>Me?`completed`:c?l??`streaming`:`completed`,[l,c,Me]);Q.useEffect(()=>{!G||!u||d?.(e.info.id)},[u,G,e.info.id,d]),Q.useEffect(()=>{Je(!1)},[e.info.id]),Q.useEffect(()=>{let t=o??a?.headerMessageId;G||!t||t!==e.info.id||(et===`streaming`||et===`cooldown`)&&Je(!0)},[o,G,e.info.id,et,a?.headerMessageId]);let tt=Q.useMemo(()=>{if(G)return!0;if(s)return!1;let t=o??a?.headerMessageId;return t?e.info.id===t?et===`completed`||qe||et===`streaming`||et===`cooldown`:!1:!0},[o,qe,G,a,et,e.info.id,s]),nt=Q.useCallback(e=>{Jt(e).then(t=>{t.ok&&(I(e),setTimeout(()=>I(null),2e3))})},[]),rt=G?void 0:a?.userMessageVariant??le?.variant,it=!G&&xe&&typeof rt==`string`&&rt.trim().length>0?rt:void 0,at=Q.useMemo(()=>{if(!G)return qM(e.info?.error,p(`chat.messageBody.aborted`))},[G,e.info,p]),ot=at?.text,st=at?.variant,ct=Q.useMemo(()=>{if(G){let e=Ie.filter(e=>e.type===`text`).map(e=>{let t=e.shellAction?.output;return typeof t==`string`?t.trim():``}).filter(e=>e.length>0);if(e.length>0)return e.join(`
|
|
6575
|
+
`).trim()||bA(t)},AA=({containerRef:e})=>{let{t}=Yt(),[n,r]=Q.useState({x:0,y:0,show:!1}),[i,a]=Q.useState(``),[o,s]=Q.useState(``),c=Q.useRef(!1),[l,u]=Q.useState(!1),d=Q.useRef(null),f=Q.useRef(gA),p=Q.useRef(null),m=Q.useRef(null),h=Q.useRef(null),g=Q.useRef(!1),_=X(e=>e.createSession),v=un(e=>e.setPendingInputText),y=q(e=>e.isMobile),b=Qy(Zy()).textSelectionMutation;Q.useEffect(()=>{g.current=n.show},[n.show]),Q.useEffect(()=>()=>{m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),h.current!==null&&(window.clearTimeout(h.current),h.current=null)},[]);let x=Q.useCallback(()=>{p.current=null,_A===x&&(_A=null),g.current&&=(m.current!==null&&(window.cancelAnimationFrame(m.current),m.current=null),u(!1),r(e=>({...e,show:!1})),a(``),s(``),!1)},[]);Q.useEffect(()=>()=>{_A===x&&(_A=null)},[x]);let S=Q.useCallback(e=>{if(typeof window>`u`)return e;let t=window.innerWidth,n=f.current/2,r=hA+n,i=t-hA-n;return r>i?t/2:Math.min(Math.max(e,r),i)},[]),C=Q.useCallback(()=>{if(!p.current)return;_A!==x&&(_A?.(),_A=x);let{plainText:e,markdownText:t,rect:i}=p.current,o=!n.show,c=y?i.left+i.width/2:S(i.left+i.width/2),l=i.top-10;a(e),s(t),r({x:c,y:l,show:!0}),g.current=!0,o&&(u(!0),m.current!==null&&window.cancelAnimationFrame(m.current),m.current=window.requestAnimationFrame(()=>{u(!1),m.current=null}))},[S,x,y,n.show]);Q.useLayoutEffect(()=>{if(!n.show||y||!d.current)return;let e=d.current.offsetWidth;!Number.isFinite(e)||e<=0||e===f.current||(f.current=e,r(e=>({...e,x:S(e.x)})))},[S,y,n.show]),Q.useEffect(()=>{if(!n.show||y)return;let e=()=>{r(e=>({...e,x:S(e.x)}))};return window.addEventListener(`resize`,e),()=>{window.removeEventListener(`resize`,e)}},[S,y,n.show]);let w=Q.useCallback(()=>{let t=window.getSelection(),n=e.current;if(!t||!n){c.current||x();return}let r=bA(t.toString());if(!r){c.current||x();return}let i=CA(t,n);if(!i){c.current||x();return}let a=i.getBoundingClientRect();p.current={plainText:r,markdownText:kA(i,r),rect:a},c.current||C()},[e,x,C]);Q.useEffect(()=>{let t=e.current;if(!t)return;let n=()=>{c.current=!0,x()},r=()=>{c.current=!1,h.current!==null&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>{h.current=null,w()},10)},i=new Set,a=()=>{for(let e of SA(t))i.has(e)||(i.add(e),e.addEventListener(`selectionchange`,w))};a();let o=new MutationObserver(a);o.observe(t,{childList:!0,subtree:!0}),document.addEventListener(`selectionchange`,w),t.addEventListener(`mousedown`,n),document.addEventListener(`mouseup`,r);let s=e=>{d.current&&!d.current.contains(e.target)&&!window.getSelection()?.toString().trim()&&x()};return document.addEventListener(`mousedown`,s),()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),o.disconnect();for(let e of i)e.removeEventListener(`selectionchange`,w);document.removeEventListener(`selectionchange`,w),t.removeEventListener(`mousedown`,n),document.removeEventListener(`mouseup`,r),document.removeEventListener(`mousedown`,s)}},[e,w,x,C]),Q.useEffect(()=>{if(!n.show)return;let e=e=>{d.current&&e.target instanceof Node&&d.current.contains(e.target)||x()};return window.addEventListener(`scroll`,e,{capture:!0,passive:!0}),()=>{window.removeEventListener(`scroll`,e,!0)}},[n.show,x]);let T=Q.useCallback(e=>{if(!e)return;let t=`\`\`\`md\n${e}\n\`\`\``;v(t,`append`),x(),window.getSelection()?.removeAllRanges()},[v,x]),E=Q.useCallback(()=>{T(o)},[T,o]);Q.useEffect(()=>{let t=t=>{if(!b||!t.metaKey||t.ctrlKey||t.altKey||t.shiftKey||t.key.toLowerCase()!==`i`)return;let n=window.getSelection(),r=e.current;if(!n||!r||!n.toString().trim())return;let i=CA(n,r);i&&(t.preventDefault(),T(kA(i,n.toString())))};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[T,b,e]);let D=Q.useCallback(async()=>{i&&(await _(void 0,null,null)&&v(i,`replace`),x(),window.getSelection()?.removeAllRanges())},[i,_,v,x]),O=Q.useCallback(async()=>{if(!i)return;let e=await Jt(i);e.ok||console.error(`Failed to copy:`,e.error),x(),window.getSelection()?.removeAllRanges()},[i,x]);return n.show?y?(0,Sf.createPortal)((0,$.jsx)(`div`,{ref:d,className:Y(`fixed left-3 right-3 bottom-0 z-50 mx-auto max-w-[420px]`,`rounded-2xl border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] p-2 shadow-lg`,`safe-area-bottom`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),style:{bottom:`calc(0.5rem + env(safe-area-inset-bottom, 0px))`},children:(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[b?(0,$.jsxs)(`button`,{onClick:E,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--primary-base)] text-[var(--primary-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(Z,{name:`add`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.addToChat`)})]}):null,b?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--interactive-selection)] text-[var(--interactive-selection-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(Z,{name:`chat-new`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.newSession`)})]}):null,(0,$.jsxs)(`button`,{onClick:O,className:Y(`col-span-2 flex min-w-0 items-center gap-2 rounded-xl px-3 py-2.5 text-left`,`text-sm font-medium leading-tight`,`bg-[var(--surface-muted)] text-[var(--surface-foreground)]`,`active:opacity-80`,`transition-opacity duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(Z,{name:`file-copy`,className:`h-5 w-5 flex-shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 whitespace-normal`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):(0,Sf.createPortal)((0,$.jsx)(`div`,{ref:d,className:`fixed z-50`,style:{left:n.x,top:n.y,transform:`translate(-50%, -100%)`},children:(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-1 whitespace-nowrap`,`rounded-lg border border-[var(--interactive-border)]`,`bg-[var(--surface-elevated)] shadow-none`,`px-1.5 py-1`,`transition-[opacity,transform] duration-200 ease-out will-change-[opacity,transform]`,l?`opacity-0 translate-y-[4px]`:`opacity-100 translate-y-0`),children:[b?(0,$.jsxs)(`button`,{onClick:E,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.addToCurrentChat`),type:`button`,children:[(0,$.jsx)(Z,{name:`add`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.addToChat`)}),(0,$.jsx)(yv,{shortcut:`⌘+I`})]}):null,b?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,b?(0,$.jsxs)(`button`,{onClick:D,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.title.newSessionWithSelection`),type:`button`,children:[(0,$.jsx)(Z,{name:`chat-new`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.newSession`)})]}):null,b?(0,$.jsx)(`div`,{className:`w-px h-4 bg-[var(--interactive-border)]`}):null,(0,$.jsxs)(`button`,{onClick:O,className:Y(`flex items-center gap-1.5 px-2 py-1 rounded-md`,`text-sm font-medium`,`text-[var(--surface-foreground)]`,`hover:bg-[var(--interactive-hover)]`,`transition-colors duration-150`),title:t(`chat.textSelection.actions.copy`),type:`button`,children:[(0,$.jsx)(Z,{name:`file-copy`,className:`h-4 w-4`}),(0,$.jsx)(`span`,{className:`whitespace-nowrap`,children:t(`chat.textSelection.actions.copy`)})]})]})}),document.body):null},jA=(e,t)=>e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate(),MA=(e,t)=>{let n=new Date(t);return n.setDate(t.getDate()-1),jA(e,n)},NA=e=>Number.isFinite(e)&&!Number.isNaN(new Date(e).getTime()),PA=(e,t)=>{if(!NA(e))return``;let n=new Date(e),r=new Date,i=Ms(n,t),a=Zt(),o=en.getState().dictionary;if(jA(n,r))return i;if(MA(n,r))return tn(o,`common.date.yesterdayWithTime`,{time:i});let s=`${n.toLocaleString(a,{month:`short`})} ${n.getDate()}`;return n.getFullYear()===r.getFullYear()?`${s}, ${i}`:`${s}, ${n.getFullYear()}, ${i}`},FA=e=>typeof e!=`number`||!Number.isFinite(e)||e<0?0:e,IA=e=>e,LA=e=>{if(!Array.isArray(e)||e.length===0)return 0;let t=0;for(let n of e){let e=IA(n);if(e.type!==`tool`)continue;let r=e.state,i=r?.time?.start,a=r?.time?.end;typeof i!=`number`||!Number.isFinite(i)||typeof a!=`number`||!Number.isFinite(a)||a<i||(t+=a-i)}return t},RA=(e,t,n,r)=>{let i=(typeof e==`number`&&Number.isFinite(e)&&e>0&&typeof t==`number`&&Number.isFinite(t)&&t>e?t-e:null)??(typeof r==`number`&&Number.isFinite(r)&&r>0?r:null);if(i===null)return null;let a=i-LA(n);return!Number.isFinite(a)||a<=0?null:a},zA=e=>{let t=RA(e.createdAt,e.completedAt,e.parts,e.fallbackDurationMs);if(t===null)return null;let n=FA(e.outputTokens)+FA(e.reasoningTokens);if(n<=0)return null;let r=t/1e3;if(r<=0)return null;let i=n/r;return!Number.isFinite(i)||i<=0?null:i},BA=e=>{if(!Number.isFinite(e)||e<=0)return``;if(e>=1e3){let t=e/1e3;return`${t>=10?t.toFixed(0):t.toFixed(1)}k tok/s`}return e>=100?`${Math.round(e)} tok/s`:e>=10?`${e.toFixed(1)} tok/s`:`${e.toFixed(2)} tok/s`},VA=e=>{let t=(0,pd.c)(20),{text:n,active:r,className:i}=e,a=Q.useRef(n),[o,s]=Q.useState(n),[c,l]=Q.useState(null),u,d;t[0]!==r||t[1]!==n?(u=()=>{if(n===a.current)return;let e=a.current;if(a.current=n,!r||e.length===0){l(null),s(n);return}l(e),s(n)},d=[r,n],t[0]=r,t[1]=n,t[2]=u,t[3]=d):(u=t[2],d=t[3]),Q.useEffect(u,d);let f;t[4]===Symbol.for(`react.memo_cache_sentinel`)?(f=()=>{l(null)},t[4]=f):f=t[4];let p=J(f),m;t[5]===i?m=t[6]:(m=Y(`oc-summary-flip-viewport relative block h-5 min-h-0 w-full min-w-0 max-w-full overflow-clip sm:h-6`,i),t[5]=i,t[6]=m);let h=c&&`invisible`,g;t[7]===h?g=t[8]:(g=Y(`block h-full min-w-0 truncate leading-5 sm:leading-6`,h),t[7]=h,t[8]=g);let _;t[9]!==o||t[10]!==g?(_=(0,$.jsx)(`span`,{className:g,children:o}),t[9]=o,t[10]=g,t[11]=_):_=t[11];let v;t[12]!==o||t[13]!==p||t[14]!==c?(v=c?(0,$.jsxs)(`span`,{className:`oc-summary-flip-stage absolute inset-0 block overflow-clip`,children:[(0,$.jsx)(`span`,{className:`oc-summary-flip-out absolute inset-x-0 top-0 block h-full truncate`,"aria-hidden":`true`,children:c}),(0,$.jsx)(`span`,{className:`oc-summary-flip-in absolute inset-x-0 top-0 block h-full truncate`,onAnimationEnd:p,children:o})]}):null,t[12]=o,t[13]=p,t[14]=c,t[15]=v):v=t[15];let y;return t[16]!==m||t[17]!==_||t[18]!==v?(y=(0,$.jsxs)(`span`,{className:m,children:[_,v]}),t[16]=m,t[17]=_,t[18]=v,t[19]=y):y=t[19],y},HA=[`search`,`read`,`list`];function UA(e){let t=UD(e);return t===`read`?`read`:t===`glob`||t===`grep`?`search`:t===`list`?`list`:null}function WA(e){let t={read:0,search:0,list:0};for(let n of e){let e=UA(n);e&&(t[e]+=1)}return t}var GA=[`edit`,`command`,`other`],KA=new Set([`edit`,`multiedit`,`write`,`create`,`file_write`,`apply_patch`,`patch`]),qA=new Set([`bash`,`shell`,`cmd`,`command`,`exec`,`terminal`]);function JA(e){if(!zD(e))return null;let t=UD(e);return KA.has(t)?`edit`:qA.has(t)?`command`:`other`}function YA(e){let t={edit:0,command:0,other:0};for(let n of e){let e=JA(n);e&&(t[e]+=1)}return t}function XA(e){return fD(e)}var ZA=[...HA,...GA];function QA(e){return{...WA(e),...YA(e)}}function $A(e){return HD(e)}function ej(e){return e.kind===`reasoning`||e.type===`reasoning`?!1:e.kind===`justification`||e.type===`text`?!0:e.kind===`tool`||e.type===`tool`?!BD(e.toolName):e.kind!=null||e.type!=null}function tj(e,t,n){for(let r=t;r<e.length;r+=1)if(ej(n(e[r])))return!0;return!1}function nj(e){return`parts`in e?e.parts.some(e=>$A(e))?!0:!e.hasFollowingOtherType&&e.isTurnLive:e.some(e=>$A(e))}function rj(e,t,n){let r=[],i=t;for(;i<e.length&&BD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var ij=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,aj=e=>{let t=(0,pd.c)(12),{added:n,removed:r}=e;if(n<=0&&r<=0)return null;let i;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(i=Y(`inline-flex flex-none items-center gap-0.5 tabular-nums`,ij),t[0]=i):i=t[0];let a;t[1]===n?a=t[2]:(a=n>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-success)`},children:[`+`,n]}):null,t[1]=n,t[2]=a);let o;t[3]!==n||t[4]!==r?(o=n>0&&r>0?(0,$.jsx)(`span`,{style:{color:`var(--tools-description)`},children:`/`}):null,t[3]=n,t[4]=r,t[5]=o):o=t[5];let s;t[6]===r?s=t[7]:(s=r>0?(0,$.jsxs)(`span`,{style:{color:`var(--status-error)`},children:[`-`,r]}):null,t[6]=r,t[7]=s);let c;return t[8]!==a||t[9]!==o||t[10]!==s?(c=(0,$.jsxs)(`span`,{className:i,children:[a,o,s]}),t[8]=a,t[9]=o,t[10]=s,t[11]=c):c=t[11],c},oj=({activities:e,isMobile:t,isTurnLive:n=!1,hasFollowingOtherType:r=!1,exploring:i,children:a})=>{let{t:o}=Yt(),[s,c]=Q.useState(!1),l=Q.useId(),u=e.map(e=>e.part),d=i??nj({parts:u,hasFollowingOtherType:r,isTurnLive:n}),f=QA(u.map(e=>e.tool)),p=XA(u),m=ZA.filter(e=>f[e]>0).map(e=>{let t=f[e];return o(e===`search`?t===1?`chat.contextGroup.searchSingle`:`chat.contextGroup.searchPlural`:e===`read`?t===1?`chat.contextGroup.readSingle`:`chat.contextGroup.readPlural`:e===`list`?t===1?`chat.contextGroup.listSingle`:`chat.contextGroup.listPlural`:e===`edit`?t===1?`chat.usedGroup.editSingle`:`chat.usedGroup.editPlural`:e===`command`?t===1?`chat.usedGroup.commandSingle`:`chat.usedGroup.commandPlural`:t===1?`chat.usedGroup.otherSingle`:`chat.usedGroup.otherPlural`,{count:t})}).join(`, `),h=J(()=>{c(e=>!e)}),g=J(e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),h())}),_=o(s?`chat.usedGroup.collapseAria`:`chat.usedGroup.expandAria`),v=o(d?`chat.usedGroup.running`:`chat.usedGroup.used`),y=t?`h-5`:`h-6`;return(0,$.jsxs)(`div`,{"data-component":`context-tool-group`,className:Ev(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":s,"aria-controls":l,"aria-label":_,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,Ov),onClick:h,onKeyDown:g,children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center self-center`,y,t?`w-4`:`w-3.5`),style:{color:`var(--tools-icon)`},children:d?(0,$.jsx)(TD,{isMobile:t,label:o(`chat.usedGroup.running`),className:`block`}):(0,$.jsx)(Z,{name:`search`,className:`block h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex flex-none items-center self-center font-medium`,y,ij,d&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...d?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:v}),m?(0,$.jsx)(`span`,{className:Y(`typography-meta inline-flex min-h-0 w-0 min-w-0 max-w-full flex-1 items-center self-center overflow-clip`,y,ij),style:{color:`var(--tools-description)`},children:(0,$.jsx)(VA,{text:m,active:d,className:t?`!h-5 sm:!h-5`:`!h-6 sm:!h-6`})}):null,(0,$.jsx)(aj,{added:p.added,removed:p.removed}),(0,$.jsx)(Z,{name:s?`arrow-down-s`:`arrow-right-s`,className:`ml-auto size-3.5 flex-none self-center text-muted-foreground opacity-70`})]}),s&&a?(0,$.jsxs)(`div`,{id:l,className:Dv(t),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute bottom-0 left-0 top-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),a]}):null]})};function sj(e,t,n){let r=[],i=t;for(;i<e.length&&RD(n(e[i]));)r.push(e[i]),i+=1;return{items:r,end:i}}var cj=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t.length>0?t:null};function lj(e){if(!e||typeof e!=`object`)return null;let t=e.state;if(!t||typeof t!=`object`)return null;let n=t;if(n.metadata&&typeof n.metadata==`object`){let e=cj(n.metadata.name);if(e)return e}if(n.input&&typeof n.input==`object`){let e=n.input,t=cj(e.name);if(t)return t;let r=cj(e.id);if(r)return r}if(n.output&&typeof n.output==`object`){let e=cj(n.output.name);if(e)return e}return null}function uj(e){let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n.trim();e&&t.push(e)}let n=t.slice(0,3);return{visibleNames:n,hiddenCount:Math.max(0,t.length-n.length),joinedVisible:n.join(`, `)}}var dj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,fj=({activities:e,isMobile:t,children:n})=>{let{t:r}=Yt(),[i,a]=Q.useState(!1),o=Q.useId(),s=e.map(e=>e.part),c=s.some(e=>HD(e)),{joinedVisible:l,hiddenCount:u}=uj(s.map(lj)),d=u>0?r(`chat.skillGroup.summaryOverflow`,{names:l,count:u}):l,f=J(()=>{a(e=>!e)}),p=J(e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),f())}),m=r(i?`chat.skillGroup.collapseAria`:`chat.skillGroup.expandAria`),h=r(`chat.tools.display.skill`);return(0,$.jsxs)(`div`,{"data-component":`skill-tool-group`,className:Ev(t),children:[(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,"aria-expanded":i,"aria-controls":o,"aria-label":m,"data-mobile-press-feedback":`soft`,className:Y(`flex min-h-0 min-w-0 items-center gap-1.5 overflow-clip`,Ov),onClick:f,onKeyDown:p,children:[(0,$.jsx)(`span`,{className:Y(`flex flex-none items-center justify-center`,t?`size-4`:`size-3.5`),style:{color:`var(--tools-icon)`},children:c?(0,$.jsx)(TD,{isMobile:t,label:h,className:`block`}):(0,$.jsx)(Z,{name:`book`,className:`h-[13px] w-[13px]`})}),(0,$.jsx)(`span`,{className:Y(`typography-meta flex-none font-medium`,dj,c&&`animate-text-shimmer`),style:{color:`var(--tools-title)`,...c?{"--oc-text-shimmer-base":`var(--tools-title)`}:{}},children:h}),d?(0,$.jsx)(`span`,{className:Y(`typography-meta h-5 min-h-0 w-0 min-w-0 max-w-full flex-1 overflow-clip sm:h-6`,dj),style:{color:`var(--tools-description)`},children:(0,$.jsx)(VA,{text:d,active:c})}):null,(0,$.jsx)(Z,{name:i?`arrow-down-s`:`arrow-right-s`,className:`ml-auto size-3.5 flex-none text-muted-foreground opacity-70`})]}),i&&n?(0,$.jsxs)(`div`,{id:o,className:Dv(t),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute bottom-0 left-0 top-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),n]}):null]})},pj=Q.memo(e=>{let t=(0,pd.c)(18),{part:n,messageId:r,onContentChange:i,actions:a,streamPhase:o,onShowPopup:s}=e,c=q(mj),l=n,u=typeof l.text==`string`?l.text:``,d=typeof l.content==`string`?l.content:``,f=d.length>u.length?d:u,p=l.time,m=n.sessionID,h=o===void 0||o!==`completed`,g,_;if(t[0]!==i||t[1]!==f?(g=()=>{f.trim().length!==0&&i?.(`structural`)},_=[i,f],t[0]=i,t[1]=f,t[2]=g,t[3]=_):(g=t[2],_=t[3]),Q.useEffect(g,_),!f||f.trim().length===0)return null;let v=o??`streaming`,y=h&&typeof p?.end!=`number`,b;t[4]!==c||t[5]!==r||t[6]!==i||t[7]!==s||t[8]!==n||t[9]!==m||t[10]!==v||t[11]!==y?(b=(0,$.jsx)(`div`,{"data-message-text-export-source":`true`,children:(0,$.jsx)(xk,{part:n,sessionId:m,messageId:r,streamPhase:v,chatRenderMode:c,hasStreamingHapticLifecycle:y,onContentChange:i,onShowPopup:s})}),t[4]=c,t[5]=r,t[6]=i,t[7]=s,t[8]=n,t[9]=m,t[10]=v,t[11]=y,t[12]=b):b=t[12];let x;t[13]===a?x=t[14]:(x=a?(0,$.jsx)(`div`,{className:`mt-2 mb-1 flex items-center justify-start gap-1.5`,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:`flex items-center gap-1.5`,"data-message-action-group":`true`,children:a})}):null,t[13]=a,t[14]=x);let S;return t[15]!==b||t[16]!==x?(S=(0,$.jsxs)(`div`,{"data-message-text-export-root":`true`,children:[b,x]}),t[15]=b,t[16]=x,t[17]=S):S=t[17],S});function mj(e){return e.chatRenderMode}var hj=e=>{let t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`},gj=`!text-[length:var(--text-meta)] !leading-5 sm:!leading-6 tracking-normal`,_j=Y(`typography-meta font-medium`,gj),vj=Y(`typography-meta`,gj),yj=[],bj=e=>{let t=e.part;return t.slim===!0&&(t.type===`tool`||t.type===`reasoning`||t.type===`file`)},xj=e=>{let t=new Set;for(let n of e)bj(n)&&n.messageId&&t.add(n.messageId);return[...t]},Sj=(e,t)=>e.some(e=>{if(!t.has(e.messageId))return!1;let n=e.part;if(n.slim===!0)return!1;if(n.type===`reasoning`)return typeof n.text==`string`&&n.text.trim().length>0;if(n.type===`file`)return typeof n.url==`string`&&n.url.trim().length>0;if(n.type===`tool`){let e=n.state?.output,t=n.state?.error;return(typeof e==`string`?e.trim().length>0:e!=null)||(typeof t==`string`?t.trim().length>0:t!=null)}return!1}),Cj=e=>{let t=(0,pd.c)(5),{href:n}=e,[r,i]=Q.useState(!1),a;t[0]===n?a=t[1]:(a=Ll(n),t[0]=n,t[1]=a);let o=a;if(!o||r)return null;let s;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>i(!0),t[2]=s):s=t[2];let c;return t[3]===o?c=t[4]:(c=(0,$.jsx)(`span`,{className:`inline-flex size-[18px] flex-shrink-0 items-center justify-center rounded border border-[var(--border)] bg-[var(--interactive-hover)]`,children:(0,$.jsx)(`img`,{src:o,alt:``,"aria-hidden":`true`,loading:`lazy`,decoding:`async`,className:`size-3.5 rounded-sm`,onError:s})}),t[3]=o,t[4]=c),c},wj=e=>e,Tj=e=>{let t=e.part.state,n=t?.input,r=t?.metadata,i=n?.filePath||n?.file_path||n?.path||r?.filePath||r?.file_path||r?.path;if(typeof i==`string`&&i.trim().length>0){let e=i.lastIndexOf(`/`);return e>=0?i.slice(e+1):i}return null},Ej=e=>{let t=e.part.state,n=t?.input,r=t?.metadata,i=n?.filePath||n?.file_path||n?.path||r?.filePath||r?.file_path||r?.path;return typeof i==`string`&&i.trim().length>0?i:null},Dj=e=>{let t=e.part.state?.metadata?.dir;return typeof t==`string`&&t.trim().length>0?t:null},Oj=e=>{if(typeof e!=`string`)return null;let t=e.trim().toLowerCase();return t===`pending`?`pending`:t===`in_progress`||t===`in progress`||t===`inprogress`?`in_progress`:t===`completed`||t===`done`?`completed`:t===`cancelled`||t===`canceled`?`cancelled`:null},kj=e=>{if(e.length===0)return`0 tasks`;let t=0,n=0;for(let r of e){if(!r||typeof r!=`object`)continue;let e=Oj(r.status);e&&(e===`pending`&&(t+=1),e===`in_progress`&&(n+=1))}let r=t+n;return r===0?`0 tasks`:`${r} ${r===1?`task`:`tasks`}`},Aj=e=>{let t=e.part.state,n=t?.input,r=t?.output;if(Array.isArray(n?.todos)){let e=kj(n.todos);if(e)return e}if(Array.isArray(r)){let e=kj(r);if(e)return e}if(r&&typeof r==`object`&&Array.isArray(r.todos)){let e=kj(r.todos);if(e)return e}if(typeof r==`string`&&r.trim().length>0)try{let e=JSON.parse(r);if(Array.isArray(e)){let t=kj(e);if(t)return t}if(e&&typeof e==`object`&&Array.isArray(e.todos)){let t=kj(e.todos);if(t)return t}}catch{}return null},jj=e=>{let t=e.part.state,n=t?.input,r=t?.metadata,i=(typeof n?.offset==`number`&&Number.isFinite(n.offset)?n.offset:void 0)??(typeof n?.line==`number`&&Number.isFinite(n.line)?n.line:void 0)??(typeof r?.offset==`number`&&Number.isFinite(r.offset)?r.offset:void 0)??(typeof r?.line==`number`&&Number.isFinite(r.line)?r.line:void 0);if(!(typeof i!=`number`||i<=0))return Math.floor(i)},Mj=(e,t=!0)=>{let n=e.lastIndexOf(`/`);if(n===-1)return(0,$.jsx)(LT,{variant:t?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,vj),style:{color:`var(--tools-description)`},title:e,children:e});let r=e.slice(0,n),i=e.slice(n+1),a=r.startsWith(`/`),o=a?r.slice(1):r;return(0,$.jsxs)(`span`,{className:Y(`min-w-0 inline-flex max-w-full flex-1 items-baseline overflow-hidden`,vj),title:e,children:[a?(0,$.jsx)(`span`,{className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:`/`}):null,(0,$.jsx)(`span`,{className:`min-w-0 shrink truncate whitespace-nowrap`,style:{color:`var(--tools-description)`,direction:`rtl`,textAlign:`left`,unicodeBidi:`plaintext`},children:o}),(0,$.jsx)(`span`,{className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:`/`}),(0,$.jsx)(LT,{variant:t?`generate-effect`:`static`,className:`flex-shrink-0`,style:{color:`var(--tools-description)`},children:i})]})},Nj=e=>{let t=au(e);return t?t.toLowerCase().endsWith(`/skill.md`)?t:`${t}/SKILL.md`:``},Pj=e=>{let t=e.part,n=t.tool?.toLowerCase()??``,r=t.state,i=r?.input,a=r?.metadata;if(n===`grep`||n===`search`||n===`find`||n===`ripgrep`){let e=i?.pattern;if(typeof e==`string`&&e.trim().length>0)return e.length>40?e.slice(0,40)+`...`:e}if(n===`glob`){let e=i?.pattern;if(typeof e==`string`&&e.trim().length>0)return e.length>40?e.slice(0,40)+`...`:e}if(n===`websearch`||n===`web-search`||n===`search_web`||n===`codesearch`||n===`perplexity`){let e=i?.query;if(typeof e==`string`&&e.trim().length>0)return e.length>50?e.slice(0,50)+`...`:e}if(n===`skill`)return lj(t);if(n===`webfetch`||n===`fetch`||n===`curl`||n===`wget`){let e=typeof i?.url==`string`&&i.url||typeof i?.URL==`string`&&i.URL||typeof a?.url==`string`&&a.url||typeof a?.URL==`string`&&a.URL||``;if(typeof e==`string`&&e.trim().length>0)return e.trim()}return n===`todowrite`||n===`todoread`?Aj(e):Tj(e)},Fj=e=>{let t=[],n=[];for(let r of e){if(r.kind!==`tool`)continue;let e=r.part;if(e.tool?.trim().toLowerCase()!==`task`)continue;let i=typeof e.id==`string`?e.id.trim():``;if(!i)continue;let a=e.state;if(!a||typeof a!=`object`)continue;let o=a;n.push(i),(o.status===`pending`||o.status===`running`)&&t.push(i)}return{active:t,all:n}},Ij=Q.memo(e=>{let t=(0,pd.c)(16),{activity:n,isExpanded:r,isMobile:i,onToggleTool:a,onShowPopup:o,onContentChange:s}=e,c;t[0]!==n.id||t[1]!==a?(c=()=>{a(n.id)},t[0]=n.id,t[1]=a,t[2]=c):c=t[2];let l=J(c),u;t[3]===i?u=t[4]:(u=Ev(i),t[3]=i,t[4]=u);let d=n.part,f;t[5]!==n.messageId||t[6]!==l||t[7]!==r||t[8]!==i||t[9]!==s||t[10]!==o||t[11]!==d?(f=(0,$.jsx)(tk,{part:d,messageId:n.messageId,isExpanded:r,onToggle:l,isMobile:i,onContentChange:s,onShowPopup:o,animateTailText:!1}),t[5]=n.messageId,t[6]=l,t[7]=r,t[8]=i,t[9]=s,t[10]=o,t[11]=d,t[12]=f):f=t[12];let p;return t[13]!==u||t[14]!==f?(p=(0,$.jsx)(`div`,{className:u,children:f}),t[13]=u,t[14]=f,t[15]=p):p=t[15],p},(e,t)=>e.isExpanded===t.isExpanded&&e.isMobile===t.isMobile&&e.onToggleTool===t.onToggleTool&&e.onShowPopup===t.onShowPopup&&e.onContentChange===t.onContentChange&&e.activity.id===t.activity.id&&e.activity.messageId===t.activity.messageId&&e.activity.kind===t.activity.kind&&e.activity.endedAt===t.activity.endedAt&&TE([e.activity.part],[t.activity.part])),Lj=Q.memo(e=>{let t=(0,pd.c)(9),{toolName:n,activities:r,isMobile:i}=e,a;t[0]===i?a=t[1]:(a=Ev(i),t[0]=i,t[1]=a);let o;t[2]!==r||t[3]!==i||t[4]!==n?(o=(0,$.jsx)(Bj,{toolName:n,activities:r,isMobile:i,animateTailText:!1}),t[2]=r,t[3]=i,t[4]=n,t[5]=o):o=t[5];let s;return t[6]!==a||t[7]!==o?(s=(0,$.jsx)(`div`,{className:a,children:o}),t[6]=a,t[7]=o,t[8]=s):s=t[8],s},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&zj(e.activities,t.activities)),Rj=e=>{let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.kind===`reasoning`){if(!qa(r.part).trim()){n++;continue}t.push({type:`reasoning`,activity:r}),n++;continue}if(r.kind===`justification`){t.push({type:`justification`,activity:r}),n++;continue}let i=r.part.tool?.toLowerCase()??``;if(BD(i)){let r=rj(e,n,e=>e.part.tool);t.push({type:`tool-context-group`,activities:r.items,hasFollowingOtherType:tj(e,r.end,e=>({kind:e.kind,toolName:e.part.tool}))}),n=r.end;continue}if(RD(i)){let r=sj(e,n,e=>e.part.tool);if(r.items.length>0){t.push({type:`tool-skill-group`,activities:r.items}),n=r.end;continue}}if(FD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(PD(i)){t.push({type:`tool-expandable`,activity:r}),n++;continue}if(ID(i)){t.push({type:`tool-static-group`,toolName:i,activities:[r]}),n++;continue}t.push({type:`tool-fallback`,activity:r}),n++}return t},zj=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(r.id!==i.id||r.kind!==i.kind||r.endedAt!==i.endedAt||!TE([r.part],[i.part]))return!1}return!0},Bj=Q.memo(e=>{let t=(0,pd.c)(106),{toolName:n,activities:r,isMobile:i,animateTailText:a}=e,{t:o}=Yt(),s=q(Wj),c=Vl(n,o),l;t[0]===n?l=t[1]:(l=RT(n),t[0]=n,t[1]=l);let u=l,d;t[2]===n?d=t[3]:(d=n.toLowerCase(),t[2]=n,t[3]=d);let f=d===`read`,p=Q.useContext(ic),m=Fu(),h=$e(Gj),g=Zy(),_=g.kind===`embedded`?g.directory:h,v;t[4]===n?v=t[5]:(v=n.toLowerCase(),t[4]=n,t[5]=v);let y=v===`skill`,b;t[6]===y?b=t[7]:(b={enabled:y},t[6]=y,t[7]=b);let x=hi(b),S;t[8]===x.data?S=t[9]:(S=x.data??[],t[8]=x.data,t[9]=S);let C=S,w;t[10]===C?w=t[11]:(w=new Map(C.map(Kj)),t[10]=C,t[11]=w);let T=w,E=r[0]??null,D=!E||HD(E.part),O;t[12]===E?O=t[13]:(O=E?Pj(E):null,t[12]=E,t[13]=O);let k=O,A;if(t[14]!==k||t[15]!==E||t[16]!==T||t[17]!==n){bb0:{if(n.toLowerCase()!==`skill`||!E||!k){A=null;break bb0}let e=T.get(k)?.path||Dj(E);if(!e||e===`<built-in>`){A=null;break bb0}let r=Nj(e);if(!r){A=null;break bb0}let i;t[19]!==k||t[20]!==r?(i={name:k,path:r},t[19]=k,t[20]=r,t[21]=i):i=t[21],A=i}t[14]=k,t[15]=E,t[16]=T,t[17]=n,t[18]=A}else A=t[18];let j=A,M;if(t[22]!==_||t[23]!==f||t[24]!==E){bb1:{if(!f||!E){M=null;break bb1}let e=Ej(E);if(!e){M=null;break bb1}let n=cu(e,_);if(!n){M=null;break bb1}let r;t[26]===E?r=t[27]:(r=jj(E),t[26]=E,t[27]=r);let i;t[28]!==n||t[29]!==e||t[30]!==r?(i={path:e,displayPath:n,offset:r},t[28]=n,t[29]=e,t[30]=r,t[31]=i):i=t[31],M=i}t[22]=_,t[23]=f,t[24]=E,t[25]=M}else M=t[25];let N=M,P;t[32]!==_||t[33]!==m||t[34]!==p?(P=(e,t)=>{if(!_)return;let n=ru(_,e);if(!n)return;if(m){m.openFile({path:n,targetLine:t&&Number.isFinite(t)?Math.max(1,Math.trunc(t)):void 0});return}if(p?.editor){p.editor.openFile(n,t);return}if(!tu(n,_)){Wl(n,_).then(()=>{let e=q.getState(),r=_||nu(_,n);if(t&&Number.isFinite(t)){e.openContextFileAtLine(r,n,Math.max(1,Math.trunc(t)),1);return}e.openContextFile(r,n)});return}let r=q.getState(),i=nu(_,n);if(t&&Number.isFinite(t)){r.openContextFileAtLine(i,n,Math.max(1,Math.trunc(t)),1);return}r.openContextFile(i,n)},t[32]=_,t[33]=m,t[34]=p,t[35]=P):P=t[35];let F=J(P),I;t[36]!==_||t[37]!==m?(I=e=>{let t=au(e);if(!t)return;let n=()=>{if(m){m.openFile({path:t});return}let e=q.getState(),n=_||nu(``,t);e.openContextFile(n,t)};if(_&&!tu(t,_)){Wl(t,_).then(n);return}n()},t[36]=_,t[37]=m,t[38]=I):I=t[38];let L=J(I),R;t[39]===n?R=t[40]:(R=n.toLowerCase(),t[39]=n,t[40]=R);let z=R,B=z===`grep`||z===`search`||z===`find`||z===`ripgrep`||z===`glob`,V=z===`webfetch`||z===`fetch`||z===`curl`||z===`wget`,H=z===`skill`,ee=!!(N||j),U=!!(N&&_||j),te;t[41]!==U||t[42]!==F||t[43]!==L||t[44]!==ee||t[45]!==N||t[46]!==j?(te=()=>{if(!(!ee||!U)){if(N){F(N.path,N.offset);return}j&&L(j.path)}},t[41]=U,t[42]=F,t[43]=L,t[44]=ee,t[45]=N,t[46]=j,t[47]=te):te=t[47];let W=J(te),ne;t[48]===W?ne=t[49]:(ne=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),W())},t[48]=W,t[49]=ne);let G=J(ne),re=ee&&U&&`cursor-pointer`,ie=ee&&!U&&`cursor-default opacity-70`,K;t[50]!==re||t[51]!==ie?(K=Y(`flex w-full items-center gap-x-1.5 min-w-0`,Ov,re,ie),t[50]=re,t[51]=ie,t[52]=K):K=t[52];let ae=ee?`soft`:void 0,oe=ee?W:void 0,se=ee?G:void 0,ce=ee?`button`:void 0,le=ee&&U?0:void 0,ue=ee&&!U?!0:void 0,de=i?`size-4`:`size-3.5`,fe;t[53]===de?fe=t[54]:(fe=Y(`inline-flex items-center justify-center flex-shrink-0`,de),t[53]=de,t[54]=fe);let pe;t[55]===Symbol.for(`react.memo_cache_sentinel`)?(pe={color:`var(--tools-icon)`},t[55]=pe):pe=t[55];let me=D?(0,$.jsx)(TD,{isMobile:i,label:o(`chat.assistantStatus.usingTool`,{tool:c})}):u,he;t[56]!==fe||t[57]!==pe||t[58]!==me?(he=(0,$.jsx)(`div`,{className:fe,style:pe,children:me}),t[56]=fe,t[57]=pe,t[58]=me,t[59]=he):he=t[59];let ge,_e;t[60]===Symbol.for(`react.memo_cache_sentinel`)?(ge=Y(_j,`inline-flex items-center flex-shrink-0 opacity-85`),_e={color:`var(--tools-title)`},t[60]=ge,t[61]=_e):(ge=t[60],_e=t[61]);let ve;t[62]===c?ve=t[63]:(ve=(0,$.jsx)(`span`,{className:ge,style:_e,title:c,children:c}),t[62]=c,t[63]=ve);let ye;t[64]!==a||t[65]!==f||t[66]!==N||t[67]!==s?(ye=f&&N?(0,$.jsxs)(`span`,{className:Y(`inline-flex !min-h-0 items-center justify-start gap-1 min-w-0 flex-1 text-left`,vj),style:{color:`var(--tools-description)`},title:N.offset?`${N.displayPath}:${N.offset}`:N.displayPath,children:[s?(0,$.jsx)(Hh,{filePath:N.path,className:`h-3.5 w-3.5`}):null,Mj(N.displayPath,a)]}):null,t[64]=a,t[65]=f,t[66]=N,t[67]=s,t[68]=ye):ye=t[68];let be;t[69]!==a||t[70]!==k||t[71]!==B?(be=B&&k?(0,$.jsx)(`span`,{className:`inline-flex min-w-0 flex-1`,children:(0,$.jsxs)(LT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,vj),style:{color:`var(--tools-description)`},title:k,children:[`"`,k,`"`]})}):null,t[69]=a,t[70]=k,t[71]=B,t[72]=be):be=t[72];let xe;t[73]!==k||t[74]!==V?(xe=V&&k?(0,$.jsxs)(`a`,{href:k,target:`_blank`,rel:`noopener noreferrer`,onClick:qj,className:Y(`min-w-0 flex-1 inline-flex items-center gap-1.5 underline decoration-[color:var(--status-info)] underline-offset-2 hover:opacity-90`,`truncate whitespace-nowrap`,vj),style:{color:`var(--status-info)`},title:k,children:[(0,$.jsx)(Cj,{href:k}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:k})]}):null,t[73]=k,t[74]=V,t[75]=xe):xe=t[75];let Se;t[76]!==H||t[77]!==j?(Se=H&&j?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,vj),style:{color:`var(--tools-description)`},title:j.path,children:j.name}):null,t[76]=H,t[77]=j,t[78]=Se):Se=t[78];let Ce;t[79]!==k||t[80]!==H||t[81]!==j?(Ce=H&&!j&&k?(0,$.jsx)(`span`,{className:Y(`!min-h-0 min-w-0 flex-1 truncate whitespace-nowrap text-left`,vj),style:{color:`var(--tools-description)`},title:k,children:k}):null,t[79]=k,t[80]=H,t[81]=j,t[82]=Ce):Ce=t[82];let we;t[83]!==a||t[84]!==k||t[85]!==V||t[86]!==f||t[87]!==B||t[88]!==H?(we=!f&&!B&&!V&&!H&&k?(0,$.jsx)(LT,{variant:a?`generate-effect`:`static`,className:Y(`min-w-0 flex-1 truncate whitespace-nowrap`,vj),style:{color:`var(--tools-description)`},children:k}):null,t[83]=a,t[84]=k,t[85]=V,t[86]=f,t[87]=B,t[88]=H,t[89]=we):we=t[89];let Te;return t[90]!==K||t[91]!==ae||t[92]!==oe||t[93]!==se||t[94]!==ce||t[95]!==le||t[96]!==ue||t[97]!==he||t[98]!==ve||t[99]!==ye||t[100]!==be||t[101]!==xe||t[102]!==Se||t[103]!==Ce||t[104]!==we?(Te=(0,$.jsxs)(`div`,{className:K,"data-mobile-press-feedback":ae,onClick:oe,onKeyDown:se,role:ce,tabIndex:le,"aria-disabled":ue,children:[he,ve,ye,be,xe,Se,Ce,we]}),t[90]=K,t[91]=ae,t[92]=oe,t[93]=se,t[94]=ce,t[95]=le,t[96]=ue,t[97]=he,t[98]=ve,t[99]=ye,t[100]=be,t[101]=xe,t[102]=Se,t[103]=Ce,t[104]=we,t[105]=Te):Te=t[105],Te},(e,t)=>e.toolName===t.toolName&&e.isMobile===t.isMobile&&e.animateTailText===t.animateTailText&&zj(e.activities,t.activities)),Vj=Q.memo(e=>{let t=(0,pd.c)(5),{activity:n,onContentChange:r,streamPhase:i}=e,a;return t[0]!==n.messageId||t[1]!==n.part||t[2]!==r||t[3]!==i?(a=(0,$.jsx)(Nk,{part:n.part,messageId:n.messageId,streamPhase:i,onContentChange:r}),t[0]=n.messageId,t[1]=n.part,t[2]=r,t[3]=i,t[4]=a):a=t[4],a}),Hj=Q.memo(e=>{let t=(0,pd.c)(7),{activity:n,onContentChange:r,onShowPopup:i,actions:a,streamPhase:o}=e,s;return t[0]!==a||t[1]!==n.messageId||t[2]!==n.part||t[3]!==r||t[4]!==i||t[5]!==o?(s=(0,$.jsx)(pj,{part:n.part,messageId:n.messageId,onContentChange:r,onShowPopup:i,actions:a,streamPhase:o}),t[0]=a,t[1]=n.messageId,t[2]=n.part,t[3]=r,t[4]=i,t[5]=o,t[6]=s):s=t[6],s}),Uj=Q.memo(({parts:e,materializationParts:t=e,isExpanded:n,collapsedPreviewCount:r=0,completionDisposition:i,activityPresentationKind:a=`default`,durationMs:o,onToggle:s,isMobile:c,expandedTools:l,onToggleTool:u,onShowPopup:d,onContentChange:f,streamPhase:p,showHeader:m,renderJustificationActions:h})=>{let{t:g}=Yt(),_=Hl()??``,v=Q.useMemo(()=>xj(t),[t]),y=Q.useRef(new Set),b=Q.useRef(new Map),x=Q.useRef(new Set),[,S]=Q.useState(0),C=Q.useRef(null),w=Q.useRef(null),T=i===`active`,E=!T&&(i===`normal`||i===`abnormal`)&&typeof o==`number`&&Number.isFinite(o)&&o>=0?hj(o):null,D=i===`normal`||i===`abnormal`,O=a===`compaction`,k=O?`fold-vertical`:`stack`,A=g(i===void 0?`chat.activity.title`:T?O?`chat.activity.compacting`:`chat.activity.active`:D?O?`chat.activity.compactionCompleted`:`chat.activity.completedStatus`:`chat.activity.title`),j=Q.useMemo(()=>Fj(e),[e]),M=T?j.active:j.all,N=M.slice(0,c?2:3),P=J((e=!1,n=!1)=>{if(!(!_||!v.length)){for(let r of v){let i=t.find(e=>e.messageId===r)?.part.sessionID;if(!i)continue;let a=ci(_,i,r);if(a.status===`ready`||n&&a.status===`error`||e&&a.status!==`error`&&!x.current.has(r)||(y.current.add(r),x.current.delete(r),b.current.has(r)))continue;let o=_i(_,i,r,{priority:n?`background`:`user`}).catch(()=>{x.current.add(r)}).finally(()=>{b.current.delete(r),S(e=>e+1)});b.current.set(r,o)}S(e=>e+1)}}),F=J(e=>{e.stopPropagation(),P(!0)}),I=T,L=I||n,R=J(()=>{if(I)return;let e=C.current;w.current=e?{top:e.getBoundingClientRect().top,scrollContainer:e.closest(`[data-scrollbar="chat"]`)}:null,L||P(),s()});Q.useEffect(()=>{T||!L||P(!1,!0)},[T,L]),Q.useLayoutEffect(()=>{let e=w.current,t=C.current;if(!e||!t)return;let n=()=>{if(!t.isConnected)return;let n=t.getBoundingClientRect().top-e.top;if(!(Math.abs(n)<.5)){if(e.scrollContainer?.isConnected){e.scrollContainer.scrollTop+=n;return}window.scrollBy(0,n)}};if(n(),typeof window>`u`||typeof window.requestAnimationFrame!=`function`){w.current=null;return}let r=window.requestAnimationFrame(()=>{n(),w.current=null});return()=>window.cancelAnimationFrame(r)},[L]);let z=m&&!L?Math.max(0,Math.floor(r)):0,B=!m||L||z>0,V=y.current,H=[...V].map(e=>{if(b.current.has(e))return`loading`;if(x.current.has(e))return`error`;let n=t.find(t=>t.messageId===e)?.part.sessionID??``;return ci(_,n,e).status}),ee=H.includes(`loading`),U=H.includes(`error`),te=H.length>0&&H.every(e=>e===`ready`),W=t.some(e=>V.has(e.messageId)&&bj(e)),ne=te&&!W&&!Sj(t,V),G=Q.useMemo(()=>B?wj(e):yj,[e,B]),re=Q.useMemo(()=>B?Rj(G):[],[B,G]),ie=Q.useMemo(()=>L||z===0?0:Math.max(0,re.length-z),[L,z,re.length]),K=Q.useMemo(()=>L||z===0?re:re.slice(-z),[L,z,re]);if((!m||I&&!O)&&re.length===0)return null;let ae=(e,t)=>{let n=(0,$.jsx)(`div`,{className:Ev(c),children:t});return(0,$.jsx)(Q.Fragment,{children:n},e)},oe=B?K.map((e,t)=>{switch(e.type){case`reasoning`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Vj,{activity:e.activity,streamPhase:p,onContentChange:f})}));case`justification`:return ae(e.activity.id,(0,$.jsx)($.Fragment,{children:(0,$.jsx)(Hj,{activity:e.activity,onContentChange:f,onShowPopup:d,actions:h?.(e.activity),streamPhase:p})}));case`tool-expandable`:return(0,$.jsx)(Ij,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);case`tool-static-group`:return(0,$.jsx)(Lj,{toolName:e.toolName,activities:e.activities,isMobile:c},e.activities[0]?.id??`static-${e.toolName}-${t}`);case`tool-context-group`:return(0,$.jsx)(oj,{activities:e.activities,isMobile:c,isTurnLive:T,hasFollowingOtherType:e.hasFollowingOtherType,children:e.activities.map(e=>{let t=e.part,n=t.tool?.toLowerCase()??``;return LD(n)?(0,$.jsx)(Bj,{toolName:n,activities:[e],isMobile:c,animateTailText:!1},e.id):(0,$.jsx)(tk,{part:t,messageId:e.messageId,isExpanded:l.has(e.id),onToggle:u,isMobile:c,onContentChange:f,onShowPopup:d,animateTailText:!1},e.id)})},e.activities[0]?.id??`context-${t}`);case`tool-skill-group`:return(0,$.jsx)(fj,{activities:e.activities,isMobile:c,children:e.activities.map(e=>{let t=e.part;return(0,$.jsx)(Bj,{toolName:t.tool?.toLowerCase()??``,activities:[e],isMobile:c,animateTailText:!1},e.id)})},e.activities[0]?.id??`skill-${t}`);case`tool-fallback`:return(0,$.jsx)(Ij,{activity:e.activity,isExpanded:l.has(e.activity.id),isMobile:c,onToggleTool:u,onShowPopup:d,onContentChange:f},e.activity.id);default:return null}}):null,se=K.length>0;return m?(0,$.jsxs)(`div`,{className:Ev(c),children:[(0,$.jsxs)(`button`,{ref:C,type:`button`,className:Y(`group/tool flex w-full min-w-0 flex-nowrap items-center text-left`,c?`gap-x-1`:`gap-x-2`,!I&&Ov,I&&`oc-tool-row -mx-2 rounded-lg px-2 py-0.5 cursor-default`,c&&`pr-0`),"data-mobile-press-feedback":I?void 0:`soft`,onClick:I?void 0:R,"aria-expanded":L,"aria-disabled":I||void 0,"aria-label":I?A:g(L?`chat.activity.collapseAria`:`chat.activity.expandAria`),children:[(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 flex-1 items-center overflow-clip`,c?`gap-x-1`:`gap-x-1.5`),children:[(0,$.jsx)(`span`,{className:Y(`inline-flex flex-none items-center justify-center`,c?`h-5 w-4`:`h-6 w-3.5`),style:{color:`var(--tools-icon)`},children:T&&!O?(0,$.jsx)(TD,{isMobile:c,label:A,className:`block`}):(0,$.jsx)(Z,{name:k,className:`h-3.5 w-3.5`})}),(0,$.jsx)(`span`,{className:Y(`inline-flex flex-shrink-0 items-center`,c?`typography-meta h-5`:`typography-ui-label h-5 font-semibold`,T?`animate-text-shimmer text-[var(--status-info)] [--oc-text-shimmer-base:var(--status-info)]`:`text-foreground/85`),children:A}),E?(0,$.jsx)(`span`,{className:`typography-meta shrink-0 tabular-nums text-muted-foreground`,children:E}):null]}),(0,$.jsxs)(`span`,{className:Y(`ml-auto inline-flex max-w-[min(14rem,55%)] shrink-0 items-center justify-end`,c?`gap-0.5`:`gap-1`),children:[M.length>0?(0,$.jsxs)(`span`,{className:Y(`inline-flex min-w-0 items-center text-muted-foreground`,c?`gap-1`:`gap-1.5`),children:[(0,$.jsx)(`span`,{className:`inline-flex shrink-0 items-center gap-0.5`,"aria-hidden":`true`,children:N.map((e,t)=>(0,$.jsx)(vo,{name:e,size:c?12:14,className:Y(`flex-none`,c?`size-3 min-h-3 min-w-3 max-h-3 max-w-3`:`size-3.5 min-h-3.5 min-w-3.5 max-h-3.5 max-w-3.5`)},`${e}-${t}`))}),(0,$.jsx)(`span`,{className:`typography-meta min-w-0 truncate`,children:g(T?`chat.activity.agentsWorking`:`chat.activity.agentsInvolved`,{count:M.length})})]}):null,I?null:(0,$.jsx)(Z,{name:L?`arrow-down-s`:`arrow-right-s`,className:Y(`flex-shrink-0 text-muted-foreground opacity-70`,c&&`-mr-0.5`,c?`size-3`:`size-3.5`)})]})]}),se?(0,$.jsxs)(`div`,{className:I?void 0:`relative ml-2 pl-3`,children:[I?null:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute left-0 top-px bottom-0 w-px opacity-40`,style:{backgroundColor:`var(--tools-border)`}}),ie>0?(0,$.jsxs)(`button`,{type:`button`,onClick:R,className:`typography-meta leading-4 px-2 py-1 text-muted-foreground/45 hover:text-muted-foreground/65 text-left`,children:[`+`,ie,` more...`]}):null,(0,$.jsx)(`div`,{className:`flow-root`,children:oe})]}):null,L&&(ee||U||ne)?(0,$.jsx)(`div`,{className:Y(`typography-meta flex min-h-9 items-center gap-2 px-2 text-muted-foreground`,I?void 0:`ml-5`,U&&`text-[var(--status-error)]`),role:U?`alert`:`status`,children:ee?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 shrink-0 animate-spin`}),(0,$.jsx)(`span`,{children:g(`chat.activity.outputLoading`)})]}):U?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Z,{name:`error-warning`,className:`size-3.5 shrink-0`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:g(`chat.activity.outputLoadFailed`)}),(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`xs`,onClick:F,children:g(`chat.activity.outputRetry`)})]}):(0,$.jsx)(`span`,{children:g(`chat.toolOutputDialog.noOutputProduced`)})}):null]}):(0,$.jsx)(`div`,{className:Ev(c),children:oe})});function Wj(e){return e.showToolFileIcons}function Gj(e){return e.currentDirectory}function Kj(e){return[e.name,e]}function qj(e){e.stopPropagation()}var Jj=Q.memo(e=>{let t=(0,pd.c)(2),n;return t[0]===e?n=t[1]:(n=(0,$.jsx)(Uj,{...e}),t[0]=e,t[1]=n),n}),Yj={contain:`layout`},Xj={containerType:`inline-size`,containerName:`message-footer`},Zj=`mt-1.5 mb-0.5 flex items-center justify-start gap-1.5`,Qj=`mt-3 mb-0.5 flex items-center justify-start gap-1.5`,$j=`size-6! p-0 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`,eM=`size-3.5!`,tM=`mt-1.5 mb-0.5 flex flex-wrap items-center gap-3`,nM=`mt-3 mb-0.5 flex flex-wrap items-center gap-3 -ml-[5px]`,rM=`flex items-center gap-2`,iM=`flex items-center gap-2 text-muted-foreground`,aM=`inline-flex h-3.5 items-center gap-1 text-[11px] leading-none tabular-nums text-muted-foreground`,oM=`size-3.5!`,sM=`medium`,cM=e=>e.replace(/\\/g,`/`).split(`/`).filter(Boolean).at(-1)??e,lM=`w-full min-w-0 justify-start rounded-[var(--radius-md)] bg-transparent px-1 hover:!bg-interactive-hover focus-visible:!bg-interactive-hover active:!bg-interactive-active supports-[corner-shape:squircle]:rounded-[var(--radius-md)]`,uM=`h-7 gap-1.5`,dM=`h-6 gap-1`,fM=`text-[11px] leading-none`,pM=`size-3.5`,mM=`size-3`,hM=5,gM=Q.memo(e=>{let t=(0,pd.c)(30),{file:n,isMobile:r}=e,i=r?`gap-1 text-[11px]`:`gap-1.5 text-xs`,a;t[0]===i?a=t[1]:(a=Y(`flex min-w-0 flex-1 items-center leading-none text-muted-foreground`,i),t[0]=i,t[1]=a);let o=n.file,s=r?`h-3 w-3`:`h-3.5 w-3.5`,c;t[2]===s?c=t[3]:(c=Y(`flex-shrink-0`,s),t[2]=s,t[3]=c);let l;t[4]!==n.file||t[5]!==c?(l=(0,$.jsx)(Hh,{filePath:o,className:c}),t[4]=n.file,t[5]=c,t[6]=l):l=t[6];let u=n.file,d;t[7]===n.file?d=t[8]:(d=cM(n.file),t[7]=n.file,t[8]=d);let f;t[9]!==n.file||t[10]!==d?(f=(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-left text-foreground/80`,title:u,children:d}),t[9]=n.file,t[10]=d,t[11]=f):f=t[11];let p=r?`text-[11px]`:`typography-meta`,m;t[12]===p?m=t[13]:(m=Y(`inline-flex flex-shrink-0 items-center gap-0 leading-none tabular-nums`,p),t[12]=p,t[13]=m);let h;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(h={color:`var(--status-success)`},t[14]=h):h=t[14];let g;t[15]===n.additions?g=t[16]:(g=(0,$.jsxs)(`span`,{style:h,children:[`+`,n.additions]}),t[15]=n.additions,t[16]=g);let _,v;t[17]===Symbol.for(`react.memo_cache_sentinel`)?(_=(0,$.jsx)(`span`,{className:`text-muted-foreground/70`,children:`/`}),v={color:`var(--status-error)`},t[17]=_,t[18]=v):(_=t[17],v=t[18]);let y;t[19]===n.deletions?y=t[20]:(y=(0,$.jsxs)(`span`,{style:v,children:[`-`,n.deletions]}),t[19]=n.deletions,t[20]=y);let b;t[21]!==m||t[22]!==g||t[23]!==y?(b=(0,$.jsxs)(`span`,{className:m,children:[g,_,y]}),t[21]=m,t[22]=g,t[23]=y,t[24]=b):b=t[24];let x;return t[25]!==b||t[26]!==a||t[27]!==l||t[28]!==f?(x=(0,$.jsxs)(`span`,{className:a,children:[l,f,b]}),t[25]=b,t[26]=a,t[27]=l,t[28]=f,t[29]=x):x=t[29],x}),_M=Q.memo(e=>{let t=(0,pd.c)(18),{file:n,canOpen:r,isMobile:i,onOpen:a}=e,{t:o}=Yt(),s;t[0]!==n.file||t[1]!==a?(s=()=>{a(n.file)},t[0]=n.file,t[1]=a,t[2]=s):s=t[2];let c=J(s),l=!r,u=i?dM:uM,d;t[3]===u?d=t[4]:(d=Y(lM,u),t[3]=u,t[4]=d);let f;t[5]!==n.file||t[6]!==o?(f=o(`chat.changedFiles.actions.openFileTitle`,{path:n.file}),t[5]=n.file,t[6]=o,t[7]=f):f=t[7];let p;t[8]!==n||t[9]!==i?(p=(0,$.jsx)(gM,{file:n,isMobile:i}),t[8]=n,t[9]=i,t[10]=p):p=t[10];let m;return t[11]!==n.file||t[12]!==c||t[13]!==l||t[14]!==d||t[15]!==f||t[16]!==p?(m=(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`xs`,disabled:l,"data-turn-change-file":`true`,className:d,"aria-label":f,title:n.file,onClick:c,children:p}),t[11]=n.file,t[12]=c,t[13]=l,t[14]=d,t[15]=f,t[16]=p,t[17]=m):m=t[17],m}),vM=Q.memo(e=>{let t=(0,pd.c)(53),{fileCount:n,changedFiles:r,turnId:i,isLatestTurn:a,isMobile:o}=e,{t:s}=Yt(),c=Hl(),l=Zy(),u=l.directory||c,d=l.sessionId,f=Fu(),p=q(MM),m;t[0]===r?m=t[1]:(m=r??[],t[0]=r,t[1]=m);let h=m,g;t[2]===h?g=t[3]:(g=h.slice(0,hM),t[2]=h,t[3]=g);let _=g,v=Math.max(0,h.length-_.length),y=h.length>0?h.length:n,b=!!(f||!o&&u||o&&a),x;t[4]!==y||t[5]!==s?(x=s(y===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:y}),t[4]=y,t[5]=s,t[6]=x):x=t[6];let S=x,C;t[7]!==v||t[8]!==s?(C=s(v===1?`chat.pendingChanges.fileCountSingle`:`chat.pendingChanges.fileCountPlural`,{count:v}),t[7]=v,t[8]=s,t[9]=C):C=t[9];let w=C,T=Y(lM,o?dM:uM),E=o?mM:pM,D;t[10]===o?D=t[11]:(D=o?Y(fM,`font-semibold text-foreground/85`):`typography-meta font-semibold text-foreground/85`,t[10]=o,t[11]=D);let O=D,k;t[12]===o?k=t[13]:(k=o?Y(fM,`text-muted-foreground`):`typography-meta text-muted-foreground`,t[12]=o,t[13]=k);let A=k,j;t[14]===o?j=t[15]:(j=o?Y(fM,`font-medium`):`typography-meta font-medium`,t[14]=o,t[15]=j);let M=j,N;t[16]!==u||t[17]!==d||t[18]!==a||t[19]!==o||t[20]!==f||t[21]!==i?(N=e=>{if(f){f.openTurnDiff(i,d,e);return}if(!o&&u){Ik({directory:u,filePath:e,turnMessageId:i,sessionId:d});return}o&&a&&u&&Ik({directory:u,filePath:e,turnMessageId:i,sessionId:d,mobile:!0})},t[16]=u,t[17]=d,t[18]=a,t[19]=o,t[20]=f,t[21]=i,t[22]=N):N=t[22];let P=J(N),F;t[23]!==u||t[24]!==d||t[25]!==a||t[26]!==o||t[27]!==f||t[28]!==p||t[29]!==i||t[30]!==_[0]?.file?(F=()=>{if(f){f.openTurnDiff(i,d);return}if(!o&&u){p(u,{mode:`diff`,dedupeKey:`turn-diff:${d||`session`}:${i}`,targetPath:null,diffScope:`turn`,diffTurnMessageId:i,diffSessionId:d});return}let e=_[0]?.file;e&&o&&a&&u&&Ik({directory:u,filePath:e,turnMessageId:i,sessionId:d,mobile:!0})},t[23]=u,t[24]=d,t[25]=a,t[26]=o,t[27]=f,t[28]=p,t[29]=i,t[30]=_[0]?.file,t[31]=F):F=t[31];let I=J(F),L=o?`gap-0 border-foreground/15 p-1`:`gap-0.5 border-border/50 p-1.5`,R;t[32]===L?R=t[33]:(R=Y(`mt-4 flex min-w-0 flex-col rounded-[var(--radius-lg)] border bg-muted/20`,L),t[32]=L,t[33]=R);let z=Y(T,`max-w-full text-muted-foreground hover:text-foreground`),B;t[34]===s?B=t[35]:(B=s(`diffView.actions.reviewAria`),t[34]=s,t[35]=B);let V;t[36]===s?V=t[37]:(V=s(`diffView.actions.reviewAria`),t[36]=s,t[37]=V);let H;t[38]===E?H=t[39]:(H=(0,$.jsx)(Z,{name:`file-edit`,className:E}),t[38]=E,t[39]=H);let ee=`turn-changes-${i}`,U;t[40]===s?U=t[41]:(U=s(`chat.changedFiles.title`),t[40]=s,t[41]=U);let te;t[42]!==ee||t[43]!==U||t[44]!==O?(te=(0,$.jsx)(`span`,{id:ee,className:O,children:U}),t[42]=ee,t[43]=U,t[44]=O,t[45]=te):te=t[45];let W;t[46]!==S||t[47]!==A?(W=(0,$.jsx)(`span`,{className:A,children:S}),t[46]=S,t[47]=A,t[48]=W):W=t[48];let ne;t[49]===E?ne=t[50]:(ne=Y(E,`opacity-60`),t[49]=E,t[50]=ne);let G;return t[51]===ne?G=t[52]:(G=(0,$.jsx)(Z,{name:`arrow-right-s`,className:ne}),t[51]=ne,t[52]=G),(0,$.jsxs)(`section`,{className:R,"data-turn-changes-preview":`true`,"data-message-action-group":`true`,"aria-labelledby":`turn-changes-${i}`,children:[(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,onClick:I,className:z,"aria-label":B,title:V,children:[H,te,W,G]}),_.length>0?(0,$.jsxs)(`div`,{className:Y(`flex min-w-0 flex-col`,o?`gap-0`:`gap-0.5`),children:[_.map(e=>(0,$.jsx)(_M,{file:e,canOpen:b,isMobile:o,onOpen:P},e.file)),v>0?(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`xs`,disabled:!b,className:Y(T,`text-muted-foreground hover:text-foreground`),onClick:I,"aria-label":s(`diffView.actions.reviewAria`),title:s(`diffView.actions.reviewAria`),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(E,`flex-shrink-0`)}),(0,$.jsxs)(`span`,{className:M,children:[`+`,w]}),(0,$.jsx)(Z,{name:`arrow-right-s`,className:E})]}):null]}):null]})}),yM=e=>e.type===`subtask`,bM=e=>{let t=e;return t.type===`text`&&typeof t.shellAction==`object`&&t.shellAction!==null},xM=e=>{if(!e||typeof e!=`object`)return null;let t=typeof e.providerID==`string`?e.providerID.trim():``,n=typeof e.modelID==`string`?e.modelID.trim():``;return!t||!n?null:`${t}/${n}`},SM=e=>{let t=(0,pd.c)(49),{part:n}=e,[r,i]=Q.useState(!1),a=Hl(),{isMobile:o}=qs(),s=X(NM),c=q(PM),l=Zy(),{t:u}=Yt(),d;t[0]===n.description?d=t[1]:(d=typeof n.description==`string`?n.description.trim():``,t[0]=n.description,t[1]=d);let f=d,p;t[2]===n.command?p=t[3]:(p=typeof n.command==`string`?n.command.trim():``,t[2]=n.command,t[3]=p);let m=p,h;t[4]===n.agent?h=t[5]:(h=typeof n.agent==`string`?n.agent.trim():``,t[4]=n.agent,t[5]=h);let g=h,_;t[6]===n.prompt?_=t[7]:(_=typeof n.prompt==`string`?n.prompt.trim():``,t[6]=n.prompt,t[7]=_);let v=_,y;t[8]===n.taskSessionID?y=t[9]:(y=typeof n.taskSessionID==`string`?n.taskSessionID.trim():``,t[8]=n.taskSessionID,t[9]=y);let b=y,x;t[10]===n.model?x=t[11]:(x=xM(n.model),t[10]=n.model,t[11]=x);let S=x,C=!!v&&!(o&&l.kind===`primary`),w;t[12]===u?w=t[13]:(w=u(`chat.messageBody.subtask.title`),t[12]=u,t[13]=w);let T;t[14]===w?T=t[15]:(T=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:w}),t[14]=w,t[15]=T);let E;t[16]===m?E=t[17]:(E=m?(0,$.jsxs)(`span`,{className:`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground`,children:[`/`,m]}):null,t[16]=m,t[17]=E);let D;t[18]===g?D=t[19]:(D=g?(0,$.jsxs)(`span`,{className:`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground`,children:[`@`,g]}):null,t[18]=g,t[19]=D);let O;t[20]===S?O=t[21]:(O=S?(0,$.jsx)(`span`,{className:`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none bg-foreground/5 text-muted-foreground`,children:S}):null,t[20]=S,t[21]=O);let k;t[22]!==D||t[23]!==O||t[24]!==T||t[25]!==E?(k=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[T,E,D,O]}),t[22]=D,t[23]=O,t[24]=T,t[25]=E,t[26]=k):k=t[26];let A;t[27]===f?A=t[28]:(A=f?(0,$.jsx)(`div`,{className:`typography-ui-label text-foreground/90 mt-1.5`,children:f}):null,t[27]=f,t[28]=A);let j;t[29]!==r||t[30]!==v||t[31]!==C||t[32]!==u?(j=C?(0,$.jsxs)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:[(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>i(FM),children:u(r?`chat.messageBody.subtask.hidePrompt`:`chat.messageBody.subtask.showPrompt`)}),r?(0,$.jsx)(`pre`,{className:`typography-meta mt-1.5 overflow-x-auto whitespace-pre-wrap break-words text-foreground/85`,children:v}):null]}):null,t[29]=r,t[30]=v,t[31]=C,t[32]=u,t[33]=j):j=t[33];let M;t[34]!==g||t[35]!==f||t[36]!==a||t[37]!==o||t[38]!==c||t[39]!==l||t[40]!==s||t[41]!==u||t[42]!==b?(M=b&&l.capabilities.navigateNestedSession?(0,$.jsx)(`div`,{className:`mt-1.5`,children:(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>{let e=l.directory||a;e&&$y(l,b,e,()=>{if(!fa({sessionId:b,directory:e})){if(Nf()||o||ge()){s(b,e);return}c(e,{mode:`chat`,dedupeKey:`session:${b}`,label:f||g||u(`contextPanel.mode.chat`),readOnly:!0})}})},children:u(`chat.messageBody.subtask.openSession`)})}):null,t[34]=g,t[35]=f,t[36]=a,t[37]=o,t[38]=c,t[39]=l,t[40]=s,t[41]=u,t[42]=b,t[43]=M):M=t[43];let N;return t[44]!==k||t[45]!==A||t[46]!==j||t[47]!==M?(N=(0,$.jsxs)(`div`,{className:`mt-2`,children:[k,A,j,M]}),t[44]=k,t[45]=A,t[46]=j,t[47]=M,t[48]=N):N=t[48],N},CM=e=>{let t=(0,pd.c)(34),{notification:n}=e,r=Hl(),i=q(IM),{isMobile:a}=qs(),{t:o}=Yt(),s;t[0]!==r||t[1]!==a?(s=r&&!a&&!ge(),t[0]=r,t[1]=a,t[2]=s):s=t[2];let c=!!s,l;t[3]!==n.state||t[4]!==o?(l=n.state===`completed`?o(`chat.messageBody.subagent.completed`):n.state===`error`?o(`chat.messageBody.subagent.error`):o(`chat.messageBody.subagent.cancelled`),t[3]=n.state,t[4]=o,t[5]=l):l=t[5];let u=l,d=n.state===`completed`?o(`chat.messageBody.subagent.completedDescription`):n.state===`error`?o(`chat.messageBody.subagent.errorDescription`):o(`chat.messageBody.subagent.cancelledDescription`),f=n.description||d,p=J(()=>{!c||!r||i(r,{mode:`chat`,dedupeKey:`session:${n.sessionID}`,label:f,readOnly:!0})}),m;t[6]===p?m=t[7]:(m=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),p())},t[6]=p,t[7]=m);let h=J(m),g=c&&`cursor-pointer hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]`,_;t[8]===g?_=t[9]:(_=Y(`mt-2 flex min-w-0 gap-2.5 rounded-[var(--radius-lg)] border border-border/60 bg-muted/20 px-3 py-2.5`,g),t[8]=g,t[9]=_);let v=c?`button`:void 0,y=c?0:void 0,b=c?o(`chat.messageBody.subagent.openSession`,{label:f}):void 0,x=c?p:void 0,S=c?h:void 0,C;t[10]===Symbol.for(`react.memo_cache_sentinel`)?(C=(0,$.jsx)(`span`,{className:`mt-0.5 flex size-6 flex-shrink-0 items-center justify-center rounded-md bg-foreground/5 text-muted-foreground`,children:(0,$.jsx)(Z,{name:`robot-2`,className:`size-3.5`})}),t[10]=C):C=t[10];let w;t[11]===f?w=t[12]:(w=(0,$.jsx)(`span`,{className:`typography-meta min-w-0 flex-1 truncate font-semibold text-foreground/90`,children:f}),t[11]=f,t[12]=w);let T=n.state===`completed`?`bg-[var(--status-success-background)] text-[var(--status-success)]`:n.state===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`,E;t[13]===T?E=t[14]:(E=Y(`inline-flex h-5 flex-shrink-0 items-center rounded px-1.5 text-[11px] leading-none`,T),t[13]=T,t[14]=E);let D;t[15]!==u||t[16]!==E?(D=(0,$.jsx)(`span`,{className:E,children:u}),t[15]=u,t[16]=E,t[17]=D):D=t[17];let O;t[18]!==w||t[19]!==D?(O=(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[w,D]}),t[18]=w,t[19]=D,t[20]=O):O=t[20];let k;t[21]===n.body?k=t[22]:(k=n.body?(0,$.jsx)(`div`,{className:`typography-meta mt-1 max-h-16 overflow-clip text-muted-foreground [&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,children:(0,$.jsx)(gl,{content:n.body,variant:`tool`,enableFileReferences:!1})}):null,t[21]=n.body,t[22]=k);let A;t[23]!==O||t[24]!==k?(A=(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[O,k]}),t[23]=O,t[24]=k,t[25]=A):A=t[25];let j;return t[26]!==S||t[27]!==A||t[28]!==_||t[29]!==v||t[30]!==y||t[31]!==b||t[32]!==x?(j=(0,$.jsxs)(`div`,{className:_,role:v,tabIndex:y,"aria-label":b,onClick:x,onKeyDown:S,children:[C,A]}),t[26]=S,t[27]=A,t[28]=_,t[29]=v,t[30]=y,t[31]=b,t[32]=x,t[33]=j):j=t[33],j},wM={background:`transparent`,backgroundColor:`transparent`},TM=e=>{let t=(0,pd.c)(36),{part:n}=e,[r,i]=Q.useState(!1),[a,o]=Q.useState(!1),s=Q.useRef(null),{t:c}=Yt(),l;t[0]===n.shellAction?l=t[1]:(l=typeof n.shellAction?.command==`string`?n.shellAction.command.trim():``,t[0]=n.shellAction,t[1]=l);let u=l,d=typeof n.shellAction?.output==`string`?n.shellAction.output:``,f;t[2]===n.shellAction?f=t[3]:(f=typeof n.shellAction?.status==`string`?n.shellAction.status.trim().toLowerCase():``,t[2]=n.shellAction,t[3]=f);let p=f,m;t[4]===d?m=t[5]:(m=d.trim(),t[4]=d,t[5]=m);let h=m.length>0,g;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(g=()=>{s.current!==null&&typeof window<`u`&&(window.clearTimeout(s.current),s.current=null)},t[6]=g):g=t[6];let _=J(g),v,y;t[7]===_?(v=t[8],y=t[9]):(v=()=>()=>{_()},y=[_],t[7]=_,t[8]=v,t[9]=y),Q.useEffect(v,y);let b;t[10]!==_||t[11]!==h||t[12]!==d?(b=async()=>{h&&(await Jt(d)).ok&&(_(),o(!0),typeof window<`u`&&(s.current=window.setTimeout(()=>{o(!1),s.current=null},2e3)))},t[10]=_,t[11]=h,t[12]=d,t[13]=b):b=t[13];let x=J(b),S;t[14]===c?S=t[15]:(S=c(`chat.messageBody.shellCommand.title`),t[14]=c,t[15]=S);let C;t[16]===S?C=t[17]:(C=(0,$.jsx)(`span`,{className:`typography-meta font-semibold text-foreground`,children:S}),t[16]=S,t[17]=C);let w;t[18]===p?w=t[19]:(w=p?(0,$.jsx)(`span`,{className:Y(`inline-flex h-5 items-center rounded px-1.5 text-[11px] leading-none`,p===`error`?`bg-[var(--status-error-background)] text-[var(--status-error)]`:`bg-foreground/5 text-muted-foreground`),children:p}):null,t[18]=p,t[19]=w);let T;t[20]!==w||t[21]!==C?(T=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[C,w]}),t[20]=w,t[21]=C,t[22]=T):T=t[22];let E;t[23]===u?E=t[24]:(E=u?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 overflow-x-auto font-mono`,children:(0,$.jsx)(bu,{language:`bash`,code:u,codeStyle:wM,wrap:!0})}):null,t[23]=u,t[24]=E);let D;t[25]!==a||t[26]!==x||t[27]!==r||t[28]!==h||t[29]!==d||t[30]!==c?(D=h?(0,$.jsxs)(`div`,{className:`mt-2 border-t border-border/60 pt-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3 flex-wrap`,children:[(0,$.jsx)(`button`,{type:`button`,className:`typography-meta text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2`,onClick:()=>i(LM),children:c(r?`chat.messageBody.shellCommand.hideOutput`:`chat.messageBody.shellCommand.showOutput`)}),(0,$.jsx)(`button`,{type:`button`,className:`inline-flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors`,onClick:()=>{x()},"aria-label":c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),title:c(a?`chat.messageBody.shellCommand.copied`:`chat.messageBody.shellCommand.copyOutput`),children:a?(0,$.jsx)(Z,{name:`check`,className:`h-3.5 w-3.5`}):(0,$.jsx)(Z,{name:`file-copy`,className:`h-3.5 w-3.5`})})]}),r?(0,$.jsx)(`div`,{className:`typography-meta mt-1.5 max-h-56 overflow-auto font-mono text-foreground/85`,children:(0,$.jsx)(bu,{language:`bash`,code:d,codeStyle:wM,wrap:!0})}):null]}):null,t[25]=a,t[26]=x,t[27]=r,t[28]=h,t[29]=d,t[30]=c,t[31]=D):D=t[31];let O;return t[32]!==T||t[33]!==E||t[34]!==D?(O=(0,$.jsxs)(`div`,{className:`mt-2`,children:[T,E,D]}),t[32]=T,t[33]=E,t[34]=D,t[35]=O):O=t[35],O},EM=e=>{let t=e/1e3;return t<60?`${t.toFixed(1)}s`:`${Math.floor(t/60)}m ${Math.round(t%60)}s`},DM=(e,t)=>{if(t&&typeof t==`object`)return{output:typeof t.output==`number`&&Number.isFinite(t.output)?Math.max(0,t.output):0,reasoning:typeof t.reasoning==`number`&&Number.isFinite(t.reasoning)?Math.max(0,t.reasoning):0};for(let t of e){let e=t.tokens;if(!(!e||typeof e!=`object`))return{output:typeof e.output==`number`&&Number.isFinite(e.output)?Math.max(0,e.output):0,reasoning:typeof e.reasoning==`number`&&Number.isFinite(e.reasoning)?Math.max(0,e.reasoning):0}}return{output:0,reasoning:0}},OM=Q.memo(({sessionId:e,messageId:t,parts:n,sourceParts:r,messageCreatedAt:i,isMobile:a,alwaysShowActions:o=a,hasTouchInput:s,hasTextContent:c,onCopyMessage:l,copiedMessage:u,onShowPopup:d,agentMention:f,onEdit:p,onRevert:m,onFork:h,pendingMessageAction:g,editing:_,editStaged:v,onCancelEdit:y,userActionsMode:b=`inline`,stickyUserHeaderEnabled:x=!0})=>{let{locale:S,t:C}=Yt(),w=Fb(),T=Qy(Zy()),E=q(e=>e.timeFormatPreference),[D,O]=Q.useState(!1),k=Q.useRef(null),A=Q.useMemo(()=>n.filter(e=>e.type===`text`?!Dn(e):!!(yM(e)||bM(e))),[n]),j=Q.useMemo(()=>A.map(e=>Lr(e)?iE(qa(e)):void 0),[A]),M=f?.token,N=!1,P=!!l,F=!!u,I=!!(s??a),L=!!c,R=b!==`external-actions`,z=b!==`external-content`,B=x&&b===`inline`,V=J(()=>{k.current!==null&&typeof window<`u`&&(window.clearTimeout(k.current),k.current=null)}),H=J(()=>{!I||!P||!L||typeof window>`u`||(V(),O(!0),k.current=window.setTimeout(()=>{O(!1),k.current=null},1800))});Q.useEffect(()=>{L||(O(!1),V())},[V,L]);let ee=J(e=>{!l||!L||(e.stopPropagation(),e.preventDefault(),l(),I&&H())}),U=w===`mini-chat`||!T.fork?void 0:h,te=Q.useMemo(()=>{if(typeof i!=`number`||i<=0)return null;let e=PA(i,E);return e.length>0?e:null},[S,i,E]),W=Y(`group/user-actions`,a?b===`inline`?`flex items-center justify-end pt-2 pb-3`:x?`flex h-9 items-start justify-end pt-0`:`flex h-11 items-start justify-end pt-0`:b===`inline`?`absolute top-full left-0 right-0 z-10 pt-5`:`flex h-8 items-start justify-end pt-2`),ne=!_&&v&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsxs)(`div`,{className:Y(rM,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-auto opacity-100`),"data-message-action-group":`true`,children:[(0,$.jsxs)(`span`,{className:Y(aM,`text-primary`),"aria-live":`polite`,children:[(0,$.jsx)(Z,{weight:sM,name:`edit`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:C(`chat.messageBody.actions.editStaged`)})]}),y?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.cancelEdit`),onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),y()},children:(0,$.jsx)(Z,{weight:sM,name:`close`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.cancelEdit`)})]}):null]})}):null,G=(_&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsx)(`div`,{className:Y(rM,`justify-end`,!a&&b===`inline`&&`translate-x-5`,`pointer-events-none opacity-100`),children:(0,$.jsx)(`span`,{className:Y(aM,`animate-text-shimmer`),"aria-live":`polite`,children:C(`chat.messageBody.actions.editing`)})})}):null)??ne??((P&&L||p||m||U)&&z?(0,$.jsx)(`div`,{className:W,children:(0,$.jsxs)(`div`,{className:Y(rM,`justify-end`,!a&&b===`inline`&&`translate-x-5`,o?`pointer-events-auto opacity-100`:`pointer-events-none opacity-0 transition-opacity duration-150 group-hover/message:pointer-events-auto group-hover/message:opacity-100 group-hover/user-actions:pointer-events-auto group-hover/user-actions:opacity-100 group-hover/user-shell:pointer-events-auto group-hover/user-shell:opacity-100`),"data-message-action-group":`true`,children:[te?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:Y(aM,`mr-1`),"aria-label":`Message time: ${te}`,children:[(0,$.jsx)(Z,{weight:sM,name:`time`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:te})]})}),(0,$.jsx)(Jo,{children:te})]}):null,m&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.revertAria`),"aria-busy":g===`revert`,disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),m()},children:(0,$.jsx)(Z,{weight:sM,name:g===`revert`?`loader-4`:`arrow-go-back`,className:Y(eM,g===`revert`&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.revert`)})]}),p&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.editAria`),disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),p()},children:(0,$.jsx)(Z,{weight:sM,name:`edit`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.edit`)})]}),U&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":C(`chat.messageBody.actions.forkAria`),"aria-busy":g===`fork`,disabled:!!g,onPointerDown:e=>e.stopPropagation(),onClick:e=>{e.stopPropagation(),U()},children:(0,$.jsx)(Z,{weight:sM,name:g===`fork`?`loader-4`:`git-branch`,className:Y(eM,g===`fork`&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.fork`)})]}),P&&L&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":D||F?`true`:void 0,className:$j,"aria-label":C(`chat.messageBody.actions.copyMessageAria`),onPointerDown:e=>e.stopPropagation(),onClick:ee,onFocus:()=>O(!0),onBlur:()=>{F||O(!1)},children:F?(0,$.jsx)(Z,{weight:sM,name:`check`,className:Y(eM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(Z,{weight:sM,name:`file-copy`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:C(`chat.messageBody.actions.copyMessage`)})]})]})}):null);return R?(0,$.jsxs)(`div`,{className:`relative w-full group/message`,"data-user-message-body":`true`,style:Yj,onTouchStart:I&&P&&L?H:void 0,children:[(0,$.jsx)(`div`,{className:Y(`leading-relaxed text-foreground/90 text-base overflow-x-hidden`,B?`overflow-y-auto overscroll-contain scrollbar-none`:`overflow-y-hidden`),style:B?{maxHeight:`calc(var(--chat-scroll-height, 100dvh) * 0.4)`}:void 0,children:A.map((e,i)=>{if(yM(e))return(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(SM,{part:e})},e.id??`user-subtask-${i}`);if(bM(e))return(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(TM,{part:e})},e.id??`user-shell-${i}`);let o=j[i];if(o)return(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(CM,{notification:o})},e.id??`subagent-notification-${i}`);let s;return f&&M&&!N&&qa(e).includes(M)&&(s=f,N=!0),(0,$.jsx)(Q.Fragment,{children:(0,$.jsx)(FT,{part:e,messageId:t,isMobile:a,agentMention:s,messageParts:r??n})},e.id??`user-text-${i}`)})}),(0,$.jsx)(mg,{files:n,messageID:t,sessionID:e,onShowPopup:d,compact:!0}),G]}):(0,$.jsx)($.Fragment,{children:G})}),kM=Q.memo(({hasCopyableText:e,isTouchContext:t,onCopyMessage:n,reviewTransferAction:r,ttsText:i,sessionId:a})=>{let{t:o}=Yt(),s=Fb(),c=Zy(),l=Qy(c),{isPlaying:u,play:d,stop:f}=mA(),p=Oa(e=>e.showMessageTTSButtons),m=Oa(e=>e.voiceProvider),[h,g]=Q.useState(!1),[_,v]=Q.useState(!1),[y,b]=Q.useState(!1),x=Q.useRef(null),S=Q.useRef(null),C=!!n,w=!!((c.sessionId||a)&&c.directory&&l.openSourceSession&&s!==`mini-chat`),T=J(()=>{x.current!==null&&typeof window<`u`&&(window.clearTimeout(x.current),x.current=null)}),E=J(()=>{S.current!==null&&typeof window<`u`&&(window.clearTimeout(S.current),S.current=null)});Q.useEffect(()=>()=>{T(),E()},[E,T]),Q.useEffect(()=>{(!e||!C)&&(g(!1),v(!1),T(),E())},[C,E,T,e]);let D=J(()=>{!t||!C||!e||typeof window>`u`||(T(),g(!0),x.current=window.setTimeout(()=>{g(!1),x.current=null},1800))}),O=J(async r=>{!n||!e||(r.stopPropagation(),r.preventDefault(),await n()!==!1&&(E(),v(!0),typeof window<`u`&&(S.current=window.setTimeout(()=>{v(!1),S.current=null},2e3)),t&&D()))}),k=J(async t=>{if(t.stopPropagation(),t.preventDefault(),!(!r||y||!e)){b(!0);try{await r.onClick()}finally{b(!1)}}}),A=J(e=>{e.stopPropagation(),e.preventDefault();let t=c.sessionId||a;!t||!c.directory||!c.openSourceSession||c.openSourceSession(t,c.directory)}),j=Q.useMemo(()=>u?o(`chat.messageBody.tts.stopSpeaking`):o(`chat.messageBody.tts.readAloudWithProvider`,{provider:m===`browser`?`Browser`:m===`openai`?`OpenAI`:m===`openai-compatible`?`Custom`:`Say`}),[u,o,m]),M=J(e=>{if(e.stopPropagation(),e.preventDefault(),u){f();return}i.trim()&&d(i)});return(0,$.jsxs)($.Fragment,{children:[n&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,"data-visible":h||_?`true`:void 0,className:Y($j,!e&&`opacity-50`),disabled:!e,"aria-label":o(`chat.messageBody.actions.copyMessageAria`),"aria-hidden":!e,onPointerDown:e=>e.stopPropagation(),onClick:e=>{O(e)},onFocus:()=>{e&&g(!0)},onBlur:()=>{_||g(!1)},children:_?(0,$.jsx)(Z,{weight:sM,name:`check`,className:Y(eM,`text-[color:var(--status-success)]`)}):(0,$.jsx)(Z,{weight:sM,name:`file-copy`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:o(`chat.messageBody.actions.copyAnswer`)})]}),w?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":o(`chat.messageBody.actions.openSourceSessionAria`),onPointerDown:e=>e.stopPropagation(),onClick:A,children:(0,$.jsx)(Z,{weight:sM,name:`target`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:o(`chat.messageBody.actions.openSourceSession`)})]}):null,r&&s!==`mini-chat`&&l.reviewTransfer?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,size:`icon`,variant:`ghost`,disabled:y||!e,className:Y($j,(!e||y)&&`opacity-50`),"aria-label":r.ariaLabel,onPointerDown:e=>e.stopPropagation(),onClick:e=>{k(e)},children:y?(0,$.jsx)(Z,{weight:sM,name:`loader-4`,className:Y(eM,`animate-spin`)}):(0,$.jsx)(Z,{weight:sM,name:`arrow-left-right`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:r.tooltip})]}):null,s!==`mini-chat`&&p&&e&&(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:Y($j,u?`text-green-500`:`hover:text-foreground/80`),"aria-label":o(u?`chat.messageBody.tts.stopSpeaking`:`chat.messageBody.tts.readAloud`),onPointerDown:e=>e.stopPropagation(),onClick:M,children:u?(0,$.jsx)(Z,{weight:sM,name:`stop`,className:eM}):(0,$.jsx)(Z,{weight:sM,name:`volume-up`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:j})]})]})}),AM=Q.memo(({sessionId:e,messageId:t,parts:n,sourceParts:r,isMessageCompleted:i,messageFinish:a,messageCompletedAt:o,messageCreatedAt:s,messageTokens:c,isMobile:l,alwaysShowActions:u,hasTouchInput:d,expandedTools:f,onToggleTool:p,onShowPopup:m,streamPhase:h,allowAnimation:g,onContentChange:_,hasTextContent:v=!1,onCopyMessage:y,onAuxiliaryContentComplete:b,showReasoningTraces:x=!1,turnGroupingContext:S,errorMessage:C,errorVariant:w=`error`,reviewTransferDirection:T=null})=>{let{t:E,locale:D}=Yt(),O=Fb(),k=Qy(Zy()),A=h,j=Q.useRef(null),M=Q.useRef(null),N=h===`streaming`||h===`cooldown`,P=Q.useRef({messageId:t,experiencedStreamingOrCooldown:N});P.current.messageId===t?N&&(P.current.experiencedStreamingOrCooldown=!0):P.current={messageId:t,experiencedStreamingOrCooldown:N};let F=!!(d??l),I=!!(u??l),L=l?nM:tM,R=!i,z=Q.useMemo(()=>n.filter(e=>!Dn(e)).filter(e=>e.type!==`compaction`),[n]),B=Q.useMemo(()=>z.filter(e=>e.type===`tool`),[z]),V=Q.useMemo(()=>z.filter(e=>e.type===`text`),[z]),H=Q.useMemo(()=>Ln(V),[V]),ee=q(e=>e.openContextPreview),U=ge(),te=O===`mini-chat`,W=Q.useMemo(()=>{if(U||l||te)return null;for(let e of V){let t=e.text;if(typeof t!=`string`||t.length===0)continue;let n=Rl(t)[0];if(n)return n.includes(`0.0.0.0`)?n.replace(`0.0.0.0`,`127.0.0.1`):n}for(let e of B){let t=e.state,n=t&&typeof t.output==`string`?t.output:null;if(!n)continue;let r=Rl(n.replace(/\x1b\[[0-9;]*m/g,``))[0];if(r)return r.includes(`0.0.0.0`)?r.replace(`0.0.0.0`,`127.0.0.1`):r}return null},[V,l,te,U,B]),ne=X(e=>e.forkFromMessage),G=X(e=>e.forkTransition),re=X(e=>e.currentSessionId),ie=X(e=>e.getDirectoryForSession),K=Hl(),ae=T===`review-to-original`,oe=!l&&!U?T:null,se=Q.useMemo(()=>{let t=H.trim();if(!(!e||!K||!t||!oe))return oe===`review-to-original`?{ariaLabel:E(`chat.messageBody.actions.sendReviewFeedback`),tooltip:E(`chat.messageBody.actions.sendReviewFeedback`),onClick:async()=>{try{await or(e,K,t)}catch(e){console.error(`[review-flow] failed to send review feedback`,e)}}}:{ariaLabel:E(`chat.messageBody.actions.sendImplementationResponse`),tooltip:E(`chat.messageBody.actions.sendImplementationResponse`),onClick:async()=>{try{await Qi(e,K,t)}catch(e){console.error(`[review-flow] failed to send implementation response`,e)}}}},[H,K,oe,e,E]),[ce,le]=Q.useState(!1),ue=q(e=>e.chatRenderMode),de=q(e=>e.collapsibleThinkingBlocks),fe=q(e=>e.showSplitAssistantMessageActions),pe=q(e=>e.showAssistantTps),me=q(e=>e.timeFormatPreference),he=ue===`sorted`,_e=S?.isLastAssistantInTurn??!1,ve=a===`stop`,ye=(ve||i||!!C)&&(S?.isTurnSettled??!0),be=ve?`completed`:A,xe=B.length>0,Se=Q.useMemo(()=>B.some(e=>HD(e)),[B]),Ce=HD,we=VD,Te=P.current.experiencedStreamingOrCooldown,Ee=Q.useRef({messageId:t,initialized:!1,observedPartIds:new Set});Q.useEffect(()=>{if(Ee.current.messageId!==t&&(Ee.current={messageId:t,initialized:!1,observedPartIds:new Set}),!Te||!Cn())return;let n=Ee.current,r=!n.initialized;n.initialized=!0;for(let i of B){if(n.observedPartIds.has(i.id))continue;if(!gr(r,Ce(i))){n.observedPartIds.add(i.id);continue}let a=e??i.sessionID;a&&(n.observedPartIds.add(i.id),Nr({sessionID:a,messageID:t,partID:i.id,kind:`tool`}))}},[Te,Ce,t,e,B]);let De=Q.useMemo(()=>B.length===0||!Se&&B.every(e=>we(e)),[B,Se,we]),Oe=Q.useMemo(()=>z.filter(e=>e.type===`reasoning`),[z]),ke=Q.useMemo(()=>Oe.length===0||Oe.every(e=>typeof e.time?.end==`number`),[Oe]),Ae=typeof a!=`string`,je=Oe.length>0&&xe&&(Se||Ae||!De),Me=R||xe&&(Se||Ae||!De),Ne=R||je,Pe=xe||Oe.length>0,Fe=V.length===0,Ie=Pe&&Fe&&!Me&&!Ne&&De&&ke,Le=Q.useRef(!1),Re=Q.useRef(!1);Q.useEffect(()=>{Re.current=!1},[t]),Q.useEffect(()=>{if(!Ie){Le.current=!1;return}Le.current||(Le.current=!0,b?.())},[Ie,b]),Q.useEffect(()=>{if(R){Re.current=!1;return}if(xe){Re.current=!1;return}Oe.length!==0&&(Ne||!ke||Re.current||(Re.current=!0,_?.(`structural`)))},[R,xe,_,ke,Oe.length,Ne]);let ze=!!v&&!R,Be=J(async n=>{if(n.stopPropagation(),n.preventDefault(),!(!e||!t||ce||G)){le(!0);try{await ne(e,t)}finally{le(!1)}}}),Ve=Q.useMemo(()=>{let e=S?.activityParts;return!he||!e?[]:e},[he,S?.activityParts]),He=Q.useMemo(()=>{let e=S?.activityGroupSegments;return!he||!e?[]:e.filter(e=>e.anchorMessageId===t)},[he,t,S?.activityGroupSegments]),Ue=He.length>0,We=Q.useMemo(()=>{let e=new Map,t=new Map;return Ve.forEach(n=>{e.set(n.part,n);let r=n.part.id;typeof r==`string`&&r.length>0&&t.set(r,n)}),{get:n=>{let r=e.get(n);if(r)return r;let i=n.id;if(typeof i==`string`&&i.length>0)return t.get(i)}}},[Ve]),Ge=S?.toggleGroup,Ke=S?.activityPresentationKind===`compaction`,qe=S?.isGroupExpanded===!0,Je=he&&Ke&&!qe,Ye=he?S?.activityOwnerMessageId===t||Ue:!S?.activityOwnerMessageId||S.activityOwnerMessageId===t||Ue,Xe=he&&Ye&&(Ue||Ke)&&!!Ge,Ze=Uk(a,z),Qe={finish:a,parts:z,streamPhase:be,error:C,isLastAssistantInTurn:_e},$e=Jk(Qe),et=he&&Yk(Qe),tt=he&&!$e&&!(Ke&&qe),nt=!!C,rt=w===`info`?`information`:`error-warning`,it=w===`muted`,at=ze,ot=_e&&ye&&!Je&&(v||!!C||i),st=S?.diffStats?.hasDiffs===!0,ct=!te&&_e&&Ze&&ye&&!Je&&S?.diffStats?.hasDiffs===!0,lt=fe&&at&&!ot&&!he,ut=Q.useMemo(()=>(0,$.jsx)(kM,{hasCopyableText:ze,isTouchContext:F,onCopyMessage:y,ttsText:H,reviewTransferAction:se,sessionId:e}),[H,ze,F,y,se,e]),dt=Q.useMemo(()=>e=>{if(!fe||!he)return null;let t=qa(e.part).trim();return t?(0,$.jsx)(kM,{hasCopyableText:!0,isTouchContext:F,onCopyMessage:async()=>(await Jt(t)).ok,ttsText:t}):null},[he,F,fe]),ft=Q.useMemo(()=>{if(!lt)return-1;let e=-1;for(let t=0;t<z.length;t+=1){let n=z[t];!n||n.type!==`text`||tt||We.get(n)?.kind!==`justification`&&(e=t)}return e},[We,tt,lt,z]),pt=lt&&ft<0,mt=Q.useMemo(()=>{let n=[];if(Xe&&Ge&&S){let e=(e,t,r=t)=>{n.push((0,$.jsx)(`div`,{children:(0,$.jsx)(Jj,{parts:t,materializationParts:r,isExpanded:S.isGroupExpanded===!0,collapsedPreviewCount:0,completionDisposition:S.completionDisposition,activityPresentationKind:S.activityPresentationKind,durationMs:S.durationMs,startedAt:S.userMessageCreatedAt,onToggle:Ge,isMobile:l,expandedTools:f,onToggleTool:p,onShowPopup:m,onContentChange:_,streamPhase:be,showHeader:!0,diffStats:S.diffStats,renderJustificationActions:dt})},`progressive-group-${e}`))};He.length>0?He.forEach(t=>{let n=x?t.parts:t.parts.filter(e=>e.kind!==`reasoning`);e(t.id,n,t.parts)}):Ke&&e(`${t}:compaction-status`,[])}let r=0;for(;r<z.length;){let i=z[r];if(i.type===`text`){let a=We.get(i);if(tt){r+=1;continue}if(Je){r+=1;continue}if(a?.kind===`justification`){r+=1;continue}n.push((0,$.jsx)(`div`,{ref:M,"data-message-text-export-source":`true`,children:(0,$.jsx)(xk,{part:i,sessionId:e,messageId:t,streamPhase:be,chatRenderMode:ue,allowSortedFinalStreaming:et,hasStreamingHapticLifecycle:Te,onContentChange:_,onShowPopup:m})},`assistant-text-${t}-${i.id??r}`)),lt&&r===ft&&n.push((0,$.jsx)(`div`,{className:l?Qj:Zj,"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:rM,"data-message-action-group":`true`,children:ut})},`message-actions-${t}`)),r++;continue}if(i.type===`reasoning`){if(We.get(i)?.kind===`reasoning`){r+=1;continue}if(!qa(i).trim()){r+=1;continue}x&&(de?n.push((0,$.jsx)(`div`,{className:Ev(l),children:(0,$.jsx)(Nk,{part:i,messageId:t,streamPhase:be,onContentChange:_})},`reasoning-${t}-${i.id??r}`)):n.push((0,$.jsx)(xk,{part:i,sessionId:e,messageId:t,streamPhase:be,chatRenderMode:ue,hasStreamingHapticLifecycle:Te,onContentChange:_,onShowPopup:m},`reasoning-${t}-${i.id??r}`))),r++;continue}if(i.type===`tool`){let e=i,a=e.tool?.toLowerCase()??``;if(he&&!Ye){r+=1;continue}if(We.get(i)?.kind===`tool`){r+=1;continue}if(BD(a)){let e=rj(z,r,e=>e.type!==`tool`||We.get(e)?.kind===`tool`?``:e.tool);if(e.items.length>0){let i=e.items.map((e,n)=>{let i=e;return{id:i.id,turnId:``,messageId:t,partIndex:r+n,part:i,kind:`tool`}});n.push((0,$.jsx)(oj,{activities:i,isMobile:l,isTurnLive:be!==`completed`,hasFollowingOtherType:tj(z,e.end,e=>({type:e.type,toolName:e.type===`tool`?e.tool:void 0})),children:i.map(e=>{let n=e.part.tool?.toLowerCase()??``;return LD(n)?(0,$.jsx)(Bj,{toolName:n,activities:[e],isMobile:l,animateTailText:!1},e.id):(0,$.jsx)(tk,{part:e.part,messageId:t,isExpanded:f.has(e.part.id),onToggle:p,isMobile:l,alwaysShowActions:I,onContentChange:_,onShowPopup:m,animateTailText:!1},e.id)})},`context-tools-${i[0].id}`)),r=e.end;continue}}if(RD(a)){let e=sj(z,r,e=>e.type!==`tool`||We.get(e)?.kind===`tool`?``:e.tool);if(e.items.length>0){let i=e.items.map((e,n)=>{let i=e;return{id:i.id,turnId:``,messageId:t,partIndex:r+n,part:i,kind:`tool`}});n.push((0,$.jsx)(fj,{activities:i,isMobile:l,children:i.map(e=>(0,$.jsx)(Bj,{toolName:e.part.tool?.toLowerCase()??``,activities:[e],isMobile:l,animateTailText:!1},e.id))},`skill-tools-${i[0].id}`)),r=e.end;continue}}if(PD(a)){n.push((0,$.jsx)(`div`,{className:Ev(l),children:(0,$.jsx)(tk,{part:e,messageId:t,isExpanded:f.has(e.id),onToggle:p,isMobile:l,alwaysShowActions:I,onContentChange:_,onShowPopup:m,animateTailText:!1})},`tool-${e.id}`)),r++;continue}n.push((0,$.jsx)(`div`,{className:Ev(l),children:(0,$.jsx)(Bj,{toolName:a,activities:[{id:e.id,turnId:``,messageId:t,partIndex:r,part:e,kind:`tool`}],isMobile:l,animateTailText:!1})},`static-tools-${e.id}`)),r++;continue}r++}return n},[We,He,I,ue,de,0,f,Je,Ke,l,Ye,he,ft,t,ut,dt,e,_,m,p,Xe,lt,be,Te,x,tt,et,Ge,S,z]),ht=Q.useMemo(()=>{if(!_e||!ye)return;let e=S?.durationMs;if(!(typeof e!=`number`||e<=0))return EM(e)},[_e,ye,S?.durationMs]),gt=Q.useMemo(()=>{let e=typeof o==`number`&&o>0?o:typeof s==`number`&&s>0?s:null;if(e===null)return null;let t=PA(e,me);return t.length>0?t:null},[o,s,me,D]),_t=Q.useMemo(()=>{if(!pe||!_e||!ye)return null;let e=r??n,t=DM(e,c),i=zA({createdAt:s,completedAt:o,fallbackDurationMs:S?.durationMs,outputTokens:t.output,reasoningTokens:t.reasoning,parts:e});if(i===null)return null;let a=BA(i);return a.length>0?a:null},[pe,_e,ye,n,r,c,s,o,S?.durationMs]),vt=(0,$.jsxs)($.Fragment,{children:[!te&&!l&&!U&&W?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:$j,"aria-label":E(`chat.messageBody.actions.openPreviewAria`),onPointerDown:e=>e.stopPropagation(),onClick:()=>{let e=K??(re?ie(re):null);e&&ee(e,W)},children:(0,$.jsx)(Z,{weight:sM,name:`global`,className:eM})})}),(0,$.jsx)(Jo,{sideOffset:6,children:E(`chat.messageBody.actions.openPreview`)})]}):null,!te&&!ae&&k.fork?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,size:`icon`,variant:`ghost`,className:$j,"aria-label":E(`chat.messageBody.actions.forkAria`),"aria-busy":ce,disabled:ce||!!G,onPointerDown:e=>e.stopPropagation(),onClick:e=>{Be(e)},children:(0,$.jsx)(Z,{weight:sM,name:ce?`loader-4`:`git-branch`,className:Y(eM,ce&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:E(`chat.messageBody.actions.fork`)})]}):null]});return(0,$.jsxs)(`div`,{ref:j,"data-message-text-export-root":`true`,className:Y(`relative w-full group/message`),style:Yj,children:[(0,$.jsx)(AA,{containerRef:j}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`message-content-text leading-relaxed text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0`,children:[mt,nt&&(0,$.jsx)(Xl,{children:it?(0,$.jsxs)(`div`,{role:`status`,className:`my-1.5 flex max-w-full items-center gap-1.5 break-words typography-meta text-muted-foreground`,children:[(0,$.jsx)(Z,{name:`stop-circle`,className:`size-3.5 shrink-0`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`min-w-0`,children:C})]}):(0,$.jsxs)(`div`,{className:Y(`group/assistant-text relative flow-root my-1.5 break-words max-w-full`,w===`info`?Y(`inline-flex w-fit max-w-full border border-[var(--status-info-border)]/45 bg-[var(--status-info-background)]/40`,l?`items-start gap-1.5 rounded-lg px-2.5 py-1.5`:Y(`items-center gap-1.5`,`rounded-lg px-2 py-0.5`)):`mt-3 flex items-center gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3`),children:[w===`info`&&l?(0,$.jsx)(`span`,{className:`inline-flex h-5 w-3.5 shrink-0 items-center justify-center translate-y-[2px]`,"aria-hidden":`true`,children:(0,$.jsx)(Z,{name:rt,weight:sM,className:Y(eM,`text-[var(--status-info)]/80`)})}):(0,$.jsx)(Z,{name:rt,weight:w===`info`?sM:void 0,className:Y(`shrink-0`,w===`info`?Y(eM,`text-[var(--status-info)]/80`):`h-4 w-4 text-[var(--status-error)]`)}),(0,$.jsx)(`div`,{className:Y(`min-w-0 break-words`,w===`info`?Y(`text-muted-foreground [&_.markdown-content]:text-muted-foreground [&_p]:m-0`,`[&_.markdown-content]:!leading-5`,l?`[&_.markdown-content]:!text-[length:var(--text-meta)]`:`[&_.markdown-content]:!text-[13px]`):`flex-1`),children:(0,$.jsx)(gl,{content:C??``,onShowPopup:m,className:`[&_.markdown-content>*:first-child]:mt-0 [&_.markdown-content>*:last-child]:mb-0`,enableFileReferences:!1})})]})},`assistant-error`)]}),ct&&S?.diffStats?(0,$.jsx)(vM,{fileCount:S.diffStats.files,changedFiles:S.changedFiles,turnId:S.turnId,isLatestTurn:S.isLatestTurn,isMobile:l}):null,(0,$.jsx)(mg,{files:n,messageID:t,sessionID:e,onShowPopup:m}),pt&&(0,$.jsx)(`div`,{className:Y(l?Qj:Zj),"data-message-actions":`true`,children:(0,$.jsx)(`div`,{className:rM,"data-message-action-group":`true`,children:ut})}),ot&&(0,$.jsxs)(`div`,{className:L,"data-message-footer":`true`,style:Xj,children:[(0,$.jsxs)(`div`,{className:rM,"data-message-action-group":`true`,children:[ut,vt]}),_t||ht||gt?(0,$.jsxs)(`div`,{className:iM,children:[_t?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:aM,"aria-label":E(`chat.messageBody.meta.tpsAria`,{rate:_t}),children:[(0,$.jsx)(Z,{weight:sM,name:`pulse`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:_t})]})}),(0,$.jsx)(Jo,{children:E(`chat.messageBody.meta.tpsTooltip`)})]}):null,ht?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:aM,children:[(0,$.jsx)(Z,{weight:sM,name:`hourglass`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:ht})]})}),(0,$.jsx)(Jo,{children:ht})]}):null,gt?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsxs)(`span`,{className:aM,"aria-label":`Message time: ${gt}`,children:[(0,$.jsx)(Z,{weight:sM,name:`time`,className:oM}),(0,$.jsx)(`span`,{className:`message-footer__label`,children:gt})]})}),(0,$.jsx)(Jo,{children:gt})]}):null]}):null,!te&&_e&&ve&&!st?(0,$.jsx)(Lk,{activityParts:S?.activityParts}):null]})]})]})}),jM=Q.memo(e=>{let t=(0,pd.c)(28),n,r;if(t[0]===e?(n=t[1],r=t[2]):({isUser:n,...r}=e,t[0]=e,t[1]=n,t[2]=r),n){let e;return t[3]!==r.agentMention||t[4]!==r.alwaysShowActions||t[5]!==r.copiedMessage||t[6]!==r.editStaged||t[7]!==r.editing||t[8]!==r.hasTextContent||t[9]!==r.hasTouchInput||t[10]!==r.isMobile||t[11]!==r.messageCreatedAt||t[12]!==r.messageId||t[13]!==r.onCancelEdit||t[14]!==r.onCopyMessage||t[15]!==r.onEdit||t[16]!==r.onFork||t[17]!==r.onRevert||t[18]!==r.onShowPopup||t[19]!==r.parts||t[20]!==r.pendingMessageAction||t[21]!==r.sessionId||t[22]!==r.sourceParts||t[23]!==r.stickyUserHeaderEnabled||t[24]!==r.userActionsMode?(e=(0,$.jsx)(OM,{sessionId:r.sessionId,messageId:r.messageId,parts:r.parts,sourceParts:r.sourceParts,messageCreatedAt:r.messageCreatedAt,isMobile:r.isMobile,alwaysShowActions:r.alwaysShowActions,hasTouchInput:r.hasTouchInput,hasTextContent:r.hasTextContent,onCopyMessage:r.onCopyMessage,copiedMessage:r.copiedMessage,onShowPopup:r.onShowPopup,agentMention:r.agentMention,onEdit:r.onEdit,onRevert:r.onRevert,onFork:r.onFork,pendingMessageAction:r.pendingMessageAction,editing:r.editing,editStaged:r.editStaged,onCancelEdit:r.onCancelEdit,userActionsMode:r.userActionsMode,stickyUserHeaderEnabled:r.stickyUserHeaderEnabled}),t[3]=r.agentMention,t[4]=r.alwaysShowActions,t[5]=r.copiedMessage,t[6]=r.editStaged,t[7]=r.editing,t[8]=r.hasTextContent,t[9]=r.hasTouchInput,t[10]=r.isMobile,t[11]=r.messageCreatedAt,t[12]=r.messageId,t[13]=r.onCancelEdit,t[14]=r.onCopyMessage,t[15]=r.onEdit,t[16]=r.onFork,t[17]=r.onRevert,t[18]=r.onShowPopup,t[19]=r.parts,t[20]=r.pendingMessageAction,t[21]=r.sessionId,t[22]=r.sourceParts,t[23]=r.stickyUserHeaderEnabled,t[24]=r.userActionsMode,t[25]=e):e=t[25],e}let i;return t[26]===r?i=t[27]:(i=(0,$.jsx)(AM,{...r}),t[26]=r,t[27]=i),i});function MM(e){return e.openContextPanelTab}function NM(e){return e.setCurrentSession}function PM(e){return e.openContextPanelTab}function FM(e){return!e}function IM(e){return e.openContextPanelTab}function LM(e){return!e}var RM=e=>{let t=e,n=t?.clientRole,r=t?.role;return t?.userMessageMarker===!0||n===`user`||r===`user`||t?.origin===`user`||t?.source===`user`?{role:`user`,isUser:!0}:{role:n||r||`assistant`,isUser:!1}},zM=(e,t,n)=>e===`active`||n?.isLastTurn&&n.hasConfirmedFinalBody!==!0?!0:t===`summary`,BM=e=>!e,VM=e=>e.completionDisposition===`active`?e.isLastTurn&&e.sessionIsWorking?{completionDisposition:`active`,durationMs:e.durationMs}:{completionDisposition:`abnormal`,durationMs:e.durationMs}:{completionDisposition:e.completionDisposition,durationMs:e.durationMs},HM=e=>!(e.completionDisposition===`active`||e.isLastTurn&&e.sessionIsWorking&&!e.hasConfirmedSettledAssistant),UM=e=>e.isWorking?!0:e.isInActiveTurn?e.headerCompletionDisposition!==`normal`&&e.headerCompletionDisposition!==`abnormal`:!1,WM=e=>e.turnCompletionDisposition===`active`&&(e.isLastTurn||e.hasAssistantMessages)?`active`:e.headerPresentationDisposition,GM=`Authentication failed for this provider. Please re-authenticate and retry.`,KM=e=>{if(typeof e!=`string`)return!1;let t=e.toLowerCase().trim();if(!t)return!1;if(t.includes(`token refresh failed`)||t.includes(`unauthorized`)||t.includes(`invalid token`)||t.includes(`expired token`))return!0;let n=t.includes(`oauth`),r=t.includes(`failed`)||t.includes(`invalid`)||t.includes(`expired`);if(n&&r)return!0;let i=/\b401\b/.test(t),a=t.includes(`auth`)||t.includes(`token`)||t.includes(`unauthorized`);return i&&a};function qM(e,t){if(!e||typeof e!=`object`)return;let n=e,r=typeof n.data?.message==`string`?n.data.message:void 0,i=typeof n.message==`string`?n.message:void 0,a=typeof n.name==`string`?n.name:void 0,o=r||i||a;if(o)return a===`SessionRetry`?{text:`Opencode failed to send a message. Retry attempt info: \n\`${o}\``,variant:`info`}:KM(o)?{text:GM,variant:`error`}:a===`MessageAbortedError`||o.trim().toLowerCase()===`aborted`?{text:t,variant:`muted`}:{text:`Opencode failed to send message with error:\n\`${o}\``,variant:`error`}}var JM=_l(()=>Et(()=>import(`./ToolOutputDialog-nhZwyPOH.js`),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52]))),YM=4e3,XM=new Map,ZM=new Map,QM=new Set([`bash`,`shell`,`cmd`,`terminal`]),$M=e=>{if(typeof e!=`string`)return``;let t=e.trim().toLowerCase();if(!t)return``;let n=t.replace(/:\d+$/,``);if(!n.includes(`.`))return n;let r=n.split(`.`).filter(Boolean);return r[r.length-1]??n},eN=e=>{let t=XM.get(e);return t?new Set(t):new Set},tN=(e,t)=>{if(XM.size>=YM&&!XM.has(e)){let e=XM.keys().next().value;typeof e==`string`&&XM.delete(e)}XM.set(e,new Set(t))},nN=e=>{let t=ZM.get(e);return t?new Set(t):new Set},rN=(e,t)=>{if(ZM.size>=YM&&!ZM.has(e)){let e=ZM.keys().next().value;typeof e==`string`&&ZM.delete(e)}ZM.set(e,new Set(t))},iN=200,aN=new Map,oN=e=>aN.get(e),sN=(e,t)=>{if(!t.agent&&!t.provider&&!t.model)return;let n=aN.get(e);if(!(n&&n.agent===t.agent&&n.provider===t.provider&&n.model===t.model)){if(aN.size>=iN&&!aN.has(e)){let e=aN.keys().next().value;typeof e==`string`&&aN.delete(e)}aN.set(e,t)}};function cN(e){let t=(0,pd.c)(3),[n,r]=Q.useState(e),i,a;return t[0]===e?(i=t[1],a=t[2]):(i=()=>{e!=null&&r(e)},a=[e],t[0]=e,t[1]=i,t[2]=a),Q.useEffect(i,a),e??n}var lN=(e,t)=>{if(typeof e==`object`&&e)return e[t]},uN=Q.memo(({message:e,previousMessage:t,nextMessage:n,onContentChange:r,animationHandlers:i,turnGroupingContext:a,assistantHeaderMessageId:o,turnOwnsAssistantHeader:s=!1,isInActiveTurn:c=!1,activeStreamingPhase:l=null,animateUserOnMount:u=!1,onUserAnimationConsumed:d,reviewTransferDirection:f=null})=>{let{t:p}=Yt(),{isMobile:m,isTablet:h,hasTouchInput:g}=qs(),_=Zy(),v=Qy(_),y=m||h,b=Q.useRef(null),x=X(e=>e.currentSessionId),S=Hr(e=>e.getAgentModelForSession),C=Hr(e=>e.getSessionModelSelection),w=X(e=>e.revertToMessage),T=X(e=>e.editMessagePreservingChanges),E=X(e=>e.forkFromMessage),D=X(t=>t.messageEditCommitting?.messageId===e.info.id&&t.messageEditCommitting?.sessionId===e.info.sessionID),O=X(t=>t.stagedMessageEdit?.messageId===e.info.id&&t.stagedMessageEdit?.sessionId===e.info.sessionID),k=X(e=>e.clearStagedMessageEdit);pt(`ui.chat_message.render`),c&&pt(`ui.chat_message.render.streaming`);let A=Oa(e=>e.providers),{showReasoningTraces:j,stickyUserHeader:M,chatRenderMode:N,showExpandedBashTools:P}=q(He(e=>({showReasoningTraces:e.showReasoningTraces,stickyUserHeader:e.stickyUserHeader,chatRenderMode:e.chatRenderMode,showExpandedBashTools:e.showExpandedBashTools})));Q.useEffect(()=>{x&&CT.getInstance().recordSessionStart(x)},[x]);let[F,I]=Q.useState(null),[L,R]=Q.useState(!1),[z,B]=Q.useState(null),V=Q.useRef(null),[H,ee]=Q.useState(()=>eN(e.info.id)),[U,te]=Q.useState(()=>nN(e.info.id)),[W,ne]=Q.useState({open:!1,title:``,content:``});Q.useEffect(()=>{ee(eN(e.info.id)),te(nN(e.info.id))},[e.info.id]);let G=Q.useMemo(()=>RM(e.info),[e.info]).isUser,re=G&&(m||!M),ie=G&&!m&&M&&!re,K=e.info.sessionID,{currentContextAgent:ae,savedSessionAgentSelection:oe}=Hv(He(e=>({currentContextAgent:c&&K?e.currentAgentContext.get(K):void 0,savedSessionAgentSelection:c&&K?e.sessionAgentSelections.get(K):void 0}))),se=Q.useMemo(()=>xn(e.sourceParts??e.parts),[e.parts,e.sourceParts]),ce=Q.useMemo(()=>G?_n(se):xn(e.parts),[G,e.parts,se]),le=Q.useMemo(()=>{if(G||!t)return null;let e=lN(t.info,`clientRole`),n=lN(t.info,`role`);if((typeof e==`string`?e:typeof n==`string`?n:void 0)!==`user`)return null;let r=lN(t.info,`mode`),i=lN(t.info,`agent`),a=lN(t.info,`providerID`),o=lN(t.info,`modelID`),s=lN(t.info,`model`),c=typeof s==`object`&&s?s.variant:void 0,l=lN(t.info,`variant`),u=c??l,d=typeof s==`object`&&s?s.providerID:void 0,f=typeof s==`object`&&s?s.modelID:void 0,p=typeof r==`string`&&r.trim().length>0?r:typeof i==`string`&&i.trim().length>0?i:void 0,m=typeof a==`string`&&a.trim().length>0?a:typeof d==`string`&&d.trim().length>0?d:void 0,h=typeof o==`string`&&o.trim().length>0?o:typeof f==`string`&&f.trim().length>0?f:void 0,g=typeof u==`string`&&u.trim().length>0?u:void 0;return!p&&!m&&!h&&!g?null:{agentName:p,providerId:m,modelId:h,variant:g}},[G,t]),ue=Q.useMemo(()=>{if(G)return;let t=lN(e.info,`mode`);if(typeof t==`string`&&t.trim().length>0)return t;let n=lN(e.info,`agent`);if(typeof n==`string`&&n.trim().length>0)return n;if(le?.agentName)return le.agentName;if(K)return ae||(oe??void 0)},[G,e.info,le,K,ae,oe]),de=G?null:lN(e.info,`providerID`),fe=G?null:lN(e.info,`modelID`),pe=Q.useMemo(()=>{if(G||!K)return null;if(le?.providerId&&le?.modelId)return{providerId:le.providerId,modelId:le.modelId};if(ue){let e=S(K,ue);if(e?.providerId&&e?.modelId)return e}let e=C(K);return e?.providerId&&e?.modelId?e:null},[G,K,ue,le,S,C]),me=Q.useMemo(()=>G?null:typeof de==`string`&&de.trim().length>0?de:pe?.providerId??null,[G,de,pe]),he=Q.useMemo(()=>G?null:typeof fe==`string`&&fe.trim().length>0?fe:pe?.modelId??null,[G,fe,pe]),ge=e.info.id?oN(e.info.id):void 0;G||sN(e.info.id,{agent:ue,provider:me??void 0,model:he??void 0});let _e=ue??ge?.agent,ve=me??ge?.provider??null,ye=he??ge?.model??null,be=Q.useMemo(()=>{if(G)return;let e=ve&&A.length>0?A.find(e=>e.id===ve):void 0;return ri(e,ye)||void 0},[G,ve,ye,A]),xe=Q.useMemo(()=>{if(G||!me||!he)return!1;let e=A.find(e=>e.id===me);if(!e?.models||!Array.isArray(e.models))return!1;let t=e.models.find(e=>e.id===he)?.variants;return!!(t&&Object.keys(t).length>0)},[G,he,me,A]),Se=cN(_e),Ce=cN(ve??void 0),we=cN(ye??void 0),Te=cN(be),Ee=Se??void 0,De=Ce??null,Oe=we??null,ke=Te??void 0,Ae=Q.useMemo(()=>{let t=e.info.time;return typeof t?.completed==`number`?t.completed:null},[e.info.time]),je=Q.useMemo(()=>{let t=e.info.time;return typeof t?.created==`number`?t.created:null},[e.info.time]),Me=Q.useMemo(()=>G?!0:!!(Ae&&Ae>0),[G,Ae]),Ne=Q.useMemo(()=>{let t=e.info.finish;return typeof t==`string`?t:void 0},[e.info]),Pe=Q.useMemo(()=>{if(G)return null;let t=e.info.tokens;return!t||typeof t!=`object`?null:{output:typeof t.output==`number`?t.output:void 0,reasoning:typeof t.reasoning==`number`?t.reasoning:void 0}},[G,e.info]),Fe=Q.useMemo(()=>jr(ce,{includeReasoning:j}),[ce,j]),Ie=Q.useMemo(()=>G?Fe:!Me&&N===`sorted`?[]:Fe,[N,Me,G,Fe]),Le=Q.useMemo(()=>G?[]:Fe.filter(e=>e.type===`text`),[G,Fe]),Re=Q.useMemo(()=>G?[]:Fe.filter(e=>e.type===`tool`),[G,Fe]),ze=Q.useMemo(()=>{if(!P)return new Set;let e=new Set;for(let t of Re){let n=typeof t?.id==`string`?t.id:``;if(!n)continue;let r=$M(t.tool);!r||!QM.has(r)||e.add(n)}for(let t of a?.activityParts??[]){if(t.kind!==`tool`)continue;let n=$M(t.part.tool);!n||!QM.has(n)||e.add(t.id)}return e},[P,Re,a?.activityParts]),Be=Q.useMemo(()=>{if(ze.size===0&&U.size===0)return H;let e=new Set(H);return ze.forEach(t=>{U.has(t)||e.add(t)}),U.forEach(t=>{e.delete(t)}),e},[U,ze,H]),Ve=Q.useMemo(()=>{if(!G)return;let e=ce.find(e=>e.type===`agent`);if(!e)return;let t=e,n=typeof t.name==`string`?t.name:void 0;if(n)return{name:n,token:t.source&&typeof t.source.value==`string`&&t.source.value.trim().length>0?t.source.value:`@${n}`}},[G,ce]),Ue=G&&!Or(Ie),We=typeof Ne!=`string`,Ge=Q.useMemo(()=>G?!1:Le.length===0||Re.length===0?We:!0,[Le.length,Re.length,We,G]),Ke=Q.useMemo(()=>!G&&CT.getInstance().shouldAnimateMessage(e.info,x||e.info.sessionID),[e.info,x,G]),[qe,Je]=Q.useState(!1),Ye=Q.useMemo(()=>n?RM(n.info):null,[n]),Xe=!!a,Ze=a?.isLastAssistantInTurn??!1,Qe=UM({isWorking:a?.isWorking===!0,isInActiveTurn:c,headerCompletionDisposition:a?.completionDisposition}),$e=Q.useMemo(()=>G?!1:Xe?!Ze:Ye?!Ye.isUser&&Ye.role===`assistant`:!1,[Xe,Ze,G,Ye]),et=Q.useMemo(()=>Me?`completed`:c?l??`streaming`:`completed`,[l,c,Me]);Q.useEffect(()=>{!G||!u||d?.(e.info.id)},[u,G,e.info.id,d]),Q.useEffect(()=>{Je(!1)},[e.info.id]),Q.useEffect(()=>{let t=o??a?.headerMessageId;G||!t||t!==e.info.id||(et===`streaming`||et===`cooldown`)&&Je(!0)},[o,G,e.info.id,et,a?.headerMessageId]);let tt=Q.useMemo(()=>{if(G)return!0;if(s)return!1;let t=o??a?.headerMessageId;return t?e.info.id===t?et===`completed`||qe||et===`streaming`||et===`cooldown`:!1:!0},[o,qe,G,a,et,e.info.id,s]),nt=Q.useCallback(e=>{Jt(e).then(t=>{t.ok&&(I(e),setTimeout(()=>I(null),2e3))})},[]),rt=G?void 0:a?.userMessageVariant??le?.variant,it=!G&&xe&&typeof rt==`string`&&rt.trim().length>0?rt:void 0,at=Q.useMemo(()=>{if(!G)return qM(e.info?.error,p(`chat.messageBody.aborted`))},[G,e.info,p]),ot=at?.text,st=at?.variant,ct=Q.useMemo(()=>{if(G){let e=Ie.filter(e=>e.type===`text`).map(e=>{let t=e.shellAction?.output;return typeof t==`string`?t.trim():``}).filter(e=>e.length>0);if(e.length>0)return e.join(`
|
|
6576
6576
|
|
|
6577
6577
|
`);let t=Ie.filter(e=>e.type===`text`).map(e=>{let t=e.shellAction?.command;return typeof t==`string`?t.trim():``}).filter(e=>e.length>0);return t.length>0?t.join(`
|
|
6578
6578
|
`):Ie.filter(e=>e.type===`text`).map(e=>(e.text||e.content||``).trim()).filter(e=>e.length>0).join(`
|
|
@@ -6580,8 +6580,8 @@ import{o as e}from"./rolldown-runtime-C0FnF6B9.js";import{S as t,l as n,p as r}f
|
|
|
6580
6580
|
`)}return ot&&ot.trim().length>0?ot:Ln(Ie)},[ot,Ie,G]),lt=ct.length>0,ut=Q.useCallback(async()=>(await Jt(ct)).ok?(G&&(R(!0),setTimeout(()=>R(!1),2e3)),!0):!1,[G,ct]),dt=Q.useCallback(async()=>{if(!(!K||!e.info.id||V.current)){V.current=`revert`,B(`revert`);try{_.onRevertMessage?await _.onRevertMessage(e.info.id):await w(K,e.info.id,{directory:_.directory??void 0})}finally{V.current=null,B(null)}}},[K,e.info.id,w,_]),ft=J(()=>{if(!K||!e.info.id||V.current)return;let t={info:e.info,parts:e.parts};if(_.onEditMessage){_.onEditMessage(e.info.id,t).catch(()=>{});return}T(K,e.info.id,t).catch(()=>{})}),mt=J(()=>{K&&k(K)}),ht=Q.useCallback(async()=>{if(e.info.id,!K||!e.info.id){console.warn(`[session-fork] message action is missing identifiers`,{hasSessionId:!!K,hasMessageId:!!e.info.id});return}if(!V.current){V.current=`fork`,B(`fork`);try{await E(K,e.info.id)}finally{V.current=null,B(null)}}},[K,e.info.id,E]),gt=J(t=>{let n=ze.has(t),r=Be.has(t);if(n){te(n=>{let i=new Set(n);return r?i.add(t):i.delete(t),rN(e.info.id,i),i}),r||ee(n=>{let r=new Set(n);return r.delete(t),tN(e.info.id,r),r});return}ee(n=>{let r=new Set(n);return r.has(t)?r.delete(t):r.add(t),tN(e.info.id,r),r}),te(n=>{if(!n.has(t))return n;let r=new Set(n);return r.delete(t),rN(e.info.id,r),r})}),_t=i??null,vt=Q.useRef(!1),yt=Q.useRef(!1),bt=Q.useRef(!1),xt=Q.useRef(!1),St=Q.useRef(!1),Ct=Q.useRef(!1);Q.useEffect(()=>{yt.current=!1,bt.current=!1,xt.current=!1,St.current=!1,vt.current=!1,Ct.current=!1},[e.info.id]);let wt=Q.useCallback(()=>{G||vt.current||(vt.current=!0,r?.(`structural`))},[G,r]),Tt=q(e=>e.setImagePreviewOpen),Et=Q.useCallback(e=>{(e.image||e.mermaid)&&(ne(e),Tt(!0))},[Tt]),Dt=Q.useCallback(e=>{ne(t=>({...t,open:e})),Tt(e)},[Tt]),Ot=!!lN(e.info,`animationSettled`),kt=et===`streaming`||et===`cooldown`;kt&&(Ct.current=!0);let At=Q.useMemo(()=>!G&&Fe.some(e=>e.type===`reasoning`),[G,Fe]),jt=Ke&&!Ot&&!kt&&!Ct.current,Mt=!G&&Ke&&Le.length>0&&!Ge;return Q.useEffect(()=>{if(_t?.onStreamingCandidate){if(!Mt){bt.current&&=(At&&_t?.onReasoningBlock?_t.onReasoningBlock():_t?.onReservationCancelled&&_t.onReservationCancelled(),!1);return}St.current||(St.current=!0,_t.onStreamingCandidate(),bt.current=!0)}},[_t,Mt,At]),Q.useEffect(()=>{_t?.onAnimationStart&&jt&&(xt.current||=(_t.onAnimationStart(),!0))},[_t,jt]),Q.useEffect(()=>{if(G)return;let e=_t?.onAnimatedHeightChange;if(!e||!(jt||Mt))return;let t=b.current;if(!t)return;if(typeof window>`u`||typeof ResizeObserver>`u`){e(t.getBoundingClientRect().height);return}let n=null,r=t=>{if(typeof window>`u`){e(t);return}n!==null&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(()=>{e(t)})},i=new ResizeObserver(e=>{let t=e[0];t&&r(t.contentRect.height)});return i.observe(t),r(t.getBoundingClientRect().height),()=>{n!==null&&(window.cancelAnimationFrame(n),n=null),i.disconnect()}},[jt,G,_t,Mt]),Ue?null:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:Y(`group w-full`,G?m?`pt-2`:`pt-6`:!G&&tt?m?M?`pt-4`:`pt-0`:`pt-6`:`pt-0`,G||$e||s?`pb-0`:Qe?`pb-1`:`pb-8`),id:`message-${e.info.id}`,"data-message-id":e.info.id,ref:b,children:(0,$.jsx)(`div`,{className:`chat-message-column relative`,children:G?Or(Ie)?(0,$.jsx)(Xl,{forceAnimation:!0,skipAnimation:!u,ignoreContextDisabled:!0,respectReducedMotion:!0,children:(0,$.jsx)(`div`,{className:Y(`relative flex justify-end`,m?void 0:`group/user-shell`),children:(0,$.jsxs)(`div`,{className:Y(`max-w-[85%]`,ie?`pb-5`:void 0),children:[(0,$.jsx)(`div`,{style:{backgroundColor:`var(--chat-user-message-bg)`,borderRadius:`var(--radius-xl)`,borderBottomRightRadius:`var(--radius-sm)`},className:`px-3 py-1.5 shadow-none border border-primary/5`,"data-user-message-bubble":`true`,children:(0,$.jsx)(jM,{messageId:e.info.id,parts:Ie,sourceParts:se,isUser:G,isMessageCompleted:Me,messageFinish:Ne,messageCreatedAt:je??void 0,isMobile:m,alwaysShowActions:y,hasTouchInput:g,copiedCode:F,onCopyCode:nt,expandedTools:H,onToggleTool:gt,onShowPopup:Et,streamPhase:et,allowAnimation:jt,onContentChange:r,shouldShowHeader:!1,hasTextContent:lt,onCopyMessage:ut,copiedMessage:L,showReasoningTraces:j,onAuxiliaryContentComplete:wt,agentMention:Ve,onEdit:!D&&v.edit?ft:void 0,onRevert:!D&&v.revert?dt:void 0,onFork:!D&&G&&v.fork?ht:void 0,editing:D,editStaged:O,onCancelEdit:O?mt:void 0,pendingMessageAction:z,errorMessage:ot,errorVariant:st,userActionsMode:re?`external-content`:`inline`,stickyUserHeaderEnabled:M})}),re?(0,$.jsx)(jM,{messageId:e.info.id,parts:Ie,sourceParts:se,isUser:G,isMessageCompleted:Me,messageFinish:Ne,messageCreatedAt:je??void 0,isMobile:m,alwaysShowActions:y,hasTouchInput:g,copiedCode:F,onCopyCode:nt,expandedTools:H,onToggleTool:gt,onShowPopup:Et,streamPhase:et,allowAnimation:jt,onContentChange:r,shouldShowHeader:!1,hasTextContent:lt,onCopyMessage:ut,copiedMessage:L,showReasoningTraces:j,onAuxiliaryContentComplete:wt,agentMention:Ve,onEdit:!D&&v.edit?ft:void 0,onRevert:!D&&v.revert?dt:void 0,onFork:!D&&G&&v.fork?ht:void 0,editing:D,editStaged:O,onCancelEdit:O?mt:void 0,pendingMessageAction:z,errorMessage:ot,errorVariant:st,userActionsMode:`external-actions`,stickyUserHeaderEnabled:M}):null]})})}):null:(0,$.jsxs)(`div`,{className:`relative`,children:[tt&&(0,$.jsx)(TT,{isUser:G,isMobile:m,providerID:De,modelID:Oe,agentName:Ee,modelName:ke,variant:it}),(0,$.jsx)(jM,{sessionId:e.info.sessionID,messageId:e.info.id,parts:Fe,sourceParts:ce,isUser:G,isMessageCompleted:Me,messageFinish:Ne,messageCompletedAt:Ae??void 0,messageCreatedAt:je??void 0,messageTokens:Pe,isMobile:m,alwaysShowActions:y,hasTouchInput:g,copiedCode:F,onCopyCode:nt,expandedTools:Be,onToggleTool:gt,onShowPopup:Et,streamPhase:et,allowAnimation:jt,onContentChange:r,shouldShowHeader:tt,hasTextContent:lt,onCopyMessage:ut,copiedMessage:L,onAuxiliaryContentComplete:wt,showReasoningTraces:j,agentMention:Ve,turnGroupingContext:a,errorMessage:ot,errorVariant:st,reviewTransferDirection:f})]})})}),W.open?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(JM,{popup:W,onOpenChange:Dt,isMobile:m})}):null]})},(e,t)=>DE({info:e.message.info,parts:e.message.parts},{info:t.message.info,parts:t.message.parts})&&e.message.sourceParts===t.message.sourceParts&&OE(e.previousMessage?{info:e.previousMessage.info,parts:e.previousMessage.parts}:void 0,t.previousMessage?{info:t.previousMessage.info,parts:t.previousMessage.parts}:void 0)&&OE(e.nextMessage?{info:e.nextMessage.info,parts:e.nextMessage.parts}:void 0,t.nextMessage?{info:t.nextMessage.info,parts:t.nextMessage.parts}:void 0)&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.reviewTransferDirection===t.reviewTransferDirection&&e.assistantHeaderMessageId===t.assistantHeaderMessageId&&e.turnOwnsAssistantHeader===t.turnOwnsAssistantHeader&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&IE(e.turnGroupingContext,t.turnGroupingContext,e.message.info.id,RM(e.message.info).isUser)),dN=e=>{let t=e;return typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:``},fN=e=>{let t=e?.type;return t===`compaction`||t===`text`&&dN(e).trim()===`/compact`},pN=e=>e?e.some(e=>fN(e)):!1,mN=e=>pN(e.parts),hN=e=>e?pN(e.sourceParts)||pN(e.parts):!1,gN=e=>{if(!mN(e))return e;let t=!1,n=e.parts.map(e=>e?.type===`compaction`?(t=!0,{type:`text`,text:`/compact`}):e),r=e.info.clientRole!==`user`;return!t&&!r?e:{...e,info:r?{...e.info,clientRole:`user`}:e.info,parts:t?n:e.parts}},_N=e=>{let t=xn(e.parts);return t.length===e.parts.length?e:{...e,parts:t}},vN=new WeakMap,yN=e=>{let t=vN.get(e);if(t)return t;let n=gN(_N(e)),r=n.parts,i=Ur(r),a=i===r?n:{...n,parts:i,sourceParts:r};return vN.set(e,a),a},bN={activity:`idle`,hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isGenericStatus:!0,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,isTurnSettled:!1,retryInfo:null,turnStartedAt:void 0},xN=[],SN=`\0`,CN=new Set([`edit`,`write`,`multiedit`,`apply_patch`]),wN={read:`chat.assistantStatus.readingFile`,write:`chat.assistantStatus.writingFile`,edit:`chat.assistantStatus.editingFile`,multiedit:`chat.assistantStatus.editingFiles`,apply_patch:`chat.assistantStatus.applyingPatch`,bash:`chat.assistantStatus.runningCommand`,grep:`chat.assistantStatus.searchingContent`,glob:`chat.assistantStatus.findingFiles`,list:`chat.assistantStatus.listingDirectory`,task:`chat.assistantStatus.delegatingTask`,webfetch:`chat.assistantStatus.fetchingUrl`,websearch:`chat.assistantStatus.searchingWeb`,codesearch:`chat.assistantStatus.webCodeSearch`,todowrite:`chat.assistantStatus.updatingTodos`,todoread:`chat.assistantStatus.readingTodos`,skill:`chat.assistantStatus.learningSkill`,question:`chat.assistantStatus.askingQuestion`},TN=[`chat.assistantStatus.working`,`chat.assistantStatus.processing`,`chat.assistantStatus.preparing`,`chat.assistantStatus.warmingUp`,`chat.assistantStatus.gearsTurning`,`chat.assistantStatus.computing`,`chat.assistantStatus.calculating`,`chat.assistantStatus.analyzing`,`chat.assistantStatus.wheelsSpinning`,`chat.assistantStatus.calibrating`,`chat.assistantStatus.synthesizing`,`chat.assistantStatus.connectingDots`,`chat.assistantStatus.inspectingLogic`,`chat.assistantStatus.weighingOptions`],EN=(e,t)=>{let n=wN[e];return n?t(n):t(`chat.assistantStatus.usingTool`,{tool:e})},DN=e=>{let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)},ON=(e,t)=>t(TN[DN(e)%TN.length]??`chat.assistantStatus.working`),kN=(e,t,n)=>{let r,i;if(!Vn(e))for(let t=e.length-1;t>=0;--t){let n=e[t];if(n)switch(n.type){case`reasoning`:{let e=n.time??FN(n);(!e||e.end===void 0)&&!r&&(r=`reasoning`);break}case`tool`:{let e=n.state?.status;if((e===`running`||e===`pending`)&&!r){let e=IN(n);CN.has(e)?(r=`editing`,i=e):(r=`tool`,i=e)}break}case`text`:{let e=PN(n)??``;if(typeof e==`string`&&e.trim().length>0){let e=FN(n);(!e||e.end===void 0)&&!r&&(r=`text`)}break}}}let a=r===void 0,o=r===`editing`?i===`multiedit`?EN(i,n):n(`chat.assistantStatus.editingFile`):r===`tool`&&i?EN(i,n):r===`reasoning`?n(`chat.assistantStatus.thinking`):r===`text`?n(`chat.assistantStatus.composing`):ON(t,n);return{activePartType:r,activeToolName:i,statusText:o,isGenericStatus:a}},AN=e=>[e.activePartType??``,e.activeToolName??``,e.statusText,e.isGenericStatus?`1`:`0`].join(SN),jN=e=>{let[t,n,r=`working`,i]=e.split(SN);return{activePartType:t===`text`||t===`tool`||t===`reasoning`||t===`editing`?t:void 0,activeToolName:n||void 0,statusText:r,isGenericStatus:i===`1`}},MN=e=>e.type===`reasoning`,NN=e=>e.type===`text`,PN=e=>{if(NN(e))return e.text;let t=e;if(typeof t.text==`string`)return t.text;if(typeof t.content==`string`)return t.content;if(typeof t.value==`string`)return t.value},FN=e=>(NN(e)||MN(e),e.time),IN=e=>{if(e.tool)return e.tool;let t=e;return typeof t.name==`string`?t.name:`tool`};function LN(e,t){let{t:n}=Yt(),r=X(e=>e.currentSessionId),i=X(e=>e.currentSessionDirectory),a=e??r,o=t??i,s=Q.useMemo(()=>e=>a?e.pendingSendMessageIDs.get(a)??null:null,[a]),c=X(s),l=ka(a??``,o??void 0),u=Q.useMemo(()=>{for(let e=l.length-1;e>=0;e--){let t=l[e];if(t.role===`assistant`)return{id:t.id,finish:t.finish,error:t.error}}return{id:null,finish:void 0,error:void 0}},[l]),d=u.id,f=Q.useMemo(()=>{for(let e=l.length-1;e>=0;e--){let t=l[e];if(t.role===`user`)return{id:t.id,turnStartedAt:Number.isFinite(t.time.created)?t.time.created:void 0}}return{id:null,turnStartedAt:void 0}},[l]),p=f.id,m=mi(d??``,o??void 0,a??void 0),h=mi(p??``,o??void 0,a??void 0),g=!!p&&pN(h),_=!!(d&&Gk(u.finish,m,u.error)),v=Q.useMemo(()=>{let e=`${a??``}:${d??``}`;return AN(kN(d?m:xN,e,n))},[a,d,m,n]),y=ya(a??``,o??void 0),b=Na(a??``,o??void 0),x=Q.useMemo(()=>e=>a?e.sessionAbortFlags?.get(a)??null:null,[a]),S=X(x),{phase:C,isWorking:w}=Gb(a,o??void 0),T=wi(a??``,o??void 0),E=T?.type===`retry`?T.attempt:void 0,D=T?.type===`retry`?T.next:void 0,O=Q.useMemo(()=>jN(v),[v]),k=Q.useMemo(()=>{let e=!!(S&&!S.acknowledged);return{wasAborted:e,abortActive:e}},[S]),A=Q.useMemo(()=>{if(k.wasAborted)return{...bN,wasAborted:!0,abortActive:k.abortActive,activity:`idle`,hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1,retryInfo:null};if(_)return{...bN,isComplete:!0,isTurnSettled:!0,turnStartedAt:f.turnStartedAt};let e=w,t=C===`busy`,r=C===`retry`,i=e&&g,a=`idle`;e&&(a=!i&&(O.activePartType===`tool`||O.activePartType===`editing`)?`tooling`:`streaming`);let o=r?{attempt:E,next:D}:null;return{activity:a,hasWorkingContext:e,hasActiveTools:!i&&(O.activePartType===`tool`||O.activePartType===`editing`),isWorking:e,isStreaming:t,isCooldown:!1,lifecyclePhase:t?`streaming`:null,statusText:e?i?n(`chat.assistantStatus.compacting`):O.statusText:null,isGenericStatus:!e||!i&&O.isGenericStatus,isWaitingForPermission:!1,canAbort:e,compactionDeadline:null,activePartType:e&&!i?O.activePartType:void 0,activeToolName:e&&!i?O.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1,isTurnSettled:!1,retryInfo:o,turnStartedAt:f.turnStartedAt}},[C,w,_,g,f.turnStartedAt,O,k,E,D,n]);return{forming:Q.useMemo(()=>({isActive:w&&O.activePartType===`text`,characterCount:0}),[w,O.activePartType]),working:Q.useMemo(()=>{if(A.wasAborted||A.abortActive)return A;if(c)return{...A,activity:`streaming`,hasWorkingContext:!0,isWorking:!0,isStreaming:!0,isCooldown:!1,lifecyclePhase:`streaming`,statusText:n(`chat.assistantStatus.sendingMessage`),isGenericStatus:!1,isWaitingForPermission:!1,canAbort:!0,activePartType:void 0,activeToolName:void 0,isComplete:!1,isTurnSettled:!1,retryInfo:null};let e=y.length>0,t=b.length>0;return!e&&!t?A:t?{...A,statusText:null,isWorking:!1,hasWorkingContext:!1,hasActiveTools:!1,canAbort:!1,activePartType:void 0,activeToolName:void 0,retryInfo:null}:{...A,statusText:n(`chat.assistantStatus.waitingForPermission`),isWaitingForPermission:!0,canAbort:!1,retryInfo:null}},[A,c,y,b,n])}}var RN=Q.memo(()=>{let e=(0,pd.c)(15),t=Zy(),n=X(zN),r=X(BN),i=t.sessionId??n,a=t.directory??r??void 0,o;e[0]===i?o=e[1]:(o=e=>i?e.sessionAbortFlags?.get(i)??null:null,e[0]=i,e[1]=o);let s=X(o),c=X(VN),l=X(HN),{working:u}=LN(i,a),d=Oa(UN),f=!!(s&&!s.acknowledged),p=!!(i&&c===i&&typeof l==`number`&&l>Date.now()),m=u.isWaitingForPermission||!!u.retryInfo||f||u.wasAborted||u.isWorking,h=f||u.wasAborted,g=f||u.abortActive,_;return e[2]!==d||e[3]!==p||e[4]!==m||e[5]!==h||e[6]!==g||e[7]!==u.isGenericStatus||e[8]!==u.isTurnSettled||e[9]!==u.isWaitingForPermission||e[10]!==u.isWorking||e[11]!==u.retryInfo||e[12]!==u.statusText||e[13]!==u.turnStartedAt?(_=(0,$.jsx)(nb,{isWorking:u.isWorking,statusText:u.statusText,isGenericStatus:u.isGenericStatus,isWaitingForPermission:u.isWaitingForPermission,wasAborted:h,abortActive:g,retryInfo:u.retryInfo,turnStartedAt:u.turnStartedAt,isTurnSettled:u.isTurnSettled,showAbortPrompt:p,showAssistantStatus:m,showTodos:!1,agentName:d}),e[2]=d,e[3]=p,e[4]=m,e[5]=h,e[6]=g,e[7]=u.isGenericStatus,e[8]=u.isTurnSettled,e[9]=u.isWaitingForPermission,e[10]=u.isWorking,e[11]=u.retryInfo,e[12]=u.statusText,e[13]=u.turnStartedAt,e[14]=_):_=e[14],_});RN.displayName=`StatusRowContainer`;function zN(e){return e.currentSessionId}function BN(e){return e.currentSessionDirectory}function VN(e){return e.abortPromptSessionId}function HN(e){return e.abortPromptExpiresAt}function UN(e){return e.currentAgentName}var WN=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},GN=e=>{if(typeof e!=`object`||!e)return null;let t=e,n=WN(t.mode)??WN(t.agent),r=WN(t.providerID)??WN(t.model?.providerID),i=WN(t.modelID)??WN(t.model?.modelID),a=WN(t.model?.variant)??WN(t.variant);return!n&&!r&&!i&&!a?null:{agentName:n,providerId:r,modelId:i,variant:a}},KN=e=>{let t=e?.modelId??null;return{providerID:e?.providerId??null,modelID:t,agentName:e?.agentName,modelName:ri(void 0,t)||void 0,variant:e?.variant}},qN=e=>!(!e.isLastTurn||!e.sessionIsWorking||e.hasAssistantMessages||e.activityPresentationKind===`compaction`||e.hasActiveStreamingMessage),JN=(e,t)=>{if(typeof e!=`object`||!e)return;let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0},YN=e=>{let t=(0,pd.c)(3),[n,r]=Q.useState(e),i,a;return t[0]===e?(i=t[1],a=t[2]):(i=()=>{e!=null&&r(e)},a=[e],t[0]=e,t[1]=i,t[2]=a),Q.useEffect(i,a),e??n},XN=Q.memo(({assistantMessage:e,userMessage:t,pendingPresentation:n,assistantIsInActiveTurn:r,isMobile:i})=>{let a=Oa(e=>e.providers),o=e?.info.sessionID??t.info.sessionID,s=Hr(e=>e.getAgentModelForSession),c=Hr(e=>e.getSessionModelSelection),{currentContextAgent:l,savedSessionAgentSelection:u}=Hv(He(e=>({currentContextAgent:r&&o?e.currentAgentContext.get(o):void 0,savedSessionAgentSelection:r&&o?e.sessionAgentSelections.get(o):void 0}))),d=Q.useMemo(()=>GN(t.info),[t.info]),f=Q.useMemo(()=>e?JN(e.info,`mode`)??JN(e.info,`agent`)??d?.agentName??l??u:n?.agentName??d?.agentName,[e,l,n?.agentName,u,d?.agentName]),p=Q.useMemo(()=>{if(d?.providerId&&d.modelId)return{providerId:d.providerId,modelId:d.modelId};if(o&&f){let e=s(o,f);if(e?.providerId&&e.modelId)return e}if(!o)return null;let e=c(o);return e?.providerId&&e.modelId?e:null},[f,s,c,o,d?.modelId,d?.providerId]),m=e?JN(e.info,`providerID`)??p?.providerId:n?.providerID??d?.providerId,h=e?JN(e.info,`modelID`)??p?.modelId:n?.modelID??d?.modelId,g=YN(f),_=YN(m),v=YN(h),y=_?a.find(e=>e.id===_):void 0,b=ri(y,v??null)||n?.modelName||void 0,x=y?.models?.find(e=>e.id===v),S=x?.variants&&Object.keys(x.variants).length>0?d?.variant??n?.variant:void 0;return(0,$.jsx)(TT,{isUser:!1,isMobile:i,providerID:_??null,modelID:v??null,agentName:g??void 0,modelName:b,variant:S})}),ZN=Q.memo(e=>{let t=(0,pd.c)(10),{assistantMessages:n,activityExpanded:r,renderMessage:i}=e,a;if(t[0]!==r||t[1]!==n||t[2]!==i){let e;t[4]!==r||t[5]!==i?(e=e=>i(e,r),t[4]=r,t[5]=i,t[6]=e):e=t[6],a=n.map(e),t[0]=r,t[1]=n,t[2]=i,t[3]=a}else a=t[3];let o;return t[7]!==r||t[8]!==a?(o=(0,$.jsx)(`div`,{className:`relative z-0`,"data-turn-assistant-activity-expanded":r,children:a}),t[7]=r,t[8]=a,t[9]=o):o=t[9],o}),QN=new Set,$N=()=>{},eP=()=>{},tP=Q.memo(e=>{let t=(0,pd.c)(34),{turn:n,activityExpanded:r,showCompactionStatus:i,pendingAssistantHeader:a,assistantHeaderMessage:o,assistantHeaderIsInActiveTurn:s,preserveActiveTurnGap:c,onToggleActivity:l,stickyUserHeader:u,renderMessage:d}=e,f=a===void 0?null:a,p=s!==void 0&&s,m=c!==void 0&&c,h=u===void 0||u,g=q(nP),_=n.userMessage.info.time?.created,v=n.activityPresentationKind===`compaction`,y=`relative w-full ${m?`pb-1`:`pb-8`}`,b=`turn-${n.turnId}`,x;t[0]!==r||t[1]!==v||t[2]!==d||t[3]!==h||t[4]!==n.userMessage?(x=v?null:h?(0,$.jsxs)(`div`,{className:`sticky top-0 z-20 relative bg-[var(--surface-background)] [overflow-anchor:none]`,children:[(0,$.jsx)(`div`,{className:`relative z-10`,children:d(n.userMessage,r)}),(0,$.jsx)(`div`,{"aria-hidden":`true`,className:`pointer-events-none absolute inset-x-0 top-full z-0 h-4 bg-gradient-to-b from-[var(--surface-background)] to-transparent sm:h-8`})]}):d(n.userMessage,r),t[0]=r,t[1]=v,t[2]=d,t[3]=h,t[4]=n.userMessage,t[5]=x):x=t[5];let S;t[6]!==p||t[7]!==o||t[8]!==g||t[9]!==f||t[10]!==h||t[11]!==n.userMessage?(S=f||o?(0,$.jsx)(`div`,{className:`group w-full ${g?h?`pt-4`:`pt-0`:`pt-6`} pb-0`,children:(0,$.jsx)(`div`,{className:`chat-message-column relative`,children:(0,$.jsx)(XN,{assistantMessage:o,userMessage:n.userMessage,pendingPresentation:f,assistantIsInActiveTurn:p,isMobile:g})})}):null,t[6]=p,t[7]=o,t[8]=g,t[9]=f,t[10]=h,t[11]=n.userMessage,t[12]=S):S=t[12];let C;t[13]!==r||t[14]!==g||t[15]!==l||t[16]!==i||t[17]!==n.completionDisposition||t[18]!==n.durationMs||t[19]!==_?(C=i?(0,$.jsx)(`div`,{className:`group w-full ${g?`pt-4`:`pt-6`} pb-0`,children:(0,$.jsx)(`div`,{className:`chat-message-column relative`,children:(0,$.jsx)(Jj,{parts:[],isExpanded:r,completionDisposition:n.completionDisposition,activityPresentationKind:`compaction`,durationMs:n.durationMs,startedAt:typeof _==`number`?_:void 0,onToggle:l,isMobile:g,expandedTools:QN,onToggleTool:$N,onShowPopup:eP,streamPhase:n.completionDisposition===`active`?`streaming`:`completed`,showHeader:!0})})}):null,t[13]=r,t[14]=g,t[15]=l,t[16]=i,t[17]=n.completionDisposition,t[18]=n.durationMs,t[19]=_,t[20]=C):C=t[20];let w;t[21]!==r||t[22]!==d||t[23]!==n.assistantMessages?(w=(0,$.jsx)(ZN,{assistantMessages:n.assistantMessages,activityExpanded:r,renderMessage:d}),t[21]=r,t[22]=d,t[23]=n.assistantMessages,t[24]=w):w=t[24];let T;return t[25]!==r||t[26]!==w||t[27]!==y||t[28]!==b||t[29]!==x||t[30]!==S||t[31]!==C||t[32]!==n.turnId?(T=(0,$.jsxs)(`section`,{className:y,id:b,"data-turn-id":n.turnId,"data-turn-activity-expanded":r,"data-scroll-spy-id":n.turnId,children:[x,S,C,w]}),t[25]=r,t[26]=w,t[27]=y,t[28]=b,t[29]=x,t[30]=S,t[31]=C,t[32]=n.turnId,t[33]=T):T=t[33],T});function nP(e){return e.isMobile}var rP=(e,t,n)=>t.id??`${e}-part-${n}-${t.type}`,iP=e=>{let t=e.state?.time?.end;if(typeof t==`number`)return t;let n=e.time?.end;return typeof n==`number`?n:void 0},aP=e=>{let t=e.text;if(typeof t==`string`&&t.trim().length>0)return t;let n=e.content;if(typeof n==`string`&&n.trim().length>0)return n},oP=e=>{let t=e.info.finish;return typeof t==`string`?t:void 0},sP=(e,t,n,r)=>({id:rP(t,n,r),turnId:e,messageId:t,part:n,partIndex:r,endedAt:iP(n)}),cP=e=>{let t=[],n=!1,r=!1;e.assistantMessages.forEach(e=>{e.parts.forEach(e=>{if(e.type===`tool`){n=!0;return}e.type===`reasoning`&&aP(e)&&(r=!0)})});let i=!!e.summarySourceMessageId&&!!e.summarySourcePartId&&e.assistantMessages.some(t=>t.info.id===e.summarySourceMessageId&&Uk(oP(t),t.parts));e.assistantMessages.forEach(n=>{let r=oP(n),a=n.parts.some(e=>e.type===`tool`);n.parts.forEach((o,s)=>{let c=o.type===`tool`,l=o.type===`reasoning`||o.type===`text`?aP(o):void 0,u=rP(n.info.id,o,s),d=o.type===`text`&&typeof l==`string`&&Uk(r,n.parts)&&e.summarySourceMessageId===n.info.id&&e.summarySourcePartId===u,f=null;c?f=`tool`:o.type===`reasoning`?f=`reasoning`:e.showTextJustificationActivity&&o.type===`text`&&l&&!d&&(i||a||typeof r==`string`&&r!==`stop`)&&(f=`justification`),f&&t.push({...sP(e.turnId,n.info.id,o,s),kind:f})})});let a=[];if(t.length>0){let n=e.assistantMessages[0]?.info.id;n&&a.push({id:`${e.turnId}:activity`,anchorMessageId:n,afterToolPartId:null,parts:t})}return{activityParts:t,activitySegments:a,hasTools:n,hasReasoning:r}},lP=e=>{let t=new Map,n=new Map,r=new Map,i=new Set;e.forEach(e=>{t.set(e.turnId,e);let a=e.assistantMessages[0]?.info.id,o=e.assistantMessages[e.assistantMessages.length-1]?.info.id;n.set(e.userMessageId,e.turnId),i.add(e.userMessageId),r.set(e.userMessageId,{turnId:e.turnId,messageId:e.userMessageId,userMessageId:e.userMessageId,isUserMessage:!0,isAssistantMessage:!1,isFirstAssistantInTurn:!1,isLastAssistantInTurn:!1,headerMessageId:e.headerMessageId}),e.assistantMessageIds.forEach(t=>{n.set(t,e.turnId),i.add(t),r.set(t,{turnId:e.turnId,messageId:t,userMessageId:e.userMessageId,isUserMessage:!1,isAssistantMessage:!0,isFirstAssistantInTurn:t===a,isLastAssistantInTurn:t===o,headerMessageId:e.headerMessageId})})});let a=e.length>0?e[e.length-1]:null,o=new Set;return a&&(o.add(a.userMessageId),a.assistantMessageIds.forEach(e=>{o.add(e)})),{turns:e,indexes:{turnById:t,messageToTurnId:n,messageMetaById:r},lastTurnId:a?.turnId??null,lastTurnMessageIds:o,ungroupedMessageIds:new Set}},uP=e=>{let t=e.text;if(typeof t==`string`&&t.trim().length>0)return t;let n=e.content;if(typeof n==`string`&&n.trim().length>0)return n},dP=e=>{for(let t=e.length-1;t>=0;--t){let n=e[t];if(!n)continue;let r=n.info.finish;if(Uk(r,n.parts))for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(!t||!Wk(t))continue;let r=uP(t);if(r)return{text:r,sourceMessageId:n.info.id,sourcePartId:rP(n.info.id,t,e)}}}for(let t=e.length-1;t>=0;--t){let n=e[t];if(n)for(let e=n.parts.length-1;e>=0;--e){let t=n.parts[e];if(!t||t.type!==`text`)continue;let r=uP(t);if(r)return{text:r,sourceMessageId:n.info.id,sourcePartId:rP(n.info.id,t,e)}}}return{}},fP=e=>{let t=e.info.summary,n=t?.diffs,r=Array.isArray(n)?n:[],i=typeof t?.diffCount==`number`&&Number.isFinite(t.diffCount)?Math.max(0,Math.trunc(t.diffCount)):void 0,a=0,o=0,s=0;r.forEach(e=>{if(!e)return;let t=typeof e.additions==`number`?e.additions:0,n=typeof e.deletions==`number`?e.deletions:0;(t!==0||n!==0)&&(s+=1),a+=t,o+=n});let c=i??s,l=t?.hasDiffs===!0||c>0||r.length>0;if(l)return{additions:a,deletions:o,files:c,hasDiffs:l}},pP=e=>{let t=e.info.summary?.diffs;if(!Array.isArray(t)||t.length===0)return;let n=t.map(e=>{if(!e||typeof e.file!=`string`||e.file.trim().length===0)return null;let t=typeof e.additions==`number`?e.additions:0,n=typeof e.deletions==`number`?e.deletions:0;return t===0&&n===0?null:{file:e.file,additions:t,deletions:n}}).filter(e=>e!==null);return n.length>0?n:void 0},mP=e=>{let t=e.info.clientRole??e.info.role;return typeof t==`string`?t:``},hP=e=>{let t=e.info.parentID;if(typeof t==`string`&&t.trim().length!==0)return t},gP=e=>{let t=e.info.time?.created;return typeof t==`number`?t:void 0},_P=e=>{let t=e.info.time?.completed;return typeof t==`number`?t:void 0},vP=e=>{let t=e.state?.time?.end;if(typeof t==`number`)return t;let n=e.time?.end;return typeof n==`number`?n:void 0},yP=e=>{let t=e.info?.summary?.body;if(typeof t==`string`)return t.trim().length>0?t:void 0},bP=(e,t)=>{let n=mP(e);return{messageId:e.info.id,role:n,parentMessageId:hP(e),message:e,order:t}},xP=(e,t)=>{let n=gP(e),r,i,a=!1;t.forEach(e=>{let t=_P(e);typeof t==`number`?r=Math.max(r??0,t):a=!0,e.parts.forEach(e=>{let t=vP(e);typeof t==`number`&&(i=Math.max(i??0,t))})});let o=r??i,s=typeof n==`number`&&typeof o==`number`&&o>=n?o-n:void 0;return{isStreaming:a,isRetrying:t.length>1,startedAt:n,completedAt:r,durationMs:s}},SP=e=>{if(e.length===0)return`active`;let t=e[e.length-1];if(!t)return`active`;let n=t.info.finish;if(t.info.error)return`abnormal`;if(n===`tool-calls`||Hk(t.parts)>0)return`active`;if(n===`stop`)return`normal`;if(typeof n==`string`&&n.length>0)return`abnormal`;for(let t of e)if(typeof _P(t)!=`number`)return`active`;return`active`},CP=e=>{let t=e[e.length-1];if(!t)return!1;let n=t.info;return Gk(n.finish,t.parts,n.error)},wP=e=>hN(e)?`compaction`:`default`,TP={previousProjection:null,showTextJustificationActivity:!1,showTurnChangedFiles:!1},EP=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},DP=(e,t)=>e.userMessage===t.userMessage&&e.headerMessageId===t.headerMessageId&&EP(e.assistantMessages,t.assistantMessages),OP=(e,t)=>{e.summary=dP(e.assistantMessages),e.summaryText=e.summary.text??yP(e.userMessage),e.diffStats=fP(e.userMessage),e.changedFiles=t.showTurnChangedFiles?pP(e.userMessage):void 0,e.completionDisposition=SP(e.assistantMessages),e.hasConfirmedFinalBody=CP(e.assistantMessages),e.activityPresentationKind=wP(e.userMessage);let n=cP({turnId:e.turnId,assistantMessages:e.assistantMessages,summarySourceMessageId:e.summary.sourceMessageId,summarySourcePartId:e.summary.sourcePartId,showTextJustificationActivity:t.showTextJustificationActivity});return e.activityParts=n.activityParts,e.activitySegments=n.activitySegments,e.hasTools=n.hasTools,e.hasReasoning=n.hasReasoning,e.stream=xP(e.userMessage,e.assistantMessages),e.startedAt=e.stream.startedAt,e.completedAt=e.stream.completedAt,e.durationMs=e.stream.durationMs,e},kP=(e,t)=>{let n=t.previousProjection;if(!n||n.turns.length===0||e.length===0)return e.map(e=>OP(e,t));let r=n.turns.length===e.length,i=!1,a=e.map((e,a)=>{let o=n.indexes.turnById.get(e.turnId);return o&&DP(o,e)?(i=!0,n.turns[a]!==o&&(r=!1),o):(r=!1,OP(e,t))});return r&&i?n.turns:a},AP=e=>{if(e.length<=1)return e;let t=!1,n=e.map((n,r)=>{if(r===e.length-1||n.completionDisposition!==`active`||(e[r+1]?.assistantMessages.length??0)===0)return n;t=!0;let i=e[r+1]?.startedAt,a=n.durationMs,o=n.completedAt;return typeof a!=`number`&&typeof n.startedAt==`number`&&typeof i==`number`&&i>=n.startedAt&&(o=i,a=i-n.startedAt),{...n,completionDisposition:`abnormal`,completedAt:o,durationMs:a,stream:{...n.stream,isStreaming:!1,completedAt:o??n.stream.completedAt,durationMs:a}}});return t?n:e},jP=(e,t)=>{let n={...TP,...t},r=[],i=new Map,a=new Set;e.forEach((e,t)=>{if(mP(e)!==`user`)return;let n={turnId:e.info.id,userMessageId:e.info.id,userMessage:e,headerMessageId:void 0,messages:[bP(e,t)],assistantMessageIds:[],assistantMessages:[],activityParts:[],activitySegments:[],summary:{},summaryText:void 0,hasTools:!1,hasReasoning:!1,diffStats:void 0,changedFiles:void 0,stream:{isStreaming:!1,isRetrying:!1},completionDisposition:`active`,activityPresentationKind:`default`,hasConfirmedFinalBody:!1};r.push(n),i.set(n.userMessageId,n),a.add(e.info.id)}),e.forEach((e,t)=>{if(mP(e)!==`assistant`)return;let n=hP(e),r=n?i.get(n):void 0;r&&(r.assistantMessages.push(e),r.assistantMessageIds.push(e.info.id),r.messages.push(bP(e,t)),r.headerMessageId||=e.info.id,a.add(e.info.id))});let o=lP(AP(kP(r,n))),s=new Set;return e.forEach(e=>{mP(e)!==`assistant`&&(a.has(e.info.id)||s.add(e.info.id))}),{...o,ungroupedMessageIds:s}},MP=30,NP=4,PP=4,FP=33554432,IP=8388608,LP=new Map,RP=new Map,zP=0,BP=new WeakMap,VP=1,HP=()=>ge()?NP:yr()?PP:MP,UP=()=>ge()||yr()?IP:FP,WP=(e,t)=>{let n=e.length*2+256;for(let e of t.turns)n+=512,n+=e.messages.length*160,n+=e.activityParts.length*128,n+=(e.changedFiles?.length??0)*160,n+=(e.summaryText?.length??0)*2;return n},GP=e=>{LP.delete(e);let t=RP.get(e)??0;RP.delete(e),zP=Math.max(0,zP-t)},KP=e=>{let t=BP.get(e);if(t!==void 0)return t;let n=VP;return VP+=1,BP.set(e,n),n},qP=e=>e.map(e=>`${KP(e.info)}:${KP(e.parts)}:${e.parts.map(e=>KP(e)).join(`,`)}`).join(`;`),JP=(e,t,n,r)=>{let i=t.length>0?t[t.length-1]:void 0,a=i?.info?.id??``,o=i?.parts?.length??0;return[e,t.length,a,o,qP(t),n?`1`:`0`,r?`1`:`0`].join(`|`)},YP=e=>{let t=LP.get(e);return t&&(LP.delete(e),LP.set(e,t)),t},XP=(e,t)=>{GP(e);let n=HP(),r=UP(),i=WP(e,t);if(!(i>r)){for(;LP.size>=n||zP+i>r;){let e=LP.keys().next().value;if(typeof e!=`string`)break;GP(e)}LP.set(e,t),RP.set(e,i),zP+=i}},ZP=[],QP=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0},$P=e=>{if(!e.hasLiveTail)return null;if(e.turnCount===0)return e.previousStart;let t=e.previousStart??e.turnCount-1,n=Math.min(Math.max(t,0),e.turnCount-1);return!e.liveTailActive&&e.turnCount-n>12?e.turnCount-1:n},eF=(e,t)=>t===null?{staticTurns:e,streamingTurns:ZP}:{staticTurns:t===0?ZP:e.slice(0,t),streamingTurns:e.slice(t)},tF=(e,t)=>{let n=Q.useRef(null),r=Q.useRef([]),i=Q.useRef(ZP),a=Q.useRef(null),o=Q.useRef(t.sessionKey),s=Q.useRef(t.showTextJustificationActivity),c=Q.useRef(t.showTurnChangedFiles);(o.current!==t.sessionKey||s.current!==t.showTextJustificationActivity||c.current!==t.showTurnChangedFiles)&&(o.current=t.sessionKey,s.current=t.showTextJustificationActivity,c.current=t.showTurnChangedFiles,n.current=null,r.current=[],i.current=ZP,a.current=null);let l=Q.useMemo(()=>{let r=JP(t.sessionKey??``,e,t.showTextJustificationActivity,t.showTurnChangedFiles),i=YP(r);return i?(n.current=i,i):Ze(`ui.turns.projection_ms`,()=>{let i=jP(e,{previousProjection:n.current,showTextJustificationActivity:t.showTextJustificationActivity,showTurnChangedFiles:t.showTurnChangedFiles});return n.current=i,XP(r,i),i})},[e,t.showTextJustificationActivity,t.showTurnChangedFiles,t.sessionKey]),u=$P({turnCount:l.turns.length,hasLiveTail:t.hasLiveTail,liveTailActive:t.liveTailActive,previousStart:a.current});return a.current=u,{projection:l,staticTurns:Q.useMemo(()=>{let e=eF(l.turns,u).staticTurns;return QP(r.current,e)?r.current:r.current=e},[u,l.turns]),streamingTurns:Q.useMemo(()=>{let e=eF(l.turns,u).streamingTurns;return QP(i.current,e)?i.current:i.current=e},[u,l.turns])}},nF=e=>{let t=e.info;return(typeof t.clientRole==`string`?t.clientRole:null)??(typeof t.role==`string`?t.role:null)??null},rF=(e,t)=>{if(!t.sessionId)return e;let n={name:`SessionRetry`,message:t.message,data:{message:t.message}},r=-1;for(let t=e.length-1;t>=0;--t)if(nF(e[t])===`user`){r=t;break}if(r<0)return e;let i=-1;for(let t=e.length-1;t>r;--t)if(nF(e[t])===`assistant`){i=t;break}if(i>=0)return e[i].info.error?e:e.map((e,t)=>t===i?{...e,info:{...e.info,error:n}}:e);let a=typeof t.confirmedAt==`number`?t.confirmedAt:t.fallbackTimestamp,o={info:{id:`synthetic_retry_notice_${t.sessionId}`,sessionID:t.sessionId,role:`assistant`,time:{created:a,completed:a},finish:`stop`,error:n},parts:[]},s=e.slice();return s.splice(r+1,0,o),s},iF=(e,t,n)=>{if(e.info.id!==t||e.parts===n)return e;let r=ta(e.parts,n,e.info);return r.length===e.parts.length&&r.every((t,n)=>t===e.parts[n])?e:yN({...e,parts:r})},aF=(e,t)=>{let n=t.activeStreamingMessageId;if(!n)return e;if(e.kind===`ungrouped`){let r=iF(e.message,n,t.liveParts);return r===e.message?e:{...e,message:r}}let r=!1,i=e.turn.assistantMessages.map(e=>{let i=iF(e,n,t.liveParts);return i!==e&&(r=!0),i});if(!r)return e;let a=jP([e.turn.userMessage,...i],{showTextJustificationActivity:t.showTextJustificationActivity,showTurnChangedFiles:t.showTurnChangedFiles}).turns[0]??{...e.turn,assistantMessages:i,assistantMessageIds:i.map(e=>e.info.id)};return{...e,turn:a}},oF=e=>{let t=Q.useRef(e);return t.current=e,Q.useMemo(()=>(...e)=>t.current(...e),[])},sF=2,cF=2,lF=e=>Math.min(Math.max(0,e),sF),uF=(e,t)=>Math.min(Math.max(0,t),Math.max(0,e)+cF),dF=e=>{let t=(0,pd.c)(3),{children:n,enabled:r}=e,i;return t[0]!==n||t[1]!==r?(i=(0,$.jsx)(pD.Provider,{value:r,children:n}),t[0]=n,t[1]=r,t[2]=i):i=t[2],i},fF=e=>{let t=(0,pd.c)(3),{children:n,enabled:r}=e,i;return t[0]!==n||t[1]!==r?(i=(0,$.jsx)(vl.Provider,{value:r,children:n}),t[0]=n,t[1]=r,t[2]=i):i=t[2],i},pF=12,mF=16,hF=new Map,gF=e=>{let t=hF.get(e);if(t)return hF.delete(e),hF.set(e,t),t},_F=(e,t)=>{if(t.size!==0)for(hF.delete(e),hF.set(e,t);hF.size>mF;){let e=hF.keys().next().value;if(typeof e!=`string`)break;hF.delete(e)}},vF=(e,t)=>{let n=Math.max(1,Math.floor(t?.seedCount??pF)),r=new Set;for(let t=Math.max(0,e.length-n);t<e.length;t+=1){let n=e[t];n&&r.add(n)}let i=t?.restore;if(i&&i.size>0){let t=new Set(e);for(let e of i)t.has(e)&&r.add(e)}return r},yF=(e,t)=>{let n=t[t.length-1];if(!n||e.has(n))return e;let r=new Set(e);return r.add(n),r},bF=({entryKeys:e,mountedIndexes:t,visibleStartIndex:n,visibleEndIndex:r,scrollDirection:i,preloadEntries:a,hydratedKeys:o})=>{if(e.length===0||t.length===0)return{visible:[],preload:[]};let s=new Set(t),c=[],l=[],u=new Set,d=(t,n)=>{if(n<0||n>=e.length||!s.has(n))return;let r=e[n];!r||o.has(r)||u.has(r)||(u.add(r),t.push(r))},f=e.length-1,p=Math.min(f,Math.max(0,Math.floor(n))),m=Math.min(f,Math.max(p,Math.floor(r)));for(let e=m;e>=p;--e)d(c,e);let h=Math.max(0,Math.floor(a)),g=()=>{let e=Math.min(f,m+h);for(let t=m+1;t<=e;t+=1)d(l,t)},_=()=>{let e=Math.max(0,p-h);for(let t=p-1;t>=e;--t)d(l,t)};return i===`backward`?(_(),g()):(g(),_()),{visible:c,preload:l}},xF=e=>{let{visible:t,preload:n}=bF(e),r=n.slice(0,Math.max(0,Math.floor(e.preloadReleaseLimit)));if(!e.allowVisibleRelease)return r;let i=e.visibleReleaseLimit,a=typeof i==`number`&&i>0?t.slice(0,Math.floor(i)):t;return a.length>0?[...a,...r]:r},SF=(e,t)=>{let n=new Set(t),r=!1,i=new Set;for(let t of e)n.has(t)?i.add(t):r=!0;return r?i:e},CF=`data-markdown-ready`,wF=`data-markdown-hydration`,TF=`data-markdown-pin-reveal`,EF=e=>[...vF(e.entryKeys,{seedCount:e.seedCount,restore:e.restore})],DF=e=>e.reason===`jump-to-latest`||!e.alreadyRevealedForScope,OF=e=>{if(e.querySelector(`[data-markdown-hydration="deferred"]`))return!1;let t=e.querySelectorAll(`[data-markdown-content]`);if(t.length===0)return!0;for(let e of t)if(!e.closest(`[data-markdown-ready="true"]`))return!1;return!0},kF=(e,t)=>{if(t.size===0)return!0;let n=e.querySelectorAll(`[data-turn-entry]`),r=!1;for(let e of n){let n=e.getAttribute(`data-turn-entry`);if(!(!n||!t.has(n))&&(r=!0,!OF(e)))return!1}return r},AF=(e,t)=>{if(e){if(t){e.style.visibility=`hidden`,e.setAttribute(TF,`pending`);return}e.style.removeProperty(`visibility`),e.setAttribute(TF,`ready`)}},jF=(e,t)=>t?{...e,visibility:`hidden`}:e,MF=({root:e,relevantKeys:t,onReady:n,timeoutMs:r=600,signal:i})=>{let a=!1,o=()=>{a||(a=!0,d(),n())},s=()=>{if(i?.aborted){o();return}kF(e,t)&&o()},c=null;if(typeof MutationObserver<`u`){c=new MutationObserver(s);let t=e instanceof Element?e:e instanceof Document?e.documentElement:null;t&&c.observe(t,{subtree:!0,childList:!0,attributes:!0,attributeFilter:[CF,wF,`data-turn-entry`]})}let l=null;r>0&&(l=setTimeout(o,r));let u=()=>o();i?.addEventListener(`abort`,u,{once:!0});let d=()=>{c?.disconnect(),c=null,l!==null&&(clearTimeout(l),l=null),i?.removeEventListener(`abort`,u)};return s(),queueMicrotask(s),()=>{a||(a=!0,d())}},NF=e=>{let t=new Map,n=!1,r=()=>{if(n=!1,t.size===0)return;let r=new Map(t);t.clear(),e(r)};return{enqueue(e,i){t.set(e,i),!n&&(n=!0,queueMicrotask(r))},flush:r,clear(){t.clear(),n=!1},pendingCount:()=>t.size}},PF=e=>{let t=e.borderBoxSize?.[0];return t?{width:t.inlineSize,height:t.blockSize}:{width:e.contentRect.width,height:e.contentRect.height}},FF=e=>{let t=NF(e),n=typeof ResizeObserver>`u`?null:new ResizeObserver(e=>{for(let n of e)t.enqueue(n.target,PF(n))});return{observe(e){n?.observe(e)},unobserve(e){n?.unobserve(e)},disconnect(){n?.disconnect(),t.clear()}}},IF=e=>{let t=e.resizeItem.bind(e),n=NF(e=>{for(let[n,r]of e)t(n,r)});return e.resizeItem=(e,t)=>{n.enqueue(e,t)},()=>{e.resizeItem=t,n.flush()}},LF=({scopeKey:e,generation:t=0,root:n,relevantKeys:r,enabled:i=!0,initiallyRevealed:a=!1})=>{let o=`${e}:${t}`,[s,c]=Q.useState(o),[l,u]=Q.useState(i&&!a),d=Q.useRef(new Set(a?[e]:[]));i&&s!==o&&(DF({reason:t>0&&s.startsWith(`${e}:`)?`jump-to-latest`:`session-open`,alreadyRevealedForScope:d.current.has(e)})&&u(!0),c(o)),!i&&l&&u(!1);let f=r.join(`\0`),p=Q.useMemo(()=>new Set(r),[f]),m=J(()=>{d.current.add(e),u(!1)});return Gt(()=>{if(!i||!l){AF(n,!1);return}if(AF(n,!0),n)return MF({root:n,relevantKeys:p,onReady:m})},[i,l,n,p,o]),i&&l},RF=(e,t)=>{if(t.length===0||!Number.isFinite(e.scroll)||!Number.isFinite(e.start))return null;let n=Math.max(0,Math.min(Math.floor(e.start),t.length-1)),r=t[n];if(r===void 0)return null;let i=e.positionAtIndex(n);return i===void 0||!Number.isFinite(i)?null:{key:r,offsetFromViewportTop:i-e.scroll}},zF=(e,t)=>{let n=RF(e,t);return n===null?null:{anchor:n,knownKeys:new Set(t)}},BF=15e3,VF=(e,t)=>{let n=e.positionByKey(t.key);return n===void 0||!Number.isFinite(n)?null:n-t.offsetFromViewportTop},HF=(e,t)=>{if(!Number.isFinite(e.scroll))return null;let n=VF(e,t);return n===null?null:e.scroll-n},UF=e=>{if(e.drift===null||e.elapsedMs>=3e3)return{action:`release`,stableFrames:0};if(Math.abs(e.drift)<=1){let t=e.stableFrames+1;return{action:t>=8?`release`:`wait`,stableFrames:t}}return{action:e.msSinceLastCorrection>=64?`correct`:`wait`,stableFrames:0}},WF=1;function GF(e,{offset:t=0,hideTopShadow:n=!1,hideBottomShadow:r=!1}={}){let i=e.scrollTop>t+WF,a=e.scrollHeight-(e.scrollTop+e.clientHeight)>t+WF,o=!n&&i;return r&&(a=!1),o&&a?(e.dataset.topBottomScroll=`true`,e.removeAttribute(`data-top-scroll`),e.removeAttribute(`data-bottom-scroll`)):(e.dataset.topScroll=String(o),e.dataset.bottomScroll=String(a),e.removeAttribute(`data-top-bottom-scroll`)),o&&a?`both`:o?`top`:a?`bottom`:`none`}function KF(e,t=48){e.dataset.scrollShadow=`true`,e.dataset.orientation=`vertical`,e.style.setProperty(`--scroll-shadow-size`,`${t}px`)}var qF=.4,JF=e=>!Number.isFinite(e)||e<=0?0:e*qF,YF=(e,t=16)=>Number.isFinite(e)&&e>0?e:t,XF=({viewportHeight:e,endInsetHeight:t=0,anchorOffset:n=16})=>!Number.isFinite(e)||e<=0?0:Math.max(0,e-(Number.isFinite(t)?Math.max(0,t):0)-n),ZF=e=>{let{contentLength:t,scrollLength:n}=e;return typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)?null:Math.max(0,t-n)},QF=({anchorTop:e,anchorOffset:t=16,maxScrollOffset:n})=>{let r=Math.max(0,e-t);return typeof n!=`number`||!Number.isFinite(n)?r:Math.min(r,Math.max(0,n))},$F=({scroll:e,parkOffset:t})=>!Number.isFinite(e)||!Number.isFinite(t)?0:Math.max(0,t-e),eI=`data-oc-timeline-park-end`,tI=e=>{if(!e)return null;let t=e.getAttribute(eI);if(t===null||t===``)return null;let n=Number(t);return Number.isFinite(n)?n:null},nI=(e,t)=>{if(!e)return;if(t===null||!Number.isFinite(t)){e.hasAttribute(`data-oc-timeline-park-end`)&&e.removeAttribute(eI);return}let n=String(Math.round(t));e.getAttribute(`data-oc-timeline-park-end`)!==n&&e.setAttribute(eI,n)},rI=(e,t)=>t!==null&&Number.isFinite(t)?$F({scroll:e.scrollTop,parkOffset:t}):Math.max(0,e.scrollHeight-e.scrollTop-e.clientHeight),iI=({usableViewportHeight:e,viewportHeight:t,contentHeight:n})=>{if(!Number.isFinite(e)||e<=0)return 0;let r=JF(Number.isFinite(t)&&t>0?t:e),i=r>0?Math.min(e,r):e;return n===null||!Number.isFinite(n)||n<=0?i:Math.min(i,Math.max(0,e-n))},aI=(e,t)=>!Number.isFinite(e)||!Number.isFinite(t)||t<=0?!1:e>t+1,oI=({overflowsUsableViewport:e=!1,previousEndSpaceSize:t,nextEndSpaceSize:n})=>e?!0:t===void 0||n===void 0||!Number.isFinite(t)||!Number.isFinite(n)?!1:n>t+1,sI=({previous:e,reserveId:t,entryKey:n,contentHeight:r,usableViewportHeight:i,viewportHeight:a})=>{let o=iI({usableViewportHeight:i,viewportHeight:a,contentHeight:r}),s=r!==null&&aI(r,i),c={reserveId:t,entryKey:n,contentHeight:r,spacerHeight:s?0:o};return s?{snapshot:c,release:!0}:e===null||e.reserveId!==t||e.entryKey!==n?{snapshot:c,release:!1}:e.contentHeight!==null&&r!==null&&r+1<e.contentHeight&&oI({previousEndSpaceSize:e.spacerHeight,nextEndSpaceSize:o})?{snapshot:{...c,spacerHeight:0},release:!0}:{snapshot:c,release:!1}},cI=(e,t)=>{let n=e.positionAtIndex(t),r=e.sizeAtIndex(t);return typeof n!=`number`||typeof r!=`number`||!Number.isFinite(n)||!Number.isFinite(r)?null:n+Math.max(1,r)},lI=({state:e,anchorIndex:t,endInsetHeight:n,anchorOffset:r,lastIndex:i})=>{if(e.data.length===0)return null;let a=Math.max(0,Math.min(t,e.data.length-1)),o=e.positionAtIndex(a),s=cI(e,Math.max(0,Math.min(i??e.data.length-1,e.data.length-1)));if(typeof o!=`number`||!Number.isFinite(o)||s===null)return null;let c=XF({viewportHeight:e.scrollLength,endInsetHeight:n,anchorOffset:r}),l=Math.max(0,s-o),u=e.scroll+c,d=Math.max(0,s-c),f=Math.max(0,d-e.scroll);return{anchorTop:o,lastBottom:s,turnHeight:l,usableViewportHeight:c,visibleUsableBottom:u,overflowsUsableViewport:l>c,targetScrollToRevealEnd:d,scrollDeltaToRevealEnd:f}},uI=e=>{if(!e)return;let{contentLength:t,scroll:n,scrollLength:r}=e;return typeof t==`number`&&typeof n==`number`&&typeof r==`number`&&Number.isFinite(t)?t-(n+r)<=40:e.isNearEnd??e.isAtEnd},dI=e=>{if(!e)return;let{contentLength:t,scroll:n,scrollLength:r}=e;if(!(typeof t!=`number`||typeof n!=`number`||typeof r!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)))return Math.max(0,t-(n+r))},fI=(e,t)=>e===void 0||!Number.isFinite(e)?t:e<=40?!1:e>=80||t,pI=(e,t)=>{if(e.length===0||t.length<=e.length)return!1;let n=e[0];return n===void 0||t[0]===n?!1:t.includes(n)},mI=`data-oc-timeline-anchoring`,hI=1200,gI=(e,t,n,r={})=>{if(t!==null)for(let i=e.length-1;i>=0;--i){let a=e[i];if(a!==void 0&&n(a)===t)return{anchorIndex:i,anchorOffset:r.anchorOffset??16,anchorId:t}}},_I=({sessionChanged:e,previousUserOrder:t,currentUserOrder:n,currentAnchorId:r,consumedSendMessageId:i})=>{if(i!==null)return i;if(e||r===null)return null;if(n.includes(r))return r;let a=t[t.length-1],o=n[n.length-1];return r===a&&o!==void 0&&n.length===t.length&&t.length>0?o:r},vI=(e,t)=>!Number.isFinite(t)||t<=0||typeof e!=`number`||!Number.isFinite(e)||t+1>=e?null:t,yI={itemVisiblePercentThreshold:0},bI=100,xI=116,SI=500,CI=new Set,wI=Q.createContext(CI),TI=`oc-reply-reserve`,EI=e=>e.kind===TI,DI=e=>{if(EI(e))return e.spacerHeight>0?e.spacerHeight:void 0},OI=(e,t,n,r,i)=>{if(!e||t)return null;let a=lI({state:n,anchorIndex:e.anchorIndex,lastIndex:e.anchorIndex,endInsetHeight:r,anchorOffset:i});return a?QF({anchorTop:a.anchorTop,anchorOffset:i,maxScrollOffset:ZF(n)}):null},kI=(e,t)=>{if(typeof t==`number`&&Number.isFinite(t)&&t>0)return t;let n=e?.clientHeight??0;return n>0?n:0},AI=e=>e.key,jI=e=>e.kind,MI=()=>{let e=(0,pd.c)(6),t=Q.useRef(null),n=Q.useRef(0),[r,i]=Q.useState(null),[a,o]=Q.useState(0),s;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(s=()=>{let e=t.current?.offsetHeight??0;n.current=e,o(t=>t===e?t:e)},e[0]=s):s=e[0];let c=J(s),l;e[1]===c?l=e[2]:(l=e=>{t.current=e,i(t=>t===e?t:e),c()},e[1]=c,e[2]=l);let u=J(l);Vt(typeof ResizeObserver<`u`?r:null,c);let d;return e[3]!==a||e[4]!==u?(d={height:a,heightRef:n,setElement:u},e[3]=a,e[4]=u,e[5]=d):d=e[5],d},NI=({entry:e,index:t,renderEntryRef:n,sizeObserverRef:r})=>{let i=Q.useContext(wI),a=Q.useRef(null);return Q.useLayoutEffect(()=>{let e=a.current,t=r.current;if(!(!e||!t))return t.observe(e),()=>t.unobserve(e)},[e.key,r]),(0,$.jsx)(`div`,{ref:a,"data-turn-entry":e.key,className:`oc-chat-message-layout-boundary`,children:n.current?.(e,t,i.has(e.key))})},PI=Q.memo(({entries:e,timelineCacheKey:t,estimatedItemSize:n,hydrationTuning:r,renderEntry:i,rowInvalidationKey:a,scrollElementRef:o,scrollElementDataset:s,hideTopScrollShadow:c=!1,hideBottomScrollShadow:l=!1,registerList:u,anchoredEndSpace:d,onAnchoredTurnParkReleased:f,followEnabled:p=!0,historyAnchorToken:m=0,pinRevealGeneration:h=0,initialPinRevealComplete:g=!1,sessionIsWorking:_=!1,onIsAtEndChange:v,onScroll:y,header:b,footer:x,className:S,style:C,contentContainerClassName:w,contentContainerStyle:T})=>{let E=Q.useRef(null),D=Q.useMemo(()=>e.map(e=>e.key),[e]),O=Q.useRef(D);O.current=D;let k=Q.useRef(r);k.current=r;let A=J(e=>{E.current=e,u?.(e)}),j=Q.useRef(null),[M,N]=Q.useState(null),[P,F]=Q.useState(0),{height:I,setElement:L}=MI(),{height:R,heightRef:z,setElement:B}=MI(),V=b==null?null:(0,$.jsx)(`div`,{ref:L,"data-oc-timeline-header":``,children:b}),H=x==null?null:(0,$.jsx)(`div`,{ref:B,"data-oc-timeline-footer":``,children:x}),ee=Q.useRef(c);ee.current=c;let U=Q.useRef(l);U.current=l;let te=J((e=j.current)=>{!e||s?.scrollShadow!==`true`||(KF(e),GF(e,{hideTopShadow:ee.current,hideBottomShadow:U.current}))}),W=J(e=>{let t=e?.getScrollableNode?.()??null;if(t&&s){for(let[e,n]of Object.entries(s))t.dataset[e]=n;te(t)}j.current=t,o&&(o.current=t),N(t);let n=kI(t,E.current?.getState()?.scrollLength);F(e=>e===n?e:n)}),ne=J(()=>{let e=kI(j.current,E.current?.getState()?.scrollLength);F(t=>t===e?t:e),te()});Q.useLayoutEffect(()=>{te(M)},[l,c,M]),Vt(typeof ResizeObserver<`u`?M:null,ne);let[G,re]=Q.useState(0),[ie,K]=Q.useState(0),ae=G!==ie,oe=Q.useRef(!0),se=Q.useRef(!1),[ce,le]=Q.useState(!1),ue=Q.useRef(!1);Q.useLayoutEffect(()=>{oe.current=!0,se.current=!1,ue.current=!1,le(!1)},[t]);let[de,fe]=Q.useState(null),pe=J(e=>{fe(t=>t?.token===e?null:t)});Q.useEffect(()=>{p&&fe(null)},[p]),Q.useLayoutEffect(()=>{if(m<=0)return;let e=E.current;if(!e)return;let t=zF(e.getState(),O.current);t&&fe({token:m,arm:t,holding:!1})},[m]),Q.useEffect(()=>{if(!de||de.holding)return;let{token:e}=de,t=window.setTimeout(()=>{fe(t=>t?.token===e&&!t.holding?null:t)},BF);return()=>window.clearTimeout(t)},[de]);let me=Q.useRef(D);Q.useLayoutEffect(()=>{let e=me.current;me.current=D,pI(e,D)&&(re(e=>e+1),fe(e=>e===null||e.holding?e:{...e,holding:!0}))},[D]),Q.useEffect(()=>{if(!ae)return;let e=window.setTimeout(()=>{K(G)},hI);return()=>window.clearTimeout(e)},[ae,G]),Q.useEffect(()=>{if(!de?.holding)return;let{token:e,arm:{anchor:t}}=de,n=E.current;if(!n||typeof window>`u`){pe(e);return}let r=j.current,i=Date.now(),a=0,o=null,s=null,c=!1,l=[],u=t=>{if(!c){c=!0,s!==null&&(window.cancelAnimationFrame(s),s=null);for(let[e,t]of l)r?.removeEventListener(e,t);t&&pe(e)}},d=()=>{if(s=null,c)return;let e=n.getState();if(uI(e)??e.isAtEnd){u(!0);return}let r=Date.now(),l=UF({drift:HF(e,t),elapsedMs:r-i,stableFrames:a,msSinceLastCorrection:o===null?1/0:r-o});if(a=l.stableFrames,l.action===`release`){u(!0);return}if(l.action===`correct`){let i=VF(e,t);i!==null&&(o=r,n.scrollToOffset({offset:i,animated:!1}))}s=window.requestAnimationFrame(d)},f=()=>{u(!0)};for(let e of[`touchstart`,`touchmove`,`wheel`,`pointerdown`,`keydown`])l.push([e,f]);for(let[e,t]of l)r?.addEventListener(e,t,{passive:!0});return s=window.requestAnimationFrame(d),()=>{u(!1)}},[pe,de]);let he=ae||de!==null;Q.useLayoutEffect(()=>{let e=j.current;if(!(!e||!he))return e.setAttribute(mI,`true`),()=>{e.removeAttribute(mI)}},[he]);let ge=Q.useMemo(()=>{if(de===null)return{data:!0,size:ae};let{knownKeys:e}=de.arm;return{data:!0,size:!0,shouldRestorePosition:t=>e.has(t.key)}},[de,ae]),[_e,ve]=Q.useState(()=>vF(D,{restore:gF(t)??null})),ye=Q.useRef(_e);ye.current=_e;let be=Q.useRef(0),xe=Q.useRef(0),Se=Q.useRef(null),Ce=Q.useRef(!1),we=Q.useRef(null),Te=Q.useMemo(()=>yF(_e,D),[_e,D]),Ee=jF(C,LF({scopeKey:t,generation:h,root:M,relevantKeys:Q.useMemo(()=>EF({entryKeys:D}),[t,h,D.length,D[D.length-1]]),enabled:D.length>0,initiallyRevealed:g}));Q.useEffect(()=>{ve(e=>SF(e,D))},[D]),Q.useEffect(()=>()=>{_F(t,ye.current)},[t]);let De=J(()=>{Ce.current=!1;let e=E.current;if(!e)return;let t=O.current;if(t.length===0)return;let n=e.getState(),r=t.length-1,i=Math.max(0,Math.floor(n.startBuffered)),a=Math.min(r,Math.floor(n.endBuffered));if(!Number.isFinite(i)||!Number.isFinite(a)||a<i)return;let o=[];for(let e=i;e<=a;e+=1)o.push(e);let s=Math.max(0,Math.floor(n.start)),c=Math.min(r,Math.floor(n.end)),l=Math.max(0,c-s+1),u=Date.now()-be.current>=bI,d=k.current,f=d.resolvePreloadEntries(l),p=xF({entryKeys:t,mountedIndexes:o,visibleStartIndex:s,visibleEndIndex:c,scrollDirection:Se.current,preloadEntries:f,hydratedKeys:ye.current,allowVisibleRelease:u,preloadReleaseLimit:u?f:d.resolvePreloadReleaseWhileScrolling(),visibleReleaseLimit:d.resolveVisibleReleaseLimit()});p.length!==0&&(ke(),Q.startTransition(()=>{ve(e=>{let t=!1,n=new Set(e);for(let e of p)n.has(e)||(n.add(e),t=!0);return t?n:e})}))}),Oe=J(()=>{Ce.current||(Ce.current=!0,Jl(De))}),ke=J(()=>{typeof window>`u`||(we.current!==null&&window.clearTimeout(we.current),we.current=window.setTimeout(()=>{we.current=null,Oe()},xI))});Q.useEffect(()=>()=>{we.current!==null&&(window.clearTimeout(we.current),we.current=null)},[]);let Ae=J(()=>{Oe()}),je=J(()=>{be.current=Date.now();let e=E.current;if(e){let t=e.getState(),n=t.scroll;Number.isFinite(n)&&n!==xe.current&&(Se.current=n>xe.current?`forward`:`backward`,xe.current=n);let r=kI(j.current,t.scrollLength);r>0&&F(e=>e===r?e:r);let i=OI(Ye.current,Ie.current,t,z.current,Ze.current);nI(j.current,i);let a=i===null?null:$F({scroll:t.scroll,parkOffset:i}),o=a??dI(t),s=a===null?uI(t)??t.isAtEnd:a<=40,c=fI(o,se.current);(s!==oe.current||c!==se.current)&&(oe.current=s,se.current=c,v?.(s,c)),s&&!ue.current&&(ue.current=!0,le(!0))}y?.(),te(),Oe(),ke()}),Me=Q.useRef(i);Me.current=i;let[Ne,Pe]=Q.useState(null),Fe=Q.useRef(null),Ie=Q.useRef(!1),Le=Q.useRef(null),Re=Q.useRef(null),ze=Q.useRef(0),Be=Q.useRef(0),Ve=Q.useRef(null),He=J((e,t)=>{let n=E.current,r=n?.getState().sizes.get(e);if(n&&vI(r,t.height)!==null&&n.setItemSize(e,t),Ie.current||e!==Re.current)return;let i=Le.current;if(i===null)return;let{snapshot:a,release:o}=sI({previous:Fe.current,reserveId:i,entryKey:e,contentHeight:t.height,usableViewportHeight:ze.current,viewportHeight:Be.current});if(o){Pe(null),ct(i),lt(`reveal`);return}let s=Fe.current;(s?.spacerHeight!==a.spacerHeight||s?.contentHeight!==a.contentHeight||s?.entryKey!==a.entryKey||s?.reserveId!==a.reserveId)&&Pe(a),Ve.current!==i&<(`park`)&&(Ve.current=i)}),Ue=Q.useRef(He);Ue.current=He;let We=Q.useMemo(()=>FF(e=>{for(let[t,n]of e){let e=t instanceof HTMLElement?t.dataset.turnEntry:void 0;e&&n.height>0&&Ue.current(e,n)}}),[]),Ge=Q.useRef(We);Ge.current=We,Q.useEffect(()=>()=>{We.disconnect()},[We]);let Ke=Q.useMemo(()=>({item:e,index:t})=>EI(e)?(0,$.jsx)(`div`,{"data-oc-reply-reserve":`true`,"aria-hidden":`true`,style:{height:e.spacerHeight,flexShrink:0}}):(0,$.jsx)(NI,{entry:e,index:t,renderEntryRef:Me,sizeObserverRef:Ge}),[]),qe=Q.useRef(p);qe.current=p;let Je=Q.useRef(de);Je.current=de;let Ye=Q.useRef(d);Ye.current=d;let Xe=Q.useRef(0),Ze=Q.useRef(16),Qe=Q.useRef(null),[$e,et]=Q.useState(null),tt=d?e[d.anchorIndex]?.key??null:null,nt=d?.anchorId??tt,rt=nt!==null&&$e===nt;d||(Ve.current=null,Xe.current=0);let it=P>0?P:kI(j.current,E.current?.getState()?.scrollLength),at=YF(I),ot=XF({viewportHeight:it,endInsetHeight:R,anchorOffset:at}),st=Ne;if(!nt||!tt||rt)Ne!==null&&Pe(null),st=null;else if(ot<=0)st=Ne!==null&&Ne.reserveId===nt&&Ne.entryKey===tt?Ne:null;else if(Ne===null||Ne.reserveId!==nt||Ne.entryKey!==tt){let{snapshot:e}=sI({previous:Ne?.reserveId===nt?Ne:null,reserveId:nt,entryKey:tt,contentHeight:Ne?.reserveId===nt?Ne.contentHeight:null,usableViewportHeight:ot,viewportHeight:it});Pe(e),st=e}Fe.current=st,Ie.current=rt,Le.current=nt,Re.current=tt,ze.current=ot,Be.current=it,Ze.current=at,Q.useLayoutEffect(()=>{Ve.current=null,Xe.current=0,Qe.current=null,et(null)},[t]),Q.useLayoutEffect(()=>{d&&ne()},[d]);let ct=J(e=>{e!==null&&Qe.current!==e&&(Qe.current=e,et(e),f?.(e))}),lt=J(t=>{let n=Ye.current;if(!n||Je.current)return!1;let r=E.current;if(!r)return!1;let i=r.getState(),a=Ze.current,o=lI({state:i,anchorIndex:n.anchorIndex,lastIndex:n.anchorIndex,endInsetHeight:z.current,anchorOffset:a});if(!o)return!1;if(t===`park`){let e=Math.max(0,o.anchorTop-a),t=typeof performance<`u`?performance.now():Date.now(),n=!(typeof window<`u`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches)&&Math.abs(i.scroll-e)>=1;return n&&(Xe.current=t+SI),r.scrollToOffset({offset:e,animated:n}),!0}return aI(o.turnHeight,ze.current)&&ct(n.anchorId??e[n.anchorIndex]?.key??null),(typeof performance<`u`?performance.now():Date.now())<Xe.current||!qe.current||o.scrollDeltaToRevealEnd<1?!1:(r.scrollToOffset({offset:o.targetScrollToRevealEnd,animated:!1}),!0)});Q.useLayoutEffect(()=>{if(!nt||!tt||rt||ot<=0)return;let e=Fe.current;if(e===null||e.reserveId!==nt||e.entryKey!==tt)return;let{snapshot:t,release:n}=sI({previous:e,reserveId:nt,entryKey:tt,contentHeight:e.contentHeight,usableViewportHeight:ot,viewportHeight:it});if(n){Pe(null),ct(nt),lt(`reveal`);return}t.spacerHeight!==e.spacerHeight&&Pe(t)},[tt,rt,nt,it,ot]),Q.useLayoutEffect(()=>{!st||de||Ve.current!==nt&<(`park`)&&(Ve.current=nt)},[st,de,nt]),Q.useLayoutEffect(()=>{let e=j.current,t=E.current;if(e){if(!t){nI(e,null);return}nI(e,OI(d,rt,t.getState(),R,at))}},[d,R,at,rt]);let ut=Q.useMemo(()=>{let t=st?.spacerHeight??0;return!st||t<=0?e:[...e,{key:`${TI}:${st.reserveId}`,kind:TI,spacerHeight:t}]},[st,e]),dt=Q.useMemo(()=>d&&!rt||!p||de?!1:{animated:_&&ce,on:{dataChange:!0,itemLayout:!0,layout:!0,footerLayout:!0}},[d,ce,p,de,rt,_]);return(0,$.jsx)(wI.Provider,{value:Te,children:(0,$.jsx)(ud,{ref:A,refScrollView:W,data:ut,extraData:a,keyExtractor:AI,getItemType:jI,getFixedItemSize:DI,renderItem:Ke,estimatedItemSize:n,initialScrollAtEnd:!0,recycleItems:!1,maintainScrollAtEnd:dt,maintainVisibleContentPosition:ge,onScroll:je,onViewableItemsChanged:Ae,viewabilityConfig:yI,ListHeaderComponent:V,ListFooterComponent:H,className:S,style:Ee,contentContainerClassName:w,contentContainerStyle:T})})}),FI=e=>{let t=e.info;return(typeof t.clientRole==`string`?t.clientRole:null)??(typeof t.role==`string`?t.role:null)??null},II=e=>{let t=e.info;return typeof t.parentID==`string`&&t.parentID.length>0?t.parentID:null},LI=e=>!e||FI(e)!==`user`?!1:e.parts.some(e=>{if(e?.type!==`text`)return!1;let t=e.text;return e.synthetic===!0&&typeof t==`string`&&t.trim().startsWith(`The following tool was executed by the user`)}),RI=(e,t)=>{if(FI(e)!==`assistant`||t&&II(e)!==t||e.parts.length!==1)return{hide:!1,details:null};let n=e.parts[0];return n?.type!==`tool`||(typeof n.tool==`string`?n.tool.toLowerCase():``)!==`bash`?{hide:!1,details:null}:{hide:!0,details:{command:typeof n.state?.input?.command==`string`?n.state.input.command:void 0,output:(typeof n.state?.output==`string`?n.state.output:void 0)??(typeof n.state?.metadata?.output==`string`?n.state.metadata.output:void 0),status:typeof n.state?.status==`string`?n.state.status:void 0}}},zI=(e,t)=>{let n=e[t];if(!n)return null;let r=n.info.id;for(let n=t+1;n<e.length;n+=1){let t=e[n];if(FI(t)===`user`)break;let{hide:i,details:a}=RI(t,r);if(i){let e=typeof a?.command==`string`?a.command.trim():``;return e.length>0?e:null}}return null},BI=e=>{let t=e.info,n=t.time?.completed,r=t.status;return typeof n!=`number`||n<=0?!1:typeof r!=`string`||r===`completed`},VI=(e,t)=>{if(e.length===0)return[];if(e.filter(BI).length===e.length)return e;if(t){let n=e.findIndex(e=>e.info.id===t);if(n>=0)return e.slice(0,n+1)}return e},HI=e=>{if(e.chatRenderMode!==`sorted`)return null;let t=e.streamingAssistantMessageId;if(!t)return null;let n=e.assistants.find(e=>e.info.id===t);if(!n)return null;let r=n.info,i=qk({finish:r.finish,isMessageCompleted:BI(n),activeStreamingPhase:e.activeStreamingPhase});return Jk({finish:r.finish,parts:n.parts,streamPhase:i,error:r.error,isLastAssistantInTurn:!0})?t:null},UI=(e,t)=>{if(!t)return e;let n=e.filter(e=>e.kind!==`justification`||e.messageId!==t);return n.length===e.length?e:n},WI=(e,t)=>{if(!t)return e;let n=!1,r=e.map(e=>{let r=UI(e.parts,t);return r===e.parts?e:(n=!0,{...e,parts:r})});return n?r:e},GI=e=>e.isActivelyProcessing||e.expansionDisposition===`active`?!0:zM(e.expansionDisposition,e.activityRenderMode,{isLastTurn:e.isLastTurn,hasConfirmedFinalBody:e.hasConfirmedFinalBody}),KI=5,qI=[],JI=new Set,YI=[],XI=16,ZI=(e,t)=>e===t?!0:!e||!t||e.length!==t.length?!1:e.every((e,n)=>e===t[n]),QI=320,$I=168,eL=8,tL=16,nL=6,rL=12,iL=4,aL=1,oL=2,sL=6,cL=4,lL=()=>yr()?tL:eL,uL=30,dL=180,fL=5,pL=2,mL=120,hL=1200,gL=80,_L=160,vL=1500,yL=1.5,bL=90,xL=(e,t)=>{if(e.length===0||t.length<=e.length||e[e.length-1]?.key!==t[t.length-1]?.key)return!1;let n=e[0]?.key;return t.findIndex(e=>e.key===n)>0},SL=(e=>{let t=new Map;return{read:(e,n)=>{let r=t.get(e);if(r){if(ZI(r.keys,n))return r.items;t.delete(e)}},write:(n,r,i)=>{if(r.length!==0)for(t.delete(n),t.set(n,{keys:r.slice(),items:i});t.size>e;){let e=t.keys().next().value;if(typeof e!=`string`)break;t.delete(e)}}}})(XI),CL=(e,t,n)=>{if(t.size===0)return[];let r=0;return e.map((e,i)=>{let a=t.get(e)??n,o={index:i,key:e,start:r,size:a,end:r+a,lane:0};return r+=a,o})},wL=(e,t)=>({sessionKey:e,virtualizerKey:t??e}),TL=e=>e===`collapsed`?$I:QI,EL=(e,t)=>`${e}::activity:${t}`,DL=(e,t)=>!Number.isFinite(t)||t<=0||e===null?!1:Math.round(e)!==Math.round(t),OL=(e,t,n)=>{let r=Number.isFinite(e)?Math.max(0,e):0,i=Number.isFinite(t)?Math.max(r,t):r,a=Number.isFinite(n)?Math.max(0,n):0;return{paddingTop:r,paddingBottom:Math.max(0,a-i),minHeight:a}},kL=(e,t)=>{if(!e)return;let n=`${Math.max(0,Number.isFinite(t)?t:0)}px`;e.style.height!==``&&(e.style.height=``),e.style.minHeight!==n&&(e.style.minHeight=n)},AL=(e,t=0)=>Math.max(e===`collapsed`?rL:nL,Math.max(0,Math.floor(t))),jL=e=>e===`collapsed`?oL:aL,ML=e=>e===`collapsed`?cL:sL,NL=e=>e===`collapsed`?pL:fL,PL=(e,t)=>{e.current=t},FL=(e,t)=>SL.read(e,t),IL=(e,t,n)=>{!n||t.length===0||SL.write(e,t,n.takeSnapshot())},LL=e=>{let t=e.info;return(typeof t.clientRole==`string`?t.clientRole:null)??(typeof t.role==`string`?t.role:null)??null},RL=(e,t)=>{if(LL(e)!==`system`)return e;let n=VL(e);return!n||!t.has(n)||e.info.clientRole===`assistant`?e:{...e,info:{...e.info,clientRole:`assistant`}}},zL=e=>!e||LL(e)!==`user`?!1:e.parts.some(e=>e?.type===`subtask`),BL=e=>{if(!e)return null;let t=e.info.id;return typeof t==`string`&&t.trim().length>0?t:null},VL=e=>{let t=e.info.parentID;return typeof t==`string`&&t.trim().length>0?t:null},HL=(e,t,n)=>{if(typeof window>`u`)return!1;let r=e;for(;r&&r!==t;){if(window.getComputedStyle(r).position===`sticky`&&r.getBoundingClientRect().top<=n+1)return!0;r=r.parentElement}return!1},UL=(e,t)=>Array.from(e.querySelectorAll(`[data-message-id]`)).find(e=>e.dataset.messageId===t)??null,WL=(e,t=e)=>{let n=e.getBoundingClientRect(),r=Array.from(t.querySelectorAll(`[data-message-id]`)),i=r.find(t=>t.getBoundingClientRect().bottom>n.top+1&&!HL(t,e,n.top))??r.find(e=>e.getBoundingClientRect().bottom>n.top+1),a=i?.dataset.messageId;return!i||!a?null:{messageId:a,offsetTop:i.getBoundingClientRect().top-n.top}},GL=(e,t)=>{let n=WL(t,e);if(!n)return null;let r=UL(e,n.messageId)?.closest(`[data-turn-entry]`)?.dataset.turnEntry;return r?{...n,entryKey:r,attempts:0}:null},KL=e=>{let t=e,n=t.state?.metadata,r=KT(n)??null;if(r)return r;let i=t.state?.output;return typeof i==`string`?XT(i)??null:null},qL=e=>{if(LL(e)!==`assistant`||e.parts.length!==1)return{hide:!1,taskSessionId:null};let t=e.parts[0];return t?.type!==`tool`||(typeof t.tool==`string`?t.tool.toLowerCase():``)!==`task`?{hide:!1,taskSessionId:null}:{hide:!0,taskSessionId:KL(e.parts[0])}},JL=(e,t)=>{if(!t)return e;let n=qT(e.parts,t);return n===e.parts?e:{...e,parts:n}},YL=(e,t)=>{let n=typeof t?.command==`string`?t.command.trim():``,r=typeof t?.output==`string`?t.output:``,i=typeof t?.status==`string`?t.status.trim():``,a=[],o=!1;for(let t of e.parts){if(!o&&t?.type===`text`){let e=t.text;if(t.synthetic===!0&&typeof e==`string`&&e.trim().startsWith(`The following tool was executed by the user`)){a.push({type:`text`,text:`/shell`,shellAction:{...n?{command:n}:{},...r?{output:r}:{},...i?{status:i}:{}}}),o=!0;continue}}a.push(t)}return o||a.push({type:`text`,text:`/shell`,shellAction:{...n?{command:n}:{},...r?{output:r}:{},...i?{status:i}:{}}}),{...e,parts:a}},XL=e=>e.kind===`turn`?e.turn.userMessage.info.id:LL(e.message)===`user`?e.message.info.id:null,ZL=e=>e.chatRenderMode!==`sorted`||e.activityPresentationKind!==`compaction`||e.hasVisibleActivitySegments||e.hasAssistantMessages?!1:e.completionDisposition===`normal`||e.completionDisposition===`abnormal`||e.completionDisposition===`active`&&e.isLastTurn&&e.sessionIsWorking,QL=Q.memo(e=>{let t=(0,pd.c)(23),{message:n,previousMessage:r,nextMessage:i,turnGroupingContext:a,assistantHeaderMessageId:o,turnOwnsAssistantHeader:s,isInActiveTurn:c,activeStreamingPhase:l,animateUserOnMount:u,onUserAnimationConsumed:d,onContentChange:f,animationHandlers:p,scrollToBottom:m,reviewTransferDirection:h}=e,g=Zy(),_;t[0]!==n.sourceDirectory||t[1]!==n.sourceSessionID||t[2]!==g?(_=n.sourceSessionID?{...g,sessionId:n.sourceSessionID,directory:n.sourceDirectory??null,onRevertMessage:void 0,onEditMessage:void 0,capabilities:{...g.capabilities,compose:!1,mutateSession:!1,answerRequests:!1,openTimeline:!1,forkSession:!1}}:g,t[0]=n.sourceDirectory,t[1]=n.sourceSessionID,t[2]=g,t[3]=_):_=t[3];let v=_,y;t[4]!==l||t[5]!==u||t[6]!==p||t[7]!==o||t[8]!==c||t[9]!==n||t[10]!==i||t[11]!==f||t[12]!==d||t[13]!==r||t[14]!==h||t[15]!==m||t[16]!==a||t[17]!==s?(y=(0,$.jsx)(uN,{message:n,previousMessage:r,nextMessage:i,animateUserOnMount:u,onUserAnimationConsumed:d,onContentChange:f,animationHandlers:p,scrollToBottom:m,turnGroupingContext:a,assistantHeaderMessageId:o,turnOwnsAssistantHeader:s,isInActiveTurn:c,activeStreamingPhase:l,reviewTransferDirection:h}),t[4]=l,t[5]=u,t[6]=p,t[7]=o,t[8]=c,t[9]=n,t[10]=i,t[11]=f,t[12]=d,t[13]=r,t[14]=h,t[15]=m,t[16]=a,t[17]=s,t[18]=y):y=t[18];let b=y,x;return t[19]!==b||t[20]!==v||t[21]!==g?(x=v===g?b:(0,$.jsx)(Xy.Provider,{value:v,children:b}),t[19]=b,t[20]=v,t[21]=g,t[22]=x):x=t[22],x},(e,t)=>{let n=e.turnGroupingContext,r=t.turnGroupingContext;return DE(e.message,t.message)&&e.message.sourceSessionID===t.message.sourceSessionID&&e.message.sourceDirectory===t.message.sourceDirectory&&OE(e.previousMessage,t.previousMessage)&&OE(e.nextMessage,t.nextMessage)&&e.animateUserOnMount===t.animateUserOnMount&&e.onUserAnimationConsumed===t.onUserAnimationConsumed&&e.onContentChange===t.onContentChange&&e.scrollToBottom===t.scrollToBottom&&IE(n,r,e.message.info.id,LL(e.message)===`user`)&&e.assistantHeaderMessageId===t.assistantHeaderMessageId&&e.turnOwnsAssistantHeader===t.turnOwnsAssistantHeader&&e.isInActiveTurn===t.isInActiveTurn&&e.activeStreamingPhase===t.activeStreamingPhase&&e.reviewTransferDirection===t.reviewTransferDirection&&e.animationHandlers?.onChunk===t.animationHandlers?.onChunk&&e.animationHandlers?.onComplete===t.animationHandlers?.onComplete&&e.animationHandlers?.onStreamingCandidate===t.animationHandlers?.onStreamingCandidate&&e.animationHandlers?.onAnimationStart===t.animationHandlers?.onAnimationStart&&e.animationHandlers?.onReservationCancelled===t.animationHandlers?.onReservationCancelled&&e.animationHandlers?.onReasoningBlock===t.animationHandlers?.onReasoningBlock&&e.animationHandlers?.onAnimatedHeightChange===t.animationHandlers?.onAnimatedHeightChange});QL.displayName=`MessageRow`;var $L=Q.memo(({turn:e,isLastTurn:t,sessionIsWorking:n,activityRenderMode:r,turnUiStates:i,onToggleTurnGroup:a,chatRenderMode:o,onMessageContentChange:s,getAnimationHandlers:c,scrollToBottom:l,stickyUserHeader:u=!0,shouldAnimateUserMessage:d,onUserAnimationConsumed:f,activeStreamingMessageId:p,activeStreamingPhase:m,reviewTransferDirection:h})=>{let g=Q.useRef(null);g.current===e.turnId&&!t&&e.completionDisposition!==`active`?g.current=null:e.completionDisposition===`active`&&t&&n&&(g.current=e.turnId);let _=g.current===e.turnId,v=Q.useRef({turnId:e.turnId,shown:!1});v.current.turnId!==e.turnId&&(v.current={turnId:e.turnId,shown:!1});let y=i.get(e.turnId),b=VM({completionDisposition:e.completionDisposition,isLastTurn:t,sessionIsWorking:n,durationMs:e.durationMs}),x=GI({expansionDisposition:WM({isLastTurn:t,turnCompletionDisposition:e.completionDisposition,headerPresentationDisposition:b.completionDisposition,hasAssistantMessages:e.assistantMessages.length>0}),activityRenderMode:r,isLastTurn:t,isActivelyProcessing:t&&n,hasConfirmedFinalBody:e.hasConfirmedFinalBody}),S=y?y.isExpanded:x,C=J(()=>{a(e.turnId,x)}),w=Q.useMemo(()=>{let t=[e.userMessage,...e.assistantMessages],n=new Map;return t.forEach((e,t)=>{n.set(e.info.id,t)}),{ordered:t,lookup:n}},[e.assistantMessages,e.userMessage]),T=Q.useMemo(()=>{if(p&&e.assistantMessages.some(e=>e.info.id===p))return p;for(let t=e.assistantMessages.length-1;t>=0;--t){let n=e.assistantMessages[t];if(!BI(n))return n.info.id}return null},[p,e.assistantMessages]),E=Q.useMemo(()=>HI({chatRenderMode:o,assistants:e.assistantMessages,streamingAssistantMessageId:T,activeStreamingPhase:m}),[m,o,T,e.assistantMessages]),D=Q.useMemo(()=>o===`live`?e.assistantMessages:VI(e.assistantMessages,T),[o,T,e.assistantMessages]),O=Q.useMemo(()=>{let e=new Map;return D.forEach((t,n)=>{e.set(t.info.id,n)}),e},[D]),k=Q.useMemo(()=>new Set(D.map(e=>e.info.id)),[D]),A=Q.useMemo(()=>D[0]?.info.id,[D]),j=Q.useMemo(()=>o===`sorted`?UI(k.size===e.assistantMessages.length?e.activityParts:e.activityParts.filter(e=>k.has(e.messageId)),E):e.activityParts,[o,E,k,e.activityParts,e.assistantMessages.length]),M=Q.useMemo(()=>o===`sorted`?E?WI(e.activitySegments,E):k.size===e.assistantMessages.length?e.activitySegments:e.activitySegments.map(e=>{let t=e.parts.filter(e=>k.has(e.messageId));if(t.length===0)return null;let n=k.has(e.anchorMessageId)?e.anchorMessageId:t[0]?.messageId;return n?{...e,anchorMessageId:n,parts:t}:null}).filter(e=>e!==null):e.activitySegments,[o,E,k,e.activitySegments,e.assistantMessages.length]),N=Q.useMemo(()=>{let t=e.userMessage.info.time?.created,n=e.userMessage.info,r=n?.model?.variant??n?.variant,i=typeof r==`string`&&r.trim().length>0?r:void 0;return{turnId:e.turnId,summaryBody:e.summaryText,activityParts:j,activityGroupSegments:M,headerMessageId:e.headerMessageId,hasTools:e.hasTools,hasReasoning:e.hasReasoning,activityPresentationKind:e.activityPresentationKind,diffStats:e.diffStats,changedFiles:e.changedFiles,userMessageCreatedAt:typeof t==`number`?t:void 0,userMessageVariant:i}},[e.activityPresentationKind,e.changedFiles,e.diffStats,e.hasReasoning,e.hasTools,e.headerMessageId,e.summaryText,e.turnId,e.userMessage.info,j,M]),P=oF((r,i)=>{let a=LL(r)===`user`,u=w.lookup.get(r.info.id),p=O.get(r.info.id)??-1,g=p>=0,_=p===0,v=p===D.length-1,y=!!A&&r.info.id===A,b=M.some(e=>e.anchorMessageId===r.info.id),x=o===`sorted`?g:y||_||v,S=D[0]?.info.id??e.headerMessageId,E=a?void 0:g?_?e.userMessage:void 0:typeof u==`number`&&u>0?w.ordered[u-1]:void 0,k=VM({completionDisposition:e.completionDisposition,isLastTurn:t,sessionIsWorking:n,durationMs:e.durationMs}),j=g?{turnId:e.turnId,activityOwnerMessageId:A,isFirstAssistantInTurn:_,isLastAssistantInTurn:v,isLatestTurn:t,isWorking:(t||e.completionDisposition===`active`)&&n&&(o===`sorted`?b:r.info.id===T),isTurnSettled:HM({completionDisposition:e.completionDisposition,isLastTurn:t,sessionIsWorking:n,hasConfirmedSettledAssistant:e.hasConfirmedFinalBody}),hasTools:e.hasTools,hasReasoning:e.hasReasoning,completionDisposition:k.completionDisposition,activityPresentationKind:e.activityPresentationKind,durationMs:k.durationMs,...x?{summaryBody:N.summaryBody,activityParts:N.activityParts,activityGroupSegments:N.activityGroupSegments,headerMessageId:N.headerMessageId,diffStats:N.diffStats,changedFiles:N.changedFiles,userMessageCreatedAt:N.userMessageCreatedAt,userMessageVariant:N.userMessageVariant,isGroupExpanded:i,toggleGroup:C}:{}}:void 0;return(0,$.jsx)(QL,{message:r,previousMessage:E,nextMessage:void 0,turnGroupingContext:j,assistantHeaderMessageId:S,turnOwnsAssistantHeader:g,isInActiveTurn:!!T&&r.info.id===T,activeStreamingPhase:r.info.id===T?m:null,reviewTransferDirection:h,animateUserOnMount:d(r),onUserAnimationConsumed:f,onContentChange:s,animationHandlers:c(r.info.id),scrollToBottom:l},r.info.id)}),F=Q.useMemo(()=>D===e.assistantMessages?e:{...e,assistantMessages:D},[e,D]),I=Q.useMemo(()=>((qN({isLastTurn:t,sessionIsWorking:n,hasAssistantMessages:e.assistantMessages.length>0,activityPresentationKind:e.activityPresentationKind,hasActiveStreamingMessage:!!p})||e.assistantMessages.length>0)&&(v.current.shown=!0),!v.current.shown||e.activityPresentationKind===`compaction`?null:KN(GN(e.userMessage.info))),[p,t,n,e.activityPresentationKind,e.assistantMessages.length,e.userMessage.info]);return(0,$.jsx)(tP,{turn:F,activityExpanded:S,onToggleActivity:C,showCompactionStatus:ZL({chatRenderMode:o,activityPresentationKind:e.activityPresentationKind,hasVisibleActivitySegments:M.length>0,hasAssistantMessages:e.assistantMessages.length>0,completionDisposition:e.completionDisposition,isLastTurn:t,sessionIsWorking:n}),pendingAssistantHeader:I,assistantHeaderMessage:D[0],assistantHeaderIsInActiveTurn:D[0]?.info.id===T,preserveActiveTurnGap:_,stickyUserHeader:u,renderMessage:P})});$L.displayName=`TurnBlock`;var eR=Q.memo(e=>{let t=(0,pd.c)(31),{message:n,previousMessage:r,nextMessage:i,onMessageContentChange:a,getAnimationHandlers:o,scrollToBottom:s,shouldAnimateUserMessage:c,onUserAnimationConsumed:l,activeStreamingMessageId:u,activeStreamingPhase:d,reviewTransferDirection:f}=e,{t:p}=Yt();if(Ua(n)){let e;t[0]===p?e=t[1]:(e=p(`assistants.conversation.newSessionDivider`),t[0]=p,t[1]=e);let n;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,$.jsx)(`div`,{className:`min-w-0 flex-1 border-t`}),t[2]=n):n=t[2];let r;t[3]===p?r=t[4]:(r=p(`assistants.conversation.newSessionDivider`),t[3]=p,t[4]=r);let i;t[5]===r?i=t[6]:(i=(0,$.jsx)(`span`,{className:`shrink-0 typography-meta text-muted-foreground`,children:r}),t[5]=r,t[6]=i);let a;t[7]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(`div`,{className:`min-w-0 flex-1 border-t`}),t[7]=a):a=t[7];let o;t[8]===i?o=t[9]:(o=(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[n,i,a]}),t[8]=i,t[9]=o);let s;return t[10]!==e||t[11]!==o?(s=(0,$.jsx)(`div`,{className:`chat-message-column px-4 py-5`,role:`separator`,"aria-label":e,children:o}),t[10]=e,t[11]=o,t[12]=s):s=t[12],s}let m;t[13]!==n||t[14]!==c?(m=c(n),t[13]=n,t[14]=c,t[15]=m):m=t[15];let h;t[16]!==o||t[17]!==n.info.id?(h=o(n.info.id),t[16]=o,t[17]=n.info.id,t[18]=h):h=t[18];let g=!!u&&n.info.id===u,_=n.info.id===u?d:null,v;return t[19]!==n||t[20]!==i||t[21]!==a||t[22]!==l||t[23]!==r||t[24]!==f||t[25]!==s||t[26]!==m||t[27]!==h||t[28]!==g||t[29]!==_?(v=(0,$.jsx)(QL,{message:n,previousMessage:r,nextMessage:i,animateUserOnMount:m,onUserAnimationConsumed:l,onContentChange:a,animationHandlers:h,scrollToBottom:s,isInActiveTurn:g,activeStreamingPhase:_,reviewTransferDirection:f}),t[19]=n,t[20]=i,t[21]=a,t[22]=l,t[23]=r,t[24]=f,t[25]=s,t[26]=m,t[27]=h,t[28]=g,t[29]=_,t[30]=v):v=t[30],v});eR.displayName=`UngroupedMessageRow`;var tR=Q.memo(e=>{let t=(0,pd.c)(24),{entry:n,onMessageContentChange:r,getAnimationHandlers:i,scrollToBottom:a,stickyUserHeader:o,sessionIsWorking:s,activityRenderMode:c,turnUiStates:l,onToggleTurnGroup:u,chatRenderMode:d,shouldAnimateUserMessage:f,onUserAnimationConsumed:p,activeStreamingMessageId:m,activeStreamingPhase:h,reviewTransferDirection:g,showLiveStatusRow:_}=e,v=_!==void 0&&_,y;t[0]!==m||t[1]!==h||t[2]!==c||t[3]!==d||t[4]!==n.isLastTurn||t[5]!==n.kind||t[6]!==n.message||t[7]!==n.nextMessage||t[8]!==n.previousMessage||t[9]!==n.turn||t[10]!==i||t[11]!==r||t[12]!==u||t[13]!==p||t[14]!==g||t[15]!==a||t[16]!==s||t[17]!==f||t[18]!==o||t[19]!==l?(y=n.kind===`ungrouped`?(0,$.jsx)(eR,{message:n.message,previousMessage:n.previousMessage,nextMessage:n.nextMessage,onMessageContentChange:r,getAnimationHandlers:i,scrollToBottom:a,shouldAnimateUserMessage:f,onUserAnimationConsumed:p,activeStreamingMessageId:m,activeStreamingPhase:h,reviewTransferDirection:g}):(0,$.jsx)($L,{turn:n.turn,isLastTurn:n.isLastTurn,sessionIsWorking:s,activityRenderMode:c,turnUiStates:l,onToggleTurnGroup:u,chatRenderMode:d,shouldAnimateUserMessage:f,onUserAnimationConsumed:p,activeStreamingMessageId:m,activeStreamingPhase:h,reviewTransferDirection:g,onMessageContentChange:r,getAnimationHandlers:i,scrollToBottom:a,stickyUserHeader:o}),t[0]=m,t[1]=h,t[2]=c,t[3]=d,t[4]=n.isLastTurn,t[5]=n.kind,t[6]=n.message,t[7]=n.nextMessage,t[8]=n.previousMessage,t[9]=n.turn,t[10]=i,t[11]=r,t[12]=u,t[13]=p,t[14]=g,t[15]=a,t[16]=s,t[17]=f,t[18]=o,t[19]=l,t[20]=y):y=t[20];let b=y;if(!v)return b;let x;t[21]===Symbol.for(`react.memo_cache_sentinel`)?(x=(0,$.jsx)(`div`,{className:`mb-1`,children:(0,$.jsx)(RN,{})}),t[21]=x):x=t[21];let S;return t[22]===b?S=t[23]:(S=(0,$.jsxs)($.Fragment,{children:[b,x]}),t[22]=b,t[23]=S),S});tR.displayName=`MessageListEntry`;var nR=Q.memo(({entries:e,engine:t,contentRef:n,scrollRef:r,registerTanstackVirtualizer:i,virtualizerKey:a,onMessageContentChange:o,getAnimationHandlers:s,scrollToBottom:c,stickyUserHeader:l,activityRenderMode:u,turnUiStates:d,onToggleTurnGroup:f,chatRenderMode:p,shouldAnimateUserMessage:m,onUserAnimationConsumed:h,reviewTransferDirection:g})=>{let _=t===`tanstack`,v=Q.useRef(t),y=Q.useRef(null),[b,x]=Q.useReducer(e=>e+1,0);if(t===`none`)y.current=null;else if(v.current===`none`&&_&&y.current===null){let e=n.current,t=r?.current;e&&t&&(y.current=GL(e,t))}let S=Q.useRef(!1),C=Q.useRef(0),w=Q.useRef(null),T=_&&yr();Q.useEffect(()=>{if(!T)return;let e=r?.current;if(!e)return;let t=()=>{S.current=!0},n=()=>{S.current=!1},i=()=>{C.current=performance.now()};return e.addEventListener(`touchstart`,t,{passive:!0}),e.addEventListener(`touchend`,n,{passive:!0}),e.addEventListener(`touchcancel`,n,{passive:!0}),e.addEventListener(`scroll`,i,{passive:!0}),()=>{e.removeEventListener(`touchstart`,t),e.removeEventListener(`touchend`,n),e.removeEventListener(`touchcancel`,n),e.removeEventListener(`scroll`,i)}},[T,r]);let E=()=>S.current||performance.now()-C.current<_L,D=()=>{let e=r?.current;return!e||e.scrollTop<e.clientHeight*yL},[O,k]=Q.useState(e),A=O;e===O?w.current!==null&&(w.current=null):T&&xL(O,e)&&E()&&!D()&&(w.current===null||performance.now()-w.current<vL)?w.current===null&&(w.current=performance.now()):(w.current=null,k(e),A=e);let[,j]=Q.useReducer(e=>e+1,0);Bt(()=>{if(w.current===null)return;let e=performance.now()-w.current>=vL;(!E()||D()||e)&&j()},T?bL:null);let M=Q.useRef(A);M.current=A;let N=Q.useMemo(()=>A.map(e=>e.key),[A]),P=lL(),[F,I]=Q.useState(()=>lF(P));Q.useEffect(()=>{if(!(!_||F>=P))return Jl(()=>{Q.startTransition(()=>{I(e=>uF(e,P))})})},[F,_,P]);let L=EL(a,u),[R]=Q.useState(()=>_?FL(L,e.map(e=>e.key)):void 0),z=Q.useRef(null),B=TL(u),V=Q.useRef(B),H=Q.useRef(u);H.current!==u&&(H.current=u,V.current=B);let ee=Q.useRef(_),U=Q.useRef(new Map),te=Q.useRef(void 0);Q.useLayoutEffect(()=>{if(_)return;let e=n?.current;if(!e)return;let t=U.current;t.clear(),e.querySelectorAll(`[data-turn-entry]`).forEach(e=>{let n=e.dataset.turnEntry;n&&t.set(n,e.getBoundingClientRect().height)}),te.current=void 0}),_&&te.current===void 0&&(te.current=R??CL(N,U.current,V.current));let W=od({count:A.length,enabled:_,getScrollElement:()=>r?.current??null,estimateSize:()=>V.current,overscan:F,scrollToFn:(e,t,n)=>{kL(z.current,n.getTotalSize()),ad(e,t,n)},getItemKey:e=>M.current[e]?.key??`index:${e}`,anchorTo:`end`,followOnAppend:!0,scrollEndThreshold:gL,initialOffset:()=>ee.current?2**53-1:r?.current?.scrollTop??0,initialMeasurementsCache:te.current});Gt(()=>{if(_)return IF(W)},[_,W]);let ne=Q.useRef(null),G=Q.useRef(null);_||(ne.current=null);let re=J(()=>{if(!_)return;let e=z.current??r?.current;if(!e)return;let t=e.offsetWidth;if(!DL(ne.current,t)){ne.current===null&&t>0&&(ne.current=t);return}ne.current=t,G.current!==null&&clearTimeout(G.current),G.current=setTimeout(()=>{G.current=null,W.measure()},220)}),ie=_&&typeof ResizeObserver<`u`;Vt(ie?z:null,re),Vt(ie&&r?r:null,re),Ht(()=>{G.current!==null&&(clearTimeout(G.current),G.current=null)}),Gt(()=>{_&&re()},[_]),Gt(()=>{if(v.current=t,!_){y.current=null;return}let e=y.current,n=r?.current;if(!e||!n)return;let i=UL(n,e.messageId);if(i){let t=i.getBoundingClientRect().top-n.getBoundingClientRect().top-e.offsetTop;Math.abs(t)>.5&&(n.scrollTop+=t),y.current=null;return}let a=N.indexOf(e.entryKey);if(a<0||e.attempts>=1){y.current=null;return}e.attempts+=1,W.scrollToIndex(a,{align:`start`}),x()},[t,N,_,W,b]);let K=W.getVirtualItems(),ae=K.map(e=>e.index),[oe,se]=Q.useState(()=>vF(N,{seedCount:AL(u),restore:gF(L)})),ce=yF(oe,N);ce!==oe&&se(ce);let le=Q.useRef(ce);le.current=ce;let ue=Q.useRef(null);W.scrollDirection&&(ue.current=W.scrollDirection);let de=W.range?.startIndex??K[0]?.index??Math.max(0,A.length-1),fe=W.range?.endIndex??K[K.length-1]?.index??Math.max(0,A.length-1),pe=W.isScrolling,me=Math.max(0,fe-de+1),he=xF({entryKeys:N,mountedIndexes:ae,visibleStartIndex:de,visibleEndIndex:fe,scrollDirection:ue.current,preloadEntries:AL(u,me),hydratedKeys:ce,allowVisibleRelease:!pe,preloadReleaseLimit:pe?jL(u):iL,visibleReleaseLimit:pe?0:ML(u)}),ge=he.join(`\0`),_e=Q.useRef(he);_e.current=he,Q.useEffect(()=>{if(!(!_||!ge))return Jl(()=>{Q.startTransition(()=>{se(e=>{let t=null;for(let n of _e.current)e.has(n)||(t??=new Set(e),t.add(n));return t??e})})})},[_,ge]),Q.useEffect(()=>{se(e=>SF(e,N))},[N]),Q.useEffect(()=>{if(!_)return;let e=W.itemSizeCache,t=NL(u);if(e.size>=t){let t=0;for(let n of e.values())t+=n;V.current=Math.min(hL,Math.max(mL,Math.round(t/e.size)))}}),Q.useEffect(()=>{if(_)return i?.(W),()=>{IL(L,M.current.map(e=>e.key),W),_F(L,le.current),i?.(null)}},[_,W,L]);let ve=oF((e,t=!0)=>(0,$.jsx)(fF,{enabled:t,children:(0,$.jsx)(tR,{entry:e,onMessageContentChange:o,getAnimationHandlers:s,scrollToBottom:c,stickyUserHeader:l,sessionIsWorking:!1,activityRenderMode:u,turnUiStates:d,onToggleTurnGroup:f,chatRenderMode:p,shouldAnimateUserMessage:m,onUserAnimationConsumed:h,reviewTransferDirection:g},e.key)}));if(t===`none`)return(0,$.jsx)(`div`,{ref:n,className:`relative w-full`,children:A.map(e=>(0,$.jsx)(`div`,{"data-turn-entry":e.key,className:`oc-chat-message-layout-boundary`,children:ve(e)},e.key))});if(t===`tanstack`){let e=OL(K[0]?.start??0,K[K.length-1]?.end??0,W.getTotalSize());return(0,$.jsx)(`div`,{ref:z,className:`relative w-full`,style:{minHeight:e.minHeight},children:(0,$.jsx)(`div`,{style:{paddingTop:e.paddingTop,paddingBottom:e.paddingBottom},children:K.map(e=>{let t=A[e.index];return t?(0,$.jsx)(`div`,{"data-index":e.index,ref:W.measureElement,"data-turn-entry":t.key,className:`oc-chat-message-layout-boundary`,children:ve(t,ce.has(t.key))},t.key):null})})})}return null});nR.displayName=`StaticHistoryList`;var rR=Q.memo(e=>{let t=(0,pd.c)(2),n;return t[0]===e?n=t[1]:(n=(0,$.jsx)(`div`,{className:`oc-chat-message-layout-boundary`,children:(0,$.jsx)(tR,{...e})}),t[0]=e,t[1]=n),n});rR.displayName=`TailEntry`;var iR=e=>{let t=(0,pd.c)(43),{entries:n,directory:r,sessionId:i,onMessageContentChange:a,getAnimationHandlers:o,scrollToBottom:s,stickyUserHeader:c,sessionIsWorking:l,activityRenderMode:u,turnUiStates:d,onToggleTurnGroup:f,chatRenderMode:p,showTurnChangedFiles:m,shouldAnimateUserMessage:h,onUserAnimationConsumed:g,activeStreamingMessageId:_,activeStreamingPhase:v,reviewTransferDirection:y}=e,b=n.length-1,x=mi(_??``,r,i??void 0),S;bb0:{let e=n[b];if(!e){S=void 0;break bb0}let r=p===`sorted`,i;t[0]!==_||t[1]!==x||t[2]!==e||t[3]!==m||t[4]!==r?(i=aF(e,{activeStreamingMessageId:_,liveParts:x,showTextJustificationActivity:r,showTurnChangedFiles:m}),t[0]=_,t[1]=x,t[2]=e,t[3]=m,t[4]=r,t[5]=i):i=t[5],S=i}let C=S,w;if(t[6]!==_||t[7]!==v||t[8]!==u||t[9]!==p||t[10]!==n||t[11]!==o||t[12]!==C||t[13]!==b||t[14]!==a||t[15]!==f||t[16]!==g||t[17]!==y||t[18]!==s||t[19]!==l||t[20]!==h||t[21]!==c||t[22]!==d){let e;t[24]!==_||t[25]!==v||t[26]!==u||t[27]!==p||t[28]!==o||t[29]!==C||t[30]!==b||t[31]!==a||t[32]!==f||t[33]!==g||t[34]!==y||t[35]!==s||t[36]!==l||t[37]!==h||t[38]!==c||t[39]!==d?(e=(e,t)=>{let n=t===b;return(0,$.jsx)(rR,{entry:n?C??e:e,onMessageContentChange:a,getAnimationHandlers:o,scrollToBottom:s,stickyUserHeader:c,sessionIsWorking:n?l:!1,activityRenderMode:u,turnUiStates:d,onToggleTurnGroup:f,chatRenderMode:p,shouldAnimateUserMessage:h,onUserAnimationConsumed:g,activeStreamingMessageId:n?_:null,activeStreamingPhase:n?v:null,reviewTransferDirection:y},e.key)},t[24]=_,t[25]=v,t[26]=u,t[27]=p,t[28]=o,t[29]=C,t[30]=b,t[31]=a,t[32]=f,t[33]=g,t[34]=y,t[35]=s,t[36]=l,t[37]=h,t[38]=c,t[39]=d,t[40]=e):e=t[40],w=n.map(e),t[6]=_,t[7]=v,t[8]=u,t[9]=p,t[10]=n,t[11]=o,t[12]=C,t[13]=b,t[14]=a,t[15]=f,t[16]=g,t[17]=y,t[18]=s,t[19]=l,t[20]=h,t[21]=c,t[22]=d,t[23]=w}else w=t[23];let T;return t[41]===w?T=t[42]:(T=(0,$.jsx)($.Fragment,{children:w}),t[41]=w,t[42]=T),T};iR.displayName=`StreamingTailContent`;var aR=e=>{let t=(0,pd.c)(74),{historyEntries:n,tailEntries:r,timelineCacheKey:i,directory:a,sessionId:o,scrollRef:s,registerList:c,onHistoryContentChange:l,onTailContentChange:u,getAnimationHandlers:d,scrollToBottom:f,stickyUserHeader:p,sessionIsWorking:m,activityRenderMode:h,turnUiStates:g,onToggleTurnGroup:_,chatRenderMode:v,showTurnChangedFiles:y,shouldAnimateUserMessage:b,onUserAnimationConsumed:x,activeStreamingMessageId:S,activeStreamingPhase:C,reviewTransferDirection:w,header:T,footer:E,scrollClassName:D,scrollStyle:O,scrollDataset:k,onScroll:A,followEnabled:j,historyAnchorToken:M,pinRevealGeneration:N,initialPinRevealComplete:P,onIsAtEndChange:F,anchoredUserMessageId:I,onAnchoredTurnParkReleased:L}=e,R=j===void 0||j,z=N===void 0?0:N,B=P!==void 0&&P,V=I===void 0?null:I,H=q(cR),ee=n.length,U=r.length>0?r[r.length-1]:void 0,te=U?.key??null,W=mi(S??``,a,o??void 0),ne;bb0:{if(!U){ne=r;break bb0}let e=v===`sorted`,n;t[0]!==S||t[1]!==W||t[2]!==U||t[3]!==y||t[4]!==e?(n=aF(U,{activeStreamingMessageId:S,liveParts:W,showTextJustificationActivity:e,showTurnChangedFiles:y}),t[0]=S,t[1]=W,t[2]=U,t[3]=y,t[4]=e,t[5]=n):n=t[5];let i=n;if(i===U){ne=r;break bb0}let a;t[6]!==i||t[7]!==r?(a=r.slice(),a[a.length-1]=i,t[6]=i,t[7]=r,t[8]=a):a=t[8],ne=a}let G=ne,re;t[9]!==n||t[10]!==G?(re=G.length>0?[...n,...G]:n,t[9]=n,t[10]=G,t[11]=re):re=t[11];let ie=re,K;t[12]!==ie||t[13]!==V?(K=gI(ie,V,XL,{anchorOffset:16}),t[12]=ie,t[13]=V,t[14]=K):K=t[14];let ae=K,oe;t[15]===h?oe=t[16]:(oe={resolvePreloadEntries:e=>AL(h,e),resolvePreloadReleaseWhileScrolling:()=>jL(h),resolveVisibleReleaseLimit:()=>ML(h)},t[15]=h,t[16]=oe);let se=oe,ce;t[17]!==S||t[18]!==C||t[19]!==h||t[20]!==v||t[21]!==ee||t[22]!==te||t[23]!==w||t[24]!==m||t[25]!==y||t[26]!==p||t[27]!==g?(ce={historyCount:ee,newestTailKey:te,sessionIsWorking:m,activityRenderMode:h,turnUiStates:g,chatRenderMode:v,showTurnChangedFiles:y,stickyUserHeader:p,activeStreamingMessageId:S,activeStreamingPhase:C,reviewTransferDirection:w},t[17]=S,t[18]=C,t[19]=h,t[20]=v,t[21]=ee,t[22]=te,t[23]=w,t[24]=m,t[25]=y,t[26]=p,t[27]=g,t[28]=ce):ce=t[28];let le=ce,ue;t[29]!==S||t[30]!==C||t[31]!==h||t[32]!==v||t[33]!==d||t[34]!==ee||t[35]!==te||t[36]!==l||t[37]!==u||t[38]!==_||t[39]!==x||t[40]!==w||t[41]!==f||t[42]!==m||t[43]!==b||t[44]!==p||t[45]!==g?(ue=(e,t,n)=>{let r=t>=ee,i=te!==null&&e.key===te;return(0,$.jsx)($l,{disabled:!r,children:(0,$.jsx)(fF,{enabled:n,children:(0,$.jsx)(tR,{entry:e,onMessageContentChange:r?u:l,getAnimationHandlers:d,scrollToBottom:f,stickyUserHeader:p,sessionIsWorking:i?m:!1,activityRenderMode:h,turnUiStates:g,onToggleTurnGroup:_,chatRenderMode:v,shouldAnimateUserMessage:b,onUserAnimationConsumed:x,activeStreamingMessageId:i?S:null,activeStreamingPhase:i?C:null,reviewTransferDirection:w,showLiveStatusRow:i})})})},t[29]=S,t[30]=C,t[31]=h,t[32]=v,t[33]=d,t[34]=ee,t[35]=te,t[36]=l,t[37]=u,t[38]=_,t[39]=x,t[40]=w,t[41]=f,t[42]=m,t[43]=b,t[44]=p,t[45]=g,t[46]=ue):ue=t[46];let de=oF(ue),fe;t[47]===h?fe=t[48]:(fe=TL(h),t[47]=h,t[48]=fe);let pe=H&&p,me;return t[49]!==ie||t[50]!==ae||t[51]!==R||t[52]!==E||t[53]!==T||t[54]!==M||t[55]!==se||t[56]!==B||t[57]!==H||t[58]!==L||t[59]!==F||t[60]!==A||t[61]!==z||t[62]!==c||t[63]!==de||t[64]!==le||t[65]!==D||t[66]!==k||t[67]!==s||t[68]!==O||t[69]!==m||t[70]!==fe||t[71]!==pe||t[72]!==i?(me=(0,$.jsx)(dF,{enabled:!0,children:(0,$.jsx)(PI,{entries:ie,timelineCacheKey:i,estimatedItemSize:fe,hydrationTuning:se,renderEntry:de,rowInvalidationKey:le,scrollElementRef:s,registerList:c,followEnabled:R,historyAnchorToken:M,pinRevealGeneration:z,initialPinRevealComplete:B,anchoredEndSpace:ae,onAnchoredTurnParkReleased:L,sessionIsWorking:m,header:T,footer:E,className:D,style:O,scrollElementDataset:k,hideTopScrollShadow:pe,hideBottomScrollShadow:H,onScroll:A,onIsAtEndChange:F})}),t[49]=ie,t[50]=ae,t[51]=R,t[52]=E,t[53]=T,t[54]=M,t[55]=se,t[56]=B,t[57]=H,t[58]=L,t[59]=F,t[60]=A,t[61]=z,t[62]=c,t[63]=de,t[64]=le,t[65]=D,t[66]=k,t[67]=s,t[68]=O,t[69]=m,t[70]=fe,t[71]=pe,t[72]=i,t[73]=me):me=t[73],me};aR.displayName=`LegendTimelineHost`;var oR=Q.forwardRef(({sessionKey:e,virtualizerKey:t,messages:n,sessionIsWorking:r=!1,activeStreamingMessageId:i=null,activeStreamingPhase:a=null,retryOverlay:o=null,onMessageContentChange:s,getAnimationHandlers:c,scrollToBottom:l,scrollRef:u,directory:d,headerSlot:f,footerSlot:p,liveStatusSlot:m,timelineScrollClassName:h,timelineScrollStyle:g,timelineScrollDataset:_,timelineOnScroll:v,timelineFollowEnabled:y,timelineHistoryAnchorToken:b,timelineOnIsAtEndChange:x,enableSendPark:S=!0,initialPinRevealComplete:C=!1},w)=>{pt(`ui.message_list.render`);let{sessionKey:T,virtualizerKey:E}=wL(e,t),D=q(e=>e.stickyUserHeader),O=q(e=>e.chatRenderMode),k=q(e=>e.activityRenderMode),A=q(e=>e.showTurnChangedFiles),j=Ui(e=>e.reviewTransferBySessionId.get(T)??null),[M,N]=Q.useState(()=>new Map),P=Q.useRef({sessionKey:void 0,previousOrder:[],animatedIds:new Set}),[F,I]=Q.useState(null),L=Q.useRef(null);L.current=F;let R=J(t=>{oo(e),L.current===t&&I(null)});Gt(()=>{if(S)return()=>{queueMicrotask(()=>{oo(e)})}},[S,e]);let z=J(c),B=J(()=>{l?.()}),V=J((e,t)=>{N(n=>{let r=new Map(n),i=n.get(e)?.isExpanded??t;return r.set(e,{isExpanded:BM(i)}),r})}),H=Q.useMemo(()=>Ze(`ui.message_list.base_display_ms`,()=>{let e=new Set,t=new Map,r=[];for(let e of n){let n=e.info?.id;typeof n==`string`&&t.set(n,e)}for(let i=0;i<n.length;i+=1){let a=n[i],o=a.info?.id;if(typeof o==`string`){if(e.has(o))continue;e.add(o)}r.push(yN(typeof o==`string`?t.get(o)??a:a))}let i=[],a=new Set;for(let e=0;e<r.length;e+=1){let t=r[e],n=RL(t,a);hN(t)&&a.add(t.info.id);let o=i.length>0?i[i.length-1]:void 0;if(zL(o)){let e=qL(n);if(e.hide){i[i.length-1]=JL(o,e.taskSessionId);continue}}if(LI(o)){let e=RI(n,BL(o));if(e.hide){i[i.length-1]=YL(o,e.details);continue}}i.push(n)}return i}),[n]),ee=Q.useRef(null),U=Q.useRef(null),te=Q.useCallback(()=>{let e=U.current;e&&(U.current=null,e.cancel())},[]);Q.useEffect(()=>()=>{te()},[te]);let W=J(()=>u?.current?u.current:typeof document>`u`?null:document.querySelector(`[data-scrollbar="chat"]`)),ne=Q.useMemo(()=>Ze(`ui.message_list.retry_overlay_ms`,()=>rF(H,{sessionId:o?.sessionId??null,message:o?.message??`Quota limit reached. Retrying automatically.`,confirmedAt:o?.confirmedAt,fallbackTimestamp:o?.fallbackTimestamp??0})),[H,o]),G=r||!!i,re=Q.useRef(G),ie=Q.useRef(T);ie.current!==T&&(ie.current=T,re.current=!1),G&&(re.current=!0);let{projection:K,staticTurns:ae,streamingTurns:oe}=tF(ne,{sessionKey:T,showTextJustificationActivity:O===`sorted`,showTurnChangedFiles:A,hasLiveTail:G||re.current,liveTailActive:G}),se=K.ungroupedMessageIds.size>0,ce=se?ne:qI,le=se?K.ungroupedMessageIds:JI,ue=Q.useMemo(()=>Ze(`ui.message_list.render_entries_ms`,()=>{let e=ae.map(e=>({kind:`turn`,key:`turn:${e.turnId}`,turn:e,isLastTurn:e.turnId===K.lastTurnId}));if(le.size===0)return e;let t=new Map;e.forEach(e=>{t.set(e.turn.userMessage.info.id,e)});let n=[];return ce.forEach((e,r)=>{let i=t.get(e.info.id);if(i){n.push(i);return}le.has(e.info.id)&&n.push({kind:`ungrouped`,key:`msg:${e.info.id}`,message:e,previousMessage:r>0?ce[r-1]:void 0,nextMessage:r<ce.length-1?ce[r+1]:void 0})}),n}),[K.lastTurnId,ce,le,ae]),de=Q.useMemo(()=>{if(oe.length>0)return oe.map(e=>({kind:`turn`,key:`turn:${e.turnId}`,turn:e,isLastTurn:e.turnId===K.lastTurnId}));if(K.ungroupedMessageIds.size===0)return YI;let e=ne[ne.length-1];return!e||!K.ungroupedMessageIds.has(e.info.id)?YI:[{kind:`ungrouped`,key:`msg:${e.info.id}`,message:e,previousMessage:ne.length>1?ne[ne.length-2]:void 0,nextMessage:void 0}]},[ne,K.lastTurnId,K.ungroupedMessageIds,oe]),fe=de.length>0;fe&&G&&pt(`ui.message_list.render.streaming`);let pe=ue,me=pe.length>=KI,he=Q.useRef(me);PL(he,me);let ge=me?`tanstack`:`none`,_e=hl(e=>e.legendTimelineEnabled),ve=Q.useRef(null),ye=J(e=>{ve.current=e}),be=Q.useRef(null),xe=J(e=>{be.current=e}),Se=Q.useMemo(()=>de.length>0?[...pe,...de]:pe,[pe,de]),[Ce,we]=Q.useState(0),[Te,Ee]=Q.useState(null),De=EL(E,k),Oe=jF(void 0,LF({scopeKey:De,generation:Ce,root:Te,relevantKeys:Q.useMemo(()=>EF({entryKeys:Se.map(e=>e.key),seedCount:AL(k)}),[De,Ce,Se.length,Se[Se.length-1]?.key,k]),enabled:!_e&&Se.length>0,initiallyRevealed:C})),ke=J(e=>{s(e)}),Ae=J(e=>{s(e)}),je=Q.useMemo(()=>n.filter(e=>LL(e)===`user`).map(e=>e.info.id),[n]),Me=P.current,Ne=Me.sessionKey!==e,Pe=Me.previousOrder;Ne&&(S&&Me.sessionKey!==void 0&&oo(Me.sessionKey),Me.sessionKey=e,Me.previousOrder=je,Me.animatedIds=new Set);let Fe=S?pn({sessionId:e,sessionChanged:Ne,previousUserOrder:Pe,currentUserOrder:je,animatedIds:Me.animatedIds}):null;Me.previousOrder=je;let Ie=S?_I({sessionChanged:Ne,previousUserOrder:Pe,currentUserOrder:je,currentAnchorId:F,consumedSendMessageId:Fe}):null;S&&Ie!==F&&I(Ie),S&&(L.current=Ie);let Le=J(e=>LL(e)===`user`&&P.current.animatedIds.has(e.info.id)),Re=J(e=>{P.current.animatedIds.delete(e)}),ze=Q.useMemo(()=>{let e=new Map;return Se.forEach((t,n)=>{if(t.kind===`ungrouped`){e.set(t.message.info.id,n);return}e.set(t.turn.userMessage.info.id,n),t.turn.assistantMessages.forEach(t=>{e.set(t.info.id,n)})}),e},[Se]),Be=Q.useMemo(()=>{let e=new Map;return Se.forEach((t,n)=>{t.kind===`turn`&&e.set(t.turn.turnId,n)}),e},[Se]),Ve=J(e=>{let t=W();return t?t.querySelector(`[data-message-id="${e}"]`):null}),He=J((e,t=`auto`)=>{if(e<0||e>=pe.length)return!1;if(_e){let n=ve.current;return n?(n.scrollToIndex({index:e,animated:t===`smooth`,viewOffset:0}),!0):!1}if(!me)return!1;let n=be.current;return n?(n.scrollToIndex(e,{align:`start`,behavior:t===`smooth`?`smooth`:`auto`}),!0):!1}),Ue=J((e,t=`auto`)=>{let n=W();if(!n)return!1;let r=Ve(e);if(!r)return!1;let i=n.getBoundingClientRect(),a=r.getBoundingClientRect().top-i.top+n.scrollTop-50;return n.scrollTo({top:a,behavior:t}),!0});return Q.useEffect(()=>{if(!w)return;let e={scrollToTurnId:(e,t)=>{let n=t?.behavior??`auto`,r=Be.get(e);if(r===void 0)return!1;let i=W();if(!i)return!1;let a=i.querySelector(`[data-turn-id="${e}"]`);return a?(a.scrollIntoView({behavior:n,block:`start`}),!0):fe&&r>=pe.length?!1:He(r,n)},scrollToMessageId:(e,t)=>{let n=t?.behavior??`auto`,r=ze.get(e);return r===void 0?!1:Ue(e,n)||(fe&&r>=pe.length?!1:He(r,n))},holdViewportAnchor:e=>{let t=W();if(!t||typeof window>`u`)return;te();let n=0,r=0,i=!1,a=null,o=()=>{t.removeEventListener(`touchstart`,c),t.removeEventListener(`wheel`,c),t.removeEventListener(`keydown`,c),t.removeEventListener(`pointerdown`,c)},s=()=>{i||(i=!0,a!==null&&(window.cancelAnimationFrame(a),a=null),o(),U.current?.cancel===s&&(U.current=null))},c=()=>{s()};U.current={cancel:s},t.addEventListener(`touchstart`,c,{passive:!0}),t.addEventListener(`wheel`,c,{passive:!0}),t.addEventListener(`keydown`,c),t.addEventListener(`pointerdown`,c,{passive:!0});let l=()=>{if(i)return;let o=Ve(e.messageId);if(o){let n=o.getBoundingClientRect().top-t.getBoundingClientRect().top-e.offsetTop;Math.abs(n)>.5?(t.scrollTop+=n,r=0):r+=1}if(n+=1,r>=uL||n>=dL){s();return}a=window.requestAnimationFrame(l)};a=window.requestAnimationFrame(l)},cancelViewportAnchorHold:te,isHistoryVirtualized:()=>_e?!0:he.current,captureViewportAnchor:()=>{let e=W();if(!e)return null;let t=e.getBoundingClientRect(),n=Array.from(e.querySelectorAll(`[data-message-id]`)),r=n.find(n=>n.getBoundingClientRect().bottom<=t.top+1?!1:typeof window>`u`||!HL(n,e,t.top))??n.find(e=>e.getBoundingClientRect().bottom>t.top+1);if(!r)return null;let i=r.dataset.messageId;return i?{messageId:i,offsetTop:r.getBoundingClientRect().top-t.top}:null},restoreViewportAnchor:e=>{let t=W();if(!t||!ze.has(e.messageId))return!1;let n=()=>{let n=Ve(e.messageId);if(!n)return!1;let r=t.getBoundingClientRect(),i=n.getBoundingClientRect().top-r.top-e.offsetTop;return i!==0&&(t.scrollTop+=i),!0};if(!n()){let t=ze.get(e.messageId);if(typeof t==`number`&&t<pe.length)return He(t,`auto`)}return n()},scrollToBottom:()=>{if(we(e=>e+1),_e){let e=tI(W());if(e!==null){ve.current?.scrollToOffset({offset:e,animated:!1});return}ve.current?.scrollToEnd({animated:!1});return}if(me&&pe.length>0&&be.current){be.current.scrollToEnd();return}let e=W();e&&(e.scrollTop=e.scrollHeight)}};if(typeof w==`function`)return w(e),()=>{w(null)};let t=w;return t.current=e,()=>{t.current=null}},[te,pe.length,_e,ze,me,fe,Be,w]),_e?(0,$.jsx)(aR,{historyEntries:pe,tailEntries:de,timelineCacheKey:EL(E,k),directory:d,sessionId:T,scrollRef:u,registerList:ye,onHistoryContentChange:ke,onTailContentChange:Ae,getAnimationHandlers:z,scrollToBottom:B,stickyUserHeader:D,sessionIsWorking:r,activityRenderMode:k,turnUiStates:M,onToggleTurnGroup:V,chatRenderMode:O,showTurnChangedFiles:A,shouldAnimateUserMessage:Le,onUserAnimationConsumed:Re,activeStreamingMessageId:i,activeStreamingPhase:a,reviewTransferDirection:j,header:f,footer:p,scrollClassName:h,scrollStyle:g,scrollDataset:_,onScroll:v,followEnabled:y,historyAnchorToken:b,pinRevealGeneration:Ce,initialPinRevealComplete:C,onIsAtEndChange:x,anchoredUserMessageId:Ie,onAnchoredTurnParkReleased:R},E):(0,$.jsx)(`div`,{children:(0,$.jsx)($l,{disabled:!1,children:(0,$.jsxs)(`div`,{ref:Ee,className:`relative w-full`,style:Oe,children:[(0,$.jsx)($l,{disabled:me,children:(0,$.jsx)(dF,{enabled:!0,children:(0,$.jsx)(nR,{entries:pe,engine:ge,contentRef:ee,scrollRef:u,registerTanstackVirtualizer:xe,virtualizerKey:E,onMessageContentChange:ke,getAnimationHandlers:z,scrollToBottom:B,stickyUserHeader:D,activityRenderMode:k,turnUiStates:M,onToggleTurnGroup:V,chatRenderMode:O,shouldAnimateUserMessage:Le,onUserAnimationConsumed:Re,reviewTransferDirection:j},E)})}),(0,$.jsx)(iR,{entries:de,directory:d,sessionId:T,onMessageContentChange:Ae,getAnimationHandlers:z,scrollToBottom:B,stickyUserHeader:D,sessionIsWorking:r,activityRenderMode:k,turnUiStates:M,onToggleTurnGroup:V,chatRenderMode:O,showTurnChangedFiles:A,shouldAnimateUserMessage:Le,onUserAnimationConsumed:Re,activeStreamingMessageId:i,activeStreamingPhase:a,reviewTransferDirection:j}),m]})})})});oR.displayName=`MessageList`;var sR=Q.memo(oR);function cR(e){return e.isMobile}var lR=e=>{let t=(0,pd.c)(3),{content:n,html:r}=e,i;return t[0]!==n||t[1]!==r?(i=r===void 0?(0,$.jsx)(`span`,{className:`whitespace-pre-wrap break-all`,children:n}):(0,$.jsx)(`span`,{className:`whitespace-pre-wrap break-all`,dangerouslySetInnerHTML:{__html:r}}),t[0]=n,t[1]=r,t[2]=i):i=t[2],i},uR=({diff:e,filePath:t})=>{let{currentTheme:n}=Ws(),r=Q.useMemo(()=>$s(n),[n]),i=Q.useMemo(()=>yu(e),[e]),a=zl(t||i[0]?.file)||`text`,o=Q.useMemo(()=>i.flatMap(e=>e.lines.map(e=>e.content)).join(`
|
|
6581
6581
|
`),[i]),s=ku(o,a),c=0;return(0,$.jsx)(`div`,{className:`typography-code px-1 pb-1 pt-0 space-y-0`,style:r,children:i.map((e,n)=>(0,$.jsxs)(`div`,{className:`-mx-1 px-1 border-b border-border/20 last:border-b-0`,children:[(0,$.jsx)(`div`,{className:`bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1`,children:`${e.file||t?.split(`/`).pop()||`file`} (line ${e.oldStart})`}),(0,$.jsx)(`div`,{children:e.lines.map((e,t)=>{let n=s?.[c];return c+=1,(0,$.jsxs)(`div`,{className:Y(`typography-code font-mono px-2 py-0.5 flex -mx-2`,e.type===`context`&&`bg-transparent`,e.type===`removed`&&`bg-transparent`,e.type===`added`&&`bg-transparent`),style:e.type===`removed`?{backgroundColor:`var(--tools-edit-removed-bg)`}:e.type===`added`?{backgroundColor:`var(--tools-edit-added-bg)`}:{},children:[(0,$.jsx)(`span`,{className:`w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5`,style:{color:`var(--tools-edit-line-number)`,borderColor:`var(--tools-border)`},children:e.lineNumber||``}),(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsx)(lR,{content:e.content,html:n})})]},t)})})]},n))})},dR=e=>{let t=(0,pd.c)(21),{content:n,filePath:r}=e,{currentTheme:i}=Ws(),a;t[0]===i?a=t[1]:(a=$s(i),t[0]=i,t[1]=a);let o=a,s;t[2]===n?s=t[3]:(s=n.split(`
|
|
6582
6582
|
`),t[2]=n,t[3]=s);let c=s,l;t[4]===r?l=t[5]:(l=zl(r??``)||`text`,t[4]=r,t[5]=l);let u=l,d;t[6]===r?d=t[7]:(d=r?.split(`/`).pop()||`New file`,t[6]=r,t[7]=d);let f=d,p=Math.max(c.length,1),m=p===1?`line 1`:`lines 1-${p}`,h=ku(n,u),g=o,_=`${f} (${m})`,v;t[8]===_?v=t[9]:(v=(0,$.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:_}),t[8]=_,t[9]=v);let y;if(t[10]!==h||t[11]!==c){let e;t[13]===h?e=t[14]:(e=(e,t)=>(0,$.jsxs)(`div`,{className:`typography-code font-mono px-2 py-0.5 flex -mx-1`,children:[(0,$.jsx)(`span`,{className:`w-10 flex-shrink-0 text-right pr-3 select-none border-r mr-3 -my-0.5 py-0.5`,style:{color:`var(--tools-edit-line-number)`,borderColor:`var(--tools-border)`},children:t+1}),(0,$.jsx)(`div`,{className:`flex-1 min-w-0`,children:(0,$.jsx)(lR,{content:e||` `,html:h?.[t]})})]},t),t[13]=h,t[14]=e),y=c.map(e),t[10]=h,t[11]=c,t[12]=y}else y=t[12];let b;t[15]===y?b=t[16]:(b=(0,$.jsx)(`div`,{className:`space-y-0`,children:y}),t[15]=y,t[16]=b);let x;return t[17]!==g||t[18]!==v||t[19]!==b?(x=(0,$.jsxs)(`div`,{className:`w-full min-w-0`,style:g,children:[v,b]}),t[17]=g,t[18]=v,t[19]=b,t[20]=x):x=t[20],x},fR=new Set([`id`,`identifier`,`title`,`name`]),pR=e=>typeof e==`object`&&!!e&&!Array.isArray(e),mR=e=>e.replace(/([A-Z])/g,` $1`).replace(/[_-]/g,` `).replace(/^./,e=>e.toUpperCase()),hR=e=>{let t=typeof e.id==`string`?e.id:typeof e.identifier==`string`?e.identifier:``,n=typeof e.title==`string`?e.title:typeof e.name==`string`?e.name:``;return t&&n?`${t} · ${n}`:n||t||null},gR=e=>{try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}},_R=Q.memo(e=>{let t=(0,pd.c)(54),{value:n,label:r,depth:i}=e;if(Array.isArray(n)){let e;t[0]!==r||t[1]!==n.length?(e=r?`${mR(r)} (${n.length})`:`(${n.length})`,t[0]=r,t[1]=n.length,t[2]=e):e=t[2];let a=e,o=i<2,s;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(s=(0,$.jsx)(Z,{name:`arrow-right-s`,className:`h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90`}),t[3]=s):s=t[3];let c;t[4]===a?c=t[5]:(c=(0,$.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center gap-1.5 py-1.5 typography-meta text-[var(--surface-foreground)] hover:text-[var(--surface-mutedForeground)]`,children:[s,(0,$.jsx)(`span`,{className:`min-w-0 truncate font-medium`,children:a})]}),t[4]=a,t[5]=c);let l;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(l=(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)] opacity-40`}),t[6]=l):l=t[6];let u;if(t[7]!==i||t[8]!==n){let e;t[10]===i?e=t[11]:(e=(e,t)=>(0,$.jsx)(_R,{value:e,depth:i+1},t),t[10]=i,t[11]=e),u=n.map(e),t[7]=i,t[8]=n,t[9]=u}else u=t[9];let d;t[12]===u?d=t[13]:(d=(0,$.jsxs)(`div`,{className:`relative ml-1 pl-3 pb-1`,children:[l,(0,$.jsx)(`div`,{className:`space-y-1`,children:u})]}),t[12]=u,t[13]=d);let f;return t[14]!==o||t[15]!==c||t[16]!==d?(f=(0,$.jsxs)(`details`,{open:o,className:`group/json-summary`,children:[c,d]}),t[14]=o,t[15]=c,t[16]=d,t[17]=f):f=t[17],f}if(pR(n)){let e;t[18]===n?e=t[19]:(e=hR(n),t[18]=n,t[19]=e);let a=e,o;t[20]===n?o=t[21]:(o=Object.entries(n).filter(yR),t[20]=n,t[21]=o);let s=o,c;t[22]!==a||t[23]!==r?(c=r?`${mR(r)}${a?` · ${a}`:``}`:a,t[22]=a,t[23]=r,t[24]=c):c=t[24];let l=c,u;t[25]!==i||t[26]!==s?(u=(0,$.jsx)(`div`,{className:`space-y-1`,children:s.map(e=>{let[t,n]=e;return(0,$.jsx)(_R,{label:t,value:n,depth:i+1},t)})}),t[25]=i,t[26]=s,t[27]=u):u=t[27];let d=u;if(!r&&i===0){let e;t[28]===a?e=t[29]:(e=a?(0,$.jsx)(`div`,{className:`typography-meta font-medium text-[var(--surface-foreground)]`,children:a}):null,t[28]=a,t[29]=e);let n;return t[30]!==d||t[31]!==e?(n=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[e,d]}),t[30]=d,t[31]=e,t[32]=n):n=t[32],n}let f=i<2,p;t[33]===Symbol.for(`react.memo_cache_sentinel`)?(p=(0,$.jsx)(Z,{name:`arrow-right-s`,className:`h-3.5 w-3.5 shrink-0 transition-transform group-open/json-summary:rotate-90`}),t[33]=p):p=t[33];let m;t[34]!==r||t[35]!==l?(m=l??(r?mR(r):`{}`),t[34]=r,t[35]=l,t[36]=m):m=t[36];let h;t[37]===m?h=t[38]:(h=(0,$.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center gap-1.5 py-1.5 typography-meta text-[var(--surface-foreground)] hover:text-[var(--surface-mutedForeground)]`,children:[p,(0,$.jsx)(`span`,{className:`min-w-0 truncate font-medium`,children:m})]}),t[37]=m,t[38]=h);let g;t[39]===Symbol.for(`react.memo_cache_sentinel`)?(g=(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`pointer-events-none absolute bottom-1 left-0 top-0 w-px bg-[var(--tools-border)] opacity-40`}),t[39]=g):g=t[39];let _;t[40]===d?_=t[41]:(_=(0,$.jsxs)(`div`,{className:`relative ml-1 pl-3 pb-1`,children:[g,d]}),t[40]=d,t[41]=_);let v;return t[42]!==_||t[43]!==f||t[44]!==h?(v=(0,$.jsxs)(`details`,{open:f,className:`group/json-summary`,children:[h,_]}),t[42]=_,t[43]=f,t[44]=h,t[45]=v):v=t[45],v}let a=n===null?`null`:typeof n==`boolean`?n?`true`:`false`:String(n),o;t[46]!==a||t[47]!==n?(o=typeof n==`string`&&gR(n)?(0,$.jsx)(`a`,{href:n,target:`_blank`,rel:`noopener noreferrer`,className:`truncate text-[var(--status-info)] underline underline-offset-2 hover:opacity-80`,title:n,children:n}):(0,$.jsx)(`span`,{className:Y(`min-w-0 break-words`,n===null?`text-[var(--surface-mutedForeground)]`:`text-[var(--surface-foreground)]`),children:a}),t[46]=a,t[47]=n,t[48]=o):o=t[48];let s=o,c;t[49]===r?c=t[50]:(c=r?(0,$.jsx)(`span`,{className:`truncate text-[var(--surface-mutedForeground)]`,title:r,children:mR(r)}):(0,$.jsx)(`span`,{}),t[49]=r,t[50]=c);let l;return t[51]!==s||t[52]!==c?(l=(0,$.jsxs)(`div`,{className:`grid grid-cols-[minmax(6rem,auto)_minmax(0,1fr)] gap-x-2 py-1 typography-meta`,children:[c,s]}),t[51]=s,t[52]=c,t[53]=l):l=t[53],l});_R.displayName=`JsonSummaryValue`;var vR=Q.memo(e=>{let t=(0,pd.c)(2),{data:n}=e,r;return t[0]===n?r=t[1]:(r=(0,$.jsx)(`div`,{className:`space-y-1`,children:(0,$.jsx)(_R,{value:n,depth:0})}),t[0]=n,t[1]=r),r});vR.displayName=`JsonSummaryView`;function yR(e){let[t]=e;return!fR.has(t)}var bR={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`},xR={style:{whiteSpace:`pre-wrap`,wordBreak:`break-word`,overflowWrap:`break-word`}},SR=e=>{let t=`h-3 w-3`,n=e.toLowerCase();return n===`edit`||n===`multiedit`||n===`str_replace`||n===`str_replace_based_edit_tool`?(0,$.jsx)(Z,{name:`pencil-ai`,className:t}):n===`write`||n===`create`||n===`file_write`?(0,$.jsx)(Z,{name:`file-edit`,className:t}):n===`bash`||n===`shell`||n===`cmd`||n===`terminal`||n===`shell_command`?(0,$.jsx)(Z,{name:`terminal-box`,className:t}):n===`webfetch`||n===`fetch`||n===`curl`||n===`wget`?(0,$.jsx)(Z,{name:`global`,className:t}):(0,$.jsx)(Z,{name:`tools`,className:t})},CR=e=>{let t=e.toLowerCase();return t===`edit`||t===`multiedit`||t===`str_replace`||t===`str_replace_based_edit_tool`?`edit`:t===`write`||t===`create`||t===`file_write`?`write`:t===`bash`||t===`shell`||t===`cmd`||t===`terminal`||t===`shell_command`?`bash`:t===`webfetch`||t===`fetch`||t===`curl`||t===`wget`?`webfetch`:e},wR=e=>e===`filepath`||e===`file_path`?`filePath`:e===`parentDir`||e===`parent_dir`?`parentDirectory`:e,TR=e=>{let t=(0,pd.c)(2),{data:n}=e,r;return t[0]===n?r=t[1]:(r=(0,$.jsx)(`div`,{className:`rounded-lg border border-border/20 bg-muted/15 px-2 py-1 sm:px-2.5 sm:py-1.5 [&_.typography-meta]:!text-xs [&_summary]:py-1`,children:(0,$.jsx)(vR,{data:n})}),t[0]=n,t[1]=r),r},ER=({permission:e,onResponse:t})=>{let{t:n}=Yt(),[r,i]=Q.useState(!1),[a,o]=Q.useState(!1),s=$n,c=Ca(),l=X(e=>e.currentSessionId),u=Q.useMemo(()=>{if(!l||e.sessionID===l)return!1;let t=c.find(t=>t.id===e.sessionID);return!!(t?.parentID&&t.parentID===l)},[e.sessionID,l,c]),d=async n=>{i(!0);try{await s(e.sessionID,e.id,n),o(!0),t?.(n)}catch(e){console.error(`[PermissionCard] Failed to respond to permission:`,e)}finally{i(!1)}};if(a)return null;let f=e.permission||`unknown`,p=f.toLowerCase(),m=(t,n=``)=>{let r=e.metadata[t];return typeof r==`string`?r:typeof r==`number`?String(r):n},h=t=>{let n=e.metadata[t];return typeof n==`number`?n:void 0},g=t=>!!e.metadata[t],_=CR(f),v=Object.fromEntries(Object.entries(e.metadata).filter(([e])=>e!==`always`).map(([e,t])=>[wR(e),t]));return(0,$.jsx)(`div`,{className:`group w-full pt-0 pb-2`,children:(0,$.jsx)(`div`,{className:`chat-column`,children:(0,$.jsxs)(`div`,{className:`-mt-1 overflow-hidden border border-border/30 rounded-xl bg-muted/10`,children:[(0,$.jsx)(`div`,{className:`px-2.5 py-2 sm:px-2 sm:py-1.5 border-b border-border/20 bg-muted/5`,children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center justify-between gap-2`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-1.5 sm:gap-2`,children:[(0,$.jsx)(Z,{name:`question`,className:`h-3.5 w-3.5 text-[var(--status-warning)]`}),(0,$.jsx)(`span`,{className:`truncate text-xs leading-4 sm:text-[length:var(--text-meta)] font-medium text-muted-foreground`,children:n(`sessions.sidebar.session.status.permissionRequired`)}),u?(0,$.jsx)(`span`,{className:`hidden sm:inline typography-micro text-muted-foreground px-1.5 py-0.5 rounded bg-foreground/5`,children:n(`chat.questionCard.fromSubagent`)}):null]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 max-w-[48%] items-center gap-1.5`,children:[SR(f),(0,$.jsx)(`span`,{className:`truncate text-xs leading-4 sm:text-[length:var(--text-meta)] text-muted-foreground font-medium`,children:_})]})]})}),(0,$.jsxs)(`div`,{className:`px-2.5 py-2 sm:px-2 [&_.typography-meta]:!text-xs [&_.typography-micro]:!text-[0.6875rem]`,children:[e.patterns.length>0&&(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:n(`chat.permissionCard.patterns`)}),(0,$.jsx)(`div`,{className:`overflow-hidden rounded-lg border border-border/20 bg-muted/15`,children:e.patterns.map((e,t)=>(0,$.jsx)(`code`,{className:Y(`block break-all px-2 py-1.5 text-xs leading-4 sm:text-[length:var(--text-meta)]`,t>0&&`border-t border-border/15`),children:e},`${e}-${t}`))})]}),(()=>{if(p===`bash`||p===`shell`||p===`shell_command`){let e=m(`command`)||m(`cmd`)||m(`script`),t=m(`description`),r=m(`cwd`)||m(`working_directory`)||m(`directory`)||m(`path`),i=h(`timeout`);return(0,$.jsxs)($.Fragment,{children:[t&&(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:t}),r&&(0,$.jsxs)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:[(0,$.jsx)(`span`,{className:`font-semibold`,children:n(`chat.permissionCard.workingDirectory`)}),` `,(0,$.jsx)(`code`,{className:`px-1 py-0.5 bg-muted/30 rounded`,children:r})]}),i&&(0,$.jsxs)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:[(0,$.jsx)(`span`,{className:`font-semibold`,children:n(`chat.permissionCard.timeout`)}),` `,i,`ms`]}),e&&(0,$.jsx)(`div`,{children:(0,$.jsx)(bu,{language:`bash`,code:e,style:bR,codeStyle:xR.style,wrap:!0})})]})}if(p===`edit`||p===`multiedit`||p===`str_replace`||p===`str_replace_based_edit_tool`){let e=m(`path`)||m(`file_path`)||m(`filename`)||m(`filePath`),t=m(`changes`)||m(`diff`),r=g(`replace_all`)||g(`replaceAll`);return(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-2`,children:(0,$.jsxs)(`span`,{className:`font-semibold`,children:[`⚠️ `,n(`chat.permissionCard.replaceAll`)]})}),t&&(0,$.jsx)(bl,{outerClassName:`max-h-[60vh]`,className:`tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent`,children:(0,$.jsx)(uR,{diff:t,filePath:e})})]})}if(p===`write`||p===`create`||p===`file_write`){let e=m(`path`)||m(`file_path`)||m(`filename`)||m(`filePath`),t=m(`content`)||m(`text`)||m(`data`);return t?(0,$.jsx)(bl,{outerClassName:`max-h-[60vh]`,className:`tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent`,children:(0,$.jsx)(dR,{content:t,filePath:e})}):null}if(p===`webfetch`||p===`fetch`||p===`curl`||p===`wget`){let t=m(`url`)||m(`uri`)||m(`endpoint`),r=m(`method`)||`GET`,i=e.metadata.headers&&typeof e.metadata.headers==`object`?e.metadata.headers:void 0,a=e.metadata.body??e.metadata.data??e.metadata.payload,o=h(`timeout`),s=m(`format`)||m(`responseType`);return(0,$.jsxs)($.Fragment,{children:[t&&(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-1`,children:n(`chat.permissionCard.request`)}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded`,children:r}),(0,$.jsx)(`code`,{className:`typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all`,children:t})]})]}),i&&Object.keys(i).length>0&&(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-1`,children:n(`chat.permissionCard.headers`)}),(0,$.jsx)(bl,{outerClassName:`max-h-32`,className:`p-0`,children:(0,$.jsx)(TR,{data:i})})]}),a&&(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsx)(`div`,{className:`typography-meta text-muted-foreground mb-1`,children:n(`chat.permissionCard.body`)}),(0,$.jsx)(bl,{outerClassName:`max-h-32`,className:`p-0`,children:typeof a==`object`&&a?(0,$.jsx)(TR,{data:a}):(0,$.jsx)(`pre`,{className:`typography-meta font-mono px-2 py-1.5 bg-muted/20 border border-border/20 rounded-lg whitespace-pre-wrap break-all`,children:String(a)})})]}),(o||s)&&(0,$.jsxs)(`div`,{className:`typography-micro text-muted-foreground`,children:[o&&(0,$.jsxs)(`span`,{children:[n(`chat.permissionCard.timeout`),` `,o,`ms`]}),o&&s&&(0,$.jsx)(`span`,{children:` • `}),s&&(0,$.jsxs)(`span`,{children:[n(`chat.permissionCard.responseFormat`),` `,s]})]})]})}return Object.keys(v).length===0?null:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1`,children:n(`chat.permissionCard.details`)}),(0,$.jsx)(bl,{outerClassName:`max-h-48`,className:`p-0`,children:(0,$.jsx)(TR,{data:v})})]})})()]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-3 gap-1 border-t border-border/20 px-1.5 py-1.5 sm:flex sm:items-center sm:flex-wrap sm:px-2 sm:py-1`,children:[(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>d(`once`),disabled:r,className:`h-8 min-w-0 w-full gap-1 px-1 !text-xs leading-4 text-foreground sm:h-6 sm:w-auto sm:px-2`,children:[(0,$.jsx)(Z,{name:`check`,className:`size-3.5 shrink-0 text-[var(--status-success)] sm:size-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:n(`chat.permissionCard.allowOnce`)})]}),(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>d(`always`),disabled:r,className:`h-8 min-w-0 w-full gap-1 px-1 !text-xs leading-4 text-foreground sm:h-6 sm:w-auto sm:px-2`,children:[(0,$.jsx)(Z,{name:`arrow-right`,className:`size-3.5 shrink-0 text-[var(--status-success)] sm:size-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:n(`chat.permissionCard.alwaysAgree`)})]}),(0,$.jsxs)(Qt,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>d(`reject`),disabled:r,className:`h-8 min-w-0 w-full gap-1 px-1 !text-xs leading-4 text-[var(--status-error)] sm:h-6 sm:w-auto sm:px-2`,children:[(0,$.jsx)(Z,{name:`close`,className:`size-3.5 shrink-0 sm:size-3`}),(0,$.jsx)(`span`,{className:`truncate`,children:n(`chat.permissionToast.actions.deny`)})]}),r&&(0,$.jsx)(`div`,{className:`col-span-3 flex justify-center w-full sm:w-auto sm:ml-auto py-1 sm:py-0 typography-meta text-muted-foreground`,children:(0,$.jsx)(`div`,{className:`animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full`})})]})]})})})};function DR(e){let t=[];return(e.questions??[]).forEach((e,n)=>{let r=e.header?.trim(),i=r&&r.length>0?r:`Question ${n+1}`;t.push(`## ${i}`),t.push(``),t.push(e.question),t.push(``),e.multiple&&(t.push(`_Select all that apply._`),t.push(``)),e.options.forEach(e=>{let n=e.label,r=e.description?.trim();t.push(r?`- **${n}** — ${r}`:`- **${n}**`)}),t.push(``)}),t.join(`
|
|
6583
|
-
`).trimEnd()}function OR(e){let t={questions:(e.questions??[]).map(e=>({header:e.header??null,question:e.question,multiple:!!e.multiple,options:e.options.map(e=>({label:e.label,description:e.description??null}))}))};return JSON.stringify(t,null,2)}var kR=200;function AR(e){return Math.min(Math.max(e,40),kR)}var jR=`summary`,MR=Q.memo(function(e){let t=(0,pd.c)(27),{value:n,placeholder:r,disabled:i,onValueChange:a,onKeyDown:o}=e,s=Q.useRef(null),[c,l]=Q.useState(n),[u,d]=Q.useState(40),[f,p]=Q.useState(!1),m;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(m=()=>{let e=s.current;if(!e||document.activeElement!==e)return;let t=e.closest(`.chat-scroll`);if(!t){e.scrollIntoView({block:`nearest`});return}let n=window.visualViewport,r=t.getBoundingClientRect(),i=n?.offsetTop??0,a=n?n.offsetTop+n.height:document.documentElement.clientHeight,o=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(`--oc-kb-scroll-inset`))||0,c=Math.max(r.top,i),l=Math.min(r.bottom,a-o),u=Math.max(0,l-c),d=e.closest(`[data-question-card]`),f=d?.getBoundingClientRect(),p=(d&&f&&f.height<=u?d:e).getBoundingClientRect();p.bottom>l-12?t.scrollTop+=p.bottom-l+12:p.top<c+12&&(t.scrollTop+=p.top-c-12)},t[0]=m):m=t[0];let h=J(m),g;t[1]===h?g=t[2]:(g=()=>{requestAnimationFrame(h)},t[1]=h,t[2]=g);let _=J(g),v;t[3]===h?v=t[4]:(v=()=>{let e=()=>requestAnimationFrame(h);return e(),window.addEventListener(`oc:keyboard-settled`,e),window.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`scroll`,e),()=>{window.removeEventListener(`oc:keyboard-settled`,e),window.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`scroll`,e)}},t[3]=h,t[4]=v);let y;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(y=[],t[5]=y):y=t[5],Q.useEffect(v,y);let b,x;t[6]===n?(b=t[7],x=t[8]):(b=()=>{l(n)},x=[n],t[6]=n,t[7]=b,t[8]=x),Q.useEffect(b,x);let S;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(S=()=>{let e=s.current;if(!e)return;e.style.height=`auto`,e.style.overflowY=`hidden`;let t=e.scrollHeight,n=AR(t),r=t>n;e.style.height=`${n}px`,e.style.overflowY=``,d(e=>e===n?e:n),p(e=>e===r?e:r)},t[9]=S):S=t[9];let C;t[10]===c?C=t[11]:(C=[c],t[10]=c,t[11]=C),Q.useLayoutEffect(S,C);let w;t[12]===a?w=t[13]:(w=e=>{let t=e.target.value;l(t),a(t)},t[12]=a,t[13]=w);let T;t[14]===u?T=t[15]:(T={height:u},t[14]=u,t[15]=T);let E=f?`overflow-y-auto`:`overflow-hidden`,D;t[16]===E?D=t[17]:(D=Y(`w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none`,E),t[16]=E,t[17]=D);let O;return t[18]!==i||t[19]!==_||t[20]!==c||t[21]!==o||t[22]!==r||t[23]!==T||t[24]!==D||t[25]!==w?(O=(0,$.jsx)(`textarea`,{ref:s,value:c,onChange:w,placeholder:r,disabled:i,rows:2,onKeyDown:o,onFocus:_,style:T,className:D,autoFocus:!0}),t[18]=i,t[19]=_,t[20]=c,t[21]=o,t[22]=r,t[23]=T,t[24]=D,t[25]=w,t[26]=O):O=t[26],O}),NR=({question:e})=>{let{t}=Yt(),n=na(e),r=Da,i=Xr,a=q(e=>e.isMobile),o=Ca(),s=X(e=>e.currentSessionId),c=Q.useMemo(()=>{if(!s||e.sessionID===s)return!1;let t=o.find(t=>t.id===e.sessionID);return!!(t?.parentID&&t.parentID===s)},[e.sessionID,s,o]),[l,u]=Q.useState(`0`),[d,f]=Q.useState(!1),p=d||n.claimed||n.pending===`delegate`||n.request?.state===`submitting`||n.request?.state===`uncertain`||n.request?.state===`settled`,[m,h]=Q.useState(!1),[g,_]=Q.useState({}),[v,y]=Q.useState({}),b=Q.useRef({}),[x,S]=Q.useState({}),C=Q.useMemo(()=>e.questions??[],[e.questions]),w=l===jR,T=w?-1:Math.max(0,Math.min(C.length-1,Number(l)||0)),E=w?null:C[T],D=Q.useMemo(()=>{if(w)return null;let e=E?.header?.trim();return e&&e.length>0?e:null},[E?.header,w]);Q.useEffect(()=>{u(`0`),_({}),y({}),b.current={},S({}),h(!1)},[e.id]);let O=Q.useMemo(()=>{let e=C.map((e,t)=>({value:String(t),label:e.header?.trim()||`Q${t+1}`}));return C.length>1&&e.push({value:jR,label:t(`chat.questionCard.summaryTab`)}),e},[C,t]),k=e=>{if(v[e])return(b.current[e]??``).trim()||t(`chat.questionCard.noAnswer`);let n=g[e]??[];return n.length>0?n.join(`, `):t(`chat.questionCard.noAnswer`)},A=!!E?.multiple,j=g[T]??[],M=!!v[T],N=Q.useMemo(()=>{let e=[];for(let t=0;t<C.length;t+=1){if(v[t]){x[t]||e.push(t);continue}(g[t]??[]).length===0&&e.push(t)}return e},[v,x,C.length,g]),P=Q.useMemo(()=>C.length!==0&&N.length===0,[C.length,N.length]),F=J(()=>{if(C.length===0||N.length===0)return;let e=w?-1:T;for(let t=1;t<=C.length;t+=1){let n=(e+t+C.length)%C.length;if(N.includes(n)){u(String(n));return}}u(String(N[0]))}),I=()=>{let e=[];for(let t=0;t<C.length;t+=1){if(v[t]){let n=(b.current[t]??``).trim();e.push(n?[n]:[]);continue}e.push(g[t]??[])}return e},L=J(e=>{E&&(y(e=>({...e,[T]:!1})),S(e=>e[T]?{...e,[T]:!1}:e),_(t=>{let n=t[T]??[];if(A){let r=n.includes(e)?n.filter(t=>t!==e):[...n,e];return{...t,[T]:r}}return{...t,[T]:[e]}}))}),R=J(()=>{y(e=>({...e,[T]:!0})),_(e=>({...e,[T]:[]}));let e=(b.current[T]??``).trim().length>0;S(t=>t[T]===e?t:{...t,[T]:e})}),z=J(e=>{b.current[T]=e;let t=e.trim().length>0;S(e=>e[T]===t?e:{...e,[T]:t})}),B=J(async()=>{if(!P||p)return;let i=n.scope;f(!0);try{let t=I();await r(e.sessionID,e.id,t,n.request?.directory),h(!0)}catch(e){zr(e)?await n.submissionClaimed(i):Hn(e)?(ro.info(t(`chat.questionCard.noLongerPending`)),h(!0)):ro.error(t(`chat.questionCard.submitFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{f(!1)}}),V=J(e=>{Lu(e)||e.key===`Enter`&&!e.shiftKey&&(!a||e.ctrlKey||e.metaKey)&&(e.preventDefault(),P?B():F())}),H=J(async()=>{if(p)return;let r=n.scope;f(!0);try{await i(e.sessionID,e.id,n.request?.directory),h(!0)}catch(e){zr(e)?await n.submissionClaimed(r):Hn(e)?(ro.info(t(`chat.questionCard.noLongerPending`)),h(!0)):ro.error(t(`chat.questionCard.dismissFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{f(!1)}}),ee=J(async()=>{let n=DR(e);if((await Jt(n)).ok){ro.success(t(`chat.questionCard.copiedMarkdown`));return}ro.error(t(`chat.questionCard.copyFailed`))}),U=J(async()=>{let n=OR(e);if((await Jt(n)).ok){ro.success(t(`chat.questionCard.copiedJson`));return}ro.error(t(`chat.questionCard.copyFailed`))});return m||C.length===0?null:(0,$.jsx)(`div`,{className:`group w-full pt-0 pb-2`,children:(0,$.jsx)(`div`,{className:`chat-column`,children:(0,$.jsxs)(`div`,{"data-question-card":!0,className:`-mt-1 border border-border/30 rounded-xl bg-muted/10`,onPointerDownCapture:n.interaction,onClickCapture:n.interaction,onKeyDownCapture:n.interaction,onInputCapture:n.interaction,onPasteCapture:n.interaction,onCompositionStartCapture:n.interaction,children:[(0,$.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border/20`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`question`,className:`h-3.5 w-3.5 text-primary`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground`,children:t(`chat.questionCard.inputNeeded`)}),c?(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground px-1.5 py-0.5 rounded bg-foreground/5`,children:t(`chat.questionCard.fromSubagent`)}):null,D?(0,$.jsx)(`span`,{className:`ml-auto typography-micro font-medium text-foreground/70 px-1.5 py-0.5 rounded bg-muted/30 border border-border/20`,children:D}):null,(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-0.5`,D?null:`ml-auto`),children:[(0,$.jsx)(`button`,{type:`button`,onClick:ee,title:t(`chat.questionCard.copyMarkdown`),"aria-label":t(`chat.questionCard.copyMarkdown`),className:`flex items-center justify-center h-5 w-5 rounded text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,children:(0,$.jsx)(Z,{name:`file-text`,className:`h-3 w-3`})}),(0,$.jsx)(`button`,{type:`button`,onClick:U,title:t(`chat.questionCard.copyJson`),"aria-label":t(`chat.questionCard.copyJson`),className:`flex items-center justify-center h-5 w-5 rounded text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,children:(0,$.jsx)(Z,{name:`code-box`,className:`h-3 w-3`})})]})]})}),(0,$.jsxs)(`div`,{className:`px-2 py-2`,children:[O.length>1?(0,$.jsx)(`div`,{className:`flex items-center gap-1 mb-2 flex-wrap`,children:O.map(e=>{let t=l===e.value,n=e.value===jR,r=n?-1:Number(e.value),i=!n&&Number.isFinite(r)&&!N.includes(r);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>u(e.value),className:Y(`px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1`,t?`bg-interactive-selection/40 text-foreground`:n?`text-muted-foreground hover:text-foreground hover:bg-interactive-hover/20`:i?`text-muted-foreground/60 hover:text-muted-foreground hover:bg-interactive-hover/20`:`text-foreground/85 hover:text-foreground hover:bg-interactive-hover/20`),children:[n?(0,$.jsx)(Z,{name:`list-check-3`,className:`h-3 w-3`}):null,e.label]},e.value)})}):null,w?(0,$.jsx)(`div`,{className:`space-y-2`,children:C.map((e,n)=>{let r=k(n),i=r!==t(`chat.questionCard.noAnswer`);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>u(String(n)),className:`w-full text-left rounded px-1.5 py-1 hover:bg-interactive-hover/20 transition-colors`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:e.header||t(`chat.questionCard.questionFallback`,{index:n+1})}),(0,$.jsx)(`div`,{className:Y(`typography-meta`,i?`text-foreground`:`text-muted-foreground/50 italic`),children:r})]},n)})}):E?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-foreground mb-1.5`,children:E.question}),A?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1.5`,children:t(`chat.questionCard.selectMultiple`)}):null,(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[E.options.map((e,n)=>{let r=j.includes(e.label),i=/\(recommended\)/i.test(e.label);return(0,$.jsx)(`button`,{type:`button`,onClick:()=>L(e.label),disabled:p,className:Y(`w-full px-1.5 py-1 text-left rounded transition-colors`,`hover:bg-interactive-hover/30`,r?`bg-interactive-selection/20`:null,p?`opacity-60 cursor-not-allowed`:null),children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:A?(0,$.jsx)(Oo,{checked:r,onChange:()=>L(e.label),disabled:p}):(0,$.jsx)(ts,{checked:r,onChange:()=>L(e.label),disabled:p})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:Y(`typography-meta break-all`,r?`text-foreground font-medium`:`text-foreground/80`),children:e.label}),i?(0,$.jsx)(`span`,{className:`typography-micro text-primary/80`,children:t(`chat.questionCard.recommended`)}):null]}),e.description?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground break-words`,children:e.description}):null]})]})},`${n}:${e.label}`)}),(0,$.jsx)(`button`,{type:`button`,onClick:R,disabled:p,className:Y(`w-full px-1.5 py-1 text-left rounded transition-colors`,`hover:bg-interactive-hover/30`,M?`bg-interactive-selection/20`:null,p?`opacity-60 cursor-not-allowed`:null),children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`edit`,className:Y(`h-3.5 w-3.5`,M?`text-primary`:`text-muted-foreground/50`)}),(0,$.jsx)(`span`,{className:Y(`typography-meta`,M?`text-foreground font-medium`:`text-muted-foreground`),children:t(`chat.questionCard.other`)})]})}),M?(0,$.jsx)(`div`,{className:`pl-6 pr-1 pt-0.5`,children:(0,$.jsx)(MR,{value:b.current[T]??``,onValueChange:z,placeholder:t(`chat.questionCard.yourAnswer`),disabled:p,onKeyDown:V})}):null]})]}):null]}),(0,$.jsxs)(`div`,{className:`px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:P?B:F,disabled:p,className:Y(`flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors`,`bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]`,`disabled:opacity-50 disabled:cursor-not-allowed`),children:[P?(0,$.jsx)(Z,{name:`check`,className:`h-3 w-3`}):(0,$.jsx)(Z,{name:`arrow-right-s`,className:`h-3 w-3`}),t(P?`chat.questionCard.submit`:`chat.questionCard.next`)]}),(0,$.jsxs)(`button`,{type:`button`,onClick:H,disabled:p,className:Y(`flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors`,`bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]`,`disabled:opacity-50 disabled:cursor-not-allowed`),children:[(0,$.jsx)(Z,{name:`close`,className:`h-3 w-3`}),t(`chat.questionCard.dismiss`)]}),p?(0,$.jsx)(`div`,{className:`ml-auto`,children:(0,$.jsx)(`div`,{className:`animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full`})}):null]}),(0,$.jsx)(hr,{delegation:n})]})})})};function PR(e){return e.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
6584
|
-
`)}function FR(e,t=80){let n=PR(e).replace(/\n/g,` `);return n.length>t?`${n.slice(0,t)}…`:n}var IR=160,LR=28,RR=12,zR=6,BR=30,VR=12,HR=18,UR=80,WR=4,GR=10,KR=14,qR=20,JR=54,YR=4,XR=8,ZR=2,QR=160,$R=(e,t)=>e.map(e=>({turnId:e,preview:FR(t.get(e)??[],IR)})),ez=[1,.6,.35,.15],tz=(e,t,n)=>{let r=n?KR:GR;if(t===null)return r;let i=ez[Math.abs(e-t)]??0;return Math.round(r+(qR-r)*i)};function nz({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:i,isLoadingOlder:a,onLoadEarlier:o}){let{t:s}=Yt(),c=q(e=>e.isPromptNavigatorPanelOpen),l=q(e=>e.setPromptNavigatorPanelOpen),u=Q.useRef(null),d=Q.useRef(null),[f,p]=Q.useState(null),[m,h]=Q.useState(0),[g,_]=Q.useState(!1);Q.useEffect(()=>{let e=d.current?.parentElement;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.querySelector(`.chat-message-column`);if(!t){_(!1);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.right-zR-LR;_(r.right>i)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let v=Q.useMemo(()=>$R(e,t),[t,e]),y=Math.min(v.length,BR),b=Math.max(0,v.length-y),x=Math.min(m,b),S=x+y,C=x>0,w=S<v.length,T=s(`chat.timeline.noTextContent`),E=s(`chat.promptNavigator.currentPrompt`),D=s(`chat.promptNavigator.loadMore`),O=Q.useMemo(()=>n?v.findIndex(e=>e.turnId===n):-1,[n,v]),k=Q.useRef(x);k.current=x;let A=Q.useRef(v.length);A.current=v.length;let j=Q.useRef(null),M=Q.useRef(null),N=Q.useRef(0),P=Q.useCallback(e=>{h(t=>{let n=A.current,r=Math.min(n,BR),i=Math.max(0,n-r),a=Math.min(t,i);return e<a?e:e>=a+r?Math.min(i,e-r+1):a})},[]),F=Q.useRef(v[0]?.turnId),I=Q.useRef(v.length);Q.useLayoutEffect(()=>{let e=F.current,t=I.current,n=v.length-t;n>0&&t>0&&e&&v[0]?.turnId!==e&&(h(e=>e+n),p(e=>e===null?null:e+n)),F.current=v[0]?.turnId,I.current=v.length},[v]),Q.useEffect(()=>{if(f!==null)return;let e=O>=0?O:v.length-1;h(()=>{let t=A.current,n=Math.min(t,BR),r=Math.max(0,t-n);return Math.max(0,Math.min(r,e-Math.floor(n/2)))})},[O,f,v.length]);let L=Q.useCallback(e=>{let t=u.current;if(!t)return null;let n=t.getBoundingClientRect(),r=Math.floor((e-n.top)/VR),i=Math.min(A.current,BR);return i===0?null:Math.max(0,Math.min(i-1,r))},[]),R=Q.useCallback(()=>{N.current=0,M.current!==null&&(window.clearInterval(M.current),M.current=null)},[]),z=Q.useCallback(()=>{let e=N.current;if(e===0){R();return}let t=A.current,n=Math.max(0,t-Math.min(t,BR)),r=Math.min(k.current,n),i=Math.max(0,Math.min(n,r+e));if(i===r){R();return}k.current=i,h(i);let a=j.current;if(a!==null){let e=L(a);e!==null&&p(Math.min(t-1,i+e))}},[L,R]),B=Q.useCallback(e=>{let t=u.current;if(!t)return;let n=t.getBoundingClientRect(),r=e-n.top,i=0;if(r<=HR&&C?i=-1:r>=n.height-HR&&w&&(i=1),N.current=i,i===0){R();return}M.current===null&&(M.current=window.setInterval(z,UR))},[z,C,w,R]);Q.useEffect(()=>()=>{M.current!==null&&window.clearInterval(M.current)},[]);let V=Q.useRef(null),H=Q.useCallback(()=>{V.current!==null&&(window.clearTimeout(V.current),V.current=null)},[]),ee=Q.useCallback(()=>{H(),V.current=window.setTimeout(()=>{V.current=null,p(null)},QR)},[H]);Q.useEffect(()=>()=>{V.current!==null&&window.clearTimeout(V.current)},[]);let U=Q.useCallback(e=>{H(),j.current=e.clientY;let t=L(e.clientY);t!==null&&p(Math.min(A.current-1,k.current+t)),B(e.clientY)},[H,L,B]),te=Q.useCallback(()=>{j.current=null,R(),ee()},[ee,R]),W=Q.useCallback(()=>{l(!1)},[l]),ne=Q.useCallback(e=>{if(e===null)return;let t=v[e];t&&(r(t.turnId),R(),p(null),W(),u.current?.blur())},[W,r,v,R]),G=Q.useCallback(e=>{let t=L(e.clientY);t!==null&&ne(Math.min(v.length-1,k.current+t))},[ne,v.length,L]);Q.useEffect(()=>{if(!c)return;let e=u.current;!e||e===document.activeElement||(e.focus(),p(e=>{if(e!==null)return e;let t=O>=0?O:v.length-1;return P(t),t}))},[O,P,c,v.length]),Q.useEffect(()=>()=>{l(!1)},[l]);let re=Q.useCallback(e=>{if(v.length===0)return;let t=f??(O>=0?O:v.length-1),n=e=>{let t=Math.max(0,Math.min(v.length-1,e));P(t),p(t)};if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault(),n(t+(e.key===`ArrowUp`?-1:1));return}if(e.key===`Home`){e.preventDefault(),n(0);return}if(e.key===`End`){e.preventDefault(),n(v.length-1);return}if(e.key===`Enter`||e.key===` `){e.preventDefault(),ne(t);return}e.key===`Escape`&&(e.preventDefault(),p(null),W(),u.current?.blur())},[O,W,P,ne,f,v.length]),ie=Q.useCallback(()=>{R(),p(null),W()},[W,R]),K=Q.useRef(null),ae=Q.useRef(f);ae.current=f;let oe=f!==null,se=Q.useRef(0);Q.useEffect(()=>{let e=K.current;if(!e)return;let t=e=>{e.preventDefault(),e.stopPropagation(),se.current+=e.deltaY;let t=Math.trunc(se.current/JR);if(t===0)return;se.current-=t*JR;let n=ae.current;if(n===null)return;let r=Math.max(0,Math.min(A.current-1,n+t));r!==n&&(P(r),p(r))};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[P,oe]);let ce=f===null?void 0:v[f],le=Math.min(v.length,XR),ue=le*JR,de=v.length*JR-ue,fe=e=>Math.max(0,Math.min(de,e)),pe=Q.useRef(null),me=0;if(f===null)pe.current=null;else if(pe.current===null)me=fe(f*JR-(ue-JR)/2),pe.current=me;else{let e=pe.current,t=(f-ZR)*JR,n=(f+1+ZR)*JR-ue;e>t?e=t:e<n&&(e=n),me=fe(e),pe.current=me}let he=Math.floor(me/JR),ge=Math.max(0,he-WR),_e=Math.min(v.length,he+le+WR),ve=me>0,ye=me<de,be=ve||ye?`linear-gradient(to bottom, ${ve?`transparent, black 10%`:`black`}, ${ye?`black 90%, transparent`:`black`})`:void 0,xe=Math.max(0,x-WR),Se=Math.min(v.length,S+WR),Ce=v.slice(xe,Se),we=C||w?`linear-gradient(to bottom, ${C?`transparent, black 14%`:`black`}, ${w?`black 86%, transparent`:`black`})`:void 0;return v.length===0?null:(0,$.jsx)(`nav`,{ref:d,"aria-label":s(`chat.promptNavigator.aria`),className:`pointer-events-none absolute right-1.5 top-1/2 z-20 -translate-y-1/2`,children:(0,$.jsxs)(`div`,{className:`pointer-events-auto flex flex-col items-end`,children:[i?(0,$.jsx)(`button`,{type:`button`,tabIndex:-1,className:Y(`-mr-px mb-1.5 flex size-5 shrink-0 items-center justify-center rounded-full`,`text-[var(--surface-mutedForeground)] transition-colors`,`hover:bg-[var(--interactive-hover)]/60 hover:text-[var(--surface-foreground)]`,a?`cursor-wait opacity-70`:void 0),"aria-label":D,title:D,disabled:a,onClick:e=>{e.stopPropagation(),a||o()},children:a?(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(Z,{name:`arrow-up-s`,className:`size-3.5`})}):null,(0,$.jsxs)(`div`,{ref:u,role:`listbox`,tabIndex:-1,"aria-activedescendant":ce?`prompt-rail-tick-${ce.turnId}`:void 0,className:`relative cursor-pointer outline-none`,style:{width:`${g?RR:LR}px`,height:`${y*VR}px`},onMouseMove:U,onMouseLeave:te,onClick:G,onKeyDown:re,onBlur:ie,children:[(0,$.jsx)(`div`,{className:`absolute inset-0 overflow-hidden`,style:we?{maskImage:we,WebkitMaskImage:we}:void 0,children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-300 ease-out`,style:{transform:`translateY(-${x*VR}px)`},children:Ce.map((e,t)=>{let r=xe+t,i=e.turnId===n,a=f===r,o=tz(r,f,i);return(0,$.jsx)(`div`,{id:`prompt-rail-tick-${e.turnId}`,role:`option`,"aria-selected":a,"aria-current":i?`true`:void 0,"aria-label":e.preview.trim()||T,className:`pointer-events-none absolute right-1 flex items-center justify-end`,style:{top:`${r*VR}px`,height:`${VR}px`},children:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(`block h-0.5 rounded-full transition-all duration-200 ease-out`,i?`bg-[var(--surface-foreground)]`:a?`bg-[var(--surface-foreground)]/80`:`bg-[var(--surface-foreground)]/30`),style:{width:`${o}px`}})},e.turnId)})},v[0]?.turnId)}),ce&&f!==null?(0,$.jsx)(`div`,{ref:K,className:Y(`pointer-events-auto absolute right-full top-1/2 z-30 mr-3 -translate-y-1/2`,`w-[min(20rem,calc(100vw-6rem))] overflow-hidden rounded-xl`,`border border-[var(--interactive-border)]/60 bg-[var(--surface-elevated)] py-1 shadow-md`),onMouseEnter:H,onMouseLeave:ee,onMouseMove:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:(0,$.jsx)(`div`,{className:`relative overflow-hidden`,style:{height:`${le*JR}px`,maskImage:be,WebkitMaskImage:be},children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-200 ease-out`,style:{height:`${v.length*JR}px`,transform:`translateY(-${me}px)`},children:v.slice(ge,_e).map((e,t)=>{let r=ge+t,i=e.turnId===n,a=f===r;return(0,$.jsx)(`div`,{role:`option`,"aria-selected":a,"aria-current":i?`true`:void 0,title:i?E:void 0,className:`absolute inset-x-0 cursor-pointer px-1.5`,style:{top:`${r*JR+YR}px`,height:`46px`},onMouseMove:()=>{H(),ae.current!==r&&(P(r),p(r))},onClick:()=>ne(r),children:(0,$.jsx)(`div`,{className:Y(`flex h-full items-center rounded-lg border px-2 transition-colors`,i?`border-transparent bg-[var(--interactive-selection)]`:a?`border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]`:`border-[var(--interactive-border)]/40`),children:(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] text-[length:calc(var(--text-meta)-0.0625rem)] leading-snug`,i?`text-[var(--interactive-selectionForeground)]`:`text-[var(--surface-mutedForeground)]`),children:e.preview.trim()||T})})},e.turnId)})})})}):null]})]})})}var rz=100,iz=(e,t)=>{if(e.length===0)return;let n=0,r=e.length-1,i=0;for(;n<=r;){let a=n+r>>1,o=e[a]?.top;if(o===void 0)break;if(o<=t){i=a,n=a+1;continue}r=a-1}return e[i]?.id},az=e=>{let t=e.raf??requestAnimationFrame,n=e.caf??cancelAnimationFrame,r=e.ResizeObserver??globalThis.ResizeObserver,i=e.MutationObserver??globalThis.MutationObserver,a,o,s,c,l,u,d=!0,f=new Map,p=[],m=()=>{c===void 0&&(c=t(()=>{c=void 0,g()}))},h=()=>{let e=a;if(!e){p=[],d=!1;return}let t=e.getBoundingClientRect().top;p=[...f].map(([n,r])=>({id:n,top:r.getBoundingClientRect().top-t+e.scrollTop})),p.sort((e,t)=>e.top-t.top),d=!1},g=()=>{let t=a;if(!t)return;d&&h();let n=iz(p,t.scrollTop+rz);!n||n===u||(u=n,e.onActive(n))},_=()=>{let e=a;if(e){if(clearTimeout(l),l=void 0,o?.disconnect(),o=void 0,r){o=new r(()=>{clearTimeout(l),l=setTimeout(()=>{d=!0,m()},100)}),o.observe(e);for(let e of f.values())o.observe(e)}if(s?.disconnect(),s=void 0,i){s=new i(()=>{d=!0,m()});let t={subtree:!0,childList:!0};r||(t.characterData=!0,t.characterDataOldValue=!1),s.observe(e,t)}d=!0,m()}},v=e=>{a!==e&&(a=e,u=void 0,_())},y=(e,t)=>{let n=f.get(t);n&&n!==e&&o?.unobserve(n),f.set(t,e),o&&o.observe(e),d=!0,m()},b=e=>{let t=f.get(e);t&&(o?.unobserve(t),f.delete(e),d=!0,m())},x=()=>{d=!0,m()},S=()=>{for(let e of f.values())o?.unobserve(e);f.clear(),p=[],u=void 0,d=!0};return{setContainer:v,register:y,unregister:b,onScroll:m,markDirty:x,clear:S,destroy:()=>{c!==void 0&&n(c),c=void 0,clearTimeout(l),l=void 0,S(),o?.disconnect(),s?.disconnect(),o=void 0,s=void 0,a=void 0},getActiveId:()=>u}},oz=10,sz=`${oz}vh`,cz=`80px`,lz=`calc(${cz} + var(--oc-chat-foot-inset))`,uz=(e,t)=>e?80:t<=0?96:Math.max(48,oz/100*t),dz=(e,t)=>({sessionId:e,viewportKey:t}),fz=(e,t)=>e?.sessionId===t?.sessionId&&e?.viewportKey===t?.viewportKey,pz=(e,t)=>fz(e,t),mz=(e,t,n)=>({identity:e,anchor:t,scrollPosition:n}),hz=150,gz=1500,_z=2,vz=350,yz=600,bz=8e3,xz=24,Sz=2,Cz=(e,t)=>e<t,wz=()=>typeof performance<`u`?performance.now():Date.now(),Tz=e=>({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}),Ez=e=>e.scrollHeight-e.scrollTop-e.clientHeight,Dz=e=>Ez(Tz(e)),Oz=e=>e.scrollHeight-e.clientHeight>1,kz=(e,t)=>Ez(e)<=uz(t,e.clientHeight),Az=({enabled:e=!0,currentSessionId:t,viewportKey:n,sessionMessageCount:r,sessionIsWorking:i,isMobile:a,onActiveTurnChange:o,onUpwardUserIntent:s})=>{let c=Q.useRef(null),[l,u]=Q.useState(null),d=Q.useRef(null),[f,p]=Q.useState(`following`),[m,h]=Q.useState(!1),[g,_]=Q.useState(!1),[v,y]=Q.useState(!1),b=Q.useRef(`following`),x=Q.useRef(a);x.current=a;let S=Q.useRef(r);S.current=r;let C=Q.useRef(dz(t,n));C.current=dz(t,n);let w=Q.useRef(null),T=Q.useRef(null),E=Q.useRef(null),D=Q.useRef(0),O=Q.useRef(null),k=Q.useRef(null),A=Q.useRef(0),j=Q.useRef(!1),M=Q.useRef(!1),N=Q.useRef(null),P=Q.useRef(0),F=J(()=>{P.current=wz()+450}),I=Q.useRef(0),L=Q.useRef(!1),R=Q.useRef(null),z=Q.useRef(null),B=Q.useRef(0),V=Q.useRef(!1),H=Q.useRef(null),ee=Q.useRef(null),U=Q.useRef(null),te=Xa(e=>e.updateViewportAnchor);Q.useLayoutEffect(()=>{c.current!==d.current&&(d.current=c.current,u(c.current))});let W=J(e=>{b.current!==e&&(b.current=e,p(e))}),ne=J(e=>{T.current={top:Math.max(0,e.scrollHeight-e.clientHeight),time:wz()},E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{T.current=null,E.current=null},gz)}),G=J(e=>{let t=T.current;return t?wz()-t.time>gz?(T.current=null,!1):Math.abs(e.scrollTop-t.top)<_z:!1}),re=J(()=>wz()<A.current),ie=J(()=>{L.current=!1,R.current&&=(clearTimeout(R.current),null),z.current&&=(clearTimeout(z.current),null)}),K=J(()=>{R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{R.current=null,ie()},yz)}),ae=J(()=>{let e=c.current;e&&(L.current=!0,B.current=e.scrollHeight,K(),z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{z.current=null,ie()},bz))}),oe=J(e=>{let t=c.current;if(!t){h(!1),_(!1);return}let n=e??Tz(t),r=Oz(n);if(h(r),!r){_(!1);return}let i=b.current===`released`&&!kz(n,x.current);_(i)}),se=J(()=>{D.current+=1,O.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(O.current),O.current=null),k.current?.(),k.current=null});Q.useEffect(()=>()=>se(),[l]);let ce=J(()=>{if(!e)return;let t=c.current;if(!t)return;se();let n=D.current,r=t.style.overflow,i=t.style.scrollBehavior;t.style.scrollBehavior=`auto`,t.style.overflow=`hidden`,t.scrollTop=t.scrollHeight,t.scrollHeight,t.style.overflow=r,t.style.scrollBehavior=i;let a=()=>{ne(t),t.scrollTop=t.scrollHeight,I.current=t.scrollTop};if(a(),oe(),typeof window>`u`)return;let o=0,s=()=>{Cz(wz(),P.current)||se()};t.addEventListener(`touchstart`,s,{passive:!0,once:!0}),k.current=()=>t.removeEventListener(`touchstart`,s);let l=()=>{if(n===D.current){if(Dz(t)>Sz&&a(),o+=1,o>=xz){O.current=null,k.current?.(),k.current=null,oe();return}O.current=window.requestAnimationFrame(l)}};O.current=window.requestAnimationFrame(l)}),le=J(e=>{let t=c.current;if(t){if(ne(t),e===`smooth`){t.scrollTo({top:t.scrollHeight,behavior:e});return}t.scrollTop=t.scrollHeight}}),ue=J((t,n=`auto`)=>{if(!e)return;let r=c.current;if(t&&b.current!==`following`&&W(`following`),r&&!(!t&&b.current!==`following`)){if(Dz(r)<_z){ne(r);return}le(t?n:`auto`)}}),de=J(e=>{let t=c.current;if(!t)return;let n=e??Tz(t);if(!Oz(n)){W(`following`);return}b.current!==`released`&&(W(`released`),oe(n))}),fe=J((e=`instant`)=>{if(V.current=!1,W(`following`),ie(),e===`instant`){ce();return}se(),ue(!0,`smooth`),oe()}),pe=J(()=>{V.current=!1,ue(!0)}),me=J(()=>{se(),ie(),W(`released`),oe()}),he=J(()=>{V.current=!0,me()}),ge=J(()=>{V.current=!1}),_e=Q.useRef(s);_e.current=s;let ve=J(()=>{Cz(wz(),P.current)||(se(),ie(),de())}),ye=J(()=>{ve(),_e.current?.()}),be=J(()=>{H.current!==null&&(clearTimeout(H.current),H.current=null);let e=ee.current;if(e){if(!e.identity.sessionId){ee.current=null;return}te(e.identity.sessionId,e.anchor,e.scrollPosition,e.identity.viewportKey),ee.current=null}}),xe=J(()=>{let e=C.current;if(!e.sessionId)return;let t=c.current;if(!t)return;let{scrollTop:n,scrollHeight:r,clientHeight:i}=t,a=r>0?(n+i/2)/r:0,o=Math.floor(a*S.current);ee.current=mz(e,o,{scrollTop:n,scrollHeight:r,clientHeight:i}),H.current===null&&(H.current=setTimeout(()=>{H.current=null,be()},hz))}),Se=J(()=>{be()}),Ce=J(async(e=C.current)=>{if(!e.sessionId)return!1;V.current=!1;let t=gi(e.sessionId,e.viewportKey);return c.current?(U.current=null,I.current=t?.scrollPosition?.scrollTop??0,W(`following`),F(),x.current?ce():ue(!0),ae(),oe(),!1):(U.current=e,W(`following`),!1)});Q.useEffect(()=>{let e=C.current,n=w.current;fz(e,n)||(be(),se(),F(),w.current=e,T.current=null,I.current=0,ie(),V.current=!1,W(`following`),U.current=null,t&&t!==n?.sessionId&&CT.getInstance().recordSessionStart(t))},[t,n]),Q.useEffect(()=>{i&&!V.current&&b.current===`following`&&ue(!0)},[i]),Q.useEffect(()=>{y(f===`following`&&i)},[f,i]),Q.useLayoutEffect(()=>{if(!l)return;let e=U.current;e&&pz(e,C.current)&&Ce(e)},[l,t,n]);let we=J(()=>{let e=c.current;if(!e)return;let t=Tz(e),n=I.current;I.current=t.scrollTop;let r=t.scrollTop>n+.5,i=Math.abs(t.scrollTop-n)<.5;if(oe(t),V.current){xe();return}if(!Oz(t)){W(`following`);return}if(kz(t,x.current)){let e=Math.min(n,Math.max(0,t.scrollHeight-t.clientHeight));if(t.scrollTop<e-.5){ve(),xe();return}(r||b.current===`following`)&&W(`following`),xe();return}if(b.current===`following`&&(G(e)||re()||i)){j.current||ue(!1),xe();return}de(t),xe()});Q.useEffect(()=>{!e||!l||(I.current=l.scrollTop)},[l,e]);let Te=Q.useRef(null),Ee=J(e=>{let t=c.current;t&&(e.deltaY>=0||Ju(t,e.target)||ye())}),De=J(e=>{let t=e.touches.item(0);Te.current=t?{x:t.clientX,y:t.clientY,dx:0,dy:0}:null}),Oe=J(e=>{let t=c.current,n=e.touches.item(0);if(!n){Te.current=null;return}let r=Te.current;if(!r)return;let i=n.clientY-r.y,a=i*r.dy<0,o=(a?0:r.dx)+n.clientX-r.x,s=(a?0:r.dy)+i;if(Te.current={x:n.clientX,y:n.clientY,dx:o,dy:s},!(s<=0||Math.abs(o)>=s)&&t){if(Ju(t,e.target)){Te.current.dx=0,Te.current.dy=0;return}s<=2||ye()}}),ke=J(()=>{Te.current=null}),Ae=J(e=>{zu(e)&&ye()}),je=J(e=>{let t=e.target;t instanceof Element&&t.closest(`[data-overlay-scrollbar-thumb]`)&&ve()}),Me=Q.useMemo(()=>()=>void 0,[]),Ne=e&&l?l:Me,Pe=Q.useMemo(()=>({passive:!0}),[]);Kt(`scroll`,we,Ne,Pe),Kt(`wheel`,Ee,Ne,Pe),Kt(`touchstart`,De,Ne,Pe),Kt(`touchmove`,Oe,Ne,Pe),Kt(`touchend`,ke,Ne,Pe),Kt(`touchcancel`,ke,Ne,Pe),Kt(`keydown`,Ae,Ne),Kt(`pointerdown`,je,e&&typeof window<`u`?window:Me,!0);let Fe=J(()=>{let e=c.current;if(j.current){oe(e?Tz(e):void 0);return}if(V.current){oe(e?Tz(e):void 0);return}if(!e){oe(void 0);return}let t=Tz(e);if(!Oz(t)){W(`following`),oe(t);return}if(oe(t),L.current){let n=t.scrollHeight>B.current+1;B.current=t.scrollHeight,Ez(t)<=_z?ne(e):ue(!0),n&&K();return}if(b.current===`following`){if(Ez(t)<=_z){ne(e);return}ue(!1)}}),Ie=typeof ResizeObserver<`u`,Le=Ie&&e?l:null,Re=Ie&&e&&l&&l.firstElementChild instanceof Element?l.firstElementChild:null;Vt(Le,Fe),Vt(Re,Fe);let ze=J(()=>{N.current!==null&&(clearTimeout(N.current),N.current=null)}),Be=J(e=>{j.current=!0,typeof e==`number`&&e>0?A.current=wz()+e+vz:A.current=Math.max(A.current,wz()+vz)}),Ve=J(e=>{let t=e.detail;if(t){if(t.open===!0){Be(),ze(),N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},1500);return}ze(),Be()}}),He=J(e=>{let t=e.detail;t&&(ze(),Be(t.durationMs))}),Ue=J(e=>{let t=e.detail;ze(),t?.open===!0?(M.current=!0,j.current=!0):(M.current=!1,j.current=!0,N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},vz)),oe()}),We=e&&typeof window<`u`?window:Me;Kt(`oc:keyboard-intent`,Ve,We),Kt(`oc:keyboard-anim`,He,We),Kt(`oc:keyboard-settled`,Ue,We),Q.useEffect(()=>{if(!(!e||typeof window>`u`))return()=>{ze(),j.current=!1,M.current=!1}},[e]),Q.useEffect(()=>{e&&oe()},[e,r]);let Ge=J(t=>{if(e){if(t===`animation`&&(A.current=wz()+vz),oe(),L.current){ue(!0),K();return}b.current===`following`&&ue(!1)}}),Ke=Q.useRef(new Map),qe=J(t=>{let n=Ke.current.get(t);if(n)return n;let r=()=>{e&&b.current===`following`&&ue(!1)},i={onChunk:r,onComplete:()=>{e&&oe()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:r,onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return Ke.current.set(t,i),i});Q.useEffect(()=>()=>{E.current&&=(clearTimeout(E.current),null),se(),ie(),be(),H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);let Je=J(e=>{o?.(e)}),Ye=!!o;return Q.useEffect(()=>{if(!e||!Ye)return;let t=l;if(!t)return;let n=null,r=az({onActive:e=>{e!==n&&(n=e,Je(e))}});r.setContainer(t);let i=new Map,a=e=>{let t=e.dataset.turnId;return t?(i.set(t,e),r.register(e,t),!0):!1},o=e=>{let t=e.dataset.turnId;return!t||i.get(t)!==e?!1:(i.delete(t),r.unregister(t),!0)},s=e=>{if(!(e instanceof HTMLElement))return[];let t=[];return e.matches(`[data-turn-id]`)&&t.push(e),e.querySelectorAll(`[data-turn-id]`).forEach(e=>t.push(e)),t};t.querySelectorAll(`[data-turn-id]`).forEach(a),r.markDirty();let c=new MutationObserver(e=>{let t=!1;e.forEach(e=>{e.removedNodes.forEach(e=>{s(e).forEach(e=>{o(e)&&(t=!0)})}),e.addedNodes.forEach(e=>{s(e).forEach(e=>{a(e)&&(t=!0)})})}),t&&r.markDirty()});c.observe(t,{subtree:!0,childList:!0});let u=()=>r.onScroll();return t.addEventListener(`scroll`,u,{passive:!0}),()=>{t.removeEventListener(`scroll`,u),c.disconnect(),r.destroy()}},[l,e,Ye]),{scrollRef:c,state:f,isPinned:f===`following`,isOverflowing:m,isFollowingProgrammatically:v,showScrollButton:g,notifyContentChange:Ge,getAnimationHandlers:qe,goToBottom:fe,scrollToBottomOnSend:pe,releaseAutoFollow:me,beginHistoryViewportPreservation:he,endHistoryViewportPreservation:ge,saveSnapshotNow:Se,restoreSnapshot:Ce}},jz=`--oc-mobile-composer-swap`,Mz=`--oc-native-composer-dock`,Nz=()=>({phase:`rest`,rest:`expanded`,progress:0,pinned:!1}),Pz=(e,t,n)=>Math.min(n,Math.max(t,e)),Fz=(e,t)=>e.phase===t.phase&&e.rest===t.rest&&e.progress===t.progress&&e.pinned===t.pinned,Iz=(e,t)=>{let n={phase:t.phase,rest:t.rest,progress:t.progress,pinned:t.pinned??e.pinned};return Fz(e,n)?e:n},Lz=(e,t)=>t?Iz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0}):e.pinned?Iz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!1}):e,Rz=(e,t)=>{if(e.pinned&&t===`compact`)return e;let n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Iz(e,{phase:`snapping`,rest:t,progress:n})},zz=e=>Pz(e/80,0,1),Bz=e=>e>=80?1:Pz(e/80,0,1),Vz=(e,t,n={})=>{if(e.pinned||n.userDriven===!1)return e;let r=Math.max(0,t),i=e.phase===`snapping`?Iz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e;if(i.rest===`expanded`){if(r<=2||n.holdExpanded)return Iz(i,{phase:`rest`,rest:`expanded`,progress:0});let e=zz(r);return e>=1?Iz(i,{phase:`rest`,rest:`compact`,progress:1}):Iz(i,{phase:`tracking`,rest:`expanded`,progress:e})}if(r<=2)return Iz(i,{phase:`rest`,rest:`expanded`,progress:0});if(n.suppressReturn)return Iz(i,{phase:`rest`,rest:`compact`,progress:1});if(n.towardBottom&&r>=80)return Iz(i,{phase:`snapping`,rest:`expanded`,progress:0});let a=Bz(r);return a>=1?Iz(i,{phase:`rest`,rest:`compact`,progress:1}):Iz(i,{phase:`tracking`,rest:`compact`,progress:a})},Hz=e=>e.pinned?`expanded`:e.rest===`expanded`?e.progress>=.5?`compact`:`expanded`:e.progress<=.5?`expanded`:`compact`,Uz=e=>{if(e.pinned)return Iz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0});if(e.phase===`snapping`)return e;let t=Hz(e),n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Iz(e,{phase:`snapping`,rest:t,progress:n})},Wz=e=>e.phase===`snapping`?Iz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e,Gz=e=>Pz(Math.max(0,e)/80,0,1),Kz=(e,t=`away`)=>{let n=Math.max(0,e);return n<=2?{progress:0,rest:`bottom`}:t===`away`||n>=40?{progress:1,rest:`away`}:{progress:Gz(n),rest:`bottom`}},qz=e=>{e.style.removeProperty(jz),e.style.removeProperty(Mz),delete e.dataset.ocComposerSwapPhase,delete e.dataset.ocComposerSwapRest,delete e.dataset.ocNativeComposerDock},Jz=(e,t,n)=>{let r=Kz(t,n?.rest===`bottom`?`bottom`:`away`),i=String(r.progress),a=r.rest;return n?.progress!==i&&e.style.setProperty(Mz,i),n?.rest!==a&&(e.dataset.ocNativeComposerDock=a),{progress:i,rest:a}},Yz=(e,t,n)=>{let r=String(t.progress),i=t.phase,a=t.rest;return n?.phase!==i&&(e.dataset.ocComposerSwapPhase=i,i===`snapping`&&n&&n.phase!==`snapping`&&e.offsetWidth),n?.progress!==r&&e.style.setProperty(jz,r),n?.rest!==a&&(e.dataset.ocComposerSwapRest=a),{progress:r,phase:i,rest:a}},Xz=e=>({scrollHeight:e.scrollHeight,scrollTop:e.scrollTop,clientHeight:e.clientHeight}),Zz=()=>{let e=document.documentElement;return e.classList.contains(`oc-keyboard-open`)||e.classList.contains(`oc-kb-animating`)},Qz=e=>{if(Zz()||e.querySelector(`[data-oc-composer-dictation-active="true"]`))return!0;let t=document.activeElement;return t instanceof HTMLElement&&t.matches(`textarea[data-chat-input="true"]`)&&e.contains(t)},$z=e=>{let t=Q.useRef(Nz()),n=Q.useRef(void 0),r=Q.useRef(void 0),i=Q.useRef(null),a=Q.useRef(null),o=Q.useRef(0),s=Q.useRef(!1),c=Q.useRef(0),l=Q.useRef(new Map),u=Q.useRef(!1),d=Q.useRef(0),f=Q.useRef(null),p=Q.useRef(null),m=Q.useRef(0),h=Q.useRef(0),g=Q.useRef(!1),_=Q.useRef(e.enabled);_.current=e.enabled;let v=e=>{e.current!==null&&(window.clearTimeout(e.current),e.current=null)},y=J(t=>{let r=e.scopeRef.current;r&&(n.current=Yz(r,t,n.current))}),b=J(e=>{e!==t.current&&(t.current=e,y(e))}),x=J(()=>{if(v(a),t.current.phase!==`snapping`)return;let e=t.current.rest;a.current=window.setTimeout(()=>{a.current=null;let n=Wz(t.current);b(n),n.rest===`compact`&&e===`compact`&&(o.current=Date.now()+320,s.current=!0)},240)}),S=J(()=>{let n=e.scopeRef.current;!n||!_.current||b(Lz(t.current,Qz(n)))}),C=J(e=>s.current?Date.now()>=o.current?(s.current=!1,!1):e>=80?(s.current=!1,o.current=0,!1):!0:!1),w=J(()=>{if(v(i),!_.current||c.current>0||t.current.phase!==`tracking`)return;let e=Uz(t.current);b(e),x()}),T=J(()=>{u.current=!1,d.current=0;for(let e of l.current.values())e.startX=e.currentX,e.startY=e.currentY}),E=J(e=>{if(!_.current)return;let t=!1;for(let n=0;n<e.changedTouches.length;n+=1){let r=e.changedTouches[n];if(!r)continue;let i=l.current.get(r.identifier);if(!i){l.current.set(r.identifier,{startX:r.clientX,startY:r.clientY,currentX:r.clientX,currentY:r.clientY});continue}i.currentX=r.clientX,i.currentY=r.clientY;let a=Math.abs(i.currentX-i.startX),o=Math.abs(i.currentY-i.startY);o>0&&o>a&&(t=!0)}!t&&!u.current||(u.current=!0,d.current=Date.now(),s.current=!1,o.current=0)}),D=J(t=>{if(_.current){if(c.current===0){l.current.clear(),T(),m.current=0,h.current=0;let t=e.scrollRef.current;if(t){let e=Xz(t);p.current=e,f.current=rI(e,tI(t))}}for(let e=0;e<t.changedTouches.length;e+=1){let n=t.changedTouches[e];n&&l.current.set(n.identifier,{startX:n.clientX,startY:n.clientY,currentX:n.clientX,currentY:n.clientY})}c.current=l.current.size,v(i)}}),O=J(()=>{if(!_.current)return;let n=e.scrollRef.current,o=e.scopeRef.current;if(!n||!o)return;let s=Qz(o),l=Xz(n),y=rI(l,tI(n)),S=f.current,E=p.current;if(f.current=y,p.current=l,n.hasAttribute(`data-oc-timeline-anchoring`)){m.current=0,h.current=0,T();return}r.current=Jz(o,y,r.current);let D=u.current&&(c.current>0||Date.now()-d.current<=1200),O=E!==null&&(E.scrollHeight!==l.scrollHeight||E.clientHeight!==l.clientHeight),k=D&&!O,A=S===null?0:S-y;k?A>0?(h.current=0,l.scrollTop>0&&(m.current+=A)):A<0&&(m.current=0,h.current+=-A,h.current>=24&&(g.current=!1)):(m.current=0,h.current=0),k&&y<=2&&(g.current=!1);let j=t.current,M=Lz(j,s);if(!s){let e=M.rest===`compact`;M=Vz(M,y,{suppressReturn:k&&C(y),towardBottom:m.current>=24,holdExpanded:g.current,userDriven:k}),e&&M.rest===`expanded`&&y>2&&(g.current=!0,m.current=0)}if(b(M),k){if(v(i),M.phase===`snapping`){(j.phase!==`snapping`||j.rest!==M.rest||j.progress!==M.progress)&&x();return}j.phase===`snapping`&&v(a),M.phase===`tracking`&&c.current===0&&(i.current=window.setTimeout(()=>{i.current=null,w()},120))}}),k=J(()=>{u.current&&(c.current>0||Date.now()-d.current<=1200)&&w()}),A=J((e,n)=>{if(_.current){for(let t=0;t<e.changedTouches.length;t+=1){let n=e.changedTouches[t];n&&l.current.delete(n.identifier)}c.current=l.current.size,!(c.current>0)&&(l.current.clear(),n&&u.current?d.current=Date.now():T(),t.current.phase===`tracking`&&(v(i),i.current=window.setTimeout(()=>{i.current=null,w()},120)))}}),j=J(e=>{A(e,!0)}),M=J(e=>{A(e,!1)}),N=J(()=>{let t=e.scopeRef.current;if(!t||typeof window>`u`)return;let n=e=>{e.preventDefault(),e.stopPropagation()};t.addEventListener(`pointerup`,n,!0),t.addEventListener(`click`,n,!0),window.setTimeout(()=>{t.removeEventListener(`pointerup`,n,!0),t.removeEventListener(`click`,n,!0)},240)}),P=J(n=>{if(!_.current)return;let r=n.target;r instanceof Element&&r.closest(`[data-oc-composer-compact-surface="true"]`)&&(r.closest(`[data-composer-action="true"]`)||(`preventDefault`in n&&n.preventDefault(),`stopPropagation`in n&&n.stopPropagation(),g.current=!0,m.current=0,h.current=0,b(Rz(t.current,`expanded`)),x(),N(),(e.scopeRef.current?.querySelector(`textarea[data-chat-input="true"]`))?.focus({preventScroll:!0})))}),[F,I]=Q.useState(null),[L,R]=Q.useState(null),z=Q.useRef(null),B=J(e=>{e&&qz(e),n.current=void 0,r.current=void 0,s.current=!1,o.current=0,c.current=0,l.current.clear(),u.current=!1,d.current=0,f.current=null,p.current=null,m.current=0,h.current=0,g.current=!1,b(Nz())});Q.useLayoutEffect(()=>{let t=e.enabled?e.scrollRef.current:null,n=e.enabled?e.scopeRef.current:null;z.current&&z.current!==n&&B(z.current),z.current=n,I(e=>e===t?e:t),R(e=>e===n?e:n)});let V=Q.useMemo(()=>()=>void 0,[]),H=e.enabled&&F?F:V,ee=e.enabled&&L?L:V,U=e.enabled&&typeof window<`u`?window:V,te=Q.useMemo(()=>({passive:!0}),[]);Kt(`scroll`,O,H,te),Kt(`scrollend`,k,H,te),Kt(`touchstart`,D,H,te),Kt(`touchmove`,E,H,te),Kt(`touchend`,j,H,te),Kt(`touchcancel`,M,H,te),Kt(`pointerdown`,P,ee),Kt(`focusin`,S,ee),Kt(`focusout`,S,ee),Kt(`oc:keyboard-intent`,S,U),Kt(`oc:keyboard-anim`,S,U),Kt(`oc:keyboard-settled`,S,U),Q.useEffect(()=>{if(!e.enabled){B(z.current),z.current=null;return}return S(),O(),()=>{v(i),v(a)}},[e.enabled,F,L])},eB=e=>{let t=e.info.clientRole??e.info.role;return typeof t==`string`?t:``},tB=e=>{let t=e.info.parentID;if(typeof t==`string`&&t.trim().length!==0)return t},nB=e=>{if(!e)return null;let t=eB(e);return`${typeof e.info?.id==`string`?e.info.id:``}::${t}::${tB(e)??``}`},rB=e=>({turnIds:[...e.turnIds],turnMessageStartIndexes:[...e.turnMessageStartIndexes],turnIndexById:new Map(e.turnIndexById),messageToTurnId:new Map(e.messageToTurnId),messageToTurnIndex:new Map(e.messageToTurnIndex),turnCount:e.turnCount}),iB=(e,t,n)=>{if(!e||!t)return null;if(t.length===n.length){let r=-1;for(let e=0;e<n.length;e+=1)if(t[e]!==n[e]){if(r!==-1)return null;r=e}return r===-1||r===n.length-1&&nB(t[r])===nB(n[r])?e:null}if(n.length!==t.length+1)return null;for(let e=0;e<t.length;e+=1)if(t[e]!==n[e])return null;let r=n[n.length-1];if(!r)return null;let i=eB(r),a=r.info.id,o=rB(e);if(i===`user`){let e=o.turnIds.length;return o.turnIds.push(a),o.turnMessageStartIndexes.push(n.length-1),o.turnIndexById.set(a,e),o.messageToTurnId.set(a,a),o.messageToTurnIndex.set(a,e),o.turnCount=o.turnIds.length,o}if(i!==`assistant`){let e=o.turnIds.length-1;if(e<0)return null;let t=o.turnIds[e];return t?(o.messageToTurnId.set(a,t),o.messageToTurnIndex.set(a,e),o):null}let s=tB(r);if(!s)return o;let c=o.turnIndexById.get(s);if(typeof c!=`number`||c<0)return null;let l=o.turnIds[c];return l?(o.messageToTurnId.set(a,l),o.messageToTurnIndex.set(a,c),o):null},aB=e=>{let t=[],n=[],r=new Map,i=new Map,a=new Map,o=new Map,s=-1;return e.forEach((e,c)=>{let l=eB(e),u=e.info.id;if(l===`user`){s=t.length,t.push(u),n.push(c),r.set(u,s),o.set(u,s),i.set(u,u),a.set(u,s);return}if(l!==`assistant`){if(s>=0){let e=t[s];e&&(i.set(u,e),a.set(u,s))}return}let d=tB(e);if(!d)return;let f=o.get(d);if(typeof f!=`number`||f<0)return;let p=t[f];p&&(i.set(u,p),a.set(u,f))}),{turnIds:t,turnMessageStartIndexes:n,turnIndexById:r,messageToTurnId:i,messageToTurnIndex:a,turnCount:t.length}},oB=200,sB={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:6e5},cB=()=>oB,lB=()=>Math.round(cB()*.6),uB={MAX_SESSIONS:sB.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(oB*.6),HISTORICAL_MESSAGES:oB,FETCH_BUFFER:20,HISTORY_CHUNK:oB,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:sB.ZOMBIE_TIMEOUT},dB=()=>{let e=cB(),t=lB();return{...uB,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},fB=uB,pB=600,mB=6e3,hB=.5,gB=(e,t)=>e.querySelector(`[data-message-id="${CSS.escape(t)}"]`),_B=e=>{let t=e.getBoundingClientRect(),n=e.querySelectorAll(`[data-message-id]`);for(let e of n)if(e.getBoundingClientRect().bottom>t.top)return e;return null},vB=(e,t)=>{let n=gB(e,t);if(n||=_B(e),!n)return null;let r=n.dataset.messageId;if(!r)return null;let i=e.getBoundingClientRect();return{messageId:r,offsetTop:n.getBoundingClientRect().top-i.top}},yB=e=>{let{container:t,quiesceMs:n=pB,maxLifetimeMs:r=mB}=e,i={messageId:e.anchor.messageId,offsetTop:e.anchor.offsetTop},a=!1,o=null,s=null,c=!1,l=t.scrollTop,u=()=>{o!==null&&(clearTimeout(o),o=null)},d=()=>{s!==null&&(clearTimeout(s),s=null)},f=()=>{a||(a=!0,y.disconnect(),t.removeEventListener(`scroll`,v),u(),d())},p=()=>{u(),!a&&(o=setTimeout(()=>{o=null,f()},n))},m=()=>{d(),!a&&(s=setTimeout(()=>{s=null,f()},r))},h=()=>{if(a)return;let e=vB(t,i.messageId);if(!e){f();return}i.messageId=e.messageId,i.offsetTop=e.offsetTop,l=t.scrollTop},g=()=>{if(a)return;if(Math.abs(t.scrollTop-l)>hB){h();return}let e=gB(t,i.messageId);if(!e){let n=_B(t);if(!n){f();return}let r=n.dataset.messageId;if(!r){f();return}let a=t.getBoundingClientRect();i.messageId=r,i.offsetTop=n.getBoundingClientRect().top-a.top,e=n,l=t.scrollTop}let n=t.getBoundingClientRect(),r=e.getBoundingClientRect().top-n.top-i.offsetTop;Math.abs(r)>hB&&(t.scrollTop+=r),l=t.scrollTop},_=()=>{a||c||(c=!0,queueMicrotask(()=>{c=!1,g()}))},v=()=>{h(),p(),m()},y=new MutationObserver(()=>{a||(_(),p())});return y.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`style`,`class`]}),t.addEventListener(`scroll`,v,{passive:!0}),m(),p(),{rebase:h,dispose:f}},bB=30,xB=1200,SB=1.5,CB=e=>Math.max(xB,e*SB),wB=4,TB=30,EB=4,DB=30,OB=250,kB=2e3,AB=mr+2e3,jB=40,MB=`history-loading-timeout`,NB=e=>!!(e&&typeof e==`object`&&e.code===`history-loading-timeout`),PB=()=>{let e=Error(`chat history pagination wait timed out`);return e.code=MB,e},FB=(e,t,n)=>{if(e===`no-growth`){console.error(`[chat-history] load older completed without prepending messages`,t instanceof Error?t:Error(`chat history pagination returned no growth`),n);return}if(e===`timeout`){console.error(`[chat-history] load older timed out waiting for sync pagination`,t,n);return}console.error(`[chat-history] load older failed`,t,n)},IB=2500,LB=new Map,RB=()=>ge()?wB:yr()?EB:bB,zB=e=>ge()?e.length<=TB:!yr()||e.length<=DB,BB=(e,t)=>{if(LB.delete(e),!zB(t.messages))return;let n=RB();for(;LB.size>=n;){let e=LB.keys().next().value;if(typeof e!=`string`)break;LB.delete(e)}LB.set(e,t)},VB=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),HB=e=>e?{owner:`tanstack-core`}:{owner:`controller`},UB=(e,t)=>e?e.canLoadEarlier:t>=dB().HISTORICAL_MESSAGES,WB=e=>!(e.isMobile||e.isLoadingOlder||e.pendingRevealWork||!e.canLoadEarlier||e.source===`scroll`&&e.isPinned||e.scrollTop>=CB(e.clientHeight)),GB=e=>e.pagesLoaded>=e.maxPages?`stop-bounded`:e.hasMoreAbove?e.scrollHeightAfter-e.scrollHeightBefore>1?`stop-visible`:e.messageCountAfter>e.messageCountBefore||typeof e.oldestIdBefore==`string`&&typeof e.oldestIdAfter==`string`&&e.oldestIdBefore!==e.oldestIdAfter||e.limitAfter>e.limitBefore?`continue`:`stop-no-growth`:`stop-exhausted`,KB=1,qB=8,JB=e=>!(!e.enabled||e.isMobile||!e.sessionReady||!e.messageReady||e.historyLoading||!e.canLoadEarlier||!e.isPinned||e.fillBlocked||e.pendingRevealWork||e.isLoadingOlder||!e.hasMessages||e.clientHeight<=0||e.scrollHeight>e.clientHeight+48),YB=e=>[`chat-timeline-auto-fill`,e.runtimeKey,e.sessionId,e.oldestMessageId,e.messageCount,e.canLoadEarlier],XB=e=>[`chat-timeline-load-earlier`,e.runtimeKey,e.sessionId],ZB=20,QB=4,$B=80,eV=new WeakMap,tV=new WeakMap,nV=e=>{let t=tV.get(e)??{generation:0};return t.generation+=1,tV.set(e,t),t.generation},rV=e=>{let t=eV.get(e);t&&(t.touches=0,t.pending=null,t.settleScheduled=!1),nV(e)},iV=e=>{aV(e)},aV=e=>{let t=eV.get(e);if(t)return t;let n={touches:0,pending:null,settleScheduled:!1};e.addEventListener(`touchstart`,()=>{n.touches+=1},{passive:!0});let r=()=>{n.touches=Math.max(0,n.touches-1),n.touches===0&&n.pending&&oV(e,n)};return e.addEventListener(`touchend`,r,{passive:!0}),e.addEventListener(`touchcancel`,r,{passive:!0}),eV.set(e,n),n},oV=(e,t)=>{t.settleScheduled||typeof window>`u`||(t.settleScheduled=!0,window.requestAnimationFrame(()=>{t.settleScheduled=!1;let n=t.pending;t.pending=null,!(!n||t.touches>0||!e.isConnected)&&(Math.abs(e.scrollTop-n.anchorTop)>n.delta+$B||sV(e,n.anchorTop+n.delta))}))},sV=(e,t)=>{let n=nV(e),r=e.style.overflow;if(e.style.overflow=`hidden`,e.scrollTop=t,e.scrollHeight,e.style.overflow=r,e.scrollTop=t,typeof window>`u`)return;let i=!1,a=0,o=()=>{i=!0};e.addEventListener(`touchstart`,o,{passive:!0,once:!0});let s=()=>{if(!i){if((tV.get(e)?.generation??0)!==n){e.removeEventListener(`touchstart`,o);return}e.scrollTop<t-QB&&(e.scrollTop=t),a+=1,a<ZB?window.requestAnimationFrame(s):e.removeEventListener(`touchstart`,o)}};window.requestAnimationFrame(s)},cV=(e,t,n)=>{let r=aV(e);if(r.touches>0&&typeof n==`number`&&n>0){r.pending=r.pending?{anchorTop:r.pending.anchorTop,delta:r.pending.delta+n}:{anchorTop:e.scrollTop,delta:n};return}r.pending=null,sV(e,t)},lV=(e,t,n)=>!e||!t||t===e?!1:n.some(t=>t.info.id===e),uV=(e,t)=>e.scrollHeight===t.scrollHeight&&e.clientHeight===t.clientHeight?e:t,dV=({sessionId:e,directory:t=null,messages:n,historyMeta:r,scrollRef:i,messageListRef:a,loadMoreMessages:o,goToBottom:s,releaseAutoFollow:c,beginHistoryViewportPreservation:l,endHistoryViewportPreservation:d,isPinned:f,showScrollButton:p,isMobile:m,autoFillEnabled:h=!1,onWillLoadEarlier:g})=>{let _=Q.useRef(m),v=Q.useRef(h);_.current=m,v.current=h;let y=Q.useRef(null),b=Q.useRef(null),x=Q.useMemo(()=>{let t=e??``,r=t?LB.get(t):void 0;if(r&&r.messages===n)return BB(t,r),y.current=r.model,b.current=n,r.model;let i=iB(y.current,b.current,n)??aB(n);return y.current=i,b.current=n,t&&n.length>0&&BB(t,{messages:n,model:i}),i},[n,e]),[S,C]=Q.useState(!1),[w,T]=Q.useState(!1),[E,D]=Q.useState(null),[O,k]=Q.useState(!1),[A,j]=Q.useState(null),[M,N]=Q.useState({scrollHeight:0,clientHeight:0}),P=Q.useRef(x),F=Q.useRef(f),I=Q.useRef(S),L=Q.useRef(w),R=Q.useRef(e),z=Q.useRef(t??null),B=Q.useRef(n),V=Q.useRef(r),H=Q.useRef(A),ee=Q.useRef([]),U=Q.useRef(null),te=Q.useRef(null),W=Q.useRef(!1),ne=Q.useRef(null),[G,re]=Q.useState(e);G!==e&&(re(e),ne.current!==null&&typeof window<`u`&&(window.clearTimeout(ne.current),ne.current=null),W.current=!1,I.current=!1,te.current=null,C(!1),T(!1),D(null),k(!1),H.current=null,j(null),N({scrollHeight:0,clientHeight:0}));let ie=Q.useMemo(()=>{let e=r?.limit!==A&&UB(r,n.length);return{hasBufferedTurns:!1,hasMoreAboveTurns:e,historyLoading:!!r?.loading,canLoadEarlier:e}},[r,n.length]),K=Q.useRef(ie);P.current=x,F.current=f,L.current=w,K.current=ie,R.current=e,z.current=t??null,B.current=n,V.current=r,H.current=A;let ae=J(()=>{W.current=!0,ne.current!==null&&typeof window<`u`&&(window.clearTimeout(ne.current),ne.current=null)}),oe=J(()=>{if(typeof window>`u`){W.current=!1;return}ne.current!==null&&window.clearTimeout(ne.current),ne.current=window.setTimeout(()=>{ne.current=null,W.current=!1},kB)}),se=J(()=>{let e=ee.current;e.length!==0&&(ee.current=[],e.forEach(e=>e()))}),ce=J(()=>new Promise(e=>{if(typeof window>`u`){e();return}let t=!1,n=()=>{t||(t=!0,window.clearTimeout(r),e())};ee.current.push(n);let r=window.setTimeout(n,OB)})),le=J(e=>{let t=U.current;t&&(U.current=null,t.resolve(e))}),ue=J(()=>{let e=U.current;if(e){if(e.sessionId!==R.current){le(!1);return}if(e.kind===`turn`?a.current?.scrollToTurnId(e.id,{behavior:e.behavior})??!1:a.current?.scrollToMessageId(e.id,{behavior:e.behavior})??!1){e.turnId&&(te.current={turnId:e.turnId,expiresAt:Date.now()+IB},D(e.turnId)),le(!0);return}typeof(e.kind===`turn`?P.current.turnIndexById.get(e.id):P.current.messageToTurnIndex.get(e.id))==`number`&&le(!1)}}),de=Q.useRef(null),fe=J(()=>{let e=de.current;e&&(de.current=null,e.dispose())});Ht(()=>{ne.current!==null&&typeof window<`u`&&(window.clearTimeout(ne.current),ne.current=null),fe(),se(),le(!1)});let pe=n;Gt(()=>{se(),ue()},[pe]);let me=J(()=>{let e=i.current;if(!e){N(e=>uV(e,{scrollHeight:0,clientHeight:0}));return}N(t=>uV(t,{scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}))});Vt(typeof ResizeObserver<`u`?i:null,me),Gt(()=>{me()},[e,S]);let he=Q.useRef(null),ge=J(()=>a.current?.captureViewportAnchor()??null),_e=J(e=>a.current?.restoreViewportAnchor(e)??!1),ve=J(()=>{if(yr())return;fe();let e=i.current;if(!e)return;let t=ge();t&&(de.current=yB({container:e,anchor:t}))}),ye=Q.useRef(null);Gt(()=>{if(!yr())return;let e=i.current;e&&(iV(e),rV(e))},[e,i]),Gt(()=>{fe(),he.current=null,ye.current=null,a.current?.cancelViewportAnchorHold()},[e]),Gt(()=>{let e=i.current;if(!e)return;let t=he.current;t&&Math.abs(e.scrollTop-t.top)>qB&&(he.current=null,t=null);let n=ye.current,r=pe[0]?.info?.id??null,o=pe[pe.length-1]?.info?.id??null,c=n?VB({previousOldestId:n.oldestId,previousNewestId:n.newestId,currentOldestId:r,currentNewestId:o})||lV(n.oldestId,r,pe):!1;t&&t.sessionId!==R.current&&(he.current=null,t=null);let l=t?VB({previousOldestId:t.oldestId,previousNewestId:t.newestId,currentOldestId:r,currentNewestId:o})||lV(t.oldestId,r,pe):!1,u=c||l,d=e=>{ye.current={oldestId:r,newestId:o,scrollHeight:e??ye.current?.scrollHeight??0}};if(F.current&&!t){fe(),u?(he.current=null,s(`instant`),d(e.scrollHeight)):d();return}let f=HB(a.current?.isHistoryVirtualized()??!1);if(t){if(f.owner===`tanstack-core`){a.current?.cancelViewportAnchorHold();let e=t.anchor;e&&_e(e),d();return}let n=e.scrollHeight,r=n-t.height;if(yr()){r>0&&cV(e,t.top+r,r),d(n);return}let i=t.anchor;!(i&&_e(i))&&r>0&&(e.scrollTop=t.top+r),d(n);return}if(c&&n&&f.owner===`controller`){let t=e.scrollHeight,r=t-n.scrollHeight;if(r>0){let t=e.scrollTop+r;yr()?cV(e,t,r):e.scrollTop=t}d(t),ve();return}d()},[pe,s]);let be=J(async()=>!1),xe=J(async e=>{let t=Date.now(),n=t+AB,r=z.current,i=r?Ha()?.getRequestState?.(En(r,e)):void 0;for(K.current.historyLoading,V.current,i?.status,i?.error;K.current.historyLoading;){if(R.current!==e)return Date.now()-t,`switched`;if(Date.now()>=n){let n=r?Ha()?.getRequestState?.(En(r,e)):void 0;return console.error(`[chat-history] historyLoading wait timed out — sync flag still true`,{sessionId:e,directory:r,elapsedMs:Date.now()-t,waitMs:AB,hostTurnPageTimeoutMs:mr,historyLoading:K.current.historyLoading,historyMeta:V.current,requestStatusAtStart:i?.status??null,requestStatusAtTimeout:n?.status??null,requestErrorAtTimeout:n?.error??null,likelyStaleLoadingFlag:n?.status===`ready`||n?.status===`error`||n==null}),`timeout`}await new Promise(e=>{if(typeof window>`u`){e();return}window.setTimeout(e,jB)})}return Date.now()-t,r&&Ha()?.getRequestState?.(En(r,e))?.status,R.current===e?`cleared`:`switched`}),Se=J(async e=>{if(!R.current||I.current||!K.current.hasMoreAboveTurns)return!1;I.current=!0,ae(),C(!0);let t=R.current,n=null,r=!!e.userInitiated;r&&l();let s=()=>{n&&he.current===n&&(he.current=null,a.current?.cancelViewportAnchorHold()),r&&(r=!1,d())};try{if(K.current.historyLoading){if(!e.userInitiated)return!1;let n=await xe(t);if(n===`timeout`)throw PB();if(n===`switched`||!K.current.hasMoreAboveTurns)return!1}if(!R.current||R.current!==t)return!1;let r=i.current,a=B.current,c=a.length,l=a[0]?.info?.id??null,u=V.current?.limit??dB().HISTORICAL_MESSAGES;e.preserveViewport&&r&&(n={sessionId:R.current,height:r.scrollHeight,top:r.scrollTop,anchor:ge(),oldestId:l,newestId:a[a.length-1]?.info?.id??null},he.current=n,ve());let d=c,f=l,p=u,m=0;for(;;){if(K.current.historyLoading)if(e.userInitiated){let e=await xe(t);if(e===`timeout`)throw s(),PB();if(e===`switched`)return s(),!1}else return s(),!1;let n=i.current?.scrollHeight??0,r=d,a=f,c=p;if(await o(t,`up`),m+=1,R.current!==t)return s(),!1;await ce();let l=B.current,u=l.length,h=l[0]?.info?.id??null,g=V.current?.limit??p,_=GB({scrollHeightBefore:n,scrollHeightAfter:i.current?.scrollHeight??n,messageCountBefore:r,messageCountAfter:u,oldestIdBefore:a,oldestIdAfter:h,limitBefore:c,limitAfter:g,hasMoreAbove:K.current.hasMoreAboveTurns,pagesLoaded:m,maxPages:KB});if(_===`continue`){d=u,f=h,p=g;continue}if(_===`stop-no-growth`){if(K.current.historyLoading){if(e.userInitiated){let e=await xe(t);if(e===`timeout`)throw s(),PB();if(e===`switched`)return s(),!1;--m;continue}return s(),!1}let n=V.current?.limit??c;return H.current=n,j(n),K.current={...K.current,hasMoreAboveTurns:!1,canLoadEarlier:!1},s(),!1}return!0}}catch(e){throw s(),e}finally{I.current=!1,C(!1),oe(),ce().then(s)}}),{t:Ce}=Yt(),we=At({mutationKey:XB({runtimeKey:u(),sessionId:e??``}),mutationFn:async e=>{if(R.current!==e.sessionId)return!1;ae(),e.userInitiated&&c();try{return await Se({preserveViewport:!0,userInitiated:!!e.userInitiated})}finally{oe()}}}),Te=J(async e=>{let t=R.current;if(t&&!(we.isPending&&we.variables?.sessionId===t)){e?.userInitiated&&g?.();try{let n=await we.mutateAsync({sessionId:t,userInitiated:!!e?.userInitiated});if(n===!1&&K.current.canLoadEarlier){let r={sessionId:t,grew:n,userInitiated:!!e?.userInitiated,canLoadEarlier:K.current.canLoadEarlier,hasMoreAboveTurns:K.current.hasMoreAboveTurns,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null};FB(`no-growth`,Error(`chat history pagination returned no growth`),r),e?.userInitiated&&ro.error(Ce(`chat.history.loadOlderFailed`))}}catch(n){let r={sessionId:t,userInitiated:!!e?.userInitiated,waitMs:AB,hostTurnPageTimeoutMs:mr,canLoadEarlier:K.current.canLoadEarlier,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null};NB(n)?FB(`timeout`,n,r):FB(`failed`,n,r),e?.userInitiated&&ro.error(NB(n)?Ce(`chat.history.loadOlderTimeout`):Ce(`chat.history.loadOlderFailed`))}}}),Ee=we.isPending&&we.variables?.sessionId===e||S,De=n[0]?.info?.id??null,Oe=JB({enabled:h,isMobile:m,sessionReady:!!e,messageReady:n.length>0||!!r,historyLoading:ie.historyLoading,canLoadEarlier:ie.canLoadEarlier,isPinned:f,fillBlocked:O,scrollHeight:M.scrollHeight,clientHeight:M.clientHeight,pendingRevealWork:w,isLoadingOlder:!1,hasMessages:n.length>0});jt({queryKey:YB({runtimeKey:u(),sessionId:e??``,oldestMessageId:De,messageCount:n.length,canLoadEarlier:ie.canLoadEarlier}),enabled:!!e&&Oe,staleTime:1/0,gcTime:0,retry:(e,t)=>t?.code===`auto-fill-busy`&&e<40,retryDelay:50,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,queryFn:async()=>{if(!v.current||_.current)return{status:`skip`};let e=R.current;if(!e)return{status:`skip`};if(K.current.historyLoading||I.current){let e=Error(`auto-fill-busy`);throw e.code=`auto-fill-busy`,e}if(!K.current.canLoadEarlier)return{status:`skip`};let t=i.current;if(!t||t.clientHeight<=0)return{status:`skip`};if(t.scrollHeight>t.clientHeight+48)return{status:`tall`};try{let t=await Se({preserveViewport:!0});return t?{status:`grew`}:(K.current.canLoadEarlier&&FB(`no-growth`,Error(`chat history pagination returned no growth`),{sessionId:e,source:`auto-fill`,grew:t,canLoadEarlier:K.current.canLoadEarlier,hasMoreAboveTurns:K.current.hasMoreAboveTurns,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null}),k(!0),{status:`blocked`})}catch(t){if(t?.code===`auto-fill-busy`)throw t;let n={sessionId:e,source:`auto-fill`,waitMs:AB,canLoadEarlier:K.current.canLoadEarlier,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null};throw NB(t)?FB(`timeout`,t,n):FB(`failed`,t,n),k(!0),t instanceof Error?t:Error(`chat timeline auto-fill failed`)}}});let ke=J(e=>{let t=i.current;t&&WB({source:e,isMobile:_.current,isPinned:F.current,scrollTop:t.scrollTop,clientHeight:t.clientHeight,canLoadEarlier:K.current.canLoadEarlier,isLoadingOlder:I.current,pendingRevealWork:L.current})&&Te({userInitiated:!0})}),Ae=J(()=>{ke(`scroll`)}),je=J(()=>{ke(`upward-intent`)}),Me=J(async(t,n)=>{if(!t||!R.current)return!1;c(),T(!0);try{return R.current!==e||typeof P.current.turnIndexById.get(t)!=`number`?!1:!!await new Promise(r=>{U.current={sessionId:R.current??e??``,kind:`turn`,id:t,behavior:n?.behavior??`auto`,turnId:t,resolve:r},ue()})}finally{T(!1)}}),Ne=J(async(t,n)=>{if(!t||!R.current)return!1;c(),T(!0);try{if(R.current!==e)return!1;let r=P.current.messageToTurnId.get(t);return typeof P.current.messageToTurnIndex.get(t)==`number`&&!!await new Promise(i=>{U.current={sessionId:R.current??e??``,kind:`message`,id:t,behavior:n?.behavior??`auto`,turnId:r??null,resolve:i},ue()})}finally{T(!1)}}),Pe=J(async()=>{T(!1),I.current=!1,C(!1),a.current?.scrollToBottom(),s(`smooth`)}),Fe=J(async()=>{T(!1),I.current=!1,C(!1),a.current?.scrollToBottom(),s(`instant`)}),Ie=J(e=>{let t=te.current;if(t){if(e!==t.turnId&&Date.now()<t.expiresAt)return;te.current=null}D(e)});return{turnIds:x.turnIds,turnStart:0,renderedMessages:pe,historySignals:ie,isLoadingOlder:Ee,pendingRevealWork:w,activeTurnId:E,showScrollToBottom:p&&!w,turnWindowModel:x,loadEarlier:Te,revealBufferedTurns:be,resumeToBottom:Pe,resumeToBottomInstant:Fe,scrollToTurn:Me,scrollToMessage:Ne,handleHistoryScroll:Ae,handleHistoryUpwardIntent:je,captureViewportAnchor:ge,restoreViewportAnchor:_e,handleActiveTurnChange:Ie}},fV=({mutateSession:e,forkSession:t})=>({revert:e,fork:t}),pV=({open:e,onOpenChange:t,sessionID:n,directory:r,onScrollToMessage:i,onScrollByTurnOffset:a,onResumeToLatest:o,canLoadEarlier:s=!1,isLoadingEarlier:c=!1,onLoadEarlier:l,onRevertMessage:u})=>{let[d,f]=Q.useState(null),[p,m]=Q.useState(``),[h,g]=Q.useState(0),_=Q.useRef(!1),v=Q.useRef(0),y=J(async(e,n,r)=>{if(_.current)return;_.current=!0;let i=v.current+1;v.current=i,f({type:e,messageId:n});try{await r(),t(!1)}finally{v.current===i&&(_.current=!1,f(null))}});return n?(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsx)(po,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:(0,$.jsx)(mV,{open:e,onOpenChange:t,sessionID:n,directory:r,onScrollToMessage:i,onScrollByTurnOffset:a,onResumeToLatest:o,canLoadEarlier:s,isLoadingEarlier:c,onLoadEarlier:l,onRevertMessage:u,searchQuery:p,onSearchQueryChange:m,selectedIndex:h,onSelectedIndexChange:g,pendingAction:d,runPendingMessageAction:y})})}):null},mV=e=>{let t=(0,pd.c)(145),{open:n,onOpenChange:r,sessionID:i,directory:a,onScrollToMessage:o,onScrollByTurnOffset:s,onResumeToLatest:c,canLoadEarlier:l,isLoadingEarlier:u,onLoadEarlier:d,onRevertMessage:f,searchQuery:p,onSearchQueryChange:m,selectedIndex:h,onSelectedIndexChange:g,pendingAction:_,runPendingMessageAction:v}=e,{t:y}=Yt(),b=Zy(),x=i,S=ha(x??``,a),C=X(gV),w=X(_V),T;t[0]===b.capabilities?T=t[1]:(T=fV(b.capabilities),t[0]=b.capabilities,t[1]=T);let E=T,{isMobile:D,isTablet:O}=qs(),k=D||O,A;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(A=[],t[2]=A):A=t[2];let j=Q.useRef(A),M=Q.useRef(null),N=Q.useRef(null),P=Q.useRef(!1),F=Q.useRef(!1),I=vV,L=yV,R;t[3]===S?R=t[4]:(R=S.filter(bV).map(xV),t[3]=S,t[4]=R);let z=R,B;if(t[5]!==p||t[6]!==z){bb0:{let e=p.trim();if(!e){B=z;break bb0}let t=e.toLowerCase();B=z.filter(e=>{let{message:n}=e;return PR(n.parts).toLowerCase().includes(t)})}t[5]=p,t[6]=z,t[7]=B}else B=t[7];let V=B,H;t[8]!==V.length||t[9]!==g||t[10]!==p?(H=()=>{P.current||g(p.trim()?0:Math.max(0,V.length-1))},t[8]=V.length,t[9]=g,t[10]=p,t[11]=H):H=t[11];let ee;t[12]!==V||t[13]!==g||t[14]!==p?(ee=[V,p,g],t[12]=V,t[13]=g,t[14]=p,t[15]=ee):ee=t[15],Q.useEffect(H,ee);let U,te;t[16]===V.length?(U=t[17],te=t[18]):(U=()=>{j.current=j.current.slice(0,V.length)},te=[V.length],t[16]=V.length,t[17]=U,t[18]=te),Q.useEffect(U,te);let W,ne;t[19]===h?(W=t[20],ne=t[21]):(ne=()=>{P.current||j.current[h]?.scrollIntoView({block:`nearest`})},W=[h],t[19]=h,t[20]=W,t[21]=ne),Q.useEffect(ne,W);let G;t[22]===u?G=t[23]:(G=()=>{!P.current||N.current||u||(P.current=!1)},t[22]=u,t[23]=G);let re;t[24]!==V.length||t[25]!==u?(re=[V.length,u],t[24]=V.length,t[25]=u,t[26]=re):re=t[26],Q.useEffect(G,re);let ie,K;t[27]!==n||t[28]!==p?(ie=()=>{let e=F.current;if(F.current=n,!n||e||P.current||p.trim())return;let t=M.current;t&&(t.scrollTop=t.scrollHeight)},K=[n,p],t[27]=n,t[28]=p,t[29]=ie,t[30]=K):(ie=t[29],K=t[30]),Q.useLayoutEffect(ie,K);let ae;t[31]===u?ae=t[32]:(ae=()=>{let e=N.current,t=M.current;if(!e||!t||u)return;N.current=null;let n=j.current.find(t=>t?.dataset.timelineMessageId===e.messageId);if(!n)return;let r=n.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=r-e.top},t[31]=u,t[32]=ae);let oe;t[33]!==V.length||t[34]!==u?(oe=[V.length,u],t[33]=V.length,t[34]=u,t[35]=oe):oe=t[35],Q.useLayoutEffect(ae,oe);let se;t[36]===d?se=t[37]:(se=()=>{let e=M.current;if(e){let t=e.getBoundingClientRect().top,n=j.current.find(e=>e?e.getBoundingClientRect().bottom>=t:!1);n?.dataset.timelineMessageId&&(N.current={messageId:n.dataset.timelineMessageId,top:n.getBoundingClientRect().top-t})}P.current=!0,d?.()},t[36]=d,t[37]=se);let ce=J(se),le;t[38]!==r||t[39]!==o?(le=async e=>{await o?.(e)!==!1&&r(!1)},t[38]=r,t[39]=o,t[40]=le):le=t[40];let ue=J(le),de;t[41]!==V||t[42]!==ue||t[43]!==g||t[44]!==h?(de=e=>{let t=V.length;if(t!==0){if(e.key===`ArrowDown`){e.preventDefault(),g(e=>(e+1)%t);return}if(e.key===`ArrowUp`){e.preventDefault(),g(e=>(e-1+t)%t);return}if(e.key===`Enter`){e.preventDefault();let n=(h%t+t)%t,r=V[n];r&&ue(r.message.info.id)}}},t[41]=V,t[42]=ue,t[43]=g,t[44]=h,t[45]=de):de=t[45];let fe=J(de),pe;t[46]!==x||t[47]!==a||t[48]!==w||t[49]!==f||t[50]!==C||t[51]!==v?(pe=async(e,t)=>{x&&await v(e,t,async()=>{e===`revert`?f?await f(t):await C(x,t,{directory:a}):await w(x,t,{directory:a})})},t[46]=x,t[47]=a,t[48]=w,t[49]=f,t[50]=C,t[51]=v,t[52]=pe):pe=t[52];let me=J(pe),he;t[53]===Symbol.for(`react.memo_cache_sentinel`)?(he=(0,$.jsx)(Z,{name:`time`,className:`h-5 w-5`}),t[53]=he):he=t[53];let ge;t[54]===y?ge=t[55]:(ge=y(`chat.timeline.title`),t[54]=y,t[55]=ge);let _e;t[56]===ge?_e=t[57]:(_e=(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[he,ge]}),t[56]=ge,t[57]=_e);let ve;t[58]===y?ve=t[59]:(ve=y(`chat.timeline.description`),t[58]=y,t[59]=ve);let ye;t[60]===ve?ye=t[61]:(ye=(0,$.jsx)(ho,{children:ve}),t[60]=ve,t[61]=ye);let be;t[62]!==_e||t[63]!==ye?(be=(0,$.jsxs)(lo,{children:[_e,ye]}),t[62]=_e,t[63]=ye,t[64]=be):be=t[64];let xe;t[65]===Symbol.for(`react.memo_cache_sentinel`)?(xe=(0,$.jsx)(Z,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),t[65]=xe):xe=t[65];let Se;t[66]===y?Se=t[67]:(Se=y(`chat.timeline.searchPlaceholder`),t[66]=y,t[67]=Se);let Ce;t[68]===m?Ce=t[69]:(Ce=e=>m(e.target.value),t[68]=m,t[69]=Ce);let we;t[70]!==fe||t[71]!==p||t[72]!==Se||t[73]!==Ce?(we=(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[xe,(0,$.jsx)(Ko,{autoFocus:!0,placeholder:Se,value:p,onChange:Ce,onKeyDown:fe,className:`pl-9 w-full`})]}),t[70]=fe,t[71]=p,t[72]=Se,t[73]=Ce,t[74]=we):we=t[74];let Te;t[75]!==l||t[76]!==ce||t[77]!==u||t[78]!==d||t[79]!==y?(Te=l&&d&&(0,$.jsx)(`div`,{className:`flex justify-center py-1`,children:(0,$.jsxs)(Qt,{type:`button`,variant:`link`,size:`sm`,onClick:ce,disabled:u,className:`h-auto px-1 py-0 text-muted-foreground hover:text-foreground`,children:[u&&(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}),y(`chat.history.loadOlder`)]})}),t[75]=l,t[76]=ce,t[77]=u,t[78]=d,t[79]=y,t[80]=Te):Te=t[80];let Ee;t[81]!==E.fork||t[82]!==E.revert||t[83]!==k||t[84]!==V||t[85]!==me||t[86]!==ue||t[87]!==g||t[88]!==_||t[89]!==p||t[90]!==h||t[91]!==y?(Ee=V.length===0?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:y(p?`chat.timeline.empty.search`:`chat.timeline.empty.session`)}):V.map((e,t)=>{let{message:n}=e,r=FR(n.parts),i=n.info.time.created,a=I(i),o=V[t-1],s=a!==(o?I(o.message.info.time.created):null),c=L(i),l=t===h,u=p.trim()?hV(PR(n.parts),p):null;return(0,$.jsxs)(Q.Fragment,{children:[s&&(0,$.jsxs)(`div`,{className:`sticky top-0 z-10 flex items-center gap-3 bg-background/95 py-2 backdrop-blur-sm`,children:[(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border/60`}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a}),(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border/60`})]}),(0,$.jsxs)(`div`,{ref:e=>{j.current[t]=e},"data-timeline-message-id":n.info.id,className:Y(`group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,l&&`bg-interactive-selection text-interactive-selection-foreground`),onClick:()=>void ue(n.info.id),onMouseEnter:()=>g(t),children:[(0,$.jsx)(`span`,{className:Y(`typography-meta w-16 flex-shrink-0 text-right tabular-nums`,l?`text-interactive-selection-foreground/70`:`text-muted-foreground`),children:c}),(0,$.jsxs)(`p`,{className:Y(`flex-1 min-w-0 typography-micro truncate`,l?`text-interactive-selection-foreground`:`text-foreground`),children:[u??(r||y(`chat.timeline.noTextContent`)),!u&&r&&r.length>=80&&`…`]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:(0,$.jsxs)(`div`,{className:Y(`gap-1`,k?`flex`:`hidden group-hover:flex`),children:[E.revert?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":_?.type===`revert`&&_.messageId===n.info.id,disabled:_!==null,onClick:e=>{e.stopPropagation(),me(`revert`,n.info.id)},children:(0,$.jsx)(Z,{name:_?.type===`revert`&&_.messageId===n.info.id?`loader-4`:`arrow-go-back`,className:Y(`h-4 w-4`,_?.type===`revert`&&_.messageId===n.info.id&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:y(`chat.timeline.actions.revertFromHere`)})]}):null,E.fork?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":_?.type===`fork`&&_.messageId===n.info.id,onClick:e=>{e.stopPropagation(),me(`fork`,n.info.id)},disabled:_!==null,children:_?.type===`fork`&&_.messageId===n.info.id?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(Z,{name:`git-branch`,className:`h-4 w-4`})})}),(0,$.jsx)(Jo,{sideOffset:6,children:y(`chat.timeline.actions.forkFromHere`)})]}):null]})})]})]},n.info.id)}),t[81]=E.fork,t[82]=E.revert,t[83]=k,t[84]=V,t[85]=me,t[86]=ue,t[87]=g,t[88]=_,t[89]=p,t[90]=h,t[91]=y,t[92]=Ee):Ee=t[92];let De;t[93]===Ee?De=t[94]:(De=(0,$.jsx)(`div`,{ref:M,className:`flex-1 overflow-y-auto`,children:Ee}),t[93]=Ee,t[94]=De);let Oe;t[95]===y?Oe=t[96]:(Oe=y(`chat.timeline.actions.title`),t[95]=y,t[96]=Oe);let ke;t[97]===Oe?ke=t[98]:(ke=(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:Oe}),t[97]=Oe,t[98]=ke);let Ae;t[99]!==r||t[100]!==s?(Ae=()=>{s?.(-1),r(!1)},t[99]=r,t[100]=s,t[101]=Ae):Ae=t[101];let je;t[102]===y?je=t[103]:(je=y(`chat.timeline.actions.previousTurn`),t[102]=y,t[103]=je);let Me;t[104]!==Ae||t[105]!==je?(Me=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Ae,children:je}),t[104]=Ae,t[105]=je,t[106]=Me):Me=t[106];let Ne;t[107]===Symbol.for(`react.memo_cache_sentinel`)?(Ne=(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),t[107]=Ne):Ne=t[107];let Pe;t[108]!==r||t[109]!==c?(Pe=()=>{c?.(),r(!1)},t[108]=r,t[109]=c,t[110]=Pe):Pe=t[110];let Fe;t[111]===y?Fe=t[112]:(Fe=y(`chat.timeline.actions.latest`),t[111]=y,t[112]=Fe);let Ie;t[113]!==Pe||t[114]!==Fe?(Ie=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Pe,children:Fe}),t[113]=Pe,t[114]=Fe,t[115]=Ie):Ie=t[115];let Le;t[116]!==Me||t[117]!==Ie?(Le=(0,$.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[Me,Ne,Ie]}),t[116]=Me,t[117]=Ie,t[118]=Le):Le=t[118];let Re;t[119]===y?Re=t[120]:(Re=y(`chat.timeline.help.clickMessage`),t[119]=y,t[120]=Re);let ze;t[121]===Re?ze=t[122]:(ze=(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,$.jsx)(`span`,{children:Re})}),t[121]=Re,t[122]=ze);let Be;t[123]===Symbol.for(`react.memo_cache_sentinel`)?(Be=(0,$.jsx)(Z,{name:`arrow-go-back`,className:`h-4 w-4 flex-shrink-0`}),t[123]=Be):Be=t[123];let Ve;t[124]===y?Ve=t[125]:(Ve=y(`chat.timeline.help.undoToPoint`),t[124]=y,t[125]=Ve);let He;t[126]===Ve?He=t[127]:(He=(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[Be,(0,$.jsx)(`span`,{children:Ve})]}),t[126]=Ve,t[127]=He);let Ue;t[128]!==E.fork||t[129]!==y?(Ue=E.fork?(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`git-branch`,className:`h-4 w-4 flex-shrink-0`}),(0,$.jsx)(`span`,{children:y(`chat.timeline.help.createSessionFromHere`)})]}):null,t[128]=E.fork,t[129]=y,t[130]=Ue):Ue=t[130];let We;t[131]!==ze||t[132]!==He||t[133]!==Ue?(We=(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 typography-meta text-muted-foreground`,children:[ze,He,Ue]}),t[131]=ze,t[132]=He,t[133]=Ue,t[134]=We):We=t[134];let Ge;t[135]!==ke||t[136]!==Le||t[137]!==We?(Ge=(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[ke,Le,We]}),t[135]=ke,t[136]=Le,t[137]=We,t[138]=Ge):Ge=t[138];let Ke;return t[139]!==be||t[140]!==we||t[141]!==Te||t[142]!==De||t[143]!==Ge?(Ke=(0,$.jsxs)($.Fragment,{children:[be,we,Te,De,Ge]}),t[139]=be,t[140]=we,t[141]=Te,t[142]=De,t[143]=Ge,t[144]=Ke):Ke=t[144],Ke};function hV(e,t,n=30){let r=e.toLowerCase(),i=t.toLowerCase(),a=r.indexOf(i);if(a===-1)return null;let o=Math.max(0,a-n),s=Math.min(e.length,a+t.length+n);return`${o>0?`…`:``}${e.slice(o,s).replace(/\n/g,` `)}${s<e.length?`…`:``}`}function gV(e){return e.revertToMessage}function _V(e){return e.forkFromMessage}function vV(e){return xs(e)}function yV(e){return as(e)}function bV(e){return e.info.role===`user`}function xV(e){return{message:e}}var SV=e=>{let t=e.startsWith(`#`)?e.slice(1):e;if(!t)return null;let n=t.match(/^turn-(.+)$/);if(n?.[1])return{kind:`turn`,id:n[1]};let r=t.match(/^message-(.+)$/);return r?.[1]?{kind:`message`,id:r[1]}:null},CV=(e,t,n)=>{if(n===0||e.length===0)return{kind:`noop`};let r=t?e.indexOf(t):e.length-1,i=(r>=0?r:e.length-1)+n;if(i>=e.length)return{kind:`resume`};let a=e[Math.max(0,i)];return a?{kind:`turn`,turnId:a}:{kind:`noop`}},wV=e=>{if(typeof window>`u`)return;let t=e?`#${e}`:``,n=`${window.location.pathname}${window.location.search}${t}`;window.history.replaceState(window.history.state,``,n)},TV=e=>{let t=(0,pd.c)(29),{sessionId:n,turnIds:r,activeTurnId:i,scrollToTurn:a,scrollToMessage:o,resumeToBottom:s}=e,c=Q.useRef(r),l=Q.useRef(i),u,d;t[0]===r?(u=t[1],d=t[2]):(u=()=>{c.current=r},d=[r],t[0]=r,t[1]=u,t[2]=d),Q.useEffect(u,d);let f,p;t[3]===i?(f=t[4],p=t[5]):(f=()=>{l.current=i},p=[i],t[3]=i,t[4]=f,t[5]=p),Q.useEffect(f,p);let m;t[6]===a?m=t[7]:(m=async(e,t)=>e?(t?.updateHash!==!1&&wV(`turn-${e}`),a(e,{behavior:t?.behavior})):!1,t[6]=a,t[7]=m);let h=m,g;t[8]===o?g=t[9]:(g=async(e,t)=>e?(t?.updateHash!==!1&&wV(`message-${e}`),o(e,{behavior:t?.behavior})):!1,t[8]=o,t[9]=g);let _=g,v;t[10]!==s||t[11]!==h?(v=async(e,t)=>{let n=c.current,r=CV(n,l.current,e);if(r.kind===`noop`)return e===0;if(r.kind===`resume`){if(t?.resumePastEnd===!1){let e=n[n.length-1];return e?h(e,{behavior:`auto`}):!1}return wV(null),s(),!0}return h(r.turnId,{behavior:`auto`})},t[10]=s,t[11]=h,t[12]=v):v=t[12];let y=v,b;t[13]===s?b=t[14]:(b=()=>{wV(null),s()},t[13]=s,t[14]=b);let x=b,S;t[15]!==_||t[16]!==h||t[17]!==n?(S=()=>{if(!n||typeof window>`u`)return;let e=()=>{let e=SV(window.location.hash);if(e){if(e.kind===`turn`){h(e.id,{behavior:`auto`,updateHash:!1});return}_(e.id,{behavior:`auto`,updateHash:!1})}};return e(),window.addEventListener(`hashchange`,e),()=>{window.removeEventListener(`hashchange`,e)}},t[15]=_,t[16]=h,t[17]=n,t[18]=S):S=t[18];let C;t[19]!==_||t[20]!==h||t[21]!==n||t[22]!==r.length?(C=[n,_,h,r.length],t[19]=_,t[20]=h,t[21]=n,t[22]=r.length,t[23]=C):C=t[23],Q.useEffect(S,C);let w;return t[24]!==x||t[25]!==y||t[26]!==_||t[27]!==h?(w={scrollToTurnId:h,scrollToMessageId:_,scrollByTurnOffset:y,resumeToLatest:x},t[24]=x,t[25]=y,t[26]=_,t[27]=h,t[28]=w):w=t[28],w},EV=2e4,DV=6e4,OV=2e3,kV=e=>e?(typeof e.text==`string`?e.text.length:0)+(typeof e.state?.output==`string`?e.state.output.length:0):0,AV=e=>{if(e.length===0)return`0`;let t=e[e.length-1];if(!t)return`0`;let n=t.parts??[],r=n[n.length-1],i=0;for(let e of n)i+=kV(e);return[e.length,t.info.id,n.length,r?.id??``,r?.state?.status??``,i].join(`:`)},jV={sessionKey:null,fingerprint:null,lastMovementAt:null,lastRefreshAt:null,attempts:0},MV=(e,t)=>{let{sessionKey:n,working:r,streaming:i,fingerprint:a,now:o}=t;if(!n)return{state:jV,shouldRefresh:!1,stalledForMs:0};if(e.sessionKey!==n)return{state:{sessionKey:n,fingerprint:a,lastMovementAt:o,lastRefreshAt:null,attempts:0},shouldRefresh:!1,stalledForMs:0};if(e.fingerprint!==a)return{state:{...e,fingerprint:a,lastMovementAt:o,attempts:0},shouldRefresh:!1,stalledForMs:0};if(!r||i)return{state:{...e,lastMovementAt:o},shouldRefresh:!1,stalledForMs:0};let s=e.lastMovementAt??o,c=o-s,l=e.lastRefreshAt===null||o-e.lastRefreshAt>=t.cooldownMs,u=c>=t.thresholdMs&&l&&e.attempts<t.maxAttempts;return{state:{...e,lastMovementAt:s,lastRefreshAt:u?o:e.lastRefreshAt,attempts:u?e.attempts+1:e.attempts},shouldRefresh:u,stalledForMs:c}},NV=e=>{console.warn(`[transcript] tail frozen while session is working — refetching authority`,e)};function PV(e){return!!(e.active&&e.sessionId&&e.sessionKey&&e.sessionIsWorking)}function FV(e){return e===jV?e:jV}function IV(e){let t=e.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!t)return null;let n=[],r=t[1],i=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g,a;for(;(a=i.exec(r))!==null;)n.push({question:a[1],answer:a[2]});return n.length>0?n:null}function LV(e){if(typeof e.id==`string`&&e.id)return e.id;if(typeof e.callID==`string`&&e.callID)return e.callID;let t=e.state;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.callID;if(typeof e==`string`&&e)return e}return null}function RV(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(t.type!==`tool`||t.tool!==`question`)return!1;let n=t.state&&typeof t.state==`object`&&!Array.isArray(t.state)?t.state:{},r=typeof n.status==`string`?n.status:void 0;if(r===`error`)return!1;if(r===`pending`||r===`running`||r===void 0)return!0;if(r!==`completed`)return!1;let i=typeof n.output==`string`?n.output:``;return!i||IV(i)==null}function zV(e){let t=[];for(let n of e){let e=Array.isArray(n.parts)?n.parts:[];for(let n of e){if(!RV(n))continue;let e=LV(n);e&&t.push(e)}}return t}function BV(e,t){return`${e}:${t.join(`,`)}`}function VV(e){let t=e.sessionId?.trim()??``,n=e.directory?.trim()??``;if(!t||!n||e.sessionQuestionCount>0||e.unansweredToolIds.length===0)return{recover:!1,attemptKey:null};let r=BV(t,e.unansweredToolIds);return e.attemptedKey===r?{recover:!1,attemptKey:r}:{recover:!0,attemptKey:r}}function HV(e,t,n,r){let i=(0,pd.c)(7),a=Kr(),o=Q.useRef(null),s=Q.useRef(`${e??``}:${t??``}`),c,l;i[0]!==a||i[1]!==t||i[2]!==n||i[3]!==e||i[4]!==r?(c=()=>{let i=`${e??``}:${t??``}`;s.current!==i&&(o.current=null,s.current=i);let c=VV({sessionId:e,directory:t,sessionQuestionCount:r,unansweredToolIds:zV(n),attemptedKey:o.current});if(!c.recover||!e||!t||!c.attemptKey)return;let l=a.getChild(t);l&&(o.current=c.attemptKey,Pn(t,l,[e]))},l=[e,t,n,r,a],i[0]=a,i[1]=t,i[2]=n,i[3]=e,i[4]=r,i[5]=c,i[6]=l):(c=i[5],l=i[6]),Q.useEffect(c,l)}var UV=e=>!Number.isFinite(e)||e<0?0:Math.ceil(e),WV=(e,t)=>({...e,key:GV(e),estimatedBytes:UV(t)}),GV=({runtimeKey:e,sessionId:t,directory:n})=>JSON.stringify([e,n??``,t]),KV=e=>({key:e?GV(e):null,selection:e}),qV=(e,t,n)=>{let r=Math.max(1,Math.floor(n.maxEntries)),i=Math.max(0,n.maxEstimatedBytes),a=e.reduce((e,t)=>e+t.estimatedBytes,0);if(e.length<=r&&a<=i)return e;let o=[...e];for(;o.length>r||a>i;){let e=o.findIndex(e=>e.key!==t);if(e===-1)break;let[n]=o.splice(e,1);a-=n?.estimatedBytes??0}return o},JV=(e,t,n,r)=>{let i=GV(t),a=e.findIndex(e=>e.key===i),o=a>=0?e[a]:void 0;if(o&&a===e.length-1)return qV(e,i,n);let s=o||WV(t,r),c=a>=0?e.filter((e,t)=>t!==a):[...e];return c.push(s),qV(c,i,n)},YV=(e,t,n)=>{let r=UV(n),i=e.findIndex(e=>e.key===t);return i===-1||e[i].estimatedBytes===r?e:e.map((e,t)=>t===i?{...e,estimatedBytes:r}:e)},XV=(e,t)=>t&&e.some(e=>e.key===t)?t:null,ZV=(e,t,n)=>{let r=t.key?e.cachedSessionViews.find(e=>e.key===t.key):void 0,i=r&&t.selection?JV(e.cachedSessionViews,t.selection,n,r.estimatedBytes):qV(e.cachedSessionViews,t.key??``,n),a=!r&&e.pendingSessionView?.intent===t?e.pendingSessionView:null;return e.activeIntent===t&&!e.cacheNeedsTrim&&i===e.cachedSessionViews&&a===e.pendingSessionView?e:{activeIntent:t,cacheNeedsTrim:!1,cachedSessionViews:i,pendingSessionView:a}},QV=(e,t,n,r)=>{if(n!==t||e.activeIntent!==t||!t.selection||e.cachedSessionViews.some(e=>e.key===t.key))return e;let i={entry:WV(t.selection,r),intent:t};return e.pendingSessionView?.intent===t?e:{activeIntent:e.activeIntent,cacheNeedsTrim:e.cacheNeedsTrim,cachedSessionViews:e.cachedSessionViews,pendingSessionView:i}},$V=(e,t,n)=>{let r=e.pendingSessionView;return e.activeIntent!==t||r?.intent!==t||!t.selection?e:{activeIntent:e.activeIntent,cacheNeedsTrim:!1,cachedSessionViews:JV(e.cachedSessionViews,t.selection,n,r.entry.estimatedBytes),pendingSessionView:null}},eH=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},tH=e=>{if(!(!e.info||typeof e.info!=`object`))return e.info},nH=e=>tH(e)?.role===`assistant`,rH=(e,t)=>{let n=tH(t);n&&(e.agentName??=eH(n.agent),e.providerId??=eH(n.providerID),e.modelId??=eH(n.modelID))},iH=e=>!!(e.agentName&&e.providerId&&e.modelId),aH=e=>{let t={};for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||!nH(r))&&(rH(t,r),iH(t)))return t}for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||nH(r))&&(rH(t,r),iH(t)))break}return t},oH=e=>!!e.sessionId&&!(e.hasRenderableSessionSnapshot&&e.hasCurrentSessionEntity),sH=[],cH=[],lH={type:`idle`},uH=`openchamber:chat-force-scroll-bottom`,dH=()=>void 0,fH=`Quota limit reached. Retrying automatically.`,pH=1048576,mH=pH,hH=20,gH=pH,_H=16*pH,vH={maxEntries:3,maxEstimatedBytes:32*pH},yH={maxEntries:2,maxEstimatedBytes:32*pH},bH=e=>i(()=>e()),xH={overflowAnchor:`none`,overscrollBehavior:`contain`,overscrollBehaviorY:`contain`},SH={scrollbar:`chat`,scrollShadow:`true`,orientation:`vertical`},CH=()=>{let e=(0,pd.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsx)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-full z-0 h-11 bg-gradient-to-t from-[var(--surface-background)] to-transparent`}),e[0]=t):t=e[0],t},wH=`calc(max(0.625rem, var(--oc-safe-area-top, 0px)) + var(--oc-mobile-detail-navigation-height) + 1.25rem)`,TH=lz,EH=[`a[href]`,`button`,`input`,`select`,`textarea`,`[contenteditable="true"]`,`[role="button"]`,`[role="combobox"]`,`[role="dialog"]`,`[role="listbox"]`,`[role="menu"]`,`[role="menuitem"]`,`[role="option"]`,`[role="textbox"]`,`[data-radix-popper-content-wrapper]`].join(`,`),DH=e=>e instanceof HTMLElement,OH=e=>DH(e)?!!e.closest(EH):!1,kH=(e,t)=>typeof document>`u`||!e||e===document.body||e===document.documentElement||OH(e)?!0:!t?.contains(e),AH=()=>{let{isAboutDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isImagePreviewOpen:r,isMultiRunLauncherOpen:i,isSessionSwitcherOpen:a,isSettingsDialogOpen:o}=q.getState();return e||t||n||r||i||a||o},jH=Q.memo(({currentSessionId:e,virtualizerKey:t,isDesktopExpandedInput:n,isMobile:r,stickyUserHeader:i,directory:a,scrollRef:o,messageListRef:s,pendingRevealWork:c,initialPinRevealComplete:l=!1,renderedMessages:u,isLoadingOlder:d,sessionIsWorking:f,streamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,handleMessageContentChange:g,getAnimationHandlers:_,handleHistoryScroll:v,handleHistoryUpwardIntent:y,onTimelineIsAtEndChange:b,timelineFollowSuspended:x,timelineHistoryAnchorToken:S,scrollToBottom:C,sessionQuestions:w,sessionPermissions:T,isProgrammaticFollowActive:E,showLoadOlderButton:D,onLoadOlder:O,turnIds:k,activeTurnId:A,onSelectTurn:j,showPromptNavigator:M,canLoadEarlierPrompts:N,isLoadingOlderPrompts:P,onLoadEarlierPrompts:F,transcriptStatusRow:I})=>{let{t:L}=Yt(),R=hl(e=>e.legendTimelineEnabled),z=uT({isLoadingOlder:d}),B=dT({isMobile:r,isLoadingOlder:z}),V=Q.useRef(new Map),H=Q.useRef(new WeakMap),ee=Q.useRef(new Map),U=Q.useMemo(()=>{let e=new Map;for(let t=0;t<u.length;t+=1){let n=u[t];if(n.info.role!==`user`)continue;if(LI(n)){let r=zI(u,t)??``,i=ee.current.get(n.info.id);if(i&&i.command===r)e.set(n.info.id,i.parts);else{let t=[{type:`text`,text:r?`$ ${r}`:`/shell`}];ee.current.set(n.info.id,{command:r,parts:t}),e.set(n.info.id,t)}continue}if(Vn(n.parts))continue;let r=H.current.get(n.parts);r||(r=_n(n.parts),H.current.set(n.parts,r)),r.length!==0&&e.set(n.info.id,r)}let t=V.current;if(t.size===e.size){let n=!0;for(let[r,i]of e)if(t.get(r)!==i){n=!1;break}if(n)return t}return V.current=e,e},[u]),te=Q.useMemo(()=>k.filter(e=>U.has(e)),[U,k]),W=Q.useMemo(()=>{if(!A||U.has(A))return A;let e=k.indexOf(A);for(let t=e-1;t>=0;--t){let e=k[t];if(U.has(e))return e}return null},[A,U,k]),ne=J(e=>{e.defaultPrevented||OH(e.target)||typeof window<`u`&&window.getSelection()?.type===`Range`||o.current?.focus({preventScroll:!0})});return Xu({scrollRef:o,enabled:R,onUpwardIntent:y}),R?(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(sR,{ref:s,sessionKey:e,virtualizerKey:t,disableStaging:c,initialPinRevealComplete:l,messages:u,sessionIsWorking:f,activeStreamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,onMessageContentChange:g,getAnimationHandlers:_,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:a,timelineScrollClassName:`absolute inset-0 z-0 chat-scroll overlay-scrollbar-target`,timelineScrollStyle:xH,timelineScrollDataset:SH,timelineOnScroll:v,timelineFollowEnabled:!c&&!x,timelineHistoryAnchorToken:S,timelineOnIsAtEndChange:b,headerSlot:(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:wH},"aria-hidden":`true`}),D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(Qt,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})})]}),footerSlot:(0,$.jsxs)($.Fragment,{children:[(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(NR,{question:e},e.id)),T.map(e=>(0,$.jsx)(ER,{permission:e},e.id))]}),I?(0,$.jsx)(`div`,{className:`mb-1`,children:I}):null,(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?TH:sz},"aria-hidden":`true`})]})}),(0,$.jsx)(Js,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(nz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})}):(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(xl,{className:Y(`absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target`),ref:o,style:xH,observeMutations:!1,hideTopShadow:r&&i,hideBottomShadow:r,tabIndex:0,onClick:ne,onScroll:v,"data-scroll-shadow":`true`,"data-scrollbar":`chat`,children:(0,$.jsxs)(`div`,{className:Y(`oc-chat-scroll-content relative z-0 min-h-full`,r&&`chat-scroll-foot-inset`),children:[D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(Qt,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})}),(0,$.jsx)(sR,{ref:s,sessionKey:e,virtualizerKey:t,disableStaging:c,initialPinRevealComplete:l,messages:u,sessionIsWorking:f,activeStreamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,onMessageContentChange:g,getAnimationHandlers:_,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:a,liveStatusSlot:u.length>0?(0,$.jsx)(`div`,{className:`mb-1`,children:I??(0,$.jsx)(RN,{})}):null}),(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(NR,{question:e},e.id)),T.map(e=>(0,$.jsx)(ER,{permission:e},e.id))]}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?cz:sz},"aria-hidden":`true`})]})}),(0,$.jsx)(Js,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(nz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.virtualizerKey===t.virtualizerKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.stickyUserHeader===t.stickyUserHeader&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.initialPinRevealComplete===t.initialPinRevealComplete&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.handleHistoryUpwardIntent===t.handleHistoryUpwardIntent&&e.onTimelineIsAtEndChange===t.onTimelineIsAtEndChange&&e.timelineFollowSuspended===t.timelineFollowSuspended&&e.timelineHistoryAnchorToken===t.timelineHistoryAnchorToken&&e.scrollToBottom===t.scrollToBottom&&e.sessionQuestions===t.sessionQuestions&&e.sessionPermissions===t.sessionPermissions&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&e.onLoadOlder===t.onLoadOlder&&e.turnIds===t.turnIds&&e.activeTurnId===t.activeTurnId&&e.onSelectTurn===t.onSelectTurn&&e.showPromptNavigator===t.showPromptNavigator&&e.canLoadEarlierPrompts===t.canLoadEarlierPrompts&&e.isLoadingOlderPrompts===t.isLoadingOlderPrompts&&e.onLoadEarlierPrompts===t.onLoadEarlierPrompts&&e.transcriptStatusRow===t.transcriptStatusRow);jH.displayName=`ChatViewport`;var MH=[{id:1,toolRows:[{id:`search`,titleWidth:`w-24`,detailWidth:`w-52`},{id:`read`,titleWidth:`w-20`,detailWidth:`w-36`},{id:`edit`,titleWidth:`w-24`,detailWidth:`w-64`}],textWidths:[`w-24`,`w-[92%]`,`w-[78%]`]},{id:2,toolRows:[{id:`read`,titleWidth:`w-20`,detailWidth:`w-40`},{id:`search`,titleWidth:`w-24`,detailWidth:`w-48`}],textWidths:[`w-20`,`w-[88%]`,`w-[70%]`]},{id:3,toolRows:[{id:`shell`,titleWidth:`w-28`,detailWidth:`w-44`},{id:`edit`,titleWidth:`w-24`,detailWidth:`w-56`}],textWidths:[`w-24`,`w-[84%]`,`w-[64%]`]}],NH=e=>Xt(e.path),PH=(e,t)=>{if(!t)return e;let n=e.indexOf(t);return n===-1?e:(0,$.jsxs)($.Fragment,{children:[e.slice(0,n),(0,$.jsx)(`span`,{className:`font-medium`,children:t}),e.slice(n+t.length)]})},FH=e=>{let t=Math.ceil(Math.max(0,e)/hH);return Math.min(_H,mH+t*gH)},IH=Q.memo(({autoOpenDraft:e=!0,readOnly:t=!1,active:n=!0,sessionId:r,sessionDirectory:i,sessionViewKey:a,onSessionViewEstimateChange:o,composerSurface:s,hostedFeatures:c,assistantHistory:l,onRevertMessage:u,warning:d=null,pendingUserMessages:f=cH,onPendingUserMessagesMaterialized:p,committedDraftHandoffMessageId:m=null})=>{let h=c??hT(void 0),{t:g}=Yt();Gt(()=>{ba()},[]);let _=X(e=>e.openNewSessionDraft),v=X(e=>e.setCurrentSession),y=X(e=>e.newSessionDraft),b=X(e=>e.newSessionDraft.draftSubmitting??!1),x=X(e=>e.newSessionDraft.draftEstablishing??!1),S=X(e=>e.forkTransition),C=eo(e=>e.projects),w=eo(e=>e.activeProjectId),T=Oa(e=>e.providers),E=Qm(),D=la(),O=i??D;Gt(()=>{!n||!r||!O||Kn(O,r)},[n,r,O]);let k=J(e=>E.ensureSessionRenderable(e,{directory:O})),A=q(e=>e.isExpandedInput),j=q(e=>e.stickyUserHeader),M=q(e=>e.promptNavigatorEnabled),N=q(e=>e.allowPromptingSubagentSessions),P=q(e=>e.isTimelineDialogOpen),F=q(e=>e.setTimelineDialogOpen),I=vn(e=>n&&r?e.streamingMessageIds.get(r)??null:null),L=vn(e=>I?e.messageStreamStates.get(I)?.phase??null:null),R=ji(r??``,O),z=FH(R);Q.useEffect(()=>{!a||!o||o(a,z)},[o,z,a]);let B=on(r??``,O).renderable,V=si(r,O),H=Un(r),ee=V??H,U=Kb({sessionId:r,hasSessionEntity:!!ee,hasRenderableSessionSnapshot:B,composerSurfaceKind:s?.kind}),te=r?JSON.stringify([O,r]):null,[W,ne]=Q.useState({key:te,attempt:0}),G=ha(r??``,O,{suspendPartUpdates:!!I,suspendPartUpdatesForMessageId:I,enabled:n}),re=r?G:sH,ie=y.pendingUserMessage,K=X(e=>r?e.retainedPendingUserMessages.get(r):void 0)??cH,ae=!!(m||K.length>0),oe=X(e=>e.clearRetainedPendingUserMessages),se=Q.useMemo(()=>{if(K.length===0)return f;if(f.length===0)return K;let e=new Set(f.map(e=>e.info.id));return[...f,...K.filter(t=>!e.has(t.info.id))]},[f,K]),ce=Q.useMemo(()=>aH(re),[re]),le=Q.useMemo(()=>{if(!ce.modelId)return g(`common.unavailable`);let e=T.find(e=>e.id===ce.providerId);return ri(e,ce.modelId)||ce.modelId},[T,ce.modelId,ce.providerId,g]),ue=Fa(r??``,O),de=Oi(r??``,O),[fe,pe]=Q.useState(null),me=!!r&&fe===r,he=J(()=>{if(!r||me)return;let e=r,t=O;pe(e);let n=Sa(()=>{let n=Ha();if(!n)throw Error(`unbound`);return n.getTranscript(En(t,e))});za(Vi({kind:`refresh`,sessionID:e,directory:t,purpose:`retry`,source:`network`,request:ue?{sessionID:e,status:ue.status===`ready`?`ready`:ue.status,error:ue.error}:void 0,hydration:de,error:ue?.error})),(async()=>{try{await Ka(t,e),await E.ensureSessionRenderable(e,{directory:t});try{let r=Sa(()=>{let n=Ha();if(!n)throw Error(`unbound`);return n.getTranscript(En(t,e))});n&&r&&Di({trigger:`user-refresh`,sessionID:e,directory:t,purpose:`retry`,before:n,after:r})}catch{}}catch(n){za(Vi({kind:`request-error`,sessionID:e,directory:t,purpose:`retry`,source:`network`,hydration:de,error:n}))}finally{pe(t=>t===e?null:t)}})()}),_e=Pi(r??``,O).boundary,ve=J(async e=>{if(_e.kind===`has-more`){await Ii(O,e);return}if(_e.kind===`unknown`){await Bi(O,e);return}l&&!l.complete&&await l.fetchPrevious()}),ye=wi(r??``,O),be=oa(r??``,O),xe=Ba(O),Se=ye??lH,Ce=ai(r,O),we=ti(r,O);HV(r,O,re,we.length);let Te=Q.useMemo(()=>{if(!r||Ce.length>0||we.length>0)return!1;let e=Se.type??`idle`;if(e===`busy`||e===`retry`||oT(se,{resolvedSessionStatus:ye,sessionStatusObservedAt:be}))return!0;let t=re[re.length-1]?.info,n=t?.time?.created;return ye&&typeof be==`number`&&typeof n==`number`&&n<=be||typeof xe==`number`&&typeof n==`number`&&n<=xe?!1:!!(t&&t.role===`assistant`&&typeof t.time?.completed!=`number`)},[r,se,ye,re,Ce.length,we.length,Se.type,be,xe]),Ee=Q.useMemo(()=>!r||Se.type!==`retry`?null:{sessionId:r,message:(typeof Se.message==`string`?(Se.message??``).trim():``)||fH,confirmedAt:Se.confirmedAt},[r,Se]),[De,Oe]=Q.useState(0),ke=Q.useRef(null);Q.useEffect(()=>{if(!Ee||typeof Ee.confirmedAt==`number`){ke.current=null,Oe(0);return}ke.current!==Ee.sessionId&&(ke.current=Ee.sessionId,Oe(Date.now()))},[Ee]);let Ae=Q.useMemo(()=>Ee?{...Ee,fallbackTimestamp:De}:null,[Ee,De]),je=!!(r&&E.isLoading(r,{directory:O})),Me=Q.useMemo(()=>{if(!r)return null;let e=sT({boundary:_e,assistantComplete:l?.complete??!0});return{limit:_e.loadedTurns,complete:e.complete,canLoadEarlier:e.canLoadEarlier,loading:cT({syncLoading:je,assistantLoading:!!l?.loading})}},[l?.complete,l?.loading,r,_e,je]),Ne=q(e=>e.isMobile),Pe=Fu()!==null,Fe=ge(),Ie=Fb(),Le=!!y?.open,Re=Ja(e=>e.error),ze=A,Be=Pe||Ne||Fe||Ie===`mini-chat`,Ve=Q.useRef(null),He=Q.useMemo(()=>{let e=y?.selectedProjectId?C.find(e=>e.id===y.selectedProjectId)??null:null,t=w?C.find(e=>e.id===w)??null:null,n=e??t??C[0]??null;return n?NH(n):null},[w,y?.selectedProjectId,C]),Ue=Xn(r,O),We=a??r??``,[Ge,Ke]=Q.useState(null),qe=Zb(Ge,We,Ue,ce);Gt(()=>{Ke(e=>Zb(e,We,Ue,ce))},[Ue,ce,We]);let Je=Ue??qe?.parentTarget??null,Ye=qe?.execution??ce,Xe=Pf(),Ze=Xe!==null&&r===Xe,Qe=J(()=>{Je&&v(Je.id,Je.directory)}),$e=Je?.session?.title,et=h.returnToParent&&Je&&!Ze?(0,$.jsxs)(Qt,{type:`button`,variant:`outline`,size:`xs`,onClick:Qe,className:`absolute left-3 top-3 z-20 !font-normal bg-[var(--surface-background)]/95`,"aria-label":g(`chat.container.returnToParent.aria`),title:$e?.trim()?g(`chat.container.returnToParent.titleNamed`,{title:$e}):g(`chat.container.returnToParent.title`),children:[(0,$.jsx)(Z,{name:`arrow-left`,className:`h-4 w-4`}),g(`chat.container.returnToParent.label`)]}):null,tt=qb({readOnly:t,sessionIdentityPending:U,isSubagentSession:!!ee?.parentID||!!qe,allowPromptingSubagentSessions:N}),nt=Ye.modelId===ce.modelId?le:Ye.modelId?ri(T.find(e=>e.id===Ye.providerId),Ye.modelId)||Ye.modelId:g(`common.unavailable`),rt=Je?(0,$.jsx)(yT,{agentName:Ye.agentName,providerId:Ye.providerId,modelId:Ye.modelId,modelName:nt}):(0,$.jsx)(yT,{}),it=J(e=>{q.getState().setAllowPromptingSubagentSessions(e.allowPromptingSubagentSessions)}),at=J(e=>{if(typeof window>`u`||e.source!==window.parent||e.origin!==window.location.origin)return;let t=e.data;t?.type===`openchamber:chat-settings-sync`&&typeof t.payload?.allowPromptingSubagentSessions==`boolean`&&it({allowPromptingSubagentSessions:t.payload.allowPromptingSubagentSessions})}),ot=typeof window<`u`&&window.parent!==window;Kt(`message`,at,ot?window:dH),Wt(()=>{if(!ot)return;let e=window;e.__openchamberApplyChatSettingsSync=it,window.parent.postMessage({type:`openchamber:chat-settings-request`},window.location.origin)}),Ht(()=>{if(typeof window>`u`)return;let e=window;e.__openchamberApplyChatSettingsSync===it&&delete e.__openchamberApplyChatSettingsSync}),Q.useEffect(()=>{h.newSessionDraft&&e&&!r&&!Le&&_()},[e,r,Le,h.newSessionDraft,_]);let st=Q.useRef(()=>{}),ct=J(e=>{st.current(e)}),lt=Q.useRef(()=>{}),ut=J(()=>{lt.current()}),dt=hl(e=>e.legendTimelineEnabled),[ft,pt]=Q.useState(!0),[mt,ht]=Q.useState(!1),[gt,_t]=Q.useState(!1),[vt,yt]=Q.useState(0),bt=J(()=>{yt(e=>e+1)}),xt=J((e,t)=>{pt(e),e&&_t(!1),t!==void 0&&ht(t)});Q.useEffect(()=>{pt(!0),ht(!1),_t(!1)},[r]);let{scrollRef:St,notifyContentChange:Ct,getAnimationHandlers:wt,goToBottom:Tt,scrollToBottomOnSend:Et,releaseAutoFollow:Dt,beginHistoryViewportPreservation:Ot,endHistoryViewportPreservation:kt,restoreSnapshot:At,isPinned:jt,isFollowingProgrammatically:Mt,showScrollButton:Nt}=Az({enabled:n&&!dt,currentSessionId:r,viewportKey:a,sessionMessageCount:R,sessionIsWorking:Te,isMobile:Ne,onActiveTurnChange:ct,onUpwardUserIntent:ut}),Pt=Q.useRef(null);$z({enabled:Ne,scrollRef:St,scopeRef:Pt});let Ft=Q.useRef([]),It=Q.useMemo(()=>{let e=vi(l?.entries??[],r,Ft.current);return Ft.current=e,e},[l?.entries,r]),Lt=Q.useRef([]),Rt=Q.useMemo(()=>{if(!l)return re;let e=no(l.entries,r,re,Lt.current);return Lt.current=e,e},[l,r,re]),zt=Q.useMemo(()=>aT(It.length===0?Rt:r?[...It,li(r),...Rt]:It,se),[r,Rt,It,se]),Bt=Q.useRef(null),Ut=Q.useMemo(()=>mT({sessionId:r,messages:zt,retained:Bt.current}),[r,zt]);Bt.current=Ut.retained;let qt=Ut.messages,Jt=Q.useRef(null),Xt=Jt.current===r,Zt=Q.useRef(jV),$t=r?`${O}\n${r}`:null,en=J(()=>AV(qt));Q.useEffect(()=>{if(!PV({active:n,sessionId:r,sessionKey:$t,sessionIsWorking:Te})){Zt.current=FV(Zt.current);return}let e=r,t=O,i=setInterval(()=>{let n=en(),r=MV(Zt.current,{sessionKey:$t,working:!0,streaming:!!I,fingerprint:n,now:Date.now(),thresholdMs:EV,cooldownMs:DV,maxAttempts:3});Zt.current=r.state,r.shouldRefresh&&(NV({sessionId:e,directory:t,stalledForMs:r.stalledForMs,attempt:r.state.attempts,fingerprint:n}),Dr(t,e).catch(()=>{}))},OV);return()=>clearInterval(i)},[n,r,O,en,Te,I,$t]);let tn=Q.useMemo(()=>{if(se.length===0)return[];let e=new Set([...It,...Rt].filter(e=>Qa(e.parts)).map(e=>e.info.id));return se.map(e=>e.info.id).filter(t=>e.has(t))},[Rt,It,se]);Q.useEffect(()=>{tn.length!==0&&(p?.(tn),r&&oe(r,tn))},[oe,r,tn,p]);let nn=dV({sessionId:r,directory:O,messages:qt,historyMeta:Me,scrollRef:St,messageListRef:Ve,loadMoreMessages:ve,goToBottom:Tt,releaseAutoFollow:Dt,beginHistoryViewportPreservation:Ot,endHistoryViewportPreservation:kt,isPinned:dt?ft:jt,showScrollButton:dt?mt:Nt,isMobile:Ne,autoFillEnabled:n&&!ze,onWillLoadEarlier:bt}),rn=J(()=>{_t(!1),Ve.current?.scrollToBottom(),Tt(`instant`)}),an=J(()=>{_t(!1),Et()}),sn=J(()=>{_t(!0),nn.handleHistoryUpwardIntent()}),cn=lT({isMobile:Ne,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingOlder:nn.isLoadingOlder}),ln=nn.isLoadingOlder,dn=nn.loadEarlier,fn=J(()=>{_t(!0),dn({userInitiated:!0})});st.current=nn.handleActiveTurnChange,lt.current=nn.handleHistoryUpwardIntent,Q.useEffect(()=>{(Ce.length!==0||we.length!==0)&&Ct(`permission`)},[Ct,Ce,we]);let pn=TV({sessionId:r,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,scrollToTurn:nn.scrollToTurn,scrollToMessage:nn.scrollToMessage,resumeToBottom:rn}),mn=tt.showReadOnlyBanner?rt:t?null:(0,$.jsx)(Zw,{surface:s,scrollToBottom:an,showScrollToBottom:Ne&&nn.showScrollToBottom,onScrollToBottom:pn.resumeToLatest,submissionBlocked:tt.blockSubmission}),hn=J(e=>{pn.scrollToTurnId(e,{behavior:`smooth`})}),gn=nn.historySignals.canLoadEarlier,_n=h.promptNavigator&&!Ne&&!Fe&&!ze&&M&&nn.turnIds.length>=2;Q.useEffect(()=>{_n||q.getState().setPromptNavigatorPanelOpen(!1)},[_n]);let yn=J(e=>{if(!n||!r)return;let t=e;t.detail?.sessionId&&t.detail.sessionId!==r||Tt(`instant`)});Kt(uH,yn,n&&r&&typeof window<`u`?window:dH);let bn=J(e=>{if(!n||!r||ze||e.defaultPrevented||e.isComposing||e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let{activeMainTab:t}=q.getState();if(t!==`chat`||AH())return;let i=St.current;if(kH(document.activeElement,i)||OH(e.target))return;e.preventDefault();let a=e.key===`ArrowUp`?-1:1;pn.scrollByTurnOffset(a,{resumePastEnd:!1})});Kt(`keydown`,bn,n&&r&&!ze&&typeof window<`u`?window:dH);let xn=Q.useRef(0),Sn=J(()=>{let e=St.current;e&&e.style.setProperty(`--chat-scroll-height`,`${e.clientHeight}px`)}),Cn=J(()=>{xn.current||=requestAnimationFrame(()=>{xn.current=0,Sn()})});Gt(()=>{n&&Sn()},[n,r,ze,Sn]);let wn=typeof ResizeObserver<`u`;Vt(n&&wn?St:null,Cn),Kt(`resize`,Cn,n&&!wn&&typeof window<`u`?window:dH),Ht(()=>{xn.current&&=(cancelAnimationFrame(xn.current),0)});let Tn=Q.useRef(null),Dn=Q.useRef(0),On=fT({transcriptMessageCount:re.length,pendingUserCount:se.length,historyPrefixCount:It.length}),kn=pT({hasTranscriptShell:On,p0Satisfied:de.p0Satisfied,hasBusyShell:Te&&On,hasImmediateShell:se.length>0||It.length>0,hasRenderableSessionSnapshot:B,prefetchStatus:ue?.status,syncLoading:!!(r&&E.isLoading(r,{directory:O})),userRetrying:me,hasPaintedTranscript:Xt});kn===`pass`&&qt.length>0&&(Jt.current=r);let An=!!r&&kn===`hydrating`,jn=!!r&&kn===`load-error`;Q.useEffect(()=>{!jn||!r||za(Vi({kind:`request-error`,sessionID:r,directory:O,purpose:`load-failed`,source:`network`,request:ue?{sessionID:r,status:ue.status===`ready`?`ready`:ue.status,error:ue.error}:void 0,hydration:de,error:ue?.error}))},[r,O,jn,ue,de]),Q.useEffect(()=>{if(!n||!r||An)return;let e=qt.length,t=Tn.current!==r,i=!t&&Dn.current===0&&e>0;if(!t&&!i){Tn.current===r&&(Dn.current=e);return}let a=typeof window<`u`&&window.location.hash.length>0;if(Tn.current=r,Dn.current=e,a){Dt();return}let o=()=>{At()};typeof window>`u`?o():window.requestAnimationFrame(o)},[n,r,An,Dt,At,qt.length]),Q.useEffect(()=>{ne(e=>e.key===te?e:{key:te,attempt:0})},[te]),Q.useEffect(()=>{if(!n||!r||W.key!==te||!oH({sessionId:r,hasRenderableSessionSnapshot:B,hasCurrentSessionEntity:!!ee})||(k(r),ee||W.attempt>=2))return;let e=W.attempt+1,t=window.setTimeout(()=>{ne(t=>t.key===te&&t.attempt===W.attempt?{key:te,attempt:e}:t)},e*1e3);return()=>window.clearTimeout(t)},[n,ee,r,O,k,B,te,W]);let Mn=S&&r&&(S.targetSessionId?r===S.targetSessionId:r===S.sourceSessionId)?S:null;if(Mn){let e=Mn.stage===`preparing`?`chat.forkTransition.preparing`:Mn.stage===`copying`?`chat.forkTransition.copying`:Mn.stage===`opening`?`chat.forkTransition.opening`:`chat.forkTransition.loading`,t=[`preparing`,`copying`,`opening`,`loading`],n=g(`chat.forkTransition.progress`,{current:Math.max(1,t.indexOf(Mn.stage)+1),total:t.length});return(0,$.jsx)(`div`,{className:`flex h-full flex-col items-center justify-center bg-background px-6 text-center`,children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,role:`status`,"aria-live":`polite`,"aria-label":`${g(e)}. ${n}`,children:[(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:g(e)}),(0,$.jsx)(uv,{})]}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground/70 tabular-nums`,children:n})]})})}if(!r&&!Le)return e&&!Re?(0,$.jsx)(`div`,{className:`flex h-full flex-col bg-background`}):(0,$.jsx)(`div`,{className:`flex flex-col h-full bg-background`,children:(0,$.jsx)(xT,{})});if(!r&&Le){if((b||x)&&ie){let e=`draft:${y.draftID??`pending`}`;return(0,$.jsxs)(`div`,{ref:Pt,className:Y(`relative flex h-full flex-col bg-background`,Ne&&`oc-chat-composer-swap-scope`),children:[(0,$.jsx)(jH,{currentSessionId:e,virtualizerKey:e,isDesktopExpandedInput:!1,isMobile:Ne,stickyUserHeader:j,directory:O,scrollRef:St,messageListRef:Ve,pendingRevealWork:!1,initialPinRevealComplete:!0,renderedMessages:[ie],isLoadingOlder:!1,sessionIsWorking:!0,streamingMessageId:null,activeStreamingPhase:null,retryOverlay:null,handleMessageContentChange:Ct,getAnimationHandlers:wt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:sn,onTimelineIsAtEndChange:xt,timelineFollowSuspended:!1,timelineHistoryAnchorToken:vt,scrollToBottom:rn,sessionQuestions:[],sessionPermissions:[],isProgrammaticFollowActive:Mt,showLoadOlderButton:!1,onLoadOlder:fn,turnIds:[],activeTurnId:null,onSelectTurn:hn,showPromptNavigator:!1,canLoadEarlierPrompts:!1,isLoadingOlderPrompts:!1,onLoadEarlierPrompts:fn,transcriptStatusRow:(0,$.jsx)(`div`,{className:`chat-column`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex h-[1.2rem] items-center py-0.5 typography-meta text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:g(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(uv,{})]})})},e),(0,$.jsxs)(`div`,{className:Y(`invisible pointer-events-none relative z-10`,Ne&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,ze?`absolute inset-0 bg-background`:`bg-background`),"aria-hidden":`true`,children:[!Ne&&!ze?(0,$.jsx)(CH,{}):null,mn]}),(0,$.jsx)(iT,{})]})}return b||x?(0,$.jsx)(`div`,{className:`flex h-full flex-col items-center justify-center bg-background px-6 text-center`,children:(0,$.jsx)(`div`,{className:`flex flex-col items-center gap-3`,role:`status`,"aria-live":`polite`,"aria-label":g(`chat.emptyState.establishingConversation`),children:(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:g(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(uv,{})]})})}):(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[Be&&!ze?(0,$.jsxs)(`div`,{className:`oc-draft-center flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-balance text-3xl font-normal tracking-tight text-foreground`,children:PH(He?g(`chat.emptyState.draftTitleWithProject`,{project:He}):g(`chat.emptyState.draftTitle`),He)}),(0,$.jsx)(Ux,{onSubmit:e=>un.getState().requestPresetSubmit(e),className:`oc-draft-starters mt-8 max-w-md`})]}):null,(0,$.jsx)(`div`,{className:Y(`relative z-10 flex min-h-0`,Ne&&`oc-mobile-composer-foot`,ze?`flex-1 bg-background`:Be?Y(`bg-background`,`px-0`):`flex-1 items-center justify-center bg-background px-0 pb-[6vh]`),children:mn})]})}return r?jn?(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[et,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,ze?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":ze,children:ze?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center px-6`,children:(0,$.jsxs)(`div`,{className:`flex max-w-sm flex-col items-center text-center`,role:`alert`,"aria-live":`polite`,children:[(0,$.jsx)(`div`,{className:`mb-4 flex size-10 items-center justify-center rounded-full bg-[var(--status-error-background)] text-[var(--status-error-foreground)]`,children:(0,$.jsx)(Z,{name:`error-warning`,className:`size-5`,"aria-hidden":`true`})}),(0,$.jsx)(`h2`,{className:`typography-ui-header text-foreground`,children:g(`chat.history.loadFailedTitle`)}),(0,$.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:g(`chat.history.loadFailedDescription`)}),(0,$.jsxs)(Qt,{type:`button`,className:`mt-5`,onClick:he,children:[(0,$.jsx)(Z,{name:`refresh`,className:`size-4`,"aria-hidden":`true`}),g(`chat.history.retry`)]})]})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:mn})]}):An?(0,$.jsxs)(`div`,{ref:Pt,className:Y(`relative flex flex-col h-full bg-background`,Ne&&`oc-chat-composer-swap-scope`),children:[et,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,ze?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":ze,children:(0,$.jsx)(`div`,{ref:St,className:`absolute inset-0 overflow-y-auto overflow-x-hidden bg-background pt-6 chat-scroll`,style:xH,children:(0,$.jsx)(`div`,{className:`space-y-4 chat-scroll-foot-inset`,children:MH.map(e=>(0,$.jsx)(`div`,{className:`group w-full`,children:(0,$.jsx)(`div`,{className:`chat-message-column`,children:(0,$.jsxs)(`div`,{className:`space-y-2.5 px-4 py-3`,children:[(0,$.jsx)(`div`,{className:`space-y-1.5`,children:e.toolRows.map(t=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(id,{className:`h-3.5 w-3.5 rounded-full flex-shrink-0`}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,t.titleWidth)}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,t.detailWidth)})]},`${e.id}-${t.id}`))}),(0,$.jsxs)(`div`,{className:`space-y-1.5 pt-1`,children:[(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,e.textWidths[0])}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,e.textWidths[1])}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,e.textWidths[2])})]})]})})},e.id))})})}),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Ne&&!ze?(0,$.jsx)(CH,{}):null,mn]})]}):qt.length===0&&!Te?(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full bg-background`,children:[et,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,ze?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":ze,children:ze?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,$.jsx)(xT,{})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:mn}),(0,$.jsx)(iT,{})]}):(0,$.jsxs)(`div`,{ref:Pt,className:Y(`relative flex flex-col h-full bg-background`,Ne&&`oc-chat-composer-swap-scope`),children:[d?(0,$.jsx)(`div`,{className:`shrink-0 border-b border-border bg-[var(--status-warning-background)] px-4 py-2.5 typography-meta text-[var(--status-warning-foreground)]`,children:d}):null,et,(0,$.jsx)(jH,{currentSessionId:r,virtualizerKey:a??r,isDesktopExpandedInput:ze,isMobile:Ne,stickyUserHeader:j,directory:O,scrollRef:St,messageListRef:Ve,pendingRevealWork:nn.pendingRevealWork,initialPinRevealComplete:ae,renderedMessages:nn.renderedMessages,isLoadingOlder:ln,sessionIsWorking:Te,streamingMessageId:I,activeStreamingPhase:L,retryOverlay:Ae,handleMessageContentChange:Ct,getAnimationHandlers:wt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:sn,onTimelineIsAtEndChange:xt,timelineFollowSuspended:gt,timelineHistoryAnchorToken:vt,scrollToBottom:rn,sessionQuestions:we,sessionPermissions:Ce,isProgrammaticFollowActive:Mt,showLoadOlderButton:cn,onLoadOlder:fn,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,onSelectTurn:hn,showPromptNavigator:_n,canLoadEarlierPrompts:gn,isLoadingOlderPrompts:ln,onLoadEarlierPrompts:fn},r),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Ne&&!ze?(0,$.jsx)(CH,{}):null,!ze&&qt.length>0&&(Ne?(0,$.jsx)(Nb,{placement:`expanded`,visible:nn.showScrollToBottom,onClick:pn.resumeToLatest}):(0,$.jsx)(Nb,{visible:nn.showScrollToBottom,onClick:pn.resumeToLatest})),mn]}),(0,$.jsx)(iT,{}),(0,$.jsx)(pV,{open:P,onOpenChange:F,sessionID:r??void 0,directory:O,onRevertMessage:u,onScrollToMessage:nn.scrollToMessage,onScrollByTurnOffset:pn.scrollByTurnOffset,onResumeToLatest:rn,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingEarlier:ln,onLoadEarlier:fn})]}):null});IH.displayName=`MemoizedChatContainerContent`;var LH=()=>{let e=(0,pd.c)(2),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(id,{className:`h-4 w-4/5 animate-none rounded-md`}),(0,$.jsx)(id,{className:`h-4 w-2/3 animate-none rounded-md`}),(0,$.jsx)(id,{className:`h-4 w-1/2 animate-none rounded-md`})]}),e[0]=t):t=e[0];let n;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,$.jsx)(`div`,{className:`flex h-full flex-col bg-background`,"data-session-view-loading":`true`,"aria-hidden":`true`,children:(0,$.jsx)(`div`,{className:`mt-auto w-full pb-5 motion-safe:animate-pulse`,children:(0,$.jsxs)(`div`,{className:`chat-message-column space-y-6 px-4`,children:[t,(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(id,{className:`h-4 w-5/6 animate-none rounded-md`}),(0,$.jsx)(id,{className:`h-4 w-3/5 animate-none rounded-md`})]}),(0,$.jsx)(id,{className:`h-24 w-full animate-none rounded-xl`})]})})}),e[1]=n):n=e[1],n},RH=({runtimeKey:e,...t})=>{let n=Fb(),r=la(),i=X(He(e=>({sessionId:e.currentSessionId,directory:e.currentSessionDirectory,draftID:e.newSessionDraft.open?e.newSessionDraft.draftID:null,draftPendingMessageId:e.newSessionDraft.open?e.newSessionDraft.pendingUserMessage?.info.id??null:null}))),a=Q.useRef(null),o=i.draftID&&i.draftPendingMessageId?`${i.draftID}:${i.draftPendingMessageId}`:null;o&&a.current?.identity!==o&&(a.current=null),Gt(()=>{!o||!i.draftPendingMessageId||(a.current={identity:o,messageId:i.draftPendingMessageId})},[o,i.draftPendingMessageId]);let s=X(e=>i.sessionId?e.retainedPendingUserMessages.get(i.sessionId)??cH:cH),c=a.current,l=c&&s.some(e=>e.info.id===c.messageId)?c.messageId:null,u=Q.useMemo(()=>i.sessionId?{runtimeKey:e,sessionId:i.sessionId,directory:i.directory??r}:null,[e,i.directory,i.sessionId,r]),d=Q.useMemo(()=>KV(u),[u]),f=d.key,p=yr()||ge()||n===`mini-chat`?yH:vH,[m,h]=Q.useState(()=>({activeIntent:d,cacheNeedsTrim:!1,cachedSessionViews:u?JV([],u,p,mH):[],pendingSessionView:null})),g=Q.useRef(d),_=Q.useRef(f),{cacheNeedsTrim:v,cachedSessionViews:y,pendingSessionView:b}=m,x=b?.intent===d?b.entry:null,S=Q.useMemo(()=>!u||!l?null:JV([],u,p,mH)[0]??null,[p,l,u]),C=Q.useMemo(()=>{let e=[...y];return x&&!e.some(e=>e.key===x.key)&&e.push(x),S&&!e.some(e=>e.key===S.key)&&e.push(S),e.sort((e,t)=>e.key.localeCompare(t.key))},[y,S,x]),w=XV(C,f),T=!!(f&&!w);Gt(()=>{g.current=d,_.current=f,h(e=>{let t=ZV(e,d,p);return l?QV(t,d,d,mH):t})},[p,v,l,d,f]);let E=b?.intent??null;Gt(()=>{E&&h(e=>$V(e,E,p))},[p,E]),Q.useEffect(()=>{if(!d.selection||w)return;let e=d,t=f;return Jl(()=>{g.current===e&&_.current===t&&h(n=>_.current===t?QV(n,e,g.current,mH):n)},{priority:`user-blocking`})},[w,p,d,f]);let D=J((e,t)=>{let n=g.current,r=_.current;h(i=>{if(g.current!==n||_.current!==r||i.activeIntent!==n||e!==r)return i;let a=YV(i.cachedSessionViews,e,t);return a===i.cachedSessionViews?i:{...i,cacheNeedsTrim:!0,cachedSessionViews:a}})});return(0,$.jsxs)(`div`,{className:`h-full bg-background`,"aria-busy":T||void 0,children:[T?(0,$.jsx)(LH,{},f):null,C.map(e=>(0,$.jsx)(Q.Activity,{name:`chat-session-${e.sessionId}`,mode:w===e.key?`visible`:`hidden`,children:(0,$.jsx)(IH,{...t,sessionId:e.sessionId,sessionDirectory:e.directory,sessionViewKey:e.key,onSessionViewEstimateChange:D,committedDraftHandoffMessageId:w===e.key?l:null})},e.key)),f?null:(0,$.jsx)(IH,{...t,sessionId:null,sessionDirectory:i.directory})]})},zH=e=>{let t=(0,pd.c)(24),{host:n,runtimeKey:r,readOnly:i}=e,a=i!==void 0&&i,o;t[0]===n?o=t[1]:(o=hT(n),t[0]=n,t[1]=o);let s=o,c;t[2]===n.onRevertMessage?c=t[3]:(c=n.onRevertMessage?{onRevertMessage:n.onRevertMessage}:{},t[2]=n.onRevertMessage,t[3]=c);let l;t[4]!==n.directory||t[5]!==n.sessionId||t[6]!==n.sessionSurface||t[7]!==c?(l={...n.sessionSurface,sessionId:n.sessionId,directory:n.directory,...c},t[4]=n.directory,t[5]=n.sessionId,t[6]=n.sessionSurface,t[7]=c,t[8]=l):l=t[8];let u=l,d=`host:${r}:${u.surfaceId}:${n.sessionId}`,f;t[9]!==n.assistantHistory||t[10]!==n.composerSurface||t[11]!==n.directory||t[12]!==n.onPendingUserMessagesMaterialized||t[13]!==n.onRevertMessage||t[14]!==n.pendingUserMessages||t[15]!==n.sessionId||t[16]!==n.warning||t[17]!==s||t[18]!==a||t[19]!==d?(f=(0,$.jsx)(`div`,{className:`h-full bg-background`,children:(0,$.jsx)(IH,{autoOpenDraft:!1,readOnly:a,sessionId:n.sessionId,sessionDirectory:n.directory,sessionViewKey:d,composerSurface:n.composerSurface,hostedFeatures:s,assistantHistory:n.assistantHistory,pendingUserMessages:n.pendingUserMessages,onPendingUserMessagesMaterialized:n.onPendingUserMessagesMaterialized,onRevertMessage:n.onRevertMessage,warning:n.warning})}),t[9]=n.assistantHistory,t[10]=n.composerSurface,t[11]=n.directory,t[12]=n.onPendingUserMessagesMaterialized,t[13]=n.onRevertMessage,t[14]=n.pendingUserMessages,t[15]=n.sessionId,t[16]=n.warning,t[17]=s,t[18]=a,t[19]=d,t[20]=f):f=t[20];let p;return t[21]!==u||t[22]!==f?(p=(0,$.jsx)(Xy.Provider,{value:u,children:f}),t[21]=u,t[22]=f,t[23]=p):p=t[23],p},BH=e=>{let t=(0,pd.c)(16),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({explicitSession:n,runtimeKey:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a=la(),o=n.directory??a,s;t[4]!==o||t[5]!==n?(s=Yy({...n,directory:o}),t[4]=o,t[5]=n,t[6]=s):s=t[6];let c=s,l=`explicit:${i}:${n.viewKey}`,u;t[7]!==o||t[8]!==n.active||t[9]!==n.sessionId||t[10]!==r||t[11]!==l?(u=(0,$.jsx)(`div`,{className:`h-full bg-background`,children:(0,$.jsx)(IH,{...r,active:n.active,sessionId:n.sessionId,sessionDirectory:o,sessionViewKey:l})}),t[7]=o,t[8]=n.active,t[9]=n.sessionId,t[10]=r,t[11]=l,t[12]=u):u=t[12];let d;return t[13]!==c||t[14]!==u?(d=(0,$.jsx)(Xy.Provider,{value:c,children:u}),t[13]=c,t[14]=u,t[15]=d):d=t[15],d},VH=e=>{let t=(0,pd.c)(14),n=Q.useSyncExternalStore(bH,u,u);if(e.host){let r=`${n}:${e.host.sessionSurface.surfaceId}`,i;return t[0]!==e||t[1]!==n||t[2]!==r?(i=(0,$.jsx)(zH,{...e,host:e.host,runtimeKey:n},r),t[0]=e,t[1]=n,t[2]=r,t[3]=i):i=t[3],i}if(e.explicitSession){let r=`${n}:${e.explicitSession.viewKey}`,i;return t[4]!==e.active||t[5]!==e.autoOpenDraft||t[6]!==e.explicitSession||t[7]!==e.readOnly||t[8]!==n||t[9]!==r?(i=(0,$.jsx)(BH,{autoOpenDraft:e.autoOpenDraft,readOnly:e.readOnly,active:e.active,explicitSession:e.explicitSession,runtimeKey:n},r),t[4]=e.active,t[5]=e.autoOpenDraft,t[6]=e.explicitSession,t[7]=e.readOnly,t[8]=n,t[9]=r,t[10]=i):i=t[10],i}let r;return t[11]!==e||t[12]!==n?(r=(0,$.jsx)(RH,{...e,runtimeKey:n},n),t[11]=e,t[12]=n,t[13]=r):r=t[13],r},HH=2e4,UH=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,WH=e=>{if(!le()&&!mt())return;let t=g();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:ht()})},GH=e=>{let t=e?.enabled??!0;Q.useEffect(()=>{if(!t||!le()&&!mt()||typeof window>`u`)return;if(mt()){let e=!0,t=!1,n=null,r=()=>WH(e);Et(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([53,1,10])).then(async({App:i})=>{if(t)return;let a=await i.getState().catch(()=>null);a&&(e=a.isActive===!0),r();let o=await i.addListener(`appStateChange`,({isActive:t})=>{e=t===!0,r()});if(t){o.remove();return}n=()=>void o.remove()}).catch(()=>void 0);let i=window.setInterval(()=>{e&&WH(!0)},HH);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{WH(UH()===`visible`)},n=()=>{UH()===`visible`&&WH(!0)},r=()=>{WH(!1)};e();let i=window.setInterval(n,HH);return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pagehide`,r),window.addEventListener(`pageshow`,e),window.addEventListener(`focus`,e),window.addEventListener(`blur`,e),()=>{window.clearInterval(i),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pagehide`,r),window.removeEventListener(`pageshow`,e),window.removeEventListener(`focus`,e),window.removeEventListener(`blur`,e)}},[t])},KH=`OpenChamber`,qH=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},JH=(e,t)=>[e,t,KH].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),YH=()=>{let e=eo(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=Q.useMemo(()=>e&&qH(e.path)||null,[e]),[n,r]=Q.useState(null);Q.useEffect(()=>{if(typeof window>`u`||!O()){r(null);return}let e=!1,t=async()=>{try{if(R()){e||r(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,n=d();if(n&&Oe(n,t)){e||r(null);return}let i=(await Ie()).hosts.find(e=>n?Oe(n,je(e)):!1),a=i?.label?.trim()?ke(i.label.trim()):`Instance`;e||r(a)}catch{e||r(`Instance`)}};t();let n=()=>{t()};return window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[]);let i=Q.useMemo(()=>JH(t,n),[t,n]);Q.useEffect(()=>{typeof document<`u`&&(document.title=i),O()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await $t(i)}catch{return}})()},[i])},XH=()=>{let e=X.getState().currentSessionId;if(!e)return``;let t=ia().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},ZH=async(e,t=6e3)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t),i=Date.now();try{let t=await f(e,{method:`GET`,headers:{Accept:`application/json`},signal:n.signal}),r=Date.now()-i,a=t.headers.get(`content-type`)||``,o=a.toLowerCase(),s=o.includes(`json`)&&!o.includes(`text/html`),c=``;if(s){let e=await t.json().catch(()=>null);if(Array.isArray(e))c=`json[array] len=${e.length}`;else if(e&&typeof e==`object`){let t=Object.keys(e).slice(0,8);c=`json[object] keys=${t.join(`,`)}${Object.keys(e).length>t.length?`,…`:``}`}else c=`json[${typeof e}]`}else c=a?`content-type=${a}`:`no content-type`;return{ok:t.ok&&s,status:t.status,elapsedMs:r,summary:c}}catch(e){return{ok:!1,status:0,elapsedMs:Date.now()-i,summary:`error=${n.signal.aborted||e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`aborted`))?`timeout after ${t}ms`:e instanceof Error?e.message:String(e)}`}}finally{clearTimeout(r)}},QH=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},$H=e=>{if(typeof e==`number`&&Number.isFinite(e)&&e>0)return Math.trunc(e);if(typeof e==`string`){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return null},eU=e=>!!e&&typeof e==`object`&&!Array.isArray(e),tU=(e,t=`(n/a)`)=>typeof e==`string`?e.trim()||t:typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`boolean`?e?`true`:`false`:t,nU=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,rU=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=XH(),r=q.getState().eventStreamStatus,i=typeof window<`u`?window.location.origin:``,o=a(),s=o.health(),c=o.api(`/api/`),l=await(async()=>{if(!s)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);try{let t=await f(s,{method:`GET`,headers:{Accept:`application/json`},signal:e.signal});if(!t.ok)return null;let n=await t.json().catch(()=>null);return!n||typeof n!=`object`||Array.isArray(n)?null:n}catch{return null}finally{clearTimeout(t)}})(),u=await(async()=>{if(!c)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),7e3);try{let t=await f(o.api(`/api/config/opencode-resolution`),{method:`GET`,headers:{Accept:`application/json`},signal:e.signal}),n=t.headers.get(`content-type`)||`(none)`;if(!t.ok)return{data:null,status:t.status,error:`http ${t.status} content-type=${n}`};let r=await t.text(),i=null;try{i=JSON.parse(r)}catch{let e=r.replace(/\s+/g,` `).slice(0,120);return{data:null,status:t.status,error:`invalid json content-type=${n} body=${e||`(empty)`}`}}return!i||typeof i!=`object`||Array.isArray(i)?{data:null,status:t.status,error:`invalid json-shape content-type=${n}`}:{data:i,status:t.status,error:null}}catch(e){return{data:null,status:null,error:e instanceof Error?e.message:String(e)}}finally{clearTimeout(t)}})()||{data:null,status:null,error:null},d=(e,t=!0)=>{if(!c)return null;let r=new URL(e.replace(/^\/+/,``),c);return t&&n&&r.searchParams.set(`directory`,n),r.toString()},p=c?await Promise.all([{label:`health`,path:`/health`,includeDirectory:!1},{label:`config`,path:`/config`,includeDirectory:!0},{label:`providers`,path:`/config/providers`,includeDirectory:!0},{label:`agents`,path:`/agent`,includeDirectory:!0,timeoutMs:12e3},{label:`commands`,path:`/command`,includeDirectory:!0,timeoutMs:1e4},{label:`project`,path:`/project/current`,includeDirectory:!0},{label:`path`,path:`/path`,includeDirectory:!0},{label:`sessions`,path:`/session`,includeDirectory:!0,timeoutMs:12e3},{label:`sessionStatus`,path:`/session/status`,includeDirectory:!0}].map(async e=>{let t=d(e.path,e.includeDirectory!==!1);if(!t)return{label:e.label,url:`(none)`,result:null};let n=await ZH(t,typeof e.timeoutMs==`number`?e.timeoutMs:void 0);return{label:e.label,url:t,result:n}})):[],m=[];m.push(`Time: ${e.toISOString()}`),m.push(`OpenChamber version: 1.19.17-beta.3`),m.push(`Runtime: ${i||`(unknown)`} (api=${c||`(unknown)`})`),m.push(`OpenCode SDK base: ${it.getBaseUrl()}`),m.push(`Event stream: ${r}`),m.push(`Directory: ${n||`(none)`}`),m.push(`Platform: ${t}`);let h=$H(l?.openCodePort);if(m.push(`OpenCode runtime port: ${h??`(unknown)`}`),typeof l?.openCodeRunning==`boolean`&&m.push(`OpenCode runtime running: ${l.openCodeRunning?`yes`:`no`}`),typeof l?.openCodeSecureConnection==`boolean`&&m.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?`true`:`false`}`),typeof l?.openCodeAuthSource==`string`&&l.openCodeAuthSource.trim()&&m.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<`u`){let e=window.__OPENCHAMBER_MACOS_MAJOR__;typeof e==`number`&&Number.isFinite(e)&&e>0&&m.push(`macOS major: ${e}`)}if(/Mac OS X|Macintosh/.test(t)){m.push(``),m.push(`OpenCode CLI resolution:`);let e=eU(l?.lastOpenCodeLaunchDiagnostics)?l.lastOpenCodeLaunchDiagnostics:null,t=e&&Array.isArray(e.args)?e.args.filter(e=>typeof e==`string`):[],n=u.data,r=n&&typeof n.configured==`string`?n.configured:null,i=n&&typeof n.resolved==`string`?n.resolved:l&&typeof l.opencodeBinaryResolved==`string`?l.opencodeBinaryResolved:``,a=n&&typeof n.resolvedDir==`string`?n.resolvedDir:``,o=n&&typeof n.source==`string`?n.source:l&&typeof l.opencodeBinarySource==`string`?l.opencodeBinarySource:``,s=n&&typeof n.launchBinary==`string`?n.launchBinary:l&&typeof l.opencodeLaunchBinary==`string`?l.opencodeLaunchBinary:``,c=n&&typeof n.launchWrapperType==`string`?n.launchWrapperType:l&&typeof l.opencodeLaunchWrapperType==`string`?l.opencodeLaunchWrapperType:``,d=n&&Array.isArray(n.launchArgs)?n.launchArgs.filter(e=>typeof e==`string`):l&&Array.isArray(l.opencodeLaunchArgs)?l.opencodeLaunchArgs.filter(e=>typeof e==`string`):[],f=n&&typeof n.node==`string`?n.node:l&&typeof l.nodeBinaryResolved==`string`?l.nodeBinaryResolved:``,p=n&&typeof n.bun==`string`?n.bun:l&&typeof l.bunBinaryResolved==`string`?l.bunBinaryResolved:``,h=n&&typeof n.detectedNow==`string`?n.detectedNow:``,g=n&&typeof n.detectedSourceNow==`string`?n.detectedSourceNow:``;if(r!==null&&m.push(`- configured: ${r.trim().length===0?`(cleared)`:r}`),i){let e=a||(i.includes(`/`)?i.split(`/`).slice(0,-1).join(`/`)||`/`:``);m.push(`- opencode: ${i}${e?` (dir=${e})`:``}`)}else m.push(`- opencode: (n/a)`);m.push(`- source: ${o||`(n/a)`}`),h&&(m.push(`- detected-now: ${h}`),m.push(`- detected-source: ${g||`(n/a)`}`)),e?(m.push(`- launched-at: ${tU(e.launchedAt)}`),m.push(`- launch: ${tU(e.binary)} ${t.join(` `)}`.trim()),m.push(`- cwd: ${tU(e.cwd)}`),m.push(`- wrapper: ${tU(e.wrapperType)}`),m.push(`- runtime: ${nU(tU(e.wrapperType,``),f,p)}`),m.push(`- PATH entries: ${tU(e.pathEntryCount,`(unknown)`)}`),m.push(`- shell env: ${tU(e.hasShellEnv,`(unknown)`)} (${tU(e.shellEnvKeysCount,`?`)} keys)`)):(m.push(`- launch-binary: ${s||`(n/a)`}`),m.push(`- launch-wrapper: ${c||`(n/a)`}`),m.push(`- launch-args: ${d.length?d.join(` `):`(none)`}`),m.push(`- runtime: ${nU(c||``,f,p)}`)),!n&&u.error&&m.push(`- resolution-endpoint: ${u.error}`)}if(m.push(``),p.length){m.push(`OpenCode API probes:`);for(let e of p){if(!e.result){m.push(`- ${e.label}: (no url)`);continue}let{ok:t,status:n,elapsedMs:r,summary:i}=e.result,a=t?``:` url=${e.url}`;m.push(`- ${e.label}: ${t?`ok`:`fail`} status=${n} time=${r}ms ${i}${a}`)}}else m.push(`OpenCode API probes: (skipped)`);return m.push(``),m.push(`Generated: ${QH(Date.now())}`),m.join(`
|
|
6583
|
+
`).trimEnd()}function OR(e){let t={questions:(e.questions??[]).map(e=>({header:e.header??null,question:e.question,multiple:!!e.multiple,options:e.options.map(e=>({label:e.label,description:e.description??null}))}))};return JSON.stringify(t,null,2)}var kR=200;function AR(e){return Math.min(Math.max(e,40),kR)}var jR=`summary`,MR=Q.memo(function(e){let t=(0,pd.c)(27),{value:n,placeholder:r,disabled:i,onValueChange:a,onKeyDown:o}=e,s=Q.useRef(null),[c,l]=Q.useState(n),[u,d]=Q.useState(40),[f,p]=Q.useState(!1),m;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(m=()=>{let e=s.current;if(!e||document.activeElement!==e)return;let t=e.closest(`.chat-scroll`);if(!t){e.scrollIntoView({block:`nearest`});return}let n=window.visualViewport,r=t.getBoundingClientRect(),i=n?.offsetTop??0,a=n?n.offsetTop+n.height:document.documentElement.clientHeight,o=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(`--oc-kb-scroll-inset`))||0,c=Math.max(r.top,i),l=Math.min(r.bottom,a-o),u=Math.max(0,l-c),d=e.closest(`[data-question-card]`),f=d?.getBoundingClientRect(),p=(d&&f&&f.height<=u?d:e).getBoundingClientRect();p.bottom>l-12?t.scrollTop+=p.bottom-l+12:p.top<c+12&&(t.scrollTop+=p.top-c-12)},t[0]=m):m=t[0];let h=J(m),g;t[1]===h?g=t[2]:(g=()=>{requestAnimationFrame(h)},t[1]=h,t[2]=g);let _=J(g),v;t[3]===h?v=t[4]:(v=()=>{let e=()=>requestAnimationFrame(h);return e(),window.addEventListener(`oc:keyboard-settled`,e),window.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`resize`,e),window.visualViewport?.addEventListener(`scroll`,e),()=>{window.removeEventListener(`oc:keyboard-settled`,e),window.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`resize`,e),window.visualViewport?.removeEventListener(`scroll`,e)}},t[3]=h,t[4]=v);let y;t[5]===Symbol.for(`react.memo_cache_sentinel`)?(y=[],t[5]=y):y=t[5],Q.useEffect(v,y);let b,x;t[6]===n?(b=t[7],x=t[8]):(b=()=>{l(n)},x=[n],t[6]=n,t[7]=b,t[8]=x),Q.useEffect(b,x);let S;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(S=()=>{let e=s.current;if(!e)return;e.style.height=`auto`,e.style.overflowY=`hidden`;let t=e.scrollHeight,n=AR(t),r=t>n;e.style.height=`${n}px`,e.style.overflowY=``,d(e=>e===n?e:n),p(e=>e===r?e:r)},t[9]=S):S=t[9];let C;t[10]===c?C=t[11]:(C=[c],t[10]=c,t[11]=C),Q.useLayoutEffect(S,C);let w;t[12]===a?w=t[13]:(w=e=>{let t=e.target.value;l(t),a(t)},t[12]=a,t[13]=w);let T;t[14]===u?T=t[15]:(T={height:u},t[14]=u,t[15]=T);let E=f?`overflow-y-auto`:`overflow-hidden`,D;t[16]===E?D=t[17]:(D=Y(`w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none`,E),t[16]=E,t[17]=D);let O;return t[18]!==i||t[19]!==_||t[20]!==c||t[21]!==o||t[22]!==r||t[23]!==T||t[24]!==D||t[25]!==w?(O=(0,$.jsx)(`textarea`,{ref:s,value:c,onChange:w,placeholder:r,disabled:i,rows:2,onKeyDown:o,onFocus:_,style:T,className:D,autoFocus:!0}),t[18]=i,t[19]=_,t[20]=c,t[21]=o,t[22]=r,t[23]=T,t[24]=D,t[25]=w,t[26]=O):O=t[26],O}),NR=({question:e})=>{let{t}=Yt(),n=na(e),r=Da,i=Xr,a=q(e=>e.isMobile),o=Ca(),s=X(e=>e.currentSessionId),c=Q.useMemo(()=>{if(!s||e.sessionID===s)return!1;let t=o.find(t=>t.id===e.sessionID);return!!(t?.parentID&&t.parentID===s)},[e.sessionID,s,o]),[l,u]=Q.useState(`0`),[d,f]=Q.useState(!1),p=d||n.claimed||n.pending===`delegate`||n.request?.state===`submitting`||n.request?.state===`uncertain`||n.request?.state===`settled`,[m,h]=Q.useState(!1),[g,_]=Q.useState({}),[v,y]=Q.useState({}),b=Q.useRef({}),[x,S]=Q.useState({}),C=Q.useMemo(()=>e.questions??[],[e.questions]),w=l===jR,T=w?-1:Math.max(0,Math.min(C.length-1,Number(l)||0)),E=w?null:C[T],D=Q.useMemo(()=>{if(w)return null;let e=E?.header?.trim();return e&&e.length>0?e:null},[E?.header,w]);Q.useEffect(()=>{u(`0`),_({}),y({}),b.current={},S({}),h(!1)},[e.id]);let O=Q.useMemo(()=>{let e=C.map((e,t)=>({value:String(t),label:e.header?.trim()||`Q${t+1}`}));return C.length>1&&e.push({value:jR,label:t(`chat.questionCard.summaryTab`)}),e},[C,t]),k=e=>{if(v[e])return(b.current[e]??``).trim()||t(`chat.questionCard.noAnswer`);let n=g[e]??[];return n.length>0?n.join(`, `):t(`chat.questionCard.noAnswer`)},A=!!E?.multiple,j=g[T]??[],M=!!v[T],N=Q.useMemo(()=>{let e=[];for(let t=0;t<C.length;t+=1){if(v[t]){x[t]||e.push(t);continue}(g[t]??[]).length===0&&e.push(t)}return e},[v,x,C.length,g]),P=Q.useMemo(()=>C.length!==0&&N.length===0,[C.length,N.length]),F=J(()=>{if(C.length===0||N.length===0)return;let e=w?-1:T;for(let t=1;t<=C.length;t+=1){let n=(e+t+C.length)%C.length;if(N.includes(n)){u(String(n));return}}u(String(N[0]))}),I=()=>{let e=[];for(let t=0;t<C.length;t+=1){if(v[t]){let n=(b.current[t]??``).trim();e.push(n?[n]:[]);continue}e.push(g[t]??[])}return e},L=J(e=>{E&&(y(e=>({...e,[T]:!1})),S(e=>e[T]?{...e,[T]:!1}:e),_(t=>{let n=t[T]??[];if(A){let r=n.includes(e)?n.filter(t=>t!==e):[...n,e];return{...t,[T]:r}}return{...t,[T]:[e]}}))}),R=J(()=>{y(e=>({...e,[T]:!0})),_(e=>({...e,[T]:[]}));let e=(b.current[T]??``).trim().length>0;S(t=>t[T]===e?t:{...t,[T]:e})}),z=J(e=>{b.current[T]=e;let t=e.trim().length>0;S(e=>e[T]===t?e:{...e,[T]:t})}),B=J(async()=>{if(!P||p)return;let i=n.scope;f(!0);try{let t=I();await r(e.sessionID,e.id,t,n.request?.directory),h(!0)}catch(e){zr(e)?await n.submissionClaimed(i):Hn(e)?(ro.info(t(`chat.questionCard.noLongerPending`)),h(!0)):ro.error(t(`chat.questionCard.submitFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{f(!1)}}),V=J(e=>{Lu(e)||e.key===`Enter`&&!e.shiftKey&&(!a||e.ctrlKey||e.metaKey)&&(e.preventDefault(),P?B():F())}),H=J(async()=>{if(p)return;let r=n.scope;f(!0);try{await i(e.sessionID,e.id,n.request?.directory),h(!0)}catch(e){zr(e)?await n.submissionClaimed(r):Hn(e)?(ro.info(t(`chat.questionCard.noLongerPending`)),h(!0)):ro.error(t(`chat.questionCard.dismissFailed`),{description:t(`chat.questionCard.tryAgain`)})}finally{f(!1)}}),ee=J(async()=>{let n=DR(e);if((await Jt(n)).ok){ro.success(t(`chat.questionCard.copiedMarkdown`));return}ro.error(t(`chat.questionCard.copyFailed`))}),U=J(async()=>{let n=OR(e);if((await Jt(n)).ok){ro.success(t(`chat.questionCard.copiedJson`));return}ro.error(t(`chat.questionCard.copyFailed`))});return m||C.length===0?null:(0,$.jsx)(`div`,{className:`group w-full pt-0 pb-2`,children:(0,$.jsx)(`div`,{className:`chat-column`,children:(0,$.jsxs)(`div`,{"data-question-card":!0,className:`-mt-1 border border-border/30 rounded-xl bg-muted/10`,onPointerDownCapture:n.interaction,onClickCapture:n.interaction,onKeyDownCapture:n.interaction,onInputCapture:n.interaction,onPasteCapture:n.interaction,onCompositionStartCapture:n.interaction,children:[(0,$.jsx)(`div`,{className:`px-2 py-1.5 border-b border-border/20`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`question`,className:`h-3.5 w-3.5 text-primary`}),(0,$.jsx)(`span`,{className:`typography-meta font-medium text-muted-foreground`,children:t(`chat.questionCard.inputNeeded`)}),c?(0,$.jsx)(`span`,{className:`typography-micro text-muted-foreground px-1.5 py-0.5 rounded bg-foreground/5`,children:t(`chat.questionCard.fromSubagent`)}):null,D?(0,$.jsx)(`span`,{className:`ml-auto typography-micro font-medium text-foreground/70 px-1.5 py-0.5 rounded bg-muted/30 border border-border/20`,children:D}):null,(0,$.jsxs)(`div`,{className:Y(`flex items-center gap-0.5`,D?null:`ml-auto`),children:[(0,$.jsx)(`button`,{type:`button`,onClick:ee,title:t(`chat.questionCard.copyMarkdown`),"aria-label":t(`chat.questionCard.copyMarkdown`),className:`flex items-center justify-center h-5 w-5 rounded text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,children:(0,$.jsx)(Z,{name:`file-text`,className:`h-3 w-3`})}),(0,$.jsx)(`button`,{type:`button`,onClick:U,title:t(`chat.questionCard.copyJson`),"aria-label":t(`chat.questionCard.copyJson`),className:`flex items-center justify-center h-5 w-5 rounded text-muted-foreground hover:text-foreground hover:bg-interactive-hover/30 transition-colors`,children:(0,$.jsx)(Z,{name:`code-box`,className:`h-3 w-3`})})]})]})}),(0,$.jsxs)(`div`,{className:`px-2 py-2`,children:[O.length>1?(0,$.jsx)(`div`,{className:`flex items-center gap-1 mb-2 flex-wrap`,children:O.map(e=>{let t=l===e.value,n=e.value===jR,r=n?-1:Number(e.value),i=!n&&Number.isFinite(r)&&!N.includes(r);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>u(e.value),className:Y(`px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1`,t?`bg-interactive-selection/40 text-foreground`:n?`text-muted-foreground hover:text-foreground hover:bg-interactive-hover/20`:i?`text-muted-foreground/60 hover:text-muted-foreground hover:bg-interactive-hover/20`:`text-foreground/85 hover:text-foreground hover:bg-interactive-hover/20`),children:[n?(0,$.jsx)(Z,{name:`list-check-3`,className:`h-3 w-3`}):null,e.label]},e.value)})}):null,w?(0,$.jsx)(`div`,{className:`space-y-2`,children:C.map((e,n)=>{let r=k(n),i=r!==t(`chat.questionCard.noAnswer`);return(0,$.jsxs)(`button`,{type:`button`,onClick:()=>u(String(n)),className:`w-full text-left rounded px-1.5 py-1 hover:bg-interactive-hover/20 transition-colors`,children:[(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground`,children:e.header||t(`chat.questionCard.questionFallback`,{index:n+1})}),(0,$.jsx)(`div`,{className:Y(`typography-meta`,i?`text-foreground`:`text-muted-foreground/50 italic`),children:r})]},n)})}):E?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`typography-meta font-medium text-foreground mb-1.5`,children:E.question}),A?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground mb-1.5`,children:t(`chat.questionCard.selectMultiple`)}):null,(0,$.jsxs)(`div`,{className:`space-y-0.5`,children:[E.options.map((e,n)=>{let r=j.includes(e.label),i=/\(recommended\)/i.test(e.label);return(0,$.jsx)(`button`,{type:`button`,onClick:()=>L(e.label),disabled:p,className:Y(`w-full px-1.5 py-1 text-left rounded transition-colors`,`hover:bg-interactive-hover/30`,r?`bg-interactive-selection/20`:null,p?`opacity-60 cursor-not-allowed`:null),children:(0,$.jsxs)(`div`,{className:`flex items-start gap-2`,children:[(0,$.jsx)(`div`,{className:`mt-0.5 shrink-0`,children:A?(0,$.jsx)(Oo,{checked:r,onChange:()=>L(e.label),disabled:p}):(0,$.jsx)(ts,{checked:r,onChange:()=>L(e.label),disabled:p})}),(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:Y(`typography-meta break-all`,r?`text-foreground font-medium`:`text-foreground/80`),children:e.label}),i?(0,$.jsx)(`span`,{className:`typography-micro text-primary/80`,children:t(`chat.questionCard.recommended`)}):null]}),e.description?(0,$.jsx)(`div`,{className:`typography-micro text-muted-foreground break-words`,children:e.description}):null]})]})},`${n}:${e.label}`)}),(0,$.jsx)(`button`,{type:`button`,onClick:R,disabled:p,className:Y(`w-full px-1.5 py-1 text-left rounded transition-colors`,`hover:bg-interactive-hover/30`,M?`bg-interactive-selection/20`:null,p?`opacity-60 cursor-not-allowed`:null),children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`edit`,className:Y(`h-3.5 w-3.5`,M?`text-primary`:`text-muted-foreground/50`)}),(0,$.jsx)(`span`,{className:Y(`typography-meta`,M?`text-foreground font-medium`:`text-muted-foreground`),children:t(`chat.questionCard.other`)})]})}),M?(0,$.jsx)(`div`,{className:`pl-6 pr-1 pt-0.5`,children:(0,$.jsx)(MR,{value:b.current[T]??``,onValueChange:z,placeholder:t(`chat.questionCard.yourAnswer`),disabled:p,onKeyDown:V})}):null]})]}):null]}),(0,$.jsx)(hr,{delegation:n}),(0,$.jsxs)(`div`,{className:`px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:P?B:F,disabled:p,className:Y(`flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors`,`bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]`,`disabled:opacity-50 disabled:cursor-not-allowed`),children:[P?(0,$.jsx)(Z,{name:`check`,className:`h-3 w-3`}):(0,$.jsx)(Z,{name:`arrow-right-s`,className:`h-3 w-3`}),t(P?`chat.questionCard.submit`:`chat.questionCard.next`)]}),(0,$.jsxs)(`button`,{type:`button`,onClick:H,disabled:p,className:Y(`flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors`,`bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]`,`disabled:opacity-50 disabled:cursor-not-allowed`),children:[(0,$.jsx)(Z,{name:`close`,className:`h-3 w-3`}),t(`chat.questionCard.dismiss`)]}),p?(0,$.jsx)(`div`,{className:`ml-auto`,children:(0,$.jsx)(`div`,{className:`animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full`})}):null]})]})})})};function PR(e){return e.filter(e=>e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(`
|
|
6584
|
+
`)}function FR(e,t=80){let n=PR(e).replace(/\n/g,` `);return n.length>t?`${n.slice(0,t)}…`:n}var IR=160,LR=28,RR=12,zR=6,BR=30,VR=12,HR=18,UR=80,WR=4,GR=10,KR=14,qR=20,JR=54,YR=4,XR=8,ZR=2,QR=160,$R=(e,t)=>e.map(e=>({turnId:e,preview:FR(t.get(e)??[],IR)})),ez=[1,.6,.35,.15],tz=(e,t,n)=>{let r=n?KR:GR;if(t===null)return r;let i=ez[Math.abs(e-t)]??0;return Math.round(r+(qR-r)*i)};function nz({turnIds:e,previewsByTurnId:t,activeTurnId:n,onSelectTurn:r,canLoadEarlier:i,isLoadingOlder:a,onLoadEarlier:o}){let{t:s}=Yt(),c=q(e=>e.isPromptNavigatorPanelOpen),l=q(e=>e.setPromptNavigatorPanelOpen),u=Q.useRef(null),d=Q.useRef(null),[f,p]=Q.useState(null),[m,h]=Q.useState(0),[g,_]=Q.useState(!1);Q.useEffect(()=>{let e=d.current?.parentElement;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.querySelector(`.chat-message-column`);if(!t){_(!1);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.right-zR-LR;_(r.right>i)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let v=Q.useMemo(()=>$R(e,t),[t,e]),y=Math.min(v.length,BR),b=Math.max(0,v.length-y),x=Math.min(m,b),S=x+y,C=x>0,w=S<v.length,T=s(`chat.timeline.noTextContent`),E=s(`chat.promptNavigator.currentPrompt`),D=s(`chat.promptNavigator.loadMore`),O=Q.useMemo(()=>n?v.findIndex(e=>e.turnId===n):-1,[n,v]),k=Q.useRef(x);k.current=x;let A=Q.useRef(v.length);A.current=v.length;let j=Q.useRef(null),M=Q.useRef(null),N=Q.useRef(0),P=Q.useCallback(e=>{h(t=>{let n=A.current,r=Math.min(n,BR),i=Math.max(0,n-r),a=Math.min(t,i);return e<a?e:e>=a+r?Math.min(i,e-r+1):a})},[]),F=Q.useRef(v[0]?.turnId),I=Q.useRef(v.length);Q.useLayoutEffect(()=>{let e=F.current,t=I.current,n=v.length-t;n>0&&t>0&&e&&v[0]?.turnId!==e&&(h(e=>e+n),p(e=>e===null?null:e+n)),F.current=v[0]?.turnId,I.current=v.length},[v]),Q.useEffect(()=>{if(f!==null)return;let e=O>=0?O:v.length-1;h(()=>{let t=A.current,n=Math.min(t,BR),r=Math.max(0,t-n);return Math.max(0,Math.min(r,e-Math.floor(n/2)))})},[O,f,v.length]);let L=Q.useCallback(e=>{let t=u.current;if(!t)return null;let n=t.getBoundingClientRect(),r=Math.floor((e-n.top)/VR),i=Math.min(A.current,BR);return i===0?null:Math.max(0,Math.min(i-1,r))},[]),R=Q.useCallback(()=>{N.current=0,M.current!==null&&(window.clearInterval(M.current),M.current=null)},[]),z=Q.useCallback(()=>{let e=N.current;if(e===0){R();return}let t=A.current,n=Math.max(0,t-Math.min(t,BR)),r=Math.min(k.current,n),i=Math.max(0,Math.min(n,r+e));if(i===r){R();return}k.current=i,h(i);let a=j.current;if(a!==null){let e=L(a);e!==null&&p(Math.min(t-1,i+e))}},[L,R]),B=Q.useCallback(e=>{let t=u.current;if(!t)return;let n=t.getBoundingClientRect(),r=e-n.top,i=0;if(r<=HR&&C?i=-1:r>=n.height-HR&&w&&(i=1),N.current=i,i===0){R();return}M.current===null&&(M.current=window.setInterval(z,UR))},[z,C,w,R]);Q.useEffect(()=>()=>{M.current!==null&&window.clearInterval(M.current)},[]);let V=Q.useRef(null),H=Q.useCallback(()=>{V.current!==null&&(window.clearTimeout(V.current),V.current=null)},[]),ee=Q.useCallback(()=>{H(),V.current=window.setTimeout(()=>{V.current=null,p(null)},QR)},[H]);Q.useEffect(()=>()=>{V.current!==null&&window.clearTimeout(V.current)},[]);let U=Q.useCallback(e=>{H(),j.current=e.clientY;let t=L(e.clientY);t!==null&&p(Math.min(A.current-1,k.current+t)),B(e.clientY)},[H,L,B]),te=Q.useCallback(()=>{j.current=null,R(),ee()},[ee,R]),W=Q.useCallback(()=>{l(!1)},[l]),ne=Q.useCallback(e=>{if(e===null)return;let t=v[e];t&&(r(t.turnId),R(),p(null),W(),u.current?.blur())},[W,r,v,R]),G=Q.useCallback(e=>{let t=L(e.clientY);t!==null&&ne(Math.min(v.length-1,k.current+t))},[ne,v.length,L]);Q.useEffect(()=>{if(!c)return;let e=u.current;!e||e===document.activeElement||(e.focus(),p(e=>{if(e!==null)return e;let t=O>=0?O:v.length-1;return P(t),t}))},[O,P,c,v.length]),Q.useEffect(()=>()=>{l(!1)},[l]);let re=Q.useCallback(e=>{if(v.length===0)return;let t=f??(O>=0?O:v.length-1),n=e=>{let t=Math.max(0,Math.min(v.length-1,e));P(t),p(t)};if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault(),n(t+(e.key===`ArrowUp`?-1:1));return}if(e.key===`Home`){e.preventDefault(),n(0);return}if(e.key===`End`){e.preventDefault(),n(v.length-1);return}if(e.key===`Enter`||e.key===` `){e.preventDefault(),ne(t);return}e.key===`Escape`&&(e.preventDefault(),p(null),W(),u.current?.blur())},[O,W,P,ne,f,v.length]),ie=Q.useCallback(()=>{R(),p(null),W()},[W,R]),K=Q.useRef(null),ae=Q.useRef(f);ae.current=f;let oe=f!==null,se=Q.useRef(0);Q.useEffect(()=>{let e=K.current;if(!e)return;let t=e=>{e.preventDefault(),e.stopPropagation(),se.current+=e.deltaY;let t=Math.trunc(se.current/JR);if(t===0)return;se.current-=t*JR;let n=ae.current;if(n===null)return;let r=Math.max(0,Math.min(A.current-1,n+t));r!==n&&(P(r),p(r))};return e.addEventListener(`wheel`,t,{passive:!1}),()=>e.removeEventListener(`wheel`,t)},[P,oe]);let ce=f===null?void 0:v[f],le=Math.min(v.length,XR),ue=le*JR,de=v.length*JR-ue,fe=e=>Math.max(0,Math.min(de,e)),pe=Q.useRef(null),me=0;if(f===null)pe.current=null;else if(pe.current===null)me=fe(f*JR-(ue-JR)/2),pe.current=me;else{let e=pe.current,t=(f-ZR)*JR,n=(f+1+ZR)*JR-ue;e>t?e=t:e<n&&(e=n),me=fe(e),pe.current=me}let he=Math.floor(me/JR),ge=Math.max(0,he-WR),_e=Math.min(v.length,he+le+WR),ve=me>0,ye=me<de,be=ve||ye?`linear-gradient(to bottom, ${ve?`transparent, black 10%`:`black`}, ${ye?`black 90%, transparent`:`black`})`:void 0,xe=Math.max(0,x-WR),Se=Math.min(v.length,S+WR),Ce=v.slice(xe,Se),we=C||w?`linear-gradient(to bottom, ${C?`transparent, black 14%`:`black`}, ${w?`black 86%, transparent`:`black`})`:void 0;return v.length===0?null:(0,$.jsx)(`nav`,{ref:d,"aria-label":s(`chat.promptNavigator.aria`),className:`pointer-events-none absolute right-1.5 top-1/2 z-20 -translate-y-1/2`,children:(0,$.jsxs)(`div`,{className:`pointer-events-auto flex flex-col items-end`,children:[i?(0,$.jsx)(`button`,{type:`button`,tabIndex:-1,className:Y(`-mr-px mb-1.5 flex size-5 shrink-0 items-center justify-center rounded-full`,`text-[var(--surface-mutedForeground)] transition-colors`,`hover:bg-[var(--interactive-hover)]/60 hover:text-[var(--surface-foreground)]`,a?`cursor-wait opacity-70`:void 0),"aria-label":D,title:D,disabled:a,onClick:e=>{e.stopPropagation(),a||o()},children:a?(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin`}):(0,$.jsx)(Z,{name:`arrow-up-s`,className:`size-3.5`})}):null,(0,$.jsxs)(`div`,{ref:u,role:`listbox`,tabIndex:-1,"aria-activedescendant":ce?`prompt-rail-tick-${ce.turnId}`:void 0,className:`relative cursor-pointer outline-none`,style:{width:`${g?RR:LR}px`,height:`${y*VR}px`},onMouseMove:U,onMouseLeave:te,onClick:G,onKeyDown:re,onBlur:ie,children:[(0,$.jsx)(`div`,{className:`absolute inset-0 overflow-hidden`,style:we?{maskImage:we,WebkitMaskImage:we}:void 0,children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-300 ease-out`,style:{transform:`translateY(-${x*VR}px)`},children:Ce.map((e,t)=>{let r=xe+t,i=e.turnId===n,a=f===r,o=tz(r,f,i);return(0,$.jsx)(`div`,{id:`prompt-rail-tick-${e.turnId}`,role:`option`,"aria-selected":a,"aria-current":i?`true`:void 0,"aria-label":e.preview.trim()||T,className:`pointer-events-none absolute right-1 flex items-center justify-end`,style:{top:`${r*VR}px`,height:`${VR}px`},children:(0,$.jsx)(`span`,{"aria-hidden":`true`,className:Y(`block h-0.5 rounded-full transition-all duration-200 ease-out`,i?`bg-[var(--surface-foreground)]`:a?`bg-[var(--surface-foreground)]/80`:`bg-[var(--surface-foreground)]/30`),style:{width:`${o}px`}})},e.turnId)})},v[0]?.turnId)}),ce&&f!==null?(0,$.jsx)(`div`,{ref:K,className:Y(`pointer-events-auto absolute right-full top-1/2 z-30 mr-3 -translate-y-1/2`,`w-[min(20rem,calc(100vw-6rem))] overflow-hidden rounded-xl`,`border border-[var(--interactive-border)]/60 bg-[var(--surface-elevated)] py-1 shadow-md`),onMouseEnter:H,onMouseLeave:ee,onMouseMove:e=>e.stopPropagation(),onClick:e=>e.stopPropagation(),children:(0,$.jsx)(`div`,{className:`relative overflow-hidden`,style:{height:`${le*JR}px`,maskImage:be,WebkitMaskImage:be},children:(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 transition-transform duration-200 ease-out`,style:{height:`${v.length*JR}px`,transform:`translateY(-${me}px)`},children:v.slice(ge,_e).map((e,t)=>{let r=ge+t,i=e.turnId===n,a=f===r;return(0,$.jsx)(`div`,{role:`option`,"aria-selected":a,"aria-current":i?`true`:void 0,title:i?E:void 0,className:`absolute inset-x-0 cursor-pointer px-1.5`,style:{top:`${r*JR+YR}px`,height:`46px`},onMouseMove:()=>{H(),ae.current!==r&&(P(r),p(r))},onClick:()=>ne(r),children:(0,$.jsx)(`div`,{className:Y(`flex h-full items-center rounded-lg border px-2 transition-colors`,i?`border-transparent bg-[var(--interactive-selection)]`:a?`border-[var(--interactive-border)]/60 bg-[var(--interactive-hover)]`:`border-[var(--interactive-border)]/40`),children:(0,$.jsx)(`span`,{className:Y(`min-w-0 flex-1 line-clamp-2 [overflow-wrap:anywhere] text-[length:calc(var(--text-meta)-0.0625rem)] leading-snug`,i?`text-[var(--interactive-selectionForeground)]`:`text-[var(--surface-mutedForeground)]`),children:e.preview.trim()||T})})},e.turnId)})})})}):null]})]})})}var rz=100,iz=(e,t)=>{if(e.length===0)return;let n=0,r=e.length-1,i=0;for(;n<=r;){let a=n+r>>1,o=e[a]?.top;if(o===void 0)break;if(o<=t){i=a,n=a+1;continue}r=a-1}return e[i]?.id},az=e=>{let t=e.raf??requestAnimationFrame,n=e.caf??cancelAnimationFrame,r=e.ResizeObserver??globalThis.ResizeObserver,i=e.MutationObserver??globalThis.MutationObserver,a,o,s,c,l,u,d=!0,f=new Map,p=[],m=()=>{c===void 0&&(c=t(()=>{c=void 0,g()}))},h=()=>{let e=a;if(!e){p=[],d=!1;return}let t=e.getBoundingClientRect().top;p=[...f].map(([n,r])=>({id:n,top:r.getBoundingClientRect().top-t+e.scrollTop})),p.sort((e,t)=>e.top-t.top),d=!1},g=()=>{let t=a;if(!t)return;d&&h();let n=iz(p,t.scrollTop+rz);!n||n===u||(u=n,e.onActive(n))},_=()=>{let e=a;if(e){if(clearTimeout(l),l=void 0,o?.disconnect(),o=void 0,r){o=new r(()=>{clearTimeout(l),l=setTimeout(()=>{d=!0,m()},100)}),o.observe(e);for(let e of f.values())o.observe(e)}if(s?.disconnect(),s=void 0,i){s=new i(()=>{d=!0,m()});let t={subtree:!0,childList:!0};r||(t.characterData=!0,t.characterDataOldValue=!1),s.observe(e,t)}d=!0,m()}},v=e=>{a!==e&&(a=e,u=void 0,_())},y=(e,t)=>{let n=f.get(t);n&&n!==e&&o?.unobserve(n),f.set(t,e),o&&o.observe(e),d=!0,m()},b=e=>{let t=f.get(e);t&&(o?.unobserve(t),f.delete(e),d=!0,m())},x=()=>{d=!0,m()},S=()=>{for(let e of f.values())o?.unobserve(e);f.clear(),p=[],u=void 0,d=!0};return{setContainer:v,register:y,unregister:b,onScroll:m,markDirty:x,clear:S,destroy:()=>{c!==void 0&&n(c),c=void 0,clearTimeout(l),l=void 0,S(),o?.disconnect(),s?.disconnect(),o=void 0,s=void 0,a=void 0},getActiveId:()=>u}},oz=10,sz=`${oz}vh`,cz=`80px`,lz=`calc(${cz} + var(--oc-chat-foot-inset))`,uz=(e,t)=>e?80:t<=0?96:Math.max(48,oz/100*t),dz=(e,t)=>({sessionId:e,viewportKey:t}),fz=(e,t)=>e?.sessionId===t?.sessionId&&e?.viewportKey===t?.viewportKey,pz=(e,t)=>fz(e,t),mz=(e,t,n)=>({identity:e,anchor:t,scrollPosition:n}),hz=150,gz=1500,_z=2,vz=350,yz=600,bz=8e3,xz=24,Sz=2,Cz=(e,t)=>e<t,wz=()=>typeof performance<`u`?performance.now():Date.now(),Tz=e=>({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}),Ez=e=>e.scrollHeight-e.scrollTop-e.clientHeight,Dz=e=>Ez(Tz(e)),Oz=e=>e.scrollHeight-e.clientHeight>1,kz=(e,t)=>Ez(e)<=uz(t,e.clientHeight),Az=({enabled:e=!0,currentSessionId:t,viewportKey:n,sessionMessageCount:r,sessionIsWorking:i,isMobile:a,onActiveTurnChange:o,onUpwardUserIntent:s})=>{let c=Q.useRef(null),[l,u]=Q.useState(null),d=Q.useRef(null),[f,p]=Q.useState(`following`),[m,h]=Q.useState(!1),[g,_]=Q.useState(!1),[v,y]=Q.useState(!1),b=Q.useRef(`following`),x=Q.useRef(a);x.current=a;let S=Q.useRef(r);S.current=r;let C=Q.useRef(dz(t,n));C.current=dz(t,n);let w=Q.useRef(null),T=Q.useRef(null),E=Q.useRef(null),D=Q.useRef(0),O=Q.useRef(null),k=Q.useRef(null),A=Q.useRef(0),j=Q.useRef(!1),M=Q.useRef(!1),N=Q.useRef(null),P=Q.useRef(0),F=J(()=>{P.current=wz()+450}),I=Q.useRef(0),L=Q.useRef(!1),R=Q.useRef(null),z=Q.useRef(null),B=Q.useRef(0),V=Q.useRef(!1),H=Q.useRef(null),ee=Q.useRef(null),U=Q.useRef(null),te=Xa(e=>e.updateViewportAnchor);Q.useLayoutEffect(()=>{c.current!==d.current&&(d.current=c.current,u(c.current))});let W=J(e=>{b.current!==e&&(b.current=e,p(e))}),ne=J(e=>{T.current={top:Math.max(0,e.scrollHeight-e.clientHeight),time:wz()},E.current&&clearTimeout(E.current),E.current=setTimeout(()=>{T.current=null,E.current=null},gz)}),G=J(e=>{let t=T.current;return t?wz()-t.time>gz?(T.current=null,!1):Math.abs(e.scrollTop-t.top)<_z:!1}),re=J(()=>wz()<A.current),ie=J(()=>{L.current=!1,R.current&&=(clearTimeout(R.current),null),z.current&&=(clearTimeout(z.current),null)}),K=J(()=>{R.current&&clearTimeout(R.current),R.current=setTimeout(()=>{R.current=null,ie()},yz)}),ae=J(()=>{let e=c.current;e&&(L.current=!0,B.current=e.scrollHeight,K(),z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{z.current=null,ie()},bz))}),oe=J(e=>{let t=c.current;if(!t){h(!1),_(!1);return}let n=e??Tz(t),r=Oz(n);if(h(r),!r){_(!1);return}let i=b.current===`released`&&!kz(n,x.current);_(i)}),se=J(()=>{D.current+=1,O.current!==null&&typeof window<`u`&&(window.cancelAnimationFrame(O.current),O.current=null),k.current?.(),k.current=null});Q.useEffect(()=>()=>se(),[l]);let ce=J(()=>{if(!e)return;let t=c.current;if(!t)return;se();let n=D.current,r=t.style.overflow,i=t.style.scrollBehavior;t.style.scrollBehavior=`auto`,t.style.overflow=`hidden`,t.scrollTop=t.scrollHeight,t.scrollHeight,t.style.overflow=r,t.style.scrollBehavior=i;let a=()=>{ne(t),t.scrollTop=t.scrollHeight,I.current=t.scrollTop};if(a(),oe(),typeof window>`u`)return;let o=0,s=()=>{Cz(wz(),P.current)||se()};t.addEventListener(`touchstart`,s,{passive:!0,once:!0}),k.current=()=>t.removeEventListener(`touchstart`,s);let l=()=>{if(n===D.current){if(Dz(t)>Sz&&a(),o+=1,o>=xz){O.current=null,k.current?.(),k.current=null,oe();return}O.current=window.requestAnimationFrame(l)}};O.current=window.requestAnimationFrame(l)}),le=J(e=>{let t=c.current;if(t){if(ne(t),e===`smooth`){t.scrollTo({top:t.scrollHeight,behavior:e});return}t.scrollTop=t.scrollHeight}}),ue=J((t,n=`auto`)=>{if(!e)return;let r=c.current;if(t&&b.current!==`following`&&W(`following`),r&&!(!t&&b.current!==`following`)){if(Dz(r)<_z){ne(r);return}le(t?n:`auto`)}}),de=J(e=>{let t=c.current;if(!t)return;let n=e??Tz(t);if(!Oz(n)){W(`following`);return}b.current!==`released`&&(W(`released`),oe(n))}),fe=J((e=`instant`)=>{if(V.current=!1,W(`following`),ie(),e===`instant`){ce();return}se(),ue(!0,`smooth`),oe()}),pe=J(()=>{V.current=!1,ue(!0)}),me=J(()=>{se(),ie(),W(`released`),oe()}),he=J(()=>{V.current=!0,me()}),ge=J(()=>{V.current=!1}),_e=Q.useRef(s);_e.current=s;let ve=J(()=>{Cz(wz(),P.current)||(se(),ie(),de())}),ye=J(()=>{ve(),_e.current?.()}),be=J(()=>{H.current!==null&&(clearTimeout(H.current),H.current=null);let e=ee.current;if(e){if(!e.identity.sessionId){ee.current=null;return}te(e.identity.sessionId,e.anchor,e.scrollPosition,e.identity.viewportKey),ee.current=null}}),xe=J(()=>{let e=C.current;if(!e.sessionId)return;let t=c.current;if(!t)return;let{scrollTop:n,scrollHeight:r,clientHeight:i}=t,a=r>0?(n+i/2)/r:0,o=Math.floor(a*S.current);ee.current=mz(e,o,{scrollTop:n,scrollHeight:r,clientHeight:i}),H.current===null&&(H.current=setTimeout(()=>{H.current=null,be()},hz))}),Se=J(()=>{be()}),Ce=J(async(e=C.current)=>{if(!e.sessionId)return!1;V.current=!1;let t=gi(e.sessionId,e.viewportKey);return c.current?(U.current=null,I.current=t?.scrollPosition?.scrollTop??0,W(`following`),F(),x.current?ce():ue(!0),ae(),oe(),!1):(U.current=e,W(`following`),!1)});Q.useEffect(()=>{let e=C.current,n=w.current;fz(e,n)||(be(),se(),F(),w.current=e,T.current=null,I.current=0,ie(),V.current=!1,W(`following`),U.current=null,t&&t!==n?.sessionId&&CT.getInstance().recordSessionStart(t))},[t,n]),Q.useEffect(()=>{i&&!V.current&&b.current===`following`&&ue(!0)},[i]),Q.useEffect(()=>{y(f===`following`&&i)},[f,i]),Q.useLayoutEffect(()=>{if(!l)return;let e=U.current;e&&pz(e,C.current)&&Ce(e)},[l,t,n]);let we=J(()=>{let e=c.current;if(!e)return;let t=Tz(e),n=I.current;I.current=t.scrollTop;let r=t.scrollTop>n+.5,i=Math.abs(t.scrollTop-n)<.5;if(oe(t),V.current){xe();return}if(!Oz(t)){W(`following`);return}if(kz(t,x.current)){let e=Math.min(n,Math.max(0,t.scrollHeight-t.clientHeight));if(t.scrollTop<e-.5){ve(),xe();return}(r||b.current===`following`)&&W(`following`),xe();return}if(b.current===`following`&&(G(e)||re()||i)){j.current||ue(!1),xe();return}de(t),xe()});Q.useEffect(()=>{!e||!l||(I.current=l.scrollTop)},[l,e]);let Te=Q.useRef(null),Ee=J(e=>{let t=c.current;t&&(e.deltaY>=0||Ju(t,e.target)||ye())}),De=J(e=>{let t=e.touches.item(0);Te.current=t?{x:t.clientX,y:t.clientY,dx:0,dy:0}:null}),Oe=J(e=>{let t=c.current,n=e.touches.item(0);if(!n){Te.current=null;return}let r=Te.current;if(!r)return;let i=n.clientY-r.y,a=i*r.dy<0,o=(a?0:r.dx)+n.clientX-r.x,s=(a?0:r.dy)+i;if(Te.current={x:n.clientX,y:n.clientY,dx:o,dy:s},!(s<=0||Math.abs(o)>=s)&&t){if(Ju(t,e.target)){Te.current.dx=0,Te.current.dy=0;return}s<=2||ye()}}),ke=J(()=>{Te.current=null}),Ae=J(e=>{zu(e)&&ye()}),je=J(e=>{let t=e.target;t instanceof Element&&t.closest(`[data-overlay-scrollbar-thumb]`)&&ve()}),Me=Q.useMemo(()=>()=>void 0,[]),Ne=e&&l?l:Me,Pe=Q.useMemo(()=>({passive:!0}),[]);Kt(`scroll`,we,Ne,Pe),Kt(`wheel`,Ee,Ne,Pe),Kt(`touchstart`,De,Ne,Pe),Kt(`touchmove`,Oe,Ne,Pe),Kt(`touchend`,ke,Ne,Pe),Kt(`touchcancel`,ke,Ne,Pe),Kt(`keydown`,Ae,Ne),Kt(`pointerdown`,je,e&&typeof window<`u`?window:Me,!0);let Fe=J(()=>{let e=c.current;if(j.current){oe(e?Tz(e):void 0);return}if(V.current){oe(e?Tz(e):void 0);return}if(!e){oe(void 0);return}let t=Tz(e);if(!Oz(t)){W(`following`),oe(t);return}if(oe(t),L.current){let n=t.scrollHeight>B.current+1;B.current=t.scrollHeight,Ez(t)<=_z?ne(e):ue(!0),n&&K();return}if(b.current===`following`){if(Ez(t)<=_z){ne(e);return}ue(!1)}}),Ie=typeof ResizeObserver<`u`,Le=Ie&&e?l:null,Re=Ie&&e&&l&&l.firstElementChild instanceof Element?l.firstElementChild:null;Vt(Le,Fe),Vt(Re,Fe);let ze=J(()=>{N.current!==null&&(clearTimeout(N.current),N.current=null)}),Be=J(e=>{j.current=!0,typeof e==`number`&&e>0?A.current=wz()+e+vz:A.current=Math.max(A.current,wz()+vz)}),Ve=J(e=>{let t=e.detail;if(t){if(t.open===!0){Be(),ze(),N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},1500);return}ze(),Be()}}),He=J(e=>{let t=e.detail;t&&(ze(),Be(t.durationMs))}),Ue=J(e=>{let t=e.detail;ze(),t?.open===!0?(M.current=!0,j.current=!0):(M.current=!1,j.current=!0,N.current=setTimeout(()=>{N.current=null,M.current||(j.current=!1)},vz)),oe()}),We=e&&typeof window<`u`?window:Me;Kt(`oc:keyboard-intent`,Ve,We),Kt(`oc:keyboard-anim`,He,We),Kt(`oc:keyboard-settled`,Ue,We),Q.useEffect(()=>{if(!(!e||typeof window>`u`))return()=>{ze(),j.current=!1,M.current=!1}},[e]),Q.useEffect(()=>{e&&oe()},[e,r]);let Ge=J(t=>{if(e){if(t===`animation`&&(A.current=wz()+vz),oe(),L.current){ue(!0),K();return}b.current===`following`&&ue(!1)}}),Ke=Q.useRef(new Map),qe=J(t=>{let n=Ke.current.get(t);if(n)return n;let r=()=>{e&&b.current===`following`&&ue(!1)},i={onChunk:r,onComplete:()=>{e&&oe()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:r,onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return Ke.current.set(t,i),i});Q.useEffect(()=>()=>{E.current&&=(clearTimeout(E.current),null),se(),ie(),be(),H.current!==null&&(clearTimeout(H.current),H.current=null)},[]);let Je=J(e=>{o?.(e)}),Ye=!!o;return Q.useEffect(()=>{if(!e||!Ye)return;let t=l;if(!t)return;let n=null,r=az({onActive:e=>{e!==n&&(n=e,Je(e))}});r.setContainer(t);let i=new Map,a=e=>{let t=e.dataset.turnId;return t?(i.set(t,e),r.register(e,t),!0):!1},o=e=>{let t=e.dataset.turnId;return!t||i.get(t)!==e?!1:(i.delete(t),r.unregister(t),!0)},s=e=>{if(!(e instanceof HTMLElement))return[];let t=[];return e.matches(`[data-turn-id]`)&&t.push(e),e.querySelectorAll(`[data-turn-id]`).forEach(e=>t.push(e)),t};t.querySelectorAll(`[data-turn-id]`).forEach(a),r.markDirty();let c=new MutationObserver(e=>{let t=!1;e.forEach(e=>{e.removedNodes.forEach(e=>{s(e).forEach(e=>{o(e)&&(t=!0)})}),e.addedNodes.forEach(e=>{s(e).forEach(e=>{a(e)&&(t=!0)})})}),t&&r.markDirty()});c.observe(t,{subtree:!0,childList:!0});let u=()=>r.onScroll();return t.addEventListener(`scroll`,u,{passive:!0}),()=>{t.removeEventListener(`scroll`,u),c.disconnect(),r.destroy()}},[l,e,Ye]),{scrollRef:c,state:f,isPinned:f===`following`,isOverflowing:m,isFollowingProgrammatically:v,showScrollButton:g,notifyContentChange:Ge,getAnimationHandlers:qe,goToBottom:fe,scrollToBottomOnSend:pe,releaseAutoFollow:me,beginHistoryViewportPreservation:he,endHistoryViewportPreservation:ge,saveSnapshotNow:Se,restoreSnapshot:Ce}},jz=`--oc-mobile-composer-swap`,Mz=`--oc-native-composer-dock`,Nz=()=>({phase:`rest`,rest:`expanded`,progress:0,pinned:!1}),Pz=(e,t,n)=>Math.min(n,Math.max(t,e)),Fz=(e,t)=>e.phase===t.phase&&e.rest===t.rest&&e.progress===t.progress&&e.pinned===t.pinned,Iz=(e,t)=>{let n={phase:t.phase,rest:t.rest,progress:t.progress,pinned:t.pinned??e.pinned};return Fz(e,n)?e:n},Lz=(e,t)=>t?Iz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0}):e.pinned?Iz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!1}):e,Rz=(e,t)=>{if(e.pinned&&t===`compact`)return e;let n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Iz(e,{phase:`snapping`,rest:t,progress:n})},zz=e=>Pz(e/80,0,1),Bz=e=>e>=80?1:Pz(e/80,0,1),Vz=(e,t,n={})=>{if(e.pinned||n.userDriven===!1)return e;let r=Math.max(0,t),i=e.phase===`snapping`?Iz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e;if(i.rest===`expanded`){if(r<=2||n.holdExpanded)return Iz(i,{phase:`rest`,rest:`expanded`,progress:0});let e=zz(r);return e>=1?Iz(i,{phase:`rest`,rest:`compact`,progress:1}):Iz(i,{phase:`tracking`,rest:`expanded`,progress:e})}if(r<=2)return Iz(i,{phase:`rest`,rest:`expanded`,progress:0});if(n.suppressReturn)return Iz(i,{phase:`rest`,rest:`compact`,progress:1});if(n.towardBottom&&r>=80)return Iz(i,{phase:`snapping`,rest:`expanded`,progress:0});let a=Bz(r);return a>=1?Iz(i,{phase:`rest`,rest:`compact`,progress:1}):Iz(i,{phase:`tracking`,rest:`compact`,progress:a})},Hz=e=>e.pinned?`expanded`:e.rest===`expanded`?e.progress>=.5?`compact`:`expanded`:e.progress<=.5?`expanded`:`compact`,Uz=e=>{if(e.pinned)return Iz(e,{phase:`rest`,rest:`expanded`,progress:0,pinned:!0});if(e.phase===`snapping`)return e;let t=Hz(e),n=+(t===`compact`);return e.phase===`rest`&&e.rest===t&&e.progress===n?e:Iz(e,{phase:`snapping`,rest:t,progress:n})},Wz=e=>e.phase===`snapping`?Iz(e,{phase:`rest`,rest:e.rest,progress:+(e.rest===`compact`)}):e,Gz=e=>Pz(Math.max(0,e)/80,0,1),Kz=(e,t=`away`)=>{let n=Math.max(0,e);return n<=2?{progress:0,rest:`bottom`}:t===`away`||n>=40?{progress:1,rest:`away`}:{progress:Gz(n),rest:`bottom`}},qz=e=>{e.style.removeProperty(jz),e.style.removeProperty(Mz),delete e.dataset.ocComposerSwapPhase,delete e.dataset.ocComposerSwapRest,delete e.dataset.ocNativeComposerDock},Jz=(e,t,n)=>{let r=Kz(t,n?.rest===`bottom`?`bottom`:`away`),i=String(r.progress),a=r.rest;return n?.progress!==i&&e.style.setProperty(Mz,i),n?.rest!==a&&(e.dataset.ocNativeComposerDock=a),{progress:i,rest:a}},Yz=(e,t,n)=>{let r=String(t.progress),i=t.phase,a=t.rest;return n?.phase!==i&&(e.dataset.ocComposerSwapPhase=i,i===`snapping`&&n&&n.phase!==`snapping`&&e.offsetWidth),n?.progress!==r&&e.style.setProperty(jz,r),n?.rest!==a&&(e.dataset.ocComposerSwapRest=a),{progress:r,phase:i,rest:a}},Xz=e=>({scrollHeight:e.scrollHeight,scrollTop:e.scrollTop,clientHeight:e.clientHeight}),Zz=()=>{let e=document.documentElement;return e.classList.contains(`oc-keyboard-open`)||e.classList.contains(`oc-kb-animating`)},Qz=e=>{if(Zz()||e.querySelector(`[data-oc-composer-dictation-active="true"]`))return!0;let t=document.activeElement;return t instanceof HTMLElement&&t.matches(`textarea[data-chat-input="true"]`)&&e.contains(t)},$z=e=>{let t=Q.useRef(Nz()),n=Q.useRef(void 0),r=Q.useRef(void 0),i=Q.useRef(null),a=Q.useRef(null),o=Q.useRef(0),s=Q.useRef(!1),c=Q.useRef(0),l=Q.useRef(new Map),u=Q.useRef(!1),d=Q.useRef(0),f=Q.useRef(null),p=Q.useRef(null),m=Q.useRef(0),h=Q.useRef(0),g=Q.useRef(!1),_=Q.useRef(e.enabled);_.current=e.enabled;let v=e=>{e.current!==null&&(window.clearTimeout(e.current),e.current=null)},y=J(t=>{let r=e.scopeRef.current;r&&(n.current=Yz(r,t,n.current))}),b=J(e=>{e!==t.current&&(t.current=e,y(e))}),x=J(()=>{if(v(a),t.current.phase!==`snapping`)return;let e=t.current.rest;a.current=window.setTimeout(()=>{a.current=null;let n=Wz(t.current);b(n),n.rest===`compact`&&e===`compact`&&(o.current=Date.now()+320,s.current=!0)},240)}),S=J(()=>{let n=e.scopeRef.current;!n||!_.current||b(Lz(t.current,Qz(n)))}),C=J(e=>s.current?Date.now()>=o.current?(s.current=!1,!1):e>=80?(s.current=!1,o.current=0,!1):!0:!1),w=J(()=>{if(v(i),!_.current||c.current>0||t.current.phase!==`tracking`)return;let e=Uz(t.current);b(e),x()}),T=J(()=>{u.current=!1,d.current=0;for(let e of l.current.values())e.startX=e.currentX,e.startY=e.currentY}),E=J(e=>{if(!_.current)return;let t=!1;for(let n=0;n<e.changedTouches.length;n+=1){let r=e.changedTouches[n];if(!r)continue;let i=l.current.get(r.identifier);if(!i){l.current.set(r.identifier,{startX:r.clientX,startY:r.clientY,currentX:r.clientX,currentY:r.clientY});continue}i.currentX=r.clientX,i.currentY=r.clientY;let a=Math.abs(i.currentX-i.startX),o=Math.abs(i.currentY-i.startY);o>0&&o>a&&(t=!0)}!t&&!u.current||(u.current=!0,d.current=Date.now(),s.current=!1,o.current=0)}),D=J(t=>{if(_.current){if(c.current===0){l.current.clear(),T(),m.current=0,h.current=0;let t=e.scrollRef.current;if(t){let e=Xz(t);p.current=e,f.current=rI(e,tI(t))}}for(let e=0;e<t.changedTouches.length;e+=1){let n=t.changedTouches[e];n&&l.current.set(n.identifier,{startX:n.clientX,startY:n.clientY,currentX:n.clientX,currentY:n.clientY})}c.current=l.current.size,v(i)}}),O=J(()=>{if(!_.current)return;let n=e.scrollRef.current,o=e.scopeRef.current;if(!n||!o)return;let s=Qz(o),l=Xz(n),y=rI(l,tI(n)),S=f.current,E=p.current;if(f.current=y,p.current=l,n.hasAttribute(`data-oc-timeline-anchoring`)){m.current=0,h.current=0,T();return}r.current=Jz(o,y,r.current);let D=u.current&&(c.current>0||Date.now()-d.current<=1200),O=E!==null&&(E.scrollHeight!==l.scrollHeight||E.clientHeight!==l.clientHeight),k=D&&!O,A=S===null?0:S-y;k?A>0?(h.current=0,l.scrollTop>0&&(m.current+=A)):A<0&&(m.current=0,h.current+=-A,h.current>=24&&(g.current=!1)):(m.current=0,h.current=0),k&&y<=2&&(g.current=!1);let j=t.current,M=Lz(j,s);if(!s){let e=M.rest===`compact`;M=Vz(M,y,{suppressReturn:k&&C(y),towardBottom:m.current>=24,holdExpanded:g.current,userDriven:k}),e&&M.rest===`expanded`&&y>2&&(g.current=!0,m.current=0)}if(b(M),k){if(v(i),M.phase===`snapping`){(j.phase!==`snapping`||j.rest!==M.rest||j.progress!==M.progress)&&x();return}j.phase===`snapping`&&v(a),M.phase===`tracking`&&c.current===0&&(i.current=window.setTimeout(()=>{i.current=null,w()},120))}}),k=J(()=>{u.current&&(c.current>0||Date.now()-d.current<=1200)&&w()}),A=J((e,n)=>{if(_.current){for(let t=0;t<e.changedTouches.length;t+=1){let n=e.changedTouches[t];n&&l.current.delete(n.identifier)}c.current=l.current.size,!(c.current>0)&&(l.current.clear(),n&&u.current?d.current=Date.now():T(),t.current.phase===`tracking`&&(v(i),i.current=window.setTimeout(()=>{i.current=null,w()},120)))}}),j=J(e=>{A(e,!0)}),M=J(e=>{A(e,!1)}),N=J(()=>{let t=e.scopeRef.current;if(!t||typeof window>`u`)return;let n=e=>{e.preventDefault(),e.stopPropagation()};t.addEventListener(`pointerup`,n,!0),t.addEventListener(`click`,n,!0),window.setTimeout(()=>{t.removeEventListener(`pointerup`,n,!0),t.removeEventListener(`click`,n,!0)},240)}),P=J(n=>{if(!_.current)return;let r=n.target;r instanceof Element&&r.closest(`[data-oc-composer-compact-surface="true"]`)&&(r.closest(`[data-composer-action="true"]`)||(`preventDefault`in n&&n.preventDefault(),`stopPropagation`in n&&n.stopPropagation(),g.current=!0,m.current=0,h.current=0,b(Rz(t.current,`expanded`)),x(),N(),(e.scopeRef.current?.querySelector(`textarea[data-chat-input="true"]`))?.focus({preventScroll:!0})))}),[F,I]=Q.useState(null),[L,R]=Q.useState(null),z=Q.useRef(null),B=J(e=>{e&&qz(e),n.current=void 0,r.current=void 0,s.current=!1,o.current=0,c.current=0,l.current.clear(),u.current=!1,d.current=0,f.current=null,p.current=null,m.current=0,h.current=0,g.current=!1,b(Nz())});Q.useLayoutEffect(()=>{let t=e.enabled?e.scrollRef.current:null,n=e.enabled?e.scopeRef.current:null;z.current&&z.current!==n&&B(z.current),z.current=n,I(e=>e===t?e:t),R(e=>e===n?e:n)});let V=Q.useMemo(()=>()=>void 0,[]),H=e.enabled&&F?F:V,ee=e.enabled&&L?L:V,U=e.enabled&&typeof window<`u`?window:V,te=Q.useMemo(()=>({passive:!0}),[]);Kt(`scroll`,O,H,te),Kt(`scrollend`,k,H,te),Kt(`touchstart`,D,H,te),Kt(`touchmove`,E,H,te),Kt(`touchend`,j,H,te),Kt(`touchcancel`,M,H,te),Kt(`pointerdown`,P,ee),Kt(`focusin`,S,ee),Kt(`focusout`,S,ee),Kt(`oc:keyboard-intent`,S,U),Kt(`oc:keyboard-anim`,S,U),Kt(`oc:keyboard-settled`,S,U),Q.useEffect(()=>{if(!e.enabled){B(z.current),z.current=null;return}return S(),O(),()=>{v(i),v(a)}},[e.enabled,F,L])},eB=e=>{let t=e.info.clientRole??e.info.role;return typeof t==`string`?t:``},tB=e=>{let t=e.info.parentID;if(typeof t==`string`&&t.trim().length!==0)return t},nB=e=>{if(!e)return null;let t=eB(e);return`${typeof e.info?.id==`string`?e.info.id:``}::${t}::${tB(e)??``}`},rB=e=>({turnIds:[...e.turnIds],turnMessageStartIndexes:[...e.turnMessageStartIndexes],turnIndexById:new Map(e.turnIndexById),messageToTurnId:new Map(e.messageToTurnId),messageToTurnIndex:new Map(e.messageToTurnIndex),turnCount:e.turnCount}),iB=(e,t,n)=>{if(!e||!t)return null;if(t.length===n.length){let r=-1;for(let e=0;e<n.length;e+=1)if(t[e]!==n[e]){if(r!==-1)return null;r=e}return r===-1||r===n.length-1&&nB(t[r])===nB(n[r])?e:null}if(n.length!==t.length+1)return null;for(let e=0;e<t.length;e+=1)if(t[e]!==n[e])return null;let r=n[n.length-1];if(!r)return null;let i=eB(r),a=r.info.id,o=rB(e);if(i===`user`){let e=o.turnIds.length;return o.turnIds.push(a),o.turnMessageStartIndexes.push(n.length-1),o.turnIndexById.set(a,e),o.messageToTurnId.set(a,a),o.messageToTurnIndex.set(a,e),o.turnCount=o.turnIds.length,o}if(i!==`assistant`){let e=o.turnIds.length-1;if(e<0)return null;let t=o.turnIds[e];return t?(o.messageToTurnId.set(a,t),o.messageToTurnIndex.set(a,e),o):null}let s=tB(r);if(!s)return o;let c=o.turnIndexById.get(s);if(typeof c!=`number`||c<0)return null;let l=o.turnIds[c];return l?(o.messageToTurnId.set(a,l),o.messageToTurnIndex.set(a,c),o):null},aB=e=>{let t=[],n=[],r=new Map,i=new Map,a=new Map,o=new Map,s=-1;return e.forEach((e,c)=>{let l=eB(e),u=e.info.id;if(l===`user`){s=t.length,t.push(u),n.push(c),r.set(u,s),o.set(u,s),i.set(u,u),a.set(u,s);return}if(l!==`assistant`){if(s>=0){let e=t[s];e&&(i.set(u,e),a.set(u,s))}return}let d=tB(e);if(!d)return;let f=o.get(d);if(typeof f!=`number`||f<0)return;let p=t[f];p&&(i.set(u,p),a.set(u,f))}),{turnIds:t,turnMessageStartIndexes:n,turnIndexById:r,messageToTurnId:i,messageToTurnIndex:a,turnCount:t.length}},oB=200,sB={MAX_SESSIONS:3,ZOMBIE_TIMEOUT:6e5},cB=()=>oB,lB=()=>Math.round(cB()*.6),uB={MAX_SESSIONS:sB.MAX_SESSIONS,VIEWPORT_MESSAGES:Math.round(oB*.6),HISTORICAL_MESSAGES:oB,FETCH_BUFFER:20,HISTORY_CHUNK:oB,STREAMING_BUFFER:1/0,ZOMBIE_TIMEOUT:sB.ZOMBIE_TIMEOUT},dB=()=>{let e=cB(),t=lB();return{...uB,HISTORICAL_MESSAGES:e,VIEWPORT_MESSAGES:t,HISTORY_CHUNK:e}},fB=uB,pB=600,mB=6e3,hB=.5,gB=(e,t)=>e.querySelector(`[data-message-id="${CSS.escape(t)}"]`),_B=e=>{let t=e.getBoundingClientRect(),n=e.querySelectorAll(`[data-message-id]`);for(let e of n)if(e.getBoundingClientRect().bottom>t.top)return e;return null},vB=(e,t)=>{let n=gB(e,t);if(n||=_B(e),!n)return null;let r=n.dataset.messageId;if(!r)return null;let i=e.getBoundingClientRect();return{messageId:r,offsetTop:n.getBoundingClientRect().top-i.top}},yB=e=>{let{container:t,quiesceMs:n=pB,maxLifetimeMs:r=mB}=e,i={messageId:e.anchor.messageId,offsetTop:e.anchor.offsetTop},a=!1,o=null,s=null,c=!1,l=t.scrollTop,u=()=>{o!==null&&(clearTimeout(o),o=null)},d=()=>{s!==null&&(clearTimeout(s),s=null)},f=()=>{a||(a=!0,y.disconnect(),t.removeEventListener(`scroll`,v),u(),d())},p=()=>{u(),!a&&(o=setTimeout(()=>{o=null,f()},n))},m=()=>{d(),!a&&(s=setTimeout(()=>{s=null,f()},r))},h=()=>{if(a)return;let e=vB(t,i.messageId);if(!e){f();return}i.messageId=e.messageId,i.offsetTop=e.offsetTop,l=t.scrollTop},g=()=>{if(a)return;if(Math.abs(t.scrollTop-l)>hB){h();return}let e=gB(t,i.messageId);if(!e){let n=_B(t);if(!n){f();return}let r=n.dataset.messageId;if(!r){f();return}let a=t.getBoundingClientRect();i.messageId=r,i.offsetTop=n.getBoundingClientRect().top-a.top,e=n,l=t.scrollTop}let n=t.getBoundingClientRect(),r=e.getBoundingClientRect().top-n.top-i.offsetTop;Math.abs(r)>hB&&(t.scrollTop+=r),l=t.scrollTop},_=()=>{a||c||(c=!0,queueMicrotask(()=>{c=!1,g()}))},v=()=>{h(),p(),m()},y=new MutationObserver(()=>{a||(_(),p())});return y.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`style`,`class`]}),t.addEventListener(`scroll`,v,{passive:!0}),m(),p(),{rebase:h,dispose:f}},bB=30,xB=1200,SB=1.5,CB=e=>Math.max(xB,e*SB),wB=4,TB=30,EB=4,DB=30,OB=250,kB=2e3,AB=mr+2e3,jB=40,MB=`history-loading-timeout`,NB=e=>!!(e&&typeof e==`object`&&e.code===`history-loading-timeout`),PB=()=>{let e=Error(`chat history pagination wait timed out`);return e.code=MB,e},FB=(e,t,n)=>{if(e===`no-growth`){console.error(`[chat-history] load older completed without prepending messages`,t instanceof Error?t:Error(`chat history pagination returned no growth`),n);return}if(e===`timeout`){console.error(`[chat-history] load older timed out waiting for sync pagination`,t,n);return}console.error(`[chat-history] load older failed`,t,n)},IB=2500,LB=new Map,RB=()=>ge()?wB:yr()?EB:bB,zB=e=>ge()?e.length<=TB:!yr()||e.length<=DB,BB=(e,t)=>{if(LB.delete(e),!zB(t.messages))return;let n=RB();for(;LB.size>=n;){let e=LB.keys().next().value;if(typeof e!=`string`)break;LB.delete(e)}LB.set(e,t)},VB=e=>!!(e.previousOldestId&&e.currentOldestId&&e.currentOldestId!==e.previousOldestId&&e.previousNewestId&&e.currentNewestId&&e.currentNewestId===e.previousNewestId),HB=e=>e?{owner:`tanstack-core`}:{owner:`controller`},UB=(e,t)=>e?e.canLoadEarlier:t>=dB().HISTORICAL_MESSAGES,WB=e=>!(e.isMobile||e.isLoadingOlder||e.pendingRevealWork||!e.canLoadEarlier||e.source===`scroll`&&e.isPinned||e.scrollTop>=CB(e.clientHeight)),GB=e=>e.pagesLoaded>=e.maxPages?`stop-bounded`:e.hasMoreAbove?e.scrollHeightAfter-e.scrollHeightBefore>1?`stop-visible`:e.messageCountAfter>e.messageCountBefore||typeof e.oldestIdBefore==`string`&&typeof e.oldestIdAfter==`string`&&e.oldestIdBefore!==e.oldestIdAfter||e.limitAfter>e.limitBefore?`continue`:`stop-no-growth`:`stop-exhausted`,KB=1,qB=8,JB=e=>!(!e.enabled||e.isMobile||!e.sessionReady||!e.messageReady||e.historyLoading||!e.canLoadEarlier||!e.isPinned||e.fillBlocked||e.pendingRevealWork||e.isLoadingOlder||!e.hasMessages||e.clientHeight<=0||e.scrollHeight>e.clientHeight+48),YB=e=>[`chat-timeline-auto-fill`,e.runtimeKey,e.sessionId,e.oldestMessageId,e.messageCount,e.canLoadEarlier],XB=e=>[`chat-timeline-load-earlier`,e.runtimeKey,e.sessionId],ZB=20,QB=4,$B=80,eV=new WeakMap,tV=new WeakMap,nV=e=>{let t=tV.get(e)??{generation:0};return t.generation+=1,tV.set(e,t),t.generation},rV=e=>{let t=eV.get(e);t&&(t.touches=0,t.pending=null,t.settleScheduled=!1),nV(e)},iV=e=>{aV(e)},aV=e=>{let t=eV.get(e);if(t)return t;let n={touches:0,pending:null,settleScheduled:!1};e.addEventListener(`touchstart`,()=>{n.touches+=1},{passive:!0});let r=()=>{n.touches=Math.max(0,n.touches-1),n.touches===0&&n.pending&&oV(e,n)};return e.addEventListener(`touchend`,r,{passive:!0}),e.addEventListener(`touchcancel`,r,{passive:!0}),eV.set(e,n),n},oV=(e,t)=>{t.settleScheduled||typeof window>`u`||(t.settleScheduled=!0,window.requestAnimationFrame(()=>{t.settleScheduled=!1;let n=t.pending;t.pending=null,!(!n||t.touches>0||!e.isConnected)&&(Math.abs(e.scrollTop-n.anchorTop)>n.delta+$B||sV(e,n.anchorTop+n.delta))}))},sV=(e,t)=>{let n=nV(e),r=e.style.overflow;if(e.style.overflow=`hidden`,e.scrollTop=t,e.scrollHeight,e.style.overflow=r,e.scrollTop=t,typeof window>`u`)return;let i=!1,a=0,o=()=>{i=!0};e.addEventListener(`touchstart`,o,{passive:!0,once:!0});let s=()=>{if(!i){if((tV.get(e)?.generation??0)!==n){e.removeEventListener(`touchstart`,o);return}e.scrollTop<t-QB&&(e.scrollTop=t),a+=1,a<ZB?window.requestAnimationFrame(s):e.removeEventListener(`touchstart`,o)}};window.requestAnimationFrame(s)},cV=(e,t,n)=>{let r=aV(e);if(r.touches>0&&typeof n==`number`&&n>0){r.pending=r.pending?{anchorTop:r.pending.anchorTop,delta:r.pending.delta+n}:{anchorTop:e.scrollTop,delta:n};return}r.pending=null,sV(e,t)},lV=(e,t,n)=>!e||!t||t===e?!1:n.some(t=>t.info.id===e),uV=(e,t)=>e.scrollHeight===t.scrollHeight&&e.clientHeight===t.clientHeight?e:t,dV=({sessionId:e,directory:t=null,messages:n,historyMeta:r,scrollRef:i,messageListRef:a,loadMoreMessages:o,goToBottom:s,releaseAutoFollow:c,beginHistoryViewportPreservation:l,endHistoryViewportPreservation:d,isPinned:f,showScrollButton:p,isMobile:m,autoFillEnabled:h=!1,onWillLoadEarlier:g})=>{let _=Q.useRef(m),v=Q.useRef(h);_.current=m,v.current=h;let y=Q.useRef(null),b=Q.useRef(null),x=Q.useMemo(()=>{let t=e??``,r=t?LB.get(t):void 0;if(r&&r.messages===n)return BB(t,r),y.current=r.model,b.current=n,r.model;let i=iB(y.current,b.current,n)??aB(n);return y.current=i,b.current=n,t&&n.length>0&&BB(t,{messages:n,model:i}),i},[n,e]),[S,C]=Q.useState(!1),[w,T]=Q.useState(!1),[E,D]=Q.useState(null),[O,k]=Q.useState(!1),[A,j]=Q.useState(null),[M,N]=Q.useState({scrollHeight:0,clientHeight:0}),P=Q.useRef(x),F=Q.useRef(f),I=Q.useRef(S),L=Q.useRef(w),R=Q.useRef(e),z=Q.useRef(t??null),B=Q.useRef(n),V=Q.useRef(r),H=Q.useRef(A),ee=Q.useRef([]),U=Q.useRef(null),te=Q.useRef(null),W=Q.useRef(!1),ne=Q.useRef(null),[G,re]=Q.useState(e);G!==e&&(re(e),ne.current!==null&&typeof window<`u`&&(window.clearTimeout(ne.current),ne.current=null),W.current=!1,I.current=!1,te.current=null,C(!1),T(!1),D(null),k(!1),H.current=null,j(null),N({scrollHeight:0,clientHeight:0}));let ie=Q.useMemo(()=>{let e=r?.limit!==A&&UB(r,n.length);return{hasBufferedTurns:!1,hasMoreAboveTurns:e,historyLoading:!!r?.loading,canLoadEarlier:e}},[r,n.length]),K=Q.useRef(ie);P.current=x,F.current=f,L.current=w,K.current=ie,R.current=e,z.current=t??null,B.current=n,V.current=r,H.current=A;let ae=J(()=>{W.current=!0,ne.current!==null&&typeof window<`u`&&(window.clearTimeout(ne.current),ne.current=null)}),oe=J(()=>{if(typeof window>`u`){W.current=!1;return}ne.current!==null&&window.clearTimeout(ne.current),ne.current=window.setTimeout(()=>{ne.current=null,W.current=!1},kB)}),se=J(()=>{let e=ee.current;e.length!==0&&(ee.current=[],e.forEach(e=>e()))}),ce=J(()=>new Promise(e=>{if(typeof window>`u`){e();return}let t=!1,n=()=>{t||(t=!0,window.clearTimeout(r),e())};ee.current.push(n);let r=window.setTimeout(n,OB)})),le=J(e=>{let t=U.current;t&&(U.current=null,t.resolve(e))}),ue=J(()=>{let e=U.current;if(e){if(e.sessionId!==R.current){le(!1);return}if(e.kind===`turn`?a.current?.scrollToTurnId(e.id,{behavior:e.behavior})??!1:a.current?.scrollToMessageId(e.id,{behavior:e.behavior})??!1){e.turnId&&(te.current={turnId:e.turnId,expiresAt:Date.now()+IB},D(e.turnId)),le(!0);return}typeof(e.kind===`turn`?P.current.turnIndexById.get(e.id):P.current.messageToTurnIndex.get(e.id))==`number`&&le(!1)}}),de=Q.useRef(null),fe=J(()=>{let e=de.current;e&&(de.current=null,e.dispose())});Ht(()=>{ne.current!==null&&typeof window<`u`&&(window.clearTimeout(ne.current),ne.current=null),fe(),se(),le(!1)});let pe=n;Gt(()=>{se(),ue()},[pe]);let me=J(()=>{let e=i.current;if(!e){N(e=>uV(e,{scrollHeight:0,clientHeight:0}));return}N(t=>uV(t,{scrollHeight:e.scrollHeight,clientHeight:e.clientHeight}))});Vt(typeof ResizeObserver<`u`?i:null,me),Gt(()=>{me()},[e,S]);let he=Q.useRef(null),ge=J(()=>a.current?.captureViewportAnchor()??null),_e=J(e=>a.current?.restoreViewportAnchor(e)??!1),ve=J(()=>{if(yr())return;fe();let e=i.current;if(!e)return;let t=ge();t&&(de.current=yB({container:e,anchor:t}))}),ye=Q.useRef(null);Gt(()=>{if(!yr())return;let e=i.current;e&&(iV(e),rV(e))},[e,i]),Gt(()=>{fe(),he.current=null,ye.current=null,a.current?.cancelViewportAnchorHold()},[e]),Gt(()=>{let e=i.current;if(!e)return;let t=he.current;t&&Math.abs(e.scrollTop-t.top)>qB&&(he.current=null,t=null);let n=ye.current,r=pe[0]?.info?.id??null,o=pe[pe.length-1]?.info?.id??null,c=n?VB({previousOldestId:n.oldestId,previousNewestId:n.newestId,currentOldestId:r,currentNewestId:o})||lV(n.oldestId,r,pe):!1;t&&t.sessionId!==R.current&&(he.current=null,t=null);let l=t?VB({previousOldestId:t.oldestId,previousNewestId:t.newestId,currentOldestId:r,currentNewestId:o})||lV(t.oldestId,r,pe):!1,u=c||l,d=e=>{ye.current={oldestId:r,newestId:o,scrollHeight:e??ye.current?.scrollHeight??0}};if(F.current&&!t){fe(),u?(he.current=null,s(`instant`),d(e.scrollHeight)):d();return}let f=HB(a.current?.isHistoryVirtualized()??!1);if(t){if(f.owner===`tanstack-core`){a.current?.cancelViewportAnchorHold();let e=t.anchor;e&&_e(e),d();return}let n=e.scrollHeight,r=n-t.height;if(yr()){r>0&&cV(e,t.top+r,r),d(n);return}let i=t.anchor;!(i&&_e(i))&&r>0&&(e.scrollTop=t.top+r),d(n);return}if(c&&n&&f.owner===`controller`){let t=e.scrollHeight,r=t-n.scrollHeight;if(r>0){let t=e.scrollTop+r;yr()?cV(e,t,r):e.scrollTop=t}d(t),ve();return}d()},[pe,s]);let be=J(async()=>!1),xe=J(async e=>{let t=Date.now(),n=t+AB,r=z.current,i=r?Ha()?.getRequestState?.(En(r,e)):void 0;for(K.current.historyLoading,V.current,i?.status,i?.error;K.current.historyLoading;){if(R.current!==e)return Date.now()-t,`switched`;if(Date.now()>=n){let n=r?Ha()?.getRequestState?.(En(r,e)):void 0;return console.error(`[chat-history] historyLoading wait timed out — sync flag still true`,{sessionId:e,directory:r,elapsedMs:Date.now()-t,waitMs:AB,hostTurnPageTimeoutMs:mr,historyLoading:K.current.historyLoading,historyMeta:V.current,requestStatusAtStart:i?.status??null,requestStatusAtTimeout:n?.status??null,requestErrorAtTimeout:n?.error??null,likelyStaleLoadingFlag:n?.status===`ready`||n?.status===`error`||n==null}),`timeout`}await new Promise(e=>{if(typeof window>`u`){e();return}window.setTimeout(e,jB)})}return Date.now()-t,r&&Ha()?.getRequestState?.(En(r,e))?.status,R.current===e?`cleared`:`switched`}),Se=J(async e=>{if(!R.current||I.current||!K.current.hasMoreAboveTurns)return!1;I.current=!0,ae(),C(!0);let t=R.current,n=null,r=!!e.userInitiated;r&&l();let s=()=>{n&&he.current===n&&(he.current=null,a.current?.cancelViewportAnchorHold()),r&&(r=!1,d())};try{if(K.current.historyLoading){if(!e.userInitiated)return!1;let n=await xe(t);if(n===`timeout`)throw PB();if(n===`switched`||!K.current.hasMoreAboveTurns)return!1}if(!R.current||R.current!==t)return!1;let r=i.current,a=B.current,c=a.length,l=a[0]?.info?.id??null,u=V.current?.limit??dB().HISTORICAL_MESSAGES;e.preserveViewport&&r&&(n={sessionId:R.current,height:r.scrollHeight,top:r.scrollTop,anchor:ge(),oldestId:l,newestId:a[a.length-1]?.info?.id??null},he.current=n,ve());let d=c,f=l,p=u,m=0;for(;;){if(K.current.historyLoading)if(e.userInitiated){let e=await xe(t);if(e===`timeout`)throw s(),PB();if(e===`switched`)return s(),!1}else return s(),!1;let n=i.current?.scrollHeight??0,r=d,a=f,c=p;if(await o(t,`up`),m+=1,R.current!==t)return s(),!1;await ce();let l=B.current,u=l.length,h=l[0]?.info?.id??null,g=V.current?.limit??p,_=GB({scrollHeightBefore:n,scrollHeightAfter:i.current?.scrollHeight??n,messageCountBefore:r,messageCountAfter:u,oldestIdBefore:a,oldestIdAfter:h,limitBefore:c,limitAfter:g,hasMoreAbove:K.current.hasMoreAboveTurns,pagesLoaded:m,maxPages:KB});if(_===`continue`){d=u,f=h,p=g;continue}if(_===`stop-no-growth`){if(K.current.historyLoading){if(e.userInitiated){let e=await xe(t);if(e===`timeout`)throw s(),PB();if(e===`switched`)return s(),!1;--m;continue}return s(),!1}let n=V.current?.limit??c;return H.current=n,j(n),K.current={...K.current,hasMoreAboveTurns:!1,canLoadEarlier:!1},s(),!1}return!0}}catch(e){throw s(),e}finally{I.current=!1,C(!1),oe(),ce().then(s)}}),{t:Ce}=Yt(),we=At({mutationKey:XB({runtimeKey:u(),sessionId:e??``}),mutationFn:async e=>{if(R.current!==e.sessionId)return!1;ae(),e.userInitiated&&c();try{return await Se({preserveViewport:!0,userInitiated:!!e.userInitiated})}finally{oe()}}}),Te=J(async e=>{let t=R.current;if(t&&!(we.isPending&&we.variables?.sessionId===t)){e?.userInitiated&&g?.();try{let n=await we.mutateAsync({sessionId:t,userInitiated:!!e?.userInitiated});if(n===!1&&K.current.canLoadEarlier){let r={sessionId:t,grew:n,userInitiated:!!e?.userInitiated,canLoadEarlier:K.current.canLoadEarlier,hasMoreAboveTurns:K.current.hasMoreAboveTurns,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null};FB(`no-growth`,Error(`chat history pagination returned no growth`),r),e?.userInitiated&&ro.error(Ce(`chat.history.loadOlderFailed`))}}catch(n){let r={sessionId:t,userInitiated:!!e?.userInitiated,waitMs:AB,hostTurnPageTimeoutMs:mr,canLoadEarlier:K.current.canLoadEarlier,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null};NB(n)?FB(`timeout`,n,r):FB(`failed`,n,r),e?.userInitiated&&ro.error(NB(n)?Ce(`chat.history.loadOlderTimeout`):Ce(`chat.history.loadOlderFailed`))}}}),Ee=we.isPending&&we.variables?.sessionId===e||S,De=n[0]?.info?.id??null,Oe=JB({enabled:h,isMobile:m,sessionReady:!!e,messageReady:n.length>0||!!r,historyLoading:ie.historyLoading,canLoadEarlier:ie.canLoadEarlier,isPinned:f,fillBlocked:O,scrollHeight:M.scrollHeight,clientHeight:M.clientHeight,pendingRevealWork:w,isLoadingOlder:!1,hasMessages:n.length>0});jt({queryKey:YB({runtimeKey:u(),sessionId:e??``,oldestMessageId:De,messageCount:n.length,canLoadEarlier:ie.canLoadEarlier}),enabled:!!e&&Oe,staleTime:1/0,gcTime:0,retry:(e,t)=>t?.code===`auto-fill-busy`&&e<40,retryDelay:50,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,queryFn:async()=>{if(!v.current||_.current)return{status:`skip`};let e=R.current;if(!e)return{status:`skip`};if(K.current.historyLoading||I.current){let e=Error(`auto-fill-busy`);throw e.code=`auto-fill-busy`,e}if(!K.current.canLoadEarlier)return{status:`skip`};let t=i.current;if(!t||t.clientHeight<=0)return{status:`skip`};if(t.scrollHeight>t.clientHeight+48)return{status:`tall`};try{let t=await Se({preserveViewport:!0});return t?{status:`grew`}:(K.current.canLoadEarlier&&FB(`no-growth`,Error(`chat history pagination returned no growth`),{sessionId:e,source:`auto-fill`,grew:t,canLoadEarlier:K.current.canLoadEarlier,hasMoreAboveTurns:K.current.hasMoreAboveTurns,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null}),k(!0),{status:`blocked`})}catch(t){if(t?.code===`auto-fill-busy`)throw t;let n={sessionId:e,source:`auto-fill`,waitMs:AB,canLoadEarlier:K.current.canLoadEarlier,historyLoading:K.current.historyLoading,historyMeta:V.current,messageCount:B.current.length,oldestMessageId:B.current[0]?.info?.id??null};throw NB(t)?FB(`timeout`,t,n):FB(`failed`,t,n),k(!0),t instanceof Error?t:Error(`chat timeline auto-fill failed`)}}});let ke=J(e=>{let t=i.current;t&&WB({source:e,isMobile:_.current,isPinned:F.current,scrollTop:t.scrollTop,clientHeight:t.clientHeight,canLoadEarlier:K.current.canLoadEarlier,isLoadingOlder:I.current,pendingRevealWork:L.current})&&Te({userInitiated:!0})}),Ae=J(()=>{ke(`scroll`)}),je=J(()=>{ke(`upward-intent`)}),Me=J(async(t,n)=>{if(!t||!R.current)return!1;c(),T(!0);try{return R.current!==e||typeof P.current.turnIndexById.get(t)!=`number`?!1:!!await new Promise(r=>{U.current={sessionId:R.current??e??``,kind:`turn`,id:t,behavior:n?.behavior??`auto`,turnId:t,resolve:r},ue()})}finally{T(!1)}}),Ne=J(async(t,n)=>{if(!t||!R.current)return!1;c(),T(!0);try{if(R.current!==e)return!1;let r=P.current.messageToTurnId.get(t);return typeof P.current.messageToTurnIndex.get(t)==`number`&&!!await new Promise(i=>{U.current={sessionId:R.current??e??``,kind:`message`,id:t,behavior:n?.behavior??`auto`,turnId:r??null,resolve:i},ue()})}finally{T(!1)}}),Pe=J(async()=>{T(!1),I.current=!1,C(!1),a.current?.scrollToBottom(),s(`smooth`)}),Fe=J(async()=>{T(!1),I.current=!1,C(!1),a.current?.scrollToBottom(),s(`instant`)}),Ie=J(e=>{let t=te.current;if(t){if(e!==t.turnId&&Date.now()<t.expiresAt)return;te.current=null}D(e)});return{turnIds:x.turnIds,turnStart:0,renderedMessages:pe,historySignals:ie,isLoadingOlder:Ee,pendingRevealWork:w,activeTurnId:E,showScrollToBottom:p&&!w,turnWindowModel:x,loadEarlier:Te,revealBufferedTurns:be,resumeToBottom:Pe,resumeToBottomInstant:Fe,scrollToTurn:Me,scrollToMessage:Ne,handleHistoryScroll:Ae,handleHistoryUpwardIntent:je,captureViewportAnchor:ge,restoreViewportAnchor:_e,handleActiveTurnChange:Ie}},fV=({mutateSession:e,forkSession:t})=>({revert:e,fork:t}),pV=({open:e,onOpenChange:t,sessionID:n,directory:r,onScrollToMessage:i,onScrollByTurnOffset:a,onResumeToLatest:o,canLoadEarlier:s=!1,isLoadingEarlier:c=!1,onLoadEarlier:l,onRevertMessage:u})=>{let[d,f]=Q.useState(null),[p,m]=Q.useState(``),[h,g]=Q.useState(0),_=Q.useRef(!1),v=Q.useRef(0),y=J(async(e,n,r)=>{if(_.current)return;_.current=!0;let i=v.current+1;v.current=i,f({type:e,messageId:n});try{await r(),t(!1)}finally{v.current===i&&(_.current=!1,f(null))}});return n?(0,$.jsx)(_o,{open:e,onOpenChange:t,children:(0,$.jsx)(po,{className:`max-w-2xl max-h-[70vh] flex flex-col`,children:(0,$.jsx)(mV,{open:e,onOpenChange:t,sessionID:n,directory:r,onScrollToMessage:i,onScrollByTurnOffset:a,onResumeToLatest:o,canLoadEarlier:s,isLoadingEarlier:c,onLoadEarlier:l,onRevertMessage:u,searchQuery:p,onSearchQueryChange:m,selectedIndex:h,onSelectedIndexChange:g,pendingAction:d,runPendingMessageAction:y})})}):null},mV=e=>{let t=(0,pd.c)(145),{open:n,onOpenChange:r,sessionID:i,directory:a,onScrollToMessage:o,onScrollByTurnOffset:s,onResumeToLatest:c,canLoadEarlier:l,isLoadingEarlier:u,onLoadEarlier:d,onRevertMessage:f,searchQuery:p,onSearchQueryChange:m,selectedIndex:h,onSelectedIndexChange:g,pendingAction:_,runPendingMessageAction:v}=e,{t:y}=Yt(),b=Zy(),x=i,S=ha(x??``,a),C=X(gV),w=X(_V),T;t[0]===b.capabilities?T=t[1]:(T=fV(b.capabilities),t[0]=b.capabilities,t[1]=T);let E=T,{isMobile:D,isTablet:O}=qs(),k=D||O,A;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(A=[],t[2]=A):A=t[2];let j=Q.useRef(A),M=Q.useRef(null),N=Q.useRef(null),P=Q.useRef(!1),F=Q.useRef(!1),I=vV,L=yV,R;t[3]===S?R=t[4]:(R=S.filter(bV).map(xV),t[3]=S,t[4]=R);let z=R,B;if(t[5]!==p||t[6]!==z){bb0:{let e=p.trim();if(!e){B=z;break bb0}let t=e.toLowerCase();B=z.filter(e=>{let{message:n}=e;return PR(n.parts).toLowerCase().includes(t)})}t[5]=p,t[6]=z,t[7]=B}else B=t[7];let V=B,H;t[8]!==V.length||t[9]!==g||t[10]!==p?(H=()=>{P.current||g(p.trim()?0:Math.max(0,V.length-1))},t[8]=V.length,t[9]=g,t[10]=p,t[11]=H):H=t[11];let ee;t[12]!==V||t[13]!==g||t[14]!==p?(ee=[V,p,g],t[12]=V,t[13]=g,t[14]=p,t[15]=ee):ee=t[15],Q.useEffect(H,ee);let U,te;t[16]===V.length?(U=t[17],te=t[18]):(U=()=>{j.current=j.current.slice(0,V.length)},te=[V.length],t[16]=V.length,t[17]=U,t[18]=te),Q.useEffect(U,te);let W,ne;t[19]===h?(W=t[20],ne=t[21]):(ne=()=>{P.current||j.current[h]?.scrollIntoView({block:`nearest`})},W=[h],t[19]=h,t[20]=W,t[21]=ne),Q.useEffect(ne,W);let G;t[22]===u?G=t[23]:(G=()=>{!P.current||N.current||u||(P.current=!1)},t[22]=u,t[23]=G);let re;t[24]!==V.length||t[25]!==u?(re=[V.length,u],t[24]=V.length,t[25]=u,t[26]=re):re=t[26],Q.useEffect(G,re);let ie,K;t[27]!==n||t[28]!==p?(ie=()=>{let e=F.current;if(F.current=n,!n||e||P.current||p.trim())return;let t=M.current;t&&(t.scrollTop=t.scrollHeight)},K=[n,p],t[27]=n,t[28]=p,t[29]=ie,t[30]=K):(ie=t[29],K=t[30]),Q.useLayoutEffect(ie,K);let ae;t[31]===u?ae=t[32]:(ae=()=>{let e=N.current,t=M.current;if(!e||!t||u)return;N.current=null;let n=j.current.find(t=>t?.dataset.timelineMessageId===e.messageId);if(!n)return;let r=n.getBoundingClientRect().top-t.getBoundingClientRect().top;t.scrollTop+=r-e.top},t[31]=u,t[32]=ae);let oe;t[33]!==V.length||t[34]!==u?(oe=[V.length,u],t[33]=V.length,t[34]=u,t[35]=oe):oe=t[35],Q.useLayoutEffect(ae,oe);let se;t[36]===d?se=t[37]:(se=()=>{let e=M.current;if(e){let t=e.getBoundingClientRect().top,n=j.current.find(e=>e?e.getBoundingClientRect().bottom>=t:!1);n?.dataset.timelineMessageId&&(N.current={messageId:n.dataset.timelineMessageId,top:n.getBoundingClientRect().top-t})}P.current=!0,d?.()},t[36]=d,t[37]=se);let ce=J(se),le;t[38]!==r||t[39]!==o?(le=async e=>{await o?.(e)!==!1&&r(!1)},t[38]=r,t[39]=o,t[40]=le):le=t[40];let ue=J(le),de;t[41]!==V||t[42]!==ue||t[43]!==g||t[44]!==h?(de=e=>{let t=V.length;if(t!==0){if(e.key===`ArrowDown`){e.preventDefault(),g(e=>(e+1)%t);return}if(e.key===`ArrowUp`){e.preventDefault(),g(e=>(e-1+t)%t);return}if(e.key===`Enter`){e.preventDefault();let n=(h%t+t)%t,r=V[n];r&&ue(r.message.info.id)}}},t[41]=V,t[42]=ue,t[43]=g,t[44]=h,t[45]=de):de=t[45];let fe=J(de),pe;t[46]!==x||t[47]!==a||t[48]!==w||t[49]!==f||t[50]!==C||t[51]!==v?(pe=async(e,t)=>{x&&await v(e,t,async()=>{e===`revert`?f?await f(t):await C(x,t,{directory:a}):await w(x,t,{directory:a})})},t[46]=x,t[47]=a,t[48]=w,t[49]=f,t[50]=C,t[51]=v,t[52]=pe):pe=t[52];let me=J(pe),he;t[53]===Symbol.for(`react.memo_cache_sentinel`)?(he=(0,$.jsx)(Z,{name:`time`,className:`h-5 w-5`}),t[53]=he):he=t[53];let ge;t[54]===y?ge=t[55]:(ge=y(`chat.timeline.title`),t[54]=y,t[55]=ge);let _e;t[56]===ge?_e=t[57]:(_e=(0,$.jsxs)(mo,{className:`flex items-center gap-2`,children:[he,ge]}),t[56]=ge,t[57]=_e);let ve;t[58]===y?ve=t[59]:(ve=y(`chat.timeline.description`),t[58]=y,t[59]=ve);let ye;t[60]===ve?ye=t[61]:(ye=(0,$.jsx)(ho,{children:ve}),t[60]=ve,t[61]=ye);let be;t[62]!==_e||t[63]!==ye?(be=(0,$.jsxs)(lo,{children:[_e,ye]}),t[62]=_e,t[63]=ye,t[64]=be):be=t[64];let xe;t[65]===Symbol.for(`react.memo_cache_sentinel`)?(xe=(0,$.jsx)(Z,{name:`search`,className:`absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground`}),t[65]=xe):xe=t[65];let Se;t[66]===y?Se=t[67]:(Se=y(`chat.timeline.searchPlaceholder`),t[66]=y,t[67]=Se);let Ce;t[68]===m?Ce=t[69]:(Ce=e=>m(e.target.value),t[68]=m,t[69]=Ce);let we;t[70]!==fe||t[71]!==p||t[72]!==Se||t[73]!==Ce?(we=(0,$.jsxs)(`div`,{className:`relative mt-2`,children:[xe,(0,$.jsx)(Ko,{autoFocus:!0,placeholder:Se,value:p,onChange:Ce,onKeyDown:fe,className:`pl-9 w-full`})]}),t[70]=fe,t[71]=p,t[72]=Se,t[73]=Ce,t[74]=we):we=t[74];let Te;t[75]!==l||t[76]!==ce||t[77]!==u||t[78]!==d||t[79]!==y?(Te=l&&d&&(0,$.jsx)(`div`,{className:`flex justify-center py-1`,children:(0,$.jsxs)(Qt,{type:`button`,variant:`link`,size:`sm`,onClick:ce,disabled:u,className:`h-auto px-1 py-0 text-muted-foreground hover:text-foreground`,children:[u&&(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}),y(`chat.history.loadOlder`)]})}),t[75]=l,t[76]=ce,t[77]=u,t[78]=d,t[79]=y,t[80]=Te):Te=t[80];let Ee;t[81]!==E.fork||t[82]!==E.revert||t[83]!==k||t[84]!==V||t[85]!==me||t[86]!==ue||t[87]!==g||t[88]!==_||t[89]!==p||t[90]!==h||t[91]!==y?(Ee=V.length===0?(0,$.jsx)(`div`,{className:`text-center text-muted-foreground py-8`,children:y(p?`chat.timeline.empty.search`:`chat.timeline.empty.session`)}):V.map((e,t)=>{let{message:n}=e,r=FR(n.parts),i=n.info.time.created,a=I(i),o=V[t-1],s=a!==(o?I(o.message.info.time.created):null),c=L(i),l=t===h,u=p.trim()?hV(PR(n.parts),p):null;return(0,$.jsxs)(Q.Fragment,{children:[s&&(0,$.jsxs)(`div`,{className:`sticky top-0 z-10 flex items-center gap-3 bg-background/95 py-2 backdrop-blur-sm`,children:[(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border/60`}),(0,$.jsx)(`span`,{className:`typography-meta text-muted-foreground`,children:a}),(0,$.jsx)(`div`,{className:`h-px flex-1 bg-border/60`})]}),(0,$.jsxs)(`div`,{ref:e=>{j.current[t]=e},"data-timeline-message-id":n.info.id,className:Y(`group flex items-center gap-3 py-1.5 hover:bg-interactive-hover/30 rounded transition-colors cursor-pointer`,l&&`bg-interactive-selection text-interactive-selection-foreground`),onClick:()=>void ue(n.info.id),onMouseEnter:()=>g(t),children:[(0,$.jsx)(`span`,{className:Y(`typography-meta w-16 flex-shrink-0 text-right tabular-nums`,l?`text-interactive-selection-foreground/70`:`text-muted-foreground`),children:c}),(0,$.jsxs)(`p`,{className:Y(`flex-1 min-w-0 typography-micro truncate`,l?`text-interactive-selection-foreground`:`text-foreground`),children:[u??(r||y(`chat.timeline.noTextContent`)),!u&&r&&r.length>=80&&`…`]}),(0,$.jsx)(`div`,{className:`flex-shrink-0 h-5 flex items-center mr-2`,children:(0,$.jsxs)(`div`,{className:Y(`gap-1`,k?`flex`:`hidden group-hover:flex`),children:[E.revert?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":_?.type===`revert`&&_.messageId===n.info.id,disabled:_!==null,onClick:e=>{e.stopPropagation(),me(`revert`,n.info.id)},children:(0,$.jsx)(Z,{name:_?.type===`revert`&&_.messageId===n.info.id?`loader-4`:`arrow-go-back`,className:Y(`h-4 w-4`,_?.type===`revert`&&_.messageId===n.info.id&&`animate-spin`)})})}),(0,$.jsx)(Jo,{sideOffset:6,children:y(`chat.timeline.actions.revertFromHere`)})]}):null,E.fork?(0,$.jsxs)(Yo,{children:[(0,$.jsx)(qo,{asChild:!0,children:(0,$.jsx)(Qt,{type:`button`,variant:`ghost`,size:`icon`,className:`size-5 text-muted-foreground hover:text-foreground`,"aria-busy":_?.type===`fork`&&_.messageId===n.info.id,onClick:e=>{e.stopPropagation(),me(`fork`,n.info.id)},disabled:_!==null,children:_?.type===`fork`&&_.messageId===n.info.id?(0,$.jsx)(Z,{name:`loader-4`,className:`h-4 w-4 animate-spin`}):(0,$.jsx)(Z,{name:`git-branch`,className:`h-4 w-4`})})}),(0,$.jsx)(Jo,{sideOffset:6,children:y(`chat.timeline.actions.forkFromHere`)})]}):null]})})]})]},n.info.id)}),t[81]=E.fork,t[82]=E.revert,t[83]=k,t[84]=V,t[85]=me,t[86]=ue,t[87]=g,t[88]=_,t[89]=p,t[90]=h,t[91]=y,t[92]=Ee):Ee=t[92];let De;t[93]===Ee?De=t[94]:(De=(0,$.jsx)(`div`,{ref:M,className:`flex-1 overflow-y-auto`,children:Ee}),t[93]=Ee,t[94]=De);let Oe;t[95]===y?Oe=t[96]:(Oe=y(`chat.timeline.actions.title`),t[95]=y,t[96]=Oe);let ke;t[97]===Oe?ke=t[98]:(ke=(0,$.jsx)(`p`,{className:`typography-meta text-muted-foreground font-medium mb-2`,children:Oe}),t[97]=Oe,t[98]=ke);let Ae;t[99]!==r||t[100]!==s?(Ae=()=>{s?.(-1),r(!1)},t[99]=r,t[100]=s,t[101]=Ae):Ae=t[101];let je;t[102]===y?je=t[103]:(je=y(`chat.timeline.actions.previousTurn`),t[102]=y,t[103]=je);let Me;t[104]!==Ae||t[105]!==je?(Me=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Ae,children:je}),t[104]=Ae,t[105]=je,t[106]=Me):Me=t[106];let Ne;t[107]===Symbol.for(`react.memo_cache_sentinel`)?(Ne=(0,$.jsx)(`span`,{className:`text-muted-foreground/50`,children:`/`}),t[107]=Ne):Ne=t[107];let Pe;t[108]!==r||t[109]!==c?(Pe=()=>{c?.(),r(!1)},t[108]=r,t[109]=c,t[110]=Pe):Pe=t[110];let Fe;t[111]===y?Fe=t[112]:(Fe=y(`chat.timeline.actions.latest`),t[111]=y,t[112]=Fe);let Ie;t[113]!==Pe||t[114]!==Fe?(Ie=(0,$.jsx)(`button`,{type:`button`,className:`text-[11px] uppercase tracking-wide text-muted-foreground/90 hover:text-foreground`,onClick:Pe,children:Fe}),t[113]=Pe,t[114]=Fe,t[115]=Ie):Ie=t[115];let Le;t[116]!==Me||t[117]!==Ie?(Le=(0,$.jsxs)(`div`,{className:`mb-2 flex items-center gap-2`,children:[Me,Ne,Ie]}),t[116]=Me,t[117]=Ie,t[118]=Le):Le=t[118];let Re;t[119]===y?Re=t[120]:(Re=y(`chat.timeline.help.clickMessage`),t[119]=y,t[120]=Re);let ze;t[121]===Re?ze=t[122]:(ze=(0,$.jsx)(`div`,{className:`flex items-center gap-2`,children:(0,$.jsx)(`span`,{children:Re})}),t[121]=Re,t[122]=ze);let Be;t[123]===Symbol.for(`react.memo_cache_sentinel`)?(Be=(0,$.jsx)(Z,{name:`arrow-go-back`,className:`h-4 w-4 flex-shrink-0`}),t[123]=Be):Be=t[123];let Ve;t[124]===y?Ve=t[125]:(Ve=y(`chat.timeline.help.undoToPoint`),t[124]=y,t[125]=Ve);let He;t[126]===Ve?He=t[127]:(He=(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[Be,(0,$.jsx)(`span`,{children:Ve})]}),t[126]=Ve,t[127]=He);let Ue;t[128]!==E.fork||t[129]!==y?(Ue=E.fork?(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Z,{name:`git-branch`,className:`h-4 w-4 flex-shrink-0`}),(0,$.jsx)(`span`,{children:y(`chat.timeline.help.createSessionFromHere`)})]}):null,t[128]=E.fork,t[129]=y,t[130]=Ue):Ue=t[130];let We;t[131]!==ze||t[132]!==He||t[133]!==Ue?(We=(0,$.jsxs)(`div`,{className:`flex flex-col gap-1.5 typography-meta text-muted-foreground`,children:[ze,He,Ue]}),t[131]=ze,t[132]=He,t[133]=Ue,t[134]=We):We=t[134];let Ge;t[135]!==ke||t[136]!==Le||t[137]!==We?(Ge=(0,$.jsxs)(`div`,{className:`mt-4 p-3 bg-muted/30 rounded-lg`,children:[ke,Le,We]}),t[135]=ke,t[136]=Le,t[137]=We,t[138]=Ge):Ge=t[138];let Ke;return t[139]!==be||t[140]!==we||t[141]!==Te||t[142]!==De||t[143]!==Ge?(Ke=(0,$.jsxs)($.Fragment,{children:[be,we,Te,De,Ge]}),t[139]=be,t[140]=we,t[141]=Te,t[142]=De,t[143]=Ge,t[144]=Ke):Ke=t[144],Ke};function hV(e,t,n=30){let r=e.toLowerCase(),i=t.toLowerCase(),a=r.indexOf(i);if(a===-1)return null;let o=Math.max(0,a-n),s=Math.min(e.length,a+t.length+n);return`${o>0?`…`:``}${e.slice(o,s).replace(/\n/g,` `)}${s<e.length?`…`:``}`}function gV(e){return e.revertToMessage}function _V(e){return e.forkFromMessage}function vV(e){return xs(e)}function yV(e){return as(e)}function bV(e){return e.info.role===`user`}function xV(e){return{message:e}}var SV=e=>{let t=e.startsWith(`#`)?e.slice(1):e;if(!t)return null;let n=t.match(/^turn-(.+)$/);if(n?.[1])return{kind:`turn`,id:n[1]};let r=t.match(/^message-(.+)$/);return r?.[1]?{kind:`message`,id:r[1]}:null},CV=(e,t,n)=>{if(n===0||e.length===0)return{kind:`noop`};let r=t?e.indexOf(t):e.length-1,i=(r>=0?r:e.length-1)+n;if(i>=e.length)return{kind:`resume`};let a=e[Math.max(0,i)];return a?{kind:`turn`,turnId:a}:{kind:`noop`}},wV=e=>{if(typeof window>`u`)return;let t=e?`#${e}`:``,n=`${window.location.pathname}${window.location.search}${t}`;window.history.replaceState(window.history.state,``,n)},TV=e=>{let t=(0,pd.c)(29),{sessionId:n,turnIds:r,activeTurnId:i,scrollToTurn:a,scrollToMessage:o,resumeToBottom:s}=e,c=Q.useRef(r),l=Q.useRef(i),u,d;t[0]===r?(u=t[1],d=t[2]):(u=()=>{c.current=r},d=[r],t[0]=r,t[1]=u,t[2]=d),Q.useEffect(u,d);let f,p;t[3]===i?(f=t[4],p=t[5]):(f=()=>{l.current=i},p=[i],t[3]=i,t[4]=f,t[5]=p),Q.useEffect(f,p);let m;t[6]===a?m=t[7]:(m=async(e,t)=>e?(t?.updateHash!==!1&&wV(`turn-${e}`),a(e,{behavior:t?.behavior})):!1,t[6]=a,t[7]=m);let h=m,g;t[8]===o?g=t[9]:(g=async(e,t)=>e?(t?.updateHash!==!1&&wV(`message-${e}`),o(e,{behavior:t?.behavior})):!1,t[8]=o,t[9]=g);let _=g,v;t[10]!==s||t[11]!==h?(v=async(e,t)=>{let n=c.current,r=CV(n,l.current,e);if(r.kind===`noop`)return e===0;if(r.kind===`resume`){if(t?.resumePastEnd===!1){let e=n[n.length-1];return e?h(e,{behavior:`auto`}):!1}return wV(null),s(),!0}return h(r.turnId,{behavior:`auto`})},t[10]=s,t[11]=h,t[12]=v):v=t[12];let y=v,b;t[13]===s?b=t[14]:(b=()=>{wV(null),s()},t[13]=s,t[14]=b);let x=b,S;t[15]!==_||t[16]!==h||t[17]!==n?(S=()=>{if(!n||typeof window>`u`)return;let e=()=>{let e=SV(window.location.hash);if(e){if(e.kind===`turn`){h(e.id,{behavior:`auto`,updateHash:!1});return}_(e.id,{behavior:`auto`,updateHash:!1})}};return e(),window.addEventListener(`hashchange`,e),()=>{window.removeEventListener(`hashchange`,e)}},t[15]=_,t[16]=h,t[17]=n,t[18]=S):S=t[18];let C;t[19]!==_||t[20]!==h||t[21]!==n||t[22]!==r.length?(C=[n,_,h,r.length],t[19]=_,t[20]=h,t[21]=n,t[22]=r.length,t[23]=C):C=t[23],Q.useEffect(S,C);let w;return t[24]!==x||t[25]!==y||t[26]!==_||t[27]!==h?(w={scrollToTurnId:h,scrollToMessageId:_,scrollByTurnOffset:y,resumeToLatest:x},t[24]=x,t[25]=y,t[26]=_,t[27]=h,t[28]=w):w=t[28],w},EV=2e4,DV=6e4,OV=2e3,kV=e=>e?(typeof e.text==`string`?e.text.length:0)+(typeof e.state?.output==`string`?e.state.output.length:0):0,AV=e=>{if(e.length===0)return`0`;let t=e[e.length-1];if(!t)return`0`;let n=t.parts??[],r=n[n.length-1],i=0;for(let e of n)i+=kV(e);return[e.length,t.info.id,n.length,r?.id??``,r?.state?.status??``,i].join(`:`)},jV={sessionKey:null,fingerprint:null,lastMovementAt:null,lastRefreshAt:null,attempts:0},MV=(e,t)=>{let{sessionKey:n,working:r,streaming:i,fingerprint:a,now:o}=t;if(!n)return{state:jV,shouldRefresh:!1,stalledForMs:0};if(e.sessionKey!==n)return{state:{sessionKey:n,fingerprint:a,lastMovementAt:o,lastRefreshAt:null,attempts:0},shouldRefresh:!1,stalledForMs:0};if(e.fingerprint!==a)return{state:{...e,fingerprint:a,lastMovementAt:o,attempts:0},shouldRefresh:!1,stalledForMs:0};if(!r||i)return{state:{...e,lastMovementAt:o},shouldRefresh:!1,stalledForMs:0};let s=e.lastMovementAt??o,c=o-s,l=e.lastRefreshAt===null||o-e.lastRefreshAt>=t.cooldownMs,u=c>=t.thresholdMs&&l&&e.attempts<t.maxAttempts;return{state:{...e,lastMovementAt:s,lastRefreshAt:u?o:e.lastRefreshAt,attempts:u?e.attempts+1:e.attempts},shouldRefresh:u,stalledForMs:c}},NV=e=>{console.warn(`[transcript] tail frozen while session is working — refetching authority`,e)};function PV(e){return!!(e.active&&e.sessionId&&e.sessionKey&&e.sessionIsWorking)}function FV(e){return e===jV?e:jV}function IV(e){let t=e.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!t)return null;let n=[],r=t[1],i=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g,a;for(;(a=i.exec(r))!==null;)n.push({question:a[1],answer:a[2]});return n.length>0?n:null}function LV(e){if(typeof e.id==`string`&&e.id)return e.id;if(typeof e.callID==`string`&&e.callID)return e.callID;let t=e.state;if(t&&typeof t==`object`&&!Array.isArray(t)){let e=t.callID;if(typeof e==`string`&&e)return e}return null}function RV(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e;if(t.type!==`tool`||t.tool!==`question`)return!1;let n=t.state&&typeof t.state==`object`&&!Array.isArray(t.state)?t.state:{},r=typeof n.status==`string`?n.status:void 0;if(r===`error`)return!1;if(r===`pending`||r===`running`||r===void 0)return!0;if(r!==`completed`)return!1;let i=typeof n.output==`string`?n.output:``;return!i||IV(i)==null}function zV(e){let t=[];for(let n of e){let e=Array.isArray(n.parts)?n.parts:[];for(let n of e){if(!RV(n))continue;let e=LV(n);e&&t.push(e)}}return t}function BV(e,t){return`${e}:${t.join(`,`)}`}function VV(e){let t=e.sessionId?.trim()??``,n=e.directory?.trim()??``;if(!t||!n||e.sessionQuestionCount>0||e.unansweredToolIds.length===0)return{recover:!1,attemptKey:null};let r=BV(t,e.unansweredToolIds);return e.attemptedKey===r?{recover:!1,attemptKey:r}:{recover:!0,attemptKey:r}}function HV(e,t,n,r){let i=(0,pd.c)(7),a=Kr(),o=Q.useRef(null),s=Q.useRef(`${e??``}:${t??``}`),c,l;i[0]!==a||i[1]!==t||i[2]!==n||i[3]!==e||i[4]!==r?(c=()=>{let i=`${e??``}:${t??``}`;s.current!==i&&(o.current=null,s.current=i);let c=VV({sessionId:e,directory:t,sessionQuestionCount:r,unansweredToolIds:zV(n),attemptedKey:o.current});if(!c.recover||!e||!t||!c.attemptKey)return;let l=a.getChild(t);l&&(o.current=c.attemptKey,Pn(t,l,[e]))},l=[e,t,n,r,a],i[0]=a,i[1]=t,i[2]=n,i[3]=e,i[4]=r,i[5]=c,i[6]=l):(c=i[5],l=i[6]),Q.useEffect(c,l)}var UV=e=>!Number.isFinite(e)||e<0?0:Math.ceil(e),WV=(e,t)=>({...e,key:GV(e),estimatedBytes:UV(t)}),GV=({runtimeKey:e,sessionId:t,directory:n})=>JSON.stringify([e,n??``,t]),KV=e=>({key:e?GV(e):null,selection:e}),qV=(e,t,n)=>{let r=Math.max(1,Math.floor(n.maxEntries)),i=Math.max(0,n.maxEstimatedBytes),a=e.reduce((e,t)=>e+t.estimatedBytes,0);if(e.length<=r&&a<=i)return e;let o=[...e];for(;o.length>r||a>i;){let e=o.findIndex(e=>e.key!==t);if(e===-1)break;let[n]=o.splice(e,1);a-=n?.estimatedBytes??0}return o},JV=(e,t,n,r)=>{let i=GV(t),a=e.findIndex(e=>e.key===i),o=a>=0?e[a]:void 0;if(o&&a===e.length-1)return qV(e,i,n);let s=o||WV(t,r),c=a>=0?e.filter((e,t)=>t!==a):[...e];return c.push(s),qV(c,i,n)},YV=(e,t,n)=>{let r=UV(n),i=e.findIndex(e=>e.key===t);return i===-1||e[i].estimatedBytes===r?e:e.map((e,t)=>t===i?{...e,estimatedBytes:r}:e)},XV=(e,t)=>t&&e.some(e=>e.key===t)?t:null,ZV=(e,t,n)=>{let r=t.key?e.cachedSessionViews.find(e=>e.key===t.key):void 0,i=r&&t.selection?JV(e.cachedSessionViews,t.selection,n,r.estimatedBytes):qV(e.cachedSessionViews,t.key??``,n),a=!r&&e.pendingSessionView?.intent===t?e.pendingSessionView:null;return e.activeIntent===t&&!e.cacheNeedsTrim&&i===e.cachedSessionViews&&a===e.pendingSessionView?e:{activeIntent:t,cacheNeedsTrim:!1,cachedSessionViews:i,pendingSessionView:a}},QV=(e,t,n,r)=>{if(n!==t||e.activeIntent!==t||!t.selection||e.cachedSessionViews.some(e=>e.key===t.key))return e;let i={entry:WV(t.selection,r),intent:t};return e.pendingSessionView?.intent===t?e:{activeIntent:e.activeIntent,cacheNeedsTrim:e.cacheNeedsTrim,cachedSessionViews:e.cachedSessionViews,pendingSessionView:i}},$V=(e,t,n)=>{let r=e.pendingSessionView;return e.activeIntent!==t||r?.intent!==t||!t.selection?e:{activeIntent:e.activeIntent,cacheNeedsTrim:!1,cachedSessionViews:JV(e.cachedSessionViews,t.selection,n,r.entry.estimatedBytes),pendingSessionView:null}},eH=e=>{if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0},tH=e=>{if(!(!e.info||typeof e.info!=`object`))return e.info},nH=e=>tH(e)?.role===`assistant`,rH=(e,t)=>{let n=tH(t);n&&(e.agentName??=eH(n.agent),e.providerId??=eH(n.providerID),e.modelId??=eH(n.modelID))},iH=e=>!!(e.agentName&&e.providerId&&e.modelId),aH=e=>{let t={};for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||!nH(r))&&(rH(t,r),iH(t)))return t}for(let n=e.length-1;n>=0;--n){let r=e[n];if(!(!r||nH(r))&&(rH(t,r),iH(t)))break}return t},oH=e=>!!e.sessionId&&!(e.hasRenderableSessionSnapshot&&e.hasCurrentSessionEntity),sH=[],cH=[],lH={type:`idle`},uH=`openchamber:chat-force-scroll-bottom`,dH=()=>void 0,fH=`Quota limit reached. Retrying automatically.`,pH=1048576,mH=pH,hH=20,gH=pH,_H=16*pH,vH={maxEntries:3,maxEstimatedBytes:32*pH},yH={maxEntries:2,maxEstimatedBytes:32*pH},bH=e=>i(()=>e()),xH={overflowAnchor:`none`,overscrollBehavior:`contain`,overscrollBehaviorY:`contain`},SH={scrollbar:`chat`,scrollShadow:`true`,orientation:`vertical`},CH=()=>{let e=(0,pd.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsx)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-x-0 bottom-full z-0 h-11 bg-gradient-to-t from-[var(--surface-background)] to-transparent`}),e[0]=t):t=e[0],t},wH=`calc(max(0.625rem, var(--oc-safe-area-top, 0px)) + var(--oc-mobile-detail-navigation-height) + 1.25rem)`,TH=lz,EH=[`a[href]`,`button`,`input`,`select`,`textarea`,`[contenteditable="true"]`,`[role="button"]`,`[role="combobox"]`,`[role="dialog"]`,`[role="listbox"]`,`[role="menu"]`,`[role="menuitem"]`,`[role="option"]`,`[role="textbox"]`,`[data-radix-popper-content-wrapper]`].join(`,`),DH=e=>e instanceof HTMLElement,OH=e=>DH(e)?!!e.closest(EH):!1,kH=(e,t)=>typeof document>`u`||!e||e===document.body||e===document.documentElement||OH(e)?!0:!t?.contains(e),AH=()=>{let{isAboutDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isImagePreviewOpen:r,isMultiRunLauncherOpen:i,isSessionSwitcherOpen:a,isSettingsDialogOpen:o}=q.getState();return e||t||n||r||i||a||o},jH=Q.memo(({currentSessionId:e,virtualizerKey:t,isDesktopExpandedInput:n,isMobile:r,stickyUserHeader:i,directory:a,scrollRef:o,messageListRef:s,pendingRevealWork:c,initialPinRevealComplete:l=!1,renderedMessages:u,isLoadingOlder:d,sessionIsWorking:f,streamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,handleMessageContentChange:g,getAnimationHandlers:_,handleHistoryScroll:v,handleHistoryUpwardIntent:y,onTimelineIsAtEndChange:b,timelineFollowSuspended:x,timelineHistoryAnchorToken:S,scrollToBottom:C,sessionQuestions:w,sessionPermissions:T,isProgrammaticFollowActive:E,showLoadOlderButton:D,onLoadOlder:O,turnIds:k,activeTurnId:A,onSelectTurn:j,showPromptNavigator:M,canLoadEarlierPrompts:N,isLoadingOlderPrompts:P,onLoadEarlierPrompts:F,transcriptStatusRow:I})=>{let{t:L}=Yt(),R=hl(e=>e.legendTimelineEnabled),z=uT({isLoadingOlder:d}),B=dT({isMobile:r,isLoadingOlder:z}),V=Q.useRef(new Map),H=Q.useRef(new WeakMap),ee=Q.useRef(new Map),U=Q.useMemo(()=>{let e=new Map;for(let t=0;t<u.length;t+=1){let n=u[t];if(n.info.role!==`user`)continue;if(LI(n)){let r=zI(u,t)??``,i=ee.current.get(n.info.id);if(i&&i.command===r)e.set(n.info.id,i.parts);else{let t=[{type:`text`,text:r?`$ ${r}`:`/shell`}];ee.current.set(n.info.id,{command:r,parts:t}),e.set(n.info.id,t)}continue}if(Vn(n.parts))continue;let r=H.current.get(n.parts);r||(r=_n(n.parts),H.current.set(n.parts,r)),r.length!==0&&e.set(n.info.id,r)}let t=V.current;if(t.size===e.size){let n=!0;for(let[r,i]of e)if(t.get(r)!==i){n=!1;break}if(n)return t}return V.current=e,e},[u]),te=Q.useMemo(()=>k.filter(e=>U.has(e)),[U,k]),W=Q.useMemo(()=>{if(!A||U.has(A))return A;let e=k.indexOf(A);for(let t=e-1;t>=0;--t){let e=k[t];if(U.has(e))return e}return null},[A,U,k]),ne=J(e=>{e.defaultPrevented||OH(e.target)||typeof window<`u`&&window.getSelection()?.type===`Range`||o.current?.focus({preventScroll:!0})});return Xu({scrollRef:o,enabled:R,onUpwardIntent:y}),R?(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(sR,{ref:s,sessionKey:e,virtualizerKey:t,disableStaging:c,initialPinRevealComplete:l,messages:u,sessionIsWorking:f,activeStreamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,onMessageContentChange:g,getAnimationHandlers:_,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:a,timelineScrollClassName:`absolute inset-0 z-0 chat-scroll overlay-scrollbar-target`,timelineScrollStyle:xH,timelineScrollDataset:SH,timelineOnScroll:v,timelineFollowEnabled:!c&&!x,timelineHistoryAnchorToken:S,timelineOnIsAtEndChange:b,headerSlot:(0,$.jsxs)($.Fragment,{children:[r&&(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:wH},"aria-hidden":`true`}),D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(Qt,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})})]}),footerSlot:(0,$.jsxs)($.Fragment,{children:[(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(NR,{question:e},e.id)),T.map(e=>(0,$.jsx)(ER,{permission:e},e.id))]}),I?(0,$.jsx)(`div`,{className:`mb-1`,children:I}):null,(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?TH:sz},"aria-hidden":`true`})]})}),(0,$.jsx)(Js,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(nz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})}):(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,n?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":n,children:(0,$.jsxs)(`div`,{className:`absolute inset-0`,children:[(0,$.jsx)(xl,{className:Y(`absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target`),ref:o,style:xH,observeMutations:!1,hideTopShadow:r&&i,hideBottomShadow:r,tabIndex:0,onClick:ne,onScroll:v,"data-scroll-shadow":`true`,"data-scrollbar":`chat`,children:(0,$.jsxs)(`div`,{className:Y(`oc-chat-scroll-content relative z-0 min-h-full`,r&&`chat-scroll-foot-inset`),children:[D&&(0,$.jsx)(`div`,{className:`flex justify-center pt-3 pb-1`,children:(0,$.jsxs)(Qt,{variant:`secondary`,size:`sm`,onClick:O,disabled:z,"aria-busy":z,children:[z&&(0,$.jsx)(Z,{name:`loader-4`,className:`size-4 animate-spin`}),L(`chat.history.loadOlder`)]})}),B&&(0,$.jsx)(`div`,{className:`absolute inset-x-0 top-0 z-20 flex justify-center pointer-events-none`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex items-center justify-center gap-1.5 pt-3 pb-1`,children:[(0,$.jsx)(Z,{name:`loader-4`,className:`size-3.5 animate-spin text-[var(--surface-mutedForeground)]`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`typography-meta text-[var(--surface-mutedForeground)]`,children:L(`chat.history.loadingMore`)})]})}),(0,$.jsx)(sR,{ref:s,sessionKey:e,virtualizerKey:t,disableStaging:c,initialPinRevealComplete:l,messages:u,sessionIsWorking:f,activeStreamingMessageId:p,activeStreamingPhase:m,retryOverlay:h,onMessageContentChange:g,getAnimationHandlers:_,isLoadingOlder:d,scrollToBottom:C,scrollRef:o,directory:a,liveStatusSlot:u.length>0?(0,$.jsx)(`div`,{className:`mb-1`,children:I??(0,$.jsx)(RN,{})}):null}),(w.length>0||T.length>0)&&(0,$.jsxs)(`div`,{children:[w.map(e=>(0,$.jsx)(NR,{question:e},e.id)),T.map(e=>(0,$.jsx)(ER,{permission:e},e.id))]}),(0,$.jsx)(`div`,{className:`flex-shrink-0`,style:{height:r?cz:sz},"aria-hidden":`true`})]})}),(0,$.jsx)(Js,{containerRef:o,suppressVisibility:E,userIntentOnly:!0,observeMutations:!1}),M&&te.length>=2?(0,$.jsx)(nz,{turnIds:te,previewsByTurnId:U,activeTurnId:W,onSelectTurn:j,canLoadEarlier:N,isLoadingOlder:P,onLoadEarlier:F}):null]})})},(e,t)=>e.currentSessionId===t.currentSessionId&&e.virtualizerKey===t.virtualizerKey&&e.isDesktopExpandedInput===t.isDesktopExpandedInput&&e.isMobile===t.isMobile&&e.stickyUserHeader===t.stickyUserHeader&&e.directory===t.directory&&e.scrollRef===t.scrollRef&&e.messageListRef===t.messageListRef&&e.pendingRevealWork===t.pendingRevealWork&&e.initialPinRevealComplete===t.initialPinRevealComplete&&e.renderedMessages===t.renderedMessages&&e.isLoadingOlder===t.isLoadingOlder&&e.sessionIsWorking===t.sessionIsWorking&&e.streamingMessageId===t.streamingMessageId&&e.activeStreamingPhase===t.activeStreamingPhase&&e.retryOverlay===t.retryOverlay&&e.handleMessageContentChange===t.handleMessageContentChange&&e.getAnimationHandlers===t.getAnimationHandlers&&e.handleHistoryScroll===t.handleHistoryScroll&&e.handleHistoryUpwardIntent===t.handleHistoryUpwardIntent&&e.onTimelineIsAtEndChange===t.onTimelineIsAtEndChange&&e.timelineFollowSuspended===t.timelineFollowSuspended&&e.timelineHistoryAnchorToken===t.timelineHistoryAnchorToken&&e.scrollToBottom===t.scrollToBottom&&e.sessionQuestions===t.sessionQuestions&&e.sessionPermissions===t.sessionPermissions&&e.isProgrammaticFollowActive===t.isProgrammaticFollowActive&&e.showLoadOlderButton===t.showLoadOlderButton&&e.onLoadOlder===t.onLoadOlder&&e.turnIds===t.turnIds&&e.activeTurnId===t.activeTurnId&&e.onSelectTurn===t.onSelectTurn&&e.showPromptNavigator===t.showPromptNavigator&&e.canLoadEarlierPrompts===t.canLoadEarlierPrompts&&e.isLoadingOlderPrompts===t.isLoadingOlderPrompts&&e.onLoadEarlierPrompts===t.onLoadEarlierPrompts&&e.transcriptStatusRow===t.transcriptStatusRow);jH.displayName=`ChatViewport`;var MH=[{id:1,toolRows:[{id:`search`,titleWidth:`w-24`,detailWidth:`w-52`},{id:`read`,titleWidth:`w-20`,detailWidth:`w-36`},{id:`edit`,titleWidth:`w-24`,detailWidth:`w-64`}],textWidths:[`w-24`,`w-[92%]`,`w-[78%]`]},{id:2,toolRows:[{id:`read`,titleWidth:`w-20`,detailWidth:`w-40`},{id:`search`,titleWidth:`w-24`,detailWidth:`w-48`}],textWidths:[`w-20`,`w-[88%]`,`w-[70%]`]},{id:3,toolRows:[{id:`shell`,titleWidth:`w-28`,detailWidth:`w-44`},{id:`edit`,titleWidth:`w-24`,detailWidth:`w-56`}],textWidths:[`w-24`,`w-[84%]`,`w-[64%]`]}],NH=e=>Xt(e.path),PH=(e,t)=>{if(!t)return e;let n=e.indexOf(t);return n===-1?e:(0,$.jsxs)($.Fragment,{children:[e.slice(0,n),(0,$.jsx)(`span`,{className:`font-medium`,children:t}),e.slice(n+t.length)]})},FH=e=>{let t=Math.ceil(Math.max(0,e)/hH);return Math.min(_H,mH+t*gH)},IH=Q.memo(({autoOpenDraft:e=!0,readOnly:t=!1,active:n=!0,sessionId:r,sessionDirectory:i,sessionViewKey:a,onSessionViewEstimateChange:o,composerSurface:s,hostedFeatures:c,assistantHistory:l,onRevertMessage:u,warning:d=null,pendingUserMessages:f=cH,onPendingUserMessagesMaterialized:p,committedDraftHandoffMessageId:m=null})=>{let h=c??hT(void 0),{t:g}=Yt();Gt(()=>{ba()},[]);let _=X(e=>e.openNewSessionDraft),v=X(e=>e.setCurrentSession),y=X(e=>e.newSessionDraft),b=X(e=>e.newSessionDraft.draftSubmitting??!1),x=X(e=>e.newSessionDraft.draftEstablishing??!1),S=X(e=>e.forkTransition),C=eo(e=>e.projects),w=eo(e=>e.activeProjectId),T=Oa(e=>e.providers),E=Qm(),D=la(),O=i??D;Gt(()=>{!n||!r||!O||Kn(O,r)},[n,r,O]);let k=J(e=>E.ensureSessionRenderable(e,{directory:O})),A=q(e=>e.isExpandedInput),j=q(e=>e.stickyUserHeader),M=q(e=>e.promptNavigatorEnabled),N=q(e=>e.allowPromptingSubagentSessions),P=q(e=>e.isTimelineDialogOpen),F=q(e=>e.setTimelineDialogOpen),I=vn(e=>n&&r?e.streamingMessageIds.get(r)??null:null),L=vn(e=>I?e.messageStreamStates.get(I)?.phase??null:null),R=ji(r??``,O),z=FH(R);Q.useEffect(()=>{!a||!o||o(a,z)},[o,z,a]);let B=on(r??``,O).renderable,V=si(r,O),H=Un(r),ee=V??H,U=Kb({sessionId:r,hasSessionEntity:!!ee,hasRenderableSessionSnapshot:B,composerSurfaceKind:s?.kind}),te=r?JSON.stringify([O,r]):null,[W,ne]=Q.useState({key:te,attempt:0}),G=ha(r??``,O,{suspendPartUpdates:!!I,suspendPartUpdatesForMessageId:I,enabled:n}),re=r?G:sH,ie=y.pendingUserMessage,K=X(e=>r?e.retainedPendingUserMessages.get(r):void 0)??cH,ae=!!(m||K.length>0),oe=X(e=>e.clearRetainedPendingUserMessages),se=Q.useMemo(()=>{if(K.length===0)return f;if(f.length===0)return K;let e=new Set(f.map(e=>e.info.id));return[...f,...K.filter(t=>!e.has(t.info.id))]},[f,K]),ce=Q.useMemo(()=>aH(re),[re]),le=Q.useMemo(()=>{if(!ce.modelId)return g(`common.unavailable`);let e=T.find(e=>e.id===ce.providerId);return ri(e,ce.modelId)||ce.modelId},[T,ce.modelId,ce.providerId,g]),ue=Fa(r??``,O),de=Oi(r??``,O),[fe,pe]=Q.useState(null),me=!!r&&fe===r,he=J(()=>{if(!r||me)return;let e=r,t=O;pe(e);let n=Sa(()=>{let n=Ha();if(!n)throw Error(`unbound`);return n.getTranscript(En(t,e))});za(Vi({kind:`refresh`,sessionID:e,directory:t,purpose:`retry`,source:`network`,request:ue?{sessionID:e,status:ue.status===`ready`?`ready`:ue.status,error:ue.error}:void 0,hydration:de,error:ue?.error})),(async()=>{try{await Ka(t,e),await E.ensureSessionRenderable(e,{directory:t});try{let r=Sa(()=>{let n=Ha();if(!n)throw Error(`unbound`);return n.getTranscript(En(t,e))});n&&r&&Di({trigger:`user-refresh`,sessionID:e,directory:t,purpose:`retry`,before:n,after:r})}catch{}}catch(n){za(Vi({kind:`request-error`,sessionID:e,directory:t,purpose:`retry`,source:`network`,hydration:de,error:n}))}finally{pe(t=>t===e?null:t)}})()}),_e=Pi(r??``,O).boundary,ve=J(async e=>{if(_e.kind===`has-more`){await Ii(O,e);return}if(_e.kind===`unknown`){await Bi(O,e);return}l&&!l.complete&&await l.fetchPrevious()}),ye=wi(r??``,O),be=oa(r??``,O),xe=Ba(O),Se=ye??lH,Ce=ai(r,O),we=ti(r,O);HV(r,O,re,we.length);let Te=Q.useMemo(()=>{if(!r||Ce.length>0||we.length>0)return!1;let e=Se.type??`idle`;if(e===`busy`||e===`retry`||oT(se,{resolvedSessionStatus:ye,sessionStatusObservedAt:be}))return!0;let t=re[re.length-1]?.info,n=t?.time?.created;return ye&&typeof be==`number`&&typeof n==`number`&&n<=be||typeof xe==`number`&&typeof n==`number`&&n<=xe?!1:!!(t&&t.role===`assistant`&&typeof t.time?.completed!=`number`)},[r,se,ye,re,Ce.length,we.length,Se.type,be,xe]),Ee=Q.useMemo(()=>!r||Se.type!==`retry`?null:{sessionId:r,message:(typeof Se.message==`string`?(Se.message??``).trim():``)||fH,confirmedAt:Se.confirmedAt},[r,Se]),[De,Oe]=Q.useState(0),ke=Q.useRef(null);Q.useEffect(()=>{if(!Ee||typeof Ee.confirmedAt==`number`){ke.current=null,Oe(0);return}ke.current!==Ee.sessionId&&(ke.current=Ee.sessionId,Oe(Date.now()))},[Ee]);let Ae=Q.useMemo(()=>Ee?{...Ee,fallbackTimestamp:De}:null,[Ee,De]),je=!!(r&&E.isLoading(r,{directory:O})),Me=Q.useMemo(()=>{if(!r)return null;let e=sT({boundary:_e,assistantComplete:l?.complete??!0});return{limit:_e.loadedTurns,complete:e.complete,canLoadEarlier:e.canLoadEarlier,loading:cT({syncLoading:je,assistantLoading:!!l?.loading})}},[l?.complete,l?.loading,r,_e,je]),Ne=q(e=>e.isMobile),Pe=Fu()!==null,Fe=ge(),Ie=Fb(),Le=!!y?.open,Re=Ja(e=>e.error),ze=A,Be=Pe||Ne||Fe||Ie===`mini-chat`,Ve=Q.useRef(null),He=Q.useMemo(()=>{let e=y?.selectedProjectId?C.find(e=>e.id===y.selectedProjectId)??null:null,t=w?C.find(e=>e.id===w)??null:null,n=e??t??C[0]??null;return n?NH(n):null},[w,y?.selectedProjectId,C]),Ue=Xn(r,O),We=a??r??``,[Ge,Ke]=Q.useState(null),qe=Zb(Ge,We,Ue,ce);Gt(()=>{Ke(e=>Zb(e,We,Ue,ce))},[Ue,ce,We]);let Je=Ue??qe?.parentTarget??null,Ye=qe?.execution??ce,Xe=Pf(),Ze=Xe!==null&&r===Xe,Qe=J(()=>{Je&&v(Je.id,Je.directory)}),$e=Je?.session?.title,et=h.returnToParent&&Je&&!Ze?(0,$.jsxs)(Qt,{type:`button`,variant:`outline`,size:`xs`,onClick:Qe,className:`absolute left-3 top-3 z-20 !font-normal bg-[var(--surface-background)]/95`,"aria-label":g(`chat.container.returnToParent.aria`),title:$e?.trim()?g(`chat.container.returnToParent.titleNamed`,{title:$e}):g(`chat.container.returnToParent.title`),children:[(0,$.jsx)(Z,{name:`arrow-left`,className:`h-4 w-4`}),g(`chat.container.returnToParent.label`)]}):null,tt=qb({readOnly:t,sessionIdentityPending:U,isSubagentSession:!!ee?.parentID||!!qe,allowPromptingSubagentSessions:N}),nt=Ye.modelId===ce.modelId?le:Ye.modelId?ri(T.find(e=>e.id===Ye.providerId),Ye.modelId)||Ye.modelId:g(`common.unavailable`),rt=Je?(0,$.jsx)(yT,{agentName:Ye.agentName,providerId:Ye.providerId,modelId:Ye.modelId,modelName:nt}):(0,$.jsx)(yT,{}),it=J(e=>{q.getState().setAllowPromptingSubagentSessions(e.allowPromptingSubagentSessions)}),at=J(e=>{if(typeof window>`u`||e.source!==window.parent||e.origin!==window.location.origin)return;let t=e.data;t?.type===`openchamber:chat-settings-sync`&&typeof t.payload?.allowPromptingSubagentSessions==`boolean`&&it({allowPromptingSubagentSessions:t.payload.allowPromptingSubagentSessions})}),ot=typeof window<`u`&&window.parent!==window;Kt(`message`,at,ot?window:dH),Wt(()=>{if(!ot)return;let e=window;e.__openchamberApplyChatSettingsSync=it,window.parent.postMessage({type:`openchamber:chat-settings-request`},window.location.origin)}),Ht(()=>{if(typeof window>`u`)return;let e=window;e.__openchamberApplyChatSettingsSync===it&&delete e.__openchamberApplyChatSettingsSync}),Q.useEffect(()=>{h.newSessionDraft&&e&&!r&&!Le&&_()},[e,r,Le,h.newSessionDraft,_]);let st=Q.useRef(()=>{}),ct=J(e=>{st.current(e)}),lt=Q.useRef(()=>{}),ut=J(()=>{lt.current()}),dt=hl(e=>e.legendTimelineEnabled),[ft,pt]=Q.useState(!0),[mt,ht]=Q.useState(!1),[gt,_t]=Q.useState(!1),[vt,yt]=Q.useState(0),bt=J(()=>{yt(e=>e+1)}),xt=J((e,t)=>{pt(e),e&&_t(!1),t!==void 0&&ht(t)});Q.useEffect(()=>{pt(!0),ht(!1),_t(!1)},[r]);let{scrollRef:St,notifyContentChange:Ct,getAnimationHandlers:wt,goToBottom:Tt,scrollToBottomOnSend:Et,releaseAutoFollow:Dt,beginHistoryViewportPreservation:Ot,endHistoryViewportPreservation:kt,restoreSnapshot:At,isPinned:jt,isFollowingProgrammatically:Mt,showScrollButton:Nt}=Az({enabled:n&&!dt,currentSessionId:r,viewportKey:a,sessionMessageCount:R,sessionIsWorking:Te,isMobile:Ne,onActiveTurnChange:ct,onUpwardUserIntent:ut}),Pt=Q.useRef(null);$z({enabled:Ne,scrollRef:St,scopeRef:Pt});let Ft=Q.useRef([]),It=Q.useMemo(()=>{let e=vi(l?.entries??[],r,Ft.current);return Ft.current=e,e},[l?.entries,r]),Lt=Q.useRef([]),Rt=Q.useMemo(()=>{if(!l)return re;let e=no(l.entries,r,re,Lt.current);return Lt.current=e,e},[l,r,re]),zt=Q.useMemo(()=>aT(It.length===0?Rt:r?[...It,li(r),...Rt]:It,se),[r,Rt,It,se]),Bt=Q.useRef(null),Ut=Q.useMemo(()=>mT({sessionId:r,messages:zt,retained:Bt.current}),[r,zt]);Bt.current=Ut.retained;let qt=Ut.messages,Jt=Q.useRef(null),Xt=Jt.current===r,Zt=Q.useRef(jV),$t=r?`${O}\n${r}`:null,en=J(()=>AV(qt));Q.useEffect(()=>{if(!PV({active:n,sessionId:r,sessionKey:$t,sessionIsWorking:Te})){Zt.current=FV(Zt.current);return}let e=r,t=O,i=setInterval(()=>{let n=en(),r=MV(Zt.current,{sessionKey:$t,working:!0,streaming:!!I,fingerprint:n,now:Date.now(),thresholdMs:EV,cooldownMs:DV,maxAttempts:3});Zt.current=r.state,r.shouldRefresh&&(NV({sessionId:e,directory:t,stalledForMs:r.stalledForMs,attempt:r.state.attempts,fingerprint:n}),Dr(t,e).catch(()=>{}))},OV);return()=>clearInterval(i)},[n,r,O,en,Te,I,$t]);let tn=Q.useMemo(()=>{if(se.length===0)return[];let e=new Set([...It,...Rt].filter(e=>Qa(e.parts)).map(e=>e.info.id));return se.map(e=>e.info.id).filter(t=>e.has(t))},[Rt,It,se]);Q.useEffect(()=>{tn.length!==0&&(p?.(tn),r&&oe(r,tn))},[oe,r,tn,p]);let nn=dV({sessionId:r,directory:O,messages:qt,historyMeta:Me,scrollRef:St,messageListRef:Ve,loadMoreMessages:ve,goToBottom:Tt,releaseAutoFollow:Dt,beginHistoryViewportPreservation:Ot,endHistoryViewportPreservation:kt,isPinned:dt?ft:jt,showScrollButton:dt?mt:Nt,isMobile:Ne,autoFillEnabled:n&&!ze,onWillLoadEarlier:bt}),rn=J(()=>{_t(!1),Ve.current?.scrollToBottom(),Tt(`instant`)}),an=J(()=>{_t(!1),Et()}),sn=J(()=>{_t(!0),nn.handleHistoryUpwardIntent()}),cn=lT({isMobile:Ne,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingOlder:nn.isLoadingOlder}),ln=nn.isLoadingOlder,dn=nn.loadEarlier,fn=J(()=>{_t(!0),dn({userInitiated:!0})});st.current=nn.handleActiveTurnChange,lt.current=nn.handleHistoryUpwardIntent,Q.useEffect(()=>{(Ce.length!==0||we.length!==0)&&Ct(`permission`)},[Ct,Ce,we]);let pn=TV({sessionId:r,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,scrollToTurn:nn.scrollToTurn,scrollToMessage:nn.scrollToMessage,resumeToBottom:rn}),mn=tt.showReadOnlyBanner?rt:t?null:(0,$.jsx)(Zw,{surface:s,scrollToBottom:an,showScrollToBottom:Ne&&nn.showScrollToBottom,onScrollToBottom:pn.resumeToLatest,submissionBlocked:tt.blockSubmission}),hn=J(e=>{pn.scrollToTurnId(e,{behavior:`smooth`})}),gn=nn.historySignals.canLoadEarlier,_n=h.promptNavigator&&!Ne&&!Fe&&!ze&&M&&nn.turnIds.length>=2;Q.useEffect(()=>{_n||q.getState().setPromptNavigatorPanelOpen(!1)},[_n]);let yn=J(e=>{if(!n||!r)return;let t=e;t.detail?.sessionId&&t.detail.sessionId!==r||Tt(`instant`)});Kt(uH,yn,n&&r&&typeof window<`u`?window:dH);let bn=J(e=>{if(!n||!r||ze||e.defaultPrevented||e.isComposing||e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let{activeMainTab:t}=q.getState();if(t!==`chat`||AH())return;let i=St.current;if(kH(document.activeElement,i)||OH(e.target))return;e.preventDefault();let a=e.key===`ArrowUp`?-1:1;pn.scrollByTurnOffset(a,{resumePastEnd:!1})});Kt(`keydown`,bn,n&&r&&!ze&&typeof window<`u`?window:dH);let xn=Q.useRef(0),Sn=J(()=>{let e=St.current;e&&e.style.setProperty(`--chat-scroll-height`,`${e.clientHeight}px`)}),Cn=J(()=>{xn.current||=requestAnimationFrame(()=>{xn.current=0,Sn()})});Gt(()=>{n&&Sn()},[n,r,ze,Sn]);let wn=typeof ResizeObserver<`u`;Vt(n&&wn?St:null,Cn),Kt(`resize`,Cn,n&&!wn&&typeof window<`u`?window:dH),Ht(()=>{xn.current&&=(cancelAnimationFrame(xn.current),0)});let Tn=Q.useRef(null),Dn=Q.useRef(0),On=fT({transcriptMessageCount:re.length,pendingUserCount:se.length,historyPrefixCount:It.length}),kn=pT({hasTranscriptShell:On,p0Satisfied:de.p0Satisfied,hasBusyShell:Te&&On,hasImmediateShell:se.length>0||It.length>0,hasRenderableSessionSnapshot:B,prefetchStatus:ue?.status,syncLoading:!!(r&&E.isLoading(r,{directory:O})),userRetrying:me,hasPaintedTranscript:Xt});kn===`pass`&&qt.length>0&&(Jt.current=r);let An=!!r&&kn===`hydrating`,jn=!!r&&kn===`load-error`;Q.useEffect(()=>{!jn||!r||za(Vi({kind:`request-error`,sessionID:r,directory:O,purpose:`load-failed`,source:`network`,request:ue?{sessionID:r,status:ue.status===`ready`?`ready`:ue.status,error:ue.error}:void 0,hydration:de,error:ue?.error}))},[r,O,jn,ue,de]),Q.useEffect(()=>{if(!n||!r||An)return;let e=qt.length,t=Tn.current!==r,i=!t&&Dn.current===0&&e>0;if(!t&&!i){Tn.current===r&&(Dn.current=e);return}let a=typeof window<`u`&&window.location.hash.length>0;if(Tn.current=r,Dn.current=e,a){Dt();return}let o=()=>{At()};typeof window>`u`?o():window.requestAnimationFrame(o)},[n,r,An,Dt,At,qt.length]),Q.useEffect(()=>{ne(e=>e.key===te?e:{key:te,attempt:0})},[te]),Q.useEffect(()=>{if(!n||!r||W.key!==te||!oH({sessionId:r,hasRenderableSessionSnapshot:B,hasCurrentSessionEntity:!!ee})||(k(r),ee||W.attempt>=2))return;let e=W.attempt+1,t=window.setTimeout(()=>{ne(t=>t.key===te&&t.attempt===W.attempt?{key:te,attempt:e}:t)},e*1e3);return()=>window.clearTimeout(t)},[n,ee,r,O,k,B,te,W]);let Mn=S&&r&&(S.targetSessionId?r===S.targetSessionId:r===S.sourceSessionId)?S:null;if(Mn){let e=Mn.stage===`preparing`?`chat.forkTransition.preparing`:Mn.stage===`copying`?`chat.forkTransition.copying`:Mn.stage===`opening`?`chat.forkTransition.opening`:`chat.forkTransition.loading`,t=[`preparing`,`copying`,`opening`,`loading`],n=g(`chat.forkTransition.progress`,{current:Math.max(1,t.indexOf(Mn.stage)+1),total:t.length});return(0,$.jsx)(`div`,{className:`flex h-full flex-col items-center justify-center bg-background px-6 text-center`,children:(0,$.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,role:`status`,"aria-live":`polite`,"aria-label":`${g(e)}. ${n}`,children:[(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:g(e)}),(0,$.jsx)(uv,{})]}),(0,$.jsx)(`span`,{className:`text-xs text-muted-foreground/70 tabular-nums`,children:n})]})})}if(!r&&!Le)return e&&!Re?(0,$.jsx)(`div`,{className:`flex h-full flex-col bg-background`}):(0,$.jsx)(`div`,{className:`flex flex-col h-full bg-background`,children:(0,$.jsx)(xT,{})});if(!r&&Le){if((b||x)&&ie){let e=`draft:${y.draftID??`pending`}`;return(0,$.jsxs)(`div`,{ref:Pt,className:Y(`relative flex h-full flex-col bg-background`,Ne&&`oc-chat-composer-swap-scope`),children:[(0,$.jsx)(jH,{currentSessionId:e,virtualizerKey:e,isDesktopExpandedInput:!1,isMobile:Ne,stickyUserHeader:j,directory:O,scrollRef:St,messageListRef:Ve,pendingRevealWork:!1,initialPinRevealComplete:!0,renderedMessages:[ie],isLoadingOlder:!1,sessionIsWorking:!0,streamingMessageId:null,activeStreamingPhase:null,retryOverlay:null,handleMessageContentChange:Ct,getAnimationHandlers:wt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:sn,onTimelineIsAtEndChange:xt,timelineFollowSuspended:!1,timelineHistoryAnchorToken:vt,scrollToBottom:rn,sessionQuestions:[],sessionPermissions:[],isProgrammaticFollowActive:Mt,showLoadOlderButton:!1,onLoadOlder:fn,turnIds:[],activeTurnId:null,onSelectTurn:hn,showPromptNavigator:!1,canLoadEarlierPrompts:!1,isLoadingOlderPrompts:!1,onLoadEarlierPrompts:fn,transcriptStatusRow:(0,$.jsx)(`div`,{className:`chat-column`,role:`status`,"aria-live":`polite`,children:(0,$.jsxs)(`div`,{className:`flex h-[1.2rem] items-center py-0.5 typography-meta text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:g(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(uv,{})]})})},e),(0,$.jsxs)(`div`,{className:Y(`invisible pointer-events-none relative z-10`,Ne&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,ze?`absolute inset-0 bg-background`:`bg-background`),"aria-hidden":`true`,children:[!Ne&&!ze?(0,$.jsx)(CH,{}):null,mn]}),(0,$.jsx)(iT,{})]})}return b||x?(0,$.jsx)(`div`,{className:`flex h-full flex-col items-center justify-center bg-background px-6 text-center`,children:(0,$.jsx)(`div`,{className:`flex flex-col items-center gap-3`,role:`status`,"aria-live":`polite`,"aria-label":g(`chat.emptyState.establishingConversation`),children:(0,$.jsxs)(`span`,{className:`typography-ui-header text-muted-foreground`,children:[(0,$.jsx)(`span`,{className:`animate-text-shimmer`,children:g(`chat.emptyState.establishingConversation`)}),(0,$.jsx)(uv,{})]})})}):(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[Be&&!ze?(0,$.jsxs)(`div`,{className:`oc-draft-center flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center`,children:[(0,$.jsx)(`h1`,{className:`text-balance text-3xl font-normal tracking-tight text-foreground`,children:PH(He?g(`chat.emptyState.draftTitleWithProject`,{project:He}):g(`chat.emptyState.draftTitle`),He)}),(0,$.jsx)(Ux,{onSubmit:e=>un.getState().requestPresetSubmit(e),className:`oc-draft-starters mt-8 max-w-md`})]}):null,(0,$.jsx)(`div`,{className:Y(`relative z-10 flex min-h-0`,Ne&&`oc-mobile-composer-foot`,ze?`flex-1 bg-background`:Be?Y(`bg-background`,`px-0`):`flex-1 items-center justify-center bg-background px-0 pb-[6vh]`),children:mn})]})}return r?jn?(0,$.jsxs)(`div`,{className:`relative flex h-full flex-col bg-background`,children:[et,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,ze?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":ze,children:ze?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center px-6`,children:(0,$.jsxs)(`div`,{className:`flex max-w-sm flex-col items-center text-center`,role:`alert`,"aria-live":`polite`,children:[(0,$.jsx)(`div`,{className:`mb-4 flex size-10 items-center justify-center rounded-full bg-[var(--status-error-background)] text-[var(--status-error-foreground)]`,children:(0,$.jsx)(Z,{name:`error-warning`,className:`size-5`,"aria-hidden":`true`})}),(0,$.jsx)(`h2`,{className:`typography-ui-header text-foreground`,children:g(`chat.history.loadFailedTitle`)}),(0,$.jsx)(`p`,{className:`mt-2 text-sm text-muted-foreground`,children:g(`chat.history.loadFailedDescription`)}),(0,$.jsxs)(Qt,{type:`button`,className:`mt-5`,onClick:he,children:[(0,$.jsx)(Z,{name:`refresh`,className:`size-4`,"aria-hidden":`true`}),g(`chat.history.retry`)]})]})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:mn})]}):An?(0,$.jsxs)(`div`,{ref:Pt,className:Y(`relative flex flex-col h-full bg-background`,Ne&&`oc-chat-composer-swap-scope`),children:[et,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,ze?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":ze,children:(0,$.jsx)(`div`,{ref:St,className:`absolute inset-0 overflow-y-auto overflow-x-hidden bg-background pt-6 chat-scroll`,style:xH,children:(0,$.jsx)(`div`,{className:`space-y-4 chat-scroll-foot-inset`,children:MH.map(e=>(0,$.jsx)(`div`,{className:`group w-full`,children:(0,$.jsx)(`div`,{className:`chat-message-column`,children:(0,$.jsxs)(`div`,{className:`space-y-2.5 px-4 py-3`,children:[(0,$.jsx)(`div`,{className:`space-y-1.5`,children:e.toolRows.map(t=>(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(id,{className:`h-3.5 w-3.5 rounded-full flex-shrink-0`}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,t.titleWidth)}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,t.detailWidth)})]},`${e.id}-${t.id}`))}),(0,$.jsxs)(`div`,{className:`space-y-1.5 pt-1`,children:[(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,e.textWidths[0])}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,e.textWidths[1])}),(0,$.jsx)(id,{className:Y(`h-4 rounded-md`,e.textWidths[2])})]})]})})},e.id))})})}),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Ne&&!ze?(0,$.jsx)(CH,{}):null,mn]})]}):qt.length===0&&!Te?(0,$.jsxs)(`div`,{className:`relative flex flex-col h-full bg-background`,children:[et,(0,$.jsx)(`div`,{className:Y(`relative min-h-0`,ze?`absolute inset-0 opacity-0 pointer-events-none`:`flex-1`),"aria-hidden":ze,children:ze?null:(0,$.jsx)(`div`,{className:`absolute inset-0 flex items-center justify-center`,children:(0,$.jsx)(xT,{})})}),(0,$.jsx)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:mn}),(0,$.jsx)(iT,{})]}):(0,$.jsxs)(`div`,{ref:Pt,className:Y(`relative flex flex-col h-full bg-background`,Ne&&`oc-chat-composer-swap-scope`),children:[d?(0,$.jsx)(`div`,{className:`shrink-0 border-b border-border bg-[var(--status-warning-background)] px-4 py-2.5 typography-meta text-[var(--status-warning-foreground)]`,children:d}):null,et,(0,$.jsx)(jH,{currentSessionId:r,virtualizerKey:a??r,isDesktopExpandedInput:ze,isMobile:Ne,stickyUserHeader:j,directory:O,scrollRef:St,messageListRef:Ve,pendingRevealWork:nn.pendingRevealWork,initialPinRevealComplete:ae,renderedMessages:nn.renderedMessages,isLoadingOlder:ln,sessionIsWorking:Te,streamingMessageId:I,activeStreamingPhase:L,retryOverlay:Ae,handleMessageContentChange:Ct,getAnimationHandlers:wt,handleHistoryScroll:nn.handleHistoryScroll,handleHistoryUpwardIntent:sn,onTimelineIsAtEndChange:xt,timelineFollowSuspended:gt,timelineHistoryAnchorToken:vt,scrollToBottom:rn,sessionQuestions:we,sessionPermissions:Ce,isProgrammaticFollowActive:Mt,showLoadOlderButton:cn,onLoadOlder:fn,turnIds:nn.turnIds,activeTurnId:nn.activeTurnId,onSelectTurn:hn,showPromptNavigator:_n,canLoadEarlierPrompts:gn,isLoadingOlderPrompts:ln,onLoadEarlierPrompts:fn},r),(0,$.jsxs)(`div`,{className:Y(`relative z-10`,Ne&&`oc-mobile-composer-foot oc-mobile-composer-foot--overlay`,ze?`flex-1 min-h-0 bg-background`:`bg-background`),children:[!Ne&&!ze?(0,$.jsx)(CH,{}):null,!ze&&qt.length>0&&(Ne?(0,$.jsx)(Nb,{placement:`expanded`,visible:nn.showScrollToBottom,onClick:pn.resumeToLatest}):(0,$.jsx)(Nb,{visible:nn.showScrollToBottom,onClick:pn.resumeToLatest})),mn]}),(0,$.jsx)(iT,{}),(0,$.jsx)(pV,{open:P,onOpenChange:F,sessionID:r??void 0,directory:O,onRevertMessage:u,onScrollToMessage:nn.scrollToMessage,onScrollByTurnOffset:pn.scrollByTurnOffset,onResumeToLatest:rn,canLoadEarlier:nn.historySignals.canLoadEarlier,isLoadingEarlier:ln,onLoadEarlier:fn})]}):null});IH.displayName=`MemoizedChatContainerContent`;var LH=()=>{let e=(0,pd.c)(2),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(id,{className:`h-4 w-4/5 animate-none rounded-md`}),(0,$.jsx)(id,{className:`h-4 w-2/3 animate-none rounded-md`}),(0,$.jsx)(id,{className:`h-4 w-1/2 animate-none rounded-md`})]}),e[0]=t):t=e[0];let n;return e[1]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,$.jsx)(`div`,{className:`flex h-full flex-col bg-background`,"data-session-view-loading":`true`,"aria-hidden":`true`,children:(0,$.jsx)(`div`,{className:`mt-auto w-full pb-5 motion-safe:animate-pulse`,children:(0,$.jsxs)(`div`,{className:`chat-message-column space-y-6 px-4`,children:[t,(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(id,{className:`h-4 w-5/6 animate-none rounded-md`}),(0,$.jsx)(id,{className:`h-4 w-3/5 animate-none rounded-md`})]}),(0,$.jsx)(id,{className:`h-24 w-full animate-none rounded-xl`})]})})}),e[1]=n):n=e[1],n},RH=({runtimeKey:e,...t})=>{let n=Fb(),r=la(),i=X(He(e=>({sessionId:e.currentSessionId,directory:e.currentSessionDirectory,draftID:e.newSessionDraft.open?e.newSessionDraft.draftID:null,draftPendingMessageId:e.newSessionDraft.open?e.newSessionDraft.pendingUserMessage?.info.id??null:null}))),a=Q.useRef(null),o=i.draftID&&i.draftPendingMessageId?`${i.draftID}:${i.draftPendingMessageId}`:null;o&&a.current?.identity!==o&&(a.current=null),Gt(()=>{!o||!i.draftPendingMessageId||(a.current={identity:o,messageId:i.draftPendingMessageId})},[o,i.draftPendingMessageId]);let s=X(e=>i.sessionId?e.retainedPendingUserMessages.get(i.sessionId)??cH:cH),c=a.current,l=c&&s.some(e=>e.info.id===c.messageId)?c.messageId:null,u=Q.useMemo(()=>i.sessionId?{runtimeKey:e,sessionId:i.sessionId,directory:i.directory??r}:null,[e,i.directory,i.sessionId,r]),d=Q.useMemo(()=>KV(u),[u]),f=d.key,p=yr()||ge()||n===`mini-chat`?yH:vH,[m,h]=Q.useState(()=>({activeIntent:d,cacheNeedsTrim:!1,cachedSessionViews:u?JV([],u,p,mH):[],pendingSessionView:null})),g=Q.useRef(d),_=Q.useRef(f),{cacheNeedsTrim:v,cachedSessionViews:y,pendingSessionView:b}=m,x=b?.intent===d?b.entry:null,S=Q.useMemo(()=>!u||!l?null:JV([],u,p,mH)[0]??null,[p,l,u]),C=Q.useMemo(()=>{let e=[...y];return x&&!e.some(e=>e.key===x.key)&&e.push(x),S&&!e.some(e=>e.key===S.key)&&e.push(S),e.sort((e,t)=>e.key.localeCompare(t.key))},[y,S,x]),w=XV(C,f),T=!!(f&&!w);Gt(()=>{g.current=d,_.current=f,h(e=>{let t=ZV(e,d,p);return l?QV(t,d,d,mH):t})},[p,v,l,d,f]);let E=b?.intent??null;Gt(()=>{E&&h(e=>$V(e,E,p))},[p,E]),Q.useEffect(()=>{if(!d.selection||w)return;let e=d,t=f;return Jl(()=>{g.current===e&&_.current===t&&h(n=>_.current===t?QV(n,e,g.current,mH):n)},{priority:`user-blocking`})},[w,p,d,f]);let D=J((e,t)=>{let n=g.current,r=_.current;h(i=>{if(g.current!==n||_.current!==r||i.activeIntent!==n||e!==r)return i;let a=YV(i.cachedSessionViews,e,t);return a===i.cachedSessionViews?i:{...i,cacheNeedsTrim:!0,cachedSessionViews:a}})});return(0,$.jsxs)(`div`,{className:`h-full bg-background`,"aria-busy":T||void 0,children:[T?(0,$.jsx)(LH,{},f):null,C.map(e=>(0,$.jsx)(Q.Activity,{name:`chat-session-${e.sessionId}`,mode:w===e.key?`visible`:`hidden`,children:(0,$.jsx)(IH,{...t,sessionId:e.sessionId,sessionDirectory:e.directory,sessionViewKey:e.key,onSessionViewEstimateChange:D,committedDraftHandoffMessageId:w===e.key?l:null})},e.key)),f?null:(0,$.jsx)(IH,{...t,sessionId:null,sessionDirectory:i.directory})]})},zH=e=>{let t=(0,pd.c)(24),{host:n,runtimeKey:r,readOnly:i}=e,a=i!==void 0&&i,o;t[0]===n?o=t[1]:(o=hT(n),t[0]=n,t[1]=o);let s=o,c;t[2]===n.onRevertMessage?c=t[3]:(c=n.onRevertMessage?{onRevertMessage:n.onRevertMessage}:{},t[2]=n.onRevertMessage,t[3]=c);let l;t[4]!==n.directory||t[5]!==n.sessionId||t[6]!==n.sessionSurface||t[7]!==c?(l={...n.sessionSurface,sessionId:n.sessionId,directory:n.directory,...c},t[4]=n.directory,t[5]=n.sessionId,t[6]=n.sessionSurface,t[7]=c,t[8]=l):l=t[8];let u=l,d=`host:${r}:${u.surfaceId}:${n.sessionId}`,f;t[9]!==n.assistantHistory||t[10]!==n.composerSurface||t[11]!==n.directory||t[12]!==n.onPendingUserMessagesMaterialized||t[13]!==n.onRevertMessage||t[14]!==n.pendingUserMessages||t[15]!==n.sessionId||t[16]!==n.warning||t[17]!==s||t[18]!==a||t[19]!==d?(f=(0,$.jsx)(`div`,{className:`h-full bg-background`,children:(0,$.jsx)(IH,{autoOpenDraft:!1,readOnly:a,sessionId:n.sessionId,sessionDirectory:n.directory,sessionViewKey:d,composerSurface:n.composerSurface,hostedFeatures:s,assistantHistory:n.assistantHistory,pendingUserMessages:n.pendingUserMessages,onPendingUserMessagesMaterialized:n.onPendingUserMessagesMaterialized,onRevertMessage:n.onRevertMessage,warning:n.warning})}),t[9]=n.assistantHistory,t[10]=n.composerSurface,t[11]=n.directory,t[12]=n.onPendingUserMessagesMaterialized,t[13]=n.onRevertMessage,t[14]=n.pendingUserMessages,t[15]=n.sessionId,t[16]=n.warning,t[17]=s,t[18]=a,t[19]=d,t[20]=f):f=t[20];let p;return t[21]!==u||t[22]!==f?(p=(0,$.jsx)(Xy.Provider,{value:u,children:f}),t[21]=u,t[22]=f,t[23]=p):p=t[23],p},BH=e=>{let t=(0,pd.c)(16),n,r,i;t[0]===e?(n=t[1],r=t[2],i=t[3]):({explicitSession:n,runtimeKey:i,...r}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i);let a=la(),o=n.directory??a,s;t[4]!==o||t[5]!==n?(s=Yy({...n,directory:o}),t[4]=o,t[5]=n,t[6]=s):s=t[6];let c=s,l=`explicit:${i}:${n.viewKey}`,u;t[7]!==o||t[8]!==n.active||t[9]!==n.sessionId||t[10]!==r||t[11]!==l?(u=(0,$.jsx)(`div`,{className:`h-full bg-background`,children:(0,$.jsx)(IH,{...r,active:n.active,sessionId:n.sessionId,sessionDirectory:o,sessionViewKey:l})}),t[7]=o,t[8]=n.active,t[9]=n.sessionId,t[10]=r,t[11]=l,t[12]=u):u=t[12];let d;return t[13]!==c||t[14]!==u?(d=(0,$.jsx)(Xy.Provider,{value:c,children:u}),t[13]=c,t[14]=u,t[15]=d):d=t[15],d},VH=e=>{let t=(0,pd.c)(14),n=Q.useSyncExternalStore(bH,u,u);if(e.host){let r=`${n}:${e.host.sessionSurface.surfaceId}`,i;return t[0]!==e||t[1]!==n||t[2]!==r?(i=(0,$.jsx)(zH,{...e,host:e.host,runtimeKey:n},r),t[0]=e,t[1]=n,t[2]=r,t[3]=i):i=t[3],i}if(e.explicitSession){let r=`${n}:${e.explicitSession.viewKey}`,i;return t[4]!==e.active||t[5]!==e.autoOpenDraft||t[6]!==e.explicitSession||t[7]!==e.readOnly||t[8]!==n||t[9]!==r?(i=(0,$.jsx)(BH,{autoOpenDraft:e.autoOpenDraft,readOnly:e.readOnly,active:e.active,explicitSession:e.explicitSession,runtimeKey:n},r),t[4]=e.active,t[5]=e.autoOpenDraft,t[6]=e.explicitSession,t[7]=e.readOnly,t[8]=n,t[9]=r,t[10]=i):i=t[10],i}let r;return t[11]!==e||t[12]!==n?(r=(0,$.jsx)(RH,{...e,runtimeKey:n},n),t[11]=e,t[12]=n,t[13]=r):r=t[13],r},HH=2e4,UH=()=>typeof document>`u`||document.visibilityState===`visible`&&document.hasFocus()?`visible`:`hidden`,WH=e=>{if(!le()&&!mt())return;let t=g();t?.push?.setVisibility&&t.push.setVisibility({visible:e,platform:ht()})},GH=e=>{let t=e?.enabled??!0;Q.useEffect(()=>{if(!t||!le()&&!mt()||typeof window>`u`)return;if(mt()){let e=!0,t=!1,n=null,r=()=>WH(e);Et(async()=>{let{App:e}=await import(`./vendor-capacitor-app-PzT84wSx.js`).then(e=>e.t);return{App:e}},__vite__mapDeps([53,1,10])).then(async({App:i})=>{if(t)return;let a=await i.getState().catch(()=>null);a&&(e=a.isActive===!0),r();let o=await i.addListener(`appStateChange`,({isActive:t})=>{e=t===!0,r()});if(t){o.remove();return}n=()=>void o.remove()}).catch(()=>void 0);let i=window.setInterval(()=>{e&&WH(!0)},HH);return()=>{t=!0,window.clearInterval(i),n?.()}}if(typeof document>`u`)return;let e=()=>{WH(UH()===`visible`)},n=()=>{UH()===`visible`&&WH(!0)},r=()=>{WH(!1)};e();let i=window.setInterval(n,HH);return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pagehide`,r),window.addEventListener(`pageshow`,e),window.addEventListener(`focus`,e),window.addEventListener(`blur`,e),()=>{window.clearInterval(i),document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pagehide`,r),window.removeEventListener(`pageshow`,e),window.removeEventListener(`focus`,e),window.removeEventListener(`blur`,e)}},[t])},KH=`OpenChamber`,qH=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``).split(`/`).filter(Boolean);return t[t.length-1]??``},JH=(e,t)=>[e,t,KH].filter(e=>typeof e==`string`&&e.trim().length>0).join(` | `),YH=()=>{let e=eo(e=>e.activeProjectId?e.projects.find(t=>t.id===e.activeProjectId)??null:null),t=Q.useMemo(()=>e&&qH(e.path)||null,[e]),[n,r]=Q.useState(null);Q.useEffect(()=>{if(typeof window>`u`||!O()){r(null);return}let e=!1,t=async()=>{try{if(R()){e||r(null);return}let t=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,n=d();if(n&&Oe(n,t)){e||r(null);return}let i=(await Ie()).hosts.find(e=>n?Oe(n,je(e)):!1),a=i?.label?.trim()?ke(i.label.trim()):`Instance`;e||r(a)}catch{e||r(`Instance`)}};t();let n=()=>{t()};return window.addEventListener(`focus`,n),()=>{e=!0,window.removeEventListener(`focus`,n)}},[]);let i=Q.useMemo(()=>JH(t,n),[t,n]);Q.useEffect(()=>{typeof document<`u`&&(document.title=i),O()&&(async()=>{try{if(typeof navigator<`u`&&/Macintosh|Mac OS X/.test(navigator.userAgent||``))return;await $t(i)}catch{return}})()},[i])},XH=()=>{let e=X.getState().currentSessionId;if(!e)return``;let t=ia().find(t=>t.id===e);return typeof t?.directory==`string`?t.directory:``},ZH=async(e,t=6e3)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t),i=Date.now();try{let t=await f(e,{method:`GET`,headers:{Accept:`application/json`},signal:n.signal}),r=Date.now()-i,a=t.headers.get(`content-type`)||``,o=a.toLowerCase(),s=o.includes(`json`)&&!o.includes(`text/html`),c=``;if(s){let e=await t.json().catch(()=>null);if(Array.isArray(e))c=`json[array] len=${e.length}`;else if(e&&typeof e==`object`){let t=Object.keys(e).slice(0,8);c=`json[object] keys=${t.join(`,`)}${Object.keys(e).length>t.length?`,…`:``}`}else c=`json[${typeof e}]`}else c=a?`content-type=${a}`:`no content-type`;return{ok:t.ok&&s,status:t.status,elapsedMs:r,summary:c}}catch(e){return{ok:!1,status:0,elapsedMs:Date.now()-i,summary:`error=${n.signal.aborted||e instanceof Error&&(e.name===`AbortError`||e.message.toLowerCase().includes(`aborted`))?`timeout after ${t}ms`:e instanceof Error?e.message:String(e)}`}}finally{clearTimeout(r)}},QH=e=>{if(!e||!Number.isFinite(e))return`(n/a)`;try{return new Date(e).toISOString()}catch{return`(invalid)`}},$H=e=>{if(typeof e==`number`&&Number.isFinite(e)&&e>0)return Math.trunc(e);if(typeof e==`string`){let t=Number.parseInt(e,10);if(Number.isFinite(t)&&t>0)return t}return null},eU=e=>!!e&&typeof e==`object`&&!Array.isArray(e),tU=(e,t=`(n/a)`)=>typeof e==`string`?e.trim()||t:typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`boolean`?e?`true`:`false`:t,nU=(e,t,n)=>e===`node-shebang`||e===`node-launcher`?t?`node (${t})`:`node`:e===`bun-shebang`?n?`bun (${n})`:`bun`:e||`direct executable`,rU=async()=>{let e=new Date,t=typeof navigator<`u`?navigator.userAgent:`(no navigator)`,n=XH(),r=q.getState().eventStreamStatus,i=typeof window<`u`?window.location.origin:``,o=a(),s=o.health(),c=o.api(`/api/`),l=await(async()=>{if(!s)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),5e3);try{let t=await f(s,{method:`GET`,headers:{Accept:`application/json`},signal:e.signal});if(!t.ok)return null;let n=await t.json().catch(()=>null);return!n||typeof n!=`object`||Array.isArray(n)?null:n}catch{return null}finally{clearTimeout(t)}})(),u=await(async()=>{if(!c)return null;let e=new AbortController,t=setTimeout(()=>e.abort(),7e3);try{let t=await f(o.api(`/api/config/opencode-resolution`),{method:`GET`,headers:{Accept:`application/json`},signal:e.signal}),n=t.headers.get(`content-type`)||`(none)`;if(!t.ok)return{data:null,status:t.status,error:`http ${t.status} content-type=${n}`};let r=await t.text(),i=null;try{i=JSON.parse(r)}catch{let e=r.replace(/\s+/g,` `).slice(0,120);return{data:null,status:t.status,error:`invalid json content-type=${n} body=${e||`(empty)`}`}}return!i||typeof i!=`object`||Array.isArray(i)?{data:null,status:t.status,error:`invalid json-shape content-type=${n}`}:{data:i,status:t.status,error:null}}catch(e){return{data:null,status:null,error:e instanceof Error?e.message:String(e)}}finally{clearTimeout(t)}})()||{data:null,status:null,error:null},d=(e,t=!0)=>{if(!c)return null;let r=new URL(e.replace(/^\/+/,``),c);return t&&n&&r.searchParams.set(`directory`,n),r.toString()},p=c?await Promise.all([{label:`health`,path:`/health`,includeDirectory:!1},{label:`config`,path:`/config`,includeDirectory:!0},{label:`providers`,path:`/config/providers`,includeDirectory:!0},{label:`agents`,path:`/agent`,includeDirectory:!0,timeoutMs:12e3},{label:`commands`,path:`/command`,includeDirectory:!0,timeoutMs:1e4},{label:`project`,path:`/project/current`,includeDirectory:!0},{label:`path`,path:`/path`,includeDirectory:!0},{label:`sessions`,path:`/session`,includeDirectory:!0,timeoutMs:12e3},{label:`sessionStatus`,path:`/session/status`,includeDirectory:!0}].map(async e=>{let t=d(e.path,e.includeDirectory!==!1);if(!t)return{label:e.label,url:`(none)`,result:null};let n=await ZH(t,typeof e.timeoutMs==`number`?e.timeoutMs:void 0);return{label:e.label,url:t,result:n}})):[],m=[];m.push(`Time: ${e.toISOString()}`),m.push(`OpenChamber version: 1.19.17`),m.push(`Runtime: ${i||`(unknown)`} (api=${c||`(unknown)`})`),m.push(`OpenCode SDK base: ${it.getBaseUrl()}`),m.push(`Event stream: ${r}`),m.push(`Directory: ${n||`(none)`}`),m.push(`Platform: ${t}`);let h=$H(l?.openCodePort);if(m.push(`OpenCode runtime port: ${h??`(unknown)`}`),typeof l?.openCodeRunning==`boolean`&&m.push(`OpenCode runtime running: ${l.openCodeRunning?`yes`:`no`}`),typeof l?.openCodeSecureConnection==`boolean`&&m.push(`Secure OpenCode connection: ${l.openCodeSecureConnection?`true`:`false`}`),typeof l?.openCodeAuthSource==`string`&&l.openCodeAuthSource.trim()&&m.push(`OpenCode auth source: ${l.openCodeAuthSource}`),typeof window<`u`){let e=window.__OPENCHAMBER_MACOS_MAJOR__;typeof e==`number`&&Number.isFinite(e)&&e>0&&m.push(`macOS major: ${e}`)}if(/Mac OS X|Macintosh/.test(t)){m.push(``),m.push(`OpenCode CLI resolution:`);let e=eU(l?.lastOpenCodeLaunchDiagnostics)?l.lastOpenCodeLaunchDiagnostics:null,t=e&&Array.isArray(e.args)?e.args.filter(e=>typeof e==`string`):[],n=u.data,r=n&&typeof n.configured==`string`?n.configured:null,i=n&&typeof n.resolved==`string`?n.resolved:l&&typeof l.opencodeBinaryResolved==`string`?l.opencodeBinaryResolved:``,a=n&&typeof n.resolvedDir==`string`?n.resolvedDir:``,o=n&&typeof n.source==`string`?n.source:l&&typeof l.opencodeBinarySource==`string`?l.opencodeBinarySource:``,s=n&&typeof n.launchBinary==`string`?n.launchBinary:l&&typeof l.opencodeLaunchBinary==`string`?l.opencodeLaunchBinary:``,c=n&&typeof n.launchWrapperType==`string`?n.launchWrapperType:l&&typeof l.opencodeLaunchWrapperType==`string`?l.opencodeLaunchWrapperType:``,d=n&&Array.isArray(n.launchArgs)?n.launchArgs.filter(e=>typeof e==`string`):l&&Array.isArray(l.opencodeLaunchArgs)?l.opencodeLaunchArgs.filter(e=>typeof e==`string`):[],f=n&&typeof n.node==`string`?n.node:l&&typeof l.nodeBinaryResolved==`string`?l.nodeBinaryResolved:``,p=n&&typeof n.bun==`string`?n.bun:l&&typeof l.bunBinaryResolved==`string`?l.bunBinaryResolved:``,h=n&&typeof n.detectedNow==`string`?n.detectedNow:``,g=n&&typeof n.detectedSourceNow==`string`?n.detectedSourceNow:``;if(r!==null&&m.push(`- configured: ${r.trim().length===0?`(cleared)`:r}`),i){let e=a||(i.includes(`/`)?i.split(`/`).slice(0,-1).join(`/`)||`/`:``);m.push(`- opencode: ${i}${e?` (dir=${e})`:``}`)}else m.push(`- opencode: (n/a)`);m.push(`- source: ${o||`(n/a)`}`),h&&(m.push(`- detected-now: ${h}`),m.push(`- detected-source: ${g||`(n/a)`}`)),e?(m.push(`- launched-at: ${tU(e.launchedAt)}`),m.push(`- launch: ${tU(e.binary)} ${t.join(` `)}`.trim()),m.push(`- cwd: ${tU(e.cwd)}`),m.push(`- wrapper: ${tU(e.wrapperType)}`),m.push(`- runtime: ${nU(tU(e.wrapperType,``),f,p)}`),m.push(`- PATH entries: ${tU(e.pathEntryCount,`(unknown)`)}`),m.push(`- shell env: ${tU(e.hasShellEnv,`(unknown)`)} (${tU(e.shellEnvKeysCount,`?`)} keys)`)):(m.push(`- launch-binary: ${s||`(n/a)`}`),m.push(`- launch-wrapper: ${c||`(n/a)`}`),m.push(`- launch-args: ${d.length?d.join(` `):`(none)`}`),m.push(`- runtime: ${nU(c||``,f,p)}`)),!n&&u.error&&m.push(`- resolution-endpoint: ${u.error}`)}if(m.push(``),p.length){m.push(`OpenCode API probes:`);for(let e of p){if(!e.result){m.push(`- ${e.label}: (no url)`);continue}let{ok:t,status:n,elapsedMs:r,summary:i}=e.result,a=t?``:` url=${e.url}`;m.push(`- ${e.label}: ${t?`ok`:`fail`} status=${n} time=${r}ms ${i}${a}`)}}else m.push(`OpenCode API probes: (skipped)`);return m.push(``),m.push(`Generated: ${QH(Date.now())}`),m.join(`
|
|
6585
6585
|
`)},iU=async()=>{let e=await rU(),t=q.getState();t.setOpenCodeStatusText(e),t.setOpenCodeStatusDialogOpen(!0)},aU=(e,t)=>e===t?!0:!e||!t?!1:e.scope===t.scope&&e.sessionId===t.sessionId&&e.projectId===t.projectId,oU=e=>e?`${e.scope}:${e.projectId??``}:${e.sessionId}`:null,sU=e=>({scope:`project`,sessionId:e,projectId:null}),cU=ze()(e=>({focus:null,setFocus:t=>e(e=>aU(e.focus,t)?e:{focus:t})})),lU=null,uU=0,dU=(e,t)=>{let n=new Set,r=[];for(let i of t){if(!i.sessionId)continue;let t=e===`pinned`?i.sessionId:`${i.projectId??``}:${i.sessionId}`;n.has(t)||(n.add(t),r.push(i.scope===e?i:{...i,scope:e}))}return r},fU=e=>{let t=++uU;return lU={pinned:dU(`pinned`,e.pinned),project:dU(`project`,e.project)},()=>{uU===t&&(lU=null)}},pU=()=>lU,mU=e=>!!e.parentID,hU=(e,t)=>{if(!e)return null;let n=new Map(t.map(e=>[e.id,e])),r=n.get(e);if(!r)return e;for(;r&&mU(r);){let e=r.parentID;if(!e)break;let t=n.get(e);if(!t)return e;r=t}return r?.id??e},gU=()=>{let e=Ui.getState().activeSessions;if(e.length>0)return e;let t=fi();return t.length>0?t:ia()},_U=(e,t,n)=>{if(!t)return-1;if(n?.scope){let r=e.findIndex(e=>e.scope===n.scope&&e.sessionId===t&&(!n.projectId||e.projectId===n.projectId));if(r>=0)return r}if(n?.projectId){let r=e.findIndex(e=>e.sessionId===t&&e.projectId===n.projectId);if(r>=0)return r}return e.findIndex(e=>e.sessionId===t)},vU=e=>[...e.pinned,...e.project],yU=(e,t,n,r)=>{if(e.length===0)return null;let i=_U(e,n,r);return i<0?t>0?e[0]??null:e[e.length-1]??null:e[(i+t+e.length)%e.length]??null},bU=(e,t,n=cU.getState().focus)=>{let r=hU(t,gU()),i=n?.sessionId===t?n:null,a=pU();return a?yU(vU(a),e,r,i):null},xU=(e,t,n=e=>{X.getState().setCurrentSession(e.sessionId,e.directory)})=>{let r=bU(e,t);return r?(cU.getState().setFocus({scope:r.scope,sessionId:r.sessionId,projectId:r.projectId}),n(r),r):null},SU=.5,CU=.1,wU=`oc.webviewZoomFactor`,TU=e=>Number.isFinite(e)?Math.min(3,Math.max(SU,Math.round(e*100)/100)):1,EU=()=>{if(typeof window>`u`)return 1;try{let e=window.localStorage.getItem(wU);return e?TU(Number.parseFloat(e)):1}catch{return 1}},DU=e=>{if(!(typeof window>`u`))try{window.localStorage.setItem(wU,String(e))}catch{}},OU=e=>{let t=TU(e);return typeof document<`u`&&(document.documentElement.style.zoom=t===1?``:String(t)),DU(t),t},kU=()=>{if(typeof document>`u`)return 1;let e=document.documentElement.style.zoom;if(!e)return EU();let t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?TU(t):EU()},AU=()=>{if(w())return;let e=EU();e!==1&&OU(e)},jU=async()=>{if(w())try{let e=await I(`desktop_zoom_in`);if(typeof e==`number`&&Number.isFinite(e))return TU(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_in failed, using CSS zoom`,e)}return OU(kU()+CU)},MU=async()=>{if(w())try{let e=await I(`desktop_zoom_out`);if(typeof e==`number`&&Number.isFinite(e))return TU(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_out failed, using CSS zoom`,e)}return OU(kU()-CU)},NU=async()=>{if(w())try{let e=await I(`desktop_zoom_reset`);if(typeof e==`number`&&Number.isFinite(e))return TU(e)}catch(e){console.warn(`[webview-zoom] desktop_zoom_reset failed, using CSS zoom`,e)}return OU(1)},PU=9,FU=null,IU=0,LU=({pinnedTargets:e,projectTargets:t})=>[...e,...t].slice(0,PU),RU=(e,t)=>{let n=e.findIndex(e=>e.scope===t.scope&&e.sessionId===t.sessionId&&(e.projectId??null)===(t.projectId??null));return n>=0?n+1:null},zU=e=>{let t=++IU;return FU={targets:e.targets.slice(0,PU),activate:e.activate},()=>{IU===t&&(FU=null)}},BU=e=>{if(!Number.isInteger(e)||e<1||e>PU)return!1;let t=FU,n=t?.targets[e-1];return!t||!n?!1:(t.activate(n),!0)},VU=e=>{let t=e.trim();if(!t)return null;let n=dd.getState(),r=n.createTab(t);return!r||r===`tab-invalid`?null:(n.setActiveTab(t,r),r)},HU=e=>{let t=e.trim();if(!t)return null;let n=q.getState();return!n.isBottomTerminalOpen&&n.activeMainTab!==`terminal`&&n.setBottomTerminalOpen(!0),VU(t)},UU=(e,t)=>{let n=e.trim();if(!n)return!1;let r=dd.getState(),i=r.getDirectoryState(n);if(!i||i.tabs.length<2)return!1;let a=i.tabs.findIndex(e=>e.id===i.activeTabId),o=((a>=0?a:0)+t+i.tabs.length)%i.tabs.length,s=i.tabs[o]?.id;return!s||s===i.activeTabId?!1:(r.setActiveTab(n,s),!0)},WU=e=>{let t=e.trim();if(!t)return{closed:!1,wasLastTab:!1};let n=dd.getState(),r=n.getDirectoryState(t),i=r?.activeTabId??null;if(!r||!i)return{closed:!1,wasLastTab:!1};let a=r.tabs.length===1;return n.closeTab(t,i),{closed:!0,wasLastTab:a}},GU=()=>typeof window>`u`||window.parent===window||!Of(window.location.search)?!1:(window.parent.postMessage({type:Tf},window.location.origin),!0),KU=()=>{let{isMobile:e,closeActiveContextPanelTab:t}=q.getState();if(e)return!1;let n=Ul();return n&&t(n)?!0:w()?(I(`desktop_close_current_window`).catch(e=>{console.warn(`[keyboard-shortcuts] failed to close current window`,e)}),!0):!1},qU=({sessionId:e,surfaceKind:t,wiringCanAbort:n,primaryCanAbort:r,pendingSend:i=!1})=>e?i||n?!0:t!==`secondary`&&r:!1,JU=async({sessionId:e,currentProviderId:t,currentModelId:n,waitForConnectionOrThrow:r,getAuthoritativeDirectoryForSession:i,summarizeSession:a,onCompactFailed:o})=>{try{await r();let s=i(e);if(!s){o();return}await a(e,t,n,s)}catch(e){o(e)}},YU=()=>{let e=(0,pd.c)(69),{t}=Yt(),n=X(XU),r=X(ZU),i=X(QU),a=X($U),o=Nn,s=q(eW),c=q(tW),l=q(nW),u=q(rW),d=q(iW),f=q(aW),p=q(oW),m=q(sW),h=q(cW),g=q(lW),_=q(uW),v=q(dW),y=q(fW),b=q(pW),x=q(mW),S=q(hW),C=q(gW),T=q(_W),E=q(vW),D=$e(yW),O=eo(bW),{themeMode:k,setThemeMode:A}=Ws(),{working:j}=LN(),M=Q.useRef(null),N=Q.useRef(null),P=Q.useRef(null),F=Q.useRef(!1),L=Q.useRef(k),R,z;e[0]===k?(R=e[1],z=e[2]):(R=()=>{L.current=k},z=[k],e[0]=k,e[1]=R,e[2]=z),Q.useEffect(R,z);let B;e[3]===i?B=e[4]:(B=()=>{N.current&&=(clearTimeout(N.current),null),M.current=null,i()},e[3]=i,e[4]=B);let V=B,H;e[5]===Symbol.for(`react.memo_cache_sentinel`)?(H=()=>{P.current&&=(clearTimeout(P.current),null),Nm.getState().clear()},e[5]=H):H=e[5];let ee=H,U;e[6]===Symbol.for(`react.memo_cache_sentinel`)?(U=()=>{P.current&&=(clearTimeout(P.current),null);let e=Nm.getState().arm(Mm);P.current=setTimeout(()=>{let{expiresAt:e}=Nm.getState();e&&Date.now()>=e&&Nm.getState().clear(),P.current=null},Math.max(0,e-Date.now()))},e[6]=U):U=e[6];let te=U,W;e[7]!==O?.id||e[8]!==O?.path||e[9]!==r||e[10]!==D||e[11]!==h||e[12]!==n||e[13]!==V||e[14]!==_||e[15]!==b||e[16]!==m||e[17]!==y||e[18]!==C||e[19]!==d||e[20]!==f||e[21]!==g||e[22]!==v||e[23]!==A||e[24]!==x||e[25]!==E||e[26]!==t||e[27]!==p||e[28]!==s||e[29]!==T||e[30]!==c||e[31]!==S||e[32]!==u||e[33]!==l||e[34]!==j?(W=()=>{let e=e=>Os(e,E),i=e=>Ns(e,E),a=xW,k=[`[data-slot="dropdown-menu-content"]`,`[data-slot="select-content"]`,`[role="combobox"]`,`[role="listbox"]`,`[role="menu"]`,`[role="menuitem"]`,`[role="option"]`,`[data-radix-popper-content-wrapper]`].join(`,`),P=e=>e instanceof Element&&!!e.closest(k),R=CW,z=TW,B=EW,H=async()=>{let e=yC(),n=e?TC(e):null;if(n&&e){try{await n.compact({providerID:e.selection.value.providerID,modelID:e.selection.value.modelID,agent:e.selection.value.agent,variant:e.selection.value.variant})}catch(e){let n=e;ro.error(n instanceof Error?n.message:t(`chat.chatInput.toast.compactFailed`))}return}let r=X.getState().currentSessionId;if(!r)return;let{currentProviderId:i,currentModelId:a}=Oa.getState();await JU({sessionId:r,currentProviderId:i,currentModelId:a,waitForConnectionOrThrow:an,getAuthoritativeDirectoryForSession:X.getState().getAuthoritativeDirectoryForSession,summarizeSession:DW,onCompactFailed:e=>{ro.error(e instanceof Error?e.message:t(`chat.chatInput.toast.compactFailed`))}})},U=t=>{let r=Nm.getState().pending;if(t.repeat||t.isComposing&&!r||t.defaultPrevented&&!r||a(t.target)&&!r)return;let i=e(`leader_key`);if(r){let e=()=>{F.current=!0,window.setTimeout(()=>{F.current=!1},0)};if(i&&ks(t,i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),te();return}let r=t.key.toLowerCase();if(r===`escape`){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),ee();return}if(t.key===`Control`||t.key===`Shift`||t.key===`Alt`||t.key===`Meta`)return;if(t.metaKey||t.ctrlKey||t.altKey){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),ee();return}let{activeMainTab:a,isModelSelectorOpen:o,isAgentSelectorOpen:s}=q.getState(),c=vC(a)&&!B();if(r===`m`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),ee(),window.requestAnimationFrame(()=>{y(!o,{instant:!0})});return}if(r===`a`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),ee(),b(!s,{instant:!0});return}if(r===`n`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),ee();let r=yC(),i=r?TC(r):null;i?i.shortcut(`new`):(_(`chat`),g(!1),n());return}if(r===`c`&&c){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),ee(),H(),z();return}t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),e(),ee(),z();return}if(!i||!ks(t,i)||B())return;let{activeMainTab:o}=q.getState();vC(o)&&(t.preventDefault(),t.stopPropagation(),te())},W=()=>Nm.getState().pending||F.current,ne=e=>{W()&&e.preventDefault()},G=e=>{W()&&(e.preventDefault(),e.stopPropagation())},re=t=>{if(a(t.target)){if(!ge()&&ks(t,e(`new_terminal_tab`))){let e=Ul();if(!e||!VU(e))return;t.preventDefault(),t.stopPropagation();return}if(!ge()&&ks(t,e(`previous_terminal_tab`))){let e=Ul();if(!e||!UU(e,-1))return;t.preventDefault(),t.stopPropagation();return}if(!ge()&&ks(t,e(`next_terminal_tab`))){let e=Ul();if(!e||!UU(e,1))return;t.preventDefault(),t.stopPropagation();return}if(ks(t,e(`close_context_panel_tab`))){let e=Ul();if(!e)return;let{closed:n,wasLastTab:r}=WU(e);if(!n)return;if(t.preventDefault(),t.stopPropagation(),r){let e=q.getState();e.setBottomTerminalOpen(!1),e.activeMainTab===`terminal`&&e.setActiveMainTab(`chat`)}return}if(ks(t,e(`toggle_terminal`))){let{isMobile:e}=q.getState();if(e)return;t.preventDefault(),t.stopPropagation(),p();return}if(ks(t,e(`toggle_bottom_panel`))){let{isMobile:e}=q.getState();if(e)return;t.preventDefault(),t.stopPropagation(),p();return}if(ks(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=q.getState();if(e)return;t.preventDefault(),t.stopPropagation(),m(!n);return}}},ie=OW,K=t=>{if(t.defaultPrevented)return;if(ks(t,e(`close_context_panel_tab`))){(GU()||KU())&&(t.preventDefault(),t.stopPropagation());return}if(a(t.target))return;let r=kW;if(r(t.target)&&t.ctrlKey&&!t.metaKey&&!t.shiftKey&&!t.altKey&&t.key.toLowerCase()===`t`){t.preventDefault(),ie();return}if(ks(t,e(`open_command_palette`))){t.preventDefault(),s();return}if(ks(t,e(`open_timeline_dialog`))){t.preventDefault(),x(!0);return}if(ks(t,e(`toggle_prompt_navigator`))){let{activeMainTab:e,promptNavigatorEnabled:n,isSettingsDialogOpen:r,isCommandPaletteOpen:i,isHelpDialogOpen:a,isSessionSwitcherOpen:o,isAboutDialogOpen:s,isTimelineDialogOpen:c,isMultiRunLauncherOpen:l,isImagePreviewOpen:u}=q.getState();if(!n||h||ge()||e!==`chat`||r||i||a||o||s||c||l||u)return;t.preventDefault(),S();return}if(ks(t,e(`open_status`))){t.preventDefault(),iU();return}if(ks(t,e(`open_help`))){t.preventDefault(),c();return}if(w()&&ks(t,e(`new_mini_chat`))){t.preventDefault(),I(`desktop_open_draft_mini_chat_window`,{directory:D||O?.path||``,projectId:O?.id??null}).catch(AW);return}let o=ks(t,e(`new_chat`)),b=ks(t,e(`new_chat_worktree`));if(o||b){if(t.preventDefault(),_(`chat`),g(!1),!ge()&&b){hx();return}n();return}if(ks(t,e(`cycle_theme`))){if(t.preventDefault(),Ff()!==null&&window.parent&&window.parent!==window){window.parent.postMessage({type:`openchamber:cycle-theme-request`},window.location.origin);return}let e=[`light`,`dark`,`system`],n=document.activeElement,r=(e.indexOf(L.current)+1)%e.length;A(e[r]),requestAnimationFrame(()=>{typeof document>`u`||typeof window>`u`||(document.hasFocus()||window.focus(),n&&document.contains(n)&&n.focus({preventScroll:!0}))});return}if(Es(t,`in`,e(`zoom_in`))){t.preventDefault(),jU();return}if(Es(t,`out`,e(`zoom_out`))){t.preventDefault(),MU();return}if(ks(t,e(`zoom_reset`))){t.preventDefault(),NU();return}if(ks(t,e(`open_settings`))){t.preventDefault();let{isSettingsDialogOpen:e}=q.getState();v(!e);return}if(ks(t,e(`toggle_sidebar`))){t.preventDefault();let{isMobile:e,isSessionSwitcherOpen:n}=q.getState();e?g(!n):l();return}if(ks(t,e(`focus_input`))){t.preventDefault(),document.querySelector(`textarea[data-chat-input="true"]`)?.focus();return}let C=e(`cycle_agent`),E=C&&!C.includes(`shift`)?Ps(`shift+${C}`):``,k=E&&ks(t,E)?-1:+!!ks(t,C);if(k!==0){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:i,isSessionSwitcherOpen:a,isAboutDialogOpen:o,activeMainTab:s}=q.getState();if(e||n||i||a||o||!vC(s)||!r(t.target))return;let c=yC(),l=c?TC(c):null;if(l){t.preventDefault(),l.shortcut(`cycle`,k);return}let u=Oa.getState(),d=Jr(u.getVisibleAgents(),u.currentAgentName,k);if(!d)return;t.preventDefault(),u.setAgent(d),q.getState().addRecentAgent(d);let f=X.getState().currentSessionId;f&&Hr.getState().saveSessionAgentSelection(f,d);return}if(i(`toggle_right_sidebar`).some(e=>ks(t,e))){let{isMobile:e}=q.getState();if(e)return;t.preventDefault(),u();return}if(ks(t,e(`open_right_sidebar_git`))){let{isMobile:e}=q.getState();if(e)return;t.preventDefault(),d(!0),f(`git`);return}if(ks(t,e(`open_right_sidebar_files`))){let{isMobile:e}=q.getState();if(e)return;t.preventDefault(),d(!0),f(`files`);return}if(ks(t,e(`cycle_right_sidebar_tab`))){let{isMobile:e,rightSidebarTab:n}=q.getState();if(e)return;let r=[`git`,`files`],i=r[(r.indexOf(n)+1)%r.length];t.preventDefault(),d(!0),f(i);return}let j=e=>xU(e,X.getState().currentSessionId,e=>{_(`chat`),g(!1),X.getState().setCurrentSession(e.sessionId,e.directory)});if(i(`previous_session`).some(e=>ks(t,e))){t.preventDefault(),j(-1);return}if(i(`next_session`).some(e=>ks(t,e))){t.preventDefault(),j(1);return}for(let n=1;n<=9;n+=1)if(ks(t,e(`switch_tab_${n}`))){BU(n)&&t.preventDefault();return}if(ks(t,e(`toggle_terminal`))){let{isMobile:e}=q.getState();if(e)return;t.preventDefault(),p();return}if(ks(t,e(`open_new_terminal`))){let{isMobile:e}=q.getState();if(e||ge())return;let n=Ul();if(!n||!HU(n))return;t.preventDefault();return}if(ks(t,e(`toggle_bottom_panel`))){let{isMobile:e}=q.getState();if(e)return;t.preventDefault(),p();return}if(ks(t,e(`toggle_terminal_expanded`))){let{isMobile:e,isBottomTerminalExpanded:n}=q.getState();if(e)return;t.preventDefault(),m(!n);return}if(ks(t,e(`open_model_selector`))){let{isSettingsDialogOpen:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isAboutDialogOpen:a,activeMainTab:o,isModelSelectorOpen:s}=q.getState();if(e)return;let c=n||r||i||a,l=vC(o);if(c||!l)return;t.preventDefault(),y(!s,{instant:!0});return}if(ks(t,e(`cycle_thinking_variant`))){ie()&&t.preventDefault();return}if(ks(t,e(`cycle_favorite_model_forward`))||ks(t,e(`cycle_favorite_model_backward`))){let{isSettingsDialogOpen:n,isCommandPaletteOpen:r,isHelpDialogOpen:i,isSessionSwitcherOpen:a,isAboutDialogOpen:o,activeMainTab:s,favoriteModels:c,addRecentModel:l}=q.getState();if(n)return;let u=r||i||a||o,d=vC(s);if(u||!d||c.length===0)return;t.preventDefault();let f=c.length,p=ks(t,e(`cycle_favorite_model_forward`))?1:-1,m=yC();if(m?.selection.change){let e=m.selection.value.providerID,t=m.selection.value.modelID,n=c[(c.findIndex(n=>n.providerID===e&&n.modelID===t)+p+f)%f],r=Oa.getState().providers.find(e=>e.id===n.providerID)?.models?.find(e=>e.id===n.modelID),i=r?.variants?Object.keys(r.variants):[],a=n.variant!==void 0&&i.includes(n.variant)?n.variant:void 0;m.selection.change({...m.selection.value,providerID:n.providerID,modelID:n.modelID,variant:a}),l(n.providerID,n.modelID,a);return}let{currentProviderId:h,currentModelId:g,providers:_,setProvider:v,setModel:y,setCurrentVariant:b}=Oa.getState(),x=c[(c.findIndex(e=>e.providerID===h&&e.modelID===g)+p+f)%f];v(x.providerID),y(x.modelID);let S=_.find(e=>e.id===x.providerID)?.models?.find(e=>e.id===x.modelID),C=S?.variants?Object.keys(S.variants):[],w=x.variant!==void 0&&C.includes(x.variant)?x.variant:void 0;b(w),l(x.providerID,x.modelID,w);return}if(ks(t,e(`expand_input`))){if(h)return;t.preventDefault(),T();return}if(ks(t,e(`toggle_dictation`))){let{activeMainTab:e,isCommandPaletteOpen:n,isHelpDialogOpen:r,isSessionSwitcherOpen:i,isSettingsDialogOpen:a}=q.getState();if(!vC(e)||n||r||i||a)return;t.preventDefault(),window.dispatchEvent(new CustomEvent(`openchamber:dictation-toggle`));return}},ae=e=>{if(e.key!==`Escape`||e.isComposing)return;let t=e.target,n=!!t?.closest(`[role="dialog"]`),i=!!document.querySelector(`[data-settings-view="true"]`),a=!!(t?.closest(`.terminal-viewport-container`)||t?.getAttribute(`data-terminal-hidden-input`)===`true`),s=P(t)||R(),{isSettingsDialogOpen:c,isCommandPaletteOpen:l,isHelpDialogOpen:u,isSessionSwitcherOpen:d,isAboutDialogOpen:f,isMultiRunLauncherOpen:p,isImagePreviewOpen:m,isPromptNavigatorPanelOpen:h}=q.getState();if(n||a||s){V();return}if(h){e.preventDefault(),C(!1),V();return}if(c){e.preventDefault(),v(!1),V();return}if(i){V();return}if(l||u||d||f||p||m){V();return}let g=yC(),_=g?TC(g):null,y=g?.sessionID??X.getState().currentSessionId,b=!!(y&&X.getState().pendingSendMessageIDs.get(y));if(!qU({sessionId:y,surfaceKind:g?.kind,wiringCanAbort:_?.canAbort,primaryCanAbort:j.canAbort,pendingSend:b})){V();return}e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();let x=Date.now(),S=M.current;if(S&&x<S){V(),_?_.abort():(y&&vr(y),o(y??``));return}let w=g?.kind===`secondary`?x+3e3:r(3e3)??x+3e3;M.current=w,N.current&&clearTimeout(N.current);let T=Math.max(w-x,0);N.current=setTimeout(()=>{M.current&&Date.now()>=M.current&&V()},T||0)};return window.addEventListener(`keydown`,U,!0),window.addEventListener(`beforeinput`,ne,!0),window.addEventListener(`compositionstart`,G,!0),window.addEventListener(`compositionupdate`,G,!0),window.addEventListener(`compositionend`,G,!0),window.addEventListener(`keydown`,re,!0),window.addEventListener(`keydown`,ae,!0),window.addEventListener(`keydown`,K),()=>{window.removeEventListener(`keydown`,U,!0),window.removeEventListener(`beforeinput`,ne,!0),window.removeEventListener(`compositionstart`,G,!0),window.removeEventListener(`compositionupdate`,G,!0),window.removeEventListener(`compositionend`,G,!0),window.removeEventListener(`keydown`,re,!0),window.removeEventListener(`keydown`,ae,!0),window.removeEventListener(`keydown`,K)}},e[7]=O?.id,e[8]=O?.path,e[9]=r,e[10]=D,e[11]=h,e[12]=n,e[13]=V,e[14]=_,e[15]=b,e[16]=m,e[17]=y,e[18]=C,e[19]=d,e[20]=f,e[21]=g,e[22]=v,e[23]=A,e[24]=x,e[25]=E,e[26]=t,e[27]=p,e[28]=s,e[29]=T,e[30]=c,e[31]=S,e[32]=u,e[33]=l,e[34]=j,e[35]=W):W=e[35];let ne=O?.id,G=O?.path,re;e[36]!==r||e[37]!==D||e[38]!==a||e[39]!==h||e[40]!==n||e[41]!==V||e[42]!==_||e[43]!==b||e[44]!==m||e[45]!==y||e[46]!==C||e[47]!==d||e[48]!==f||e[49]!==g||e[50]!==v||e[51]!==A||e[52]!==x||e[53]!==E||e[54]!==t||e[55]!==ne||e[56]!==G||e[57]!==p||e[58]!==s||e[59]!==T||e[60]!==c||e[61]!==S||e[62]!==u||e[63]!==l||e[64]!==j?(re=[n,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x,S,C,T,A,j,r,V,te,ee,a,D,ne,G,E,t],e[36]=r,e[37]=D,e[38]=a,e[39]=h,e[40]=n,e[41]=V,e[42]=_,e[43]=b,e[44]=m,e[45]=y,e[46]=C,e[47]=d,e[48]=f,e[49]=g,e[50]=v,e[51]=A,e[52]=x,e[53]=E,e[54]=t,e[55]=ne,e[56]=G,e[57]=p,e[58]=s,e[59]=T,e[60]=c,e[61]=S,e[62]=u,e[63]=l,e[64]=j,e[65]=re):re=e[65],Q.useEffect(W,re);let ie,K;e[66]===V?(ie=e[67],K=e[68]):(K=()=>()=>{V(),ee()},ie=[V,ee],e[66]=V,e[67]=ie,e[68]=K),Q.useEffect(K,ie)};function XU(e){return e.openNewSessionDraft}function ZU(e){return e.armAbortPrompt}function QU(e){return e.clearAbortPrompt}function $U(e){return e.currentSessionId}function eW(e){return e.toggleCommandPalette}function tW(e){return e.toggleHelpDialog}function nW(e){return e.toggleSidebar}function rW(e){return e.toggleRightSidebar}function iW(e){return e.setRightSidebarOpen}function aW(e){return e.setRightSidebarTab}function oW(e){return e.toggleBottomTerminal}function sW(e){return e.setBottomTerminalExpanded}function cW(e){return e.isMobile}function lW(e){return e.setSessionSwitcherOpen}function uW(e){return e.setActiveMainTab}function dW(e){return e.setSettingsDialogOpen}function fW(e){return e.setModelSelectorOpen}function pW(e){return e.setAgentSelectorOpen}function mW(e){return e.setTimelineDialogOpen}function hW(e){return e.togglePromptNavigatorPanel}function gW(e){return e.setPromptNavigatorPanelOpen}function _W(e){return e.toggleExpandedInput}function vW(e){return e.shortcutOverrides}function yW(e){return e.currentDirectory}function bW(e){return e.getActiveProject()}function xW(e){return e instanceof Element&&!!(e.closest(`[data-terminal-view="true"]`)||e.closest(`.terminal-viewport-container`)||e.getAttribute(`data-terminal-hidden-input`)===`true`)}function SW(e){return e.getClientRects().length>0}function CW(){let e=document.querySelectorAll(`[data-slot="dropdown-menu-content"], [data-slot="select-content"], [role="menu"], [data-radix-popper-content-wrapper]`);return Array.from(e).some(SW)}function wW(){document.querySelector(`textarea[data-chat-input="true"]`)?.focus({preventScroll:!0})}function TW(){window.requestAnimationFrame(wW)}function EW(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i}=q.getState();return e||t||n||r||i}function DW(e,t,n,r){return it.summarizeSession(e,t,n,r)}function OW(){let{isSettingsDialogOpen:e,isCommandPaletteOpen:t,isHelpDialogOpen:n,isSessionSwitcherOpen:r,isAboutDialogOpen:i,activeMainTab:a}=q.getState();if(e||t||n||r||i||!vC(a))return!1;let o=yC();if(o?.selection.change){let e=o.selection.catalog?.variants??[];if(e.length===0)return!1;let t=o.selection.value.variant,n=e[((t?e.indexOf(t):-1)+1)%e.length];return o.selection.change({...o.selection.value,variant:n}),!0}let s=Oa.getState();if(s.getCurrentModelVariants().length===0)return!1;s.cycleCurrentVariant();let c=Oa.getState().currentVariant,l=X.getState().currentSessionId,u=Oa.getState().currentAgentName,d=Oa.getState().currentProviderId,f=Oa.getState().currentModelId;return l&&u&&d&&f&&Hr.getState().saveAgentModelVariantForSession(l,u,d,f,c),u&&d&&f&&Oa.getState().saveAgentModelSelection(u,d,f,c),!0}function kW(e){return e instanceof HTMLTextAreaElement&&e.getAttribute(`data-chat-input`)===`true`}function AW(e){console.warn(`[keyboard-shortcuts] failed to open draft mini chat window`,e)}var jW=3,MW=(e,t)=>{if(typeof e!=`string`)return t;let n=e.trim().replace(/\s+/g,` `);return n?n.slice(0,48):t},NW=(e,t)=>{let n=t?[...e.filter(e=>e.id===t),...e.filter(e=>e.id!==t)]:e,r=[],i=new Set;for(let e of n){let t=typeof e.id==`string`?e.id.trim():``;if(!(!t||i.has(t))&&(i.add(t),r.push({sessionId:t,title:MW(e.title,`Session ${r.length+1}`)}),r.length>=jW))break}return r},PW=()=>{let e=(0,pd.c)(9),t=Ca(),n=X(FW),r;e[0]!==n||e[1]!==t?(r=NW(t,n),e[0]=n,e[1]=t,e[2]=r):r=e[2];let i=r,a;e[3]===i?a=e[4]:(a=JSON.stringify(i),e[3]=i,e[4]=a);let o=a,s,c;e[5]!==i||e[6]!==o?(s=()=>{if(!(typeof window>`u`||!le())){try{i.length===0?localStorage.removeItem(Fs):localStorage.setItem(Fs,o)}catch{return}window.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()}},c=[i,o],e[5]=i,e[6]=o,e[7]=s,e[8]=c):(s=e[7],c=e[8]),Q.useEffect(s,c)};function FW(e){return e.currentSessionId}var IW=e=>Number.isFinite(e)?`${Math.max(0,Math.round(e))}px`:`0px`,LW=(e,t,n,r)=>{e.style.setProperty(`--oc-wco-left-inset`,IW(t)),e.style.setProperty(`--oc-wco-right-inset`,IW(n)),e.style.setProperty(`--oc-wco-titlebar-height`,IW(r))},RW=()=>{let e=(0,pd.c)(1),t;e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0],Q.useEffect(zW,t)};function zW(){if(typeof window>`u`||!le())return;let e=document.documentElement,t=typeof window.matchMedia==`function`?window.matchMedia(`(display-mode: window-controls-overlay)`):null,n=window.navigator.windowControlsOverlay,r=()=>{if(!n||!t?.matches||!n.visible){LW(e,0,0,0);return}let r=n.getTitlebarAreaRect(),i=Math.max(0,Number(r.x)||0),a=Math.max(0,Number(r.width)||0),o=Math.max(0,Number(r.height)||0),s=Math.max(0,window.innerWidth-(i+a));LW(e,i,s,o)},i=()=>{r()};return r(),window.addEventListener(`resize`,r),window.addEventListener(`focus`,r),t&&(typeof t.addEventListener==`function`?t.addEventListener(`change`,i):typeof t.addListener==`function`&&t.addListener(i)),n&&typeof n.addEventListener==`function`&&n.addEventListener(`geometrychange`,r),()=>{window.removeEventListener(`resize`,r),window.removeEventListener(`focus`,r),t&&(typeof t.removeEventListener==`function`?t.removeEventListener(`change`,i):typeof t.removeListener==`function`&&t.removeListener(i)),n&&typeof n.removeEventListener==`function`&&n.removeEventListener(`geometrychange`,r),LW(e,0,0,0)}}var BW=null,VW=e=>{let t=BW;return BW=e,()=>{BW===e&&(BW=t)}},HW=()=>({orderByProject:{},pendingProjectIDs:{}}),UW=(e,t)=>!!(e&&e.length===t.length&&e.every((e,n)=>e===t[n])),WW=o(),GW=ze()(Be((e,t)=>({runtimeIdentity:WW,...HW(),serverRevisionByProject:{},deferredServerOrderByProject:{},runtimeOrdersByIdentity:{[WW]:HW()},activateWorktreeOrderRuntime:t=>e(e=>{if(e.runtimeIdentity===t)return e;let n=e.runtimeOrdersByIdentity[t]??HW();return{runtimeIdentity:t,orderByProject:n.orderByProject,pendingProjectIDs:n.pendingProjectIDs,serverRevisionByProject:{},deferredServerOrderByProject:{},runtimeOrdersByIdentity:e.runtimeOrdersByIdentity[t]?e.runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[t]:n}}}),setWorktreeOrder:(t,n,r)=>{let i=!1;e(e=>{let n=UW(e.orderByProject[t],r),a=e.pendingProjectIDs[t]?e.pendingProjectIDs:{...e.pendingProjectIDs,[t]:!0};if(i=!n||a!==e.pendingProjectIDs,!i)return e;let o=n?e.orderByProject:{...e.orderByProject,[t]:r},s={orderByProject:o,pendingProjectIDs:a};return{orderByProject:o,pendingProjectIDs:a,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:s}}}),i&&BW?.(t,n,r)},markPendingWorktreeOrder:t=>e(e=>{if(e.pendingProjectIDs[t])return e;let n={...e.pendingProjectIDs,[t]:!0};return{pendingProjectIDs:n,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:{orderByProject:e.orderByProject,pendingProjectIDs:n}}}}),applyServerWorktreeOrder:(t,n,r)=>e(e=>{let i=e.serverRevisionByProject[t];if(i!==void 0&&r<=i)return e;let a={...e.serverRevisionByProject,[t]:r};if(e.pendingProjectIDs[t])return{serverRevisionByProject:a,deferredServerOrderByProject:{...e.deferredServerOrderByProject,[t]:{orderedPaths:n,revision:r}}};if(UW(e.orderByProject[t],n))return{serverRevisionByProject:a};let o={...e.orderByProject,[t]:n};return{orderByProject:o,serverRevisionByProject:a,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:{orderByProject:o,pendingProjectIDs:e.pendingProjectIDs}}}}),setServerRevision:(t,n)=>e(e=>{let r=e.serverRevisionByProject[t];return r!==void 0&&n<=r?e:{serverRevisionByProject:{...e.serverRevisionByProject,[t]:n}}}),resolvePendingWorktreeOrder:(t,n)=>e(e=>{let r=e.serverRevisionByProject[t],i=e.deferredServerOrderByProject[t],a=Math.max(r??0,n,i?.revision??0),o=r===a?e.serverRevisionByProject:{...e.serverRevisionByProject,[t]:a},s=i?(()=>{let n={...e.deferredServerOrderByProject};return delete n[t],n})():e.deferredServerOrderByProject;if(!e.pendingProjectIDs[t])return o===e.serverRevisionByProject&&s===e.deferredServerOrderByProject?e:{serverRevisionByProject:o,deferredServerOrderByProject:s};let c={...e.pendingProjectIDs};delete c[t];let l=i&&i.revision>n&&!UW(e.orderByProject[t],i.orderedPaths)?{...e.orderByProject,[t]:i.orderedPaths}:e.orderByProject;return{pendingProjectIDs:c,orderByProject:l,serverRevisionByProject:o,deferredServerOrderByProject:s,runtimeOrdersByIdentity:{...e.runtimeOrdersByIdentity,[e.runtimeIdentity]:{orderByProject:l,pendingProjectIDs:c}}}}),resetServerWorktreeOrders:()=>e(e=>Object.keys(e.serverRevisionByProject).length===0&&Object.keys(e.deferredServerOrderByProject).length===0?e:{serverRevisionByProject:{},deferredServerOrderByProject:{}}),hasPendingWorktreeOrder:e=>!!t().pendingProjectIDs[e]}),{name:`mobile-worktree-order`,version:2,partialize:e=>({runtimeOrdersByIdentity:e.runtimeOrdersByIdentity}),migrate:e=>{let t=e;return t.runtimeOrdersByIdentity?{runtimeOrdersByIdentity:t.runtimeOrdersByIdentity}:{runtimeOrdersByIdentity:{[WW]:{orderByProject:t.orderByProject??{},pendingProjectIDs:t.pendingProjectIDs??{}}}}},merge:(e,t)=>{let n=e.runtimeOrdersByIdentity??t.runtimeOrdersByIdentity,r=n[t.runtimeIdentity]??HW();return{...t,runtimeOrdersByIdentity:n,orderByProject:r.orderByProject,pendingProjectIDs:r.pendingProjectIDs}}})),KW=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``),qW=(e,t)=>{if(!e||e.length===0)return t;let n=new Map(e.map((e,t)=>[KW(e),t]));return t.map((e,t)=>({worktree:e,index:t})).sort((e,t)=>(n.get(KW(e.worktree.path))??2**53-1)-(n.get(KW(t.worktree.path))??2**53-1)||e.index-t.index).map(e=>e.worktree)},JW=3e4,YW=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,XW=e=>e instanceof to?e.status===501?`unsupported`:e.status>=400&&e.status<500&&e.status!==408&&e.status!==429&&e.code!==`revision_conflict`?`permanent`:`retry`:`retry`,ZW=(e,t)=>new Promise((n,r)=>{let i=()=>{clearTimeout(a),t.removeEventListener(`abort`,i),r(new DOMException(`Aborted`,`AbortError`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.aborted?i():t.addEventListener(`abort`,i,{once:!0})}),QW=(e,t)=>e.then(e=>{if(t?.aborted)throw new DOMException(`Aborted`,`AbortError`);return e}),$W={fetchSnapshot:e=>QW(io(ve),e),refreshSnapshot:e=>QW(xi(ve),e),fetchOrder:yn,setOrder:Ya,waitInvalidation:Pr,captureRuntime:()=>({transportIdentity:o(),generation:c()}),isCurrent:e=>e.transportIdentity===o()&&e.generation===c(),sleep:ZW,createRequestID:()=>typeof crypto<`u`&&crypto.randomUUID?crypto.randomUUID():`worktree-order-${Date.now()}-${Math.random().toString(36).slice(2)}`},eG=new Map,tG=()=>{for(let e of eG.values())e.controller.abort();eG.clear()},nG=(e,t,n,r=$W)=>{eG.get(e)?.controller.abort();let i={projectDirectory:YW(t),orderedPaths:[...n],capture:r.captureRuntime(),controller:new AbortController,backoffMs:500,running:!1};eG.set(e,i),rG(e,r)},rG=async(e,t=$W)=>{let n=eG.get(e);if(!(!n||n.running)){n.running=!0;try{for(;;){let n=eG.get(e);if(!n||!t.isCurrent(n.capture)||n.controller.signal.aborted)return;let r=GW.getState().serverRevisionByProject[e]??0;n.expectedRevision!==r&&(n.expectedRevision=r,n.requestID=t.createRequestID());try{let i=await t.setOrder({requestID:n.requestID,projectDirectory:n.projectDirectory,expectedRevision:r,orderedPaths:n.orderedPaths,signal:n.controller.signal});if(!t.isCurrent(n.capture)||eG.get(e)!==n)return;let a=i.worktreeOrder??{projectDirectory:n.projectDirectory,orderedPaths:n.orderedPaths,revision:i.revision};GW.getState().setServerRevision(e,a.revision),GW.getState().resolvePendingWorktreeOrder(e,a.revision),eG.delete(e);return}catch(r){if(n.controller.signal.aborted||!t.isCurrent(n.capture)||eG.get(e)!==n)return;if(r instanceof to&&r.code===`revision_conflict`)try{let r=await t.fetchOrder(n.projectDirectory,n.controller.signal);if(eG.get(e)!==n||!t.isCurrent(n.capture))return;GW.getState().applyServerWorktreeOrder(e,r.orderedPaths,r.revision),n.expectedRevision=void 0,n.requestID=void 0,n.backoffMs=500;continue}catch(e){if(XW(e)!==`retry`)return}else if(XW(r)!==`retry`)return;if(await t.sleep(n.backoffMs,n.controller.signal).catch(()=>{}),n.backoffMs=Math.min(n.backoffMs*2,JW),n.controller.signal.aborted)return}}}finally{eG.get(e)===n&&(!t.isCurrent(n.capture)||n.controller.signal.aborted)&&eG.delete(e),eG.get(e)===n&&(n.running=!1)}}},iG=(e,t,n,r)=>{let i=new Map(t.map(e=>[YW(e.path),e.id]));for(let t of e){let e=i.get(YW(t.projectDirectory));e&&r.isCurrent(n)&&GW.getState().applyServerWorktreeOrder(e,t.orderedPaths,t.revision)}},aG=(e,t=$W)=>{let n=null,r=()=>n?.abort();return{start:()=>{r(),n=new AbortController;let i=n.signal,a=t.captureRuntime();(async()=>{let n=0,r=500;for(;!i.aborted&&t.isCurrent(a);)try{let r=await t.fetchSnapshot(i);if(i.aborted||!t.isCurrent(a))return;n=r.revision;let o=e();iG(r.worktreeOrders,o,a,t);let s=new Set(r.worktreeOrders.map(e=>YW(e.projectDirectory)));for(let e of o){let n=GW.getState(),r=n.orderByProject[e.id];n.pendingProjectIDs[e.id]?nG(e.id,e.path,r??[],t):r?.length&&!s.has(YW(e.path))&&(n.markPendingWorktreeOrder(e.id),nG(e.id,e.path,r,t))}break}catch(e){if(XW(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,JW)}for(;!i.aborted&&t.isCurrent(a);)try{let o=await t.waitInvalidation(n,{signal:i});if(i.aborted||!t.isCurrent(a)||o===`aborted`)return;let s=await(t.refreshSnapshot??t.fetchSnapshot)(i);if(i.aborted||!t.isCurrent(a))return;n=s.revision,iG(s.worktreeOrders,e(),a,t),r=500}catch(e){if(XW(e)!==`retry`)return;await t.sleep(r,i).catch(()=>{}),r=Math.min(r*2,JW)}})()},stop:r}},oG=()=>{let e=(0,pd.c)(2),t=eo(cG),n;e[0]===t?n=e[1]:(n=[t],e[0]=t,e[1]=n),Q.useEffect(dG,n)};function sG(e){return[e.id,YW(e.path)]}function cG(e){return JSON.stringify(e.projects.map(sG))}function lG(e,t,n){return nG(e,t,n)}function uG(){return eo.getState().projects}function dG(){let e=o();GW.getState().activateWorktreeOrderRuntime(e);let t=VW(lG),n=aG(uG);n.start();let r=i(e=>{l(e)&&(tG(),GW.getState().activateWorktreeOrderRuntime(o()),n.start())});return()=>{t(),r(),n.stop(),tG()}}var fG=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``)||`/`,pG=e=>{let t=!1,n=0,r=0,i=0,a=new Map,o=new Map,s=new Set,c=new Set,l=new Map,u=new Set,d=new Set,f=new Set,p=``,m=[],h=t=>{let n=fG(t);return e.getProjects().find(e=>fG(e.path)===n)},g=(n,i=150)=>{let s=fG(n.path),c=o.get(s);c&&e.clearTimer(c.timer);let l=r,u=e.setTimer(()=>{!t||l!==r||(o.delete(s),a.set(s,n),_(l))},i);o.set(s,{timer:u,epoch:l})},_=(n=r)=>{if(!(!t||n!==r))for(;i<2&&a.size>0;){let[n,o]=a.entries().next().value;a.delete(n),i+=1;let s=e.generation(),c=r;e.refresh(o,{isCurrent:()=>t&&c===r&&s===e.generation()}).then(i=>{if(!(!t||c!==r||s!==e.generation())){f.add(n);for(let e of i.addedDirectories)u.add(fG(e));if(e.needsSessionSync)for(let t of i.worktrees){let n=fG(t.path);e.needsSessionSync(n)&&u.add(n)}v(c,s),y()}}).then(()=>{t&&c===r&&s===e.generation()&&l.delete(n)}).catch(()=>{if(!t||c!==r||s!==e.generation())return;let i=(l.get(n)??0)+1;l.set(n,i),t&&c===r&&g(o,[1e3,2e3,5e3,15e3,3e4][Math.min(i-1,4)])}).finally(()=>{c===r&&(--i,_(c))})}},v=(n,i)=>{if(u.size===0)return;let a=[...u];u.clear(),e.syncAdded(a).catch(()=>{if(t&&n===r&&i===e.generation()){for(let e of a)u.add(e);let o=e.setTimer(()=>{s.delete(o),t&&n===r&&v(n,i)},1e3);s.add(o)}})},y=()=>{if(f.size!==e.getProjects().length)return;let t=e.getCatalog();for(let e of d){let n=e.slice(e.indexOf(`:`)+1);[...t.entries()].some(([e,t])=>fG(e)===n||t.some(e=>fG(e.path)===n))||c.add(e)}},b=()=>{f.clear();for(let t of e.getProjects())g(t,0)},x=()=>{let t=e.getCatalog(),r=e.getProjects(),i=new Set;for(let t of e.getActiveDirectories())t.trim()&&i.add(fG(t));for(let e of[...d]){let t=e.slice(e.indexOf(`:`)+1);i.has(t)||d.delete(e)}for(let e of[...c]){let t=e.slice(e.indexOf(`:`)+1);i.has(t)||c.delete(e)}for(let e of i)if(!r.find(n=>{let r=fG(n.path),i=t.get(r)?.some(t=>fG(t.path)===e);return e===r||i})){let t=`${n}:${e}`;!c.has(t)&&!d.has(t)&&(d.add(t),b())}},S=()=>{r+=1,c.clear(),d.clear(),l.clear(),u.clear(),f.clear();for(let t of o.values())e.clearTimer(t.timer);o.clear();for(let t of s)e.clearTimer(t);s.clear(),a.clear(),i=0};return{start:()=>{t||e.isVSCode()||(t=!0,m.push(e.subscribeEvents(e=>{if(e.type===`event-stream-ready`&&(n+=1,S(),b()),e.type===`worktree-topology-changed`&&e.projectDirectory){let t=h(e.projectDirectory);t&&g(t)}})),p=e.getProjects().map(e=>`${e.id}\u0000${fG(e.path)}`).sort().join(`
|
|
6586
6586
|
`),m.push(e.subscribeProjects(()=>{let t=e.getProjects().map(e=>`${e.id}\u0000${fG(e.path)}`).sort().join(`
|
|
6587
6587
|
`);t!==p&&(p=t,S(),b(),x())})),m.push(e.subscribeCatalog(x)),m.push(e.subscribeSessions(x)),m.push(e.subscribeRuntime(e=>{e&&(n+=1,S(),b())})),b(),x())},stop:()=>{t=!1,S();for(let{timer:t}of o.values())e.clearTimer(t);for(o.clear(),a.clear(),i=0;m.length;)m.pop()?.()},reconcileAll:b}},mG=null,hG=0,gG=()=>(mG||=pG({isVSCode:ge,getProjects:()=>eo.getState().projects,getCatalog:()=>X.getState().availableWorktreesByProject,getActiveDirectories:()=>{let e=Ui.getState(),t=[];for(let n of e.activeSessions)typeof n.directory==`string`&&t.push(n.directory);for(let n of e.cachedDirectories)t.push(n);return t},needsSessionSync:e=>!Ui.getState().loadedDirectories.has(fG(e)),refresh:Vo,syncAdded:e=>ua(e,Ui.getState().activeSessions),subscribeProjects:e=>eo.subscribe(e),subscribeCatalog:e=>X.subscribe((t,n)=>{t.availableWorktreesByProject!==n.availableWorktreesByProject&&e()}),subscribeSessions:e=>Ui.subscribe((t,n)=>{(t.activeSessions!==n.activeSessions||t.cachedDirectories!==n.cachedDirectories)&&e()}),subscribeEvents:br,subscribeRuntime:e=>i(t=>e(l(t))),generation:c,setTimer:(e,t)=>globalThis.setTimeout(e,t),clearTimer:e=>globalThis.clearTimeout(e)}),hG+=1,mG.start(),()=>{hG=Math.max(0,hG-1),hG===0&&mG?.stop()}),_G=`openchamber:mini-chat-presence`,vG=()=>{let e=Qm(),t=Q.useRef(e.optimistic.add),n=Q.useRef(e.optimistic.remove),r=Q.useRef(e.optimistic.confirm);return t.current=e.optimistic.add,n.current=e.optimistic.remove,r.current=e.optimistic.confirm,Q.useEffect(()=>{ei(e=>t.current(e),e=>n.current(e),e=>r.current(e))},[]),Q.useEffect(()=>gG(),[]),null},yG=()=>{let e=(0,pd.c)(1),t;return e[0]===Symbol.for(`react.memo_cache_sentinel`)?(t=[],e[0]=t):t=e[0],Q.useEffect(TG,t),null};function bG(e){let t=(0,pd.c)(4),{embeddedBackgroundWorkEnabled:n}=e,r;t[0]===n?r=t[1]:(r={enabled:n,autoRun:!1},t[0]=n,t[1]=r),zs(r);let i=Q.useSyncExternalStore(fn,ao,ao);zn(n&&i===`legacy-enabled`),Wn();let a;t[2]===Symbol.for(`react.memo_cache_sentinel`)?(a=[],t[2]=a):a=t[2],Q.useEffect(xG,a);let o;return t[3]===Symbol.for(`react.memo_cache_sentinel`)?(o=(0,$.jsx)(vG,{}),t[3]=o):o=t[3],o}function xG(){let e=Ri(),t=er();e.start(),t.start();let n=ui(e);return()=>{n(),t.stop(),e.stop()}}function SG(e){let t=(0,pd.c)(6),{embeddedBackgroundWorkEnabled:n}=e;PW(),RW(),YU(),oG();let r;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(r=[],t[0]=r):r=t[0],Q.useEffect(CG,r);let i;t[1]===n?i=t[2]:(i=(0,$.jsx)(bG,{embeddedBackgroundWorkEnabled:n}),t[1]=n,t[2]=i);let a;t[3]===Symbol.for(`react.memo_cache_sentinel`)?(a=(0,$.jsx)(yG,{}),t[3]=a):a=t[3];let o;return t[4]===i?o=t[5]:(o=(0,$.jsxs)($.Fragment,{children:[i,a]}),t[4]=i,t[5]=o),o}function CG(){AU()}function wG(e){let t=e.data;if(t?.type!==`mini-chat-session-presence`||!t.sessionId||!t.directory)return;let n=t.viewed!==!1;Er(t.directory,t.sessionId,n),n&&ur(t.sessionId)}function TG(){if(typeof BroadcastChannel>`u`)return;let e=new BroadcastChannel(_G);return e.onmessage=wG,()=>e.close()}var EG=new Set,DG=new Map,OG=(e,t)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(e.packageName).replace(`%40`,`@`).replace(`%2F`,`/`)}/files/${e.filePrefix}-latin-${t}-normal.woff2`,kG=(e,t)=>{let n=`${e.family}:${t}`;if(EG.has(n))return Promise.resolve();let r=DG.get(n);if(r)return r;if(typeof document>`u`||typeof FontFace>`u`||!document.fonts)return Promise.resolve();let i=new FontFace(e.family,`url(${OG(e,t)}) format('woff2')`,{style:`normal`,weight:String(t),display:`swap`});document.fonts.add(i);let a=i.load().then(()=>{EG.add(n)}).catch(n=>{document.fonts.delete(i),console.warn(`Failed to load font: ${e.family} ${t}`,n)}).finally(()=>{DG.delete(n)});return DG.set(n,a),a},AG=e=>e?Promise.all(e.weights.map(t=>kG(e,t))).then(()=>void 0):Promise.resolve(),jG=e=>AG(_t[e]?.source),MG=e=>AG(xt[e]?.source),NG={family:`Syne`,packageName:`@fontsource/syne`,filePrefix:`syne`,weights:[700]},PG=()=>AG(NG);function FG(){let e=(0,pd.c)(4),{uiFont:t,monoFont:n}=fd(),r,i;e[0]!==n||e[1]!==t?(r=()=>{if(typeof document>`u`)return;let e=document.documentElement,r=_t[t]?.stack??_t.system.stack,i=xt[n]?.stack??xt[`system-mono`].stack;jG(t),MG(n),e.style.setProperty(`--font-sans`,r),e.style.setProperty(`--font-heading`,r),e.style.setProperty(`--font-family-sans`,r),e.style.setProperty(`--font-mono`,i),e.style.setProperty(`--font-family-mono`,i),e.style.setProperty(`--ui-regular-font-weight`,`400`),document.body&&(document.body.style.fontFamily=r)},i=[t,n],e[0]=n,e[1]=t,e[2]=r,e[3]=i):(r=e[2],i=e[3]),Q.useEffect(r,i)}export{Xy as $,sR as A,wx as B,GH as C,Hd as Ct,lB as D,md as Dt,fB as E,vd as Et,AA as F,Ex as G,Ox as H,mA as I,ex as J,hx as K,yT as L,zA as M,RA as N,Az as O,BA as P,qy as Q,iS as R,YH as S,hf as St,aH as T,gd as Tt,Tx as U,Dx as V,Ax as W,Nb as X,Pb as Y,Db as Z,sU as _,Ef as _t,bG as a,bh as at,cU as b,Nf as bt,HU as c,Ip as ct,zU as d,dp as dt,Rv as et,NU as f,up as ft,fU as g,Tf as gt,xU as h,Xf as ht,SG as i,Hh as it,RM as j,sz as k,LU as l,kp as lt,MU as m,Qf as mt,PG as n,yv as nt,qW as o,ih as ot,jU as p,op as pt,$b as q,jG as r,uv as rt,GW as s,Qm as st,FG as t,vv as tt,RU as u,hp as ut,oU as v,Df as vt,VH as w,yd as wt,iU as x,gf as xt,aU as y,jf as yt,qx as z};
|